diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82de08644..339e07d10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1026,7 +1026,36 @@ jobs: run: | cargo test --locked -p openless-core --target-dir src-tauri/target --test prompt_contract cargo test --locked -p openless-core --target-dir src-tauri/target --test dictation_target_capture - cargo test --locked -p openless-core --target-dir src-tauri/target --test selection_contract normal_selection_entry_serializes_full_input_and_rejects_incomplete_streams + ( + selection_scratch= + selection_finished=false + cleanup_selection_contract() { + selection_status=$? + trap - EXIT + if [ -n "$selection_scratch" ]; then + if [ "$selection_finished" != true ]; then + printf '::warning::selection_contract termination unconfirmed; keeping scratch: %s\n' "$selection_scratch" >&2 + if [ "$selection_status" -eq 0 ]; then selection_status=1; fi + elif ! rm -rf -- "$selection_scratch"; then + printf '::error::Failed to remove selection_contract scratch: %s\n' "$selection_scratch" >&2 + if [ "$selection_status" -eq 0 ]; then selection_status=1; fi + fi + fi + exit "$selection_status" + } + trap cleanup_selection_contract EXIT + trap 'selection_finished=false; exit 130' INT + trap 'selection_finished=false; exit 143' TERM + trap 'selection_finished=false; exit 129' HUP + selection_scratch="$(mktemp -d "${RUNNER_TEMP:?}/selection-contract.XXXXXX")" + if TMPDIR="$selection_scratch" cargo test --locked -p openless-core --target-dir src-tauri/target --test selection_contract -- --test-threads=1; then + selection_status=0 + else + selection_status=$? + fi + if [ "$selection_status" -lt 128 ]; then selection_finished=true; fi + exit "$selection_status" + ) cargo test --locked -p openless-core --target-dir src-tauri/target --test settings_field_updates cargo test --locked -p openless-core --target-dir src-tauri/target --lib long_recording cargo test --locked --manifest-path src-tauri/backend-tests/Cargo.toml --target-dir src-tauri/target --test clipboard_delivery diff --git a/openless-all/app/crates/openless-core/src/cloud_providers.rs b/openless-all/app/crates/openless-core/src/cloud_providers.rs index 59b907af8..fe89e959d 100644 --- a/openless-all/app/crates/openless-core/src/cloud_providers.rs +++ b/openless-all/app/crates/openless-core/src/cloud_providers.rs @@ -1527,7 +1527,13 @@ async fn run_cloud_polish( if let Some(error) = stream.take_error() { return Err(error); } - let polished = result.map_err(map_polish_error)?; + let polished = result.map_err(|error| { + if context.polish.selection_input { + map_selection_provider_error(error) + } else { + map_polish_error(error) + } + })?; if cancellation.is_cancelled() { return Err(cancelled_provider_error()); } @@ -1976,6 +1982,34 @@ fn map_polish_error(error: crate::polish::LLMError) -> BackendError { map_llm_error(error).retryable(transient) } +/// The full selection is already durable before reaching a provider. A channel +/// capacity failure must stay explicit; never retry with a shortened original. +fn map_selection_provider_error(error: crate::polish::LLMError) -> BackendError { + let input_too_large = match &error { + crate::polish::LLMError::InvalidResponse { status, body } + if matches!(status, 400 | 413 | 422) => + { + let body = body.to_ascii_lowercase(); + *status == 413 || [ + "context_length_exceeded", + "maximum context length", + "context window", + "input too long", + "input_too_long", + "input token count exceeds", + "request_too_large", + ].iter().any(|marker| body.contains(marker)) + } + _ => false, + }; + if input_too_large { + let mut error = BackendError::new(BackendErrorCode::Provider, "selectionInputTooLarge"); + error.details = Some(serde_json::json!({"original_saved": true})); + return error; + } + map_polish_error(error) +} + pub struct SharedAuxiliaryTextPolisher { credentials: Arc, traditional: Arc, @@ -2420,7 +2454,13 @@ pub(crate) async fn polish_with_omni_text( let polished = provider .complete(&system_prompt, &user_prompt, None) .await - .map_err(map_omni_error)?; + .map_err(|error| { + if context.polish.selection_input { + map_selection_provider_error(error) + } else { + map_omni_error(error) + } + })?; let cleaned = crate::output_cleaning::clean_polish_output(&polished); let text = if context.polish.translation_active { crate::split_polish_translate_output(&cleaned) diff --git a/openless-all/app/crates/openless-core/src/domains.rs b/openless-all/app/crates/openless-core/src/domains.rs index f22d2ce67..fefd2e10f 100644 --- a/openless-all/app/crates/openless-core/src/domains.rs +++ b/openless-all/app/crates/openless-core/src/domains.rs @@ -337,12 +337,70 @@ pub struct SelectionCapture { pub source_app: Option, } +/// Core-issued authority for one capture request. Revocation survives a delayed +/// host call: an old request owns its own marker, not a bounded tombstone entry +/// or the host's current generation. It carries no native target or user text. +#[derive(Debug, Clone)] +pub struct SelectionCaptureAuthorization { + session_id: SessionId, + revoked: Arc, +} + +impl SelectionCaptureAuthorization { + pub(crate) fn new(session_id: SessionId) -> Self { + Self { + session_id, + revoked: Arc::new(std::sync::atomic::AtomicBool::new(false)), + } + } + + pub fn allows(&self, session_id: SessionId) -> bool { + self.session_id == session_id + && !self.revoked.load(std::sync::atomic::Ordering::Acquire) + } + + /// Only Core revokes this marker, before publishing a terminal state or a + /// successor. No host code, callbacks, I/O or host locks run at this boundary. + pub(crate) fn revoke(&self) { + self.revoked.store(true, std::sync::atomic::Ordering::Release); + } +} + /// Platform seam for capturing and replacing the current selection. /// /// The core owns the session and preview state. Implementations may retain an /// opaque platform target internally, keyed by `SessionId`, but must never /// expose native handles through this Interface. pub trait SelectionRuntimeAdapter: Send + Sync { + /// Hosts with shared target registration must check this authority *inside* + /// their reservation lock, before invalidating another session or mutating + /// the registry. Do not call back into Core from that critical section. + /// The default preserves supplied-text/legacy hosts; it checks cancellation + /// around capture but does not claim to fence a host's shared registry. + fn capture_authorized( + &self, + session_id: SessionId, + supplied_text: Option, + authorization: SelectionCaptureAuthorization, + ) -> BoxFuture<'static, Result> { + if !authorization.allows(session_id) { + return Box::pin(async { + Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked")) + }); + } + let capture = self.capture(session_id, supplied_text); + Box::pin(async move { + if !authorization.allows(session_id) { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked")); + } + let result = capture.await; + if !authorization.allows(session_id) { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked")); + } + result + }) + } + fn capture( &self, session_id: SessionId, diff --git a/openless-all/app/crates/openless-core/src/history.rs b/openless-all/app/crates/openless-core/src/history.rs index 439e18293..7fef896d7 100644 --- a/openless-all/app/crates/openless-core/src/history.rs +++ b/openless-all/app/crates/openless-core/src/history.rs @@ -318,6 +318,35 @@ mod tests { } } + #[test] + fn legacy_selection_history_keeps_the_full_original_separate_from_the_result() { + let path = std::env::temp_dir().join(format!( + "openless-legacy-selection-{}.json", uuid::Uuid::new_v4() + )); + let original = format!(" \t{} LEGACY_MIDDLE {}\n ", "字".repeat(9000), "尾".repeat(9000)); + let mut row = session("legacy-selection", chrono::Utc::now().to_rfc3339()); + row.source = HistorySource::SelectionPolish; + row.raw_transcript = original.clone(); + row.final_text = "existing result".into(); + let mut legacy = serde_json::to_value(&row).unwrap(); + for field in ["asrTranscript", "polishSource", "pipelineMode", "hasAudioRecording"] { + legacy.as_object_mut().unwrap().remove(field); + } + let bytes = serde_json::to_vec(&vec![legacy]).unwrap(); + std::fs::write(&path, &bytes).unwrap(); + let store = HistoryStore::at_path(path.clone()); + let mut read = store.list().unwrap().remove(0); + assert_eq!(read.raw_transcript, original); + assert_eq!(read.final_text, "existing result"); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + read.final_text = "new result".into(); + store.update_entry(read).unwrap(); + let read = store.list().unwrap(); + assert_eq!(read[0].raw_transcript, original); + assert_eq!(read[0].final_text, "new result"); + std::fs::remove_file(path).unwrap(); + } + #[test] fn legacy_quick_note_history_survives_read_and_append() { let path = std::env::temp_dir().join(format!( diff --git a/openless-all/app/crates/openless-core/src/host_document/mod.rs b/openless-all/app/crates/openless-core/src/host_document/mod.rs index e5f365351..338ab36cd 100644 --- a/openless-all/app/crates/openless-core/src/host_document/mod.rs +++ b/openless-all/app/crates/openless-core/src/host_document/mod.rs @@ -5,6 +5,7 @@ mod diff; mod observation; +pub mod target; mod window; pub use diff::{ diff --git a/openless-all/app/crates/openless-core/src/host_document/target.rs b/openless-all/app/crates/openless-core/src/host_document/target.rs new file mode 100644 index 000000000..50ff9bd3a --- /dev/null +++ b/openless-all/app/crates/openless-core/src/host_document/target.rs @@ -0,0 +1,36 @@ +//! Local target evidence shared by host integrations. Never include these tokens +//! in prompts or history: they identify a destination, not document context. + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostTargetIdentity { + pub process_id: u32, + /// Opaque, process-local token; not a native handle or a window title. + pub window_token: String, + /// Opaque token for the actual focused input control, not merely its app. + pub control_token: String, + pub selection: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HostSelectionRange { + pub start: u64, + pub length: u64, + /// Offsets are native units. Consumers must not slice Rust strings using + /// these values (AX/Win32 use UTF-16; UIA may use provider text units). + pub unit: HostTextUnit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostTextUnit { + Utf16, + Native, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HostTargetValidation { + Current, + Unavailable, + TargetChanged, + PositionChanged, + Cancelled, +} diff --git a/openless-all/app/crates/openless-core/src/ports.rs b/openless-all/app/crates/openless-core/src/ports.rs index 1205e237f..35a6c9a20 100644 --- a/openless-all/app/crates/openless-core/src/ports.rs +++ b/openless-all/app/crates/openless-core/src/ports.rs @@ -46,6 +46,17 @@ pub struct CapturedTextTarget { } pub trait HostContextAdapter: Send + Sync { + /// Local destination evidence from capture time. This is deliberately kept + /// separate from HostContextCapture, whose text may be sent to a model. + fn target_identity(&self) -> Option { + None + } + /// Native checks may block; hosts must run them off the async worker. + fn validate_target( + &self, + ) -> BoxFuture<'static, crate::host_document::target::HostTargetValidation> { + Box::pin(async { crate::host_document::target::HostTargetValidation::Unavailable }) + } /// Stable identity, when this adapter is attached to a frozen insertion target. fn input_app(&self) -> Option { None diff --git a/openless-all/app/crates/openless-core/src/selection_service.rs b/openless-all/app/crates/openless-core/src/selection_service.rs index 1a1ce79c8..e7b5dbd9e 100644 --- a/openless-all/app/crates/openless-core/src/selection_service.rs +++ b/openless-all/app/crates/openless-core/src/selection_service.rs @@ -10,7 +10,7 @@ use crate::dictation_context::{ DictationContext, DictationProviderInvocations, DictationStartOptions, ProviderInvocation, }; use crate::domains::{ - SelectionApi, SelectionCapture, SelectionPhase, SelectionPolishRequest, + SelectionApi, SelectionCapture, SelectionCaptureAuthorization, SelectionPhase, SelectionPolishRequest, SelectionRuntimeAdapter, SelectionSnapshot, }; use crate::errors::{BackendError, BackendErrorCode}; @@ -30,6 +30,7 @@ use crate::{ #[derive(Clone, Default)] struct SelectionState { snapshot: SelectionSnapshot, + capture_authorization: Option, source_app: Option, context: Option>, started_at: Option, @@ -39,6 +40,14 @@ struct SelectionState { reverting: bool, } +impl SelectionState { + fn revoke_capture_authorization(&self) { + if let Some(authorization) = &self.capture_authorization { + authorization.revoke(); + } + } +} + struct SelectionServiceInner { preferences: Arc, style_packs: Arc, @@ -126,8 +135,8 @@ impl SelectionServiceInner { let _ = self .runtime_work .cleanup(Box::pin(async move { - let _ = polisher.cancel(session_id).await; - let _ = runtime.cancel(session_id).await; + let runtime_cancel = runtime.cancel(session_id); + let _ = futures_util::future::join(runtime_cancel, polisher.cancel(session_id)).await; Ok(()) })) .await; @@ -139,7 +148,9 @@ impl SelectionServiceInner { } } - fn begin(&self, request: &SelectionPolishRequest) -> Result { + fn begin(&self, request: &SelectionPolishRequest) + -> Result<(SessionId, SelectionCaptureAuthorization), BackendError> + { let mut state = self.state.write().expect("selection state lock poisoned"); if matches!( state.snapshot.phase, @@ -150,7 +161,10 @@ impl SelectionServiceInner { "a selection session is already active", )); } + state.revoke_capture_authorization(); let session_id = SessionId::new(); + let authorization = SelectionCaptureAuthorization::new(session_id); + state.capture_authorization = Some(authorization.clone()); state.snapshot = SelectionSnapshot { phase: SelectionPhase::Capturing, session_id: Some(session_id), @@ -173,7 +187,7 @@ impl SelectionServiceInner { Some(session_id), BackendEventKind::SelectionStateChanged(snapshot), ); - Ok(session_id) + Ok((session_id, authorization)) } fn ensure_active(state: &SelectionState, session_id: SessionId) -> Result<(), BackendError> { @@ -223,6 +237,7 @@ impl SelectionServiceInner { &self, session_id: SessionId, capture: &SelectionCapture, + mode: crate::types::PolishMode, ) -> Result<(), BackendError> { if capture.text.trim().is_empty() { return Err(BackendError::new( @@ -232,6 +247,9 @@ impl SelectionServiceInner { } let mut state = self.state.write().expect("selection state lock poisoned"); Self::ensure_active(&state, session_id)?; + // Cancellation must settle an existing original, rather than race a + // late insert that would leave a permanent selectionProcessing row. + self.persist_original(session_id, capture, mode)?; state.snapshot.source_text = Some(capture.text.clone()); state.source_app = capture.source_app.clone(); Ok(()) @@ -459,6 +477,7 @@ impl SelectionServiceInner { let mut state = self.state.write().expect("selection state lock poisoned"); Self::ensure_active(&state, session_id)?; state.snapshot.insert_outcome = Some(outcome); + state.revoke_capture_authorization(); state.snapshot.phase = SelectionPhase::Completed; // Completion makes a new capture admissible. Freeze all history fields // before publishing it so a successor cannot replace this turn's text. @@ -584,7 +603,7 @@ impl SelectionServiceInner { } } - fn fail_if_active(&self, session_id: SessionId) -> bool { + fn fail_if_active(&self, session_id: SessionId, cause: &BackendError) -> bool { let mut state = self.state.write().expect("selection state lock poisoned"); // Settle only sessions still in progress: Cancelled means the user ended it; // Completed means paste succeeded (race: the narrow window between the @@ -600,13 +619,19 @@ impl SelectionServiceInner { &self.history, session_id, state.snapshot.preview_text.as_deref(), - "selectionFailed", + if matches!(cause.message.as_str(), "selectionInputTooLarge" | "selectionPolishWriteUnconfirmed") { + cause.message.as_str() + } else { + "selectionFailed" + }, ) { log::warn!("failed to settle selection history: {error}"); } + state.revoke_capture_authorization(); state.snapshot.phase = SelectionPhase::Failed; let snapshot = state.snapshot.clone(); drop(state); + self.publish_history_changed(); self.events.publish( Some(session_id), BackendEventKind::SelectionStateChanged(snapshot), @@ -637,6 +662,19 @@ impl SelectionServiceInner { if !active { return false; } + if error.code == BackendErrorCode::OutcomeUnknown { + if let Err(persistence_error) = update_original_record( + &self.history, + session_id, + state.snapshot.preview_text.as_deref(), + "selectionPolishWriteUnconfirmed", + ) { + log::warn!("failed to settle uncertain selection history: {persistence_error}"); + } + } + if settled { + state.revoke_capture_authorization(); + } state.snapshot.phase = if settled { SelectionPhase::Failed } else { @@ -644,6 +682,9 @@ impl SelectionServiceInner { }; let snapshot = state.snapshot.clone(); drop(state); + if error.code == BackendErrorCode::OutcomeUnknown { + self.publish_history_changed(); + } self.events.publish( Some(session_id), BackendEventKind::SelectionStateChanged(snapshot), @@ -739,14 +780,13 @@ impl SelectionApi for SelectionService { let inner = Arc::clone(&self.inner); Box::pin(async move { let _runtime = inner.begin_runtime_work()?; - let session_id = inner.begin(&request)?; + let (session_id, authorization) = inner.begin(&request)?; let result = async { let capture = inner .runtime - .capture(session_id, request.selected_text.clone()) + .capture_authorized(session_id, request.selected_text.clone(), authorization) .await?; - inner.set_capture(session_id, &capture)?; - inner.persist_original(session_id, &capture, request.mode)?; + inner.set_capture(session_id, &capture, request.mode)?; inner .runtime .protect_original(session_id, capture.text.clone()) @@ -856,9 +896,11 @@ impl SelectionApi for SelectionService { Ok(session_id) } .await; - if result.is_err() && inner.fail_if_active(session_id) { - inner.cancel_runtime_best_effort(session_id).await; - inner.hide_preview(); + if let Err(error) = &result { + if inner.fail_if_active(session_id, error) { + inner.cancel_runtime_best_effort(session_id).await; + inner.hide_preview(); + } } result }) @@ -920,6 +962,24 @@ impl SelectionApi for SelectionService { if state.snapshot.phase == SelectionPhase::Cancelled { return Ok(()); } + // Revoke even if the host has not received capture(A) yet. + // This is a local atomic store, never an adapter callback under + // the Core state lock. B cannot become active before it. + state.revoke_capture_authorization(); + if matches!( + state.snapshot.phase, + SelectionPhase::Capturing | SelectionPhase::Preview | SelectionPhase::Applying + ) && state.snapshot.source_text.is_some() + { + if let Err(error) = update_original_record( + &inner.history, + active_session, + state.snapshot.preview_text.as_deref(), + "selectionCancelled", + ) { + log::warn!("failed to settle cancelled selection history: {error}"); + } + } state.snapshot.phase = SelectionPhase::Cancelled; let snapshot = state.snapshot.clone(); (active_session, snapshot) @@ -928,10 +988,15 @@ impl SelectionApi for SelectionService { Some(active_session.0), BackendEventKind::SelectionStateChanged(active_session.1), ); + inner.publish_history_changed(); inner.hide_preview(); let active_session = active_session.0; - let polish_result = inner.polisher.cancel(active_session).await; - let runtime_result = inner.runtime.cancel(active_session).await; + // The host synchronously invalidates pending native work at this + // call boundary; do not postpone it behind provider cancellation. + let runtime_cancel = inner.runtime.cancel(active_session); + let (runtime_result, polish_result) = futures_util::future::join( + runtime_cancel, inner.polisher.cancel(active_session), + ).await; polish_result?; runtime_result })) diff --git a/openless-all/app/crates/openless-core/tests/selection_contract.rs b/openless-all/app/crates/openless-core/tests/selection_contract.rs index 36fef91e3..eba84e178 100644 --- a/openless-all/app/crates/openless-core/tests/selection_contract.rs +++ b/openless-all/app/crates/openless-core/tests/selection_contract.rs @@ -1142,6 +1142,9 @@ async fn normal_selection_entry_serializes_full_input_and_rejects_incomplete_str backend.services().selection.begin_polish(SelectionPolishRequest { selected_text: None, mode: PolishMode::Formal, instruction: None }).await.map(|_| ()) }; assert_eq!(result.is_ok(), succeeds, "{result:?}"); + if status == "400 Bad Request" { + assert_eq!(result.as_ref().unwrap_err().message, "selectionInputTooLarge"); + } let request = server.await.unwrap(); if !translation { let system = request["messages"][0]["content"].as_str().unwrap(); @@ -1176,6 +1179,139 @@ async fn normal_selection_entry_serializes_full_input_and_rejects_incomplete_str } } +#[tokio::test] +async fn uncertain_native_write_preserves_both_texts_and_cannot_return_to_retryable_preview() { + let runtime = RecordingSelectionRuntime::new(" \toriginal\n ").with_apply_error( + BackendError::new(BackendErrorCode::OutcomeUnknown, "selectionPolishWriteUnconfirmed"), + ); + let (backend, directory) = backend_with_selection(runtime); + let mut preferences = backend.get_preferences(); + preferences.selection_polish_output_mode = SelectionPolishOutputMode::PreviewConfirm; + write_preferences(&backend, preferences); + backend.start().await.unwrap(); + let id = backend.services().selection.begin_polish(SelectionPolishRequest { + selected_text: None, mode: PolishMode::Formal, instruction: None, + }).await.unwrap(); + let error = backend.services().selection.confirm(id, None).await.unwrap_err(); + assert_eq!(error.code, BackendErrorCode::OutcomeUnknown); + assert_eq!(backend.services().selection.snapshot().await.unwrap().phase, SelectionPhase::Failed); + let history = backend.list_history().unwrap(); + assert_eq!(history[0].raw_transcript, " \toriginal\n "); + assert_eq!(history[0].final_text, "polished preview"); + assert_eq!(history[0].error_code.as_deref(), Some("selectionPolishWriteUnconfirmed")); + assert!(backend.services().selection.confirm(id, None).await.is_err()); + backend.shutdown().await.unwrap(); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[tokio::test] +async fn cancelling_a_preview_preserves_one_original_and_the_existing_result() { + let original = format!(" \t{} CANCEL_MIDDLE {}\n ", "字".repeat(9000), "尾".repeat(9000)); + let runtime = RecordingSelectionRuntime::new(&original); + let (backend, directory) = backend_with_selection(runtime.clone()); + let mut preferences = backend.get_preferences(); + preferences.selection_polish_output_mode = SelectionPolishOutputMode::PreviewConfirm; + write_preferences(&backend, preferences); + backend.start().await.unwrap(); + let id = backend.services().selection.begin_polish(SelectionPolishRequest { + selected_text: None, mode: PolishMode::Formal, instruction: None, + }).await.unwrap(); + backend.services().selection.cancel(Some(id)).await.unwrap(); + backend.services().selection.cancel(Some(id)).await.unwrap(); + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, original); + assert_eq!(history[0].final_text, "polished preview"); + assert_eq!(history[0].error_code.as_deref(), Some("selectionCancelled")); + assert_eq!(runtime.protected.lock().unwrap().as_slice(), std::slice::from_ref(&original)); + assert!(runtime.applied().is_empty()); + backend.shutdown().await.unwrap(); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[tokio::test] +async fn multimodal_selection_sends_the_complete_text_and_rejects_capacity_failures() { + use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; + for rejected in [false, true] { + let original = format!(" \t{} OMNI_MIDDLE_完整选区 {}\n ", "字".repeat(12000), "尾".repeat(12000)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}/v1", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (socket, _) = listener.accept().await.unwrap(); + let mut socket = BufReader::new(socket); + let mut length = 0; + loop { + let mut line = String::new(); + assert_ne!(socket.read_line(&mut line).await.unwrap(), 0); + if line == "\r\n" { break; } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse().unwrap(); + } + } + } + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await.unwrap(); + let (status, response) = if rejected { + ("400 Bad Request", serde_json::json!({"error":{"code":"context_length_exceeded"}})) + } else { + ("200 OK", serde_json::json!({"choices":[{"message":{"content":"complete omni result"},"finish_reason":"stop"}]})) + }; + let response = response.to_string(); + socket.write_all(format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response}", response.len()).as_bytes()).await.unwrap(); + socket.shutdown().await.unwrap(); + serde_json::from_slice::(&bytes).unwrap() + }); + let credentials = Arc::new(InMemoryCredentialStore::default()); + let runtime = RecordingSelectionRuntime::new(&original); + let (backend, directory) = backend_with_selection_parts( + runtime.clone(), + Arc::new(CountingTextPolisher::default()), + credentials, + ); + let channel = "dashscope-omni".to_string(); + backend.set_active_provider(ProviderSlot::Omni, channel.clone()).await.unwrap(); + for (account, value) in [ + ("omni.api_key", "fixture-key"), + ("omni.endpoint", endpoint.as_str()), + ("omni.model", "fixture-text-model"), + ] { + backend.set_credential( + CredentialKey::new(CredentialNamespace::Omni, Some(channel.clone()), account).unwrap(), + SecretValue::new(value), + ).await.unwrap(); + } + let mut preferences = backend.get_preferences(); + preferences.multimodal_pipeline_enabled = true; + preferences.pipeline_mode = openless_core::shared_types::PipelineMode::Multimodal; + preferences.selection_polish_output_mode = SelectionPolishOutputMode::DirectReplace; + write_preferences(&backend, preferences); + backend.start().await.unwrap(); + let result = backend.services().selection.begin_polish(SelectionPolishRequest { + selected_text: None, mode: PolishMode::Formal, instruction: None, + }).await; + let request = tokio::time::timeout(std::time::Duration::from_secs(5), server) + .await.unwrap().unwrap(); + assert_eq!(request["messages"][1]["content"], openless_core::prompts::selection_user_prompt(&original)); + assert_eq!(runtime.protected.lock().unwrap().as_slice(), std::slice::from_ref(&original)); + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, original); + if rejected { + assert_eq!(result.unwrap_err().message, "selectionInputTooLarge"); + assert_eq!(history[0].error_code.as_deref(), Some("selectionInputTooLarge")); + assert!(history[0].final_text.is_empty()); + assert!(runtime.applied().is_empty()); + } else { + result.unwrap(); + assert_eq!(history[0].final_text, "complete omni result"); + assert_eq!(runtime.applied().len(), 1); + } + backend.shutdown().await.unwrap(); + std::fs::remove_dir_all(directory).unwrap(); + } +} + #[tokio::test] async fn default_raw_selection_is_a_true_passthrough_without_an_llm_call() { let runtime = RecordingSelectionRuntime::new("keep this exactly"); @@ -1417,6 +1553,11 @@ async fn cancellation_discards_late_provider_output_and_preserves_busy_ownership assert_eq!(late_error.code, BackendErrorCode::Cancelled); assert!(runtime.applied().is_empty()); assert_eq!(polisher.cancel_count(), 1); + let history = backend.list_history().expect("cancelled original stays recoverable"); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, "late source"); + assert!(history[0].final_text.is_empty()); + assert_eq!(history[0].error_code.as_deref(), Some("selectionCancelled")); assert_eq!( backend .services() diff --git a/openless-all/app/scripts/history-selection-originals-contract.test.mjs b/openless-all/app/scripts/history-selection-originals-contract.test.mjs new file mode 100644 index 000000000..b06bbc084 --- /dev/null +++ b/openless-all/app/scripts/history-selection-originals-contract.test.mjs @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const read = (name) => readFileSync(new URL(`../${name}`, import.meta.url), 'utf8'); +const history = read('src/features/history/History.tsx'); +const list = read('src/features/history/HistoryList.tsx'); +const detail = read('src/features/history/HistoryDetail.tsx'); +const originalSelection = read('src/features/history/useHistoryOriginalSelection.ts'); +const originals = read('src/features/history/selectionOriginals.ts'); + +assert.match(history, /quickNotesOnly \? emptyHistory : filtered/); +assert.match(history, /selectedId=\{item\?\.id\}\s+onSelect=\{selectRecord\}/); +assert.match(list, /type="checkbox"[\s\S]*?toggleOriginal\(session\.id\)/); +assert.match(list, /onClick=\{\(\) => onSelect\(session\.id\)\}/); +assert.match(detail, /showingRaw && hasSelectionOriginal\(item\)/); +assert.match(detail, /onClick=\{\(\) => void onCopy\(showingRaw\)\}/); +assert.match(originalSelection, /selectionOriginalClipboardText\(entries, selectedIds\)/); +assert.match(originalSelection, /await copyTextToClipboard\(text\)/); +assert.match( + originals, + /\(entry\.source === 'selection_polish' \|\| entry\.source === 'selection_voice_edit'\)/, +); +assert.match(originals, /\.map\(\(entry\) => entry\.rawTranscript\)\s*\.join\('\\n\\n'\)/); +assert.doesNotMatch(originals, /\.trim\(|\b(?:finalText|summary)\b/); + +for (const locale of ['zh-CN', 'zh-TW', 'en', 'de', 'es', 'fr', 'ja', 'ko']) { + const source = read(`src/i18n/${locale}.ts`); + for (const key of ['copyOriginal', 'selectOriginals', 'selectAllOriginals', 'copyOriginals']) { + assert.match(source, new RegExp(`\\b${key}:\\s*['"][^'"]+`), `${locale} needs ${key}`); + } +} + +console.log('history original selection, copy and locale contracts passed'); diff --git a/openless-all/app/src-tauri/backend-tests/tests/selection_bound_native.rs b/openless-all/app/src-tauri/backend-tests/tests/selection_bound_native.rs new file mode 100644 index 000000000..a75a42915 --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/selection_bound_native.rs @@ -0,0 +1,213 @@ +//! Production bound transaction with object-addressed reads/writes, not a fake +//! success boolean. A/B deliberately share a window, source and selected range. +#![allow(dead_code)] +#[path = "../../src/selection/bound_native.rs"] +mod bound_native; +use bound_native::{Binding, Failure, Native, TextRange}; +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; + +#[derive(Clone)] +struct Field { + text: Vec, + range: TextRange, +} + +struct Desktop { + fields: RefCell>, + focus: Cell, + permission: Cell, + switch_during_gate: Cell, + switch_after_submit: Cell, + submit_error_after_write: Cell, + reads: RefCell>, + writes: RefCell>, + focus_trace: RefCell>, +} +impl Desktop { + fn fixture() -> (Self, Binding, String) { + let original = format!( + " \t{} UNIQUE_MIDDLE_😀 {}\n ", + "字".repeat(9000), + "尾".repeat(9000) + ); + let field = Field { + text: format!("前{original}后").encode_utf16().collect(), + range: TextRange { + start: 1, + length: original.encode_utf16().count() as u64, + }, + }; + let range = field.range; + ( + Self { + fields: RefCell::new(HashMap::from([(1, field.clone()), (2, field)])), + focus: Cell::new(1), + permission: Cell::new(true), + switch_during_gate: Cell::new(false), + switch_after_submit: Cell::new(false), + submit_error_after_write: Cell::new(false), + reads: RefCell::new(Vec::new()), + writes: RefCell::new(Vec::new()), + focus_trace: RefCell::new(vec![1]), + }, + Binding { + control: 1, + window: 10, + range, + }, + original, + ) + } +} +impl Native for Desktop { + type Control = u32; + type Window = u32; + fn guard(&self, control: &u32, window: &u32) -> Result<(), Failure> { + if !self.permission.get() { + return Err(Failure::Unavailable); + } + if *control != 1 || *window != 10 || self.focus.get() != 1 { + return Err(Failure::TargetChanged); + } + if self.switch_during_gate.replace(false) { + self.focus.set(2); + self.focus_trace.borrow_mut().push(2); + // A current-focus supplier at this instant would return B. + self.focus.set(1); + self.focus_trace.borrow_mut().push(1); + } + Ok(()) + } + fn selected_range(&self, control: &u32) -> Result { + self.reads.borrow_mut().push(*control); + Ok(self.fields.borrow()[control].range) + } + fn text(&self, control: &u32, range: TextRange) -> Result { + self.reads.borrow_mut().push(*control); + let fields = self.fields.borrow(); + let text = fields[control] + .text + .get(range.start as usize..(range.start + range.length) as usize) + .ok_or(Failure::Unavailable)?; + String::from_utf16(text).map_err(|_| Failure::Unavailable) + } + fn writable(&self, control: &u32) -> Result<(), Failure> { + assert_eq!(*control, 1, "capabilities must belong to the frozen object"); + Ok(()) + } + fn submit(&self, control: &u32, replacement: &str) -> Result<(), Failure> { + self.writes.borrow_mut().push(*control); + let mut fields = self.fields.borrow_mut(); + let field = fields.get_mut(control).unwrap(); + let replacement: Vec = replacement.encode_utf16().collect(); + let start = field.range.start as usize; + let end = start + field.range.length as usize; + field.text.splice(start..end, replacement.iter().copied()); + field.range = TextRange { + start: (start + replacement.len()) as u64, + length: 0, + }; + if self.switch_after_submit.get() { + self.focus.set(2); + } + if self.submit_error_after_write.get() { + return Err(Failure::WriteUnconfirmed); + } + Ok(()) + } +} + +#[test] +fn a_to_b_to_a_can_only_operate_on_frozen_a_even_when_b_is_identical() { + let (desktop, binding, original) = Desktop::fixture(); + let b = desktop.fields.borrow()[&2].text.clone(); + desktop.switch_during_gate.set(true); + bound_native::replace(&desktop, &binding, &original, "替换😀").unwrap(); + assert_eq!(*desktop.focus_trace.borrow(), [1, 2, 1]); + assert_eq!(*desktop.writes.borrow(), [1]); + assert!(desktop.reads.borrow().iter().all(|object| *object == 1)); + assert_eq!(desktop.fields.borrow()[&2].text, b); + assert_eq!( + String::from_utf16(&desktop.fields.borrow()[&1].text).unwrap(), + "前替换😀后" + ); +} + +#[test] +fn another_control_or_window_or_permission_cannot_authorize_a_write() { + for case in 0..4 { + let (desktop, mut binding, original) = Desktop::fixture(); + match case { + 0 => binding.control = 2, + 1 => binding.window = 20, + 2 => desktop.focus.set(2), + _ => desktop.permission.set(false), + } + assert!(bound_native::replace(&desktop, &binding, &original, "result").is_err()); + assert!(desktop.writes.borrow().is_empty()); + } +} + +#[test] +fn original_range_and_complete_text_must_both_match_before_submission() { + for change_range in [false, true] { + let (desktop, binding, original) = Desktop::fixture(); + let mut fields = desktop.fields.borrow_mut(); + if change_range { + fields.get_mut(&1).unwrap().range.start += 1; + } else { + fields.get_mut(&1).unwrap().text[5000] = '改' as u16; + } + drop(fields); + assert_eq!( + bound_native::replace(&desktop, &binding, &original, "result"), + Err(Failure::SelectionChanged) + ); + assert!(desktop.writes.borrow().is_empty()); + } +} + +#[test] +fn submission_failure_is_unknown_and_never_retried_or_read_from_new_focus() { + for setter_error in [false, true] { + let (desktop, binding, original) = Desktop::fixture(); + desktop.switch_after_submit.set(true); + desktop.submit_error_after_write.set(setter_error); + assert_eq!( + bound_native::replace(&desktop, &binding, &original, "already written"), + Err(Failure::WriteUnconfirmed) + ); + assert_eq!(*desktop.writes.borrow(), [1]); + assert!(desktop.reads.borrow().iter().all(|object| *object == 1)); + assert_eq!( + String::from_utf16(&desktop.fields.borrow()[&1].text).unwrap(), + "前already written后" + ); + assert!(String::from_utf16(&desktop.fields.borrow()[&2].text) + .unwrap() + .contains(&original)); + } +} + +#[test] +fn unexpected_cf_type_and_non_range_axvalue_never_reach_the_range_decoder() { + for (is_ax_value, is_range) in [(false, true), (true, false), (true, true)] { + let kind_calls = Cell::new(0); + let decode_calls = Cell::new(0); + let result = bound_native::checked_range( + || is_ax_value, + || { + kind_calls.set(kind_calls.get() + 1); + is_range + }, + || { + decode_calls.set(decode_calls.get() + 1); + Some((5, 3)) + }, + ); + assert_eq!(kind_calls.get(), usize::from(is_ax_value)); + assert_eq!(decode_calls.get(), usize::from(is_ax_value && is_range)); + assert_eq!(result.is_some(), is_ax_value && is_range); + } +} diff --git a/openless-all/app/src-tauri/backend-tests/tests/selection_direct_delivery.rs b/openless-all/app/src-tauri/backend-tests/tests/selection_direct_delivery.rs new file mode 100644 index 000000000..e981a86b5 --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/selection_direct_delivery.rs @@ -0,0 +1,116 @@ +//! Exercise the production selection handoff and clipboard ownership transaction. +#![allow(dead_code)] +mod types { + pub use openless_core::shared_types::InsertStatus; +} +#[path = "../../src/insertion/clipboard_delivery.rs"] +mod clipboard_delivery; +#[path = "../../src/selection/direct_delivery.rs"] +mod direct_delivery; +#[path = "../../src/selection/target_position.rs"] +mod target_position; + +use std::cell::RefCell; +use std::rc::Rc; + +#[derive(Default)] +struct State { + text: Option, + revision: u64, + writes: Vec, +} +struct Clipboard(Rc>); +impl clipboard_delivery::ClipboardDelivery for Clipboard { + fn text(&mut self) -> Result, String> { + Ok(self.0.borrow().text.clone()) + } + fn set_text(&mut self, text: &str) -> Result<(), String> { + let mut state = self.0.borrow_mut(); + state.text = Some(text.into()); + state.revision += 1; + state.writes.push(text.into()); + Ok(()) + } + fn sequence(&self) -> Option { + Some(self.0.borrow().revision) + } + fn paste(&mut self) -> Result<(), clipboard_delivery::DispatchError> { + panic!("selection delivery must never simulate paste") + } + fn wait_for_consumption(&mut self) { + panic!("direct delivery must never wait for paste consumption") + } +} + +#[test] +fn successful_native_write_never_copies_the_result_even_temporarily() { + let state = Rc::new(RefCell::new(State::default())); + let mut clipboard = Clipboard(state.clone()); + let original = format!( + " \t{} UNIQUE_MIDDLE {}\n ", + "字".repeat(9000), + "尾".repeat(9000) + ); + let revision = clipboard_delivery::copy_with(&mut clipboard, &original, || true).unwrap(); + let result = direct_delivery::deliver( + || Ok::<_, String>("native readback confirmed"), + |_| { + clipboard_delivery::copy_if_current_with(&mut clipboard, "result", revision, || true)?; + Ok("copied fallback") + }, + ) + .unwrap(); + assert_eq!(result, "native readback confirmed"); + assert_eq!(state.borrow().writes, [original]); +} + +#[test] +fn native_failure_is_confirmed_before_copying_the_result_once() { + let state = Rc::new(RefCell::new(State::default())); + let mut clipboard = Clipboard(state.clone()); + let original = " \toriginal\n "; + let revision = clipboard_delivery::copy_with(&mut clipboard, original, || true).unwrap(); + let attempted = RefCell::new(false); + direct_delivery::deliver( + || { + assert_eq!(state.borrow().writes, [original]); + *attempted.borrow_mut() = true; + Err::<(), _>("original control changed".to_string()) + }, + |_| { + assert!(*attempted.borrow()); + assert!(clipboard_delivery::copy_if_current_with( + &mut clipboard, + "result", + revision, + || true, + )?); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(state.borrow().writes, [original, "result"]); +} + +#[test] +fn user_copy_and_cancellation_each_prevent_result_clipboard_overwrite() { + for user_copied in [false, true] { + let state = Rc::new(RefCell::new(State::default())); + let mut clipboard = Clipboard(state.clone()); + let revision = clipboard_delivery::copy_with(&mut clipboard, "original", || true).unwrap(); + if user_copied { + clipboard_delivery::copy_with(&mut clipboard, "user-owned", || true).unwrap(); + } + let copied = direct_delivery::deliver( + || Err::("cannot safely deliver".to_string()), + |_| { + clipboard_delivery::copy_if_current_with(&mut clipboard, "result", revision, || { + user_copied + }) + }, + ) + .unwrap(); + assert!(!copied); + assert!(!state.borrow().writes.iter().any(|text| text == "result")); + } +} diff --git a/openless-all/app/src-tauri/backend-tests/tests/selection_value_outcome.rs b/openless-all/app/src-tauri/backend-tests/tests/selection_value_outcome.rs new file mode 100644 index 000000000..fe916de3b --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/selection_value_outcome.rs @@ -0,0 +1,732 @@ +//! Production native transaction -> delivery classification -> Core history. +//! Provider faults occur after mutating the bound control, not as canned backend errors. +#![allow(dead_code)] +mod types { + pub use openless_core::shared_types::InsertStatus; +} +#[path = "../../src/insertion/clipboard_delivery.rs"] +mod clipboard_delivery; +#[path = "../../src/selection/direct_delivery.rs"] +mod direct_delivery; +#[path = "../../src/host_document/windows/selection_value.rs"] +mod selection_value; +#[path = "../../src/selection/target_position.rs"] +mod target_position; + +use futures_util::future::BoxFuture; +use openless_core::{ + BackendConfig, BackendDependencies, BackendError, BackendErrorCode, InsertOutcome, + NoopSettingsRuntime, OpenLessBackend, PolishMode, SelectionCapture, SelectionPhase, + SelectionPolishOutputMode, SelectionPolishRequest, SelectionRuntimeAdapter, SessionId, + SettingsUpdateOptions, +}; +use std::sync::{Arc, Mutex}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Fault { + Preflight, + PreflightRange, + SetterAfterWrite, + ReadbackError, + ReadbackMismatch, + TargetLost, + TargetReadError, + CancelledAfterWrite, + Win32LengthChanged, + Win32Unreadable, + None, +} + +struct State { + control: String, + captured_identity: (u32, u64, u64), // PID, window, control + identity: (u32, u64, u64), + captured_position: Option<(u64, u64)>, + position: Option<(u64, u64)>, + result_position: (u64, u64), + cancelled: bool, + range_checks: usize, + identity_checks: usize, + setters: usize, + readbacks: usize, + applies: usize, + clipboard: String, + revision: u64, + protected_revision: Option, + copies: Vec, + native_error: Option, +} + +impl State { + fn identity_current(&self) -> bool { + !self.cancelled && self.identity == self.captured_identity + } +} + +#[derive(Clone)] +struct Clipboard(Arc>); +impl clipboard_delivery::ClipboardDelivery for Clipboard { + fn text(&mut self) -> Result, String> { + Ok(Some(self.0.lock().unwrap().clipboard.clone())) + } + fn set_text(&mut self, text: &str) -> Result<(), String> { + let mut state = self.0.lock().unwrap(); + state.clipboard = text.into(); + state.revision += 1; + state.copies.push(text.into()); + Ok(()) + } + fn sequence(&self) -> Option { + Some(self.0.lock().unwrap().revision) + } + fn paste(&mut self) -> Result<(), clipboard_delivery::DispatchError> { + panic!("selection writes must not paste") + } + fn wait_for_consumption(&mut self) { + panic!("selection writes must not paste") + } +} + +#[derive(Clone)] +struct Runtime { + original: String, + win32: bool, + fault: Fault, + state: Arc>, + history: std::path::PathBuf, +} + +fn control_text(win32: bool, selected: &str) -> String { + if win32 { + format!("pre {selected} post") + } else { + selected.into() + } +} + +impl SelectionRuntimeAdapter for Runtime { + fn capture( + &self, + _: SessionId, + _: Option, + ) -> BoxFuture<'static, Result> { + let text = self.original.clone(); + Box::pin(async move { + Ok(SelectionCapture { + text, + source_app: Some("ValuePattern fixture".into()), + }) + }) + } + + fn protect_original( + &self, + _: SessionId, + text: String, + ) -> BoxFuture<'static, Result, BackendError>> { + let this = self.clone(); + Box::pin(async move { + let rows = openless_core::HistoryStore::at_path(this.history).list()?; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].raw_transcript, text); + let revision = + clipboard_delivery::copy_with(&mut Clipboard(this.state.clone()), &text, || true) + .unwrap(); + this.state.lock().unwrap().protected_revision = revision; + Ok(revision) + }) + } + + fn apply( + &self, + _: SessionId, + original: String, + replacement: String, + ) -> BoxFuture<'static, Result> { + let this = self.clone(); + Box::pin(async move { + this.state.lock().unwrap().applies += 1; + let expected = control_text(this.win32, &replacement); + direct_delivery::deliver( + || { + let result = direct_delivery::native_result(selection_value::replace( + || { + let state = this.state.lock().unwrap(); + assert_eq!(state.control, control_text(this.win32, &original)); + if this.fault == Fault::Preflight { + return Err("selectionPolishTargetUnavailable".into()); + } + if this.win32 { + let units: Vec = state.control.encode_utf16().collect(); + let selected: Vec = original.encode_utf16().collect(); + let (start, length) = state.position.unwrap(); + if units.get(start as usize..(start + length) as usize) + != Some(selected.as_slice()) + { + return Err("selectionPolishSelectionChanged".into()); + } + } + Ok(()) + }, + || { + let mut state = this.state.lock().unwrap(); + state.range_checks += 1; + state.identity_current() + && target_position::unchanged( + state.captured_position, + state.position, + ) + }, + || { + let mut state = this.state.lock().unwrap(); + state.identity_checks += 1; + state.identity_current() + }, + || { + let mut state = this.state.lock().unwrap(); + state.setters += 1; + if this.win32 { + let mut units: Vec = state.control.encode_utf16().collect(); + let (start, length) = state.position.unwrap(); + drop(units.splice( + start as usize..(start + length) as usize, + replacement.encode_utf16(), + )); + state.control = String::from_utf16(&units).unwrap(); + } else { + state.control = replacement.clone(); + } + state.position = Some(state.result_position); + if this.fault == Fault::TargetLost { + state.identity.2 += 1; + } + if this.fault == Fault::CancelledAfterWrite { + state.cancelled = true; + } + if this.fault == Fault::SetterAfterWrite { + Err("provider timed out after applying") + } else { + Ok(()) + } + }, + || { + let mut state = this.state.lock().unwrap(); + state.readbacks += 1; + match this.fault { + Fault::ReadbackError => Err("CurrentValue failed"), + Fault::ReadbackMismatch => { + state.control = "provider changed value".into(); + Ok(state.control == expected) + } + Fault::Win32LengthChanged => { + // Model a field shrinking between WM_GETTEXTLENGTH + // and WM_GETTEXT, just as production read() checks. + let length = state.control.encode_utf16().count(); + state.control.pop(); + let copied = state.control.encode_utf16().count(); + assert_ne!(copied, length); + Err("selectionPolishSelectionChanged") + } + Fault::Win32Unreadable => Err("selectionPolishTargetUnavailable"), + Fault::TargetReadError => Err("CompareElements failed"), + _ => Ok(state.control == expected), + } + }, + )); + if let Err(error) = &result { + this.state.lock().unwrap().native_error = Some(error.clone()); + } + result + }, + |error| { + let revision = this.state.lock().unwrap().protected_revision; + let copied = clipboard_delivery::copy_if_current_with( + &mut Clipboard(this.state.clone()), + &replacement, + revision, + || !this.state.lock().unwrap().cancelled, + ) + .unwrap(); + direct_delivery::fallback_result( + error, + if copied { + Ok(InsertOutcome::CopiedFallback) + } else { + Err(BackendError::new( + BackendErrorCode::InvalidState, + "selectionResultInHistory", + )) + }, + ) + }, + ) + }) + } + + fn revert(&self, _: SessionId) -> BoxFuture<'static, Result> { + Box::pin(async { panic!("an uncertain write must never be rolled back") }) + } + fn cancel(&self, _: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { + Box::pin(async { Ok(()) }) + } +} + +async fn fixture(fault: Fault) -> (OpenLessBackend, Runtime, tempfile::TempDir, SessionId) { + fixture_for(fault, false).await +} + +async fn fixture_for( + fault: Fault, + win32: bool, +) -> (OpenLessBackend, Runtime, tempfile::TempDir, SessionId) { + let directory = tempfile::Builder::new() + .prefix("selection-value-outcome-") + .tempdir() + .unwrap(); + let original = if fault == Fault::None { + "abcdef".to_string() + } else { + format!( + " \t{} VALUE_MIDDLE {}\r\n ", + "字".repeat(9000), + "尾".repeat(9000) + ) + }; + let offset = if win32 { 4 } else { 0 }; + let position = Some((offset, original.encode_utf16().count() as u64)); + let runtime = Runtime { + state: Arc::new(Mutex::new(State { + control: control_text(win32, &original), + captured_identity: (11, 22, 33), + identity: (11, 22, 33), + captured_position: position, + position, + result_position: (offset + 3, 0), + cancelled: false, + range_checks: 0, + identity_checks: 0, + setters: 0, + readbacks: 0, + applies: 0, + clipboard: String::new(), + revision: 0, + protected_revision: None, + copies: Vec::new(), + native_error: None, + })), + original, + win32, + fault, + history: directory.path().join("history.json"), + }; + let mut dependencies = BackendDependencies::unsupported(); + dependencies.selection_runtime = Some(Arc::new(runtime.clone())); + dependencies.selection_polisher = Some(Arc::new( + openless_core::testing::FixtureTextPolisher::successful("XYZ"), + )); + let backend = OpenLessBackend::new( + BackendConfig { + data_dir: directory.path().to_path_buf(), + ..BackendConfig::default() + }, + dependencies, + ) + .unwrap(); + let mut preferences = backend.get_preferences(); + preferences.selection_polish_output_mode = SelectionPolishOutputMode::PreviewConfirm; + backend + .update_settings( + preferences, + SettingsUpdateOptions::STRICT, + &NoopSettingsRuntime, + ) + .unwrap(); + backend.start().await.unwrap(); + let id = backend + .services() + .selection + .begin_polish(SelectionPolishRequest { + selected_text: None, + mode: PolishMode::Formal, + instruction: None, + }) + .await + .unwrap(); + (backend, runtime, directory, id) +} + +#[tokio::test] +async fn post_submission_faults_remain_terminal_even_if_result_was_copied() { + for fault in [ + Fault::SetterAfterWrite, + Fault::ReadbackError, + Fault::ReadbackMismatch, + Fault::TargetLost, + Fault::TargetReadError, + Fault::CancelledAfterWrite, + ] { + for later_copy in [false, true] { + let (backend, runtime, directory, id) = fixture(fault).await; + if later_copy { + // Even copying the *same* original text changes ownership. + clipboard_delivery::copy_with( + &mut Clipboard(runtime.state.clone()), + &runtime.original, + || true, + ) + .unwrap(); + } + let error = backend + .services() + .selection + .confirm(id, None) + .await + .unwrap_err(); + assert_eq!(error.code, BackendErrorCode::OutcomeUnknown, "{fault:?}"); + assert_eq!(error.message, "selectionPolishWriteUnconfirmed"); + assert_eq!( + error.details, + Some(serde_json::json!({ + "original_saved": true, + "result_copied": !later_copy && fault != Fault::CancelledAfterWrite, + })) + ); + let snapshot = backend.services().selection.snapshot().await.unwrap(); + assert_eq!(snapshot.phase, SelectionPhase::Failed); + assert_ne!(snapshot.insert_outcome, Some(InsertOutcome::CopiedFallback)); + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, runtime.original); + assert_eq!(history[0].final_text, "XYZ"); + assert_eq!( + history[0].error_code.as_deref(), + Some("selectionPolishWriteUnconfirmed") + ); + assert!(backend + .services() + .selection + .confirm(id, None) + .await + .is_err()); + { + let state = runtime.state.lock().unwrap(); + assert_eq!(state.setters, 1); + assert_eq!(state.applies, 1, "no resubmission after an unknown write"); + assert_eq!( + state.readbacks, + usize::from(!matches!( + fault, + Fault::SetterAfterWrite | Fault::TargetLost | Fault::CancelledAfterWrite + )) + ); + assert_eq!( + state.range_checks, 1, + "the original range is only a pre-write fence" + ); + assert_eq!( + state.copies.len(), + if fault == Fault::CancelledAfterWrite && !later_copy { + 1 + } else { + 2 + } + ); + assert_eq!(state.copies[0], runtime.original); + assert_eq!( + state.clipboard, + if later_copy || fault == Fault::CancelledAfterWrite { + runtime.original.as_str() + } else { + "XYZ" + } + ); + assert_eq!( + state.control, + if fault == Fault::ReadbackMismatch { + "provider changed value" + } else { + "XYZ" + } + ); + } + backend.shutdown().await.unwrap(); + directory.close().unwrap(); + } + } +} + +#[tokio::test] +async fn preflight_failure_preserves_classification_and_never_calls_the_setter() { + let error = selection_value::replace( + || Err("selectionPolishTargetUnavailable".into()), + || panic!("preflight must stop the selection fence"), + || panic!("preflight must stop the identity fence"), + || -> Result<(), ()> { panic!("preflight must stop submission") }, + || -> Result { panic!("no post-write read before submission") }, + ) + .unwrap_err(); + assert_eq!( + direct_delivery::native_result(Err(error)).unwrap_err().code, + BackendErrorCode::Platform + ); + let (backend, runtime, directory, id) = fixture(Fault::Preflight).await; + backend + .services() + .selection + .confirm(id, None) + .await + .unwrap(); + assert_eq!( + backend + .services() + .selection + .snapshot() + .await + .unwrap() + .insert_outcome, + Some(InsertOutcome::CopiedFallback) + ); + { + let state = runtime.state.lock().unwrap(); + assert_eq!(state.setters, 0); + assert_eq!(state.readbacks, 0); + assert_eq!(state.control, runtime.original); + assert_eq!(state.copies, [runtime.original.clone(), "XYZ".into()]); + } + backend.shutdown().await.unwrap(); + directory.close().unwrap(); +} + +#[tokio::test] +async fn confirmed_value_write_keeps_the_original_clipboard_and_history() { + for result_position in [(3, 0), (0, 3)] { + let (backend, runtime, directory, id) = fixture(Fault::None).await; + { + let mut state = runtime.state.lock().unwrap(); + assert_eq!(state.captured_position, Some((0, 6))); + state.result_position = result_position; + } + backend + .services() + .selection + .confirm(id, None) + .await + .unwrap(); + let snapshot = backend.services().selection.snapshot().await.unwrap(); + assert_eq!(snapshot.phase, SelectionPhase::Completed); + assert_eq!(snapshot.insert_outcome, Some(InsertOutcome::Inserted)); + { + let state = runtime.state.lock().unwrap(); + assert_eq!(state.setters, 1); + assert_eq!(state.readbacks, 1); + assert_eq!(state.range_checks, 1); + assert_eq!( + state.identity_checks, 2, + "identity must fence both sides of readback" + ); + assert_eq!(state.position, Some(result_position)); + assert_eq!(state.identity, state.captured_identity); + assert_eq!(state.control, "XYZ"); + assert_eq!(state.copies, [runtime.original.clone()]); + assert_eq!(state.clipboard, runtime.original); + } + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, runtime.original); + assert_eq!(history[0].final_text, "XYZ"); + backend.shutdown().await.unwrap(); + directory.close().unwrap(); + } +} + +#[tokio::test] +async fn moving_the_original_range_before_submission_blocks_the_setter() { + let (backend, runtime, directory, id) = fixture(Fault::None).await; + runtime.state.lock().unwrap().position = Some((1, 5)); + backend + .services() + .selection + .confirm(id, None) + .await + .unwrap(); + assert_eq!( + backend + .services() + .selection + .snapshot() + .await + .unwrap() + .insert_outcome, + Some(InsertOutcome::CopiedFallback) + ); + { + let state = runtime.state.lock().unwrap(); + assert_eq!(state.range_checks, 1); + assert_eq!(state.identity_checks, 0); + assert_eq!(state.setters, 0); + assert_eq!(state.readbacks, 0); + assert_eq!(state.control, runtime.original); + assert_eq!(state.identity, state.captured_identity); + } + backend.shutdown().await.unwrap(); + directory.close().unwrap(); +} + +#[tokio::test] +async fn win32_success_and_preflight_failures_preserve_original_and_error_classification() { + for fault in [Fault::None, Fault::Preflight, Fault::PreflightRange] { + let (backend, runtime, directory, id) = fixture_for(fault, true).await; + if fault == Fault::PreflightRange { + let mut state = runtime.state.lock().unwrap(); + let (start, length) = state.captured_position.unwrap(); + state.position = Some((start + 1, length - 1)); + } + backend + .services() + .selection + .confirm(id, None) + .await + .unwrap(); + let snapshot = backend.services().selection.snapshot().await.unwrap(); + assert_eq!(snapshot.phase, SelectionPhase::Completed); + { + let state = runtime.state.lock().unwrap(); + if fault == Fault::None { + assert_eq!(snapshot.insert_outcome, Some(InsertOutcome::Inserted)); + assert_eq!( + state.control, "pre XYZ post", + "preserve the unselected fences" + ); + assert_eq!(state.captured_position, Some((4, 6))); + assert_eq!(state.position, Some((7, 0))); + assert_eq!(state.setters, 1); + assert_eq!(state.readbacks, 1); + assert_eq!(state.identity_checks, 2); + assert_eq!(state.copies, [runtime.original.clone()]); + assert!(state.native_error.is_none()); + } else { + assert_eq!(snapshot.insert_outcome, Some(InsertOutcome::CopiedFallback)); + assert_eq!(state.control, control_text(true, &runtime.original)); + assert_eq!(state.setters, 0); + assert_eq!(state.readbacks, 0); + let error = state.native_error.as_ref().unwrap(); + assert_eq!(error.code, BackendErrorCode::Platform); + assert_eq!( + error.message, + if fault == Fault::Preflight { + "selectionPolishTargetUnavailable" + } else { + "selectionPolishSelectionChanged" + } + ); + } + assert_eq!(state.copies[0], runtime.original); + } + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, runtime.original); + assert_eq!(history[0].final_text, "XYZ"); + backend.shutdown().await.unwrap(); + directory.close().unwrap(); + } +} + +#[tokio::test] +async fn win32_post_submission_faults_are_terminal_and_respect_clipboard_revision() { + for fault in [ + Fault::SetterAfterWrite, + Fault::Win32LengthChanged, + Fault::Win32Unreadable, + Fault::ReadbackMismatch, + Fault::TargetLost, + Fault::CancelledAfterWrite, + ] { + for later_copy in [false, true] { + let (backend, runtime, directory, id) = fixture_for(fault, true).await; + if later_copy { + clipboard_delivery::copy_with( + &mut Clipboard(runtime.state.clone()), + &runtime.original, + || true, + ) + .unwrap(); + } + let error = backend + .services() + .selection + .confirm(id, None) + .await + .unwrap_err(); + assert_eq!(error.code, BackendErrorCode::OutcomeUnknown, "{fault:?}"); + assert_eq!(error.message, "selectionPolishWriteUnconfirmed"); + assert_eq!( + error.details, + Some(serde_json::json!({ + "original_saved": true, + "result_copied": !later_copy && fault != Fault::CancelledAfterWrite, + })) + ); + let snapshot = backend.services().selection.snapshot().await.unwrap(); + assert_eq!(snapshot.phase, SelectionPhase::Failed); + assert_ne!(snapshot.insert_outcome, Some(InsertOutcome::CopiedFallback)); + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, runtime.original); + assert_eq!(history[0].final_text, "XYZ"); + assert_eq!( + history[0].error_code.as_deref(), + Some("selectionPolishWriteUnconfirmed") + ); + assert!(backend + .services() + .selection + .confirm(id, None) + .await + .is_err()); + { + let state = runtime.state.lock().unwrap(); + assert_eq!(state.applies, 1); + assert_eq!( + state.setters, 1, + "an unconfirmed EM_REPLACESEL is never retried" + ); + assert_eq!(state.range_checks, 1, "only before submission"); + assert_eq!( + state.readbacks, + usize::from(!matches!( + fault, + Fault::SetterAfterWrite | Fault::TargetLost | Fault::CancelledAfterWrite + )) + ); + assert_eq!(state.copies[0], runtime.original); + assert_eq!( + state.copies.len(), + if fault == Fault::CancelledAfterWrite && !later_copy { + 1 + } else { + 2 + } + ); + assert_eq!( + state.clipboard, + if later_copy || fault == Fault::CancelledAfterWrite { + runtime.original.as_str() + } else { + "XYZ" + } + ); + let expected = control_text(true, "XYZ"); + assert_eq!( + state.control == expected, + !matches!(fault, Fault::Win32LengthChanged | Fault::ReadbackMismatch) + ); + assert_eq!( + state.native_error.as_ref().unwrap().code, + BackendErrorCode::OutcomeUnknown + ); + } + backend.shutdown().await.unwrap(); + directory.close().unwrap(); + } + } +} diff --git a/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs b/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs index 814e31124..1a9c414d1 100644 --- a/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs +++ b/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs @@ -447,23 +447,28 @@ fn handle_selection_workspace_hotkey_pressed(inner: &Arc) { } Err(error) => { log::warn!("[selection-polish] hotkey workflow failed: {error}"); + let locale = inner.backend.services().remote_input.status() + .map(|status| status.locale) + .unwrap_or_else(|_| inner.backend.config().locale.clone()); let message = match error.message.as_str() { + "selectionPolishWriteUnconfirmed" => crate::selection::uncertain_write_message(&locale), "selectionPolishNoSelection" | "selected text must not be empty" => { "未选中内容" } "selectionPolishSelectionTooLong" => { - "选区超过 4000 字,未替换,以免删掉中间没有读到的原文" + "无法完整读取选区,未替换" } "selectionPolishTargetUnavailable" => "目标输入框不可用,请重新选择", "selectionPolishTargetChanged" | "selectionPolishSelectionChanged" => { "选区已变化,未替换" } - _ if error.message.contains("llmResponseIncomplete") + _ if error.message == "selectionInputTooLarge" + || error.message.contains("llmResponseIncomplete") || error.message.contains("context_length") || error.message.contains("maximum context") || error.message.contains("413") => { - "服务无法完整处理全文,未替换;原文已保存在 App 的历史记录" + crate::selection::capacity_failure_message(&locale) } "selectionOriginalCopyFailed" | "selectionOriginalUnavailable" => { "无法保护原文,已停止,未替换" diff --git a/openless-all/app/src-tauri/src/core_adapters.rs b/openless-all/app/src-tauri/src/core_adapters.rs index 7ec9bd350..e55743d86 100644 --- a/openless-all/app/src-tauri/src/core_adapters.rs +++ b/openless-all/app/src-tauri/src/core_adapters.rs @@ -1174,29 +1174,7 @@ trait SelectionPlatformBridge: Send + Sync { } #[cfg(not(mobile))] -struct NativeSelectionPlatformBridge { - app: AppHandleSlot, -} - -#[cfg(not(mobile))] -impl NativeSelectionPlatformBridge { - fn preferences(&self) -> Result { - let app = self.app.lock().clone().ok_or_else(|| { - BackendError::new( - BackendErrorCode::InvalidState, - "Tauri AppHandle is not bound yet", - ) - })?; - app.try_state::>() - .map(|backend| backend.get_preferences()) - .ok_or_else(|| { - BackendError::new( - BackendErrorCode::InvalidState, - "core backend state is unavailable", - ) - }) - } -} +struct NativeSelectionPlatformBridge; #[cfg(not(mobile))] impl SelectionPlatformBridge for NativeSelectionPlatformBridge { @@ -1254,42 +1232,68 @@ impl SelectionPlatformBridge for NativeSelectionPlatformBridge { if validation.error_code().is_some() { return crate::selection::selection_result_fallback(target, replacement_text); } - let preferences = self.preferences()?; crate::selection::insert_selection_result( target, source_text, replacement_text, - preferences.paste_shortcut, ) } } +#[cfg(not(mobile))] +struct TauriSelectionSlot { + generation: u64, + cancelled: Arc, + ready: Option, +} + +#[cfg(not(mobile))] +struct TauriSelectionCaptureReservation { + targets: Arc>>, + session_id: SessionId, + generation: u64, + cancelled: Arc, + armed: bool, +} + +#[cfg(not(mobile))] +impl Drop for TauriSelectionCaptureReservation { + fn drop(&mut self) { + if !self.armed { return; } + let mut targets = self.targets.lock(); + if targets.get(&self.session_id).is_some_and(|slot| slot.generation == self.generation) { + if let Some(slot) = targets.remove(&self.session_id) { + slot.cancelled.store(true, Ordering::Release); + } + } + } +} + #[cfg(not(mobile))] struct TauriSelectionRuntime { bridge: Arc, - targets: Arc>>, + targets: Arc>>, + next_capture_generation: AtomicU64, } #[cfg(not(mobile))] impl TauriSelectionRuntime { - fn new(app: AppHandleSlot) -> Self { - Self::with_bridge(Arc::new(NativeSelectionPlatformBridge { app })) + fn new(_app: AppHandleSlot) -> Self { + Self::with_bridge(Arc::new(NativeSelectionPlatformBridge)) } fn with_bridge(bridge: Arc) -> Self { Self { bridge, targets: Arc::new(Mutex::new(HashMap::new())), + next_capture_generation: AtomicU64::new(1), } } -} - -#[cfg(not(mobile))] -impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { - fn capture( + fn capture_with_authorization( &self, session_id: SessionId, supplied_text: Option, + authorization: Option, ) -> BoxFuture<'static, Result> { if supplied_text.is_some() { return Box::pin(async { @@ -1300,34 +1304,109 @@ impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { }); } let bridge = Arc::clone(&self.bridge); - let targets = Arc::clone(&self.targets); + // Reserve before returning the future: pending/unpolled capture is + // already cancellable, and can never publish over a later generation. + let mut reservation = { + let mut targets = self.targets.lock(); + // Core revokes A before making cancellation/B visible. Check under + // the same lock that serializes A/B reservation, before touching B. + // An unlocked "still active" check before this section is not enough. + if authorization.as_ref().is_some_and(|authority| !authority.allows(session_id)) { + return Box::pin(async { + Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked")) + }); + } + if targets.contains_key(&session_id) { + return Box::pin(async { + Err(BackendError::new(BackendErrorCode::Busy, + "selection target is already reserved for this session")) + }); + } + let generation = match self.next_capture_generation.fetch_update( + Ordering::Relaxed, Ordering::Relaxed, |generation| generation.checked_add(1), + ) { + Ok(generation) => generation, + Err(_) => return Box::pin(async { + Err(BackendError::new(BackendErrorCode::Internal, "selection capture generation exhausted")) + }), + }; + for slot in targets.values() { + slot.cancelled.store(true, Ordering::Release); + } + targets.clear(); + let cancelled = Arc::new(AtomicBool::new(false)); + targets.insert(session_id, TauriSelectionSlot { + generation, + cancelled: Arc::clone(&cancelled), + ready: None, + }); + TauriSelectionCaptureReservation { + targets: Arc::clone(&self.targets), session_id, generation, armed: true, + cancelled, + } + }; Box::pin(async move { - let (capture, target) = tauri::async_runtime::spawn_blocking(move || bridge.capture()) + if reservation.cancelled.load(Ordering::Acquire) + || authorization.as_ref().is_some_and(|authority| !authority.allows(session_id)) + { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture expired")); + } + let cancelled = Arc::clone(&reservation.cancelled); + let worker_authorization = authorization.clone(); + let (capture, mut target) = tauri::async_runtime::spawn_blocking(move || { + if cancelled.load(Ordering::Acquire) + || worker_authorization.as_ref().is_some_and(|authority| !authority.allows(session_id)) + { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture expired")); + } + bridge.capture() + }) .await .map_err(|error| { BackendError::new(BackendErrorCode::Platform, error.to_string()) })??; - let mut targets = targets.lock(); - if targets.contains_key(&session_id) { - return Err(BackendError::new( - BackendErrorCode::Busy, - "selection target is already registered for this session", - )); - } - for target in targets.values() { - target.target.cancelled.store(true, Ordering::Release); + let mut targets = reservation.targets.lock(); + let slot = targets.get_mut(&session_id).filter(|slot| { + slot.generation == reservation.generation + && !slot.cancelled.load(Ordering::Acquire) + && authorization.as_ref().is_none_or(|authority| authority.allows(session_id)) + }); + let Some(slot) = slot else { + target.cancelled.store(true, Ordering::Release); + drop(targets); + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture expired")); + }; + if target.cancelled.load(Ordering::Acquire) { + drop(targets); + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture cancelled")); } - targets.clear(); - targets.insert( - session_id, - TauriSelectionTarget { - target, - preview: false, - }, - ); + target.cancelled = Arc::clone(&slot.cancelled); + slot.ready = Some(TauriSelectionTarget { target, preview: false }); + drop(targets); + reservation.armed = false; Ok(capture) }) } +} + +#[cfg(not(mobile))] +impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { + fn capture( + &self, + session_id: SessionId, + supplied_text: Option, + ) -> BoxFuture<'static, Result> { + self.capture_with_authorization(session_id, supplied_text, None) + } + + fn capture_authorized( + &self, + session_id: SessionId, + supplied_text: Option, + authorization: openless_core::SelectionCaptureAuthorization, + ) -> BoxFuture<'static, Result> { + self.capture_with_authorization(session_id, supplied_text, Some(authorization)) + } fn protect_original( &self, @@ -1339,12 +1418,19 @@ impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { .targets .lock() .get(&session_id) - .map(|target| target.target.clone()) - .unwrap_or_default(); + .and_then(|slot| slot.ready.as_ref()) + .map(|target| target.target.clone()); Box::pin(async move { + let target = target.ok_or_else(|| BackendError::new( + BackendErrorCode::Cancelled, "selection target is no longer active", + ))?; tauri::async_runtime::spawn_blocking(move || { + if target.cancelled.load(Ordering::Acquire) { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection session cancelled")); + } bridge.protect_original(&target, &text)?; - Ok(*target.original_clipboard.lock()) + let revision = *target.original_clipboard.lock(); + Ok(revision) }) .await .map_err(|error| BackendError::new(BackendErrorCode::Platform, error.to_string()))? @@ -1360,13 +1446,16 @@ impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { let bridge = Arc::clone(&self.bridge); let targets = Arc::clone(&self.targets); Box::pin(async move { - let target = targets.lock().get(&session_id).cloned().ok_or_else(|| { + let target = targets.lock().get(&session_id).and_then(|slot| slot.ready.clone()).ok_or_else(|| { BackendError::new( BackendErrorCode::Cancelled, "selection target is no longer active", ) })?; tauri::async_runtime::spawn_blocking(move || { + if target.target.cancelled.load(Ordering::Acquire) { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection session cancelled")); + } bridge.apply( &target.target, &source_text, @@ -1386,7 +1475,7 @@ impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { let targets = Arc::clone(&self.targets); Box::pin(async move { let mut targets = targets.lock(); - let target = targets.get_mut(&session_id).ok_or_else(|| { + let target = targets.get_mut(&session_id).and_then(|slot| slot.ready.as_mut()).ok_or_else(|| { BackendError::new( BackendErrorCode::Cancelled, "selection target is no longer active", @@ -1404,24 +1493,26 @@ impl openless_core::SelectionRuntimeAdapter for TauriSelectionRuntime { let bridge = Arc::clone(&self.bridge); let targets = Arc::clone(&self.targets); Box::pin(async move { - let target = targets.lock().get(&session_id).cloned().ok_or_else(|| { + let target = targets.lock().get(&session_id).and_then(|slot| slot.ready.clone()).ok_or_else(|| { BackendError::new( BackendErrorCode::Cancelled, "selection target is no longer active", ) })?; + if target.target.cancelled.load(Ordering::Acquire) { + return Err(BackendError::new(BackendErrorCode::Cancelled, "selection session cancelled")); + } bridge.revert(&target.target) }) } fn cancel(&self, session_id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { - let targets = Arc::clone(&self.targets); - Box::pin(async move { - if let Some(target) = targets.lock().remove(&session_id) { - target.target.cancelled.store(true, Ordering::Release); - } - Ok(()) - }) + // Invalidate immediately, even when the caller has not polled cancel's + // completion future or the native capture/protection worker is queued. + if let Some(slot) = self.targets.lock().remove(&session_id) { + slot.cancelled.store(true, Ordering::Release); + } + Box::pin(async { Ok(()) }) } } @@ -5820,6 +5911,27 @@ impl TauriHostContextAdapter { } impl openless_core::HostContextAdapter for TauriHostContextAdapter { + #[cfg(not(mobile))] + fn target_identity(&self) -> Option { + crate::selection::target_identity(self.target.as_ref()?) + } + + #[cfg(not(mobile))] + fn validate_target( + &self, + ) -> BoxFuture<'static, openless_core::host_document::target::HostTargetValidation> { + let target = self.target.clone(); + Box::pin(async move { + use openless_core::host_document::target::HostTargetValidation; + let Some(target) = target else { + return HostTargetValidation::Unavailable; + }; + tauri::async_runtime::spawn_blocking(move || crate::selection::validate_target(&target)) + .await + .unwrap_or(HostTargetValidation::Unavailable) + }) + } + #[cfg(not(mobile))] fn input_app(&self) -> Option { crate::selection::input_app_for_target(self.target.as_ref()?) @@ -6363,6 +6475,8 @@ mod tests { capture_calls: std::sync::atomic::AtomicUsize, apply_calls: Mutex>, revert_calls: Mutex, + protect_calls: Mutex>, + capture_pause: Mutex, std::sync::mpsc::Receiver<()>)>>, } #[cfg(not(mobile))] @@ -6378,6 +6492,13 @@ mod tests { > { self.capture_calls .fetch_add(1, std::sync::atomic::Ordering::AcqRel); + let pause = self.capture_pause.lock().take(); + if let Some((entered, release)) = pause { + entered.notify_one(); + release.recv_timeout(std::time::Duration::from_secs(3)).map_err(|_| { + BackendError::new(BackendErrorCode::Platform, "fixture capture release timed out") + })?; + } Ok(( openless_core::SelectionCapture { text: "source".to_string(), @@ -6387,6 +6508,17 @@ mod tests { )) } + fn protect_original( + &self, + target: &crate::selection::SelectionInsertionTarget, + text: &str, + ) -> Result<(), BackendError> { + assert!(!target.cancelled.load(Ordering::Acquire)); + self.protect_calls.lock().push(text.to_string()); + *target.original_clipboard.lock() = Some(1); + Ok(()) + } + fn apply( &self, _target: &crate::selection::SelectionInsertionTarget, @@ -6748,11 +6880,220 @@ mod tests { bridge .capture_calls .load(std::sync::atomic::Ordering::Acquire), - 2 + 1 ); assert_eq!(bridge.apply_calls.lock().len(), 1); } + #[cfg(not(mobile))] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn cancelled_core_begin_cannot_arrive_after_b_and_replace_its_reservation() { + use openless_core::{ + SelectionCapture, SelectionCaptureAuthorization, SelectionPhase, + SelectionPolishOutputMode, SelectionPolishRequest, SelectionRuntimeAdapter, + }; + // Pause before the real adapter sees A. Pausing bridge.capture would + // already have reserved A and would miss the Core -> host admission gap. + struct BeforeHost { + runtime: Arc, + pause: Mutex, std::sync::mpsc::Receiver<()>)>>, + } + impl SelectionRuntimeAdapter for BeforeHost { + fn capture( + &self, id: SessionId, text: Option, + ) -> BoxFuture<'static, Result> { + self.runtime.capture(id, text) + } + fn capture_authorized( + &self, + id: SessionId, + text: Option, + admission: SelectionCaptureAuthorization, + ) -> BoxFuture<'static, Result> { + let pause = self.pause.lock().take(); + if let Some((entered, release)) = pause { + entered.notify_one(); + if release.recv_timeout(std::time::Duration::from_secs(5)).is_err() { + return Box::pin(async { + Err(BackendError::new(BackendErrorCode::Internal, "fixture admission timeout")) + }); + } + } + self.runtime.capture_authorized(id, text, admission) + } + fn protect_original( + &self, id: SessionId, text: String, + ) -> BoxFuture<'static, Result, BackendError>> { + self.runtime.protect_original(id, text) + } + fn prepare_preview(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { + self.runtime.prepare_preview(id) + } + fn apply( + &self, id: SessionId, source: String, replacement: String, + ) -> BoxFuture<'static, Result> { + self.runtime.apply(id, source, replacement) + } + fn revert(&self, id: SessionId) -> BoxFuture<'static, Result> { + self.runtime.revert(id) + } + fn cancel(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { + self.runtime.cancel(id) + } + } + + let bridge = Arc::new(TestSelectionPlatformBridge::default()); + let runtime = Arc::new(TauriSelectionRuntime::with_bridge(bridge.clone())); + let entered = Arc::new(tokio::sync::Notify::new()); + let (release, released) = std::sync::mpsc::channel(); + let adapter = Arc::new(BeforeHost { + runtime: runtime.clone(), + pause: Mutex::new(Some((entered.clone(), released))), + }); + let directory = tempfile::tempdir().unwrap(); + let mut dependencies = openless_core::BackendDependencies::unsupported(); + dependencies.selection_runtime = Some(adapter); + dependencies.selection_polisher = Some(Arc::new( + openless_core::testing::FixtureTextPolisher::successful("B result"), + )); + dependencies.host_actions = Arc::new(openless_core::NoopHostActions); + let backend = Arc::new(openless_core::OpenLessBackend::new( + openless_core::BackendConfig { + data_dir: directory.path().to_path_buf(), ..Default::default() + }, dependencies, + ).unwrap()); + let mut preferences = backend.get_preferences(); + preferences.selection_polish_output_mode = SelectionPolishOutputMode::PreviewConfirm; + backend.update_settings( + preferences, openless_core::SettingsUpdateOptions::STRICT, &openless_core::NoopSettingsRuntime, + ).unwrap(); + backend.start().await.unwrap(); + let mut events = backend.subscribe(); + let selection = backend.services().selection.clone(); + let a = tokio::spawn(async move { + selection.begin_polish(SelectionPolishRequest { + selected_text: None, mode: openless_core::PolishMode::Light, instruction: None, + }).await + }); + tokio::time::timeout(std::time::Duration::from_secs(2), entered.notified()).await.unwrap(); + // Core is accessible while an arbitrary adapter callback is blocked: + // no Core state lock is held across that callback. + let snapshot_a = backend.services().selection.snapshot().await.unwrap(); + let a_id = snapshot_a.session_id.unwrap(); + assert_eq!(snapshot_a.phase, SelectionPhase::Capturing); + let mut published_a = false; + while let Ok(event) = events.try_recv() { + if let openless_core::BackendEventKind::SelectionStateChanged(snapshot) = event.kind { + published_a |= snapshot.session_id == Some(a_id) && snapshot.phase == SelectionPhase::Capturing; + } + } + assert!(published_a); + assert!(runtime.targets.lock().is_empty(), "A has not reached host reservation"); + backend.services().selection.cancel(Some(a_id)).await.unwrap(); + + let b_id = backend.services().selection.begin_polish(SelectionPolishRequest { + selected_text: None, mode: openless_core::PolishMode::Light, instruction: None, + }).await.unwrap(); + assert_ne!(a_id, b_id); + assert!(runtime.targets.lock().get(&b_id).unwrap().ready.is_some()); + // Only now let the cancelled A actually call the real host adapter. + release.send(()).unwrap(); + assert_eq!(tokio::time::timeout(std::time::Duration::from_secs(2), a) + .await.unwrap().unwrap().unwrap_err().code, BackendErrorCode::Cancelled); + assert!(runtime.targets.lock().get(&b_id).is_some_and(|slot| { + slot.ready.is_some() && !slot.cancelled.load(Ordering::Acquire) + })); + assert_eq!(runtime.next_capture_generation.load(Ordering::Relaxed), 2, + "revoked A must not even allocate another host generation"); + assert_eq!(bridge.capture_calls.load(Ordering::Acquire), 1); + assert_eq!(bridge.protect_calls.lock().as_slice(), ["source"]); + let before = backend.list_history().unwrap(); + assert_eq!(before.len(), 1); + assert_eq!(before[0].id, b_id.to_string()); + assert_eq!(before[0].raw_transcript, "source"); + assert_eq!(before[0].final_text, "B result"); + backend.services().selection.confirm(b_id, None).await.unwrap(); + assert!(backend.services().selection.confirm(b_id, None).await.is_err()); + assert_eq!(bridge.apply_calls.lock().as_slice(), + [("source".to_string(), "B result".to_string(), true)]); + let history = backend.list_history().unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].raw_transcript, before[0].raw_transcript); + assert_eq!(history[0].final_text, before[0].final_text); + backend.shutdown().await.unwrap(); + drop(backend); + drop(directory); + } + + #[cfg(not(mobile))] + #[tokio::test] + async fn cancelled_late_selection_capture_cannot_overwrite_the_new_session() { + use openless_core::SelectionRuntimeAdapter; + let bridge = Arc::new(TestSelectionPlatformBridge::default()); + let entered = Arc::new(tokio::sync::Notify::new()); + let (release, released) = std::sync::mpsc::channel(); + *bridge.capture_pause.lock() = Some((entered.clone(), released)); + let runtime = TauriSelectionRuntime::with_bridge(bridge.clone()); + let a = SessionId::new(); + let b = SessionId::new(); + let pending_a = tokio::spawn(runtime.capture(a, None)); + tokio::time::timeout(std::time::Duration::from_secs(2), entered.notified()).await.unwrap(); + let unpolled_cancel = runtime.cancel(a); + runtime.capture(b, None).await.unwrap(); + release.send(()).unwrap(); + let error = tokio::time::timeout(std::time::Duration::from_secs(2), pending_a) + .await.unwrap().unwrap().unwrap_err(); + assert_eq!(error.code, BackendErrorCode::Cancelled); + unpolled_cancel.await.unwrap(); + runtime.protect_original(b, "B original".into()).await.unwrap(); + runtime.apply(b, "source".into(), "B result".into()).await.unwrap(); + assert_eq!(bridge.protect_calls.lock().as_slice(), ["B original"]); + assert_eq!(bridge.apply_calls.lock().as_slice(), + [("source".to_string(), "B result".to_string(), false)]); + assert_eq!(runtime.protect_original(a, "late A".into()).await.unwrap_err().code, + BackendErrorCode::Cancelled); + } + + #[cfg(not(mobile))] + #[tokio::test] + async fn selection_protection_missing_pending_or_cancelled_never_reaches_the_bridge() { + use openless_core::SelectionRuntimeAdapter; + let bridge = Arc::new(TestSelectionPlatformBridge::default()); + let runtime = TauriSelectionRuntime::with_bridge(bridge.clone()); + let missing = SessionId::new(); + assert_eq!(runtime.protect_original(missing, "missing".into()).await.unwrap_err().code, + BackendErrorCode::Cancelled); + let pending = runtime.capture(missing, None); + assert_eq!(runtime.protect_original(missing, "pending".into()).await.unwrap_err().code, + BackendErrorCode::Cancelled); + let pending_cancel = runtime.cancel(missing); + assert_eq!(pending.await.unwrap_err().code, BackendErrorCode::Cancelled); + pending_cancel.await.unwrap(); + assert_eq!(bridge.capture_calls.load(Ordering::Acquire), 0); + runtime.capture(missing, None).await.unwrap(); + let queued_copy = runtime.protect_original(missing, "cancelled".into()); + // Invalidation cannot depend on polling the completion future. + let unpolled_cancel = runtime.cancel(missing); + assert_eq!(queued_copy.await.unwrap_err().code, BackendErrorCode::Cancelled); + unpolled_cancel.await.unwrap(); + assert!(bridge.protect_calls.lock().is_empty()); + } + + #[cfg(not(mobile))] + #[tokio::test] + async fn dropping_an_old_capture_reservation_does_not_discard_a_new_target() { + use openless_core::SelectionRuntimeAdapter; + let bridge = Arc::new(TestSelectionPlatformBridge::default()); + let runtime = TauriSelectionRuntime::with_bridge(bridge.clone()); + let a = runtime.capture(SessionId::new(), None); + let b = SessionId::new(); + runtime.capture(b, None).await.unwrap(); + drop(a); + runtime.apply(b, "source".into(), "new result".into()).await.unwrap(); + assert_eq!(bridge.apply_calls.lock().len(), 1); + assert_eq!(bridge.capture_calls.load(Ordering::Acquire), 1); + } + #[cfg(not(mobile))] #[tokio::test] async fn selection_revert_is_delegated_once_to_the_platform_bridge() { diff --git a/openless-all/app/src-tauri/src/host_document/macos.rs b/openless-all/app/src-tauri/src/host_document/macos.rs index b4c9222d0..47a2652da 100644 --- a/openless-all/app/src-tauri/src/host_document/macos.rs +++ b/openless-all/app/src-tauri/src/host_document/macos.rs @@ -131,6 +131,7 @@ type AxObserverCallback = unsafe extern "C" fn( #[link(name = "ApplicationServices", kind = "framework")] extern "C" { + fn AXUIElementGetTypeID() -> CFTypeId; pub(crate) fn AXUIElementCreateApplication(pid: i32) -> AxUiElementRef; pub(crate) fn AXUIElementGetPid(element: AxUiElementRef, pid: *mut i32) -> AxError; pub(crate) fn AXObserverCreate( @@ -161,6 +162,11 @@ extern "C" { attribute: CFStringRef, value: CFTypeRef, ) -> AxError; + fn AXUIElementIsAttributeSettable( + element: AxUiElementRef, + attribute: CFStringRef, + settable: *mut u8, + ) -> AxError; pub(crate) fn AXUIElementCopyParameterizedAttributeValue( element: AxUiElementRef, parameterized_attribute: CFStringRef, @@ -168,6 +174,8 @@ extern "C" { value: *mut CFTypeRef, ) -> AxError; pub(crate) fn AXValueGetValue(value: AxValueRef, value_type: i32, out: *mut c_void) -> u8; + fn AXValueGetTypeID() -> CFTypeId; + fn AXValueGetType(value: AxValueRef) -> i32; pub(crate) fn AXValueCreate(value_type: i32, value_ptr: *const c_void) -> AxValueRef; } @@ -184,19 +192,8 @@ extern "C" { cstr: *const c_char, encoding: u32, ) -> CFStringRef; - fn CFStringGetCStringPtr(s: CFStringRef, encoding: u32) -> *const c_char; - // Returns `u8`, not `bool`: CoreFoundation's `Boolean` is `unsigned char`, - // not C's `_Bool`. Rust's `bool` requires the bit pattern to be exactly 0 - // or 1 (anything else is UB), so it must not receive an `unsigned char`. - // `AXValueGetValue` in this file already uses `u8`. - fn CFStringGetCString( - s: CFStringRef, - buffer: *mut c_char, - buffer_size: isize, - encoding: u32, - ) -> u8; fn CFStringGetLength(s: CFStringRef) -> isize; - fn CFStringGetMaximumSizeForEncoding(length: isize, encoding: u32) -> isize; + fn CFStringGetCharacters(s: CFStringRef, range: CFRange, buffer: *mut u16); fn CFNumberGetValue(number: CFTypeRef, number_type: i32, value_ptr: *mut c_void) -> u8; } @@ -394,14 +391,17 @@ fn caret_offset_from_location(location: isize) -> Option { unsafe fn copy_selected_range(focused: AxUiElementRef) -> Option { let value = copy_attr(focused, b"AXSelectedTextRange\0")?; - let mut range = CFRange::default(); - let ok = AXValueGetValue( - value as AxValueRef, - K_AX_VALUE_CF_RANGE_TYPE, - &mut range as *mut _ as *mut c_void, + let range = crate::selection::bound_native::checked_range( + || CFGetTypeID(value) == AXValueGetTypeID(), + || AXValueGetType(value as AxValueRef) == K_AX_VALUE_CF_RANGE_TYPE, + || { + let mut range = CFRange::default(); + (AXValueGetValue(value as AxValueRef, K_AX_VALUE_CF_RANGE_TYPE, + &mut range as *mut _ as *mut c_void) != 0).then_some(range) + }, ); CFRelease(value); - (ok != 0).then_some(range) + range } /// Selection coordinates only: reuse the same gated AX reader as delivery @@ -571,6 +571,150 @@ pub(super) fn apply_voice_edit_target( } } +/// Synchronous owner-scoped read seam for P5. Read only these borrowed original +/// objects; never recapture focus as a substitute or let native refs escape. +/// Call on spawn_blocking; this does not supply focus/tab continuity evidence. +pub(crate) fn with_frozen_target_read( + target: &crate::selection::SelectionInsertionTarget, + read: impl for<'a> FnOnce(&crate::selection::FrozenMacosTarget<'a>) -> Result, +) -> Result { + crate::selection::borrow_frozen_macos_target(target, |lease| { + let (control, window) = unsafe { lease.ax_objects() }; + let native = FrozenSelectionNative { lease }; + use crate::selection::bound_native::Native; + native.guard(&control, &window).map_err(|error| error.message().to_string())?; + let result = read(lease)?; + native.guard(&control, &window).map_err(|error| error.message().to_string())?; + Ok(result) + }) +} + +struct FrozenSelectionNative<'a, 'owner> { + lease: &'a crate::selection::FrozenMacosTarget<'owner>, +} + +impl crate::selection::bound_native::Native for FrozenSelectionNative<'_, '_> { + type Control = *mut c_void; + type Window = *mut c_void; + + fn guard(&self, control: &Self::Control, window: &Self::Window) + -> Result<(), crate::selection::bound_native::Failure> + { + use crate::selection::bound_native::Failure; + unsafe { + if crate::permissions::check_accessibility() != crate::permissions::PermissionStatus::Granted + || crate::unicode_keystroke::is_secure_input_enabled() + { + return Err(Failure::Unavailable); + } + let (owned_control, owned_window) = self.lease.ax_objects(); + if CFGetTypeID((*control).cast()) != AXUIElementGetTypeID() + || CFGetTypeID((*window).cast()) != AXUIElementGetTypeID() + { + return Err(Failure::Unavailable); + } + if CFEqual((*control).cast(), owned_control.cast()) == 0 + || CFEqual((*window).cast(), owned_window.cast()) == 0 + || !self.lease.is_current() + { + return Err(Failure::TargetChanged); + } + let element = (*control).cast::(); + let window = (*window).cast::(); + for object in [element, window] { + AXUIElementSetMessagingTimeout(object, AX_MESSAGING_TIMEOUT_SECS); + let mut pid = 0; + if AXUIElementGetPid(object, &mut pid) != AX_ERROR_SUCCESS + || pid != self.lease.process_id() + { + return Err(Failure::TargetChanged); + } + } + let owner_window = copy_element_attr(element, b"AXWindow\0").ok_or(Failure::Unavailable)?; + let same_window = CFEqual(owner_window.cast(), window.cast()) != 0; + CFRelease(owner_window.cast()); + if !same_window { return Err(Failure::TargetChanged); } + let bundle_id = crate::selection::bundle_id_for_pid(self.lease.process_id()) + .ok_or(Failure::Unavailable)?; + let role = copy_string_attr(element, b"AXRole\0").ok_or(Failure::Unavailable)?; + let gate = GateInputs { + secure_input: crate::unicode_keystroke::is_secure_input_enabled(), + bundle_id: Some(bundle_id), + role: Some(role), + subrole: copy_string_attr(element, b"AXSubrole\0"), + }; + if evaluate_gate(&gate).is_some() { return Err(Failure::Unavailable); } + if !self.lease.is_current() { return Err(Failure::TargetChanged); } + Ok(()) + } + } + + fn selected_range(&self, control: &Self::Control) + -> Result + { + use crate::selection::bound_native::{Failure, TextRange}; + let range = unsafe { copy_selected_range((*control).cast()) }.ok_or(Failure::Unavailable)?; + Ok(TextRange { + start: u64::try_from(range.location).map_err(|_| Failure::Unavailable)?, + length: u64::try_from(range.length).map_err(|_| Failure::Unavailable)?, + }) + } + + fn text(&self, control: &Self::Control, range: crate::selection::bound_native::TextRange) + -> Result + { + use crate::selection::bound_native::Failure; + let end = range.start.checked_add(range.length).ok_or(Failure::Unavailable)?; + isize::try_from(end).map_err(|_| Failure::Unavailable)?; + unsafe { copy_string_for_range((*control).cast(), range.start as usize, range.length as usize) } + .ok_or(Failure::Unavailable) + } + + fn writable(&self, control: &Self::Control) -> Result<(), crate::selection::bound_native::Failure> { + use crate::selection::bound_native::Failure; + unsafe { + let attribute = cfstring_from_static(b"AXSelectedText\0").ok_or(Failure::Unavailable)?; + let mut settable = 0u8; + let result = AXUIElementIsAttributeSettable((*control).cast(), attribute, &mut settable); + CFRelease(attribute); + if result != AX_ERROR_SUCCESS || settable == 0 { return Err(Failure::Unavailable); } + Ok(()) + } + } + + fn submit(&self, control: &Self::Control, replacement: &str) + -> Result<(), crate::selection::bound_native::Failure> + { + use crate::selection::bound_native::Failure; + unsafe { + let value = core_foundation::string::CFString::new(replacement); + let attribute = cfstring_from_static(b"AXSelectedText\0").ok_or(Failure::Unavailable)?; + let result = AXUIElementSetAttributeValue((*control).cast(), attribute, + value.as_concrete_TypeRef().cast()); + CFRelease(attribute); + if result != AX_ERROR_SUCCESS { return Err(Failure::WriteUnconfirmed); } + Ok(()) + } + } +} + +/// No focused-element supplier exists in this path. All operations address the +/// immutable frozen control and AX window kept alive by the owner callback. +pub(super) fn replace_selection_direct( + target: &crate::selection::SelectionInsertionTarget, + original: &str, + replacement: &str, +) -> Result<(), String> { + use crate::selection::bound_native::{self, Binding, TextRange}; + crate::selection::borrow_frozen_macos_target(target, |lease| { + let (control, window) = unsafe { lease.ax_objects() }; + let (start, length) = lease.range().ok_or("selectionPolishTargetUnavailable")?; + let binding = Binding { control, window, range: TextRange { start, length } }; + bound_native::replace(&FrozenSelectionNative { lease }, &binding, original, replacement) + .map_err(|error| error.message().to_string()) + }) +} + /// Confirms all posted keyboard input against the original text control's caret. /// Only metadata is read; the target's document text is never fetched. /// Create, wait and drop on the same blocking insertion thread. @@ -989,7 +1133,13 @@ unsafe fn copy_index_attr(element: AxUiElementRef, attribute: &[u8]) -> Option Option { - copy_attr(element, attribute).map(|value| value as AxUiElementRef) + let value = copy_attr(element, attribute)?; + if CFGetTypeID(value) == AXUIElementGetTypeID() { + Some(value as AxUiElementRef) + } else { + CFRelease(value); + None + } } /// Reads the raw CFTypeRef of any attribute. **Caller must `CFRelease`.** @@ -1016,29 +1166,13 @@ unsafe fn cfstring_from_static(bytes_with_nul: &[u8]) -> Option { } unsafe fn cfstring_to_rust(s: CFStringRef) -> Option { - let direct = CFStringGetCStringPtr(s, K_CF_STRING_ENCODING_UTF8); - if !direct.is_null() { - return CStr::from_ptr(direct).to_str().ok().map(str::to_string); - } let length = CFStringGetLength(s); - if length <= 0 { - return Some(String::new()); - } - let max_bytes = CFStringGetMaximumSizeForEncoding(length, K_CF_STRING_ENCODING_UTF8) + 1; - let mut buf: Vec = vec![0; max_bytes as usize]; - let ok = CFStringGetCString( - s, - buf.as_mut_ptr() as *mut c_char, - max_bytes, - K_CF_STRING_ENCODING_UTF8, - ); - if ok == 0 { + if length < 0 { return None; } - CStr::from_ptr(buf.as_ptr() as *const c_char) - .to_str() - .ok() - .map(str::to_string) + let mut units = vec![0u16; length as usize]; + CFStringGetCharacters(s, CFRange { location: 0, length }, units.as_mut_ptr()); + String::from_utf16(&units).ok() } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/openless-all/app/src-tauri/src/host_document/mod.rs b/openless-all/app/src-tauri/src/host_document/mod.rs index 9af1b7a6d..b026691d5 100644 --- a/openless-all/app/src-tauri/src/host_document/mod.rs +++ b/openless-all/app/src-tauri/src/host_document/mod.rs @@ -110,6 +110,33 @@ pub(crate) fn capture_voice_edit_target() -> Result< } } +/// Replace only the live explicit selection through a native control API. +/// Called on the blocking insertion thread while holding the delivery gate. +/// Unsupported editors fail closed; this function never sends keys or copies. +pub(crate) fn replace_selection_direct( + original: &str, + replacement: &str, + still_current: impl Fn() -> bool, + target: &crate::selection::SelectionInsertionTarget, +) -> Result<(), String> { + #[cfg(target_os = "macos")] + { + let _ = still_current; + macos::replace_selection_direct(target, original, replacement) + } + #[cfg(target_os = "windows")] + { + windows::replace_selection_direct(original, replacement, still_current, || { + crate::selection::selection_write_identity_is_current(target) + }) + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + let _ = (original, replacement, still_current, target); + Err("selectionPolishTargetUnavailable".into()) + } +} + /// Restore the original app, compare the exact control, full text and selection, then write. /// The inserter must recheck the prepared target predicate after acquiring the delivery gate. /// Call only on the blocking native insertion thread. @@ -817,3 +844,8 @@ pub(crate) use windows::{is_blocked_process_name, runtime_id as uia_runtime_id}; pub(crate) fn read_qa_selection() -> Option { windows::read_qa_selection() } + +#[cfg(target_os = "windows")] +pub(crate) fn read_selection_full() -> Option { + windows::read_selection_full() +} diff --git a/openless-all/app/src-tauri/src/host_document/windows.rs b/openless-all/app/src-tauri/src/host_document/windows.rs index e553089c4..2ae0e0232 100644 --- a/openless-all/app/src-tauri/src/host_document/windows.rs +++ b/openless-all/app/src-tauri/src/host_document/windows.rs @@ -27,6 +27,7 @@ use windows::Win32::{ type Callback = Box) -> bool + Send + Sync>; mod edit_settle; +mod selection_value; use edit_settle::{can_publish, has_edit_events, EditSettle}; #[derive(Debug, Clone)] @@ -163,6 +164,16 @@ fn focused_uia_position() -> Option<(u64, u64)> { } pub(super) fn read_qa_selection() -> Option { + read_selection_with_limit(16_000) +} + +/// Explicit replacement owns the complete selection; QA's separate reference +/// budget must not become a truncation boundary for editing or validation. +pub(super) fn read_selection_full() -> Option { + read_selection_with_limit(-1) +} + +fn read_selection_with_limit(max_length: i32) -> Option { with_voice_edit_uia(|uia| unsafe { let element = uia .GetFocusedElement() @@ -202,15 +213,144 @@ pub(super) fn read_qa_selection() -> Option { return Ok(None); } let text = range - .GetText(16_000) + .GetText(max_length) .map_err(|_| "selectionUnavailable".to_string())? .to_string(); + if !uia.CompareElements(&element, &uia.GetFocusedElement() + .map_err(|_| "selectionUnavailable".to_string())?) + .map_err(|_| "selectionUnavailable".to_string())?.as_bool() + { + return Ok(None); + } Ok((!text.trim().is_empty()).then_some(text)) }) .ok() .flatten() } +/// Win32 Edit/RichEdit supports a true selected-range replacement. Other UIA +/// controls are writable only when ValuePattern proves the entire field is the +/// original selection. We never synthesize paste into the current focus. +pub(super) fn replace_selection_direct( + original: &str, + replacement: &str, + still_current: impl Fn() -> bool, + identity_current: impl Fn() -> bool, +) -> std::result::Result<(), String> { + use windows::Win32::Foundation::{LPARAM, WPARAM}; + use windows::Win32::UI::WindowsAndMessaging::{ + GetClassNameW, SendMessageTimeoutW, SMTO_ABORTIFHUNG, SMTO_BLOCK, + }; + with_voice_edit_uia(|uia| unsafe { + let unavailable = |_| "selectionPolishTargetUnavailable".to_string(); + if !still_current() || original.is_empty() || replacement.contains('\0') { + return Err("selectionPolishTargetUnavailable".into()); + } + let element = uia.GetFocusedElement().map_err(unavailable)?; + if element.CurrentIsPassword().map_err(unavailable)?.as_bool() + || !allowed_process(&element).map_err(unavailable)? + { + return Err("selectionPolishTargetUnavailable".into()); + } + let hwnd = element.CurrentNativeWindowHandle().map_err(unavailable)?; + let mut class = [0u16; 128]; + let size = GetClassNameW(hwnd, &mut class); + let class = String::from_utf16_lossy(&class[..size.max(0) as usize]).to_ascii_lowercase(); + if class == "edit" || class.starts_with("richedit") { + let send = |message, wparam, lparam| -> std::result::Result { + let mut result = 0usize; + if SendMessageTimeoutW(hwnd, message, wparam, lparam, + SMTO_ABORTIFHUNG | SMTO_BLOCK, 200, Some(&mut result)).0 == 0 { + Err("selectionPolishWriteUnconfirmed".into()) + } else { + Ok(result) + } + }; + let read = || -> std::result::Result, String> { + let length = send(0x000e, WPARAM(0), LPARAM(0))?; // WM_GETTEXTLENGTH + let capacity = length.checked_add(1).ok_or("selectionPolishTargetUnavailable")?; + let mut text = Vec::new(); + text.try_reserve_exact(capacity).map_err(|_| "selectionPolishTargetUnavailable")?; + text.resize(capacity, 0u16); + let copied = send(0x000d, WPARAM(capacity), LPARAM(text.as_mut_ptr() as isize))?; + if copied != length { + return Err("selectionPolishSelectionChanged".into()); + } + text.truncate(length); + Ok(text) + }; + let selection = || -> std::result::Result<(usize, usize), String> { + let (mut start, mut end) = (u32::MAX, u32::MAX); + send(0x00b0, WPARAM(&mut start as *mut u32 as usize), + LPARAM(&mut end as *mut u32 as isize))?; // EM_GETSEL + if start == u32::MAX || end <= start { + return Err("selectionPolishSelectionChanged".into()); + } + Ok((start as usize, end as usize)) + }; + let baseline = read()?; + let (start, end) = selection()?; + let original_units: Vec = original.encode_utf16().collect(); + if baseline.get(start..end) != Some(original_units.as_slice()) { + return Err("selectionPolishSelectionChanged".into()); + } + let replacement_units: Vec = replacement.encode_utf16().collect(); + let mut expected = baseline[..start].to_vec(); + expected.extend_from_slice(&replacement_units); + expected.extend_from_slice(&baseline[end..]); + let mut value = replacement_units; + value.push(0); + if !still_current() + || !uia.CompareElements(&element, &uia.GetFocusedElement().map_err(unavailable)?) + .map_err(unavailable)?.as_bool() + || read()? != baseline || selection()? != (start, end) || !still_current() + { + return Err("selectionPolishTargetChanged".into()); + } + return selection_value::submit_and_confirm( + &identity_current, + || send(0x00c2, WPARAM(1), LPARAM(value.as_ptr() as isize)).map(|_| ()), // EM_REPLACESEL + || { + Ok(!element.CurrentIsPassword().map_err(unavailable)?.as_bool() + && allowed_process(&element).map_err(unavailable)? + && read()? == expected + && uia.CompareElements(&element, &uia.GetFocusedElement().map_err(unavailable)?) + .map_err(unavailable)?.as_bool()) + }, + ); + } + let value = element.GetCurrentPatternAs::(UIA_ValuePatternId) + .map_err(unavailable)?; + selection_value::replace( + || { + if value.CurrentIsReadOnly().map_err(unavailable)?.as_bool() + || value.CurrentValue().map_err(unavailable)?.to_string() != original + || read_selection_full().as_deref() != Some(original) + || !still_current() + || !uia.CompareElements(&element, &uia.GetFocusedElement().map_err(unavailable)?) + .map_err(unavailable)?.as_bool() + || value.CurrentValue().map_err(unavailable)?.to_string() != original + { + return Err("selectionPolishTargetUnavailable".into()); + } + Ok(()) + }, + &still_current, + &identity_current, + || value.SetValue(&windows::core::BSTR::from(replacement)), + || { + // Read only the pattern belonging to the original element. A + // lost target or unreadable value after submission is unknown. + Ok(!element.CurrentIsPassword()?.as_bool() + && allowed_process(&element)? + && !value.CurrentIsReadOnly()?.as_bool() + && value.CurrentValue()?.to_string() == replacement + && uia.CompareElements(&element, &uia.GetFocusedElement()?)?.as_bool()) + }, + ) + }) +} + pub(crate) unsafe fn runtime_id(element: &IUIAutomationElement) -> Result> { use windows::Win32::System::Ole::{ SafeArrayDestroy, SafeArrayGetElement, SafeArrayGetLBound, SafeArrayGetUBound, diff --git a/openless-all/app/src-tauri/src/host_document/windows/selection_value.rs b/openless-all/app/src-tauri/src/host_document/windows/selection_value.rs new file mode 100644 index 000000000..f1170b4e7 --- /dev/null +++ b/openless-all/app/src-tauri/src/host_document/windows/selection_value.rs @@ -0,0 +1,38 @@ +//! Native selection writes have one irreversible submission. +//! A provider error after that boundary does not prove that nothing was written. +//! selection_current includes the original range and is only checked before +//! submission. identity_current must fence cancellation and identity, not range. + +pub(crate) fn replace( + preflight: impl FnOnce() -> Result<(), String>, + selection_current: impl FnOnce() -> bool, + identity_current: impl Fn() -> bool, + submit: impl FnOnce() -> Result<(), E>, + confirm: impl FnOnce() -> Result, +) -> Result<(), String> { + preflight()?; + if !selection_current() { + return Err("selectionPolishTargetUnavailable".into()); + } + submit_and_confirm(identity_current, submit, confirm) +} + +/// Both Win32 and ValuePattern arrive here only after their original preflight. +pub(crate) fn submit_and_confirm( + identity_current: impl Fn() -> bool, + submit: impl FnOnce() -> Result<(), E>, + confirm: impl FnOnce() -> Result, +) -> Result<(), String> { + // Never retry: a native setter may have taken effect even when it returns an error. + submit().map_err(|_| "selectionPolishWriteUnconfirmed".to_string())?; + // Only the identity/cancellation fence surrounds readback. The write itself + // can legitimately collapse the old selection or select the new result. + if !identity_current() { + return Err("selectionPolishWriteUnconfirmed".into()); + } + match confirm() { + Ok(true) if identity_current() => Ok(()), + Ok(true) => Err("selectionPolishWriteUnconfirmed".into()), + Ok(false) | Err(_) => Err("selectionPolishWriteUnconfirmed".into()), + } +} diff --git a/openless-all/app/src-tauri/src/selection.rs b/openless-all/app/src-tauri/src/selection.rs index da777eb92..1a7e18311 100644 --- a/openless-all/app/src-tauri/src/selection.rs +++ b/openless-all/app/src-tauri/src/selection.rs @@ -23,6 +23,11 @@ use std::time::Duration; mod clipboard_capture; #[path = "selection/target_position.rs"] mod target_position; +#[path = "selection/direct_delivery.rs"] +mod direct_delivery; +#[path = "selection/bound_native.rs"] +#[cfg(any(target_os = "macos", test))] +pub(crate) mod bound_native; #[cfg(target_os = "windows")] use clipboard_capture::ClipboardPollOutcome; @@ -91,6 +96,7 @@ struct MacosSelectionTarget { front_app_pid: Option, dictation_window: Option, dictation_element: Option>, + dictation_ax_window: Option>, } /// Result of the final target/selection revalidation immediately before a @@ -140,6 +146,7 @@ pub(crate) enum SelectionCaptureMissReason { ClipboardEmptyAfterCopy, ClipboardReadFailed, EmptyTrimmed, + TargetChanged, NoCapturePath, } @@ -157,6 +164,7 @@ impl SelectionCaptureMissReason { Self::ClipboardEmptyAfterCopy => "clipboard_empty_after_copy", Self::ClipboardReadFailed => "clipboard_read_failed", Self::EmptyTrimmed => "empty_trimmed", + Self::TargetChanged => "target_changed", Self::NoCapturePath => "no_capture_path", } } @@ -195,7 +203,7 @@ static PREFETCHED_SELECTION_WORKSPACE: std::sync::Mutex ( return (Some(selection), insertion_target, diag); } let insertion_target = capture_selection_insertion_target(); - let (capture, reason) = capture_selection_with_status_diag(); + let (capture, reason) = capture_selection_for_target(&insertion_target); let target_captured = selection_insertion_target_is_captured(&insertion_target); let (front_app, char_count) = match &capture.selection { Some(selection) => ( @@ -336,6 +344,44 @@ fn capture_selection_source_app_hint() -> Option { current_front_app() } +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn capture_selection_for_target( + target: &SelectionInsertionTarget, +) -> (SelectionCaptureOutcome, SelectionCaptureMissReason) { + let position = *target.dictation_position.lock(); + let still_current = || { + native_input_target_is_current(target) + && position.is_none_or(|position| { + crate::host_document::focused_input_position() == Some(position) + }) + && native_input_target_is_current(target) + }; + if !still_current() { + return (SelectionCaptureOutcome { selection: None }, SelectionCaptureMissReason::TargetChanged); + } + // A replacement capture must not issue Copy before Core has durably saved + // the original. Unsupported native selection readers fail without touching + // the user's clipboard; legacy QA capture keeps its own compatibility path. + #[cfg(target_os = "macos")] + let text = read_selection_for_validation(); + #[cfg(target_os = "windows")] + let text = crate::host_document::read_selection_full(); + if !still_current() { + return (SelectionCaptureOutcome { selection: None }, SelectionCaptureMissReason::TargetChanged); + } + let selection = text.map(|text| SelectionContext { + text, + source_app: front_app_for_target(target), + omits_middle: false, + }); + let reason = if selection.is_some() { + SelectionCaptureMissReason::Ok + } else { + SelectionCaptureMissReason::NoCapturePath + }; + (SelectionCaptureOutcome { selection }, reason) +} + /// Snapshot the insertion target before starting an asynchronous Selection /// Polish request. Windows is intentionally fail-closed when this cannot /// identify a concrete foreground target; macOS records the frontmost app so @@ -370,6 +416,8 @@ pub(crate) fn capture_selection_insertion_target() -> SelectionInsertionTarget { (None, Some(bundle)) => Some(bundle.to_string()), (None, None) => None, }; + let element = macos_ax::capture_focused_element(); + let ax_window = element.as_ref().and_then(|element| element.window()); return SelectionInsertionTarget { dictation_position: std::sync::Arc::new(parking_lot::Mutex::new(crate::host_document::focused_input_position())), macos: Some(MacosSelectionTarget { @@ -378,7 +426,8 @@ pub(crate) fn capture_selection_insertion_target() -> SelectionInsertionTarget { bundle_id, front_app_pid, dictation_window: front_app_pid.and_then(macos_front_window_id), - dictation_element: macos_ax::capture_focused_element(), + dictation_element: element, + dictation_ax_window: ax_window, }), ..Default::default() }; @@ -407,7 +456,7 @@ pub(crate) fn capture_dictation_insertion_target() -> SelectionInsertionTarget { } #[cfg(target_os = "windows")] { - target.dictation_selection = crate::host_document::read_qa_selection(); + target.dictation_selection = crate::host_document::read_selection_full(); } } let mut last = LAST_DICTATION_TARGET.lock(); @@ -528,74 +577,110 @@ pub(crate) fn selection_result_fallback( #[path = "selection/recovery_notice.rs"] mod recovery_notice; -pub(crate) use recovery_notice::original_recovery_message; +pub(crate) use recovery_notice::{capacity_failure_message, original_recovery_message, uncertain_write_message}; -/// Final native handoff. Clipboard restore is mandatory for selection workflows. +/// Final native handoff. Successful selection writes never touch the clipboard. pub(crate) fn insert_selection_result( target: &SelectionInsertionTarget, source_text: &str, text: &str, - shortcut: crate::types::PasteShortcut, ) -> Result { - if !selection_insertion_target_is_current(target) { - return selection_result_fallback(target, text); - } + direct_delivery::deliver( + || { + // Serialize native delivery with other insertions, without borrowing + // or rewriting the clipboard. Drop the gate before fallback copies. + let _delivery = crate::insertion::clipboard_delivery::lock(); + direct_delivery::native_result(crate::host_document::replace_selection_direct( + source_text, + text, + || selection_insertion_target_is_current(target), + target, + )) + }, + |error| direct_delivery::fallback_result(error, selection_result_fallback(target, text)), + ) +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn opaque_target_token(domain: &str, value: impl std::hash::Hash) -> String { + use std::hash::{Hash, Hasher}; + static SALT: std::sync::OnceLock = std::sync::OnceLock::new(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + SALT.get_or_init(uuid::Uuid::new_v4).hash(&mut hasher); + domain.hash(&mut hasher); + value.hash(&mut hasher); + format!("{:016x}", hasher.finish()) +} + +/// Metadata from the frozen destination. No native reads, titles, document text +/// or native handles escape through this interface. +pub(crate) fn target_identity( + target: &SelectionInsertionTarget, +) -> Option { + #[cfg(any(target_os = "macos", target_os = "windows"))] + use openless_core::host_document::target::{ + HostSelectionRange, HostTargetIdentity, HostTextUnit, + }; #[cfg(target_os = "macos")] - let mut delivery = crate::host_document::KeyboardDelivery::capture(); - if !selection_insertion_target_is_current(target) { - return selection_result_fallback(target, text); + { + let captured = target.macos.as_ref()?; + Some(HostTargetIdentity { + process_id: u32::try_from(captured.front_app_pid?).ok()?, + window_token: opaque_target_token("window", captured.dictation_window?), + control_token: opaque_target_token("control", captured.dictation_element.as_ref()?.identity_hash()), + selection: target.dictation_position.lock().map(|(start, length)| HostSelectionRange { + start, length, unit: HostTextUnit::Utf16, + }), + }) } - let expected_clipboard = *target.original_clipboard.lock(); - if !crate::insertion::clipboard_revision_matches( - expected_clipboard, - crate::insertion::clipboard_sequence(), - ) { - return Err(openless_core::BackendError::new( - openless_core::BackendErrorCode::InvalidState, - "selectionResultInHistory", - )); + #[cfg(target_os = "windows")] + { + let captured = target.windows.as_ref()?; + Some(HostTargetIdentity { + process_id: captured.focused_process_id, + window_token: opaque_target_token("window", captured.foreground_window), + control_token: opaque_target_token("control", target.dictation_control.as_ref()?), + selection: target.dictation_position.lock().map(|(start, length)| HostSelectionRange { + start, length, unit: HostTextUnit::Native, + }), + }) } - let status = crate::insertion::TextInserter::new().insert_guarded( - text, - true, - shortcut, - expected_clipboard, - || { - selection_insertion_target_is_current(target) - && (source_text.is_empty() - || validate_selection_insertion_target(target, source_text) - .error_code() - .is_none()) - }, - ); - match status { - crate::types::InsertStatus::Inserted | crate::types::InsertStatus::PasteSent => { - #[cfg(target_os = "macos")] - if let Some(mut delivery) = delivery.take() { - delivery.record_posted(text, crate::types::MacosNewlineMode::ShiftReturn); - if matches!( - delivery.finish(), - crate::host_document::KeyboardDeliveryOutcome::Delivered - ) { - return Ok(openless_core::InsertOutcome::Inserted); - } - } - Ok(openless_core::InsertOutcome::PasteSent) - } - crate::types::InsertStatus::NotRequested => Err( - openless_core::BackendError::new( - openless_core::BackendErrorCode::InvalidState, - "selectionResultInHistory", - ) - .target_unavailable(), - ), - crate::types::InsertStatus::CopiedFallback => { - Ok(openless_core::InsertOutcome::CopiedFallback) + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + let _ = target; + None + } +} + +pub(crate) fn validate_target( + target: &SelectionInsertionTarget, +) -> openless_core::host_document::target::HostTargetValidation { + use openless_core::host_document::target::HostTargetValidation as Validation; + if target.cancelled.load(std::sync::atomic::Ordering::Acquire) { + return Validation::Cancelled; + } + if target_identity(target).is_none() { + return Validation::Unavailable; + } + if !native_input_target_is_current(target) { + return Validation::TargetChanged; + } + #[cfg(any(target_os = "macos", target_os = "windows"))] + { + let Some(captured) = *target.dictation_position.lock() else { + return Validation::Unavailable; + }; + let Some(current) = crate::host_document::focused_input_position() else { + return Validation::Unavailable; + }; + if !target_position::unchanged(Some(captured), Some(current)) { + return Validation::PositionChanged; } - _ => Err(openless_core::BackendError::new( - openless_core::BackendErrorCode::Platform, - "selectionResultInHistory", - )), + } + if native_input_target_is_current(target) { + Validation::Current + } else { + Validation::TargetChanged } } @@ -636,10 +721,61 @@ fn macos_target_is_current(target: &MacosSelectionTarget, pid: i32) -> bool { && target .dictation_element .as_ref() - .is_some_and(|element| element.is_current()) + .is_some_and(|element| { + element.is_current() && target.dictation_ax_window.as_ref() + .is_some_and(|window| { + element.belongs_to_window(window) && window.is_focused_window(pid) + }) + }) }) } +/// Host-private, non-Send borrow. Arc owners remain in SelectionInsertionTarget; +/// neither Core, IPC nor a P5 caller can replace the borrowed native objects. +#[cfg(target_os = "macos")] +pub(crate) struct FrozenMacosTarget<'a> { + owner: &'a SelectionInsertionTarget, + control: &'a macos_ax::FocusedElement, + window: &'a macos_ax::FocusedElement, + pid: i32, + window_id: u32, + range: Option<(u64, u64)>, + _thread_bound: std::marker::PhantomData>, +} + +#[cfg(target_os = "macos")] +impl FrozenMacosTarget<'_> { + /// SAFETY: refs are borrowed only for the synchronous owner callback. The + /// caller must not release, retain, return or store them outside that callback. + pub(crate) unsafe fn ax_objects(&self) -> (*mut std::ffi::c_void, *mut std::ffi::c_void) { + (self.control.raw(), self.window.raw()) + } + pub(crate) fn process_id(&self) -> i32 { self.pid } + pub(crate) fn window_id(&self) -> u32 { self.window_id } + pub(crate) fn range(&self) -> Option<(u64, u64)> { self.range } + pub(crate) fn is_current(&self) -> bool { native_input_target_is_current(self.owner) } +} + +/// Only host_document should expose operations over this borrow: its read seam +/// additionally enforces permissions/security and before/after identity fences. +#[cfg(target_os = "macos")] +pub(crate) fn borrow_frozen_macos_target( + target: &SelectionInsertionTarget, + operation: impl for<'a> FnOnce(&FrozenMacosTarget<'a>) -> Result, +) -> Result { + let captured = target.macos.as_ref().ok_or("selectionPolishTargetUnavailable")?; + let lease = FrozenMacosTarget { + owner: target, + control: captured.dictation_element.as_deref().ok_or("selectionPolishTargetUnavailable")?, + window: captured.dictation_ax_window.as_deref().ok_or("selectionPolishTargetUnavailable")?, + pid: captured.front_app_pid.ok_or("selectionPolishTargetUnavailable")?, + window_id: captured.dictation_window.ok_or("selectionPolishTargetUnavailable")?, + range: *target.dictation_position.lock(), + _thread_bound: std::marker::PhantomData, + }; + operation(&lease) +} + /// Whether the target snapshot is sufficient to start a Selection Polish /// request. On Windows, do not send selected text to the provider if we cannot /// later prove where it is safe to replace it. On macOS the frontmost-app @@ -690,7 +826,7 @@ pub(crate) fn selection_insertion_target_is_current(target: &SelectionInsertionT #[cfg(target_os = "macos")] let current_selection = read_selection_for_validation(); #[cfg(target_os = "windows")] - let current_selection = crate::host_document::read_qa_selection(); + let current_selection = crate::host_document::read_selection_full(); if target.dictation_selection.is_none() || target.dictation_selection != current_selection { return false; } @@ -698,6 +834,13 @@ pub(crate) fn selection_insertion_target_is_current(target: &SelectionInsertionT native_input_target_is_current(target) } +/// A successful SetValue may change the selection/caret. Its receipt must only +/// fence cancellation and the original process/window/control, not the old range. +#[cfg(target_os = "windows")] +pub(crate) fn selection_write_identity_is_current(target: &SelectionInsertionTarget) -> bool { + native_input_target_is_current(target) +} + /// Read-only identity for a nonactivating picker. Unlike insertion validation, /// this never compares selection text or clipboard contents. pub(crate) fn capture_capsule_menu_input_target() -> Option { @@ -718,9 +861,10 @@ fn native_input_target_is_current(target: &SelectionInsertionTarget) -> bool { return false; }; return capture_windows_selection_target().as_ref() == Some(&captured) - && (target.dictation_control.as_ref().is_some_and(|identity| { - crate::host_document::focused_input_identity().as_ref() == Some(identity) - })); + && target_position::same_control( + target.dictation_control.as_deref(), + crate::host_document::focused_input_identity().as_deref(), + ); } #[cfg(target_os = "macos")] @@ -761,7 +905,7 @@ pub(crate) fn validate_selection_insertion_target( return SelectionInsertionTargetValidation::TargetChanged; } - let current_selection = crate::host_document::read_qa_selection(); + let current_selection = crate::host_document::read_selection_full(); if !selection_text_matches(expected_selection, current_selection.as_deref()) { return SelectionInsertionTargetValidation::SelectionChanged; } @@ -979,6 +1123,16 @@ pub fn capture_selection_with_status() -> SelectionCaptureOutcome { fn capture_selection_with_status_diag() -> (SelectionCaptureOutcome, SelectionCaptureMissReason) { let source_app = current_front_app(); + #[cfg(target_os = "windows")] + if let Some(text) = crate::host_document::read_selection_full() { + return ( + SelectionCaptureOutcome { + selection: Some(SelectionContext { text, source_app, omits_middle: false }), + }, + SelectionCaptureMissReason::Ok, + ); + } + // 1. macOS AX direct read #[cfg(target_os = "macos")] if let Some(text) = macos_ax::read_selected_text() { @@ -1374,6 +1528,7 @@ mod macos_ax { extern "C" { fn AXUIElementCreateSystemWide() -> AxUiElementRef; fn AXUIElementCreateApplication(pid: i32) -> AxUiElementRef; + fn AXUIElementGetTypeID() -> usize; fn AXUIElementSetMessagingTimeout(element: AxUiElementRef, seconds: f32) -> AxError; fn AXUIElementGetPid(element: AxUiElementRef, pid: *mut i32) -> AxError; fn AXUIElementCopyAttributeValue( @@ -1392,6 +1547,7 @@ mod macos_ax { #[link(name = "CoreFoundation", kind = "framework")] extern "C" { fn CFEqual(left: CFTypeRef, right: CFTypeRef) -> u8; + fn CFHash(value: CFTypeRef) -> usize; fn CFRetain(value: CFTypeRef) -> CFTypeRef; fn CFGetTypeID(value: CFTypeRef) -> usize; fn CFStringGetTypeID() -> usize; @@ -1401,16 +1557,8 @@ mod macos_ax { cstr: *const c_char, encoding: u32, ) -> CFStringRef; - fn CFStringGetCStringPtr(s: CFStringRef, encoding: u32) -> *const c_char; - fn CFStringGetCString( - s: CFStringRef, - buffer: *mut c_char, - buffer_size: isize, - encoding: u32, - ) -> u8; fn CFStringGetLength(s: CFStringRef) -> isize; fn CFStringGetCharacters(s: CFStringRef, range: CfRange, buffer: *mut u16); - fn CFStringGetMaximumSizeForEncoding(length: isize, encoding: u32) -> isize; } const K_CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100; @@ -1427,6 +1575,33 @@ mod macos_ax { } } impl FocusedElement { + pub(super) fn raw(&self) -> *mut c_void { self.0 as *mut c_void } + pub(super) fn window(&self) -> Option> { + unsafe { + let value = element_attribute(self.0 as AxUiElementRef, b"AXWindow\0")?; + Some(std::sync::Arc::new(Self(value as usize))) + } + } + pub(super) fn belongs_to_window(&self, window: &Self) -> bool { + self.window().is_some_and(|current| current.same_as(window)) + } + pub(super) fn is_focused_window(&self, pid: i32) -> bool { + unsafe { + let application = AXUIElementCreateApplication(pid); + if application.is_null() { return false; } + AXUIElementSetMessagingTimeout(application, 0.2); + let focused = element_attribute(application, b"AXFocusedWindow\0"); + CFRelease(application as CFTypeRef); + focused.is_some_and(|focused| { + let same = CFEqual(self.0 as CFTypeRef, focused) != 0; + CFRelease(focused); + same + }) + } + } + pub(super) fn identity_hash(&self) -> usize { + unsafe { CFHash(self.0 as CFTypeRef) } + } pub(super) fn same_as(&self, other: &Self) -> bool { unsafe { CFEqual(self.0 as CFTypeRef, other.0 as CFTypeRef) != 0 } } @@ -1441,7 +1616,7 @@ mod macos_ax { let system = AXUIElementCreateSystemWide(); if system.is_null() { return None; } AXUIElementSetMessagingTimeout(system, 0.2); - let element = attribute(system, b"AXFocusedUIElement\0"); + let element = element_attribute(system, b"AXFocusedUIElement\0"); CFRelease(system as CFTypeRef); element.map(|element| std::sync::Arc::new(FocusedElement(element as usize))) } @@ -1451,11 +1626,15 @@ mod macos_ax { /// Returns None on failure (missing permission / no focus / control lacks the selection /// attribute). pub fn read_selected_text() -> Option { + if crate::unicode_keystroke::is_secure_input_enabled() { + return None; + } unsafe { let system = AXUIElementCreateSystemWide(); if system.is_null() { return None; } + AXUIElementSetMessagingTimeout(system, 0.2); // Note: the CFSTR macro is not available in Rust, so build the attribute key // temporarily with CFStringCreateWithCString. let focused_attr = @@ -1479,7 +1658,18 @@ mod macos_ax { let err = AXUIElementCopyAttributeValue(system, focused_attr, &mut focused); CFRelease(system as CFTypeRef); CFRelease(focused_attr); - if err != AX_ERROR_SUCCESS || focused.is_null() { + if err != AX_ERROR_SUCCESS || focused.is_null() + || CFGetTypeID(focused) != AXUIElementGetTypeID() + { + if !focused.is_null() { CFRelease(focused); } + CFRelease(selected_attr); + return None; + } + AXUIElementSetMessagingTimeout(focused as AxUiElementRef, 0.2); + if [b"AXRole\0".as_slice(), b"AXSubrole\0".as_slice()].iter().any(|name| { + string_attribute(focused as AxUiElementRef, *name).as_deref() == Some("AXSecureTextField") + }) { + CFRelease(focused); CFRelease(selected_attr); return None; } @@ -1496,7 +1686,11 @@ mod macos_ax { return None; } - let result = cfstring_to_rust(selected); + let result = if CFGetTypeID(selected) == CFStringGetTypeID() { + cfstring_to_rust(selected) + } else { + None + }; CFRelease(selected); result } @@ -1516,6 +1710,16 @@ mod macos_ax { None } } + unsafe fn element_attribute(element: AxUiElementRef, name: &'static [u8]) -> Option { + let value = attribute(element, name)?; + if CFGetTypeID(value) == AXUIElementGetTypeID() { + AXUIElementSetMessagingTimeout(value as AxUiElementRef, 0.2); + Some(value) + } else { + CFRelease(value); + None + } + } unsafe fn string_attribute(element: AxUiElementRef, name: &'static [u8]) -> Option { let value = attribute(element, name)?; let text = if CFGetTypeID(value) == CFStringGetTypeID() { @@ -1552,6 +1756,9 @@ mod macos_ax { } pub fn read_explicit_text(expected_pid: Option) -> Result, ()> { + if crate::unicode_keystroke::is_secure_input_enabled() { + return Ok(None); + } unsafe { let system = match expected_pid { Some(pid) => AXUIElementCreateApplication(pid), @@ -1560,8 +1767,8 @@ mod macos_ax { if system.is_null() { return Ok(None); } - let _timeout = expected_pid.map(|_| AXUIElementSetMessagingTimeout(system, 0.12)); - let focused = attribute(system, b"AXFocusedUIElement\0"); + let _ = AXUIElementSetMessagingTimeout(system, 0.12); + let focused = element_attribute(system, b"AXFocusedUIElement\0"); let Some(focused) = focused else { CFRelease(system as CFTypeRef); return Ok(None); @@ -1572,9 +1779,8 @@ mod macos_ax { || pid != expected }) || string_attribute(focused as AxUiElementRef, b"AXSubrole\0").as_deref() == Some("AXSecureTextField") - || (expected_pid.is_some() - && string_attribute(focused as AxUiElementRef, b"AXRole\0").as_deref() - == Some("AXSecureTextField")) + || string_attribute(focused as AxUiElementRef, b"AXRole\0").as_deref() + == Some("AXSecureTextField") { CFRelease(focused); CFRelease(system as CFTypeRef); @@ -1592,9 +1798,7 @@ mod macos_ax { }) { break; } - if expected_pid.is_some() { - let _ = AXUIElementSetMessagingTimeout(current as AxUiElementRef, 0.12); - } + let _ = AXUIElementSetMessagingTimeout(current as AxUiElementRef, 0.12); if let Some(value) = attribute(current as AxUiElementRef, b"AXSelectedText\0") { result = selected_string(value, expected_pid.is_some()) .map(|text| text.filter(|text| !text.trim().is_empty())); @@ -1627,7 +1831,7 @@ mod macos_ax { break; } } - let Some(parent) = attribute(current as AxUiElementRef, b"AXParent\0") else { + let Some(parent) = element_attribute(current as AxUiElementRef, b"AXParent\0") else { break; }; if parent == current { @@ -1666,29 +1870,14 @@ mod macos_ax { } unsafe fn cfstring_to_rust(s: CFStringRef) -> Option { - let direct = CFStringGetCStringPtr(s, K_CF_STRING_ENCODING_UTF8); - if !direct.is_null() { - let cstr = CStr::from_ptr(direct); - return cstr.to_str().ok().map(|s| s.to_string()); - } let length = CFStringGetLength(s); - if length <= 0 { - return Some(String::new()); - } - let max_bytes = CFStringGetMaximumSizeForEncoding(length, K_CF_STRING_ENCODING_UTF8) + 1; - let mut buf: Vec = vec![0; max_bytes as usize]; - let ok = CFStringGetCString( - s, - buf.as_mut_ptr() as *mut c_char, - max_bytes, - K_CF_STRING_ENCODING_UTF8, - ); - // CoreFoundation's Boolean is an unsigned byte in the SDK ABI. - if ok == 0 { + if length < 0 { return None; } - let cstr = CStr::from_ptr(buf.as_ptr() as *const c_char); - cstr.to_str().ok().map(|s| s.to_string()) + // Preserve embedded NULs as well as boundary whitespace. + let mut units = vec![0u16; length as usize]; + CFStringGetCharacters(s, CfRange { location: 0, length }, units.as_mut_ptr()); + String::from_utf16(&units).ok() } } diff --git a/openless-all/app/src-tauri/src/selection/bound_native.rs b/openless-all/app/src-tauri/src/selection/bound_native.rs new file mode 100644 index 000000000..cfc57e0c0 --- /dev/null +++ b/openless-all/app/src-tauri/src/selection/bound_native.rs @@ -0,0 +1,119 @@ +//! A native transaction operates only on the immutable objects in its binding. +//! Foreground checks can reject the operation, but can never supply its object. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TextRange { + pub start: u64, + pub length: u64, +} + +pub(crate) struct Binding { + pub control: C, + pub window: W, + pub range: TextRange, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Failure { + Unavailable, + TargetChanged, + SelectionChanged, + /// Submission has happened. Neither retries nor "nothing was written" are safe. + WriteUnconfirmed, +} + +impl Failure { + pub(crate) fn message(self) -> &'static str { + match self { + Self::Unavailable => "selectionPolishTargetUnavailable", + Self::TargetChanged => "selectionPolishTargetChanged", + Self::SelectionChanged => "selectionPolishSelectionChanged", + Self::WriteUnconfirmed => "selectionPolishWriteUnconfirmed", + } + } +} + +pub(crate) trait Native { + type Control; + type Window; + fn guard(&self, control: &Self::Control, window: &Self::Window) -> Result<(), Failure>; + fn selected_range(&self, control: &Self::Control) -> Result; + fn text(&self, control: &Self::Control, range: TextRange) -> Result; + fn writable(&self, control: &Self::Control) -> Result<(), Failure>; + fn submit(&self, control: &Self::Control, replacement: &str) -> Result<(), Failure>; +} + +fn verify( + native: &N, + binding: &Binding, + original: &str, +) -> Result<(), Failure> { + native.guard(&binding.control, &binding.window)?; + if native.selected_range(&binding.control)? != binding.range + || native.text(&binding.control, binding.range)? != original + { + return Err(Failure::SelectionChanged); + } + native.guard(&binding.control, &binding.window) +} + +pub(crate) fn replace( + native: &N, + binding: &Binding, + original: &str, + replacement: &str, +) -> Result<(), Failure> { + if original.is_empty() || binding.range.length == 0 { + return Err(Failure::Unavailable); + } + let length = + u64::try_from(replacement.encode_utf16().count()).map_err(|_| Failure::Unavailable)?; + let caret = binding + .range + .start + .checked_add(length) + .ok_or(Failure::Unavailable)?; + verify(native, binding, original)?; + native.writable(&binding.control)?; + verify(native, binding, original)?; + // From this point every failure has an unknown write outcome. Readback + // always addresses the frozen control, even if focus changed in submit(). + native + .submit(&binding.control, replacement) + .map_err(|_| Failure::WriteUnconfirmed)?; + let inserted = TextRange { + start: binding.range.start, + length, + }; + let observed = native + .text(&binding.control, inserted) + .map_err(|_| Failure::WriteUnconfirmed)?; + let observed_range = native + .selected_range(&binding.control) + .map_err(|_| Failure::WriteUnconfirmed)?; + if observed != replacement + || observed_range + != (TextRange { + start: caret, + length: 0, + }) + { + return Err(Failure::WriteUnconfirmed); + } + native + .guard(&binding.control, &binding.window) + .map_err(|_| Failure::WriteUnconfirmed) +} + +/// The decoder must not interpret an arbitrary CF object as an AXValue, nor an +/// AXValue of another kind as a CFRange. Native callers release ownership after this call. +pub(crate) fn checked_range( + is_ax_value: impl FnOnce() -> bool, + is_cf_range: impl FnOnce() -> bool, + decode: impl FnOnce() -> Option, +) -> Option { + if !is_ax_value() || !is_cf_range() { + return None; + } + decode() +} diff --git a/openless-all/app/src-tauri/src/selection/direct_delivery.rs b/openless-all/app/src-tauri/src/selection/direct_delivery.rs new file mode 100644 index 000000000..9d844550c --- /dev/null +++ b/openless-all/app/src-tauri/src/selection/direct_delivery.rs @@ -0,0 +1,42 @@ +//! Selection delivery never uses paste. A native failure is the only path that +//! may replace the protected original on the clipboard. + +use openless_core::{BackendError, BackendErrorCode, InsertOutcome}; + +pub(crate) fn native_result(result: Result<(), String>) -> Result { + result.map(|()| InsertOutcome::Inserted).map_err(|reason| { + BackendError::new( + if reason == "selectionPolishWriteUnconfirmed" { + BackendErrorCode::OutcomeUnknown + } else { + BackendErrorCode::Platform + }, + reason, + ) + }) +} + +pub(crate) fn fallback_result( + mut error: BackendError, + fallback: Result, +) -> Result { + if error.code == BackendErrorCode::OutcomeUnknown { + error.details = Some(serde_json::json!({ + "original_saved": true, + "result_copied": matches!(fallback, Ok(InsertOutcome::CopiedFallback)), + })); + Err(error) + } else { + fallback + } +} + +pub(crate) fn deliver( + direct: impl FnOnce() -> Result, + fallback: impl FnOnce(E) -> Result, +) -> Result { + match direct() { + Ok(outcome) => Ok(outcome), + Err(error) => fallback(error), + } +} diff --git a/openless-all/app/src-tauri/src/selection/recovery_notice.rs b/openless-all/app/src-tauri/src/selection/recovery_notice.rs index 7d57cc1d2..f38ecff2d 100644 --- a/openless-all/app/src-tauri/src/selection/recovery_notice.rs +++ b/openless-all/app/src-tauri/src/selection/recovery_notice.rs @@ -9,6 +9,32 @@ pub(crate) fn original_recovery_message( Some(localized_message(locale)) } +pub(crate) fn capacity_failure_message(locale: &str) -> &'static str { + match locale { + "zh-CN" => "服务无法完整处理全文,未替换;原文已保存在 App 的历史记录", + "zh-TW" => "服務無法完整處理全文,未替換;原文已儲存在 App 的歷史記錄", + "ja" => "全文を処理できませんでした。置換せず、原文をアプリの履歴に保存しました。", + "ko" => "전체 텍스트를 처리할 수 없어 바꾸지 않았습니다. 원문은 앱 기록에 저장했습니다.", + "es" => "El servicio no pudo procesar todo el texto. No se reemplazó; el original está en el historial.", + "fr" => "Le service n’a pas pu traiter le texte entier. Aucun remplacement ; l’original est dans l’historique.", + "de" => "Der Dienst konnte den vollständigen Text nicht verarbeiten. Nichts ersetzt; das Original ist im Verlauf.", + _ => "The service could not process the full text. Nothing replaced; the original is saved in app history.", + } +} + +pub(crate) fn uncertain_write_message(locale: &str) -> &'static str { + match locale { + "zh-CN" => "可能已写入,请先核对原输入框;原文和结果保留在历史记录", + "zh-TW" => "可能已寫入,請先核對原輸入框;原文和結果保留在歷史記錄", + "ja" => "入力済みの可能性があります。元の欄を確認してください。原文と結果は履歴にあります。", + "ko" => "이미 입력되었을 수 있습니다. 원래 입력란을 확인하세요. 원문과 결과는 기록에 있습니다.", + "es" => "Puede que el texto ya se haya insertado. Comprueba el campo original; ambos textos están en el historial.", + "fr" => "Le texte a peut-être été inséré. Vérifiez le champ d’origine ; les deux textes sont dans l’historique.", + "de" => "Der Text wurde möglicherweise eingefügt. Prüfe das ursprüngliche Feld; beide Texte sind im Verlauf.", + _ => "The text may already be inserted. Check the original field first; both texts are saved in history.", + } +} + fn localized_message(locale: &str) -> &'static str { match locale { "zh-CN" => "如果有掉词,可前往 App 的历史记录获取原文。", diff --git a/openless-all/app/src-tauri/src/selection/target_position.rs b/openless-all/app/src-tauri/src/selection/target_position.rs index e991fd916..92c53d1d8 100644 --- a/openless-all/app/src-tauri/src/selection/target_position.rs +++ b/openless-all/app/src-tauri/src/selection/target_position.rs @@ -2,6 +2,11 @@ pub(crate) fn unchanged(captured: Option<(u64, u64)>, current: Option<(u64, u64)>) -> bool { captured.is_some() && captured == current } +/// HWND equality is insufficient for two web/editor fields in one native window. +#[cfg(any(target_os = "windows", test))] +pub(crate) fn same_control(captured: Option<&[i32]>, current: Option<&[i32]>) -> bool { + captured.is_some_and(|identity| !identity.is_empty() && Some(identity) == current) +} pub(crate) fn advanced( captured: Option<(u64, u64)>, utf16_units: u64, @@ -14,11 +19,27 @@ pub(crate) fn advanced( mod tests { use super::*; #[test] + fn same_app_and_window_still_require_the_original_uia_control() { + let original = [42, 7, 101]; + let other_control_in_same_window = [42, 7, 102]; + assert!(same_control(Some(&original), Some(&original))); + assert!(!same_control( + Some(&original), + Some(&other_control_in_same_window) + )); + assert!(!same_control(Some(&original), None)); + assert!(!same_control(None, None)); + assert!(!same_control(Some(&[]), Some(&[]))); + } + #[test] fn a_new_capture_is_not_a_position_change() { assert!(unchanged(Some((4, 0)), Some((4, 0)))); assert!(!unchanged(Some((4, 0)), Some((5, 0)))); assert!(!unchanged(Some((4, 0)), Some((4, 2)))); - assert!(!unchanged(Some((4, 7)), Some((30, 7))), "an identical selected string at another occurrence is a different range"); + assert!( + !unchanged(Some((4, 7)), Some((30, 7))), + "an identical selected string at another occurrence is a different range" + ); assert!(!unchanged(None, None)); } } diff --git a/openless-all/app/src/features/history/History.tsx b/openless-all/app/src/features/history/History.tsx index f217590db..7f32537b1 100644 --- a/openless-all/app/src/features/history/History.tsx +++ b/openless-all/app/src/features/history/History.tsx @@ -15,6 +15,7 @@ import { useInteraction } from '../../ui/overlays/InteractionProvider'; import { HistoryDetail } from './HistoryDetail'; import { HistoryList } from './HistoryList'; import { errorMessage, styleLabelFor, useModeLabel } from './presentation'; +import { useHistoryOriginalSelection } from './useHistoryOriginalSelection'; const emptyHistory: DictationSession[] = []; @@ -134,6 +135,10 @@ export function History({ quickNotesOnly = false }: { quickNotesOnly?: boolean } rawTranscript.toLowerCase().includes(term) || finalText.toLowerCase().includes(term), ); }, [items, debouncedQuery]); + const originalSelection = useHistoryOriginalSelection( + quickNotesOnly ? emptyHistory : filtered, + notify, + ); const item = filtered.find((entry) => entry.id === selectedId) ?? filtered[0]; const styleLabel = (entry: DictationSession) => styleLabelFor(entry, allPacks, modeLabel); const clearableCount = items.filter((entry) => entry.source !== 'quick_note').length; @@ -205,6 +210,7 @@ export function History({ quickNotesOnly = false }: { quickNotesOnly?: boolean } loadError={loadError} refresh={refresh} styleLabel={styleLabel} + originals={originalSelection} /> )} {(!mobile || mobileDetailOpen) && diff --git a/openless-all/app/src/features/history/HistoryDetail.tsx b/openless-all/app/src/features/history/HistoryDetail.tsx index c86affc8b..72f81ef4d 100644 --- a/openless-all/app/src/features/history/HistoryDetail.tsx +++ b/openless-all/app/src/features/history/HistoryDetail.tsx @@ -17,6 +17,7 @@ import { AudioRecordingPlayer } from './AudioRecordingPlayer'; import { HistoryActionMenu } from './HistoryActionMenu'; import { RepolishPanel, HistoryResultCard } from './RepolishPanel'; import { formatDuration, formatStepDuration, TRUNCATED_PILL_STYLE } from './presentation'; +import { hasSelectionOriginal } from './selectionOriginals'; import { useHistoryEntryActions } from './useHistoryEntryActions'; import './history.css'; @@ -76,6 +77,8 @@ export function HistoryDetail({ const hasRaw = Boolean(item.rawTranscript); const activeView = hasRaw ? contentView : 'polished'; const showingRaw = activeView === 'raw'; + const copyingSelectionOriginal = showingRaw && hasSelectionOriginal(item); + const copyLabel = copyingSelectionOriginal ? t('history.copyOriginal') : t('common.copy'); const activeCopied = showingRaw ? justCopiedRaw : justCopied; const hasAsr = Boolean(item.asrProvider || item.asrMs != null); const hasPolish = Boolean(item.llmProvider || item.llmModel || item.polishMs != null); @@ -234,13 +237,17 @@ export function HistoryDetail({
void onCopy(showingRaw)} > - {activeCopied ? t('common.copied') : t('common.copy')} + {activeCopied ? t('common.copied') : copyLabel}
diff --git a/openless-all/app/src/features/history/HistoryList.tsx b/openless-all/app/src/features/history/HistoryList.tsx index 207a7a659..8af1565e2 100644 --- a/openless-all/app/src/features/history/HistoryList.tsx +++ b/openless-all/app/src/features/history/HistoryList.tsx @@ -1,5 +1,5 @@ import { TextField } from '../../ui/controls/TextField'; -import { memo, type RefObject } from 'react'; +import { memo, useId, type RefObject } from 'react'; import { useTranslation } from 'react-i18next'; import type { DictationSession } from '../../api/contracts'; import { formatHistoryTime } from '../../lib/localeFormat'; @@ -8,6 +8,7 @@ import { Button as Btn } from '../../ui/controls/Button'; import { Card } from '../../ui/layout/Card'; import { Pill } from '../../ui/controls/Pill'; import { formatDuration, historyTitle, TRUNCATED_PILL_STYLE } from './presentation'; +import type { useHistoryOriginalSelection } from './useHistoryOriginalSelection'; import './history.css'; interface Props { @@ -24,6 +25,7 @@ interface Props { loadError: string | null; refresh: (notify: boolean) => Promise; styleLabel: (session: DictationSession) => string; + originals: ReturnType; } export function HistoryList({ @@ -40,6 +42,7 @@ export function HistoryList({ loadError, refresh, styleLabel, + originals, }: Props) { const { t, i18n } = useTranslation(); const locale = i18n.resolvedLanguage || i18n.language; @@ -55,6 +58,39 @@ export function HistoryList({ placeholder={t('history.searchPlaceholder', { shortcut: searchShortcut })} aria-label={t('history.searchPlaceholder', { shortcut: searchShortcut })} /> + {(originals.active || originals.availableIds.size > 0) && ( +
+ + {originals.active ? t('common.cancel') : t('history.selectOriginals')} + + {originals.active && ( + <> + + {t('history.selectAllOriginals')} + + void originals.copy()} + > + {t('history.copyOriginals')} + + + )} +
+ )}
{loading && ( @@ -96,6 +132,13 @@ export function HistoryList({ styleLabel={styleLabel(session)} t={t} locale={locale} + toggleOriginal={ + originals.active && originals.availableIds.has(session.id) + ? originals.toggleEntry + : undefined + } + originalSelected={originals.selectedIds.has(session.id)} + copyingOriginals={originals.copying} /> ))}
@@ -111,6 +154,9 @@ const HistoryRow = memo(function HistoryRow({ styleLabel, t, locale, + toggleOriginal, + originalSelected, + copyingOriginals, }: { session: DictationSession; selected: boolean; @@ -118,10 +164,15 @@ const HistoryRow = memo(function HistoryRow({ styleLabel: string; t: ReturnType['t']; locale: string; + toggleOriginal?: (id: string) => void; + originalSelected: boolean; + copyingOriginals: boolean; }) { - return ( + const recordId = useId(); + const row = (
-); + ); + if (!toggleOriginal) return row; + return ( +
+ + {row} +
+ ); }); diff --git a/openless-all/app/src/features/history/history.css b/openless-all/app/src/features/history/history.css index 8e8d3bebe..8b79d13b3 100644 --- a/openless-all/app/src/features/history/history.css +++ b/openless-all/app/src/features/history/history.css @@ -53,6 +53,39 @@ font-size: 12px; } +.ol-history-original-actions { + display: flex; + flex: none; + flex-wrap: wrap; + gap: 6px; + min-width: 0; +} + +.ol-history-original-actions > button { + max-width: 100%; + overflow-wrap: anywhere; + text-align: start; + white-space: normal; +} + +.ol-history-selectable-record { + display: grid; + grid-template-columns: 2rem minmax(0, 1fr); +} + +.ol-history-original-check { + display: grid; + place-items: center; + cursor: pointer; +} + +.ol-history-original-check input { + inline-size: 1rem; + block-size: 1rem; + margin: 0; + accent-color: var(--ol-blue); +} + .ol-history-list-scroll { flex: 1; min-height: 0; @@ -329,6 +362,12 @@ white-space: nowrap; } +.ol-history-copy-btn--original { + max-width: 100%; + overflow-wrap: anywhere; + white-space: normal; +} + .ol-history-repolish-wrap { flex: 0 1 auto; max-height: 45%; diff --git a/openless-all/app/src/features/history/selectionOriginals.test.ts b/openless-all/app/src/features/history/selectionOriginals.test.ts new file mode 100644 index 000000000..50095bf73 --- /dev/null +++ b/openless-all/app/src/features/history/selectionOriginals.test.ts @@ -0,0 +1,74 @@ +import { hasSelectionOriginal, selectionOriginalClipboardText } from './selectionOriginals'; + +function expect(actual: unknown, expected: unknown) { + if (actual !== expected) { + throw new Error('Selection originals did not preserve record order or verbatim text'); + } +} + +const longOriginal = ` \n${'a'.repeat(25_000)}\nMIDDLE-SENTINEL\n${'b'.repeat(25_000)}\t \n`; +const polish = { + id: 'complete', + source: 'selection_polish', + rawTranscript: ' \tSecond original \n', + finalText: 'Edited result', +} as const; +const voiceEdit = { + id: 'voice-edit', + source: 'selection_voice_edit', + rawTranscript: ' \tVoice edit original\r\nsecond line \n', + finalText: 'Voice edit result', +} as const; +const missingVoiceEdit = { + id: 'missing-voice-edit', + source: 'selection_voice_edit', + rawTranscript: '', + finalText: 'Result with no saved original', +} as const; +const records = [ + { id: 'failed', source: 'selection_polish', rawTranscript: longOriginal, errorCode: 'failed' }, + { id: 'voice', source: 'voice', rawTranscript: 'Transcript' }, + { id: 'legacy', rawTranscript: 'Original of unknown source' }, + { id: 'missing', source: 'selection_polish', rawTranscript: '' }, + { id: 'quickNote', source: 'quick_note', rawTranscript: 'Quick note' }, + polish, + voiceEdit, + missingVoiceEdit, +] as const; + +expect(hasSelectionOriginal(records[0]), true); +expect(hasSelectionOriginal(records[1]), false); +expect(hasSelectionOriginal(records[2]), false); +expect(hasSelectionOriginal(records[3]), false); +expect(hasSelectionOriginal(voiceEdit), true); +expect(hasSelectionOriginal(missingVoiceEdit), false); +expect(selectionOriginalClipboardText(records, new Set(['failed'])), longOriginal); +expect(selectionOriginalClipboardText(records, new Set([voiceEdit.id])), voiceEdit.rawTranscript); +expect( + selectionOriginalClipboardText(records, new Set([polish.id, 'failed'])), + `${longOriginal}\n\n${polish.rawTranscript}`, +); +expect( + selectionOriginalClipboardText( + records, + new Set([ + voiceEdit.id, + missingVoiceEdit.id, + 'missing', + 'legacy', + 'voice', + 'quickNote', + 'failed', + 'deleted', + ]), + ), + `${longOriginal}\n\n${voiceEdit.rawTranscript}`, +); +expect(selectionOriginalClipboardText(records.slice(1), new Set(['failed'])), ''); +expect( + selectionOriginalClipboardText( + [{ id: 'spaces', source: 'selection_polish', rawTranscript: ' \t\n ' }], + new Set(['spaces']), + ), + ' \t\n ', +); diff --git a/openless-all/app/src/features/history/selectionOriginals.ts b/openless-all/app/src/features/history/selectionOriginals.ts new file mode 100644 index 000000000..fb3d9ae10 --- /dev/null +++ b/openless-all/app/src/features/history/selectionOriginals.ts @@ -0,0 +1,22 @@ +import type { DictationSession } from '../../api/contracts'; + +type SelectionHistoryEntry = Pick; + +export function hasSelectionOriginal(entry: Omit): boolean { + return ( + (entry.source === 'selection_polish' || entry.source === 'selection_voice_edit') && + typeof entry.rawTranscript === 'string' && + entry.rawTranscript.length > 0 + ); +} + +/** Preserve each original verbatim and combine them in displayed list order. */ +export function selectionOriginalClipboardText( + entries: readonly SelectionHistoryEntry[], + selectedIds: ReadonlySet, +): string { + return entries + .filter((entry) => selectedIds.has(entry.id) && hasSelectionOriginal(entry)) + .map((entry) => entry.rawTranscript) + .join('\n\n'); +} diff --git a/openless-all/app/src/features/history/useHistoryOriginalSelection.ts b/openless-all/app/src/features/history/useHistoryOriginalSelection.ts new file mode 100644 index 000000000..4ad9046b1 --- /dev/null +++ b/openless-all/app/src/features/history/useHistoryOriginalSelection.ts @@ -0,0 +1,75 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { DictationSession } from '../../api/contracts'; +import { copyTextToClipboard } from '../../api/files'; +import type { Interaction } from '../../api/interaction'; +import { errorMessage } from './presentation'; +import { hasSelectionOriginal, selectionOriginalClipboardText } from './selectionOriginals'; + +export function useHistoryOriginalSelection( + entries: DictationSession[], + notify: Interaction['notify'], +) { + const { t } = useTranslation(); + const [selection, setSelection] = useState | null>(null); + const [copying, setCopying] = useState(false); + const inFlight = useRef(false); + const availableIds = useMemo( + () => new Set(entries.filter(hasSelectionOriginal).map(({ id }) => id)), + [entries], + ); + const selectedIds = useMemo( + () => new Set(Array.from(selection ?? []).filter((id) => availableIds.has(id))), + [selection, availableIds], + ); + + useEffect(() => { + // Filtering or deleting a row must not leave its original selected off-screen. + setSelection((current) => { + if (!current?.size) return current; + const next = new Set(Array.from(current).filter((id) => availableIds.has(id))); + return current.size === next.size ? current : next; + }); + }, [availableIds]); + + const toggleEntry = useCallback((id: string) => { + setSelection((current) => { + if (!current) return current; + const next = new Set(current); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }, []); + + const copy = async () => { + if (inFlight.current || selectedIds.size === 0) return; + const text = selectionOriginalClipboardText(entries, selectedIds); + if (text.length === 0) return; + inFlight.current = true; + setCopying(true); + try { + await copyTextToClipboard(text); + notify({ state: 'saved', message: t('common.copied') }); + } catch (error) { + notify({ + state: 'failed', + message: t('history.copyFailed', { err: errorMessage(error) }), + }); + } finally { + inFlight.current = false; + setCopying(false); + } + }; + + return { + active: selection !== null, + availableIds, + selectedIds, + copying, + toggleMode: () => setSelection((current) => (current === null ? new Set() : null)), + selectAll: () => setSelection(new Set(availableIds)), + toggleEntry, + copy, + }; +} diff --git a/openless-all/app/src/i18n/de.ts b/openless-all/app/src/i18n/de.ts index 42a24dee8..92e0e564c 100644 --- a/openless-all/app/src/i18n/de.ts +++ b/openless-all/app/src/i18n/de.ts @@ -842,6 +842,10 @@ export const de: typeof zhCN = { showRaw: 'Rohtext anzeigen', hideRaw: 'Rohtext ausblenden', rawLabel: 'Rohtext', + copyOriginal: 'Original kopieren', + selectOriginals: 'Originale auswählen', + selectAllOriginals: 'Alle Originale auswählen', + copyOriginals: 'Ausgewählte Originale kopieren', rawEmpty: '(leer)', selectHint: 'Wähle links einen Eintrag aus, um die Details anzuzeigen.', recorded: 'Aufnahmedauer: {{duration}}', diff --git a/openless-all/app/src/i18n/en.ts b/openless-all/app/src/i18n/en.ts index 1997500eb..dd72f0e06 100644 --- a/openless-all/app/src/i18n/en.ts +++ b/openless-all/app/src/i18n/en.ts @@ -829,6 +829,10 @@ export const en: typeof zhCN = { showRaw: 'Show raw transcript', hideRaw: 'Hide raw transcript', rawLabel: 'Raw', + copyOriginal: 'Copy original', + selectOriginals: 'Select originals', + selectAllOriginals: 'Select all originals', + copyOriginals: 'Copy selected originals', rawEmpty: '(empty)', selectHint: 'Select an entry on the left to see details.', recorded: 'Recorded {{duration}}', diff --git a/openless-all/app/src/i18n/es.ts b/openless-all/app/src/i18n/es.ts index f710e30b2..c952e5b04 100644 --- a/openless-all/app/src/i18n/es.ts +++ b/openless-all/app/src/i18n/es.ts @@ -838,6 +838,10 @@ export const es: typeof zhCN = { showRaw: 'Mostrar transcripción original', hideRaw: 'Ocultar transcripción original', rawLabel: 'Original', + copyOriginal: 'Copiar original', + selectOriginals: 'Seleccionar originales', + selectAllOriginals: 'Seleccionar todos los originales', + copyOriginals: 'Copiar originales seleccionados', rawEmpty: '(vacío)', selectHint: 'Selecciona un registro de la izquierda para ver sus detalles.', recorded: 'Grabación: {{duration}}', diff --git a/openless-all/app/src/i18n/fr.ts b/openless-all/app/src/i18n/fr.ts index 2f34ed352..dca416b3e 100644 --- a/openless-all/app/src/i18n/fr.ts +++ b/openless-all/app/src/i18n/fr.ts @@ -849,6 +849,10 @@ export const fr: typeof zhCN = { showRaw: 'Afficher la transcription brute', hideRaw: 'Masquer la transcription brute', rawLabel: 'Brut', + copyOriginal: 'Copier l’original', + selectOriginals: 'Sélectionner les originaux', + selectAllOriginals: 'Sélectionner tous les originaux', + copyOriginals: 'Copier les originaux sélectionnés', rawEmpty: '(vide)', selectHint: 'Sélectionnez une entrée à gauche pour afficher ses détails.', recorded: 'Enregistrement : {{duration}}', diff --git a/openless-all/app/src/i18n/ja.ts b/openless-all/app/src/i18n/ja.ts index 9d1701964..9f5900605 100644 --- a/openless-all/app/src/i18n/ja.ts +++ b/openless-all/app/src/i18n/ja.ts @@ -816,6 +816,10 @@ export const ja: typeof zhCN = { showRaw: '原文を表示', hideRaw: '原文を隠す', rawLabel: '原文', + copyOriginal: '原文をコピー', + selectOriginals: '原文を選択', + selectAllOriginals: 'すべての原文を選択', + copyOriginals: '選択した原文をコピー', rawEmpty: '(空)', selectHint: '左側から 1 件選択して詳細を表示。', recorded: '録音 {{duration}}', diff --git a/openless-all/app/src/i18n/ko.ts b/openless-all/app/src/i18n/ko.ts index 9d715a387..b904928cc 100644 --- a/openless-all/app/src/i18n/ko.ts +++ b/openless-all/app/src/i18n/ko.ts @@ -809,6 +809,10 @@ export const ko: typeof zhCN = { showRaw: '원문 보기', hideRaw: '원문 숨기기', rawLabel: '원문', + copyOriginal: '원문 복사', + selectOriginals: '원문 선택', + selectAllOriginals: '모든 원문 선택', + copyOriginals: '선택한 원문 복사', rawEmpty: '(비어 있음)', selectHint: '왼쪽에서 하나를 선택하여 자세히 보기.', recorded: '녹음 {{duration}}', diff --git a/openless-all/app/src/i18n/zh-CN.ts b/openless-all/app/src/i18n/zh-CN.ts index 420b34c4e..5b350b538 100644 --- a/openless-all/app/src/i18n/zh-CN.ts +++ b/openless-all/app/src/i18n/zh-CN.ts @@ -788,6 +788,10 @@ export const zhCN = { showRaw: '查看原文', hideRaw: '隐藏原文', rawLabel: '原文', + copyOriginal: '复制原文', + selectOriginals: '选择原文', + selectAllOriginals: '全选原文', + copyOriginals: '复制所选原文', rawEmpty: '(空)', selectHint: '左侧选一条查看详情。', recorded: '录音 {{duration}}', diff --git a/openless-all/app/src/i18n/zh-TW.ts b/openless-all/app/src/i18n/zh-TW.ts index 0599e5bec..7eff6fdf1 100644 --- a/openless-all/app/src/i18n/zh-TW.ts +++ b/openless-all/app/src/i18n/zh-TW.ts @@ -789,6 +789,10 @@ export const zhTW: typeof zhCN = { showRaw: '查看原文', hideRaw: '隱藏原文', rawLabel: '原文', + copyOriginal: '複製原文', + selectOriginals: '選擇原文', + selectAllOriginals: '全選原文', + copyOriginals: '複製所選原文', rawEmpty: '(空)', selectHint: '左側選一條檢視詳情。', recorded: '錄音 {{duration}}',