diff --git a/openless-all/app/crates/openless-capsule/src/lib.rs b/openless-all/app/crates/openless-capsule/src/lib.rs index 17dc199e3..bf429667f 100644 --- a/openless-all/app/crates/openless-capsule/src/lib.rs +++ b/openless-all/app/crates/openless-capsule/src/lib.rs @@ -50,6 +50,12 @@ pub struct CapsulePopupState { /// Display name of the translation target, already localized by the host. #[serde(default)] pub translation_target: Option, + #[serde(default)] + pub skip_auto_style: bool, + #[serde(default)] + pub style_pack_id: Option, + #[serde(default)] + pub style_pack_name: Option, } /// Copy shared with the WebView capsule (`src/i18n/*.ts`, `capsule.*`). diff --git a/openless-all/app/crates/openless-core/src/api.rs b/openless-all/app/crates/openless-core/src/api.rs index e186e59e9..94d1e211f 100644 --- a/openless-all/app/crates/openless-core/src/api.rs +++ b/openless-all/app/crates/openless-core/src/api.rs @@ -22,6 +22,7 @@ use crate::dictation_context::{ DictationAudioSource, DictationContext, DictationOutputTarget, DictationProviderInvocations, DictationStartOptions, DictationStopOptions, }; +use crate::dictation_context::DictationStyleSelection; use crate::domains::{LessComputerRunRequest, LessComputerRunResult}; use crate::errors::{BackendError, BackendErrorCode}; use crate::events::{ @@ -76,6 +77,19 @@ pub struct DictationTranslationTarget { pub mutable: bool, } +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DictationStyleTarget { + pub session_id: SessionId, + pub selection: DictationStyleSelection, + pub skip_auto_style: bool, + pub style_pack_id: Option, + pub style_pack_name: Option, + pub polish_style_pack_id: Option, + pub available_styles: Vec, + pub mutable: bool, +} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct StartupSnapshot { @@ -1817,6 +1831,10 @@ struct MutableState { /// are still being captured. The accepted request is applied before finish /// by every stop entry; no Host latch survives into the next session. dictation_translation_requested: Option, + dictation_style_selection: Option, + /// Style intent not yet included in the snapshot handed to engine.start. + /// The current selection above also exists for an unchanged initial choice. + dictation_style_needs_update: bool, dictation_destination_changed: bool, credentials: CredentialsStatus, transcripts: HashMap, @@ -3659,6 +3677,8 @@ impl OpenLessBackend { dictation_context: None, dictation_start_output_target: None, dictation_translation_requested: None, + dictation_style_selection: None, + dictation_style_needs_update: false, dictation_destination_changed: false, credentials: CredentialsStatus::default(), transcripts: HashMap::new(), @@ -4482,8 +4502,7 @@ impl OpenLessBackend { .expect("pending audio capture lock poisoned") .insert(PendingAudioCaptureKey::VoiceActivation(generation), capture); let mut reservation = match self.reserve_dictation_session( - true, - DictationOutputTarget::ForegroundApp, + &DictationStartOptions::default(), Some(PendingAudioCaptureKey::VoiceActivation(generation)), ) { Ok(reservation) => reservation, @@ -5713,6 +5732,8 @@ impl OpenLessBackend { state.running = false; state.dictation = DictationStateSnapshot::default(); state.dictation_context = None; + state.dictation_style_selection = None; + state.dictation_style_needs_update = false; state.dictation_start_output_target = None; state.silence_monitor = None; state.transcripts.clear(); @@ -6221,8 +6242,7 @@ impl OpenLessBackend { let intent = hotkey.after_modifier_grace(press_id, self.snapshot().dictation.phase); let reservation = if matches!(intent, HotkeyIntent::Start { .. }) { Some(self.reserve_dictation_session( - options.start.insert_text, - options.start.output_target, + &options.start, Some(PendingAudioCaptureKey::Hotkey(press_id)), )) } else { @@ -6246,8 +6266,7 @@ impl OpenLessBackend { .expect("hotkey interpreter lock poisoned"); hotkey.start_is_current(press_id).then(|| { self.reserve_dictation_session( - options.start.insert_text, - options.start.output_target, + &options.start, Some(PendingAudioCaptureKey::Hotkey(press_id)), ) }) @@ -6483,6 +6502,80 @@ impl OpenLessBackend { }) } + /// Returns start-time styles, including installed packs. No picker choice + /// mutates global preferences or the original insertion target. + pub fn dictation_style_target(&self) -> Option { + let state = self.state.read().expect("backend state lock poisoned"); + Self::style_target(&state) + } + + fn style_target(state: &MutableState) -> Option { + let context = state.dictation_context.as_ref(); + let selection = state.dictation_style_selection.clone() + .or_else(|| context.map(|c| c.style_choices.selection.clone())).unwrap_or_default(); + Some(DictationStyleTarget { + session_id: state.dictation.session_id?, + skip_auto_style: selection != DictationStyleSelection::Automatic, + selection, + style_pack_id: context.map(|c| c.polish.style_pack_id.clone()), + style_pack_name: context.map(|c| c.polish.style_pack_name.clone()), + polish_style_pack_id: context.map(|c| c.style_choices.polish.id.clone()), + available_styles: context.map(|c| c.style_choices.available.clone()).unwrap_or_default(), + mutable: state.running && context.is_some() && matches!(state.dictation.phase, + DictationPhase::Starting | DictationPhase::Recording), + }) + } + + pub fn update_dictation_style( + &self, + session_id: SessionId, + selection: DictationStyleSelection, + ) -> Result { + self.change_dictation_style(session_id, Some(selection)) + } + + pub fn toggle_dictation_style_for_session( + &self, + session_id: SessionId, + ) -> Result { + self.change_dictation_style(session_id, None) + } + + fn change_dictation_style( + &self, + session_id: SessionId, + selection: Option, + ) -> Result { + let mut state = self.state.write().expect("backend state lock poisoned"); + ensure_running(&state)?; + if state.dictation.session_id != Some(session_id) + || !matches!(state.dictation.phase, DictationPhase::Starting | DictationPhase::Recording) { + return Err(BackendError::new(BackendErrorCode::InvalidState, + "style picker belongs to a recording that has ended")); + } + let previous = state.dictation_style_selection.clone() + .or_else(|| state.dictation_context.as_ref().map(|c| c.style_choices.selection.clone())) + .unwrap_or_default(); + let selection = selection.unwrap_or_else(|| if previous == DictationStyleSelection::Automatic { + DictationStyleSelection::SkipAuto + } else { DictationStyleSelection::Automatic }); + if let Some(context) = state.dictation_context.as_ref() { + let updated = Arc::new(context.with_style_selection(selection.clone())?); + state.dictation.style_pack_id = Some(updated.polish.style_pack_id.clone()); + state.dictation.style_pack_name = Some(updated.polish.style_pack_name.clone()); + state.dictation_context = Some(updated); + } else if matches!(&selection, DictationStyleSelection::StylePack { .. }) { + return Err(BackendError::new(BackendErrorCode::InvalidState, "recording style list is not ready")); + } + state.dictation.skip_auto_style = selection != DictationStyleSelection::Automatic; + state.dictation_style_selection = Some(selection); + state.dictation_style_needs_update = true; + let result = Self::style_target(&state).expect("checked active session"); + self.events.publish(Some(session_id), + BackendEventKind::DictationStateChanged(state.dictation.clone())); + Ok(result) + } + /// Explicitly retarget this recording and remember the choice. Ordinary settings /// edits still leave an in-flight recording's frozen context untouched. pub fn select_dictation_translation_target( @@ -8615,23 +8708,16 @@ impl OpenLessBackend { fn reserve_dictation_session( &self, - insert_text: bool, - output_target: DictationOutputTarget, + options: &DictationStartOptions, capture_key: Option, ) -> Result { - self.reserve_dictation_session_with_id( - SessionId::new(), - insert_text, - output_target, - capture_key, - ) + self.reserve_dictation_session_with_id(SessionId::new(), options, capture_key) } fn reserve_dictation_session_with_id( &self, session_id: SessionId, - insert_text: bool, - output_target: DictationOutputTarget, + options: &DictationStartOptions, capture_key: Option, ) -> Result { { @@ -8651,7 +8737,7 @@ impl OpenLessBackend { let starting_resources = self.voice_sessions.hold_resources(session_id)?; // Freeze the destination and its matching host-context reader before context/credential // awaits or feedback can change foreground focus. No native preparation happens yet. - let (inserter, host_context) = if insert_text { + let (inserter, host_context) = if options.insert_text { match self .deps .text_inserter @@ -8682,12 +8768,21 @@ impl OpenLessBackend { state.dictation = DictationStateSnapshot { phase: DictationPhase::Starting, session_id: Some(session_id), + skip_auto_style: options.skip_auto_style, ..DictationStateSnapshot::default() }; - state.dictation_start_output_target = Some(output_target); + state.dictation_start_output_target = Some(options.output_target); state.dictation_translation_requested = None; + // Publish the actual initial choice with Starting, before host or + // credential capture can suspend and a style gesture can overtake it. + state.dictation_style_selection = Some(if options.skip_auto_style { + DictationStyleSelection::SkipAuto + } else { + DictationStyleSelection::Automatic + }); + state.dictation_style_needs_update = false; state.dictation_destination_changed = false; - if output_target == DictationOutputTarget::ForegroundApp { + if options.output_target == DictationOutputTarget::ForegroundApp { self.main_dictation_trace.begin(session_id); } self.events.publish( @@ -8718,8 +8813,7 @@ impl OpenLessBackend { &self, options: DictationStartOptions, ) -> Result { - let reservation = - self.reserve_dictation_session(options.insert_text, options.output_target, None)?; + let reservation = self.reserve_dictation_session(&options, None)?; self.start_reserved_dictation(reservation, options).await } @@ -8737,7 +8831,7 @@ impl OpenLessBackend { ..Default::default() }; let reservation = - self.reserve_dictation_session_with_id(session_id, false, options.output_target, None)?; + self.reserve_dictation_session_with_id(session_id, &options, None)?; if !is_current() { let _ = self.cancel_dictation(Some(session_id)).await; return Err(VoiceCaptureLifecycle::cancelled_error()); @@ -8829,6 +8923,14 @@ impl OpenLessBackend { Some(requested) => Arc::new(context.with_translation_requested(requested)), None => context, }; + // An unchanged initial choice already belongs to the captured context; + // keep its prompt additions and fallback state intact. + let context = match state.dictation_style_selection.clone() { + Some(selection) if selection != context.style_choices.selection => { + Arc::new(context.with_style_selection(selection)?) + } + _ => context, + }; state.silence_monitor = context.recording.silence_after_ms.map(|silence_ms| { let started_at = std::time::Instant::now(); SilenceMonitor { @@ -8853,7 +8955,15 @@ impl OpenLessBackend { }; let context = Arc::new(context.with_capture_generation(capture_generation)); state.dictation.translation_active = context.polish.translation_active; + state.dictation.skip_auto_style = context.style_choices.selection != DictationStyleSelection::Automatic; + state.dictation.style_pack_id = Some(context.polish.style_pack_id.clone()); + state.dictation.style_pack_name = Some(context.polish.style_pack_name.clone()); state.dictation_context = Some(Arc::clone(&context)); + // This exact local snapshot will be passed to engine.start, even if + // insertion preparation or engine startup suspends. Consume only the + // changes it includes, under the same lock as style requests; later + // changes must survive through startup and be synchronized at stop. + state.dictation_style_needs_update = false; state.dictation_start_output_target = None; context }; @@ -9215,6 +9325,7 @@ impl OpenLessBackend { }; let context_changed = std::mem::take(&mut state.dictation_destination_changed) + | std::mem::take(&mut state.dictation_style_needs_update) || state.dictation_translation_requested.take().is_some() || state.dictation_context.as_ref().is_some_and(|previous| { previous.polish.translation_active @@ -9351,6 +9462,8 @@ impl OpenLessBackend { }, ); state.dictation_context = None; + state.dictation_style_selection = None; + state.dictation_style_needs_update = false; state.dictation_start_output_target = None; state.silence_monitor = None; hotkey.submitted(); @@ -10037,6 +10150,8 @@ impl OpenLessBackend { } state.dictation = DictationStateSnapshot::default(); state.dictation_context = None; + state.dictation_style_selection = None; + state.dictation_style_needs_update = false; state.dictation_start_output_target = None; state.silence_monitor = None; state.transcripts.remove(&session_id); @@ -10373,6 +10488,8 @@ impl OpenLessBackend { ); state.dictation = DictationStateSnapshot::default(); state.dictation_context = None; + state.dictation_style_selection = None; + state.dictation_style_needs_update = false; state.dictation_start_output_target = None; state.silence_monitor = None; state.transcripts.remove(&active); @@ -10476,9 +10593,9 @@ impl OpenLessBackend { assigned_ids.clear(); } let active_id = explicit_style.unwrap_or(&preferences.active_style_pack_id); - let style_pack = self - .style_packs - .get_for_dictation(assigned_ids.iter().map(String::as_str), active_id)?; + let (style_pack, polish_style, available_styles) = self.style_packs.capture_dictation_styles( + assigned_ids.iter().map(String::as_str), active_id, &preferences.active_style_pack_id, + )?; let mut captured_options = options.clone(); if !preferences.cursor_context_enabled { // This switch controls document text, including text supplied by @@ -10553,6 +10670,12 @@ impl OpenLessBackend { recent_history, options, ); + context.style_choices.automatic = style_pack; + context.style_choices.polish = polish_style; + context.style_choices.available = available_styles; + if options.skip_auto_style { + context = context.with_style_selection(DictationStyleSelection::SkipAuto)?; + } if foreground_output { context.polish.input_scene_prefix = Some(input_scene_prefix); } @@ -10940,7 +11063,10 @@ mod tests { assert!(backend.snapshot().dictation.session_id.is_none()); assert_eq!(discarded.load(Ordering::SeqCst), 1); let next = backend - .reserve_dictation_session(false, DictationOutputTarget::ForegroundApp, None) + .reserve_dictation_session( + &DictationStartOptions { insert_text: false, ..Default::default() }, + None, + ) .unwrap(); backend.reset_dictation_session(next.session_id); } @@ -16508,7 +16634,10 @@ mod tests { insert_text: bool, ) -> SessionId { let reservation = backend - .reserve_dictation_session(insert_text, DictationOutputTarget::ForegroundApp, None) + .reserve_dictation_session( + &DictationStartOptions { insert_text, ..Default::default() }, + None, + ) .unwrap(); let id = reservation.session_id; *backend.voice_activation_session.lock().unwrap() = @@ -20748,7 +20877,7 @@ mod tests { ..Default::default() }; let reservation = backend - .reserve_dictation_session(false, options.output_target, None) + .reserve_dictation_session(&options, None) .unwrap(); let session_id = reservation.session_id; let mut stopping = Some(Box::pin(backend.stop_dictation())); diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs index 0495d35b3..61191f8d7 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/registry.rs @@ -522,6 +522,20 @@ pub const PREFERENCE_FIELDS: &[PreferenceField] = &[ shape: PreferenceShape::Object, reason: "device_bound", }, + PreferenceField { + rust_name: "skip_auto_style_hotkey", + key: "skipAutoStyleHotkey", + class: PreferenceClass::DeviceProfile, + shape: PreferenceShape::Object, + reason: "device_bound", + }, + PreferenceField { + rust_name: "skip_auto_style_picker_enabled", + key: "skipAutoStylePickerEnabled", + class: PreferenceClass::Portable, + shape: PreferenceShape::Boolean, + reason: "portable_setting", + }, PreferenceField { rust_name: "switch_style_hotkey", key: "switchStyleHotkey", diff --git a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs index cf5e2667c..db7910ba2 100644 --- a/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs +++ b/openless-all/app/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs @@ -119,6 +119,24 @@ fn all_current_preference_fields_have_an_explicit_registration() { assert_eq!(registered.len(), registry::PREFERENCE_FIELDS.len()); } +#[test] +fn skip_auto_style_e2ee_device_profile_accepts_legacy_and_new_fields() { + let mut old = sample().documents().clone(); + let profile = old.documents.iter_mut().find(|doc| doc.kind == DocumentKind::DeviceProfile).unwrap(); + profile.value["preferences"].as_object_mut().unwrap().remove("skipAutoStyleHotkey"); + profile.value["preferences"].as_object_mut().unwrap().remove("skipAutoStylePickerEnabled"); + validate_sync_documents(old, Revision::new(3)).unwrap(); + let mut data = snapshot(); + data.preferences.expose_mut()["skipAutoStyleHotkey"] = json!({"primary":"","modifiers":[]}); + data.preferences.expose_mut()["skipAutoStylePickerEnabled"] = json!(true); + let exported = export_snapshot(data).unwrap(); + let documents = &exported.documents.documents().documents; + let profile = documents.iter().find(|doc| doc.kind == DocumentKind::DeviceProfile).unwrap(); + assert_eq!(profile.value["preferences"]["skipAutoStyleHotkey"]["primary"], ""); + let picker = documents.iter().find(|doc| doc.kind == DocumentKind::Preferences && doc.id == "skipAutoStylePickerEnabled").unwrap(); + assert_eq!(picker.value, true); +} + #[test] fn new_optional_preference_distinguishes_untouched_from_explicit_default() { let untouched = crate::shared_types::UserPreferences::default(); diff --git a/openless-all/app/crates/openless-core/src/dictation_context.rs b/openless-all/app/crates/openless-core/src/dictation_context.rs index 0bdb0165d..9d5d7168b 100644 --- a/openless-all/app/crates/openless-core/src/dictation_context.rs +++ b/openless-all/app/crates/openless-core/src/dictation_context.rs @@ -44,6 +44,7 @@ pub enum DictationOutputTarget { #[derive(Debug, Clone, PartialEq, Eq)] pub struct DictationStartOptions { pub translation_requested: bool, + pub skip_auto_style: bool, pub audio_source: DictationAudioSource, pub insert_text: bool, pub output_target: DictationOutputTarget, @@ -56,6 +57,7 @@ impl Default for DictationStartOptions { fn default() -> Self { Self { translation_requested: false, + skip_auto_style: false, audio_source: DictationAudioSource::Microphone, insert_text: true, output_target: DictationOutputTarget::ForegroundApp, @@ -125,6 +127,7 @@ impl DictationProviderInvocations { pub struct DictationPolishContext { pub mode: PolishMode, pub style_pack_id: String, + pub style_pack_name: String, pub style_system_prompt: String, /// Frozen target metadata, composed only at request time; never part of Raw identity. pub input_scene_prefix: Option, @@ -206,6 +209,9 @@ pub struct RecordingPlan { #[derive(Debug, Clone, PartialEq, Eq)] pub struct DictationContext { + /// Owned start-time alternatives. Later preference, routing and pack edits + /// cannot change either side of the toggle or a submitted parallel segment. + pub(crate) style_choices: DictationStyleChoices, pub(crate) input_app: Option, /// Annotated built-in Raw prompt, captured before any later prompt changes. pub(crate) raw_passthrough_prompt: Option, @@ -237,6 +243,27 @@ pub struct DictationContext { pub insertion: DictationInsertionContext, } +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "mode", rename_all = "camelCase")] +pub enum DictationStyleSelection { + #[default] + Automatic, + SkipAuto, + StylePack { + #[serde(rename = "stylePackId")] + style_pack_id: String, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct DictationStyleChoices { + pub automatic: StylePack, + pub polish: StylePack, + pub available: Vec, + pub automatic_prior_turns: Vec, + pub selection: DictationStyleSelection, +} + impl Default for DictationContext { fn default() -> Self { let preferences = UserPreferences::default(); @@ -342,7 +369,15 @@ impl DictationContext { let debug_keep_processed = preferences.record_audio_for_debug && (preferences.debug_archive_processed || debug_both_off); let debug_keep_raw = preferences.record_audio_for_debug && preferences.debug_archive_raw; + let automatic_prior_turns = prior_turns.clone(); Self { + style_choices: DictationStyleChoices { + automatic: style_pack.clone(), + polish: style_pack.clone(), + available: vec![style_pack.clone()], + automatic_prior_turns, + selection: DictationStyleSelection::Automatic, + }, input_app: None, audio_source: options.audio_source, output_target: options.output_target, @@ -405,6 +440,7 @@ impl DictationContext { input_scene_prefix: None, mode: style_pack.base_mode, style_pack_id: style_pack.id.clone(), + style_pack_name: style_pack.name.clone(), style_system_prompt: crate::style_packs::dictation_style_prompt(style_pack), hotwords, working_languages: preferences.working_languages.clone(), @@ -473,6 +509,36 @@ impl DictationContext { next } + pub(crate) fn with_style_selection( + &self, + selection: DictationStyleSelection, + ) -> Result { + let pack = match &selection { + DictationStyleSelection::Automatic => &self.style_choices.automatic, + DictationStyleSelection::SkipAuto => &self.style_choices.polish, + DictationStyleSelection::StylePack { style_pack_id } => self.style_choices.available + .iter().find(|pack| pack.id == *style_pack_id && pack.enabled) + .ok_or_else(|| crate::BackendError::new(crate::BackendErrorCode::InvalidArgument, + "style is not available in this recording"))?, + }; + let mut updated = self.clone(); + updated.style_choices.selection = selection; + updated.polish.mode = pack.base_mode; + updated.polish.style_pack_id = pack.id.clone(); + updated.polish.style_pack_name = pack.name.clone(); + updated.polish.style_system_prompt = crate::style_packs::dictation_style_prompt(pack); + // History turns belong to the original style. Never feed them into + // a newly selected style or re-read mutable history mid-recording. + updated.polish.prior_turns = if pack.id == self.style_choices.automatic.id { + self.style_choices.automatic_prior_turns.clone() + } else { Vec::new() }; + if updated.unconfigured_llm_raw.is_some() { + updated.unconfigured_llm_raw = Some((updated.polish.mode, updated.polish.style_system_prompt.clone())); + } + updated.restore_or_apply_unconfigured_llm_raw(); + Ok(updated) + } + pub fn with_output_target(&self, target: DictationOutputTarget) -> Self { let mut next = self.clone(); next.output_target = target; diff --git a/openless-all/app/crates/openless-core/src/lib.rs b/openless-all/app/crates/openless-core/src/lib.rs index 1e2a7c38a..f45aa57e3 100644 --- a/openless-all/app/crates/openless-core/src/lib.rs +++ b/openless-all/app/crates/openless-core/src/lib.rs @@ -240,7 +240,7 @@ pub mod contract { pub use activity::{ActivityDay, ActivityStore, DayStats}; pub use api::{ AsrRoute, AsrUsage, BackendRepositories, BackendSnapshot, CliDispatchOutcome, - DictationHotkeyDispatchOptions, DictationHotkeyEdge, DictationTranslationTarget, + DictationHotkeyDispatchOptions, DictationHotkeyEdge, DictationTranslationTarget, DictationStyleTarget, LessComputerHotkeyAction, LessComputerVoiceFinish, LessComputerVoiceOptions, LessComputerVoiceSession, OpenLessBackend, QaVoiceCaptureResult, QaVoiceCaptureSession, StartupSnapshot, VoiceTranscriptionSession, @@ -275,7 +275,7 @@ pub use credentials::{ pub use dictation_context::{ build_asr_prompt, eligible_polish_context_turns, DictationAudioSource, DictationContext, DictationInsertionContext, DictationOutputTarget, DictationPolishContext, - DictationStartOptions, DictationStopOptions, PolishHistoryTurn, ProviderInvocation, + DictationStartOptions, DictationStopOptions, DictationStyleSelection, PolishHistoryTurn, ProviderInvocation, RecordingPlan, ASR_PROMPT_CHAR_BUDGET, }; pub use dictation_engine::{PipelineDictationEngine, PolishFailurePolicy}; diff --git a/openless-all/app/crates/openless-core/src/ports.rs b/openless-all/app/crates/openless-core/src/ports.rs index 51192e2f5..1205e237f 100644 --- a/openless-all/app/crates/openless-core/src/ports.rs +++ b/openless-all/app/crates/openless-core/src/ports.rs @@ -371,8 +371,8 @@ pub trait DictationEngine: Send + Sync + 'static { } /// Replace the immutable session snapshot before finalization when a host - /// action (currently Android's finish-and-translate gesture) is only known - /// at stop time. Implementations that retain the context must override this + /// action (translation, destination or output-style selection) changes the + /// final polish intent. Implementations that retain the context must override this /// method; settings are never re-read here. fn update_context( &self, diff --git a/openless-all/app/crates/openless-core/src/settings.rs b/openless-all/app/crates/openless-core/src/settings.rs index 51600f8d8..6d9ed12c8 100644 --- a/openless-all/app/crates/openless-core/src/settings.rs +++ b/openless-all/app/crates/openless-core/src/settings.rs @@ -64,6 +64,8 @@ pub struct HotkeyRuntimeTarget { pub qa_companion_key: String, pub quick_note: Option, pub translation: ShortcutBinding, + #[serde(default = "crate::shared_types::default_skip_auto_style_hotkey")] + pub skip_auto_style: ShortcutBinding, pub switch_style: Option, pub open_app: Option, pub selection_polish: Option, @@ -85,6 +87,7 @@ impl From<&UserPreferences> for HotkeyRuntimeTarget { qa_companion_key: preferences.qa_companion_key.clone(), quick_note: preferences.quick_note_hotkey.clone(), translation: preferences.translation_hotkey.clone(), + skip_auto_style: preferences.skip_auto_style_hotkey.clone(), switch_style: preferences.switch_style_hotkey.clone(), open_app: preferences.open_app_hotkey.clone(), selection_polish: preferences.selection_polish_hotkey.clone(), diff --git a/openless-all/app/crates/openless-core/src/shared_types.rs b/openless-all/app/crates/openless-core/src/shared_types.rs index b5f1fc683..3af0c7fee 100644 --- a/openless-all/app/crates/openless-core/src/shared_types.rs +++ b/openless-all/app/crates/openless-core/src/shared_types.rs @@ -646,6 +646,10 @@ pub struct UserPreferences { pub custom_combo_hotkey: Option, #[serde(default = "default_translation_hotkey")] pub translation_hotkey: ShortcutBinding, + #[serde(default = "default_skip_auto_style_hotkey")] + pub skip_auto_style_hotkey: ShortcutBinding, + #[serde(default)] + pub skip_auto_style_picker_enabled: bool, /// "Switch style" global hotkey. `None` = disabled (no global key /// registered); `Some(...)` = registered. Defaults to `Some(default key)` /// — zero behavior change for existing users, only newly clearable @@ -1187,6 +1191,9 @@ struct UserPreferencesWire { qa_save_history: bool, custom_combo_hotkey: Option, translation_hotkey: Option, + skip_auto_style_hotkey: Option, + #[serde(default)] + skip_auto_style_picker_enabled: bool, switch_style_hotkey: Option, open_app_hotkey: Option, #[serde(default)] @@ -1442,6 +1449,8 @@ impl Default for UserPreferencesWire { qa_save_history: prefs.qa_save_history, custom_combo_hotkey: prefs.custom_combo_hotkey, translation_hotkey: None, + skip_auto_style_hotkey: None, + skip_auto_style_picker_enabled: prefs.skip_auto_style_picker_enabled, // Carry the default key (Some) so a missing field still means enabled; None exclusively means "user disabled". switch_style_hotkey: prefs.switch_style_hotkey, open_app_hotkey: prefs.open_app_hotkey, @@ -1594,6 +1603,28 @@ impl<'de> Deserialize<'de> for UserPreferences { right: AndroidOverlayGestureAction::None, }); + let skip_auto_style_hotkey = wire.skip_auto_style_hotkey.clone().unwrap_or_else(|| { + let proposed = default_skip_auto_style_hotkey(); + // A newly introduced default must never steal an existing user's key. + let occupied = [ + Some(&dictation_hotkey), wire.translation_hotkey.as_ref(), wire.qa_hotkey.as_ref(), + wire.switch_style_hotkey.as_ref(), wire.open_app_hotkey.as_ref(), + wire.quick_note_hotkey.as_ref(), wire.coding_agent_voice_hotkey.as_ref(), + wire.coding_agent_panel_hotkey.as_ref(), wire.coding_agent_quick_hotkey.as_ref(), + selection_polish_hotkey.as_ref(), + ].into_iter().flatten().any(|other| crate::shortcut_types::bindings_overlap(&proposed, other)); + if occupied { ShortcutBinding::unassigned() } else { proposed } + }); + // Older previews assigned bare Alt on Windows. Until a paired, + // menu-safe native implementation is verified, migrate modifier taps + // to unassigned; custom global combinations remain available. + #[cfg(target_os = "windows")] + let skip_auto_style_hotkey = + if crate::shortcut_types::legacy_modifier_trigger(&skip_auto_style_hotkey).is_some() { + ShortcutBinding::unassigned() + } else { + skip_auto_style_hotkey + }; Ok(Self { hotkey: wire.hotkey, dictation_hotkey, @@ -1702,6 +1733,8 @@ impl<'de> Deserialize<'de> for UserPreferences { translation_hotkey: wire .translation_hotkey .unwrap_or_else(default_translation_hotkey), + skip_auto_style_hotkey, + skip_auto_style_picker_enabled: wire.skip_auto_style_picker_enabled, // Pass the Option through: None = user disabled — no // unwrap_or_else collapse back to the default key (the root // cause of #576 "can't disable"). A missing field falls to the @@ -1972,6 +2005,16 @@ fn default_translation_hotkey() -> ShortcutBinding { } } +pub(crate) fn default_skip_auto_style_hotkey() -> ShortcutBinding { + if cfg!(target_os = "windows") { + return ShortcutBinding::unassigned(); + } + ShortcutBinding { + primary: if cfg!(target_os = "macos") { "LeftCommand" } else { "LeftAlt" }.into(), + modifiers: Vec::new(), + } +} + fn default_switch_style_hotkey() -> Option { Some(ShortcutBinding { primary: "S".into(), @@ -2102,6 +2145,8 @@ impl Default for UserPreferences { qa_save_history: false, custom_combo_hotkey: None, translation_hotkey: default_translation_hotkey(), + skip_auto_style_hotkey: default_skip_auto_style_hotkey(), + skip_auto_style_picker_enabled: false, switch_style_hotkey: default_switch_style_hotkey(), open_app_hotkey: default_open_app_hotkey(), style_pack_hotkeys: Vec::new(), @@ -2938,6 +2983,12 @@ pub struct CapsulePayload { /// user immediately knows this output goes through the translation /// pipeline. See issue #4. pub translation: bool, + #[serde(default)] + pub skip_auto_style: bool, + #[serde(default)] + pub style_pack_id: Option, + #[serde(default)] + pub style_pack_name: Option, /// Whether this is a Less Computer (voice agent controlling the /// computer) session. The frontend switches the processing label from /// "thinking" to "using" — the agent is operating the computer, not diff --git a/openless-all/app/crates/openless-core/src/shortcut_types.rs b/openless-all/app/crates/openless-core/src/shortcut_types.rs index 6a3248207..e3c7e2288 100644 --- a/openless-all/app/crates/openless-core/src/shortcut_types.rs +++ b/openless-all/app/crates/openless-core/src/shortcut_types.rs @@ -177,6 +177,11 @@ pub fn bindings_overlap(left: &ShortcutBinding, right: &ShortcutBinding) -> bool } let left_legacy = legacy_modifier_trigger(left); let right_legacy = legacy_modifier_trigger(right); + let shift = |binding: &ShortcutBinding| binding.modifiers.is_empty() && binding.primary.eq_ignore_ascii_case("shift"); + if (shift(left) && matches!(right_legacy, Some(HotkeyTrigger::LeftShift | HotkeyTrigger::RightShift))) + || (shift(right) && matches!(left_legacy, Some(HotkeyTrigger::LeftShift | HotkeyTrigger::RightShift))) { + return true; + } match (left_legacy, right_legacy) { (Some(left), Some(right)) => left == right, (Some(_), None) | (None, Some(_)) => false, @@ -567,6 +572,7 @@ fn reject_style_pack_hotkey_overlap_with_others( binding: &ShortcutBinding, preferences: &UserPreferences, ) -> Result<(), String> { + reject_overlap(binding, &preferences.skip_auto_style_hotkey, "风格快捷键不能和跳过自动风格快捷键相同")?; reject_overlap( binding, &preferences.dictation_hotkey, @@ -653,6 +659,7 @@ pub fn reconcile_hotkey_collisions( #[derive(Clone, Copy, PartialEq, Eq)] enum NonCoreHotkey { Translation, + SkipAutoStyle, Qa, SwitchStyle, OpenApp, @@ -665,6 +672,7 @@ pub fn reconcile_hotkey_collisions( fn get(self, preferences: &UserPreferences) -> Option { match self { Self::Translation => Some(preferences.translation_hotkey.clone()), + Self::SkipAutoStyle => Some(preferences.skip_auto_style_hotkey.clone()), Self::Qa => preferences.qa_hotkey.clone(), Self::SwitchStyle => preferences.switch_style_hotkey.clone(), Self::OpenApp => preferences.open_app_hotkey.clone(), @@ -681,6 +689,8 @@ pub fn reconcile_hotkey_collisions( preferences.translation_hotkey = value; } } + Self::SkipAutoStyle => preferences.skip_auto_style_hotkey = + value.unwrap_or_else(ShortcutBinding::unassigned), Self::Qa => preferences.qa_hotkey = value, Self::SwitchStyle => preferences.switch_style_hotkey = value, Self::OpenApp => preferences.open_app_hotkey = value, @@ -695,6 +705,7 @@ pub fn reconcile_hotkey_collisions( return false; } match self { + Self::SkipAutoStyle => validate_skip_auto_style_hotkey(binding).is_ok(), Self::SelectionPolish => { validate_shortcut_binding(binding).is_ok() && reject_bare_shift_dictation_shortcut(binding).is_ok() @@ -704,7 +715,7 @@ pub fn reconcile_hotkey_collisions( } } - const ORDER: [NonCoreHotkey; 7] = [ + const ORDER: [NonCoreHotkey; 8] = [ NonCoreHotkey::Translation, NonCoreHotkey::Qa, NonCoreHotkey::SwitchStyle, @@ -712,6 +723,7 @@ pub fn reconcile_hotkey_collisions( NonCoreHotkey::QuickNote, NonCoreHotkey::SelectionPolish, NonCoreHotkey::LessComputer, + NonCoreHotkey::SkipAutoStyle, ]; let mut higher = vec![preferences.dictation_hotkey.clone()]; let mut adjusted = 0; @@ -719,13 +731,19 @@ pub fn reconcile_hotkey_collisions( let Some(current) = key.get(preferences) else { continue; }; - let collides = higher.iter().any(|held| bindings_overlap(held, ¤t)); + let reserved = if key == NonCoreHotkey::SkipAutoStyle { + vec![preferences.coding_agent_panel_hotkey.as_ref(), preferences.coding_agent_quick_hotkey.as_ref()] + } else { Vec::new() }; + let conflicts = |candidate: &ShortcutBinding| higher.iter() + .chain(reserved.iter().filter_map(|binding| *binding)) + .any(|held| bindings_overlap(held, candidate)); + let collides = conflicts(¤t); if !collides && key.binding_is_valid(¤t) { higher.push(current); continue; } let fallback = key.get(previous).filter(|candidate| { - !higher.iter().any(|held| bindings_overlap(held, candidate)) + !conflicts(candidate) && key.binding_is_valid(candidate) }); let resolved = if key == NonCoreHotkey::Translation && fallback.is_none() { @@ -776,6 +794,22 @@ pub fn reconcile_hotkey_collisions( } pub fn reject_hotkey_collisions(preferences: &UserPreferences) -> Result<(), String> { + validate_skip_auto_style_hotkey(&preferences.skip_auto_style_hotkey)?; + let skip = &preferences.skip_auto_style_hotkey; + for other in [ + Some(&preferences.dictation_hotkey), + Some(&preferences.translation_hotkey), + preferences.qa_hotkey.as_ref(), + preferences.switch_style_hotkey.as_ref(), + preferences.open_app_hotkey.as_ref(), + preferences.coding_agent_voice_hotkey.as_ref(), + preferences.coding_agent_panel_hotkey.as_ref(), + preferences.coding_agent_quick_hotkey.as_ref(), + preferences.quick_note_hotkey.as_ref(), + preferences.selection_polish_hotkey.as_ref(), + ].into_iter().flatten() { + reject_overlap(skip, other, "跳过自动风格快捷键不能和其他快捷键相同")?; + } reject_non_dictation_side_specific_shortcuts(preferences)?; let switch_style = preferences.switch_style_hotkey.as_ref(); let open_app = preferences.open_app_hotkey.as_ref(); @@ -888,6 +922,24 @@ pub fn reject_hotkey_collisions(preferences: &UserPreferences) -> Result<(), Str reject_style_pack_hotkey_conflicts(&preferences.style_pack_hotkeys, preferences) } +pub fn validate_skip_auto_style_hotkey(binding: &ShortcutBinding) -> Result<(), String> { + if binding.is_unassigned() { return Ok(()); } + validate_shortcut_binding(binding).map_err(|error| error.to_string())?; + reject_side_specific_non_dictation(binding)?; + if cfg!(target_os = "windows") && legacy_modifier_trigger(binding).is_some() { + return Err("Windows 跳过自动风格快捷键暂仅支持组合键".into()); + } + // The native tap path supports physical modifier keys; a generic Shift + // belongs to translation, and media/Fn have platform system actions. + if binding.modifiers.is_empty() && legacy_modifier_trigger(binding).is_none() { + return Err("跳过自动风格快捷键需要单个修饰键或组合键".into()); + } + if matches!(legacy_modifier_trigger(binding), Some(HotkeyTrigger::Fn | HotkeyTrigger::MediaPlayPause)) { + return Err("跳过自动风格快捷键不支持 Fn 或媒体键".into()); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/openless-all/app/crates/openless-core/src/style_pack_store.rs b/openless-all/app/crates/openless-core/src/style_pack_store.rs index 363851295..48212536b 100644 --- a/openless-all/app/crates/openless-core/src/style_pack_store.rs +++ b/openless-all/app/crates/openless-core/src/style_pack_store.rs @@ -296,6 +296,28 @@ impl StylePackStore { self.get_for_dictation([], active_id) } + /// Capture all alternatives under one catalog lock, so editing a pack + /// during native startup cannot give the toggle two versions of one style. + pub(crate) fn capture_dictation_styles<'a>( + &self, + assigned_ids: impl IntoIterator, + active_id: &'a str, + polish_id: &'a str, + ) -> Result<(StylePack, StylePack, Vec), BackendError> { + let packs = self.lock()?; + let resolve = |ids: Vec<&str>| { + ids.into_iter() + .find_map(|id| packs.iter().find(|pack| pack.id == id && pack.enabled)) + .or_else(|| packs.iter().find(|pack| pack.id == default_active_style_pack_id() && pack.enabled)) + .or_else(|| packs.iter().find(|pack| pack.enabled)) + .cloned() + .ok_or_else(|| BackendError::new(BackendErrorCode::InvalidState, "no enabled style pack")) + }; + let automatic = resolve(assigned_ids.into_iter().chain([active_id]).collect())?; + let polish = resolve(vec![polish_id])?; + Ok((automatic, polish, packs.iter().filter(|pack| pack.enabled).cloned().collect())) + } + pub(crate) fn get_for_dictation<'a>( &self, assigned_ids: impl IntoIterator, diff --git a/openless-all/app/crates/openless-core/src/types.rs b/openless-all/app/crates/openless-core/src/types.rs index c2b71bb38..ac8242e60 100644 --- a/openless-all/app/crates/openless-core/src/types.rs +++ b/openless-all/app/crates/openless-core/src/types.rs @@ -239,6 +239,12 @@ pub struct DictationStateSnapshot { /// must keep their warming presentation until that callback is observed. #[serde(default)] pub recording_ready: bool, + #[serde(default)] + pub skip_auto_style: bool, + #[serde(default)] + pub style_pack_id: Option, + #[serde(default)] + pub style_pack_name: Option, } impl Default for DictationStateSnapshot { @@ -251,6 +257,9 @@ impl Default for DictationStateSnapshot { message: None, translation_active: false, recording_ready: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, } } } @@ -449,6 +458,7 @@ mod tests { message: None, translation_active: true, recording_ready: true, + ..Default::default() }; let value = serde_json::to_value(snapshot).unwrap(); assert_eq!(value["phase"], "transcribing"); diff --git a/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs b/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs index 3cba44068..602841092 100644 --- a/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs +++ b/openless-all/app/crates/openless-core/tests/dictation_target_capture.rs @@ -82,9 +82,26 @@ struct Focus { position: Option<(u64, u64)>, } +#[derive(Default)] +struct StartupBarrier { + armed: AtomicBool, + entered: Notify, + release: Notify, +} + +impl StartupBarrier { + async fn wait_if_armed(&self) { + if self.armed.swap(false, Ordering::AcqRel) { + self.entered.notify_one(); + self.release.notified().await; + } + } +} + struct FocusContextAdapter { focus: Arc>, target: &'static str, + barrier: Arc, } impl HostContextAdapter for FocusContextAdapter { @@ -117,7 +134,9 @@ impl HostContextAdapter for FocusContextAdapter { .context_captured .push(self.target); let front_app = self.target.to_string(); + let barrier = self.barrier.clone(); Box::pin(async move { + barrier.wait_if_armed().await; Ok(HostContextCapture { front_app: Some(front_app), cursor_context: None, @@ -129,10 +148,12 @@ impl HostContextAdapter for FocusContextAdapter { struct FocusInserter { focus: Arc>, target: Option<&'static str>, + barrier: Arc, + preparation: Arc, } impl TextInserter for FocusInserter { fn defer_preparation_until_stop(&self) -> bool { - true + !self.preparation.armed.load(Ordering::Acquire) } fn capture_target(&self) -> Option { let mut focus = self.focus.lock().unwrap(); @@ -142,10 +163,13 @@ impl TextInserter for FocusInserter { inserter: Arc::new(Self { focus: self.focus.clone(), target: Some(target), + barrier: self.barrier.clone(), + preparation: self.preparation.clone(), }), host_context: Arc::new(FocusContextAdapter { focus: self.focus.clone(), target, + barrier: self.barrier.clone(), }), }) } @@ -162,7 +186,11 @@ impl TextInserter for FocusInserter { focus: self.focus.clone(), target, }); - Box::pin(async move { Ok(session) }) + let preparation = self.preparation.clone(); + Box::pin(async move { + preparation.wait_if_armed().await; + Ok(session) + }) } } struct FocusSession { @@ -196,6 +224,8 @@ struct Fixture { backend: Arc, credentials: Arc, focus: Arc>, + host_capture: Arc, + preparation: Arc, directory: std::path::PathBuf, } @@ -223,6 +253,8 @@ impl Fixture { ) .unwrap(); let credentials = Arc::new(DelayedCredentials::default()); + let host_capture = Arc::new(StartupBarrier::default()); + let preparation = Arc::new(StartupBarrier::default()); let focus = Arc::new(Mutex::new(Focus { current: "A", captured: Vec::new(), @@ -239,6 +271,8 @@ impl Fixture { dependencies.text_inserter = Arc::new(FocusInserter { focus: focus.clone(), target: None, + barrier: host_capture.clone(), + preparation: preparation.clone(), }); let backend = Arc::new( OpenLessBackend::new( @@ -255,6 +289,8 @@ impl Fixture { backend, credentials, focus, + host_capture, + preparation, directory, } } @@ -266,6 +302,412 @@ impl Drop for Fixture { } } +#[tokio::test] +async fn skip_auto_style_capture_explicit_translation_and_history_use_actual_style() { + for (skip, explicit) in [(false, false), (true, false), (false, true), (true, true)] { + let engine = FixtureDictationEngine::successful("spoken", "polished"); + let fixture = Fixture::with_engine(|_| Arc::new(engine.clone())).await; + fixture.credentials.waited.store(true, Ordering::Release); + fixture.focus.lock().unwrap().current = "VS Code"; + let backend = &fixture.backend; + let polish = backend.create_style_pack(StylePack { + name: "polish".into(), prompt: "frozen polish".into(), ..Default::default() + }).unwrap(); + let automatic = backend.create_style_pack(StylePack { + name: "automatic".into(), prompt: "frozen automatic".into(), ..Default::default() + }).unwrap(); + backend.activate_style_pack(&polish.id).unwrap(); + backend.set_app_style_assignment(AppStyleAssignment::Category { + category: "coding".into(), style_pack_id: Some(automatic.id.clone()), + }).unwrap(); + let mut prefs = backend.get_preferences(); + prefs.translation_target_language = "English".into(); + prefs.working_languages = vec!["简体中文".into()]; + backend.update_settings(prefs, openless_core::SettingsUpdateOptions::STRICT, + &openless_core::NoopSettingsRuntime).unwrap(); + let id = backend.start_dictation_with_options(DictationStartOptions { + skip_auto_style: skip, + style_pack_id: explicit.then(|| "builtin.formal".into()), + translation_requested: true, + ..Default::default() + }).await.unwrap(); + let expected = if skip { polish.id.as_str() } else if explicit { "builtin.formal" } else { automatic.id.as_str() }; + let target = backend.dictation_style_target().unwrap(); + assert_eq!(target.style_pack_id.as_deref(), Some(expected)); + assert_eq!(target.skip_auto_style, skip); + assert!(target.available_styles.iter().any(|pack| pack.id == polish.id)); + assert!(backend.snapshot().dictation.translation_active); + backend.stop_dictation_session(id).await.unwrap(); + let history = backend.list_history().unwrap(); + assert_eq!(history[0].style_pack_id.as_deref(), Some(expected)); + assert!(history[0].translation_active); + } +} + +#[tokio::test] +async fn skip_auto_style_unchanged_sessions_support_engines_without_context_updates() { + use openless_core::{DictationEngine, EngineFailure, EngineProgressSink, EngineResult}; + use openless_core::testing::FixtureEngineAction; + + struct StartOnlyEngine(FixtureDictationEngine); + impl DictationEngine for StartOnlyEngine { + fn start( + &self, id: SessionId, context: Arc, progress: Arc, + ) -> BoxFuture<'static, Result<(), BackendError>> { + self.0.start(id, context, progress) + } + fn finish( + &self, id: SessionId, progress: Arc, + ) -> BoxFuture<'static, Result> { + self.0.finish(id, progress) + } + fn cancel(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { + self.0.cancel(id) + } + // Intentionally inherit the production trait's Unsupported update_context. + } + + let engine = FixtureDictationEngine::successful("spoken", "polished"); + let fixture = Fixture::with_engine(|_| Arc::new(StartOnlyEngine(engine.clone()))).await; + fixture.credentials.waited.store(true, Ordering::Release); + for initial_skip in [false, true, false] { + let id = fixture.backend.start_dictation_with_options(DictationStartOptions { + skip_auto_style: initial_skip, + ..Default::default() + }).await.unwrap(); + assert_eq!(fixture.backend.snapshot().dictation.skip_auto_style, initial_skip); + let result = fixture.backend.stop_dictation_session(id).await.unwrap(); + assert_eq!(result.session_id, id); + assert_eq!(result.polished_text, "polished"); + assert_eq!(engine.actions().iter().rev().take(2).cloned().collect::>(), + [FixtureEngineAction::Finish(id), FixtureEngineAction::Start(id)]); + let history = fixture.backend.list_history().unwrap(); + assert!(history.iter().any(|row| row.id == id.to_string() && row.error_code.is_none())); + } + assert_eq!(engine.contexts().len(), 3, "unchanged sessions must never request context updates"); + fixture.backend.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn skip_auto_style_sync_consumes_only_changes_in_the_engine_start_snapshot() { + use openless_core::{DictationEngine, DictationPhase, EngineFailure, EngineProgressSink, EngineResult}; + use openless_core::testing::FixtureEngineAction; + use std::time::Duration; + + struct GatedStartEngine { + inner: FixtureDictationEngine, + barrier: Arc, + } + impl DictationEngine for GatedStartEngine { + fn start( + &self, id: SessionId, context: Arc, progress: Arc, + ) -> BoxFuture<'static, Result<(), BackendError>> { + let starting = self.inner.start(id, context, progress); + let barrier = self.barrier.clone(); + Box::pin(async move { + barrier.wait_if_armed().await; + starting.await + }) + } + fn finish( + &self, id: SessionId, progress: Arc, + ) -> BoxFuture<'static, Result> { + self.inner.finish(id, progress) + } + fn cancel(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { + self.inner.cancel(id) + } + fn update_context( + &self, id: SessionId, context: Arc, + ) -> BoxFuture<'static, Result<(), BackendError>> { + self.inner.update_context(id, context) + } + } + + for initial_skip in [false, true] { + for stage in ["host", "credentials", "insertion", "engine", "recording"] { + let engine = FixtureDictationEngine::successful("spoken", "polished"); + let engine_start = Arc::new(StartupBarrier::default()); + engine_start.armed.store(stage == "engine", Ordering::Release); + let fixture = Fixture::with_engine(|_| Arc::new(GatedStartEngine { + inner: engine.clone(), barrier: engine_start.clone(), + })).await; + fixture.credentials.waited.store(stage != "credentials", Ordering::Release); + fixture.host_capture.armed.store(stage == "host", Ordering::Release); + fixture.preparation.armed.store(stage == "insertion", Ordering::Release); + fixture.backend.activate_style_pack("builtin.light").unwrap(); + let starting = tokio::spawn({ + let backend = fixture.backend.clone(); + async move { + backend.start_dictation_with_options(DictationStartOptions { + skip_auto_style: initial_skip, + style_pack_id: Some("builtin.formal".into()), + ..Default::default() + }).await + } + }); + let barrier = match stage { + "host" => Some((&fixture.host_capture.entered, &fixture.host_capture.release)), + "credentials" => Some((fixture.credentials.entered.as_ref(), fixture.credentials.release.as_ref())), + "insertion" => Some((&fixture.preparation.entered, &fixture.preparation.release)), + "engine" => Some((&engine_start.entered, &engine_start.release)), + _ => None, + }; + let mut starting = Some(starting); + if let Some((entered, _)) = barrier { + tokio::time::timeout(Duration::from_secs(2), entered.notified()).await.unwrap(); + assert_eq!(fixture.backend.snapshot().dictation.phase, DictationPhase::Starting); + assert!(!starting.as_ref().unwrap().is_finished()); + } else { + starting.take().unwrap().await.unwrap().unwrap(); + assert_eq!(fixture.backend.snapshot().dictation.phase, DictationPhase::Recording); + } + let id = fixture.backend.snapshot().dictation.session_id.unwrap(); + let early = matches!(stage, "host" | "credentials"); + if early || stage == "insertion" { + assert!(engine.contexts().is_empty(), "engine must not have its snapshot at {stage}"); + } else { + assert_eq!(engine.contexts().len(), 1); + } + fixture.backend.toggle_dictation_style_for_session(id).unwrap(); + if let Some((_, release)) = barrier { + release.notify_one(); + assert_eq!(tokio::time::timeout(Duration::from_secs(2), starting.take().unwrap()) + .await.unwrap().unwrap().unwrap(), id); + } + let expected = if initial_skip { "builtin.formal" } else { "builtin.light" }; + let initial = if initial_skip { "builtin.light" } else { "builtin.formal" }; + assert_eq!(engine.contexts()[0].polish.style_pack_id, + if early { expected } else { initial }); + fixture.backend.stop_dictation_session(id).await.unwrap(); + let mut expected_actions = vec![FixtureEngineAction::Start(id)]; + if !early { + expected_actions.push(FixtureEngineAction::UpdateContext(id)); + } + expected_actions.push(FixtureEngineAction::Finish(id)); + assert_eq!(engine.actions(), expected_actions, "stage={stage}, initial_skip={initial_skip}"); + assert_eq!(engine.contexts().last().unwrap().polish.style_pack_id, expected); + assert_eq!(fixture.backend.list_history().unwrap()[0].style_pack_id.as_deref(), Some(expected)); + + // A consumed update must not dirty a successor, and a stale request + // cannot alter its current choice or engine snapshot. + let next = fixture.backend.start_dictation().await.unwrap(); + assert!(fixture.backend.toggle_dictation_style_for_session(id).is_err()); + fixture.backend.stop_dictation_session(next).await.unwrap(); + assert_eq!(engine.actions().iter().rev().take(2).cloned().collect::>(), + [FixtureEngineAction::Finish(next), FixtureEngineAction::Start(next)]); + fixture.backend.shutdown().await.unwrap(); + } + } +} + +#[tokio::test] +async fn skip_auto_style_initial_choice_survives_host_and_credential_awaits() { + use openless_core::{BackendEventKind, DictationPhase, DictationStyleSelection as Selection}; + use std::time::Duration; + + for initial_skip in [true, false] { + for explicit in [false, true] { + for hotkey in [false, true] { + let engine = FixtureDictationEngine::successful("spoken", "polished"); + let fixture = Fixture::with_engine(|_| Arc::new(engine.clone())).await; + fixture.focus.lock().unwrap().current = "VS Code"; + fixture.host_capture.armed.store(true, Ordering::Release); + fixture.credentials.write( + CredentialKey::new(CredentialNamespace::Llm, Some("ark".into()), "ark.api_key").unwrap(), + SecretValue::new("fixture-key"), + ).await.unwrap(); + let backend = &fixture.backend; + let polish = backend.create_style_pack(StylePack { + name: "polish".into(), prompt: "frozen polish".into(), ..Default::default() + }).unwrap(); + let automatic = backend.create_style_pack(StylePack { + name: "automatic".into(), prompt: "frozen automatic".into(), ..Default::default() + }).unwrap(); + backend.activate_style_pack(&polish.id).unwrap(); + backend.set_app_style_assignment(AppStyleAssignment::Category { + category: "coding".into(), style_pack_id: Some(automatic.id.clone()), + }).unwrap(); + let mut prefs = backend.get_preferences(); + prefs.translation_target_language = "English".into(); + prefs.working_languages = vec!["简体中文".into()]; + backend.update_settings(prefs, openless_core::SettingsUpdateOptions::STRICT, + &openless_core::NoopSettingsRuntime).unwrap(); + let mut events = backend.subscribe(); + let starting = tokio::spawn({ + let backend = backend.clone(); + async move { + let options = DictationStartOptions { + skip_auto_style: initial_skip, + style_pack_id: explicit.then(|| "builtin.formal".into()), + ..Default::default() + }; + if hotkey { + match backend.dispatch_dictation_hotkey_edge_with_options( + DictationHotkeyEdge::Pressed { + press_id: 1, at: std::time::Instant::now(), + }, + options, + ).await? { + CliDispatchOutcome::DictationStarted(id) => Ok(id), + other => panic!("expected started session, got {other:?}"), + } + } else { + backend.start_dictation_with_options(options).await + } + } + }); + // These signals originate inside the real capture/provider futures. + // No state is fabricated, and the engine cannot start past either gate. + tokio::time::timeout(Duration::from_secs(2), fixture.host_capture.entered.notified()) + .await.unwrap(); + let snapshot = backend.snapshot().dictation; + let id = snapshot.session_id.unwrap(); + assert_eq!(snapshot.phase, DictationPhase::Starting); + assert_eq!(snapshot.skip_auto_style, initial_skip); + let initial = if initial_skip { Selection::SkipAuto } else { Selection::Automatic }; + let target = backend.dictation_style_target().unwrap(); + assert_eq!(target.selection, initial); + assert_eq!(target.skip_auto_style, initial_skip); + assert!(target.style_pack_id.is_none()); + assert!(!starting.is_finished()); + assert!(engine.contexts().is_empty()); + let mut published_starting = false; + while let Ok(event) = events.try_recv() { + match event.kind { + BackendEventKind::DictationStateChanged(state) + if state.phase == DictationPhase::Starting => { + assert_eq!(state.session_id, Some(id)); + assert_eq!(state.skip_auto_style, initial_skip); + published_starting = true; + } + _ => {} + } + } + assert!(published_starting, "first Starting feedback must show the initial choice"); + + let expected = if initial_skip { Selection::Automatic } else { Selection::SkipAuto }; + assert_eq!(backend.toggle_dictation_style_for_session(id).unwrap().selection, expected); + assert_eq!(backend.snapshot().dictation.skip_auto_style, !initial_skip); + backend.toggle_dictation_translation_for_session(id).unwrap(); + fixture.host_capture.release.notify_one(); + tokio::time::timeout(Duration::from_secs(2), fixture.credentials.entered.notified()) + .await.unwrap(); + assert_eq!(backend.dictation_style_target().unwrap().selection, expected); + assert_eq!(backend.snapshot().dictation.phase, DictationPhase::Starting); + assert!(engine.contexts().is_empty()); + // Absolute requests and toggles must apply in call order, including + // across separate startup awaits. A stale session must not change it. + assert!(backend.update_dictation_style(SessionId::new(), initial.clone()).is_err()); + assert_eq!(backend.update_dictation_style(id, initial.clone()).unwrap().selection, initial); + assert_eq!(backend.toggle_dictation_style_for_session(id).unwrap().selection, expected); + fixture.credentials.release.notify_one(); + assert_eq!(tokio::time::timeout(Duration::from_secs(2), starting) + .await.unwrap().unwrap().unwrap(), id); + let expected_id = if expected == Selection::SkipAuto { + polish.id.as_str() + } else if explicit { + "builtin.formal" + } else { + automatic.id.as_str() + }; + let target = backend.dictation_style_target().unwrap(); + assert_eq!(target.selection, expected); + assert_eq!(target.style_pack_id.as_deref(), Some(expected_id)); + assert!(backend.snapshot().dictation.translation_active); + backend.stop_dictation_session(id).await.unwrap(); + let contexts = engine.contexts(); + assert!(!contexts.is_empty()); + assert!(contexts.iter().all(|context| { + context.polish.style_pack_id == expected_id + && context.polish.translation_active + })); + let history = backend.list_history().unwrap(); + assert_eq!(history[0].style_pack_id.as_deref(), Some(expected_id)); + assert!(history[0].translation_active); + // The next ordinary session starts from its own default intent. + let next = backend.start_dictation().await.unwrap(); + assert_eq!(backend.dictation_style_target().unwrap().selection, Selection::Automatic); + assert!(!backend.snapshot().dictation.translation_active); + assert!(backend.toggle_dictation_style_for_session(id).is_err()); + backend.cancel_dictation(Some(next)).await.unwrap(); + backend.shutdown().await.unwrap(); + } + } + } +} + +#[tokio::test] +async fn skip_auto_style_starting_toggle_and_picker_keep_frozen_alternatives() { + use openless_core::DictationStyleSelection as Selection; + let engine = FixtureDictationEngine::successful("spoken", "polished"); + let fixture = Fixture::with_engine(|_| Arc::new(engine.clone())).await; + fixture.focus.lock().unwrap().current = "VS Code"; + fixture.credentials.write( + CredentialKey::new(CredentialNamespace::Llm, Some("ark".into()), "ark.api_key").unwrap(), + SecretValue::new("fixture-key"), + ).await.unwrap(); + let backend = &fixture.backend; + let polish = backend.create_style_pack(StylePack { + name: "polish".into(), prompt: "frozen polish".into(), ..Default::default() + }).unwrap(); + let automatic = backend.create_style_pack(StylePack { + name: "automatic".into(), prompt: "frozen automatic".into(), ..Default::default() + }).unwrap(); + backend.activate_style_pack(&polish.id).unwrap(); + backend.set_app_style_assignment(AppStyleAssignment::Category { + category: "coding".into(), style_pack_id: Some(automatic.id.clone()), + }).unwrap(); + let starting = tokio::spawn(start(backend.clone(), 0)); + fixture.credentials.entered.notified().await; + let id = backend.snapshot().dictation.session_id.unwrap(); + backend.toggle_dictation_style_for_session(id).unwrap(); + fixture.credentials.release.notify_one(); + assert_eq!(starting.await.unwrap().unwrap(), id); + assert_eq!(backend.dictation_style_target().unwrap().style_pack_id, Some(polish.id.clone())); + backend.activate_style_pack("builtin.raw").unwrap(); + let mut edited = polish.clone(); + edited.prompt = "edited after capture".into(); + backend.update_style_pack(edited).unwrap(); + let restored = backend.toggle_dictation_style_for_session(id).unwrap(); + assert!(!restored.skip_auto_style); + assert_eq!(restored.style_pack_id, Some(automatic.id.clone())); + let selected = backend.update_dictation_style(id, Selection::StylePack { + style_pack_id: polish.id.clone(), + }).unwrap(); + assert_eq!(selected.style_pack_name.as_deref(), Some("polish")); + let wire = serde_json::to_value(selected).unwrap(); + assert_eq!(wire["selection"]["mode"], "stylePack"); + assert_eq!(wire["selection"]["stylePackId"], polish.id); + assert_eq!(wire["skipAutoStyle"], true); + assert!(backend.update_dictation_style(id, Selection::StylePack { style_pack_id: "missing".into() }).is_err()); + assert!(backend.update_dictation_style(SessionId::new(), Selection::Automatic).is_err()); + backend.stop_dictation_session(id).await.unwrap(); + let contexts = engine.contexts(); + assert!(contexts.last().unwrap().polish.style_system_prompt.contains("frozen polish")); + assert!(!contexts.last().unwrap().polish.style_system_prompt.contains("edited after capture")); + assert_eq!(backend.list_history().unwrap()[0].style_pack_id, Some(polish.id)); + assert!(backend.toggle_dictation_style_for_session(id).is_err()); + let next = backend.start_dictation().await.unwrap(); + assert_eq!(backend.dictation_style_target().unwrap().selection, Selection::Automatic); + assert!(backend.toggle_dictation_style_for_session(id).is_err()); + backend.cancel_dictation(Some(next)).await.unwrap(); +} + +#[tokio::test] +async fn skip_auto_style_without_app_assignment_keeps_the_same_polish() { + let engine = FixtureDictationEngine::successful("spoken", "polished"); + let fixture = Fixture::with_engine(|_| Arc::new(engine.clone())).await; + fixture.credentials.waited.store(true, Ordering::Release); + let id = fixture.backend.start_dictation().await.unwrap(); + let before = engine.contexts()[0].polish.clone(); + let updated = fixture.backend.toggle_dictation_style_for_session(id).unwrap(); + assert!(updated.skip_auto_style); + assert_eq!(updated.style_pack_id.as_deref(), Some(before.style_pack_id.as_str())); + fixture.backend.stop_dictation_session(id).await.unwrap(); + assert_eq!(engine.contexts().last().unwrap().polish, before); +} + async fn start(backend: Arc, route: u8) -> Result { if route == 0 { return backend.start_dictation().await; @@ -353,7 +795,7 @@ async fn no_insertion_skips_target_capture_and_native_preparation() { } #[tokio::test] -async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() { +async fn skip_auto_style_parallel_segments_keep_live_caret_and_independent_styles() { use openless_core::{DictationEngine, EngineFailure, EngineProgressSink, EngineResult}; struct DelayedResult { @@ -394,6 +836,11 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() fn cancel(&self, id: SessionId) -> BoxFuture<'static, Result<(), BackendError>> { self.inner.cancel(id) } + fn update_context( + &self, id: SessionId, context: Arc, + ) -> BoxFuture<'static, Result<(), BackendError>> { + self.inner.update_context(id, context) + } } for (initial, moved, next_capture) in [ @@ -414,6 +861,9 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() fixture.credentials.waited.store(true, Ordering::Release); fixture.focus.lock().unwrap().position = initial; let first = fixture.backend.start_dictation().await.unwrap(); + fixture.backend.update_dictation_style(first, openless_core::DictationStyleSelection::StylePack { + style_pack_id: "builtin.formal".into(), + }).unwrap(); let stopping = tokio::spawn({ let backend = fixture.backend.clone(); async move { backend.stop_dictation_session(first).await } @@ -424,7 +874,17 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() fixture.focus.lock().unwrap().position = moved; let second = if next_capture { fixture.focus.lock().unwrap().current = "B"; - Some(fixture.backend.start_dictation().await.unwrap()) + let second = fixture.backend.start_dictation_with_options(DictationStartOptions { + skip_auto_style: true, + ..Default::default() + }).await.unwrap(); + assert_eq!(fixture.backend.dictation_style_target().unwrap().selection, + openless_core::DictationStyleSelection::SkipAuto); + fixture.backend.update_dictation_style(second, openless_core::DictationStyleSelection::StylePack { + style_pack_id: "builtin.light".into(), + }).unwrap(); + assert!(fixture.backend.toggle_dictation_style_for_session(first).is_err()); + Some(second) } else { None }; @@ -446,6 +906,9 @@ async fn ordinary_delayed_result_allows_stable_live_caret_and_ordered_sessions() .stop_dictation_session(second) .await .unwrap(); + let history = fixture.backend.list_history().unwrap(); + assert_eq!(history.iter().find(|row| row.id == first.to_string()).unwrap().style_pack_id.as_deref(), Some("builtin.formal")); + assert_eq!(history.iter().find(|row| row.id == second.to_string()).unwrap().style_pack_id.as_deref(), Some("builtin.light")); assert_eq!( fixture.focus.lock().unwrap().delivered, [ diff --git a/openless-all/app/crates/openless-core/tests/skip_auto_style.rs b/openless-all/app/crates/openless-core/tests/skip_auto_style.rs new file mode 100644 index 000000000..244a7bd96 --- /dev/null +++ b/openless-all/app/crates/openless-core/tests/skip_auto_style.rs @@ -0,0 +1,167 @@ +use openless_core::shared_types::ShortcutBinding; +use openless_core::{bindings_overlap, reconcile_hotkey_collisions, reject_hotkey_collisions}; +use openless_core::{HotkeyRuntimeTarget, UserPreferences}; + +#[test] +fn skip_auto_style_preferences_upgrade_clear_patch_and_roundtrip() { + let defaults = UserPreferences::default(); + let mut old = serde_json::to_value(&defaults).unwrap(); + old.as_object_mut().unwrap().remove("skipAutoStyleHotkey"); + old.as_object_mut() + .unwrap() + .remove("skipAutoStylePickerEnabled"); + let upgraded: UserPreferences = serde_json::from_value(old.clone()).unwrap(); + assert_eq!( + upgraded.skip_auto_style_hotkey, + defaults.skip_auto_style_hotkey + ); + assert!(!upgraded.skip_auto_style_picker_enabled); + // Exercise collision migration even where the new default is unassigned. + let proposed = if cfg!(target_os = "windows") { + ShortcutBinding { primary: "LeftAlt".into(), modifiers: vec![] } + } else { + defaults.skip_auto_style_hotkey.clone() + }; + old["dictationHotkey"] = serde_json::to_value(&proposed).unwrap(); + let occupied: UserPreferences = serde_json::from_value(old).unwrap(); + assert!( + occupied.skip_auto_style_hotkey.is_unassigned(), + "upgrade must not steal a custom recording key" + ); + let mut configured = defaults.clone(); + configured.skip_auto_style_hotkey = ShortcutBinding { + primary: "K".into(), modifiers: vec!["ctrl".into(), "shift".into()], + }; + let edits = std::collections::BTreeMap::from([ + ( + "/skipAutoStyleHotkey".into(), + serde_json::json!({"primary":"","modifiers":[]}), + ), + ( + "/skipAutoStylePickerEnabled".into(), + serde_json::json!(true), + ), + ]); + let patched = openless_core::preference_patch::patch_preferences(&configured, &edits).unwrap(); + let restored: UserPreferences = + serde_json::from_value(serde_json::to_value(&patched).unwrap()).unwrap(); + assert!(restored.skip_auto_style_hotkey.is_unassigned()); + assert!(restored.skip_auto_style_picker_enabled); + assert_ne!( + HotkeyRuntimeTarget::from(&restored), + HotkeyRuntimeTarget::from(&configured) + ); + let change = openless_core::SettingsEffectPlan::between(&configured, &restored) + .hotkeys + .unwrap(); + assert_eq!( + change.previous.skip_auto_style, + configured.skip_auto_style_hotkey + ); + assert!(change.next.skip_auto_style.is_unassigned()); +} + +#[test] +fn skip_auto_style_defaults_and_conflicts_cover_every_owner() { + let defaults = UserPreferences::default(); + assert_eq!( + defaults.skip_auto_style_hotkey.primary, + if cfg!(target_os = "macos") { + "LeftCommand" + } else if cfg!(target_os = "windows") { + "" + } else { + "LeftAlt" + } + ); + reject_hotkey_collisions(&defaults).unwrap(); + for owner in 0..10 { + let mut prefs = defaults.clone(); + // Use a supported, assigned combination on every platform. + prefs.skip_auto_style_hotkey = ShortcutBinding { + primary: "K".into(), modifiers: vec!["ctrl".into(), "shift".into()], + }; + let key = prefs.skip_auto_style_hotkey.clone(); + match owner { + 0 => prefs.dictation_hotkey = key, + 1 => prefs.translation_hotkey = key, + 2 => prefs.qa_hotkey = Some(key), + 3 => prefs.switch_style_hotkey = Some(key), + 4 => prefs.open_app_hotkey = Some(key), + 5 => prefs.coding_agent_voice_hotkey = Some(key), + 6 => prefs.selection_polish_hotkey = Some(key), + 7 => prefs.quick_note_hotkey = Some(key), + 8 => prefs.coding_agent_panel_hotkey = Some(key), + _ => prefs.coding_agent_quick_hotkey = Some(key), + } + assert!(reject_hotkey_collisions(&prefs).is_err(), "owner {owner}"); + } + let mut conflicting = defaults.clone(); + conflicting.skip_auto_style_hotkey = defaults.dictation_hotkey.clone(); + assert_eq!(reconcile_hotkey_collisions(&mut conflicting, &defaults), 1); + assert_eq!( + conflicting.skip_auto_style_hotkey, + defaults.skip_auto_style_hotkey + ); + let mut disabled = defaults.clone(); + disabled.skip_auto_style_hotkey = ShortcutBinding::unassigned(); + assert_eq!(reconcile_hotkey_collisions(&mut disabled, &defaults), 0); + let left_alt = ShortcutBinding { + primary: "LeftAlt".into(), + modifiers: vec![], + }; + let right_alt = ShortcutBinding { + primary: "RightAlt".into(), + modifiers: vec![], + }; + assert!( + !bindings_overlap(&left_alt, &right_alt), + "Windows menu key and selection polish must use distinct physical sides" + ); + let mut shift = defaults; + shift.skip_auto_style_hotkey = ShortcutBinding { + primary: "LeftShift".into(), + modifiers: vec![], + }; + assert!(reject_hotkey_collisions(&shift).is_err()); + let mut style_conflict = UserPreferences { + skip_auto_style_hotkey: ShortcutBinding { + primary: "K".into(), + modifiers: vec!["ctrl".into(), "shift".into()], + }, + ..UserPreferences::default() + }; + style_conflict + .style_pack_hotkeys + .push(openless_core::shared_types::StylePackHotkey { + pack_id: "builtin.raw".into(), + binding: style_conflict.skip_auto_style_hotkey.clone(), + }); + assert!(reject_hotkey_collisions(&style_conflict).is_err()); +} + +#[cfg(target_os = "windows")] +#[test] +fn skip_auto_style_windows_migrates_and_rejects_unverified_modifier_taps() { + for primary in ["LeftAlt", "RightAlt", "LeftOption", "LeftCommand", "LeftControl"] { + let binding = ShortcutBinding { primary: primary.into(), modifiers: vec![] }; + let prefs = UserPreferences { + skip_auto_style_hotkey: binding.clone(), + ..UserPreferences::default() + }; + assert!(reject_hotkey_collisions(&prefs).is_err(), "{primary}"); + let migrated: UserPreferences = + serde_json::from_value(serde_json::to_value(&prefs).unwrap()).unwrap(); + assert!(migrated.skip_auto_style_hotkey.is_unassigned(), "{primary}"); + } + let prefs = UserPreferences { + skip_auto_style_hotkey: ShortcutBinding { + primary: "K".into(), modifiers: vec!["ctrl".into(), "shift".into()], + }, + ..UserPreferences::default() + }; + reject_hotkey_collisions(&prefs).unwrap(); + let roundtrip: UserPreferences = + serde_json::from_value(serde_json::to_value(&prefs).unwrap()).unwrap(); + assert_eq!(roundtrip.skip_auto_style_hotkey, prefs.skip_auto_style_hotkey); +} diff --git a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs index 4c89cae68..2a1f2c439 100644 --- a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs +++ b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs @@ -764,4 +764,51 @@ assert.match( 'mobile dictation insertion must provide a no-op target restore without enabling Selection Polish', ); +const styleIpc = await read('src/lib/ipc/dictation.ts'); +const hotkeyIpc = await read('src/lib/ipc/hotkeys.ts'); +const sharedTypes = await read('crates/openless-core/src/shared_types.rs'); +const styleContext = await read('crates/openless-core/src/dictation_context.rs'); +const styleCommand = await read('src-tauri/src/commands/dictation.rs'); +const mockSettings = await read('src/lib/ipc/mock-data.ts'); +for (const field of ['skipAutoStyleHotkey', 'skipAutoStylePickerEnabled']) { + assert.ok(types.includes(field), `frontend preferences must declare ${field}`); + assert.ok(mockSettings.includes(field), `mock settings must include ${field}`); +} +for (const command of [ + 'get_dictation_style_target', + 'update_dictation_style', + 'set_capsule_style_menu', +]) { + assert.ok(styleIpc.includes(`'${command}'`)); + assert.ok(styleCommand.includes(`fn ${command}`)); + assert.ok(invokeHandlers.includes(`commands::${command}`)); +} +assert.match(hotkeyIpc, /'set_skip_auto_style_hotkey',\s*\{ binding \}/); +assert.match( + coreApi, + /pub fn update_dictation_style\([^]*?session_id: SessionId,[^]*?selection: DictationStyleSelection/, +); +assert.match(coreApi, /pub fn toggle_dictation_style_for_session/); +assert.match(coreApi, /style_choices\.available = available_styles/); +assert.match(styleContext, /pub enum DictationStyleSelection/); +for (const mode of ['automatic', 'skipAuto', 'stylePack']) + assert.ok(types.includes(`mode: "${mode}"`) || types.includes(`mode: '${mode}'`)); +for (const field of ['skip_auto_style', 'style_pack_id', 'style_pack_name']) { + assert.ok(sharedTypes.includes(`pub ${field}:`), `capsule must expose ${field}`); +} +assert.match(coordinatorHotkeys, /set_skip_auto_style_source/); +const restoreHotkeys = await read('src-tauri/src/coordinator/restore_runtime.rs'); +assert.match(restoreHotkeys, /inner\.skip_auto_style_hotkey\.lock\(\)\.take\(\)/); +assert.match( + restoreHotkeys, + /update_skip_auto_style_hotkey_on_main\(inner, target\.skip_auto_style\.clone\(\)\)/, + 'absolute restore and journal rollback must install the target style binding', +); +assert.match(coordinatorHotkeys, /toggle_dictation_style_for_session\(context\.session_id\)/); +assert.match(styleCommand, /set_capsule_picker_menu_impl\(window, coord, session_id, open, true\)/); +assert.match( + styleCommand, + /set_capsule_picker_menu_impl\(window, coord, session_id, open, false\)/, +); + console.log('shared-backend-wire-contract.test.mjs passed'); diff --git a/openless-all/app/src-tauri/backend-tests/Cargo.lock b/openless-all/app/src-tauri/backend-tests/Cargo.lock index 6417d80bb..1ad0507af 100644 --- a/openless-all/app/src-tauri/backend-tests/Cargo.lock +++ b/openless-all/app/src-tauri/backend-tests/Cargo.lock @@ -212,6 +212,9 @@ name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "blake2" @@ -559,6 +562,21 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "crunchy" version = "0.2.4" @@ -1042,6 +1060,22 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]] +name = "global-hotkey" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fbb3a4e56c901ee66c190fdb3fa08344e6d09593cc6c61f8eb9add7144b271" +dependencies = [ + "crossbeam-channel", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit", + "once_cell", + "thiserror 2.0.21", + "windows-sys 0.59.0", + "x11-dl", +] + [[package]] name = "group" version = "0.13.0" @@ -1456,6 +1490,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.13.2", + "serde", + "unicode-segmentation", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1832,12 +1877,45 @@ dependencies = [ "objc2-encode", ] +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + [[package]] name = "objc2-encode" version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + [[package]] name = "oboe" version = "0.6.1" @@ -1891,6 +1969,7 @@ dependencies = [ "cpal", "dispatch2", "futures-util", + "global-hotkey", "libc", "log", "objc2 0.5.3", @@ -3370,6 +3449,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + [[package]] name = "universal-hash" version = "0.6.1" @@ -3754,6 +3839,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -3905,6 +3999,17 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + [[package]] name = "x509-parser" version = "0.16.0" diff --git a/openless-all/app/src-tauri/backend-tests/Cargo.toml b/openless-all/app/src-tauri/backend-tests/Cargo.toml index 733e27842..5dbf2354f 100644 --- a/openless-all/app/src-tauri/backend-tests/Cargo.toml +++ b/openless-all/app/src-tauri/backend-tests/Cargo.toml @@ -39,6 +39,7 @@ parking_lot = "0.12" futures-util = "0.3" dispatch2 = "0.3" core-foundation = "0.10" +global-hotkey = "0.6" [target.'cfg(windows)'.dev-dependencies] windows = { version = "0.58", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse"] } diff --git a/openless-all/app/src-tauri/backend-tests/tests/skip_auto_style_restore.rs b/openless-all/app/src-tauri/backend-tests/tests/skip_auto_style_restore.rs new file mode 100644 index 000000000..04645444a --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/skip_auto_style_restore.rs @@ -0,0 +1,6 @@ +//! Exercise the production monitor replacement used by restore and rollback, +//! with RAII registrations instead of reserving a user's global keyboard keys. +#[path = "../../src/coordinator/skip_auto_style_monitor.rs"] +mod skip_auto_style_monitor; +#[path = "../../../crates/openless-core/tests/skip_auto_style.rs"] +mod core_contract; diff --git a/openless-all/app/src-tauri/backend-tests/tests/support/translation_ask_host.rs b/openless-all/app/src-tauri/backend-tests/tests/support/translation_ask_host.rs new file mode 100644 index 000000000..290fa121e --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/support/translation_ask_host.rs @@ -0,0 +1,61 @@ +//! The production Ask keyboard controller runs against inert desktop effects. +//! Native::key_edge, pairing, physical modifiers and runtime routing are real. +use std::{future::Future, pin::Pin, time::Duration}; +use openless_core::DictationHotkeyEdge; + +#[path = "../../../src/ask_window/hotkey.rs"] +pub(crate) mod hotkey; + +pub fn active_space_epoch() -> u64 { 0 } +pub fn foreground_pid() -> Option { None } +pub fn install_test_runtime(desktop: &std::sync::Arc) { + hotkey::install(std::sync::Arc::downgrade(desktop)); +} + +pub mod capture { + pub struct Foreground { pub pid: u32 } + pub struct Trigger; + impl Trigger { + pub fn at_key_event(_: Option) -> Self { Self } + } + pub fn foreground() -> Option { None } +} +pub mod voice { + use super::*; + #[derive(Clone)] + pub struct Target; + #[derive(Default)] + pub struct Controller; + impl Controller { + pub fn manual(&self, _: Option, _: u64, _: bool, _: Option) {} + pub fn release(&self, _: u64, _: Duration, _: bool, _: bool) {} + pub fn cancel_press(&self, _: u64) {} + } +} + +#[derive(Default)] +pub struct Ports; +impl Ports { + pub fn ordinary_dictation_is_active(&self) -> bool { true } + pub fn ordinary_dictation_edge( + &self, _: DictationHotkeyEdge, _: Option, + ) -> Pin + Send>> { Box::pin(async {}) } +} +#[derive(Default)] +pub struct Desktop { + pub ports: Ports, + pub voice: voice::Controller, +} +impl Desktop { + pub fn is_native_target(&self, _: Option<&capture::Foreground>) -> bool { false } + pub fn target_at_press(&self) -> Option { None } + pub fn voice_is_pending(&self) -> bool { false } + pub fn begin_open(&self) -> u64 { 1 } + pub fn cancel_pending_open(&self) {} + pub fn is_focused(&self) -> bool { false } + pub fn warm_dictation(&self) {} + pub fn dismiss_composer_from_escape(&self) {} + pub async fn open_with( + &self, _: Option, _: Option, _: u64, + ) -> Result<(), String> { Ok(()) } +} diff --git a/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs b/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs index 82a60eb9f..2ad6bd6eb 100644 --- a/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs +++ b/openless-all/app/src-tauri/backend-tests/tests/translation_hotkey.rs @@ -6,6 +6,12 @@ mod types { HotkeyTrigger, ShortcutBinding, }; } +#[cfg(target_os = "macos")] +#[path = "../../src/shortcut_binding.rs"] +mod shortcut_binding; +#[cfg(target_os = "macos")] +mod macos_dictation_key { pub const PRIMARY: &str = "MacDictationKey"; } +#[cfg(not(target_os = "macos"))] mod shortcut_binding { pub use openless_core::{is_side_specific_modifier_tag, normalize_side_modifier_tag}; pub fn parse_primary(primary: &str) -> Result<(), openless_core::ShortcutBindingError> { @@ -19,8 +25,15 @@ mod selection { // Selection capture is unrelated to keyboard classification in this test harness. pub fn prefetch_selection_workspace_capture() {} } -// This harness leaves Ask unconfigured so the production keyboard dispatcher -// continues through the dictation/translation route under test. +#[cfg(target_os = "macos")] +extern crate self as tauri; +#[cfg(target_os = "macos")] +pub mod async_runtime { pub use tokio::spawn; } +#[cfg(target_os = "macos")] +#[path = "support/translation_ask_host.rs"] +mod ask_window; +// Other platforms retain the stock route; no window/device runtime is needed. +#[cfg(not(target_os = "macos"))] mod ask_window { pub fn active_space_epoch() -> u64 { 0 } pub fn foreground_pid() -> Option { None } @@ -44,3 +57,17 @@ mod hotkey; mod recording_companion; #[path = "../../src/side_aware_combo.rs"] mod side_aware_combo; + +#[cfg(target_os = "macos")] +#[tokio::test] +async fn skip_auto_style_held_recording_key_uses_real_ask_keyboard_route() { + let _guard = side_aware_combo::TEST_MONITOR_LOCK.lock().await; + let desktop = std::sync::Arc::new(ask_window::Desktop::default()); + ask_window::install_test_runtime(&desktop); + ask_window::hotkey::set_binding( + &types::ShortcutBinding { primary: "RightOption".into(), modifiers: vec![] }, + types::HotkeyMode::Hold, + ); + hotkey::platform::tests::skip_auto_style_mac_held_ask_controller(); + // Drop desktop: subsequent cases revert to the stock route. +} diff --git a/openless-all/app/src-tauri/src/ask_window/hotkey.rs b/openless-all/app/src-tauri/src/ask_window/hotkey.rs index aa9e40740..098bd05fd 100644 --- a/openless-all/app/src-tauri/src/ask_window/hotkey.rs +++ b/openless-all/app/src-tauri/src/ask_window/hotkey.rs @@ -211,6 +211,17 @@ pub(crate) fn fn_is_held() -> bool { .is_some_and(|runtime| runtime.native.lock().modifiers & FN != 0) } +/// Physical recording controller, including the ordinary dictation route +/// handled by Ask before the legacy monitor can update its own latch. +#[cfg(target_os = "macos")] +pub(crate) fn held_recording_key() -> Option { + let runtime = RUNTIME.get()?; + runtime.desktop.upgrade()?; + let native = runtime.native.lock(); + let (key, _) = native.paired_primary?; + (native.modifiers & native_modifier(key) != 0).then_some(key) +} + #[cfg(target_os = "macos")] pub(crate) fn can_buffer_space() -> bool { RUNTIME.get().is_some_and(|runtime| { diff --git a/openless-all/app/src-tauri/src/ask_window/voice.rs b/openless-all/app/src-tauri/src/ask_window/voice.rs index 114008715..bc6989e80 100644 --- a/openless-all/app/src-tauri/src/ask_window/voice.rs +++ b/openless-all/app/src-tauri/src/ask_window/voice.rs @@ -473,6 +473,9 @@ fn frame( message: None, inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, capsule_style: desktop.backend.get_preferences().capsule_style, selection_polish: false, diff --git a/openless-all/app/src-tauri/src/capsule_feedback.rs b/openless-all/app/src-tauri/src/capsule_feedback.rs index 3ad5bcfe0..5e390e519 100644 --- a/openless-all/app/src-tauri/src/capsule_feedback.rs +++ b/openless-all/app/src-tauri/src/capsule_feedback.rs @@ -43,6 +43,9 @@ pub(crate) fn dictation_completion_payload( u32::try_from(result.polished_text.chars().count()).unwrap_or(u32::MAX), ), translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, warming: false, capsule_style: style, @@ -132,6 +135,9 @@ pub(crate) fn voice_activation_payload(enabled: bool, style: CapsuleStyle) -> Ca ), inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, warming: false, capsule_style: style, diff --git a/openless-all/app/src-tauri/src/capsule_snapshot.rs b/openless-all/app/src-tauri/src/capsule_snapshot.rs index 8ef60aaaf..fdc37ed3b 100644 --- a/openless-all/app/src-tauri/src/capsule_snapshot.rs +++ b/openless-all/app/src-tauri/src/capsule_snapshot.rs @@ -144,6 +144,9 @@ impl CapsuleSnapshotState { message: None, inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, warming: false, selection_polish: false, @@ -330,6 +333,9 @@ mod tests { message: None, inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, warming: false, capsule_style: CapsuleStyle::Classic, diff --git a/openless-all/app/src-tauri/src/commands/dictation.rs b/openless-all/app/src-tauri/src/commands/dictation.rs index c4668457c..89d33a18f 100644 --- a/openless-all/app/src-tauri/src/commands/dictation.rs +++ b/openless-all/app/src-tauri/src/commands/dictation.rs @@ -54,6 +54,20 @@ async fn ensure_core_started(core: &openless_core::OpenLessBackend) -> Result<() Ok(()) } +#[tauri::command] +pub fn get_dictation_style_target(core: CoreState<'_>) -> Option { + core.dictation_style_target() +} + +#[tauri::command] +pub fn update_dictation_style( + core: CoreState<'_>, + session_id: openless_core::SessionId, + selection: openless_core::dictation_context::DictationStyleSelection, +) -> Result { + core.update_dictation_style(session_id, selection).map_err(|error| error.to_string()) +} + #[tauri::command] pub async fn start_dictation(core: CoreState<'_>) -> Result<(), String> { ensure_core_started(&core).await?; @@ -224,6 +238,29 @@ pub async fn set_capsule_language_menu( coord: CoordinatorState<'_>, session_id: openless_core::SessionId, open: bool, +) -> Result<(), String> { + set_capsule_picker_menu_impl(window, coord, session_id, open, false).await +} + +#[cfg(not(mobile))] +#[tauri::command] +pub async fn set_capsule_style_menu( + window: Window, + coord: CoordinatorState<'_>, + session_id: openless_core::SessionId, + open: bool, +) -> Result<(), String> { + set_capsule_picker_menu_impl(window, coord, session_id, open, true).await +} + +/// Shared geometry, focus policy and session-bound lifecycle for both pickers. +#[cfg(not(mobile))] +async fn set_capsule_picker_menu_impl( + window: Window, + coord: CoordinatorState<'_>, + session_id: openless_core::SessionId, + open: bool, + style: bool, ) -> Result<(), String> { let label = window.label().to_string(); if label != "capsule" && !label.starts_with("capsule-mirror-") { @@ -236,12 +273,13 @@ pub async fn set_capsule_language_menu( .ok_or("capsule_window_unavailable")?; let (send, receive) = tokio::sync::oneshot::channel(); capsule.run_on_main_thread(move |capsule| { - if open - && !core - .dictation_translation_target() - .is_some_and(|active| active.mutable && active.session_id == session_id) - { - let _ = send.send(Err("recording_translation_required".into())); + let mutable = if style { + core.dictation_style_target().is_some_and(|active| active.mutable && active.session_id == session_id) + } else { + core.dictation_translation_target().is_some_and(|active| active.mutable && active.session_id == session_id) + }; + if open && !mutable { + let _ = send.send(Err(if style { "recording_style_required" } else { "recording_translation_required" }.into())); return; } let _ = send.send(capsule.set_translation_menu_open(label, session_id, open)); diff --git a/openless-all/app/src-tauri/src/commands/hotkeys.rs b/openless-all/app/src-tauri/src/commands/hotkeys.rs index b48d0a647..31f096ff4 100644 --- a/openless-all/app/src-tauri/src/commands/hotkeys.rs +++ b/openless-all/app/src-tauri/src/commands/hotkeys.rs @@ -45,6 +45,17 @@ pub fn set_translation_hotkey( super::settings::persist_strict_settings(&coord, prefs) } +#[tauri::command] +pub fn set_skip_auto_style_hotkey( + coord: CoordinatorState<'_>, + binding: Option, +) -> Result<(), String> { + let mut prefs = coord.backend().get_preferences(); + prefs.skip_auto_style_hotkey = binding.unwrap_or_else(ShortcutBinding::unassigned); + reject_hotkey_collisions(&prefs)?; + super::settings::persist_strict_settings(&coord, prefs) +} + /// Sets the "switch style" global hotkey. `binding == None` (frontend passes null) = disable: /// clears the binding and unregisters the global key. #[tauri::command] diff --git a/openless-all/app/src-tauri/src/coordinator.rs b/openless-all/app/src-tauri/src/coordinator.rs index 74815b611..75ef120d9 100644 --- a/openless-all/app/src-tauri/src/coordinator.rs +++ b/openless-all/app/src-tauri/src/coordinator.rs @@ -616,6 +616,7 @@ struct Inner { /// Mouse4/Mouse5 听写监听(WH_MOUSE_LL);与 combo / side-aware 互斥。 mouse_dictation: Mutex>, translation_hotkey: Mutex>, + skip_auto_style_hotkey: Mutex>, switch_style_hotkey: Mutex>, open_app_hotkey: Mutex>, quick_note_hotkey: Mutex>, @@ -803,6 +804,7 @@ impl Coordinator { side_aware_combo: Mutex::new(None), mouse_dictation: Mutex::new(None), translation_hotkey: Mutex::new(None), + skip_auto_style_hotkey: Mutex::new(None), switch_style_hotkey: Mutex::new(None), open_app_hotkey: Mutex::new(None), quick_note_hotkey: Mutex::new(None), @@ -943,6 +945,7 @@ impl Coordinator { side_aware_combo: Mutex::new(None), mouse_dictation: Mutex::new(None), translation_hotkey: Mutex::new(None), + skip_auto_style_hotkey: Mutex::new(None), switch_style_hotkey: Mutex::new(None), open_app_hotkey: Mutex::new(None), quick_note_hotkey: Mutex::new(None), @@ -1314,6 +1317,12 @@ impl Coordinator { coord.start_selection_polish_hotkey_listener(); coord.start_combo_hotkey_listener(); coord.start_translation_hotkey_listener(); + #[cfg(any(target_os = "macos", target_os = "windows"))] + { + let style_inner = Arc::clone(&coord.inner); + std::thread::Builder::new().name("openless-style-hotkey-supervisor".into()) + .spawn(move || skip_auto_style_hotkey_supervisor_loop(style_inner)).ok(); + } coord.start_switch_style_hotkey_listener(); coord.start_open_app_hotkey_listener(); coord.start_quick_note_hotkey_listener(); @@ -1411,6 +1420,15 @@ impl Coordinator { take_translation_hotkey_on_main_thread(&self.inner); } + pub fn stop_skip_auto_style_hotkey_listener(&self) { + let inner = Arc::clone(&self.inner); + if self.inner.host.run_on_main_thread(move || { + inner.skip_auto_style_hotkey.lock().take(); + }).is_err() { + self.inner.skip_auto_style_hotkey.lock().take(); + } + } + pub fn start_switch_style_hotkey_listener(&self) { let inner = Arc::clone(&self.inner); std::thread::Builder::new() @@ -1613,6 +1631,8 @@ impl Coordinator { let combo_tx = spawn_combo_abort_bridge(&self.inner, handle_trigger_combined); match HotkeyMonitor::start(binding, tx, cancel_tx, combo_tx) { Ok(monitor) => { + #[cfg(not(mobile))] + configure_shift_translation(&self.inner, &monitor); let adapter = monitor.kind(); let inner_clone = Arc::clone(&self.inner); std::thread::Builder::new() @@ -1667,6 +1687,10 @@ impl Coordinator { let previous = &change.previous; let next = &change.next; *self.inner.hotkey_runtime_target.lock() = next.clone(); + #[cfg(any(target_os = "macos", target_os = "windows"))] + if previous.skip_auto_style != next.skip_auto_style { + try_update_skip_auto_style_hotkey_binding(&self.inner)?; + } if previous.translation != next.translation { self.try_update_translation_hotkey_binding()?; } diff --git a/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs b/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs index 1fe5fed48..e4264b6de 100644 --- a/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs +++ b/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs @@ -202,6 +202,9 @@ fn emit_capsule_with_context_locked( message, inserted_chars, translation: !selection_polish && dictation.translation_active, + skip_auto_style: !selection_polish && dictation.skip_auto_style, + style_pack_id: (!selection_polish).then_some(dictation.style_pack_id).flatten(), + style_pack_name: (!selection_polish).then_some(dictation.style_pack_name).flatten(), operating: !selection_polish && inner.backend.less_computer_active_session().is_some(), warming: !selection_polish && state == CapsuleState::Recording @@ -505,6 +508,9 @@ mod epoch_tests { message: None, inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, warming: !dictation.recording_ready, selection_polish: false, @@ -603,6 +609,9 @@ mod tests { message: None, inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, warming: false, selection_polish: false, 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 fb46a4ef0..531b83c9d 100644 --- a/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs +++ b/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs @@ -6,6 +6,9 @@ //! parent `coordinator` module can call them through `use hotkey_loops::*;`. use super::*; +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[path = "skip_auto_style_monitor.rs"] +mod skip_auto_style_monitor; use crate::issue1266_debug::{ Event as DebugEvent, Facts as DebugFacts, Kind as DebugKind, Operation as DebugOperation, Outcome as DebugOutcome, Probe as DebugProbe, @@ -13,6 +16,85 @@ use crate::issue1266_debug::{ // ─────────────────────────── hotkey bridging ─────────────────────────── +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(super) fn skip_auto_style_hotkey_supervisor_loop(inner: Arc) { + loop { + if inner.shutdown.load(Ordering::SeqCst) { return; } + let registration = crate::issue1266_debug::lock_host( + &inner.settings_host_gate, DebugKind::TranslationHotkey); + if inner.backend.ensure_runtime_ready().is_ok() { + match try_update_skip_auto_style_hotkey_binding(&inner) { + Ok(()) => return, + Err(error) => log::warn!("[hotkey] style registration failed: {error}"), + } + } + drop(registration); + std::thread::sleep(std::time::Duration::from_secs(3)); + } +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(super) fn try_update_skip_auto_style_hotkey_binding(inner: &Arc) -> Result<(), String> { + let binding = hotkey_runtime_target(inner).skip_auto_style; + if let Some(monitor) = inner.hotkey.lock().as_ref() { + configure_shift_translation(inner, monitor); + } + let (send, receive) = mpsc::sync_channel(1); + let main = Arc::clone(inner); + inner.host.run_on_main_thread(move || { + let _ = send.send(update_skip_auto_style_hotkey_on_main(&main, binding)); + })?; + receive.recv_timeout(std::time::Duration::from_secs(5)) + .map_err(|_| "style hotkey registration timed out".to_string())? +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(super) fn update_skip_auto_style_hotkey_on_main( + inner: &Arc, + binding: crate::types::ShortcutBinding, +) -> Result<(), String> { + skip_auto_style_monitor::replace(&inner.skip_auto_style_hotkey, binding, |binding| { + let (tx, rx) = mpsc::channel(); + let monitor = ComboHotkeyMonitor::start(binding.clone(), tx) + .map_err(|error| error.to_string())?; + let bridge = Arc::clone(inner); + std::thread::Builder::new().name("openless-style-hotkey-bridge".into()) + .spawn(move || skip_auto_style_hotkey_bridge_loop(bridge, rx, binding)) + .map_err(|error| error.to_string())?; + Ok(monitor) + }) +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn skip_auto_style_hotkey_bridge_loop( + inner: Arc, rx: mpsc::Receiver, + binding: crate::types::ShortcutBinding, +) { + // The press records ownership; a release after a new capture cannot toggle it. + let mut owner = None; + while let Ok(event) = rx.recv() { + if inner.shortcut_recording_active.load(Ordering::SeqCst) + || hotkey_runtime_target(&inner).skip_auto_style != binding { + owner = None; continue; + } + match event { + ComboHotkeyEvent::Pressed { .. } => { + let snapshot = inner.backend.snapshot(); + owner = matches!(snapshot.dictation.phase, + openless_core::DictationPhase::Starting | openless_core::DictationPhase::Recording) + .then_some((snapshot.dictation.session_id, snapshot.preferences_revision)); + }, + ComboHotkeyEvent::Released { .. } => { + if let Some((Some(id), revision)) = owner.take() { + if inner.backend.snapshot().preferences_revision == revision { + let _ = inner.backend.toggle_dictation_style_for_session(id); + } + } + }, + } + } +} + /// Dedicated consumer thread for Esc cancellation. Not merged into /// `hotkey_bridge_loop` because the bridge serializes Pressed/Released with /// block_on (the #468/#475 latch fix): after a Hold release, `end_session` @@ -576,7 +658,7 @@ pub(super) fn less_computer_modifier_bridge_loop( // functions). HotkeyEvent::TranslationModifierPressed | HotkeyEvent::QaShortcutPressed => {} #[cfg(not(mobile))] - HotkeyEvent::TranslationShiftTapped(_) => {} + HotkeyEvent::TranslationShiftTapped(_) | HotkeyEvent::SkipAutoStyleTapped(_) => {} #[cfg(not(mobile))] HotkeyEvent::SelectionPolishShortcutPressed | HotkeyEvent::SelectionPolishShortcutReleased => {} @@ -1904,6 +1986,19 @@ pub(super) fn handle_style_pack_hotkey_pressed(inner: &Arc, pack_id: &str #[cfg(not(mobile))] pub(super) fn configure_shift_translation(inner: &Arc, monitor: &HotkeyMonitor) { let weak = Arc::downgrade(inner); + let style_weak = Arc::downgrade(inner); + monitor.set_skip_auto_style_source(Arc::new(move || { + let inner = style_weak.upgrade()?; + let target = hotkey_runtime_target(&inner); + let trigger = crate::shortcut_binding::legacy_modifier_trigger(&target.skip_auto_style)?; + let snapshot = inner.backend.snapshot(); + if !matches!(snapshot.dictation.phase, openless_core::DictationPhase::Starting | openless_core::DictationPhase::Recording) { return None; } + Some((crate::hotkey::ShiftTranslationContext { + session_id: snapshot.dictation.session_id?, + preferences_revision: snapshot.preferences_revision, + tap_count: 1, held_recording_key: None, + }, trigger)) + })); monitor.set_shift_translation_source(Arc::new(move || { let inner = weak.upgrade()?; let target = hotkey_runtime_target(&inner); @@ -2124,6 +2219,12 @@ pub(super) fn hotkey_bridge_loop(inner: Arc, rx: mpsc::Receiver { + if inner.backend.snapshot().preferences_revision == context.preferences_revision { + let _ = inner.backend.toggle_dictation_style_for_session(context.session_id); + } + } + #[cfg(not(mobile))] HotkeyEvent::TranslationShiftTapped(context) => { if inner.backend.snapshot().preferences_revision == context.preferences_revision && is_builtin_translation_shift(&hotkey_runtime_target(&inner).translation) @@ -2404,6 +2505,7 @@ pub(crate) mod less_computer_test_support { side_aware_combo: Mutex::new(None), mouse_dictation: Mutex::new(None), translation_hotkey: Mutex::new(None), + skip_auto_style_hotkey: Mutex::new(None), switch_style_hotkey: Mutex::new(None), open_app_hotkey: Mutex::new(None), quick_note_hotkey: Mutex::new(None), @@ -2729,6 +2831,9 @@ pub(crate) mod windows_less_computer_tests { inserted_chars: None, warming: true, translation: true, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: true, selection_polish: false, qa: false, diff --git a/openless-all/app/src-tauri/src/coordinator/restore_runtime.rs b/openless-all/app/src-tauri/src/coordinator/restore_runtime.rs index 804661462..908e8de1f 100644 --- a/openless-all/app/src-tauri/src/coordinator/restore_runtime.rs +++ b/openless-all/app/src-tauri/src/coordinator/restore_runtime.rs @@ -208,6 +208,7 @@ fn reconcile_hotkeys_on_main( // this also permits swapping two bindings during a restore. inner.combo_hotkey.lock().take(); inner.translation_hotkey.lock().take(); + inner.skip_auto_style_hotkey.lock().take(); inner.switch_style_hotkey.lock().take(); inner.open_app_hotkey.lock().take(); inner.quick_note_hotkey.lock().take(); @@ -290,9 +291,11 @@ fn reconcile_hotkeys_on_main( } sync_style_pack_hotkeys(inner)?; if let Some(monitor) = inner.hotkey.lock().as_ref() { + configure_shift_translation(inner, monitor); let (qa, selection, translation) = modifier_shortcut_triggers(inner); monitor.update_modifier_shortcuts(qa, selection, translation); } + update_skip_auto_style_hotkey_on_main(inner, target.skip_auto_style.clone())?; Ok(()) } diff --git a/openless-all/app/src-tauri/src/coordinator/skip_auto_style_monitor.rs b/openless-all/app/src-tauri/src/coordinator/skip_auto_style_monitor.rs new file mode 100644 index 000000000..ff5232a72 --- /dev/null +++ b/openless-all/app/src-tauri/src/coordinator/skip_auto_style_monitor.rs @@ -0,0 +1,68 @@ +//! Absolute replacement shared by settings changes and restore/rollback. +use openless_core::shared_types::ShortcutBinding; +use parking_lot::Mutex; + +pub(super) fn replace( + slot: &Mutex>, + binding: ShortcutBinding, + install: impl FnOnce(ShortcutBinding) -> Result, +) -> Result<(), E> { + let mut slot = slot.lock(); + // Drop before registration, including an installation that fails. The + // restore journal can then apply its old target through this same function. + slot.take(); + if !binding.is_unassigned() && openless_core::legacy_modifier_trigger(&binding).is_none() { + *slot = Some(install(binding)?); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{collections::BTreeSet, sync::Arc}; + + struct Registration { + key: String, + active: Arc>>, + } + impl Drop for Registration { + fn drop(&mut self) { assert!(self.active.lock().remove(&self.key)); } + } + fn combo(primary: &str) -> ShortcutBinding { + ShortcutBinding { primary: primary.into(), modifiers: vec!["ctrl".into(), "shift".into()] } + } + fn apply( + slot: &Mutex>, binding: ShortcutBinding, + active: &Arc>>, + ) -> Result<(), &'static str> { + replace(slot, binding, |binding| { + let mut keys = active.lock(); + if !keys.insert(binding.primary.clone()) { return Err("registration conflict"); } + Ok(Registration { key: binding.primary, active: active.clone() }) + }) + } + + #[test] + fn skip_auto_style_absolute_restore_replaces_clears_and_rolls_back_registrations() { + let active = Arc::new(Mutex::new(BTreeSet::new())); + let slot = Mutex::new(None); + apply(&slot, combo("A"), &active).unwrap(); + apply(&slot, combo("B"), &active).unwrap(); + assert_eq!(*active.lock(), BTreeSet::from(["B".into()])); + apply(&slot, ShortcutBinding::unassigned(), &active).unwrap(); + assert!(active.lock().is_empty()); + apply(&slot, combo("A"), &active).unwrap(); + // Another action already owns B; failed restore must release A, + // followed by the journal's absolute rollback to A. + active.lock().insert("B".into()); + assert!(apply(&slot, combo("B"), &active).is_err()); + assert!(slot.lock().is_none()); + assert_eq!(*active.lock(), BTreeSet::from(["B".into()])); + apply(&slot, combo("A"), &active).unwrap(); + assert_eq!(*active.lock(), BTreeSet::from(["A".into(), "B".into()])); + apply(&slot, ShortcutBinding { primary: "LeftCommand".into(), modifiers: vec![] }, &active).unwrap(); + assert!(slot.lock().is_none(), "modifier taps do not keep a combo registration"); + assert_eq!(*active.lock(), BTreeSet::from(["B".into()])); + } +} diff --git a/openless-all/app/src-tauri/src/hotkey.rs b/openless-all/app/src-tauri/src/hotkey.rs index 3ca3809b6..9b057eba6 100644 --- a/openless-all/app/src-tauri/src/hotkey.rs +++ b/openless-all/app/src-tauri/src/hotkey.rs @@ -28,6 +28,7 @@ use parking_lot::RwLock; mod shift_translation; use shift_translation::ShiftTranslationGesture; pub use shift_translation::{ShiftTranslationContext, ShiftTranslationSource}; +pub type SkipAutoStyleSource = Arc Option<(ShiftTranslationContext, HotkeyTrigger)> + Send + Sync>; use crate::types::HotkeyTrigger; use crate::types::{HotkeyAdapterKind, HotkeyBinding, HotkeyCapability, HotkeyInstallError}; @@ -59,6 +60,7 @@ pub enum HotkeyEvent { /// Explicit custom translation shortcut; preserves the existing arm-only behavior. TranslationModifierPressed, TranslationShiftTapped(ShiftTranslationContext), + SkipAutoStyleTapped(ShiftTranslationContext), QaShortcutPressed, SelectionPolishShortcutPressed, SelectionPolishShortcutReleased, @@ -91,6 +93,8 @@ mod tests { selection_polish_trigger_held: AtomicBool::new(true), translation_trigger: RwLock::new(None), translation_trigger_held: AtomicBool::new(true), + skip_style_source: RwLock::new(None), + skip_style_gesture: parking_lot::Mutex::new(crate::hotkey::shift_translation::ShiftTranslationGesture::default()), shift_source: RwLock::new(None), shift_gesture: parking_lot::Mutex::new( crate::hotkey::shift_translation::ShiftTranslationGesture::default(), @@ -171,6 +175,7 @@ pub trait HotkeyAdapter: Send + Sync { ); fn reset_held_state(&self); fn set_shift_translation_source(&self, _source: ShiftTranslationSource) {} + fn set_skip_auto_style_source(&self, _source: SkipAutoStyleSource) {} /// Shortcut-recording mode switch. While active the listener reports Fn press edges /// (`FnRecordingPressed`) so the frontend recorder can commit an Fn binding (the browser never /// delivers Fn keydown to the web layer). @@ -193,6 +198,8 @@ struct Shared { selection_polish_trigger_held: AtomicBool, translation_trigger: RwLock>, translation_trigger_held: AtomicBool, + skip_style_source: RwLock>, + skip_style_gesture: parking_lot::Mutex, shift_source: RwLock>, shift_gesture: parking_lot::Mutex, /// Whether shortcut recording is active (ShortcutRecorder capturing). While active the @@ -244,6 +251,10 @@ impl HotkeyMonitor { ); } + pub fn set_skip_auto_style_source(&self, source: SkipAutoStyleSource) { + self.adapter.set_skip_auto_style_source(source); + } + pub fn set_shift_translation_source(&self, source: ShiftTranslationSource) { self.adapter.set_shift_translation_source(source); } @@ -361,6 +372,8 @@ where selection_polish_trigger_held: AtomicBool::new(false), translation_trigger: RwLock::new(None), translation_trigger_held: AtomicBool::new(false), + skip_style_source: RwLock::new(None), + skip_style_gesture: parking_lot::Mutex::new(crate::hotkey::shift_translation::ShiftTranslationGesture::default()), shift_source: RwLock::new(None), shift_gesture: parking_lot::Mutex::new( crate::hotkey::shift_translation::ShiftTranslationGesture::default(), @@ -396,6 +409,7 @@ fn update_shared_binding(shared: &Shared, binding: HotkeyBinding) { } *current = binding; shared.shift_gesture.lock().reset(); + shared.skip_style_gesture.lock().reset(); } shared .trigger_held @@ -448,6 +462,7 @@ fn reset_shared_held_state(shared: &Shared) { .translation_trigger_held .store(false, std::sync::atomic::Ordering::SeqCst); shared.shift_gesture.lock().reset(); + shared.skip_style_gesture.lock().reset(); } fn held_recording_trigger(shared: &Shared) -> Option { @@ -500,6 +515,41 @@ fn observe_shift( } } +fn skip_style_context(shared: &Shared) -> Option<(ShiftTranslationContext, HotkeyTrigger)> { + // Windows modifier interception is disabled pending real hook-chain and + // menu validation. Custom combinations use the existing global registrar. + if cfg!(target_os = "windows") { return None; } + if shared.recording_active.load(std::sync::atomic::Ordering::SeqCst) { return None; } + shared.skip_style_source.read().as_ref().and_then(|source| source()) +} + +/// Observe only. Every real modifier edge must continue downstream, including +/// releases after cancellation, a binding change, or a successor session. +fn observe_skip_style( + shared: &Shared, + tx: &Sender, + key: u16, + down: bool, + other: bool, +) { + #[cfg(any(target_os = "macos", target_os = "windows"))] + let (context, target) = match skip_style_context(shared) { + Some((mut context, trigger)) => { + context.held_recording_key = platform::held_recording_key(shared); + context.tap_count = 1; + (Some(context), Some(platform::skip_style_key(trigger))) + }, + None => (None, None), + }; + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let (context, target): (Option, Option) = (None, None); + let now = Instant::now(); + let mut gesture = shared.skip_style_gesture.lock(); + if let Some(context) = gesture.observe(context, key, target == Some(key), down, other, now) { + send_or_log(tx, HotkeyEvent::SkipAutoStyleTapped(context)); + } +} + // ─────────────────────────── macOS implementation ─────────────────────────── #[cfg(not(any(target_os = "macos", target_os = "windows")))] @@ -526,7 +576,7 @@ mod platform { } #[cfg(target_os = "macos")] -mod platform { +pub(crate) mod platform { use std::ffi::c_void; use std::sync::atomic::Ordering; use std::sync::mpsc::Sender; @@ -608,9 +658,15 @@ mod platform { ); } + fn set_skip_auto_style_source(&self, source: super::SkipAutoStyleSource) { + *self.shared.skip_style_source.write() = Some(source); + self.shared.skip_style_gesture.lock().reset(); + } + fn set_shift_translation_source(&self, source: super::ShiftTranslationSource) { *self.shared.shift_source.write() = Some(source); self.shared.shift_gesture.lock().reset(); + self.shared.skip_style_gesture.lock().reset(); } fn reset_held_state(&self) { @@ -619,6 +675,7 @@ mod platform { fn set_recording_active(&self, active: bool) { self.shared.recording_active.store(active, Ordering::SeqCst); self.shared.shift_gesture.lock().reset(); + self.shared.skip_style_gesture.lock().reset(); if !active { self.shared.recording_fn_held.store(false, Ordering::SeqCst); } @@ -736,6 +793,10 @@ mod platform { fn CGEventSetIntegerValueField(event: CgEventRef, field: CgEventField, value: i64); fn CGEventTapPostEvent(proxy: *mut c_void, event: CgEventRef); fn CGEventPost(tap: CgEventTapLocation, event: CgEventRef); + #[cfg(test)] + fn CGEventCreateKeyboardEvent(source: *mut c_void, key: u16, down: bool) -> CgEventRef; + #[cfg(test)] + fn CGEventSetFlags(event: CgEventRef, flags: CgEventFlags); } #[link(name = "CoreFoundation", kind = "framework")] @@ -1009,7 +1070,8 @@ mod platform { let down = if keycode == 63 { flags & FLAG_MASK_SECONDARY_FN != 0 } else { - crate::side_aware_combo::platform::resolve_side_pressed_from_flags(keycode, flags) + device_modifier_pressed(keycode, flags) + .or_else(|| crate::side_aware_combo::platform::resolve_side_pressed_from_flags(keycode, flags)) .unwrap_or_else(|| crate::side_aware_combo::platform::keycode_is_down(keycode)) }; let handled = ask_key_edge(ctx, event, keycode, down).is_some(); @@ -1092,10 +1154,31 @@ mod platform { } pub(super) fn held_recording_key(shared: &Shared) -> Option { - super::held_recording_trigger(shared).map(|trigger| trigger_to_keycode(trigger) as u16) + crate::ask_window::hotkey::held_recording_key().or_else(|| { + super::held_recording_trigger(shared).map(|trigger| trigger_to_keycode(trigger) as u16) + }) + } + + pub(super) fn skip_style_key(trigger: HotkeyTrigger) -> u16 { + trigger_to_keycode(trigger) as u16 + } + + // Use the physical side bits on the very event being dispatched, as the + // gesture observer does. Sparse/synthetic flags retain the system query + // fallback. This also distinguishes release while the opposite side is held. + fn device_modifier_pressed(key: i64, flags: CgEventFlags) -> Option { + let (own, opposite) = match key { + 56 => (0x2, 0x4), 60 => (0x4, 0x2), + 59 => (0x1, 0x2000), 62 => (0x2000, 0x1), + 58 => (0x20, 0x40), 61 => (0x40, 0x20), + 55 => (0x8, 0x10), 54 => (0x10, 0x8), + _ => return None, + }; + (flags & (own | opposite) != 0).then_some(flags & own != 0) } fn observe_shift_event(ctx: &CallbackContext, kind: CgEventType, event: CgEventRef) { + if event.is_null() { return; } let flags = unsafe { CGEventGetFlags(event) }; let field = if matches!(kind, 25 | 26) { 3 @@ -1103,7 +1186,7 @@ mod platform { KEYBOARD_EVENT_KEYCODE }; let key = unsafe { CGEventGetIntegerValueField(event, field) }; - observe_shift_fields(ctx, kind, key, flags); + observe_shift_fields(ctx, kind, key, flags) } fn observe_shift_fields( @@ -1139,6 +1222,7 @@ mod platform { FLAGS_CHANGED => { if key == 57 { ctx.shared.shift_gesture.lock().invalidate(); + ctx.shared.skip_style_gesture.lock().invalidate(); return; } let shift = matches!(key, 56 | 60); @@ -1169,11 +1253,31 @@ mod platform { ), 22 | 27 | SYSTEM_DEFINED => { ctx.shared.shift_gesture.lock().invalidate(); + ctx.shared.skip_style_gesture.lock().invalidate(); return; } _ => return, }; super::observe_shift(&ctx.shared, &ctx.tx, key, shift, down, other); + let target = super::skip_style_context(&ctx.shared).map(|(_, trigger)| skip_style_key(trigger)); + let mut style_other = flags & (FLAG_MASK_SHIFT | FLAG_MASK_CONTROL + | FLAG_MASK_ALTERNATE | FLAG_MASK_COMMAND | FLAG_MASK_SECONDARY_FN); + for allowed in [target, held_recording_key(&ctx.shared)].into_iter().flatten() { + let (class, own, opposite) = match allowed { + 56 => (FLAG_MASK_SHIFT, 0x2, 0x4), + 60 => (FLAG_MASK_SHIFT, 0x4, 0x2), + 59 => (FLAG_MASK_CONTROL, 0x1, 0x2000), + 62 => (FLAG_MASK_CONTROL, 0x2000, 0x1), + 58 => (FLAG_MASK_ALTERNATE, 0x20, 0x40), + 61 => (FLAG_MASK_ALTERNATE, 0x40, 0x20), + 55 => (FLAG_MASK_COMMAND, 0x8, 0x10), + 54 => (FLAG_MASK_COMMAND, 0x10, 0x8), + 63 => (FLAG_MASK_SECONDARY_FN, FLAG_MASK_SECONDARY_FN, 0), + _ => continue, + }; + if flags & opposite == 0 && (flags & own != 0 || !down) { style_other &= !class; } + } + super::observe_skip_style(&ctx.shared, &ctx.tx, key, down, style_other != 0); } fn ask_key_edge(ctx: &CallbackContext, event: CgEventRef, keycode: i64, down: bool) -> Option { @@ -1535,7 +1639,7 @@ mod platform { } #[cfg(test)] - mod tests { + pub(crate) mod tests { use super::*; use parking_lot::RwLock; use std::sync::atomic::{AtomicBool, AtomicU64}; @@ -1557,6 +1661,8 @@ mod platform { selection_polish_trigger_held: AtomicBool::new(false), translation_trigger: RwLock::new(None), translation_trigger_held: AtomicBool::new(false), + skip_style_source: RwLock::new(None), + skip_style_gesture: parking_lot::Mutex::new(crate::hotkey::shift_translation::ShiftTranslationGesture::default()), shift_source: RwLock::new(None), shift_gesture: parking_lot::Mutex::new( crate::hotkey::shift_translation::ShiftTranslationGesture::default(), @@ -1566,6 +1672,103 @@ mod platform { }) } + #[test] + fn skip_auto_style_mac_passes_both_edges_and_late_releases() { + let _monitor_guard = crate::side_aware_combo::TEST_MONITOR_LOCK.blocking_lock(); + let shared = shared(HotkeyTrigger::RightOption); + let context = super::super::ShiftTranslationContext { + session_id: openless_core::SessionId::new(), + preferences_revision: 3, tap_count: 1, held_recording_key: None, + }; + *shared.skip_style_source.write() = Some(Arc::new(move || Some((context, HotkeyTrigger::LeftCommand)))); + let (ctx, rx, _) = callback_context_with_combo(shared.clone()); + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8); + assert!(rx.try_recv().is_err()); + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + assert!(matches!(rx.try_recv().unwrap(), HotkeyEvent::SkipAutoStyleTapped(c) if c.session_id == context.session_id)); + // Cmd+C and the opposite Command remain the foreground app's input. + for companion in [8, 54, 500] { + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8); + let kind = if companion == 54 { FLAGS_CHANGED } else if companion == 500 { 1 } else { KEY_DOWN }; + pass_event(&ctx, kind, companion, FLAG_MASK_COMMAND | 0x18); + pass_event(&ctx, if kind == KEY_DOWN { KEY_UP } else if kind == 1 { 2 } else { FLAGS_CHANGED }, companion, FLAG_MASK_COMMAND | 0x8); + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + assert!(rx.try_recv().is_err()); + } + // Cancelled session: the exposed down still receives its real up. + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8); + *shared.skip_style_source.write() = None; + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + assert!(rx.try_recv().is_err()); + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8); + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + assert!(rx.try_recv().is_err()); + // A successor cannot inherit a partial gesture. + *shared.skip_style_source.write() = Some(Arc::new(move || Some((context, HotkeyTrigger::LeftCommand)))); + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8); + let next = super::super::ShiftTranslationContext { + session_id: openless_core::SessionId::new(), ..context + }; + *shared.skip_style_source.write() = Some(Arc::new(move || Some((next, HotkeyTrigger::LeftCommand)))); + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + assert!(rx.try_recv().is_err()); + // Entering shortcut recording between edges preserves pairing. + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8); + shared.recording_active.store(true, Ordering::SeqCst); + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + shared.recording_active.store(false, Ordering::SeqCst); + assert!(rx.try_recv().is_err()); + } + + // Calls the real callback with native CGEvent objects. This proves the + // callback returns each original event, not OS delivery or system UI. + fn pass_event(ctx: &CallbackContext, kind: CgEventType, key: u16, flags: CgEventFlags) { + unsafe { + let event = CGEventCreateKeyboardEvent(std::ptr::null_mut(), key, kind != KEY_UP); + assert!(!event.is_null()); + CGEventSetFlags(event, flags); + CGEventSetIntegerValueField(event, SOURCE_PID_FIELD, 0); + let returned = tap_callback( + std::ptr::null_mut(), kind, event, ctx as *const _ as *mut c_void, + ); + assert_eq!(returned, event, "event kind={kind}, key={key} must pass"); + CFRelease(event as *const c_void); + } + } + + // The backend harness installs the production Ask runtime around this + // case, substituting only desktop/device effects. No Shared latch setup. + pub(crate) fn skip_auto_style_mac_held_ask_controller() { + let shared = shared(HotkeyTrigger::RightOption); + let context = super::super::ShiftTranslationContext { + session_id: openless_core::SessionId::new(), + preferences_revision: 4, tap_count: 1, held_recording_key: None, + }; + *shared.skip_style_source.write() = Some(Arc::new(move || Some((context, HotkeyTrigger::LeftCommand)))); + let (ctx, rx, _) = callback_context_with_combo(shared.clone()); + pass_event(&ctx, FLAGS_CHANGED, 61, FLAG_MASK_ALTERNATE | 0x40); + assert!(!shared.trigger_held.load(Ordering::SeqCst), "Ask bypasses the legacy latch"); + assert_eq!(crate::ask_window::hotkey::held_recording_key(), Some(61)); + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_COMMAND | 0x8 | FLAG_MASK_ALTERNATE | 0x40); + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_ALTERNATE | 0x40); + assert!(matches!(rx.try_recv().unwrap(), HotkeyEvent::SkipAutoStyleTapped(_))); + // A real Cmd+C path while the recording controller is held passes + // intact and does not become a standalone style tap. + let both = FLAG_MASK_COMMAND | 0x8 | FLAG_MASK_ALTERNATE | 0x40; + pass_event(&ctx, FLAGS_CHANGED, 55, both); + pass_event(&ctx, KEY_DOWN, 8, both); + pass_event(&ctx, KEY_UP, 8, both); + pass_event(&ctx, FLAGS_CHANGED, 55, FLAG_MASK_ALTERNATE | 0x40); + assert!(rx.try_recv().is_err()); + // Releasing the controller in the middle of a tap invalidates it. + pass_event(&ctx, FLAGS_CHANGED, 55, both); + pass_event(&ctx, FLAGS_CHANGED, 61, FLAG_MASK_COMMAND | 0x8); + pass_event(&ctx, FLAGS_CHANGED, 55, 0); + assert!(rx.try_recv().is_err()); + assert_eq!(crate::ask_window::hotkey::held_recording_key(), None); + assert!(rx.try_recv().is_err()); + } + #[test] fn mac_shift_requires_release_and_rejects_native_mouse_and_key_combinations() { let _monitor_guard = crate::side_aware_combo::TEST_MONITOR_LOCK.blocking_lock(); @@ -2184,9 +2387,15 @@ mod platform { ); } + fn set_skip_auto_style_source(&self, source: super::SkipAutoStyleSource) { + *self.shared.skip_style_source.write() = Some(source); + self.shared.skip_style_gesture.lock().reset(); + } + fn set_shift_translation_source(&self, source: super::ShiftTranslationSource) { *self.shared.shift_source.write() = Some(source); self.shared.shift_gesture.lock().reset(); + self.shared.skip_style_gesture.lock().reset(); } fn reset_held_state(&self) { @@ -2196,6 +2405,7 @@ mod platform { fn set_recording_active(&self, active: bool) { self.shared.recording_active.store(active, Ordering::SeqCst); self.shared.shift_gesture.lock().reset(); + self.shared.skip_style_gesture.lock().reset(); } fn shutdown(&self) { @@ -2325,11 +2535,13 @@ mod platform { 0x020B | 0x020C => (503, wparam.0 == 0x020B), 0x020A | 0x020E => { ctx.shared.shift_gesture.lock().invalidate(); + ctx.shared.skip_style_gesture.lock().invalidate(); return CallNextHookEx(None, code, wparam, lparam); } _ => return CallNextHookEx(None, code, wparam, lparam), }; super::observe_shift(&ctx.shared, &ctx.tx, key, false, down, false); + super::observe_skip_style(&ctx.shared, &ctx.tx, key, down, false); } } // Observation only: never consume mouse combinations belonging to another application. @@ -2390,6 +2602,10 @@ mod platform { super::held_recording_trigger(shared).map(|trigger| trigger_to_vk_code(trigger) as u16) } + pub(super) fn skip_style_key(trigger: HotkeyTrigger) -> u16 { + trigger_to_vk_code(trigger) as u16 + } + fn dispatch_keyboard_event(ctx: &CallbackContext, vk_code: u32, message: usize) -> bool { // Shortcut recording receives real keyboard events in the frontend; the main // dictation/Agent hooks must not swallow keys. @@ -2424,6 +2640,15 @@ mod platform { pressed, other, ); + let target = super::skip_style_context(&ctx.shared).map(|(_, trigger)| skip_style_key(trigger)); + let controller = held_recording_key(&ctx.shared); + let style_other = unsafe { + use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; + [VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU, VK_LWIN, VK_RWIN, VK_LSHIFT, VK_RSHIFT, 1, 2, 4, 5, 6] + .into_iter().any(|key| Some(key as u16) != target && Some(key as u16) != controller + && GetAsyncKeyState(key as i32) < 0) + }; + super::observe_skip_style(&ctx.shared, &ctx.tx, vk_code as u16, pressed, style_other); if vk_code == VK_ESCAPE && super::capsule_menu_open() { return false; @@ -2649,6 +2874,8 @@ mod platform { selection_polish_trigger_held: AtomicBool::new(false), translation_trigger: RwLock::new(None), translation_trigger_held: AtomicBool::new(false), + skip_style_source: RwLock::new(None), + skip_style_gesture: parking_lot::Mutex::new(crate::hotkey::shift_translation::ShiftTranslationGesture::default()), shift_source: RwLock::new(None), shift_gesture: parking_lot::Mutex::new( crate::hotkey::shift_translation::ShiftTranslationGesture::default(), @@ -2841,6 +3068,38 @@ mod platform { ); } + #[test] + fn skip_auto_style_windows_modifier_fallback_never_consumes_or_toggles() { + let _monitor_guard = crate::side_aware_combo::TEST_MONITOR_LOCK.blocking_lock(); + let shared = shared(HotkeyTrigger::RightControl); + let context = super::super::ShiftTranslationContext { + session_id: openless_core::SessionId::new(), preferences_revision: 1, + tap_count: 1, held_recording_key: None, + }; + *shared.skip_style_source.write() = Some(Arc::new(move || Some((context, HotkeyTrigger::LeftOption)))); + let (ctx, rx, _) = callback_context_with_combo(shared.clone()); + assert!(!dispatch_keyboard_event(&ctx, VK_LMENU, WM_SYSKEYDOWN)); + assert!(!dispatch_keyboard_event(&ctx, VK_LMENU, WM_SYSKEYUP)); + assert!(rx.try_recv().is_err()); + // Alt+letter, Alt+Tab, AltGr, and late releases all use stock input. + for companion in [0x43, 0x09, VK_RMENU] { + for (key, message) in [(VK_LMENU, WM_SYSKEYDOWN), + (companion, WM_SYSKEYDOWN), (companion, WM_SYSKEYUP), + (VK_LMENU, WM_SYSKEYUP)] { + assert!(!dispatch_keyboard_event(&ctx, key, message)); + } + assert!(rx.try_recv().is_err()); + } + assert!(!dispatch_keyboard_event(&ctx, VK_RMENU, WM_SYSKEYDOWN)); + assert!(!dispatch_keyboard_event(&ctx, VK_RMENU, WM_SYSKEYUP)); + assert!(rx.try_recv().is_err()); + shared.skip_style_gesture.lock().reset(); + assert!(!dispatch_keyboard_event(&ctx, VK_LMENU, WM_SYSKEYDOWN)); + *shared.skip_style_source.write() = None; + assert!(!dispatch_keyboard_event(&ctx, VK_LMENU, WM_SYSKEYUP)); + assert!(rx.try_recv().is_err()); + } + #[test] fn windows_release_carries_combo_verdict_even_when_abort_bridge_has_not_drained() { let _monitor_guard = crate::side_aware_combo::TEST_MONITOR_LOCK.blocking_lock(); diff --git a/openless-all/app/src-tauri/src/lib.rs b/openless-all/app/src-tauri/src/lib.rs index d884d3ed0..01304ce70 100644 --- a/openless-all/app/src-tauri/src/lib.rs +++ b/openless-all/app/src-tauri/src/lib.rs @@ -249,6 +249,8 @@ macro_rules! app_invoke_handler_desktop { commands::get_dictation_translation_target, commands::select_dictation_translation_target, commands::set_capsule_language_menu, + #[cfg(not(mobile))] + commands::set_capsule_style_menu, commands::get_settings, commands::get_settings_snapshot, commands::get_voice_activation_state, @@ -356,6 +358,8 @@ macro_rules! app_invoke_handler_desktop { commands::list_vocab_presets, commands::save_vocab_presets, commands::start_dictation, + commands::get_dictation_style_target, + commands::update_dictation_style, commands::stop_dictation, commands::cancel_dictation, commands::start_voice_edit_session, @@ -456,6 +460,7 @@ macro_rules! app_invoke_handler_desktop { commands::validate_shortcut_binding, commands::set_dictation_hotkey, commands::set_translation_hotkey, + commands::set_skip_auto_style_hotkey, commands::set_switch_style_hotkey, commands::set_open_app_hotkey, commands::set_quick_note_hotkey, @@ -1169,6 +1174,7 @@ fn run_desktop() { coordinator.stop_coding_agent_hotkey_listener(); coordinator.stop_combo_hotkey_listener(); coordinator.stop_translation_hotkey_listener(); + coordinator.stop_skip_auto_style_hotkey_listener(); coordinator.stop_switch_style_hotkey_listener(); coordinator.stop_open_app_hotkey_listener(); coordinator.stop_quick_note_hotkey_listener(); diff --git a/openless-all/app/src-tauri/src/native_capsule.rs b/openless-all/app/src-tauri/src/native_capsule.rs index 45161a4f3..664cabea7 100644 --- a/openless-all/app/src-tauri/src/native_capsule.rs +++ b/openless-all/app/src-tauri/src/native_capsule.rs @@ -339,6 +339,9 @@ impl NativeCapsule { text: payload.message.clone().unwrap_or_default(), audio_level: (!payload.warming).then_some(payload.level), translation_active: payload.translation, + skip_auto_style: payload.skip_auto_style, + style_pack_id: payload.style_pack_id.clone(), + style_pack_name: payload.style_pack_name.clone(), style: style.into(), warming: payload.warming && payload.state == CapsuleState::Recording, operating: payload.operating, diff --git a/openless-all/app/src-tauri/src/tauri_events.rs b/openless-all/app/src-tauri/src/tauri_events.rs index 75843ffed..e4b423581 100644 --- a/openless-all/app/src-tauri/src/tauri_events.rs +++ b/openless-all/app/src-tauri/src/tauri_events.rs @@ -327,6 +327,9 @@ async fn forward_legacy_event( .then(|| "正在准备语音…".to_string()), inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: true, warming: *phase == LessComputerVoicePhase::Starting, capsule_style: backend.get_preferences().capsule_style, @@ -396,6 +399,9 @@ async fn forward_legacy_event( message: None, inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, // First PCM frame proves capture is live (mirrors QA / Less Computer). warming: false, @@ -577,6 +583,9 @@ fn map_dictation_state( message, inserted_chars: None, translation: snapshot.translation_active, + skip_auto_style: snapshot.skip_auto_style, + style_pack_id: snapshot.style_pack_id, + style_pack_name: snapshot.style_pack_name, operating: false, warming: matches!( snapshot.phase, @@ -667,6 +676,9 @@ fn transcription_notice_payload( message: Some(message.to_string()), inserted_chars: None, translation: dictation.translation_active, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating, warming: false, capsule_style: style, @@ -784,6 +796,9 @@ fn mobile_qa_capsule_payload( }), inserted_chars: None, translation: false, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, operating: false, // Core announces Recording before native startup completes; only a // real PCM level proves the microphone is ready, including level zero. @@ -1505,6 +1520,9 @@ mod tests { message: Some("fixture".to_string()), translation_active: true, recording_ready: phase != DictationPhase::Starting, + skip_auto_style: false, + style_pack_id: None, + style_pack_name: None, }, CapsuleStyle::Classic, ); diff --git a/openless-all/app/src/lib/ipc/dictation.ts b/openless-all/app/src/lib/ipc/dictation.ts index 84141c33d..4c0aeea88 100644 --- a/openless-all/app/src/lib/ipc/dictation.ts +++ b/openless-all/app/src/lib/ipc/dictation.ts @@ -1,7 +1,7 @@ import { previewHistory } from '../../preview/history'; import { isDesktop } from './platform-exports'; import { invokeOrMock, isTauriNow, platformCapabilities, requireBackendReady } from './shared'; -import type { CapsuleSnapshot } from '../types'; +import type { CapsuleSnapshot, DictationStyleSelection, DictationStyleTarget } from '../types'; export function startDictation(): Promise { return invokeOrMock('start_dictation', undefined, () => { @@ -10,11 +10,15 @@ export function startDictation(): Promise { } export function stopDictation(sessionId?: string): Promise { - return invokeOrMock('stop_dictation', sessionId ? { sessionId } : undefined, () => previewHistory.stopRecording()); + return invokeOrMock('stop_dictation', sessionId ? { sessionId } : undefined, () => + previewHistory.stopRecording(), + ); } export function cancelDictation(sessionId?: string): Promise { - return invokeOrMock('cancel_dictation', sessionId ? { sessionId } : undefined, () => previewHistory.cancelRecording()); + return invokeOrMock('cancel_dictation', sessionId ? { sessionId } : undefined, () => + previewHistory.cancelRecording(), + ); } export async function setCapsuleTranscriptVisible(visible: boolean): Promise { @@ -64,6 +68,19 @@ export function getDictationTranslationTarget(): Promise null); } +export function getDictationStyleTarget(): Promise { + return invokeOrMock('get_dictation_style_target', undefined, () => null); +} + +export function updateDictationStyle( + sessionId: string, + selection: DictationStyleSelection, +): Promise { + return invokeOrMock('update_dictation_style', { sessionId, selection }, () => { + throw new Error('No active native recording'); + }); +} + export function selectDictationTranslationTarget( sessionId: string, targetLanguage: string, @@ -77,3 +94,8 @@ export function selectDictationTranslationTarget( export function setCapsuleLanguageMenu(open: boolean, sessionId: string): Promise { return invokeOrMock('set_capsule_language_menu', { open, sessionId }, () => undefined); } + +/** Shares native headroom and session-bound close with the language popup. */ +export function setCapsuleStyleMenu(open: boolean, sessionId: string): Promise { + return invokeOrMock('set_capsule_style_menu', { open, sessionId }, () => undefined); +} diff --git a/openless-all/app/src/lib/ipc/hotkeys.ts b/openless-all/app/src/lib/ipc/hotkeys.ts index e8629a408..6be27389d 100644 --- a/openless-all/app/src/lib/ipc/hotkeys.ts +++ b/openless-all/app/src/lib/ipc/hotkeys.ts @@ -93,6 +93,15 @@ export function setTranslationHotkey(binding: ShortcutBinding | null): Promise { + return invokeOrMock('set_skip_auto_style_hotkey', { binding }, () => { + mockSetSettings({ + ...mockSettings, + skipAutoStyleHotkey: binding ?? { primary: '', modifiers: [] }, + }); + }); +} + // binding = null disables (clears the global key). export function setSwitchStyleHotkey(binding: ShortcutBinding | null): Promise { return invokeOrMock('set_switch_style_hotkey', { binding }, () => undefined); diff --git a/openless-all/app/src/lib/ipc/index.ts b/openless-all/app/src/lib/ipc/index.ts index c8d0ebce9..ffd9a062c 100644 --- a/openless-all/app/src/lib/ipc/index.ts +++ b/openless-all/app/src/lib/ipc/index.ts @@ -102,6 +102,9 @@ export { getCapsuleSnapshot, setCapsuleTranscriptVisible, handleWindowHotkeyEvent, + getDictationStyleTarget, + updateDictationStyle, + setCapsuleStyleMenu, } from './dictation'; // style-packs @@ -146,6 +149,7 @@ export { setDictationHotkey, setSelectionPolishHotkey, setTranslationHotkey, + setSkipAutoStyleHotkey, setSwitchStyleHotkey, setOpenAppHotkey, setQuickNoteHotkey, diff --git a/openless-all/app/src/lib/ipc/mock-data.ts b/openless-all/app/src/lib/ipc/mock-data.ts index c2b0da3b4..504129f41 100644 --- a/openless-all/app/src/lib/ipc/mock-data.ts +++ b/openless-all/app/src/lib/ipc/mock-data.ts @@ -94,6 +94,16 @@ export let mockSettings: UserPreferences = { outputLanguagePreference: 'auto', qaSaveHistory: false, customComboHotkey: null, + skipAutoStyleHotkey: { + primary: + typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) + ? 'LeftCommand' + : typeof navigator !== 'undefined' && /Win/.test(navigator.platform) + ? '' + : 'LeftAlt', + modifiers: [], + }, + skipAutoStylePickerEnabled: false, translationHotkey: { primary: 'Shift', modifiers: [] }, switchStyleHotkey: { primary: 'S', diff --git a/openless-all/app/src/lib/types.ts b/openless-all/app/src/lib/types.ts index bbb87ac0f..7286a588b 100644 --- a/openless-all/app/src/lib/types.ts +++ b/openless-all/app/src/lib/types.ts @@ -541,6 +541,8 @@ export interface UserPreferences { customComboHotkey: ComboBinding | null; /** Global hotkey to trigger translation while recording. Default Shift. */ translationHotkey: ShortcutBinding; + skipAutoStyleHotkey: ShortcutBinding; + skipAutoStylePickerEnabled: boolean; /** Global hotkey to switch to the previous polish style. null = disabled by user (issue #576). */ switchStyleHotkey: ShortcutBinding | null; /** Global hotkey to open the OpenLess main window. null = disabled by user (issue #576). */ @@ -867,6 +869,9 @@ export interface CapsulePayload { insertedChars: number | null; /** Whether the current session is in translation mode (the user pressed Shift). See issue #4. */ translation: boolean; + skipAutoStyle?: boolean; + stylePackId?: string | null; + stylePackName?: string | null; /** Whether this is a Less Computer session: the processing label shows "using" instead of "thinking". */ operating?: boolean; /** @@ -945,3 +950,17 @@ export interface PlatformCapabilities { supportsAutoUpdate: boolean; supportsVoiceEdit: boolean; } + +export type DictationStyleSelection = + { mode: 'automatic' } | { mode: 'skipAuto' } | { mode: 'stylePack'; stylePackId: string }; + +export interface DictationStyleTarget { + sessionId: string; + selection: DictationStyleSelection; + skipAutoStyle: boolean; + stylePackId: string | null; + stylePackName: string | null; + polishStylePackId: string | null; + availableStyles: StylePack[]; + mutable: boolean; +} diff --git a/openless-all/harmony/ipc-audit.json b/openless-all/harmony/ipc-audit.json index 227256c39..84ca3eecb 100644 --- a/openless-all/harmony/ipc-audit.json +++ b/openless-all/harmony/ipc-audit.json @@ -1,8 +1,8 @@ { "scope": "Static shared IPC and runtime adapter command coverage; excludes event subscriptions and dynamic command names.", - "total": 190, + "total": 194, "wired": 108, - "missing": 82, + "missing": 86, "commands": [ { "name": "accept_pending_correction", @@ -480,6 +480,13 @@ ], "implementation": "rust" }, + { + "name": "get_dictation_style_target", + "calledFrom": [ + "src/lib/ipc/dictation.ts" + ], + "implementation": "unimplemented" + }, { "name": "get_dictation_translation_target", "calledFrom": [ @@ -1047,6 +1054,13 @@ ], "implementation": "unimplemented" }, + { + "name": "set_capsule_style_menu", + "calledFrom": [ + "src/lib/ipc/dictation.ts" + ], + "implementation": "unimplemented" + }, { "name": "set_capsule_transcript_visible", "calledFrom": [ @@ -1145,6 +1159,13 @@ ], "implementation": "unimplemented" }, + { + "name": "set_skip_auto_style_hotkey", + "calledFrom": [ + "src/lib/ipc/hotkeys.ts" + ], + "implementation": "unimplemented" + }, { "name": "set_style_enabled", "calledFrom": [ @@ -1286,6 +1307,13 @@ ], "implementation": "arkts" }, + { + "name": "update_dictation_style", + "calledFrom": [ + "src/lib/ipc/dictation.ts" + ], + "implementation": "unimplemented" + }, { "name": "update_setting_fields", "calledFrom": [ diff --git a/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch b/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch index f7b475b27..1ea3b4093 100644 --- a/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch +++ b/openless-all/ios/CoreHost/Patches/ios-input-contracts.patch @@ -189,7 +189,7 @@ diff --git a/crates/openless-core/src/api.rs b/crates/openless-core/src/api.rs + ..Default::default() + }; + let reservation = -+ self.reserve_dictation_session(insert_text, options.output_target, None)?; ++ self.reserve_dictation_session(&options, None)?; + self.start_reserved_dictation_with_raw_provider( + reservation, + options, @@ -283,8 +283,8 @@ diff --git a/crates/openless-core/src/api.rs b/crates/openless-core/src/api.rs &self, options: &DictationStartOptions, @@ -10480,6 +10700,11 @@ - .style_packs - .get_for_dictation(assigned_ids.iter().map(String::as_str), active_id)?; + assigned_ids.iter().map(String::as_str), active_id, &preferences.active_style_pack_id, + )?; let mut captured_options = options.clone(); + if let Some(target) = &options.translation_target_language { + captured_options.translation_target_language = Some( @@ -989,21 +989,23 @@ diff --git a/crates/openless-core/src/cloud_sync_e2ee_documents/tests.rs b/crate diff --git a/crates/openless-core/src/dictation_context.rs b/crates/openless-core/src/dictation_context.rs --- a/crates/openless-core/src/dictation_context.rs +++ b/crates/openless-core/src/dictation_context.rs -@@ -44,6 +44,9 @@ +@@ -44,7 +44,10 @@ #[derive(Debug, Clone, PartialEq, Eq)] pub struct DictationStartOptions { pub translation_requested: bool, + /// Configured target for this session only; None uses the legacy selected target. + /// Selecting a target does not request translation or enable any provider. + pub translation_target_language: Option, + pub skip_auto_style: bool, pub audio_source: DictationAudioSource, pub insert_text: bool, pub output_target: DictationOutputTarget, -@@ -56,6 +59,7 @@ +@@ -56,7 +59,8 @@ fn default() -> Self { Self { translation_requested: false, + translation_target_language: None, + skip_auto_style: false, audio_source: DictationAudioSource::Microphone, insert_text: true, output_target: DictationOutputTarget::ForegroundApp,