From 4c6c807a836a30eb6dddbef0686c7da65f6ec469 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:22:10 +0800 Subject: [PATCH 01/13] feat(capsule): own style picker requests and native menu keys --- .../capsule-style-menu-host-contract.test.mjs | 65 ++ .../shared-backend-wire-contract.test.mjs | 6 +- .../backend-tests/tests/capsule_style_menu.rs | 61 ++ .../backend-tests/tests/translation_hotkey.rs | 8 + .../app/src-tauri/src/capsule_style_menu.rs | 563 ++++++++++++++++++ .../app/src-tauri/src/commands/dictation.rs | 32 +- openless-all/app/src-tauri/src/coordinator.rs | 7 + .../src-tauri/src/coordinator/hotkey_loops.rs | 4 +- .../src-tauri/src/coordinator/style_menu.rs | 106 ++++ openless-all/app/src-tauri/src/hotkey.rs | 131 ++++ openless-all/app/src-tauri/src/lib.rs | 8 + openless-all/app/src-tauri/src/selection.rs | 14 +- .../src-tauri/src/tauri_coordinator_host.rs | 177 +++++- 13 files changed, 1163 insertions(+), 19 deletions(-) create mode 100644 openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs create mode 100644 openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs create mode 100644 openless-all/app/src-tauri/src/capsule_style_menu.rs create mode 100644 openless-all/app/src-tauri/src/coordinator/style_menu.rs diff --git a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs new file mode 100644 index 000000000..e45f9bc22 --- /dev/null +++ b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +const read = (name) => readFile(new URL(`../src-tauri/src/${name}`, import.meta.url), 'utf8'); +const [commands, lib, hotkeys, loops, bridge, host, menu, selection] = await Promise.all([ + read('commands/dictation.rs'), read('lib.rs'), read('hotkey.rs'), + read('coordinator/hotkey_loops.rs'), read('coordinator/style_menu.rs'), + read('tauri_coordinator_host.rs'), read('capsule_style_menu.rs'), read('selection.rs'), +]); +assert.match(lib, /commands::get_capsule_style_menu_request/); +assert.match(commands, /pub fn get_capsule_style_menu_request[^]*?capsule_label\(window.label\(\)\)/); +assert.match(commands, /pub async fn set_capsule_style_menu[^]*?request_id: Option,[^]*?menu_id: Option/); +assert.match(commands, /capsule\.set_style_menu_open\(label, session_id, open, request_id, menu_id\)/); +const programmatic = commands.slice(commands.indexOf('pub fn update_dictation_style'), commands.indexOf('pub async fn start_dictation')); +assert.doesNotMatch(programmatic, /hotkey_toggled|handle_skip_auto_style_hotkey/); +assert.equal((loops.match(/handle_skip_auto_style_hotkey\(&inner, /g) ?? []).length, 2, + 'modifier and custom-combination hotkeys share one provenance boundary'); +assert.match(bridge, /toggle_dictation_style_for_session\(session_id\)[^]*?menu::hotkey_toggled\(&target\)/); +assert.match(bridge, /DictationPhase::Starting \| openless_core::DictationPhase::Recording/); +assert.match(bridge, /DictationOutputTarget::AskComposer[^]*?DictationOutputTarget::Qa[^]*?DictationOutputTarget::VoiceEdit/); +assert.match(bridge, /mutable: target.mutable && surface_available/); +assert.match(host, /payload.state == CapsuleState::Recording && !payload.qa && !payload.selection_polish/); +assert.match(bridge, /capsule_menu_input_target_is_current\(target\)/); +assert.match(bridge, /capture_capsule_menu_input_target\(\)/); +assert.match(selection, /pub\(crate\) fn capture_capsule_menu_input_target[^]*?target.strict_input_target = true/); +assert.match(menu, /keyboard_available: c.keyboard_available && c.focus.is_some\(\)/); +assert.match(menu, /target.selection != DictationStyleSelection::SkipAuto/); +assert.match(menu, /c\.picker_enabled && c\.skip_auto/); +assert.match(menu, /label == "capsule"/); +for (const event of ['request', 'key', 'closed']) { + assert.match(host, new RegExp(`emit_to\\([^;]*"capsule:style-menu-${event}"`)); +} +assert.doesNotMatch(host, /\.emit\("capsule:style-menu-/); +assert.match(host, /style_menu_id\.as_deref\(\) == style_menu_id/); +assert.match(host, /let translation_menu = style_menu_id.is_none\(\)/); +assert.match(host, /set_capsule_menu_open\(translation_menu\)/); +assert.match(host, /menu_id\.ok_or\("capsule_style_menu_owner_required"\)/); +const reserve = host.slice(host.indexOf('pub(crate) fn set_style_menu_open'), host.indexOf('fn restore_style_menu_owner')); +assert.ok(reserve.indexOf('reserve_picker_geometry(') < reserve.indexOf('menu::commit('), + 'native geometry must succeed before committing input ownership'); +assert.match(host, /payload\.state != CapsuleState::Recording \|\| payload\.selection_polish \|\| !style_session_current/); +assert.match(host, /else \{ payload.state != CapsuleState::Recording \|\| !payload.translation \}/); +assert.match(host, /from_millis\(75\)/, 'foreground/window invalidation must also run without new key input'); +assert.match(lib, /WindowEvent::Destroyed[^]*?capsule_style_menu::window_lost\(&label\)/); +const mac = hotkeys.slice(hotkeys.indexOf('extern "C" fn tap_callback'), hotkeys.indexOf('fn device_modifier_pressed')); +assert.ok(mac.indexOf('capsule_style_menu::key(') < mac.indexOf('ask_key_edge(')); +assert.match(mac, /FLAG_MASK_SHIFT \| FLAG_MASK_CONTROL[^]*?FLAG_MASK_ALTERNATE \| FLAG_MASK_COMMAND/); +assert.match(mac, /fn_is_held\(\)[^]*?keycode_is_down\(63\)/); +const windows = hotkeys.slice(hotkeys.indexOf('unsafe extern "system" fn low_level_keyboard_proc'), hotkeys.indexOf('unsafe fn callback_context')); +assert.ok(windows.indexOf('capsule_style_menu::key(') < windows.indexOf('match keyboard_edge(')); +assert.match(windows, /keyboard.flags.0 & INJECTED == 0/); +assert.match(windows, /GetAsyncKeyState\(vk_code as i32\) < 0/); +assert.match(windows, /match \(vk_code, extended\)/); +assert.match(windows, /\(0x26, true\)/); +assert.match(windows, /\(0x28, true\)/); +assert.match(windows, /\(0x0D, false\)/); +assert.match(hotkeys, /TAP_DISABLED_BY_TIMEOUT \| TAP_DISABLED_BY_USER_INPUT => \{\s*crate::capsule_style_menu::invalidate\(\)/); +for (const key of ['VK_LCONTROL', 'VK_RCONTROL', 'VK_LMENU', 'VK_RMENU', 'VK_LWIN', 'VK_RWIN', 'VK_LSHIFT', 'VK_RSHIFT']) { + assert.ok(windows.includes(key), `Windows modified input must include ${key}`); +} +assert.match(menu, /return press.captured/, 'physical release ownership survives menu lifetime'); +assert.match(menu, /Some\(&event.menu_id\) == press.menu_id.as_ref\(\)/, + 'a captured repeat cannot migrate into a new menu owner'); +assert.match(menu, /prepared.focus == c.focus && owner.keyboard_available == c.keyboard_available/, + 'geometry completion must recheck the prepared input target and capability'); +console.log('capsule-style-menu-host-contract.test.mjs passed'); 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 2a1f2c439..4316ff435 100644 --- a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs +++ b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs @@ -804,11 +804,11 @@ assert.match( /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(coordinatorHotkeys, /handle_skip_auto_style_hotkey\(&inner, context\.session_id\)/); +assert.match(styleCommand, /set_capsule_picker_menu_impl\(window, coord, session_id, open, true, request_id, menu_id\)/); assert.match( styleCommand, - /set_capsule_picker_menu_impl\(window, coord, session_id, open, false\)/, + /set_capsule_picker_menu_impl\(window, coord, session_id, open, false, None, None\)/, ); console.log('shared-backend-wire-contract.test.mjs passed'); diff --git a/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs b/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs new file mode 100644 index 000000000..314141082 --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs @@ -0,0 +1,61 @@ +//! Production picker protocol plus a real Core session, without native UI/audio. +#![allow(dead_code)] +#[path = "../../src/capsule_style_menu.rs"] +mod capsule_style_menu; + +#[tokio::test] +async fn ordinary_skip_start_and_programmatic_switch_never_create_hotkey_open_intent() { + use std::sync::Arc; + use capsule_style_menu as menu; + use openless_core::{BackendConfig, BackendDependencies, DictationStartOptions, + DictationStyleSelection as Selection, OpenLessBackend}; + let directory = tempfile::tempdir().unwrap(); + let mut dependencies = BackendDependencies::unsupported(); + dependencies.host_actions = Arc::new(openless_core::testing::RecordingHostActions::default()); + dependencies.dictation_engine = Arc::new(openless_core::testing::FixtureDictationEngine::successful("", "")); + dependencies.text_inserter = Arc::new(openless_core::testing::FixtureTextInserter::with_outcome( + openless_core::InsertOutcome::Inserted, + )); + let backend = Arc::new(OpenLessBackend::new(BackendConfig { + data_dir: directory.path().to_owned(), ..Default::default() + }, dependencies).unwrap()); + backend.start().await.unwrap(); + let mut prefs = backend.get_preferences(); + prefs.skip_auto_style_picker_enabled = true; + backend.update_settings(prefs, openless_core::SettingsUpdateOptions::STRICT, + &openless_core::NoopSettingsRuntime).unwrap(); + let source = Arc::downgrade(&backend); + menu::configure(Arc::new(move || { + let core = source.upgrade()?; + if !matches!(core.snapshot().dictation.phase, openless_core::DictationPhase::Starting + | openless_core::DictationPhase::Recording) { return None; } + let target = core.dictation_style_target()?; + Some(menu::Context { session_id: target.session_id, mutable: target.mutable, + skip_auto: target.skip_auto_style, picker_enabled: true, keyboard_available: true, + focus: Some(menu::Focus(1, 1)), blocked_keys: [false; 4] }) + }), Arc::new(|_| true)); + let session = backend.start_dictation_with_options(DictationStartOptions { + skip_auto_style: true, ..Default::default() + }).await.unwrap(); + menu::refresh(); + assert!(backend.dictation_style_target().unwrap().skip_auto_style); + assert!(menu::pending("capsule").is_none(), "ordinary skipAuto start has no hotkey provenance"); + backend.update_dictation_style(session, Selection::Automatic).unwrap(); + backend.update_dictation_style(session, Selection::SkipAuto).unwrap(); + menu::refresh(); + assert!(menu::pending("capsule").is_none(), "programmatic switches have no hotkey provenance"); + let automatic = backend.toggle_dictation_style_for_session(session).unwrap(); + assert!(menu::hotkey_toggled(&automatic).is_none()); + let skipped = backend.toggle_dictation_style_for_session(session).unwrap(); + let request = menu::hotkey_toggled(&skipped).unwrap(); + let owner = menu::reservation("capsule", session, Some(&request.request_id)).unwrap(); + menu::commit(owner.clone(), Some(&request.request_id)).unwrap(); + assert!(menu::owner_current(&owner)); + backend.cancel_dictation(Some(session)).await.unwrap(); + menu::refresh(); + assert!(!menu::owner_current(&owner)); + assert!(menu::pending("capsule").is_none()); + menu::invalidate(); + menu::configure(Arc::new(|| None), Arc::new(|_| false)); + backend.shutdown().await.unwrap(); +} 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 2ad6bd6eb..d8a44f7f7 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 @@ -57,6 +57,8 @@ mod hotkey; mod recording_companion; #[path = "../../src/side_aware_combo.rs"] mod side_aware_combo; +#[path = "../../src/capsule_style_menu.rs"] +mod capsule_style_menu; #[cfg(target_os = "macos")] #[tokio::test] @@ -71,3 +73,9 @@ async fn skip_auto_style_held_recording_key_uses_real_ask_keyboard_route() { hotkey::platform::tests::skip_auto_style_mac_held_ask_controller(); // Drop desktop: subsequent cases revert to the stock route. } + +#[cfg(target_os = "macos")] +#[test] +fn style_menu_native_callback_preserves_key_pairs_across_open_close_and_cancel() { + hotkey::platform::tests::style_menu_real_callback_preserves_key_pairs_across_open_close_and_cancel(); +} diff --git a/openless-all/app/src-tauri/src/capsule_style_menu.rs b/openless-all/app/src-tauri/src/capsule_style_menu.rs new file mode 100644 index 000000000..217de51ef --- /dev/null +++ b/openless-all/app/src-tauri/src/capsule_style_menu.rs @@ -0,0 +1,563 @@ +//! Session-bound picker intent and keyboard ownership. No window activation or +//! synthetic input: a captured down is drained with its own physical release. +use std::sync::{Arc, OnceLock}; +use parking_lot::{Mutex, RwLock}; +use openless_core::{DictationStyleSelection, DictationStyleTarget, SessionId}; +use serde::Serialize; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Request { + pub session_id: SessionId, + pub request_id: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Owner { + pub session_id: SessionId, + pub menu_id: String, + pub window_label: String, + pub keyboard_available: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub(crate) enum Key { ArrowUp, ArrowDown, Enter, Escape } + +impl Key { + fn index(self) -> usize { + match self { Self::ArrowUp => 0, Self::ArrowDown => 1, Self::Enter => 2, Self::Escape => 3 } + } + pub(crate) fn from_primary(primary: &str) -> Option { + match primary.trim().to_ascii_lowercase().as_str() { + "arrowup" | "up" => Some(Self::ArrowUp), + "arrowdown" | "down" => Some(Self::ArrowDown), + "enter" | "return" => Some(Self::Enter), + "escape" | "esc" => Some(Self::Escape), + _ => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct KeyEvent { + pub session_id: SessionId, + pub menu_id: String, + pub key: Key, + pub repeat: bool, + #[serde(skip)] + pub window_label: String, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ClosedEvent { + pub session_id: SessionId, + pub menu_id: String, + #[serde(skip)] + pub window_label: String, +} +pub(crate) enum Event { Request(Request), Key(KeyEvent), Closed(ClosedEvent), Validate(Owner) } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Focus(pub u64, pub u64); + +#[derive(Clone)] +pub(crate) struct Context { + pub session_id: SessionId, + pub mutable: bool, + pub skip_auto: bool, + pub picker_enabled: bool, + pub keyboard_available: bool, + pub focus: Option, + pub blocked_keys: [bool; 4], +} + +pub(crate) fn blocked_keys(target: &openless_core::HotkeyRuntimeTarget) -> [bool; 4] { + let mut blocked = [false; 4]; + for binding in [ + Some(&target.dictation), Some(&target.translation), Some(&target.skip_auto_style), + target.qa.as_ref(), target.quick_note.as_ref(), target.switch_style.as_ref(), + target.open_app.as_ref(), target.selection_polish.as_ref(), + target.coding_agent_voice.as_ref(), target.coding_agent_panel.as_ref(), + target.coding_agent_quick.as_ref(), + ].into_iter().flatten().chain(target.style_packs.iter().map(|item| &item.binding)) { + if binding.modifiers.is_empty() { + if let Some(key) = Key::from_primary(&binding.primary) { blocked[key.index()] = true; } + } + } + blocked +} + +struct Pending { request: Request, focus: Option } +struct Active { owner: Owner, request_id: Option, focus: Option } +struct Prepared { owner: Owner, focus: Option } +#[derive(Default, Clone)] +struct Press { down: bool, captured: bool, menu_id: Option } + +#[derive(Default)] +pub(crate) struct State { + serial: u64, + pending: Option, + active: Option, + prepared: Option, + presses: [Press; 4], + closed: Vec, +} + +impl State { + fn revoke(&mut self) { + if let Some(active) = self.active.take() { + self.closed.push(ClosedEvent { session_id: active.owner.session_id, + menu_id: active.owner.menu_id, window_label: active.owner.window_label }); + } + } + fn next_id(&mut self) -> String { + self.serial = self.serial.checked_add(1).expect("style menu sequence exhausted"); + self.serial.to_string() + } + fn reconcile(&mut self, context: Option<&Context>) { + if self.prepared.as_ref().is_some_and(|prepared| !context.is_some_and(|c| + c.session_id == prepared.owner.session_id && c.mutable && c.focus == prepared.focus)) { + self.prepared = None; + } + if self.pending.as_ref().is_some_and(|pending| !context.is_some_and(|c| + c.session_id == pending.request.session_id && c.skip_auto && c.picker_enabled + && c.focus == pending.focus)) { + self.pending = None; + } + if self.active.as_ref().is_some_and(|active| !context.is_some_and(|c| + c.session_id == active.owner.session_id && c.mutable && c.focus == active.focus + && (!active.owner.keyboard_available || c.keyboard_available))) { + self.revoke(); + } + // presses deliberately survive invalidation: previously swallowed downs + // still own their releases, while passed downs never acquire an owner. + } + fn hotkey_toggled(&mut self, target: &DictationStyleTarget, context: Option<&Context>) -> Option { + self.reconcile(context); + if target.selection != DictationStyleSelection::SkipAuto { + self.pending = None; + self.prepared = None; + self.revoke(); + return None; + } + let c = context.filter(|c| c.session_id == target.session_id && c.picker_enabled && c.skip_auto)?; + self.prepared = None; + let request = Request { session_id: target.session_id, request_id: self.next_id() }; + self.pending = Some(Pending { request: request.clone(), focus: c.focus }); + Some(request) + } + fn pending(&mut self, label: &str, context: Option<&Context>) -> Option { + self.reconcile(context); + (label == "capsule").then(|| self.pending.as_ref().map(|p| p.request.clone())).flatten() + } + fn reservation( + &mut self, label: &str, session: SessionId, request: Option<&str>, context: Option<&Context>, + ) -> Result { + self.reconcile(context); + if !capsule_label(label) { return Err("capsule_window_required".into()); } + let c = context.filter(|c| c.session_id == session && c.mutable) + .ok_or("recording_style_required")?; + if c.focus.is_none() { return Err("capsule_style_menu_target_unavailable".into()); } + if let Some(request_id) = request { + if let Some(active) = self.active.as_ref().filter(|active| + active.owner.window_label == label && active.owner.session_id == session + && active.request_id.as_deref() == Some(request_id)) { + return Ok(active.owner.clone()); + } + if label != "capsule" || !self.pending.as_ref().is_some_and(|pending| + pending.request.session_id == session && pending.request.request_id == request_id) { + return Err("capsule_style_request_stale".into()); + } + } + let owner = Owner { session_id: session, menu_id: self.next_id(), window_label: label.into(), + keyboard_available: c.keyboard_available && c.focus.is_some() }; + self.prepared = Some(Prepared { owner: owner.clone(), focus: c.focus }); + Ok(owner) + } + fn commit( + &mut self, owner: Owner, request: Option<&str>, context: Option<&Context>, + ) -> Result<(), String> { + self.reconcile(context); + let c = context.filter(|c| c.session_id == owner.session_id && c.mutable) + .ok_or("recording_style_required")?; + if let Some(id) = request { + if self.active.as_ref().is_some_and(|active| active.owner == owner + && active.request_id.as_deref() == Some(id)) { return Ok(()); } + if owner.window_label != "capsule" || !self.pending.as_ref().is_some_and(|pending| + pending.request.session_id == owner.session_id && pending.request.request_id == id) { + return Err("capsule_style_request_stale".into()); + } + } + if !self.prepared.as_ref().is_some_and(|prepared| prepared.owner == owner + && prepared.focus == c.focus && owner.keyboard_available == c.keyboard_available) { + return Err("capsule_style_menu_reservation_stale".into()); + } + self.prepared = None; + self.pending = None; + if self.active.as_ref().is_some_and(|active| active.owner != owner) { self.revoke(); } + self.active = Some(Active { owner, request_id: request.map(str::to_owned), focus: c.focus }); + Ok(()) + } + fn close(&mut self, label: &str, session: SessionId, menu_id: &str) -> bool { + if self.active.as_ref().is_some_and(|a| + a.owner.window_label == label && a.owner.session_id == session && a.owner.menu_id == menu_id) { + self.revoke(); + true + } else { false } + } + fn is_owner(&mut self, event: &KeyEvent, context: Option<&Context>) -> bool { + self.reconcile(context); + self.active.as_ref().is_some_and(|a| a.owner.session_id == event.session_id + && a.owner.menu_id == event.menu_id && a.owner.window_label == event.window_label) + } + fn key( + &mut self, key: Key, down: bool, repeat: bool, modified: bool, + context: Option<&Context>, sink: &dyn Fn(KeyEvent) -> bool, + ) -> bool { + self.reconcile(context); + let index = key.index(); + let press = self.presses[index].clone(); + if !down { + self.presses[index] = Press::default(); + return press.captured; + } + self.presses[index].down = true; + if press.down || repeat { + if press.captured && !modified && matches!(key, Key::ArrowUp | Key::ArrowDown) { + if let Some(event) = self.key_event(key, true, context) + .filter(|event| Some(&event.menu_id) == press.menu_id.as_ref()) { let _ = sink(event); } + } + return press.captured; + } + if modified { return false; } + let Some(event) = self.key_event(key, false, context) else { return false; }; + // Queue acceptance is required before claiming a fresh physical down. + let menu_id = event.menu_id.clone(); + if !sink(event) { return false; } + self.presses[index].captured = true; + self.presses[index].menu_id = Some(menu_id); + true + } + fn key_event(&self, key: Key, repeat: bool, context: Option<&Context>) -> Option { + let c = context.filter(|c| c.keyboard_available && !c.blocked_keys[key.index()])?; + let active = self.active.as_ref().filter(|a| a.owner.keyboard_available && a.focus.is_some() + && c.session_id == a.owner.session_id && c.focus == a.focus)?; + Some(KeyEvent { session_id: active.owner.session_id, menu_id: active.owner.menu_id.clone(), + window_label: active.owner.window_label.clone(), key, repeat }) + } +} + +pub(crate) fn capsule_label(label: &str) -> bool { + label == "capsule" || label.strip_prefix("capsule-mirror-") + .is_some_and(|suffix| !suffix.is_empty() && suffix.chars().all(|c| c.is_ascii_digit())) +} + +type Source = Arc Option + Send + Sync>; +type Sink = Arc bool + Send + Sync>; +#[derive(Default)] +struct Runtime { state: Mutex, source: RwLock>, sink: RwLock> } +static RUNTIME: OnceLock = OnceLock::new(); +fn runtime() -> &'static Runtime { RUNTIME.get_or_init(Runtime::default) } +fn context() -> Option { + let source = runtime().source.read().clone()?; + source() +} +pub(crate) fn configure(source: Source, sink: Sink) { + *runtime().source.write() = Some(source); + *runtime().sink.write() = Some(sink); +} +fn with_state(operation: impl FnOnce(&mut State, Option<&Context>) -> T) -> T { + let context = context(); + let (result, closed) = { + let mut state = runtime().state.lock(); + let result = operation(&mut state, context.as_ref()); + (result, std::mem::take(&mut state.closed)) + }; + let sink = runtime().sink.read().clone(); + for event in closed { + if let Some(sink) = &sink { let _ = sink(Event::Closed(event)); } + } + result +} +pub(crate) fn hotkey_toggled(target: &DictationStyleTarget) -> Option { + with_state(|state, context| state.hotkey_toggled(target, context)) +} +pub(crate) fn pending(label: &str) -> Option { + with_state(|state, context| state.pending(label, context)) +} +pub(crate) fn reservation(label: &str, session: SessionId, request: Option<&str>) -> Result { + with_state(|state, context| state.reservation(label, session, request, context)) +} +pub(crate) fn commit(owner: Owner, request: Option<&str>) -> Result<(), String> { + with_state(|state, context| state.commit(owner, request, context)) +} +pub(crate) fn close(label: &str, session: SessionId, menu_id: &str) -> bool { + with_state(|state, _| state.close(label, session, menu_id)) +} +pub(crate) fn invalidate() { + with_state(|state, _| { state.pending = None; state.prepared = None; state.revoke(); }); +} +pub(crate) fn window_lost(label: &str) { + with_state(|state, _| { + if label == "capsule" { state.pending = None; } + if state.prepared.as_ref().is_some_and(|p| p.owner.window_label == label) { state.prepared = None; } + if state.active.as_ref().is_some_and(|a| a.owner.window_label == label) { state.revoke(); } + }); +} +pub(crate) fn owner_current(owner: &Owner) -> bool { + with_state(|state, context| { + state.reconcile(context); + state.active.as_ref().is_some_and(|active| active.owner == *owner) + }) +} +pub(crate) fn refresh() { + // Ordinary audio/state traffic must not query foreground windows when + // there is no picker intent or owner to validate. + { + let state = runtime().state.lock(); + if state.pending.is_none() && state.active.is_none() { return; } + } + with_state(|state, context| state.reconcile(context)); +} +pub(crate) fn is_owner(event: &KeyEvent) -> bool { + with_state(|state, context| state.is_owner(event, context)) +} +pub(crate) fn key(key: Key, down: bool, repeat: bool, modified: bool) -> bool { + { + let mut state = runtime().state.lock(); + if state.pending.is_none() && state.active.is_none() { + return state.key(key, down, repeat, modified, None, &|_| false); + } + } + let sink = runtime().sink.read().clone(); + with_state(|state, context| state.key(key, down, repeat, modified, context, &|event| + sink.as_ref().is_some_and(|sink| sink(Event::Key(event))))) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + fn context() -> Context { + Context { session_id: SessionId::new(), mutable: true, skip_auto: true, + picker_enabled: true, keyboard_available: true, focus: Some(Focus(9, 1)), + blocked_keys: [false; 4] } + } + fn target(c: &Context, selection: DictationStyleSelection) -> DictationStyleTarget { + DictationStyleTarget { session_id: c.session_id, skip_auto_style: selection != DictationStyleSelection::Automatic, + selection, mutable: c.mutable, style_pack_id: None, style_pack_name: None, + polish_style_pack_id: None, available_styles: vec![] } + } + fn open(state: &mut State, c: &Context) -> Owner { + let owner = state.reservation("capsule", c.session_id, None, Some(c)).unwrap(); + state.commit(owner.clone(), None, Some(c)).unwrap(); + owner + } + fn edge(state: &mut State, c: Option<&Context>, key: Key, down: bool) -> bool { + state.key(key, down, false, false, c, &|_| true) + } + + #[test] + fn starting_hotkey_intent_survives_late_mount_and_is_consumed_once_after_reservation() { + let mut state = State::default(); + let mut c = context(); + c.mutable = false; + // State replay / skipAuto start / programmatic selection alone cannot + // create an intent; only the explicit native-provenance method can. + state.reconcile(Some(&c)); + assert!(state.pending("capsule", Some(&c)).is_none()); + let request = state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), Some(&c)).unwrap(); + for _ in 0..3 { + assert_eq!(state.pending("capsule", Some(&c)), Some(request.clone())); + } + assert!(state.pending("capsule-mirror-0", Some(&c)).is_none()); + assert!(state.reservation("capsule", c.session_id, Some(&request.request_id), Some(&c)).is_err()); + c.mutable = true; + let owner = state.reservation("capsule", c.session_id, Some(&request.request_id), Some(&c)).unwrap(); + // Geometry has not succeeded yet: no ownership or input consumption. + assert!(!edge(&mut state, Some(&c), Key::Enter, true)); + assert!(!edge(&mut state, Some(&c), Key::Enter, false)); + assert_eq!(state.pending("capsule", Some(&c)), Some(request.clone())); + state.commit(owner.clone(), Some(&request.request_id), Some(&c)).unwrap(); + assert!(state.pending("capsule", Some(&c)).is_none()); + let replay = state.reservation("capsule", c.session_id, Some(&request.request_id), Some(&c)).unwrap(); + assert_eq!(replay, owner); + state.commit(replay, Some(&request.request_id), Some(&c)).unwrap(); + assert!(state.closed.is_empty()); + assert!(state.close("capsule", c.session_id, &owner.menu_id)); + assert!(!state.close("capsule", c.session_id, &owner.menu_id)); + assert!(state.reservation("capsule", c.session_id, Some(&request.request_id), Some(&c)).is_err()); + } + + #[test] + fn pending_intents_drop_on_automatic_disabled_picker_focus_or_session_loss() { + for reason in 0..5 { + let mut state = State::default(); + let c = context(); + state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), Some(&c)).unwrap(); + let mut changed = c.clone(); + match reason { + 0 => changed.skip_auto = false, + 1 => changed.picker_enabled = false, + 2 => changed.focus = Some(Focus(10, 1)), + 3 => changed.session_id = SessionId::new(), + _ => {}, + } + assert!(state.pending("capsule", if reason == 4 { None } else { Some(&changed) }).is_none()); + } + let mut state = State::default(); + let c = context(); + assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::Automatic), Some(&c)).is_none()); + assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::StylePack { style_pack_id: "x".into() }), Some(&c)).is_none()); + let mut disabled = c.clone(); + disabled.picker_enabled = false; + assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), Some(&disabled)).is_none()); + } + + #[test] + fn reservation_does_not_retarget_when_focus_or_capability_changes_during_geometry() { + let c = context(); + for changed_focus in [false, true] { + let mut state = State::default(); + let owner = state.reservation("capsule", c.session_id, None, Some(&c)).unwrap(); + let mut changed = c.clone(); + if changed_focus { changed.focus = Some(Focus(10, 1)); } + else { changed.keyboard_available = false; } + assert!(state.commit(owner, None, Some(&changed)).is_err()); + assert!(!edge(&mut state, Some(&changed), Key::Enter, true)); + assert!(!edge(&mut state, Some(&changed), Key::Enter, false)); + } + let mut state = State::default(); + let old = state.reservation("capsule", c.session_id, None, Some(&c)).unwrap(); + let current = state.reservation("capsule", c.session_id, None, Some(&c)).unwrap(); + assert!(state.commit(old, None, Some(&c)).is_err()); + state.commit(current.clone(), None, Some(&c)).unwrap(); + assert_eq!(state.active.as_ref().unwrap().owner, current); + let mut unknown = c; + unknown.focus = None; + assert!(state.reservation("capsule", unknown.session_id, None, Some(&unknown)).is_err()); + } + + #[test] + fn captured_releases_drain_after_close_cancel_focus_loss_and_replacement() { + for reason in 0..4 { + let mut state = State::default(); + let c = context(); + let owner = open(&mut state, &c); + assert!(edge(&mut state, Some(&c), Key::Enter, true)); + let mut changed = c.clone(); + match reason { + 0 => { assert!(state.close("capsule", c.session_id, &owner.menu_id)); }, + 1 => state.reconcile(None), + 2 => { changed.focus = Some(Focus(10, 1)); state.reconcile(Some(&changed)); }, + _ => { open(&mut state, &c); }, + } + assert!(state.key(Key::Enter, true, true, false, Some(&changed), &|_| panic!("repeat must not retarget"))); + assert!(edge(&mut state, Some(&changed), Key::Enter, false), "captured down must drain its up"); + assert!(!edge(&mut state, None, Key::Enter, false), "duplicate up is never swallowed"); + } + } + + #[test] + fn passed_or_preheld_down_never_loses_release_when_a_menu_opens() { + let c = context(); + for repeat_before_first_observation in [false, true] { + let mut state = State::default(); + assert!(!state.key(Key::ArrowDown, true, repeat_before_first_observation, false, Some(&c), &|_| true)); + open(&mut state, &c); + assert!(!state.key(Key::ArrowDown, true, true, false, Some(&c), &|_| panic!("preheld key"))); + assert!(!edge(&mut state, Some(&c), Key::ArrowDown, false)); + assert!(edge(&mut state, Some(&c), Key::ArrowDown, true)); + assert!(edge(&mut state, Some(&c), Key::ArrowDown, false)); + } + } + + #[test] + fn only_plain_unbound_keys_with_live_successful_owner_are_claimed() { + let c = context(); + let mut state = State::default(); + assert!(state.reservation("main", c.session_id, None, Some(&c)).is_err()); + assert!(state.reservation("capsule-mirror-not-a-window", c.session_id, None, Some(&c)).is_err()); + assert!(state.reservation("capsule", SessionId::new(), None, Some(&c)).is_err()); + open(&mut state, &c); + for key in [Key::ArrowUp, Key::ArrowDown, Key::Enter, Key::Escape] { + assert!(!state.key(key, true, false, true, Some(&c), &|_| panic!("modified chord"))); + assert!(!edge(&mut state, Some(&c), key, false)); + let mut blocked = c.clone(); + blocked.blocked_keys[key.index()] = true; + assert!(!edge(&mut state, Some(&blocked), key, true)); + assert!(!edge(&mut state, Some(&blocked), key, false)); + assert!(!state.key(key, true, false, false, Some(&c), &|_| false), "queue rejection must pass"); + assert!(!edge(&mut state, Some(&c), key, false)); + } + let mut unavailable = c.clone(); + unavailable.keyboard_available = false; + let owner = open(&mut state, &unavailable); + assert!(!owner.keyboard_available); + assert!(!edge(&mut state, Some(&unavailable), Key::Enter, true)); + assert!(!edge(&mut state, Some(&unavailable), Key::Enter, false)); + assert!(state.active.is_some(), "mouse-only visual owner is supported"); + } + + #[test] + fn old_closed_notifications_and_old_owners_cannot_close_or_receive_new_events() { + let mut state = State::default(); + let c = context(); + let a = open(&mut state, &c); + let b = open(&mut state, &c); + assert_ne!(a.menu_id, b.menu_id); + assert_eq!(state.closed.len(), 1); + assert_eq!(state.closed[0].menu_id, a.menu_id); + assert!(!state.close("capsule", c.session_id, &a.menu_id)); + assert!(!state.close("capsule-mirror-0", c.session_id, &b.menu_id)); + let events = RefCell::new(Vec::new()); + assert!(state.key(Key::ArrowUp, true, false, false, Some(&c), &|event| { events.borrow_mut().push(event); true })); + assert!(state.key(Key::ArrowUp, true, true, false, Some(&c), &|event| { events.borrow_mut().push(event); true })); + assert_eq!(events.borrow().len(), 2); + assert!(events.borrow().iter().all(|event| event.menu_id == b.menu_id)); + let event = events.borrow()[0].clone(); + assert!(state.is_owner(&event, Some(&c))); + let mut changed = c.clone(); + changed.focus = Some(Focus(10, 1)); + assert!(!state.is_owner(&event, Some(&changed))); + assert_eq!(state.closed.len(), 2); + assert_eq!(state.closed[1].menu_id, b.menu_id); + assert!(edge(&mut state, Some(&changed), Key::ArrowUp, false)); + assert!(!edge(&mut state, Some(&changed), Key::ArrowDown, true)); + assert!(!state.close("capsule", c.session_id, &b.menu_id), "duplicate explicit/host close is inert"); + } + + #[test] + fn all_plain_native_shortcut_owners_take_precedence_and_wire_ids_are_opaque_strings() { + let binding = openless_core::shared_types::ShortcutBinding { primary: "Enter".into(), modifiers: vec![] }; + for field in 0..11 { + let mut target = openless_core::HotkeyRuntimeTarget::from(&openless_core::UserPreferences::default()); + match field { + 0 => target.dictation = binding.clone(), 1 => target.translation = binding.clone(), + 2 => target.skip_auto_style = binding.clone(), 3 => target.qa = Some(binding.clone()), + 4 => target.quick_note = Some(binding.clone()), 5 => target.switch_style = Some(binding.clone()), + 6 => target.open_app = Some(binding.clone()), 7 => target.selection_polish = Some(binding.clone()), + 8 => target.coding_agent_voice = Some(binding.clone()), 9 => target.coding_agent_panel = Some(binding.clone()), + _ => target.coding_agent_quick = Some(binding.clone()), + } + assert!(blocked_keys(&target)[Key::Enter.index()]); + } + let c = context(); + let mut state = State::default(); + let owner = open(&mut state, &c); + let event = state.key_event(Key::Escape, false, Some(&c)).unwrap(); + let json = serde_json::to_value(event).unwrap(); + assert_eq!(json["menuId"], owner.menu_id); + assert_eq!(json["key"], "Escape"); + assert!(json.get("windowLabel").is_none()); + state.close("capsule", c.session_id, &owner.menu_id); + let json = serde_json::to_value(&state.closed[0]).unwrap(); + assert_eq!(json["sessionId"], c.session_id.to_string()); + assert_eq!(json["menuId"], owner.menu_id); + assert_eq!(json.as_object().unwrap().len(), 2); + } +} diff --git a/openless-all/app/src-tauri/src/commands/dictation.rs b/openless-all/app/src-tauri/src/commands/dictation.rs index 89d33a18f..6f4086759 100644 --- a/openless-all/app/src-tauri/src/commands/dictation.rs +++ b/openless-all/app/src-tauri/src/commands/dictation.rs @@ -239,7 +239,18 @@ pub async fn set_capsule_language_menu( session_id: openless_core::SessionId, open: bool, ) -> Result<(), String> { - set_capsule_picker_menu_impl(window, coord, session_id, open, false).await + set_capsule_picker_menu_impl(window, coord, session_id, open, false, None, None).await.map(|_| ()) +} + +#[cfg(not(mobile))] +#[tauri::command] +pub fn get_capsule_style_menu_request( + window: Window, +) -> Result, String> { + if !crate::capsule_style_menu::capsule_label(window.label()) { + return Err("capsule_window_required".into()); + } + Ok(crate::capsule_style_menu::pending(window.label())) } #[cfg(not(mobile))] @@ -249,8 +260,10 @@ pub async fn set_capsule_style_menu( coord: CoordinatorState<'_>, session_id: openless_core::SessionId, open: bool, -) -> Result<(), String> { - set_capsule_picker_menu_impl(window, coord, session_id, open, true).await + request_id: Option, + menu_id: Option, +) -> Result, String> { + set_capsule_picker_menu_impl(window, coord, session_id, open, true, request_id, menu_id).await } /// Shared geometry, focus policy and session-bound lifecycle for both pickers. @@ -261,9 +274,11 @@ async fn set_capsule_picker_menu_impl( session_id: openless_core::SessionId, open: bool, style: bool, -) -> Result<(), String> { + request_id: Option, + menu_id: Option, +) -> Result, String> { let label = window.label().to_string(); - if label != "capsule" && !label.starts_with("capsule-mirror-") { + if !crate::capsule_style_menu::capsule_label(&label) { return Err("capsule_window_required".into()); } let core = coord.backend(); @@ -282,7 +297,12 @@ async fn set_capsule_picker_menu_impl( 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)); + let result = if style { + capsule.set_style_menu_open(label, session_id, open, request_id, menu_id) + } else { + capsule.set_translation_menu_open(label, session_id, open).map(|_| None) + }; + let _ = send.send(result); })?; receive .await diff --git a/openless-all/app/src-tauri/src/coordinator.rs b/openless-all/app/src-tauri/src/coordinator.rs index 75ef120d9..858da7907 100644 --- a/openless-all/app/src-tauri/src/coordinator.rs +++ b/openless-all/app/src-tauri/src/coordinator.rs @@ -29,6 +29,8 @@ mod capsule_focus; #[path = "coordinator/dictation_core.rs"] mod dictation; mod hotkey_loops; +#[cfg(not(mobile))] +mod style_menu; mod native_dictation_key; mod restore_runtime; #[cfg(all(not(mobile), target_os = "windows"))] @@ -43,6 +45,8 @@ pub(crate) use capsule_focus::{ restore_focus_target_if_possible, }; use hotkey_loops::*; +#[cfg(not(mobile))] +use style_menu::*; use native_dictation_key::try_install_mouse_dictation; // Instance-local Less Computer replay source used by the compatibility command. @@ -832,6 +836,8 @@ impl Coordinator { }); #[cfg(all(not(mobile), target_os = "windows"))] bind_qa_selection_voice_target(&qa_context, &inner.selection_voice_host); + #[cfg(not(mobile))] + configure_style_menu(&inner); Self { inner } } } @@ -970,6 +976,7 @@ impl Coordinator { shutdown: AtomicBool::new(false), }); bind_qa_selection_voice_target(&qa_context, &selection_voice_host); + configure_style_menu(&inner); Self { inner } } 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 531b83c9d..814e31124 100644 --- a/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs +++ b/openless-all/app/src-tauri/src/coordinator/hotkey_loops.rs @@ -87,7 +87,7 @@ fn skip_auto_style_hotkey_bridge_loop( 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); + handle_skip_auto_style_hotkey(&inner, id); } } }, @@ -2221,7 +2221,7 @@ 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); + handle_skip_auto_style_hotkey(&inner, context.session_id); } } #[cfg(not(mobile))] diff --git a/openless-all/app/src-tauri/src/coordinator/style_menu.rs b/openless-all/app/src-tauri/src/coordinator/style_menu.rs new file mode 100644 index 000000000..68d908fc6 --- /dev/null +++ b/openless-all/app/src-tauri/src/coordinator/style_menu.rs @@ -0,0 +1,106 @@ +//! Real hotkey provenance and the no-focus capsule picker bridge. +use super::*; +use crate::capsule_style_menu::{self as menu, Context, Event, Focus}; + +fn foreground() -> Option { + #[cfg(target_os = "macos")] + { + let pid = crate::ask_window::foreground_pid()?; + let window = crate::selection::macos_front_window_id(pid as i32)?; + Some(Focus((u64::from(pid) << 32) | u64::from(window), + crate::ask_window::active_space_epoch())) + } + #[cfg(target_os = "windows")] + { + use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; + unsafe { + let window = GetForegroundWindow(); + if window.0.is_null() { return None; } + let mut pid = 0; + GetWindowThreadProcessId(window, Some(&mut pid)); + (pid != 0 && GetForegroundWindow() == window) + .then_some(Focus(window.0 as usize as u64, u64::from(pid))) + } + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { None } +} + +#[derive(Default)] +struct FocusState { + serial: u64, + native: Option, + target: Option, +} + +impl FocusState { + fn current(&mut self) -> Option<(Focus, bool)> { + let native = foreground()?; + let window_changed = self.native != Some(native); + let control_changed = !window_changed && self.target.as_ref() + .is_some_and(|target| !crate::selection::capsule_menu_input_target_is_current(target)); + if window_changed || control_changed { + self.serial = self.serial.checked_add(1).expect("style menu focus sequence exhausted"); + self.native = Some(native); + self.target = None; + } + if self.target.is_none() { + self.target = crate::selection::capture_capsule_menu_input_target(); + } + // A verifiable window still binds mouse-only ownership when AX/UIA is + // unavailable; it must not keep that owner across an app/window change. + Some((Focus(self.serial, native.1), self.target.is_some())) + } +} + +pub(super) fn configure_style_menu(inner: &Arc) { + let source = Arc::downgrade(inner); + let sink = Arc::downgrade(inner); + let focus = Mutex::new(FocusState::default()); + menu::configure(Arc::new(move || { + let inner = source.upgrade()?; + let snapshot = inner.backend.snapshot(); + if !matches!(snapshot.dictation.phase, + openless_core::DictationPhase::Starting | openless_core::DictationPhase::Recording) { + return None; + } + if matches!(inner.backend.dictation_output_target(), Some( + openless_core::DictationOutputTarget::AskComposer + | openless_core::DictationOutputTarget::Qa + | openless_core::DictationOutputTarget::VoiceEdit + )) || inner.selection_polish_capsule_active.load(Ordering::SeqCst) { + return None; + } + let target = inner.backend.dictation_style_target()?; + if snapshot.dictation.session_id != Some(target.session_id) { return None; } + let surface_available = inner.host.style_menu_surface_available(target.session_id); + let keyboard_available = cfg!(any(target_os = "macos", target_os = "windows")) + && !inner.shortcut_recording_active.load(Ordering::SeqCst) + && inner.hotkey.try_lock().is_some_and(|monitor| monitor.is_some()) + && surface_available; + let (focus, target_verified) = focus.lock().current() + .map(|(focus, verified)| (Some(focus), verified)).unwrap_or((None, false)); + Some(Context { + session_id: target.session_id, mutable: target.mutable && surface_available, + skip_auto: target.skip_auto_style, + picker_enabled: inner.backend.get_preferences().skip_auto_style_picker_enabled, + // Window/control identity is the insertion adapter's existing + // native proof (AX on macOS, HWND/UIA on Windows). Missing permission + // or an unverifiable input target yields mouse-only ownership. + keyboard_available: keyboard_available && target_verified, focus, + blocked_keys: menu::blocked_keys(&hotkey_runtime_target(&inner)), + }) + }), Arc::new(move |event| { + sink.upgrade().is_some_and(|inner| inner.host.queue_style_menu_event(event)) + })); +} + +/// Only the two native hotkey consumers call this. Programmatic style changes +/// and ordinary start options never pass through this provenance boundary. +pub(super) fn handle_skip_auto_style_hotkey(inner: &Arc, session_id: openless_core::SessionId) { + if let Ok(target) = inner.backend.toggle_dictation_style_for_session(session_id) { + if let Some(request) = menu::hotkey_toggled(&target) { + let _ = inner.host.queue_style_menu_event(Event::Request(request)); + } + } +} diff --git a/openless-all/app/src-tauri/src/hotkey.rs b/openless-all/app/src-tauri/src/hotkey.rs index 9b057eba6..6b8a04752 100644 --- a/openless-all/app/src-tauri/src/hotkey.rs +++ b/openless-all/app/src-tauri/src/hotkey.rs @@ -1000,6 +1000,7 @@ pub(crate) mod platform { observe_shift_event(ctx, event_type, event); match event_type { TAP_DISABLED_BY_TIMEOUT | TAP_DISABLED_BY_USER_INPUT => { + crate::capsule_style_menu::invalidate(); reset_shared_held_state(&ctx.shared); if let Some(pending) = ctx.pending_space.lock().take() { pending.replay(std::ptr::null_mut()); @@ -1021,6 +1022,28 @@ pub(crate) mod platform { let keycode = unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) }; let flags = unsafe { CGEventGetFlags(event) }; let hardware = unsafe { CGEventGetIntegerValueField(event, SOURCE_PID_FIELD) } == 0; + if hardware && matches!(event_type, KEY_DOWN | KEY_UP) { + let key = match keycode { + 126 => Some(crate::capsule_style_menu::Key::ArrowUp), + 125 => Some(crate::capsule_style_menu::Key::ArrowDown), + 36 => Some(crate::capsule_style_menu::Key::Enter), + 53 => Some(crate::capsule_style_menu::Key::Escape), + _ => None, + }; + if let Some(key) = key { + let fn_held = flags & FLAG_MASK_SECONDARY_FN != 0 + && (crate::ask_window::hotkey::fn_is_held() + || crate::side_aware_combo::platform::keycode_is_down(63)); + // Require the physical Fn controller, rather than treating a + // function-key flag on a navigation event as a held modifier. + let modified = fn_held || flags & (FLAG_MASK_SHIFT | FLAG_MASK_CONTROL + | FLAG_MASK_ALTERNATE | FLAG_MASK_COMMAND) != 0; + let repeat = unsafe { CGEventGetIntegerValueField(event, 8) } != 0; + if crate::capsule_style_menu::key(key, event_type == KEY_DOWN, repeat, modified) { + return std::ptr::null_mut(); + } + } + } let is_fn_down = event_type == FLAGS_CHANGED && hardware && keycode == 63 && flags & FLAG_MASK_SECONDARY_FN != 0; if !is_fn_down { @@ -1736,6 +1759,88 @@ pub(crate) mod platform { } } + // Run by the standalone native harness, isolating its mock Runtime + // source from main-crate tests that construct another Coordinator. + pub(crate) fn style_menu_real_callback_preserves_key_pairs_across_open_close_and_cancel() { + use crate::capsule_style_menu::{self as menu, Event, Focus}; + let _guard = crate::side_aware_combo::TEST_MONITOR_LOCK.blocking_lock(); + let session = openless_core::SessionId::new(); + let live = Arc::new(parking_lot::Mutex::new(Some(menu::Context { + session_id: session, mutable: false, skip_auto: true, picker_enabled: true, + keyboard_available: true, focus: Some(Focus(3, 1)), blocked_keys: [false; 4], + }))); + let source = live.clone(); + let (send, receive) = mpsc::channel(); + menu::configure(Arc::new(move || source.lock().clone()), + Arc::new(move |event| send.send(event).is_ok())); + let shared = shared(HotkeyTrigger::RightOption); + let context = super::super::ShiftTranslationContext { + session_id: session, preferences_revision: 1, 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); + assert!(menu::pending("capsule").is_none()); + // Actual native tap classification emits exactly one provenance event. + 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(_))); + assert!(rx.try_recv().is_err()); + let request = menu::hotkey_toggled(&openless_core::DictationStyleTarget { + session_id: session, selection: openless_core::DictationStyleSelection::SkipAuto, + skip_auto_style: true, mutable: false, style_pack_id: None, style_pack_name: None, + polish_style_pack_id: None, available_styles: vec![], + }).unwrap(); + assert!(menu::reservation("capsule", session, Some(&request.request_id)).is_err()); + // A down passed before the menu has no matching captured up. + assert!(!menu_callback(&ctx, 126, true, 0, false)); + live.lock().as_mut().unwrap().mutable = true; + let owner = menu::reservation("capsule", session, Some(&request.request_id)).unwrap(); + menu::commit(owner.clone(), Some(&request.request_id)).unwrap(); + assert!(!menu_callback(&ctx, 126, true, 0, true)); + assert!(!menu_callback(&ctx, 126, false, 0, false)); + assert!(menu_callback(&ctx, 126, true, 0, false)); + assert!(matches!(receive.try_recv().unwrap(), Event::Key(key) + if key.menu_id == owner.menu_id && key.key == menu::Key::ArrowUp)); + assert!(menu::close("capsule", session, &owner.menu_id)); + assert!(matches!(receive.try_recv().unwrap(), Event::Closed(closed) if closed.menu_id == owner.menu_id)); + assert!(menu_callback(&ctx, 126, false, 0, false), "close drains captured release"); + assert!(!menu_callback(&ctx, 36, true, 0, false)); + assert!(!menu_callback(&ctx, 36, false, 0, false)); + let replacement = menu::reservation("capsule", session, None).unwrap(); + menu::commit(replacement.clone(), None).unwrap(); + assert!(!menu_callback(&ctx, 125, true, FLAG_MASK_COMMAND | 0x8, false)); + assert!(!menu_callback(&ctx, 125, false, FLAG_MASK_COMMAND | 0x8, false)); + assert!(receive.try_recv().is_err(), "modified keys stay with the foreground target"); + assert!(menu_callback(&ctx, 125, true, 0, false)); + assert!(matches!(receive.try_recv().unwrap(), Event::Key(_))); + *live.lock() = None; + menu::refresh(); + assert!(matches!(receive.try_recv().unwrap(), Event::Closed(_))); + assert!(menu_callback(&ctx, 125, false, 0, false), "cancel drains captured release"); + assert!(!menu_callback(&ctx, 36, true, 0, false)); + assert!(!menu_callback(&ctx, 36, false, 0, false)); + assert!(receive.try_recv().is_err()); + menu::invalidate(); + menu::configure(Arc::new(|| None), Arc::new(|_| false)); + } + + fn menu_callback(ctx: &CallbackContext, key: u16, down: bool, flags: CgEventFlags, repeat: bool) -> bool { + unsafe { + let event = CGEventCreateKeyboardEvent(std::ptr::null_mut(), key, down); + assert!(!event.is_null()); + CGEventSetFlags(event, flags); + CGEventSetIntegerValueField(event, SOURCE_PID_FIELD, 0); + CGEventSetIntegerValueField(event, 8, i64::from(repeat)); + let returned = tap_callback(std::ptr::null_mut(), if down { KEY_DOWN } else { KEY_UP }, + event, ctx as *const _ as *mut c_void); + assert!(returned.is_null() || returned == event); + CFRelease(event as *const c_void); + returned.is_null() + } + } + // 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() { @@ -2570,6 +2675,32 @@ mod platform { use crate::ask_window::hotkey::{keyboard_edge, Disposition}; let down = matches!(wparam.0, WM_KEYDOWN | WM_SYSKEYDOWN); let disabled = ctx.shared.recording_active.load(Ordering::SeqCst); + if down || matches!(wparam.0, WM_KEYUP | WM_SYSKEYUP) { + // Keep keypad aliases out of this physical pairing + // slot: keypad Up/Down/Enter are distinct keys even + // when Windows gives them the same virtual-key code. + let extended = keyboard.flags.0 & LLKHF_EXTENDED.0 != 0; + let key = match (vk_code, extended) { + (0x26, true) => Some(crate::capsule_style_menu::Key::ArrowUp), + (0x28, true) => Some(crate::capsule_style_menu::Key::ArrowDown), + (0x0D, false) => Some(crate::capsule_style_menu::Key::Enter), + (0x1B, false) => Some(crate::capsule_style_menu::Key::Escape), + _ => None, + }; + if let Some(key) = key { + use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; + let modified = [VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU, + VK_LWIN, VK_RWIN, VK_LSHIFT, VK_RSHIFT].into_iter() + .any(|vk| GetAsyncKeyState(vk as i32) < 0); + // The LL callback runs before async state updates: + // an already-down key is a repeat, including a + // press that predated installation of this hook. + let repeat = down && GetAsyncKeyState(vk_code as i32) < 0; + if crate::capsule_style_menu::key(key, down, repeat, modified) { + return LRESULT(1); + } + } + } if (down || matches!(wparam.0, WM_KEYUP | WM_SYSKEYUP)) && !(down && vk_code == VK_ESCAPE && super::capsule_menu_open()) { diff --git a/openless-all/app/src-tauri/src/lib.rs b/openless-all/app/src-tauri/src/lib.rs index 01304ce70..789083926 100644 --- a/openless-all/app/src-tauri/src/lib.rs +++ b/openless-all/app/src-tauri/src/lib.rs @@ -251,6 +251,8 @@ macro_rules! app_invoke_handler_desktop { commands::set_capsule_language_menu, #[cfg(not(mobile))] commands::set_capsule_style_menu, + #[cfg(not(mobile))] + commands::get_capsule_style_menu_request, commands::get_settings, commands::get_settings_snapshot, commands::get_voice_activation_state, @@ -1140,6 +1142,10 @@ fn run_desktop() { RunEvent::Reopen { .. } => show_main_window(app), RunEvent::ExitRequested { code: None, api, .. } if desktop_resources::active() => api.prevent_exit(), RunEvent::WindowEvent { label, event, .. } => { + if matches!(event, tauri::WindowEvent::Destroyed) + && capsule_style_menu::capsule_label(&label) { + capsule_style_menu::window_lost(&label); + } if label == "main" { if let tauri::WindowEvent::CloseRequested { ref api, .. } = event { api.prevent_close(); @@ -3441,6 +3447,8 @@ pub(crate) fn hide_less_computer_glow(_app: &AppHandle) {} /// inside the module stays `cfg(windows)`. mod capsule_mirrors; mod capsule_feedback; +#[cfg(not(mobile))] +mod capsule_style_menu; mod vocab_card_placement; /// Init and card-return paths use the default stage; the recording display path passes the diff --git a/openless-all/app/src-tauri/src/selection.rs b/openless-all/app/src-tauri/src/selection.rs index 055c48cb5..da777eb92 100644 --- a/openless-all/app/src-tauri/src/selection.rs +++ b/openless-all/app/src-tauri/src/selection.rs @@ -600,7 +600,7 @@ pub(crate) fn insert_selection_result( } #[cfg(target_os = "macos")] -fn macos_front_window_id(pid: i32) -> Option { +pub(crate) fn macos_front_window_id(pid: i32) -> Option { use core_foundation::base::{CFType, TCFType}; use core_foundation::dictionary::CFDictionary; use core_foundation::number::CFNumber; @@ -698,6 +698,18 @@ pub(crate) fn selection_insertion_target_is_current(target: &SelectionInsertionT native_input_target_is_current(target) } +/// Read-only identity for a nonactivating picker. Unlike insertion validation, +/// this never compares selection text or clipboard contents. +pub(crate) fn capture_capsule_menu_input_target() -> Option { + let mut target = capture_selection_insertion_target(); + target.strict_input_target = true; + native_input_target_is_current(&target).then_some(target) +} + +pub(crate) fn capsule_menu_input_target_is_current(target: &SelectionInsertionTarget) -> bool { + native_input_target_is_current(target) +} + fn native_input_target_is_current(target: &SelectionInsertionTarget) -> bool { if target.cancelled.load(std::sync::atomic::Ordering::Acquire) { return false; } #[cfg(target_os = "windows")] diff --git a/openless-all/app/src-tauri/src/tauri_coordinator_host.rs b/openless-all/app/src-tauri/src/tauri_coordinator_host.rs index 0b47543f1..4877a9305 100644 --- a/openless-all/app/src-tauri/src/tauri_coordinator_host.rs +++ b/openless-all/app/src-tauri/src/tauri_coordinator_host.rs @@ -748,6 +748,7 @@ struct CapsuleMenuFrame { session_id: openless_core::SessionId, position: tauri::PhysicalPosition, size: tauri::PhysicalSize, + style_menu_id: Option, } fn capsule_menu_geometry(y: i32, height: u32, work_top: i32, scale: f64) -> (i32, u32) { @@ -1115,16 +1116,26 @@ impl TauriCapsuleWindow { } fn restore_translation_menu(&self, owner: Option<(&str, openless_core::SessionId)>) -> Result { + self.restore_picker_menu(owner.map(|(label, session)| (label, session, None))) + } + + fn restore_picker_menu(&self, owner: Option<(&str, openless_core::SessionId, Option<&str>)>) -> Result { let frame = { let mut slot = self.state.translation_menu.lock(); - if let Some((label, session_id)) = owner { - if !slot.as_ref().is_some_and(|frame| frame.label == label && frame.session_id == session_id) { return Ok(false); } + if let Some((label, session_id, style_menu_id)) = owner { + if !slot.as_ref().is_some_and(|frame| frame.label == label && frame.session_id == session_id + && frame.style_menu_id.as_deref() == style_menu_id) { return Ok(false); } } slot.take() }; let Some(frame) = frame else { return Ok(false); }; #[cfg(not(mobile))] - crate::hotkey::set_capsule_menu_open(false); + { + crate::hotkey::set_capsule_menu_open(false); + if let Some(menu_id) = &frame.style_menu_id { + crate::capsule_style_menu::close(&frame.label, frame.session_id, menu_id); + } + } self.invalidate_layout(); if let Some(window) = self.app.get_webview_window(&frame.label) { window.set_size(frame.size).map_err(|error| error.to_string())?; @@ -1146,19 +1157,31 @@ impl TauriCapsuleWindow { } return Ok(()); } + self.reserve_picker_geometry(label, session_id, None) + } + + fn reserve_picker_geometry(&self, label: String, session_id: openless_core::SessionId, style_menu_id: Option) -> Result<(), String> { if self.state.qa_voice_active.load(Ordering::SeqCst) { return Err("qa_owns_voice_surface".into()); } - if self.state.translation_menu.lock().as_ref().is_some_and(|frame| frame.label == label && frame.session_id == session_id) { return Ok(()); } + if self.state.translation_menu.lock().as_ref().is_some_and(|frame| frame.label == label && frame.session_id == session_id + && frame.style_menu_id == style_menu_id) { return Ok(()); } self.restore_translation_menu(None)?; let window = self.app.get_webview_window(&label).ok_or("capsule_window_unavailable")?; + if style_menu_id.is_some() && !window.is_visible().map_err(|e| e.to_string())? { + return Err("capsule_window_hidden".into()); + } let position = window.outer_position().map_err(|error| error.to_string())?; let size = window.inner_size().map_err(|error| error.to_string())?; let scale = window.scale_factor().map_err(|error| error.to_string())?; let work_top = window.current_monitor().map_err(|error| error.to_string())? .map(|monitor| monitor.work_area().position.y).unwrap_or(position.y - (320.0 * scale) as i32); let (top, height) = capsule_menu_geometry(position.y, size.height, work_top, scale); - *self.state.translation_menu.lock() = Some(CapsuleMenuFrame {label, session_id, position, size}); #[cfg(not(mobile))] - crate::hotkey::set_capsule_menu_open(true); + let translation_menu = style_menu_id.is_none(); + *self.state.translation_menu.lock() = Some(CapsuleMenuFrame {label, session_id, position, size, style_menu_id}); + #[cfg(not(mobile))] + // The legacy Esc bypass belongs to translation only. Style uses its + // committed owner router, including recording/global-key precedence. + crate::hotkey::set_capsule_menu_open(translation_menu); self.stop_layout_watch(); self.hide_transcript_overlay(); let result = (|| -> tauri::Result<()> { @@ -1178,8 +1201,56 @@ impl TauriCapsuleWindow { Ok(()) } + #[cfg(not(mobile))] + pub(crate) fn set_style_menu_open( + &self, label: String, session_id: openless_core::SessionId, open: bool, + request_id: Option, menu_id: Option, + ) -> Result, String> { + use crate::capsule_style_menu as menu; + if !open { + let menu_id = menu_id.ok_or("capsule_style_menu_owner_required")?; + self.restore_style_menu_owner(&menu::ClosedEvent { session_id, menu_id, window_label: label })?; + return Ok(None); + } + let owner = menu::reservation(&label, session_id, request_id.as_deref())?; + let already_open = menu::owner_current(&owner); + self.reserve_picker_geometry(label, session_id, Some(owner.menu_id.clone()))?; + if let Err(error) = menu::commit(owner.clone(), request_id.as_deref()) { + let _ = self.restore_style_menu_owner(&menu::ClosedEvent { session_id, + menu_id: owner.menu_id.clone(), window_label: owner.window_label.clone() }); + return Err(error); + } + if already_open { return Ok(Some(owner)); } + let owner_for_watch = owner.clone(); + let host = self.app.state::>().tauri_host(); + tauri::async_runtime::spawn(async move { + // No AppHandle/window crosses this timer's thread; validation and + // geometry restoration are queued to the native main thread. + loop { + tokio::time::sleep(std::time::Duration::from_millis(75)).await; + if !menu::owner_current(&owner_for_watch) { break; } + if !host.queue_style_menu_event(menu::Event::Validate(owner_for_watch.clone())) { break; } + } + }); + Ok(Some(owner)) + } + + #[cfg(not(mobile))] + fn restore_style_menu_owner(&self, owner: &crate::capsule_style_menu::ClosedEvent) -> Result<(), String> { + if self.restore_picker_menu(Some((&owner.window_label, owner.session_id, Some(&owner.menu_id))))? + && self.state.capsule_visible.load(Ordering::SeqCst) { + self.start_layout_watch(); + self.refresh_style(); + self.sync_capsule_mirrors(); + } + Ok(()) + } + pub(crate) fn set_size(&self, width: f64, height: f64) -> tauri::Result<()> { // Cards temporarily borrow this window; their geometry belongs to the card until released. + let _ = self.restore_translation_menu(None); + #[cfg(not(mobile))] + crate::capsule_style_menu::invalidate(); self.stop_layout_watch(); if let Some(window) = self.window() { window.set_size(tauri::LogicalSize::new(width, height))?; @@ -1500,6 +1571,8 @@ impl TauriCapsuleWindow { } pub(crate) fn hide(&self) -> tauri::Result<()> { + #[cfg(not(mobile))] + crate::capsule_style_menu::invalidate(); let _ = self.restore_translation_menu(None); self.state.capsule_visible.store(false, Ordering::SeqCst); self.stop_layout_watch(); @@ -2114,7 +2187,13 @@ impl TauriCapsuleWindow { style: CapsuleStyle, reassert_spaces: bool, ) { - if payload.state != CapsuleState::Recording || !payload.translation { + let style_menu = self.state.translation_menu.lock().as_ref() + .is_some_and(|frame| frame.style_menu_id.is_some()); + let style_session_current = self.state.translation_menu.lock().as_ref().is_some_and(|frame| + payload.session_id.as_deref() == Some(frame.session_id.to_string().as_str())); + if if style_menu { + payload.state != CapsuleState::Recording || payload.selection_polish || !style_session_current + } else { payload.state != CapsuleState::Recording || !payload.translation } { let _ = self.restore_translation_menu(None); } self.state.cache_style(style); @@ -2231,6 +2310,85 @@ pub(crate) struct TauriCoordinatorHost { } impl TauriCoordinatorHost { + #[cfg(not(mobile))] + pub(crate) fn style_menu_surface_available(&self, session: openless_core::SessionId) -> bool { + !crate::desktop_resources::active() + && self.capsule.capsule_visible.load(Ordering::SeqCst) + && !self.capsule.qa_voice_active.load(Ordering::SeqCst) + && !self.capsule.fallback_card_visible.load(Ordering::SeqCst) + && self.capsule.hit_test_mode.load(Ordering::SeqCst) != HIT_TEST_MODE_CARD + && self.capsule.snapshot.lock().payload.as_ref().is_some_and(|payload| + payload.state == CapsuleState::Recording && !payload.qa && !payload.selection_polish + && payload.session_id.as_deref() == Some(session.to_string().as_str())) + } + + /// Accept into the native main-thread queue before the hook claims a down. + /// Windows borrows its AppHandle off-main instead of cloning native Rc state. + #[cfg(not(mobile))] + pub(crate) fn queue_style_menu_event(&self, event: crate::capsule_style_menu::Event) -> bool { + #[cfg(target_os = "windows")] + { + if MAIN_THREAD.get() == Some(&std::thread::current().id()) { + self.deliver_style_menu_event(event); + return true; + } + let host = self.clone(); + self.app.lock().as_ref().is_some_and(|app| + app.run_on_main_thread(move || host.deliver_style_menu_event(event)).is_ok()) + } + #[cfg(not(target_os = "windows"))] + { + let Some(app) = self.app() else { return false; }; + let host = self.clone(); + app.run_on_main_thread(move || host.deliver_style_menu_event(event)).is_ok() + } + } + + #[cfg(not(mobile))] + fn deliver_style_menu_event(&self, event: crate::capsule_style_menu::Event) { + use crate::capsule_style_menu::{self as menu, Event}; + let Some(app) = self.app() else { return; }; + match event { + Event::Request(request) => { + if menu::pending("capsule").as_ref() == Some(&request) { + let _ = app.emit_to("capsule", "capsule:style-menu-request", request); + } + } + Event::Closed(owner) => { + if let Some(capsule) = self.capsule_window() { + if let Err(error) = capsule.restore_style_menu_owner(&owner) { + log::warn!("[capsule] style menu geometry release failed: {error}"); + } + } + let _ = app.emit_to(owner.window_label.as_str(), "capsule:style-menu-closed", &owner); + } + Event::Key(key) => { + if !menu::is_owner(&key) { return; } + let frame_matches = self.capsule.translation_menu.lock().as_ref().is_some_and(|frame| + frame.label == key.window_label && frame.session_id == key.session_id + && frame.style_menu_id.as_deref() == Some(key.menu_id.as_str())); + if !frame_matches || !app.get_webview_window(&key.window_label) + .is_some_and(|window| window.is_visible().unwrap_or(false)) { + menu::window_lost(&key.window_label); + return; + } + if app.emit_to(key.window_label.as_str(), "capsule:style-menu-key", &key).is_err() { + menu::window_lost(&key.window_label); + } + } + Event::Validate(owner) => { + if !menu::owner_current(&owner) { return; } + let frame_matches = self.capsule.translation_menu.lock().as_ref().is_some_and(|frame| + frame.label == owner.window_label && frame.session_id == owner.session_id + && frame.style_menu_id.as_deref() == Some(owner.menu_id.as_str())); + if !frame_matches || !app.get_webview_window(&owner.window_label) + .is_some_and(|window| window.is_visible().unwrap_or(false)) { + menu::window_lost(&owner.window_label); + } + } + } + } + pub(crate) fn new( app: crate::core_adapters::AppHandleSlot, qa_context: Arc, @@ -2390,6 +2548,8 @@ impl TauriCoordinatorHost { } pub(crate) fn set_qa_voice_active(&self, active: bool) { + #[cfg(not(mobile))] + if active { crate::capsule_style_menu::invalidate(); } self.capsule.qa_voice_active.store(active, Ordering::SeqCst); } @@ -2446,6 +2606,8 @@ impl TauriCoordinatorHost { /// Update replay state without waiting for the native window callback. pub(crate) fn record_backend_event(&self, event: &BackendEvent) { + #[cfg(not(mobile))] + crate::capsule_style_menu::refresh(); #[cfg(not(mobile))] if self.ask_owns_capsule() { return; @@ -2477,6 +2639,7 @@ impl TauriCoordinatorHost { #[cfg(not(mobile))] pub(crate) fn claim_ask_capsule(&self, session_id: &str) -> u64 { + crate::capsule_style_menu::invalidate(); self.capsule.snapshot.lock().claim_ask(session_id) } From d6f0684963f48083822c0b2931c233437f61c10f Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:05:28 +0800 Subject: [PATCH 02/13] feat(settings): configure skip-auto-style shortcuts and picker --- .../src/features/input/ShortcutsSection.tsx | 94 ++++++++++++++----- .../input/skipAutoStyleSettings.test.ts | 20 ++++ .../features/input/skipAutoStyleSettings.ts | 12 +++ .../app/src/features/settings/shell/tabs.tsx | 2 +- openless-all/app/src/i18n/de.ts | 5 + openless-all/app/src/i18n/en.ts | 5 + openless-all/app/src/i18n/es.ts | 5 + openless-all/app/src/i18n/fr.ts | 5 + openless-all/app/src/i18n/ja.ts | 5 + openless-all/app/src/i18n/ko.ts | 5 + openless-all/app/src/i18n/zh-CN.ts | 5 + openless-all/app/src/i18n/zh-TW.ts | 5 + 12 files changed, 143 insertions(+), 25 deletions(-) create mode 100644 openless-all/app/src/features/input/skipAutoStyleSettings.test.ts create mode 100644 openless-all/app/src/features/input/skipAutoStyleSettings.ts diff --git a/openless-all/app/src/features/input/ShortcutsSection.tsx b/openless-all/app/src/features/input/ShortcutsSection.tsx index 1fe6c4e21..064e9c343 100644 --- a/openless-all/app/src/features/input/ShortcutsSection.tsx +++ b/openless-all/app/src/features/input/ShortcutsSection.tsx @@ -1,12 +1,13 @@ import { TextField } from '../../ui/controls/TextField'; import { Segmented } from '../../ui/controls/Segmented'; -import { useDeferredValue, useEffect, useState } from 'react'; +import { Fragment, useDeferredValue, useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Icon } from '../../components/Icon'; import { ShortcutRecorder } from '../../components/ShortcutRecorder'; import { Kbd } from '../../components/Kbd'; import { SelectLite } from '../../components/ui/SelectLite'; import { PageSkeleton } from '../../components/ui/PageSkeleton'; +import { Toggle } from '../../ui/controls/SettingRow'; import { getRuntimeOS } from '../../runtime/environment'; import { defaultDictationHotkey, @@ -22,18 +23,25 @@ import { setOpenAppHotkey, setQuickNoteHotkey, setSelectionPolishHotkey, + setSkipAutoStyleHotkey, setStylePackHotkeys, setSwitchStyleHotkey, setTranslationHotkey, } from '../../api/hotkeys'; import { getStylePackPresentation } from '../../lib/stylePackPresentation'; -import type { ShortcutBinding, StylePack, StylePackHotkey } from '../../api/contracts'; +import type { + PlatformCapabilities, + ShortcutBinding, + StylePack, + StylePackHotkey, +} from '../../api/contracts'; import { useHotkeySettings } from '../../data/preferences'; +import { supportsSkipAutoStyleHotkey } from './skipAutoStyleSettings'; -export function ShortcutsSection() { +export function ShortcutsSection({ platform }: { platform: PlatformCapabilities }) { const { t } = useTranslation(); const os = getRuntimeOS(); - const { prefs, hotkey, refresh, updatePrefs } = useHotkeySettings(); + const { prefs, hotkey, capability, refresh, updatePrefs } = useHotkeySettings(); const [packs, setPacks] = useState([]); const [query, setQuery] = useState(''); const search = useDeferredValue(query.trim().toLocaleLowerCase()); @@ -43,6 +51,7 @@ export function ShortcutsSection() { const [draftPackId, setDraftPackId] = useState(''); const [error, setError] = useState(''); const tr = (key: string) => t(`uiRefinement.${key}`); + const stylePickerLabel = t('settings.shortcuts.skipAutoStylePicker'); useEffect(() => { let cancelled = false; void listStylePacks() @@ -60,6 +69,7 @@ export function ShortcutsSection() { id: string; label: string; desc?: string; + searchLabel?: string; group: string; binding: ShortcutBinding | null; unavailable?: boolean; @@ -101,6 +111,25 @@ export function ShortcutsSection() { await refresh(); }, }, + ...(supportsSkipAutoStyleHotkey(platform, capability?.adapter) + ? [ + { + id: 'skipAutoStyle', + label: t('settings.shortcuts.skipAutoStyle'), + searchLabel: stylePickerLabel, + group: 'recording', + binding: prefs.skipAutoStyleHotkey ?? null, + save: async (binding: ShortcutBinding) => { + await setSkipAutoStyleHotkey(binding); + await refresh(); + }, + disable: async () => { + await setSkipAutoStyleHotkey(null); + await refresh(); + }, + }, + ] + : []), { id: 'note', label: t('settings.shortcuts.quickNote'), @@ -180,7 +209,8 @@ export function ShortcutsSection() { (status === 'all' || (status === 'assigned') === Boolean(binding?.primary.trim())); const visible = commands.filter( (command) => - (category === 'all' || category === command.group) && matches(command.label, command.binding), + (category === 'all' || category === command.group) && + matches([command.label, command.searchLabel].filter(Boolean).join(' '), command.binding), ); const packHotkeys = prefs.stylePackHotkeys ?? []; const savePacks = async (next: StylePackHotkey[]) => { @@ -267,26 +297,42 @@ export function ShortcutsSection() {

{tr('shortcutHint')}

{visible.map((command) => ( -
-
- {command.label} - {command.desc && {command.desc}} + +
+
+ {command.label} + {command.desc && {command.desc}} +
+
- -
+ {command.id === 'skipAutoStyle' && ( +
+ {stylePickerLabel} + { + // The shared preference store handles rollback and error feedback. + void updatePrefs((current) => ({ ...current, skipAutoStylePickerEnabled })).catch( + () => {}, + ); + }} + /> +
+ )} + ))} {readonly.map((row) => (
diff --git a/openless-all/app/src/features/input/skipAutoStyleSettings.test.ts b/openless-all/app/src/features/input/skipAutoStyleSettings.test.ts new file mode 100644 index 000000000..b3e8f98d5 --- /dev/null +++ b/openless-all/app/src/features/input/skipAutoStyleSettings.test.ts @@ -0,0 +1,20 @@ +import { supportsSkipAutoStyleHotkey } from './skipAutoStyleSettings'; + +const desktop = { platform: 'desktop', supportsDesktopHotkey: true } as const; +for (const adapter of ['macEventTap', 'windowsLowLevel'] as const) { + if (!supportsSkipAutoStyleHotkey(desktop, adapter)) { + throw new Error(`Expected skip-auto-style shortcuts for ${adapter}`); + } + if ( + supportsSkipAutoStyleHotkey({ ...desktop, supportsDesktopHotkey: false }, adapter) || + supportsSkipAutoStyleHotkey({ ...desktop, platform: 'mobile' }, adapter) + ) { + throw new Error(`Expected a desktop capability for ${adapter}`); + } +} + +for (const adapter of ['fcitx5', 'unavailable', undefined] as const) { + if (supportsSkipAutoStyleHotkey(desktop, adapter)) { + throw new Error(`Unexpected skip-auto-style shortcuts for ${adapter}`); + } +} diff --git a/openless-all/app/src/features/input/skipAutoStyleSettings.ts b/openless-all/app/src/features/input/skipAutoStyleSettings.ts new file mode 100644 index 000000000..e10d21ec9 --- /dev/null +++ b/openless-all/app/src/features/input/skipAutoStyleSettings.ts @@ -0,0 +1,12 @@ +import type { HotkeyCapability, PlatformCapabilities } from '../../api/contracts'; + +export function supportsSkipAutoStyleHotkey( + platform: Pick, + adapter: HotkeyCapability['adapter'] | undefined, +) { + return ( + platform.platform === 'desktop' && + platform.supportsDesktopHotkey && + (adapter === 'macEventTap' || adapter === 'windowsLowLevel') + ); +} diff --git a/openless-all/app/src/features/settings/shell/tabs.tsx b/openless-all/app/src/features/settings/shell/tabs.tsx index 21fa72471..22345d060 100644 --- a/openless-all/app/src/features/settings/shell/tabs.tsx +++ b/openless-all/app/src/features/settings/shell/tabs.tsx @@ -213,7 +213,7 @@ export function InputMethodTab() { export function ShortcutsTab() { const platformCaps = usePlatformCaps(); if (!platformCaps?.supportsDesktopHotkey) return null; - return ; + return ; } export function AppearanceTab() { diff --git a/openless-all/app/src/i18n/de.ts b/openless-all/app/src/i18n/de.ts index c3119681a..69d90c786 100644 --- a/openless-all/app/src/i18n/de.ts +++ b/openless-all/app/src/i18n/de.ts @@ -360,6 +360,9 @@ export const de: typeof zhCN = { inserted: '{{count}} eingefügt', translateTo: 'Übersetzen in', translationChangeFailed: 'Sprache konnte nicht geändert werden. Bitte erneut auswählen.', + styleChoose: 'Ausgabestil wählen', + styleChangeFailed: 'Stil konnte nicht geändert werden. Bitte erneut auswählen.', + styleStatus: 'Ausgabestil', translating: 'Wird übersetzt', selectionPolish: { polishing: 'Wird überarbeitet…', @@ -2063,6 +2066,8 @@ export const de: typeof zhCN = { cancel: 'Aktuelle Aufnahme abbrechen', confirm: 'Einfügen über die Kapsel bestätigen', switchStyle: 'Zum vorherigen Stil wechseln', + skipAutoStyle: 'Automatischen Stil überspringen', + skipAutoStylePicker: 'Stil nach Tastendruck wählen', openApp: 'OpenLess öffnen', stylePackTitle: 'Stilkurzbefehle', stylePackDesc: diff --git a/openless-all/app/src/i18n/en.ts b/openless-all/app/src/i18n/en.ts index dba82d2a5..27c39032c 100644 --- a/openless-all/app/src/i18n/en.ts +++ b/openless-all/app/src/i18n/en.ts @@ -358,6 +358,9 @@ export const en: typeof zhCN = { inserted: 'Inserted {{count}}', translateTo: 'Translate to', translationChangeFailed: 'Could not change language. Please select it again.', + styleChoose: 'Choose output style', + styleChangeFailed: 'Could not change style. Please select it again.', + styleStatus: 'Output style', translating: 'Translating', selectionPolish: { polishing: 'Polishing…', @@ -2017,6 +2020,8 @@ export const en: typeof zhCN = { cancel: 'Cancel current recording', confirm: 'Confirm capsule insertion', switchStyle: 'Switch to previous style', + skipAutoStyle: 'Skip auto style', + skipAutoStylePicker: 'Choose output style on press', openApp: 'Open OpenLess', stylePackTitle: 'Style shortcuts', stylePackDesc: diff --git a/openless-all/app/src/i18n/es.ts b/openless-all/app/src/i18n/es.ts index 0980e5bcd..e7485c54c 100644 --- a/openless-all/app/src/i18n/es.ts +++ b/openless-all/app/src/i18n/es.ts @@ -358,6 +358,9 @@ export const es: typeof zhCN = { inserted: '{{count}} insertados', translateTo: 'Traducir al', translationChangeFailed: 'No se pudo cambiar el idioma. Vuelve a seleccionarlo.', + styleChoose: 'Elegir estilo de salida', + styleChangeFailed: 'No se pudo cambiar el estilo. Vuelve a seleccionarlo.', + styleStatus: 'Estilo de salida', translating: 'Traduciendo', selectionPolish: { polishing: 'Mejorando…', @@ -2049,6 +2052,8 @@ export const es: typeof zhCN = { cancel: 'Cancelar la grabación actual', confirm: 'Confirmar inserción de la cápsula', switchStyle: 'Cambiar al estilo anterior', + skipAutoStyle: 'Omitir estilo automático', + skipAutoStylePicker: 'Elegir estilo al pulsar', openApp: 'Abrir OpenLess', stylePackTitle: 'Atajos de estilos', stylePackDesc: diff --git a/openless-all/app/src/i18n/fr.ts b/openless-all/app/src/i18n/fr.ts index dbccf93ed..dd4907db0 100644 --- a/openless-all/app/src/i18n/fr.ts +++ b/openless-all/app/src/i18n/fr.ts @@ -363,6 +363,9 @@ export const fr: typeof zhCN = { inserted: '{{count}} insérés', translateTo: 'Traduire en', translationChangeFailed: 'Impossible de changer de langue. Veuillez réessayer.', + styleChoose: 'Choisir le style de sortie', + styleChangeFailed: 'Impossible de changer de style. Veuillez réessayer.', + styleStatus: 'Style de sortie', translating: 'Traduction', selectionPolish: { polishing: 'Amélioration…', @@ -2076,6 +2079,8 @@ export const fr: typeof zhCN = { cancel: 'Annuler l’enregistrement actuel', confirm: 'Confirmer l’insertion de la capsule', switchStyle: 'Passer au style précédent', + skipAutoStyle: 'Ignorer le style automatique', + skipAutoStylePicker: 'Choisir le style après appui', openApp: 'Ouvrir OpenLess', stylePackTitle: 'Raccourcis de styles', stylePackDesc: diff --git a/openless-all/app/src/i18n/ja.ts b/openless-all/app/src/i18n/ja.ts index e02908128..979eca727 100644 --- a/openless-all/app/src/i18n/ja.ts +++ b/openless-all/app/src/i18n/ja.ts @@ -347,6 +347,9 @@ export const ja: typeof zhCN = { inserted: '{{count}} 文字を入力しました', translateTo: '翻訳先', translationChangeFailed: '言語を変更できませんでした。もう一度選択してください。', + styleChoose: '出力スタイルを選択', + styleChangeFailed: 'スタイルを変更できませんでした。もう一度選択してください。', + styleStatus: '出力スタイル', translating: '翻訳中', selectionPolish: { polishing: '推敲中…', @@ -2000,6 +2003,8 @@ export const ja: typeof zhCN = { cancel: '本回の録音をキャンセル', confirm: 'カプセル入力を確定', switchStyle: '前のスタイルに切り替え', + skipAutoStyle: '自動スタイルをスキップ', + skipAutoStylePicker: '押した後にスタイルを選択', openApp: 'OpenLess を開く', stylePackTitle: 'スタイル直行ショートカット', stylePackDesc: diff --git a/openless-all/app/src/i18n/ko.ts b/openless-all/app/src/i18n/ko.ts index 41bf4c316..c70540215 100644 --- a/openless-all/app/src/i18n/ko.ts +++ b/openless-all/app/src/i18n/ko.ts @@ -341,6 +341,9 @@ export const ko: typeof zhCN = { inserted: '{{count}}자 입력됨', translateTo: '번역 언어', translationChangeFailed: '언어를 변경하지 못했습니다. 다시 선택해 주세요.', + styleChoose: '출력 스타일 선택', + styleChangeFailed: '스타일을 변경하지 못했습니다. 다시 선택해 주세요.', + styleStatus: '출력 스타일', translating: '번역 중', selectionPolish: { polishing: '다듬는 중…', @@ -1987,6 +1990,8 @@ export const ko: typeof zhCN = { cancel: '이번 녹음 취소', confirm: '캡슐 입력 확정', switchStyle: '이전 스타일로 전환', + skipAutoStyle: '자동 스타일 건너뛰기', + skipAutoStylePicker: '누른 후 스타일 선택', openApp: 'OpenLess 열기', stylePackTitle: '스타일 바로가기 단축키', stylePackDesc: diff --git a/openless-all/app/src/i18n/zh-CN.ts b/openless-all/app/src/i18n/zh-CN.ts index fb913a656..31e645d10 100644 --- a/openless-all/app/src/i18n/zh-CN.ts +++ b/openless-all/app/src/i18n/zh-CN.ts @@ -329,6 +329,9 @@ export const zhCN = { inserted: '已插入 {{count}}', translateTo: '翻译为', translationChangeFailed: '语言切换失败,请重新选择。', + styleChoose: '选择输出风格', + styleChangeFailed: '风格切换失败,请重新选择。', + styleStatus: '输出风格', translating: '正在翻译', selectionPolish: { polishing: '正在润色…', @@ -1909,6 +1912,8 @@ export const zhCN = { cancel: '取消本次录音', confirm: '胶囊确认插入', switchStyle: '切换到上一个风格', + skipAutoStyle: '跳过自动风格', + skipAutoStylePicker: '按下时选择输出风格', openApp: '打开 OpenLess', stylePackTitle: '风格直达快捷键', stylePackDesc: '为常用风格包各配一个快捷键,按下直接切换;停用中的包会自动启用。', diff --git a/openless-all/app/src/i18n/zh-TW.ts b/openless-all/app/src/i18n/zh-TW.ts index 3d5320a9e..6f03265bd 100644 --- a/openless-all/app/src/i18n/zh-TW.ts +++ b/openless-all/app/src/i18n/zh-TW.ts @@ -330,6 +330,9 @@ export const zhTW: typeof zhCN = { inserted: '已插入 {{count}}', translateTo: '翻譯為', translationChangeFailed: '語言切換失敗,請重新選擇。', + styleChoose: '選擇輸出風格', + styleChangeFailed: '風格切換失敗,請重新選擇。', + styleStatus: '輸出風格', translating: '正在翻譯', selectionPolish: { polishing: '正在潤色…', @@ -1911,6 +1914,8 @@ export const zhTW: typeof zhCN = { cancel: '取消本次錄音', confirm: '膠囊確認插入', switchStyle: '切換到上一個風格', + skipAutoStyle: '跳過自動風格', + skipAutoStylePicker: '按下時選擇輸出風格', openApp: '開啟 OpenLess', stylePackTitle: '風格直達快捷鍵', stylePackDesc: '為常用風格包各配一個快捷鍵,按下直接切換;停用中的包會自動啟用。', From df2a783bd0c4244ab5895a510b3d35dfb985af73 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:09:10 +0800 Subject: [PATCH 03/13] refactor(capsule): share session-bound picker geometry --- .../app/src/features/capsule/Capsule.tsx | 6 + .../capsule/CapsuleTranslationBadge.tsx | 14 +- .../capsule/capsulePickerMenu.test.ts | 63 +++++++ .../src/features/capsule/capsulePickerMenu.ts | 168 ++++++++++++++++++ .../capsule/useCapsuleLanguageMenu.ts | 157 ---------------- .../features/capsule/useCapsulePickerMenu.ts | 95 ++++++++++ 6 files changed, 344 insertions(+), 159 deletions(-) create mode 100644 openless-all/app/src/features/capsule/capsulePickerMenu.test.ts create mode 100644 openless-all/app/src/features/capsule/capsulePickerMenu.ts delete mode 100644 openless-all/app/src/features/capsule/useCapsuleLanguageMenu.ts create mode 100644 openless-all/app/src/features/capsule/useCapsulePickerMenu.ts diff --git a/openless-all/app/src/features/capsule/Capsule.tsx b/openless-all/app/src/features/capsule/Capsule.tsx index 30045aa6a..4d4aa7f92 100644 --- a/openless-all/app/src/features/capsule/Capsule.tsx +++ b/openless-all/app/src/features/capsule/Capsule.tsx @@ -9,6 +9,7 @@ import { useReducedMotion } from '../../lib/motion'; import { VoiceOrbStage } from './VoiceOrbStage'; import { DEFAULT_CAPSULE_EXIT_MS, OpenLessPill } from './OpenLessCapsule'; import { CapsuleTranscriptRail, CapsuleTranslationBadge } from './LiveTranscriptPill'; +import { CapsulePickerMenu } from './capsulePickerMenu'; import { useMainCaptionTrace } from './useMainCaptionTrace'; import { capsuleTranscriptFontSize, visibleCapsuleTranscript } from '../../lib/capsuleTranscript'; import { getSettings } from '../../api/preferences'; @@ -185,6 +186,7 @@ function SelectionPolishNotice({ state, message }: SelectionPolishNoticeProps) { // white-and-blue recording/processing surface inside that stable host. interface ClassicCapsuleProps { + pickerController: CapsulePickerMenu; sessionId?: string; os: OS; state: CapsuleState; @@ -207,6 +209,7 @@ interface ClassicCapsuleProps { * interaction only appears while recording). */ function ClassicCapsule({ + pickerController, sessionId, os, state, @@ -262,6 +265,7 @@ function ClassicCapsule({ }} > @@ -378,6 +382,7 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { const os = forcedOs ?? getRuntimeOS(); const isTauri = isTauriHost(); const [publishInputRegions] = useState(createCapsuleRegionPublisher); + const [pickerController] = useState(() => new CapsulePickerMenu()); const preview = useMemo(() => getPreviewCapsulePayload(), []); const reducedMotion = useReducedMotion(); const metrics = getCapsulePillMetrics(os); @@ -983,6 +988,7 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { {!renderedSelectionPolish && (isClassic ? ( + setCapsuleLanguageMenu(open, sessionId); + /** The same Base UI menu as settings, with temporary native headroom above the capsule. */ export const CapsuleTranslationBadge = memo(function CapsuleTranslationBadge({ + pickerController, visible = true, processing = false, }: { + pickerController: CapsulePickerMenu; visible?: boolean; processing?: boolean; }) { @@ -112,7 +119,10 @@ export const CapsuleTranslationBadge = memo(function CapsuleTranslationBadge({ setError(false); }, [snapshot?.sessionId]); - const menu = useCapsuleLanguageMenu({ + const menu = useCapsulePickerMenu({ + controller: pickerController, + kind: 'language', + setNativeMenu, anchor, target: snapshot, visible: visible && !processing, diff --git a/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts b/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts new file mode 100644 index 000000000..25ab1be50 --- /dev/null +++ b/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts @@ -0,0 +1,63 @@ +import { CapsulePickerMenu, type CapsulePickerDeps } from './capsulePickerMenu'; + +function expect(actual: unknown, expected: unknown) { + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + throw new Error(`Expected ${JSON.stringify(expected)}, received ${JSON.stringify(actual)}`); + } +} + +const controller = new CapsulePickerMenu(); +const log: string[] = []; +const language = { kind: 'language', sessionId: 'first' } as const; +const style = { kind: 'style', sessionId: 'first', requestId: 'open-1' } as const; +const deps: CapsulePickerDeps = { + native: true, + setNativeMenu: async (open, owner) => { + log.push(`${owner.kind}:${open}:${owner.sessionId}`); + }, + waitForGeometry: async () => {}, + onOpenChange: (open) => log.push(`render:${open}`), + onFailure: () => log.push('error'), +}; + +await controller.open(language, deps); +expect(controller.sessionForChoice('language'), 'first'); +controller.close('language'); +// Base UI can deliver the choice during the language popup's exit. +expect(controller.sessionForChoice('language'), 'first'); +await controller.open(style, deps); +controller.openChangeComplete('language', false); +expect(controller.owns('style', 'first', 'open-1'), true); +expect(controller.owns('style', 'first', 'older-open'), false); +expect(controller.sessionForChoice('language'), undefined); +controller.update('style', true, { sessionId: 'next', mutable: true }); +expect(controller.owns('style', 'first', 'open-1'), false); +await controller.open({ ...style, sessionId: 'next', requestId: 'open-2' }, deps); +controller.close('style'); +await controller.open({ ...language, sessionId: 'next' }, deps); +expect(log, [ + 'language:true:first', 'render:true', 'render:false', 'language:false:first', + 'style:true:first', 'render:true', 'render:false', 'style:false:first', + 'style:true:next', 'render:true', 'render:false', 'style:false:next', + 'language:true:next', 'render:true', +]); + +log.length = 0; +const openingController = new CapsulePickerMenu(); +let finishGeometry: () => void = () => {}; +const opening = openingController.open(style, { + ...deps, + waitForGeometry: () => new Promise((resolve) => { finishGeometry = resolve; }), +}); +await new Promise((resolve) => setTimeout(resolve, 0)); +openingController.handleKeydown('style', { + key: 'Escape', + preventDefault: () => log.push('escape'), +}); +finishGeometry(); +await opening; +await openingController.open(language, deps); +expect(log, [ + 'style:true:first', 'escape', 'render:false', 'style:false:first', + 'language:true:first', 'render:true', +]); diff --git a/openless-all/app/src/features/capsule/capsulePickerMenu.ts b/openless-all/app/src/features/capsule/capsulePickerMenu.ts new file mode 100644 index 000000000..276bb2b65 --- /dev/null +++ b/openless-all/app/src/features/capsule/capsulePickerMenu.ts @@ -0,0 +1,168 @@ +/** + * Session-bound lifecycle shared by the capsule's language and style pickers. + * + * The native capsule owns one temporary headroom reservation per recording + * session (`set_capsule_language_menu` / `set_capsule_style_menu`). This + * controller is the only place which reserves, queues and releases it, so every + * picker gets the same ordering, abort and session-invalidation guarantees. + */ + +export interface CapsulePickerTarget { + sessionId: string; + mutable: boolean; +} + +export type CapsulePickerKind = 'language' | 'style'; + +export interface CapsulePickerOwner { + kind: CapsulePickerKind; + sessionId: string; + requestId?: string; +} + +export interface CapsulePickerDeps { + /** Reserve (`true`) or restore (`false`) the native headroom for a session. */ + setNativeMenu: (open: boolean, owner: CapsulePickerOwner) => Promise; + /** Whether a native host owns the geometry; the browser preview has none. */ + native: boolean; + /** Resolves once the anchor and viewport can hold the popup. */ + waitForGeometry: (signal: AbortSignal) => Promise; + /** Mirrors the mounted state into the renderer. */ + onOpenChange: (open: boolean) => void; + /** An opening request failed while it was still the current one. */ + onFailure: () => void; +} + +interface Reservation extends CapsulePickerOwner { + deps: CapsulePickerDeps; + abort: AbortController; + nativeWriteStarted: boolean; + mounted: boolean; +} + +export class CapsulePickerMenu { + private reservation: Reservation | undefined; + private exiting: Reservation | undefined; + private tail: Promise = Promise.resolve(); + + owns(kind: CapsulePickerKind, sessionId: string, requestId: string) { + const owner = this.reservation; + return owner?.kind === kind && owner.sessionId === sessionId && owner.requestId === requestId; + } + + /** The session whose popup is open or still animating out. */ + sessionForChoice(kind: CapsulePickerKind) { + const owner = this.reservation ?? this.exiting; + return owner?.kind === kind ? owner.sessionId : undefined; + } + + update(kind: CapsulePickerKind, visible: boolean, target: CapsulePickerTarget | null) { + const owner = this.reservation; + if ( + owner?.kind === kind && + (!visible || !target?.mutable || target.sessionId !== owner.sessionId) + ) { + this.close(kind); + } + } + + async open(request: CapsulePickerOwner, deps: CapsulePickerDeps) { + const previous = this.reservation; + if ( + previous?.kind === request.kind && + previous.sessionId === request.sessionId && + previous.requestId === request.requestId + ) { + return; + } + if (previous) this.close(previous.kind); + // The host shares one reservation for both pickers. Release the old owner + // before reserving for a different picker or opening in the same session again. + if (this.exiting) this.release(this.exiting); + const owner: Reservation = { + ...request, + deps, + abort: new AbortController(), + nativeWriteStarted: false, + mounted: false, + }; + this.reservation = owner; + try { + if (deps.native) { + await this.enqueue(async () => { + if (owner.abort.signal.aborted) return; + owner.nativeWriteStarted = true; + await deps.setNativeMenu(true, owner); + }); + await deps.waitForGeometry(owner.abort.signal); + } + if (this.reservation !== owner || owner.abort.signal.aborted) return; + owner.mounted = true; + deps.onOpenChange(true); + } catch { + if (this.reservation === owner && !owner.abort.signal.aborted) { + this.close(owner.kind); + deps.onFailure(); + } + } + } + + close(kind: CapsulePickerKind) { + const owner = this.reservation; + if (owner?.kind !== kind) return; + this.reservation = undefined; + owner.abort.abort(); + owner.deps.onOpenChange(false); + // The style popup has no exit animation and must release native keys immediately. + if (owner.mounted && kind === 'language') this.exiting = owner; + else this.release(owner); + } + + /** Base UI finished its exit transition; the native headroom can be restored. */ + openChangeComplete(kind: CapsulePickerKind, next: boolean) { + if (!next && this.exiting?.kind === kind) this.release(this.exiting); + } + + /** Escape before the popup mounted; once mounted, Base UI owns it. */ + handleKeydown( + kind: CapsulePickerKind, + event: { key: string; isComposing?: boolean; preventDefault: () => void }, + ) { + if ( + event.key === 'Escape' && + !event.isComposing && + this.reservation?.kind === kind && + !this.reservation.mounted + ) { + event.preventDefault(); + this.close(kind); + } + } + + dispose(kind: CapsulePickerKind) { + if (this.reservation?.kind === kind) { + this.release(this.reservation); + this.reservation = undefined; + } + if (this.exiting?.kind === kind) this.release(this.exiting); + } + + private enqueue(operation: () => Promise) { + const result = this.tail.catch(() => undefined).then(operation); + this.tail = result; + return result; + } + + private release(owner: Reservation) { + if (this.exiting === owner) this.exiting = undefined; + owner.abort.abort(); + void this.enqueue(async () => { + if (owner.nativeWriteStarted) { + owner.nativeWriteStarted = false; + await owner.deps.setNativeMenu(false, owner); + } + }).catch((error) => + console.warn('[capsule] failed to restore picker menu geometry', error), + ); + } +} diff --git a/openless-all/app/src/features/capsule/useCapsuleLanguageMenu.ts b/openless-all/app/src/features/capsule/useCapsuleLanguageMenu.ts deleted file mode 100644 index e7c993745..000000000 --- a/openless-all/app/src/features/capsule/useCapsuleLanguageMenu.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'; -import { setCapsuleLanguageMenu, type DictationTranslationTarget } from '../../api/dictation'; -import { isTauriHost } from '../../runtime/environment'; -import { waitForViewportGeometry } from '../../runtime/windows/viewportGeometry'; -import { useAppViewport } from '../../ui/layout/AppViewport'; - -interface Reservation { - sessionId: string; - abort: AbortController; - nativeWriteStarted: boolean; - mounted: boolean; -} - -export function useCapsuleLanguageMenu({ - anchor, - target, - visible, - onFailure, -}: { - anchor: RefObject; - target: DictationTranslationTarget | null; - visible: boolean; - onFailure: () => void; -}) { - const { boundary } = useAppViewport(); - const [open, setOpen] = useState(false); - const reservation = useRef(); - const exiting = useRef(); - const tail = useRef>(Promise.resolve()); - const active = useRef({ visible, target }); - active.current = { visible, target }; - - const enqueue = useCallback((operation: () => Promise) => { - const result = tail.current.catch(() => undefined).then(operation); - tail.current = result; - return result; - }, []); - - const release = useCallback( - (owner: Reservation) => { - if (exiting.current === owner) exiting.current = undefined; - owner.abort.abort(); - void enqueue(async () => { - if (owner.nativeWriteStarted) { - owner.nativeWriteStarted = false; - await setCapsuleLanguageMenu(false, owner.sessionId); - } - }).catch((error) => - console.warn('[capsule] failed to restore language menu geometry', error), - ); - }, - [enqueue], - ); - - const close = useCallback(() => { - const owner = reservation.current; - if (!owner) return; - reservation.current = undefined; - owner.abort.abort(); - setOpen(false); - if (owner.mounted) exiting.current = owner; - else release(owner); - }, [release]); - - const onOpenChange = async (next: boolean) => { - if (!next) return close(); - const current = active.current; - if (!current.visible || !current.target?.mutable || reservation.current) return; - // The native owner is keyed by session, not by popup generation. Release a - // prior exit before reserving again, even when both belong to one recording. - if (exiting.current) release(exiting.current); - const owner: Reservation = { - sessionId: current.target.sessionId, - abort: new AbortController(), - nativeWriteStarted: false, - mounted: false, - }; - reservation.current = owner; - try { - if (isTauriHost()) { - await enqueue(async () => { - if (owner.abort.signal.aborted) return; - owner.nativeWriteStarted = true; - await setCapsuleLanguageMenu(true, owner.sessionId); - }); - const viewport = boundary ?? document.documentElement; - await waitForViewportGeometry( - viewport, - ({ width }) => { - if (width < 100 || !anchor.current?.getClientRects().length) return false; - const trigger = anchor.current.getBoundingClientRect(); - const frame = viewport.getBoundingClientRect(); - // Leave room for the menu inset and at least two complete options. - const room = Math.max(trigger.top - frame.top, frame.bottom - trigger.bottom); - return trigger.bottom <= frame.bottom + 1 && room >= 80; - }, - owner.abort.signal, - ); - } - if (reservation.current !== owner || owner.abort.signal.aborted) return; - if ( - !active.current.visible || - active.current.target?.sessionId !== owner.sessionId || - !active.current.target.mutable - ) - return close(); - owner.mounted = true; - setOpen(true); - } catch { - if (reservation.current === owner && !owner.abort.signal.aborted) { - close(); - onFailure(); - } - } - }; - - useEffect(() => { - if ( - reservation.current && - (!visible || !target?.mutable || target.sessionId !== reservation.current.sessionId) - ) - close(); - }, [close, visible, target?.mutable, target?.sessionId]); - - useEffect(() => { - const onKeydown = (event: KeyboardEvent) => { - if ( - event.key === 'Escape' && - !event.isComposing && - reservation.current && - !reservation.current.mounted - ) { - event.preventDefault(); - close(); - } - }; - window.addEventListener('blur', close); - window.addEventListener('keydown', onKeydown); - return () => { - window.removeEventListener('blur', close); - window.removeEventListener('keydown', onKeydown); - if (reservation.current) release(reservation.current); - if (exiting.current) release(exiting.current); - reservation.current = undefined; - }; - }, [close, release]); - - return { - open, - close, - sessionForChoice: () => reservation.current?.sessionId ?? exiting.current?.sessionId, - onOpenChange, - onOpenChangeComplete(next: boolean) { - if (!next && exiting.current) release(exiting.current); - }, - }; -} diff --git a/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts b/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts new file mode 100644 index 000000000..705357296 --- /dev/null +++ b/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts @@ -0,0 +1,95 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react'; +import { isTauriHost } from '../../runtime/environment'; +import { waitForViewportGeometry } from '../../runtime/windows/viewportGeometry'; +import { useAppViewport } from '../../ui/layout/AppViewport'; +import type { + CapsulePickerDeps, + CapsulePickerKind, + CapsulePickerMenu, + CapsulePickerTarget, +} from './capsulePickerMenu'; + +export function useCapsulePickerMenu({ + controller, + kind, + anchor, + target, + visible, + setNativeMenu, + onFailure, +}: { + controller: CapsulePickerMenu; + kind: CapsulePickerKind; + anchor: RefObject; + target: CapsulePickerTarget | null; + visible: boolean; + setNativeMenu: CapsulePickerDeps['setNativeMenu']; + onFailure: () => void; +}) { + const { boundary } = useAppViewport(); + const [open, setOpen] = useState(false); + const config = useRef({ visible, target, boundary, onFailure }); + config.current = { visible, target, boundary, onFailure }; + + const close = useCallback(() => controller.close(kind), [controller, kind]); + const openMenu = useCallback( + (requestId?: string) => { + const current = config.current; + if (!current.visible || !current.target?.mutable) return; + return controller.open( + { kind, sessionId: current.target.sessionId, requestId }, + { + native: isTauriHost(), + setNativeMenu, + onOpenChange: setOpen, + onFailure: () => config.current.onFailure(), + waitForGeometry: async (signal) => { + const viewport = current.boundary ?? document.documentElement; + await waitForViewportGeometry( + viewport, + ({ width }) => { + if (width < 100 || !anchor.current?.getClientRects().length) return false; + const trigger = anchor.current.getBoundingClientRect(); + const frame = viewport.getBoundingClientRect(); + const room = Math.max(trigger.top - frame.top, frame.bottom - trigger.bottom); + return trigger.bottom <= frame.bottom + 1 && room >= 80; + }, + signal, + ); + }, + }, + ); + }, + [anchor, controller, kind, setNativeMenu], + ); + + useLayoutEffect(() => { + controller.update(kind, visible, target); + }, [controller, kind, visible, target]); + + useEffect(() => { + const onKeydown = (event: KeyboardEvent) => controller.handleKeydown(kind, event); + window.addEventListener('blur', close); + window.addEventListener('keydown', onKeydown); + return () => { + window.removeEventListener('blur', close); + window.removeEventListener('keydown', onKeydown); + controller.dispose(kind); + }; + }, [close, controller, kind]); + + return { + open, + openMenu, + close, + sessionForChoice: () => controller.sessionForChoice(kind), + owns: (sessionId: string, requestId: string) => controller.owns(kind, sessionId, requestId), + onOpenChange(next: boolean) { + if (next) void openMenu(); + else close(); + }, + onOpenChangeComplete(next: boolean) { + controller.openChangeComplete(kind, next); + }, + }; +} From 91de1f3114d3f0534fa7fe4205dd90acc1d9ed33 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:20:02 +0800 Subject: [PATCH 04/13] fix(settings): require shortcut combinations on Windows --- .../app/src/features/input/ShortcutsSection.tsx | 13 ++++++++++--- openless-all/app/src/i18n/de.ts | 1 + openless-all/app/src/i18n/en.ts | 1 + openless-all/app/src/i18n/es.ts | 1 + openless-all/app/src/i18n/fr.ts | 1 + openless-all/app/src/i18n/ja.ts | 1 + openless-all/app/src/i18n/ko.ts | 1 + openless-all/app/src/i18n/zh-CN.ts | 1 + openless-all/app/src/i18n/zh-TW.ts | 1 + openless-all/app/src/lib/ipc/mock-data.ts | 8 ++------ 10 files changed, 20 insertions(+), 9 deletions(-) diff --git a/openless-all/app/src/features/input/ShortcutsSection.tsx b/openless-all/app/src/features/input/ShortcutsSection.tsx index 064e9c343..7453fdfd2 100644 --- a/openless-all/app/src/features/input/ShortcutsSection.tsx +++ b/openless-all/app/src/features/input/ShortcutsSection.tsx @@ -120,6 +120,9 @@ export function ShortcutsSection({ platform }: { platform: PlatformCapabilities group: 'recording', binding: prefs.skipAutoStyleHotkey ?? null, save: async (binding: ShortcutBinding) => { + if (capability?.adapter === 'windowsLowLevel' && binding.modifiers.length === 0) { + throw new Error(t('settings.shortcuts.skipAutoStyleComboRequired')); + } await setSkipAutoStyleHotkey(binding); await refresh(); }, @@ -314,6 +317,9 @@ export function ShortcutsSection({ platform }: { platform: PlatformCapabilities onSave={command.save} onDisable={command.disable} onReset={command.reset} + comboOnly={ + command.id === 'skipAutoStyle' && capability?.adapter === 'windowsLowLevel' + } sideSpecificModifiers={command.id === 'dictation'} />
@@ -325,9 +331,10 @@ export function ShortcutsSection({ platform }: { platform: PlatformCapabilities on={prefs.skipAutoStylePickerEnabled ?? false} onToggle={(skipAutoStylePickerEnabled) => { // The shared preference store handles rollback and error feedback. - void updatePrefs((current) => ({ ...current, skipAutoStylePickerEnabled })).catch( - () => {}, - ); + void updatePrefs((current) => ({ + ...current, + skipAutoStylePickerEnabled, + })).catch(() => {}); }} />
diff --git a/openless-all/app/src/i18n/de.ts b/openless-all/app/src/i18n/de.ts index 69d90c786..42a24dee8 100644 --- a/openless-all/app/src/i18n/de.ts +++ b/openless-all/app/src/i18n/de.ts @@ -2068,6 +2068,7 @@ export const de: typeof zhCN = { switchStyle: 'Zum vorherigen Stil wechseln', skipAutoStyle: 'Automatischen Stil überspringen', skipAutoStylePicker: 'Stil nach Tastendruck wählen', + skipAutoStyleComboRequired: 'Verwende eine Tastenkombination.', openApp: 'OpenLess öffnen', stylePackTitle: 'Stilkurzbefehle', stylePackDesc: diff --git a/openless-all/app/src/i18n/en.ts b/openless-all/app/src/i18n/en.ts index 27c39032c..1997500eb 100644 --- a/openless-all/app/src/i18n/en.ts +++ b/openless-all/app/src/i18n/en.ts @@ -2022,6 +2022,7 @@ export const en: typeof zhCN = { switchStyle: 'Switch to previous style', skipAutoStyle: 'Skip auto style', skipAutoStylePicker: 'Choose output style on press', + skipAutoStyleComboRequired: 'Use a key combination.', openApp: 'Open OpenLess', stylePackTitle: 'Style shortcuts', stylePackDesc: diff --git a/openless-all/app/src/i18n/es.ts b/openless-all/app/src/i18n/es.ts index e7485c54c..f710e30b2 100644 --- a/openless-all/app/src/i18n/es.ts +++ b/openless-all/app/src/i18n/es.ts @@ -2054,6 +2054,7 @@ export const es: typeof zhCN = { switchStyle: 'Cambiar al estilo anterior', skipAutoStyle: 'Omitir estilo automático', skipAutoStylePicker: 'Elegir estilo al pulsar', + skipAutoStyleComboRequired: 'Usa una combinación de teclas.', openApp: 'Abrir OpenLess', stylePackTitle: 'Atajos de estilos', stylePackDesc: diff --git a/openless-all/app/src/i18n/fr.ts b/openless-all/app/src/i18n/fr.ts index dd4907db0..2f34ed352 100644 --- a/openless-all/app/src/i18n/fr.ts +++ b/openless-all/app/src/i18n/fr.ts @@ -2081,6 +2081,7 @@ export const fr: typeof zhCN = { switchStyle: 'Passer au style précédent', skipAutoStyle: 'Ignorer le style automatique', skipAutoStylePicker: 'Choisir le style après appui', + skipAutoStyleComboRequired: 'Utilisez une combinaison de touches.', openApp: 'Ouvrir OpenLess', stylePackTitle: 'Raccourcis de styles', stylePackDesc: diff --git a/openless-all/app/src/i18n/ja.ts b/openless-all/app/src/i18n/ja.ts index 979eca727..9d1701964 100644 --- a/openless-all/app/src/i18n/ja.ts +++ b/openless-all/app/src/i18n/ja.ts @@ -2005,6 +2005,7 @@ export const ja: typeof zhCN = { switchStyle: '前のスタイルに切り替え', skipAutoStyle: '自動スタイルをスキップ', skipAutoStylePicker: '押した後にスタイルを選択', + skipAutoStyleComboRequired: 'キーの組み合わせを使用してください。', openApp: 'OpenLess を開く', stylePackTitle: 'スタイル直行ショートカット', stylePackDesc: diff --git a/openless-all/app/src/i18n/ko.ts b/openless-all/app/src/i18n/ko.ts index c70540215..9d715a387 100644 --- a/openless-all/app/src/i18n/ko.ts +++ b/openless-all/app/src/i18n/ko.ts @@ -1992,6 +1992,7 @@ export const ko: typeof zhCN = { switchStyle: '이전 스타일로 전환', skipAutoStyle: '자동 스타일 건너뛰기', skipAutoStylePicker: '누른 후 스타일 선택', + skipAutoStyleComboRequired: '키 조합을 사용해 주세요.', openApp: 'OpenLess 열기', stylePackTitle: '스타일 바로가기 단축키', stylePackDesc: diff --git a/openless-all/app/src/i18n/zh-CN.ts b/openless-all/app/src/i18n/zh-CN.ts index 31e645d10..420b34c4e 100644 --- a/openless-all/app/src/i18n/zh-CN.ts +++ b/openless-all/app/src/i18n/zh-CN.ts @@ -1914,6 +1914,7 @@ export const zhCN = { switchStyle: '切换到上一个风格', skipAutoStyle: '跳过自动风格', skipAutoStylePicker: '按下时选择输出风格', + skipAutoStyleComboRequired: '请使用组合键。', openApp: '打开 OpenLess', stylePackTitle: '风格直达快捷键', stylePackDesc: '为常用风格包各配一个快捷键,按下直接切换;停用中的包会自动启用。', diff --git a/openless-all/app/src/i18n/zh-TW.ts b/openless-all/app/src/i18n/zh-TW.ts index 6f03265bd..0599e5bec 100644 --- a/openless-all/app/src/i18n/zh-TW.ts +++ b/openless-all/app/src/i18n/zh-TW.ts @@ -1916,6 +1916,7 @@ export const zhTW: typeof zhCN = { switchStyle: '切換到上一個風格', skipAutoStyle: '跳過自動風格', skipAutoStylePicker: '按下時選擇輸出風格', + skipAutoStyleComboRequired: '請使用組合鍵。', openApp: '開啟 OpenLess', stylePackTitle: '風格直達快捷鍵', stylePackDesc: '為常用風格包各配一個快捷鍵,按下直接切換;停用中的包會自動啟用。', diff --git a/openless-all/app/src/lib/ipc/mock-data.ts b/openless-all/app/src/lib/ipc/mock-data.ts index 504129f41..2c9b7e0ea 100644 --- a/openless-all/app/src/lib/ipc/mock-data.ts +++ b/openless-all/app/src/lib/ipc/mock-data.ts @@ -18,6 +18,7 @@ import type { import { OL_DATA } from '../mockData'; import { publishPreviewChange } from '../../preview/events'; import { readPreviewThemePreference } from '../../preview/preferences'; +import { getShortcutPlatform } from '../../runtime/environment'; import { defaultAppShortcutModifiers, defaultSelectionPolishShortcut } from '../hotkey'; export let mockSettings: UserPreferences = { @@ -95,12 +96,7 @@ export let mockSettings: UserPreferences = { qaSaveHistory: false, customComboHotkey: null, skipAutoStyleHotkey: { - primary: - typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) - ? 'LeftCommand' - : typeof navigator !== 'undefined' && /Win/.test(navigator.platform) - ? '' - : 'LeftAlt', + primary: getShortcutPlatform().isMac ? 'LeftCommand' : '', modifiers: [], }, skipAutoStylePickerEnabled: false, From ce8d1b425a6383ab0d235a50fc00601b41fe8dc5 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:40:24 +0800 Subject: [PATCH 05/13] feat(capsule): show and choose session output styles --- .../skip-auto-style-ui-contract.test.mjs | 82 ++++ .../app/scripts/windows-ui-config.test.mjs | 2 +- openless-all/app/src/api/dictation.ts | 9 + .../app/src/features/capsule/Capsule.tsx | 262 ++++++------- .../features/capsule/CapsuleStyleBadge.tsx | 351 ++++++++++++++++++ .../src/features/capsule/CapsuleStyles.css | 113 +++++- .../capsule/CapsuleTranslationBadge.tsx | 9 +- .../capsule/capsuleOutputStyle.test.ts | 108 ++++++ .../features/capsule/capsuleOutputStyle.ts | 126 +++++++ .../capsule/capsulePickerMenu.test.ts | 134 ++++++- .../src/features/capsule/capsulePickerMenu.ts | 86 ++++- .../features/capsule/useCapsulePickerMenu.ts | 2 +- openless-all/app/src/lib/ipc/dictation.ts | 26 +- openless-all/app/src/lib/ipc/index.ts | 1 + openless-all/app/src/lib/types.ts | 20 + 15 files changed, 1152 insertions(+), 179 deletions(-) create mode 100644 openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs create mode 100644 openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx create mode 100644 openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts create mode 100644 openless-all/app/src/features/capsule/capsuleOutputStyle.ts diff --git a/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs b/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs new file mode 100644 index 000000000..bacb95c09 --- /dev/null +++ b/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8'); + +const shortcuts = read('src/features/input/ShortcutsSection.tsx'); +const mockSettings = read('src/lib/ipc/mock-data.ts'); +assert.match(shortcuts, /supportsSkipAutoStyleHotkey\(platform, capability\?\.adapter\)/); +assert.match(shortcuts, /binding: prefs\.skipAutoStyleHotkey/); +assert.match( + shortcuts, + /capability\?\.adapter === 'windowsLowLevel' && binding\.modifiers\.length === 0/, +); +assert.match(shortcuts, /await setSkipAutoStyleHotkey\(binding\)/); +assert.match(shortcuts, /await setSkipAutoStyleHotkey\(null\)/); +assert.match(shortcuts, /on=\{prefs\.skipAutoStylePickerEnabled \?\? false\}/); +assert.match( + shortcuts, + /updatePrefs\(\(current\) => \(\{\s*\.\.\.current,\s*skipAutoStylePickerEnabled,?\s*\}\)\)/, +); +assert.match( + mockSettings, + /skipAutoStyleHotkey: \{\s*primary: getShortcutPlatform\(\)\.isMac \? 'LeftCommand' : ''/, +); +assert.match(mockSettings, /skipAutoStylePickerEnabled: false/); + +const capsule = read('src/features/capsule/Capsule.tsx'); +const languageBadge = read('src/features/capsule/CapsuleTranslationBadge.tsx'); +const styleBadge = read('src/features/capsule/CapsuleStyleBadge.tsx'); +const subscriptions = read('src/api/dictation.ts'); +const ipc = read('src/lib/ipc/dictation.ts'); +assert.match(capsule, /projectCapsuleOutputStyle\(p\)/); +assert.match( + capsule, + /preferences\.showCapsule && preferences\.skipAutoStylePickerEnabled === true/, +); +assert.match(capsule, / void) => events.listen('capsule:state', onPayload, 'window'), + styleMenuRequests: (onPayload: (payload: CapsuleStyleMenuRequest) => void) => + events.listen('capsule:style-menu-request', onPayload, 'window'), + styleMenuKeys: (onPayload: (payload: CapsuleStyleMenuKey) => void) => + events.listen('capsule:style-menu-key', onPayload, 'window'), + styleMenuClosed: (onPayload: (payload: CapsuleStyleMenuIdentity) => void) => + events.listen('capsule:style-menu-closed', onPayload, 'window'), jobs: (onPayload: (payload: CapsuleProcessingJob[]) => void) => events.listen('dictation:jobs', onPayload, 'app'), transcript: (onPayload: (payload: BackendEvent) => void) => diff --git a/openless-all/app/src/features/capsule/Capsule.tsx b/openless-all/app/src/features/capsule/Capsule.tsx index 4d4aa7f92..28e63bb3c 100644 --- a/openless-all/app/src/features/capsule/Capsule.tsx +++ b/openless-all/app/src/features/capsule/Capsule.tsx @@ -10,6 +10,12 @@ import { VoiceOrbStage } from './VoiceOrbStage'; import { DEFAULT_CAPSULE_EXIT_MS, OpenLessPill } from './OpenLessCapsule'; import { CapsuleTranscriptRail, CapsuleTranslationBadge } from './LiveTranscriptPill'; import { CapsulePickerMenu } from './capsulePickerMenu'; +import { CapsuleStyleBadge } from './CapsuleStyleBadge'; +import { + projectCapsuleOutputStyle, + sameCapsuleOutputStyle, + type CapsuleOutputStyle, +} from './capsuleOutputStyle'; import { useMainCaptionTrace } from './useMainCaptionTrace'; import { capsuleTranscriptFontSize, visibleCapsuleTranscript } from '../../lib/capsuleTranscript'; import { getSettings } from '../../api/preferences'; @@ -186,7 +192,6 @@ function SelectionPolishNotice({ state, message }: SelectionPolishNoticeProps) { // white-and-blue recording/processing surface inside that stable host. interface ClassicCapsuleProps { - pickerController: CapsulePickerMenu; sessionId?: string; os: OS; state: CapsuleState; @@ -195,8 +200,6 @@ interface ClassicCapsuleProps { message?: string; transcript?: string; transcriptFontSize?: number; - transcriptVisible?: boolean; - transcriptInSameWindow?: boolean; operating: boolean; translation: boolean; leaving: boolean; @@ -204,12 +207,11 @@ interface ClassicCapsuleProps { } /** - * Classic pill + "translating" badge (matching 1.3.14). Cancel/confirm call the + * Classic pill and transcript. Cancel/confirm call the * dictation commands directly (the capsule window never takes focus, so button * interaction only appears while recording). */ function ClassicCapsule({ - pickerController, sessionId, os, state, @@ -218,8 +220,6 @@ function ClassicCapsule({ message, transcript, transcriptFontSize = 14, - transcriptVisible = false, - transcriptInSameWindow = true, operating, translation, leaving, @@ -232,71 +232,35 @@ function ClassicCapsule({ const onConfirm = useCallback(() => { void stopDictation(sessionId); }, [sessionId]); - const reduced = useReducedMotion(); - // The top floating translation badge reflects only the current foreground session, - // never background processing jobs (which show their own status on the rear satellite). - const translating = translation && (state === 'recording' || state === 'transcribing' || state === 'polishing'); const liveText = transcript?.trim() ?? ''; - const classicGeometry = getClassicCapsuleGeometry( - os, - transcriptVisible || Boolean(liveText), - translating, - transcriptInSameWindow, - ); return ( - <> - {/* "Translating" badge — two nested layers: - the outer layer only does absolute positioning + horizontal centering - (translateX(-50%)) with no animation; the inner layer only does vertical - shift + fade. This avoids conflicting with translateX(-50%) and avoids - keyframe vs inline transform overrides causing visual jumps. */} - {/* The language picker belongs to the interactive capsule, even when - Windows puts the transcript in a separate click-through rail. */} - - + {liveText && ( + - -
- {liveText && ( - - )} - -
- + )} + +
); } @@ -406,6 +370,8 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { const transcriptViewRef = useRef(createTranscriptViewState()); const capsuleStateRef = useRef(preview.state); const [translation, setTranslation] = useState(preview.translation); + const [outputStyle, setOutputStyle] = useState(null); + const [stylePickerEnabled, setStylePickerEnabled] = useState(false); const [selectionPolish, setSelectionPolish] = useState(preview.selectionPolish); // Preference events restyle live; recording state carries the same style so the // first show also renders correctly. @@ -553,6 +519,10 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { transcriptViewRef.current = nextTranscript; if (nextTranscript !== previousTranscript) setLocalAsrText(nextTranscript.text); setTranslation(p.translation === true); + const nextOutputStyle = projectCapsuleOutputStyle(p); + setOutputStyle((current) => + sameCapsuleOutputStyle(current, nextOutputStyle) ? current : nextOutputStyle, + ); setWarming(p.warming === true); setSelectionPolish(p.selectionPolish === true); const style = parseCapsuleStyle(p.capsuleStyle); @@ -651,6 +621,9 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { if ( !(await events.preferences((preferences) => { preferenceRevision += 1; + setStylePickerEnabled( + preferences.showCapsule && preferences.skipAutoStylePickerEnabled === true, + ); setTranscriptEnabled(preferences.capsuleTranscriptEnabled ?? true); setTranscriptFontSize(capsuleTranscriptFontSize(preferences.capsuleTranscriptFontSize)); const next = parseCapsuleStyle(preferences.capsuleStyle); @@ -664,11 +637,16 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { const revisionAtRead = preferenceRevision; const preferences = await getSettings(); const next = parseCapsuleStyle(preferences.capsuleStyle); - if (!cancelled && revisionAtRead === preferenceRevision && next) { + if (!cancelled && revisionAtRead === preferenceRevision) { + setStylePickerEnabled( + preferences.showCapsule && preferences.skipAutoStylePickerEnabled === true, + ); setTranscriptEnabled(preferences.capsuleTranscriptEnabled ?? true); setTranscriptFontSize(capsuleTranscriptFontSize(preferences.capsuleTranscriptFontSize)); - stylePreferenceReadyRef.current = true; - setCapsuleStyle(next); + if (next) { + stylePreferenceReadyRef.current = true; + setCapsuleStyle(next); + } } })().catch((error) => console.warn('[capsule] preferences subscription failed', error)); return () => { @@ -762,7 +740,6 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { // suggestion card, and the hidden idle branch. const renderedState: CapsuleState = state === 'idle' ? lastVisibleState : state; const renderedSelectionPolish = state === 'idle' ? lastVisibleSelectionPolish : selectionPolish; - const showSiriBadge = !leaving && translation; const renderedMessage = state === 'idle' ? lastVisibleMessage @@ -781,6 +758,18 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { const showLiveTranscript = state !== 'idle' && liveTranscript.length > 0; const transcriptVisible = showLiveTranscript && (state === 'recording' || (!insertFallback && suggestions.length === 0)); + const translating = + !leaving && + translation && + (!isClassic || ['recording', 'transcribing', 'polishing'].includes(renderedState)); + const badgeOffset = isClassic + ? getClassicCapsuleGeometry( + os, + transcriptVisible || (!splitTranscriptRail && showLiveTranscript), + translating || Boolean(outputStyle), + !splitTranscriptRail, + ).badgeBottomOffset + : badgeBottom; const observeCaptionTrace = useMainCaptionTrace( transcriptViewRef, transcriptVisible && !splitTranscriptRail ? liveTranscript : '', @@ -985,10 +974,38 @@ export function Capsule({ os: forcedOs }: CapsuleProps = {}) { ); })()} + {!renderedSelectionPolish && ( + + {isClassic ? ( + + ) : ( +
+ + {t('capsule.translating')} +
+ )} + +
+ )} {!renderedSelectionPolish && (isClassic ? ( ) : ( - <> - {/* "Translating" badge — two nested layers: - the outer layer only does absolute positioning + horizontal centering - (translateX(-50%)) with no animation; the inner layer only does vertical - shift + fade. This avoids conflicting with translateX(-50%) and avoids - keyframe vs inline transform overrides causing visual jumps. */} +
+ {showLiveTranscript && !splitTranscriptRail && ( + + )}
-
- - {t('capsule.translating')} -
-
-
- {showLiveTranscript && !splitTranscriptRail && ( - - )} -
- -
+
- +
))} {renderedSelectionPolish && ( diff --git a/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx b/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx new file mode 100644 index 000000000..9b58025d7 --- /dev/null +++ b/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx @@ -0,0 +1,351 @@ +import { Popover } from '@base-ui/react/popover'; +import { memo, useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { + CapsuleStyleMenuKey, + CapsuleStyleMenuRequest, + DictationStyleTarget, +} from '../../api/contracts'; +import { + createCapsuleSubscriptions, + getCapsuleStyleMenuRequest, + getDictationStyleTarget, + setCapsuleStyleMenu, + updateDictationStyle, +} from '../../api/dictation'; +import { Icon } from '../../components/Icon'; +import { stylePackDisplayName } from '../../lib/stylePackPresentation'; +import { getRuntimeEnvironment } from '../../runtime/environment'; +import { usePopupViewport } from '../../ui/layout/AppViewport'; +import { + capsuleOutputStyleLabel, + CapsuleStylePickerRequests, + styleMenuKeyAction, + stylePickerRequestForSession, + type CapsuleOutputStyle, +} from './capsuleOutputStyle'; +import type { CapsulePickerDeps, CapsulePickerMenu } from './capsulePickerMenu'; +import { useCapsulePickerMenu } from './useCapsulePickerMenu'; +import '../../ui/styles/select.css'; +import './CapsuleStyles.css'; + +export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ + style, + pickerController, + pickerEnabled, + captureSessionId, +}: { + style: CapsuleOutputStyle | null; + pickerController: CapsulePickerMenu; + pickerEnabled: boolean; + captureSessionId?: string; +}) { + const { t } = useTranslation(); + const { boundary, container } = usePopupViewport(); + const anchor = useRef(null); + const highlightedOption = useRef(null); + const onKey = useRef<(event: Pick) => boolean>( + () => false, + ); + const failureId = useId(); + const [windowLabel, setWindowLabel] = useState(); + const [request, setRequest] = useState(null); + const [requests] = useState(() => new CapsuleStylePickerRequests()); + const [loaded, setLoaded] = useState<{ + requestId: string; + target: DictationStyleTarget; + } | null>(null); + const [error, setError] = useState(false); + const [saving, setSaving] = useState(false); + const choice = useRef(); + const [selectedId, setSelectedId] = useState(''); + const [highlightedId, setHighlightedId] = useState(''); + const cursor = useRef(''); + + useEffect(() => { + setRequest(null); + setWindowLabel(undefined); + if (!pickerEnabled || !captureSessionId || getRuntimeEnvironment().isMobile) return; + const events = createCapsuleSubscriptions(); + let disposed = false; + let requestRevision = 0; + void (async () => { + const label = await events.label(); + if (disposed || label !== 'capsule') return; + if (!(await events.styleMenuKeys((event) => pickerController.receiveStyleKey(event)))) return; + if (!(await events.styleMenuClosed((event) => pickerController.receiveStyleClose(event)))) + return; + if ( + !(await events.styleMenuRequests((next) => { + if (next.sessionId !== captureSessionId) return; + requestRevision += 1; + setRequest(next); + })) + ) + return; + setWindowLabel(label); + const revisionAtRead = requestRevision; + const pending = await getCapsuleStyleMenuRequest(); + if ( + !disposed && + requestRevision === revisionAtRead && + pending?.sessionId === captureSessionId + ) { + setRequest(pending); + } + })().catch((error) => { + if (!disposed) console.warn('[capsule] style picker input subscription failed', error); + }); + return () => { + disposed = true; + events.dispose(); + }; + }, [captureSessionId, pickerController, pickerEnabled]); + + const intent = stylePickerRequestForSession( + request, + captureSessionId, + pickerEnabled && Boolean(windowLabel) && Boolean(style), + ); + const requestId = intent?.requestId; + const sessionId = intent?.sessionId; + const target = + requestId && loaded?.requestId === requestId && loaded.target.sessionId === sessionId + ? loaded.target + : null; + const setNativeMenu = useCallback( + async (open, { sessionId, requestId }, nativeOwner) => { + if (!open) { + if (nativeOwner) + await setCapsuleStyleMenu(false, sessionId, { menuId: nativeOwner.menuId }); + return; + } + const owner = await setCapsuleStyleMenu(true, sessionId, { requestId }); + if (!owner?.menuId || owner.sessionId !== sessionId || owner.windowLabel !== windowLabel) { + throw new Error('The host did not return a matching style menu owner'); + } + return owner; + }, + [windowLabel], + ); + const menu = useCapsulePickerMenu({ + controller: pickerController, + kind: 'style', + anchor, + target, + visible: Boolean(intent), + setNativeMenu, + onFailure: () => setError(true), + }); + + useEffect(() => { + setError(false); + setSaving(false); + setLoaded(null); + choice.current = undefined; + if (!requestId || !sessionId || requests.hasConsumed({ requestId, sessionId })) return; + let disposed = false; + let retry: ReturnType | undefined; + const loadTarget = async () => { + try { + const next = await getDictationStyleTarget(); + if (disposed) return; + if (!next || (next.sessionId === sessionId && !next.mutable)) { + // The host can announce a tap during Starting, before the style context freezes. + retry = setTimeout(() => void loadTarget(), 120); + return; + } + if (next.sessionId === sessionId && next.selection.mode === 'skipAuto') { + setLoaded({ requestId, target: next }); + } + } catch { + if (!disposed) setError(true); + } + }; + void loadTarget(); + return () => { + disposed = true; + clearTimeout(retry); + choice.current = undefined; + }; + }, [requestId, requests, sessionId]); + + const highlight = (stylePackId: string) => { + cursor.current = stylePackId; + setHighlightedId(stylePackId); + }; + + useEffect(() => { + if (!intent || !target) return; + const initial = requests.take(intent, target); + if (!initial) return; + setSelectedId(initial); + highlight(initial); + void menu.openMenu(intent.requestId); + }, [intent, menu.openMenu, requests, target]); + + useLayoutEffect(() => { + if (menu.open) + highlightedOption.current?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + }, [menu.open, highlightedId]); + + useLayoutEffect(() => { + if (menu.open && sessionId && requestId) { + pickerController.enableStyleKeys(sessionId, requestId, (event) => onKey.current(event)); + } + }, [menu.open, pickerController, requestId, sessionId]); + + const choose = async (stylePackId: string) => { + if ( + !intent || + !menu.open || + !menu.owns(intent.sessionId, intent.requestId) || + !target?.availableStyles.some((pack) => pack.id === stylePackId) || + choice.current + ) + return; + const inFlight = Symbol(); + choice.current = inFlight; + setSaving(true); + setError(false); + try { + const updated = await updateDictationStyle(intent.sessionId, { + mode: 'stylePack', + stylePackId, + }); + if ( + choice.current === inFlight && + updated.sessionId === intent.sessionId && + menu.owns(intent.sessionId, intent.requestId) + ) + menu.close(); + } catch { + if (choice.current === inFlight && menu.owns(intent.sessionId, intent.requestId)) { + setError(true); + } + } finally { + if (choice.current === inFlight) { + choice.current = undefined; + setSaving(false); + } + } + }; + + onKey.current = (event) => { + if (!intent || !menu.owns(intent.sessionId, intent.requestId)) return false; + const action = styleMenuKeyAction(event, target?.availableStyles ?? [], cursor.current); + if (!action) return false; + if (action.type === 'close') menu.close(); + else if (action.type === 'highlight') highlight(action.stylePackId); + else void choose(action.stylePackId); + return true; + }; + + useEffect(() => { + if (!intent) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) + return; + const { key } = event; + if (key !== 'ArrowUp' && key !== 'ArrowDown' && key !== 'Enter' && key !== 'Escape') return; + if (onKey.current({ key, repeat: event.repeat })) { + event.preventDefault(); + event.stopPropagation(); + } + }; + window.addEventListener('keydown', onKeyDown, true); + return () => window.removeEventListener('keydown', onKeyDown, true); + }, [intent]); + + if (!style) return null; + const modeLabels = { + raw: t('style.modes.raw.name'), + light: t('style.modes.light.name'), + structured: t('style.modes.structured.name'), + formal: t('style.modes.formal.name'), + }; + const failed = error && !menu.open; + const label = failed + ? t('capsule.styleChangeFailed') + : (capsuleOutputStyleLabel(style, modeLabels) ?? t('settings.shortcuts.skipAutoStyle')); + + return ( + <> +
+ + + {label} + +
+ { + if (!next) menu.close(); + }} + modal={false} + > + + + +
+ {target?.availableStyles.map((pack) => { + const selected = pack.id === selectedId; + const highlighted = pack.id === highlightedId; + return ( + + ); + })} +
+ {error && ( + + {t('capsule.styleChangeFailed')} + + )} +
+
+
+
+ + ); +}); diff --git a/openless-all/app/src/features/capsule/CapsuleStyles.css b/openless-all/app/src/features/capsule/CapsuleStyles.css index 69702b30f..34d6e0caf 100644 --- a/openless-all/app/src/features/capsule/CapsuleStyles.css +++ b/openless-all/app/src/features/capsule/CapsuleStyles.css @@ -1,7 +1,8 @@ /* Shared by the recording pill and its translation badge in every host. */ .ol-default-capsule, .ol-processing-satellite, -.ol-classic-translation { +.ol-classic-translation, +.ol-capsule-style-badge { --ol-pill-scheme: light; --ol-pill-fill: rgb(255 255 255 / 92%); --ol-pill-border: rgb(79 91 115 / 24%); @@ -26,7 +27,8 @@ } [data-ol-theme='dark'] .ol-default-capsule, [data-ol-theme='dark'] .ol-processing-satellite, -[data-ol-theme='dark'] .ol-classic-translation { +[data-ol-theme='dark'] .ol-classic-translation, +[data-ol-theme='dark'] .ol-capsule-style-badge { --ol-pill-scheme: dark; --ol-pill-fill: rgb(32 39 52 / 92%); --ol-pill-border: rgb(218 231 255 / 26%); @@ -97,9 +99,24 @@ gap: 8px; } -.ol-classic-translation { +.ol-capsule-status-lane { + position: absolute; + inset-inline: 8px; + display: flex; + justify-content: center; + align-items: center; + gap: 6px; + pointer-events: none; +} +.ol-capsule-status-lane[data-with-style='true'][data-translating='false'] + > :is(.ol-classic-translation, .ol-siri-translation-badge) { + position: absolute; +} +.ol-classic-translation, +.ol-capsule-style-badge { display: inline-flex; - flex: 0 0 28px; + flex: 0 1 auto; + min-width: 0; height: 28px; box-sizing: border-box; align-items: center; @@ -118,14 +135,68 @@ white-space: nowrap; transform-origin: center bottom; will-change: transform, opacity; +} +.ol-classic-translation { transition: padding-right 200ms cubic-bezier(0.22, 1, 0.36, 1); } +.ol-capsule-style-badge { + flex: 0 0 auto; + gap: 5px; + height: auto; + min-height: 28px; + max-width: 100%; + font-size: 0.6875rem; + font-weight: var(--ol-font-weight-medium); +} +.ol-capsule-status-lane[data-translating='true'] .ol-capsule-style-badge { + max-width: max(42%, calc(100% - 250px)); +} +.ol-capsule-style-badge > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} +.ol-capsule-style-badge[data-error='true'] { + color: var(--ol-pill-error); +} +.ol-siri-translation-badge { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: 10.5px; + font-weight: var(--ol-font-weight-semibold); + color: var(--ol-capsule-center-ink); + background: var(--ol-capsule-badge-bg); + border: 1px solid var(--ol-capsule-pill-border); + border-radius: 999px; + padding: 4px 10px; + letter-spacing: 0.02em; + white-space: nowrap; + transform-origin: center bottom; + transition: opacity 0.24s ease-out, transform 0.34s cubic-bezier(0.2, 0.9, 0.3, 1.1); +} +.ol-siri-translation-badge[aria-hidden='true'] { + opacity: 0; + transform: translateY(40px) scale(0.88); +} +.ol-siri-translation-badge > span { + width: 5px; + height: 5px; + border-radius: 999px; + background: rgb(150 185 255 / 95%); + box-shadow: 0 0 8px rgb(90 140 255 / 90%); +} .ol-classic-translation[data-picker-open='true'] { padding-right: 4px; } .ol-classic-translation-label { flex: 0 0 auto; } +.ol-capsule-status-lane[data-with-style='true'] .ol-classic-translation-label { + flex: 0 1 auto; + overflow: hidden; + text-overflow: ellipsis; +} /* Pure CSS grid-template-columns 0fr -> 1fr avoids Framer Motion width:'auto' JS layout measurement stalls on first Shift press and after long idle. */ .ol-translation-language-collapse { @@ -145,6 +216,10 @@ margin-left: 6px; opacity: 1; } +.ol-capsule-status-lane[data-with-style='true'] .ol-translation-language-collapse { + flex: 0 1 auto; + min-width: 0; +} @media (prefers-reduced-motion: reduce) { .ol-translation-language-collapse { transition: none; @@ -162,15 +237,41 @@ width: max-content; max-width: 174px; } -.ol-select-popup.ol-capsule-language-popup { +.ol-select-popup.ol-capsule-picker-popup { background: var(--ol-select-popover-bg); backdrop-filter: none; -webkit-backdrop-filter: none; transition: none; } -.ol-capsule-language-popup[data-ending-style] { +.ol-capsule-picker-popup[data-ending-style] { pointer-events: none; } +.ol-select-popup.ol-capsule-style-popup { + width: 19rem; + font-size: 0.8125rem; +} +.ol-select-item.ol-capsule-style-option { + width: 100%; + min-height: 2rem; + border: 0; + color: inherit; + background: transparent; + font: inherit; + text-align: start; + grid-template-columns: minmax(0, 1fr) 12px; +} +.ol-select-item.ol-capsule-style-option > :first-child { + white-space: normal; + overflow-wrap: anywhere; +} +.ol-capsule-style-option .ol-select-check { + grid-column: 2; +} +.ol-capsule-style-error { + padding: 6px 10px; + color: var(--ol-err); + overflow-wrap: anywhere; +} .ol-translation-language .ol-select-trigger { height: 22px; min-width: 0; diff --git a/openless-all/app/src/features/capsule/CapsuleTranslationBadge.tsx b/openless-all/app/src/features/capsule/CapsuleTranslationBadge.tsx index e308c9189..48706d7d2 100644 --- a/openless-all/app/src/features/capsule/CapsuleTranslationBadge.tsx +++ b/openless-all/app/src/features/capsule/CapsuleTranslationBadge.tsx @@ -14,7 +14,7 @@ import { } from '../../api/dictation'; import { localizedLanguages, nativeLanguageName } from '../../lib/languageCatalog'; import { isTranslationTargetRedundant } from '../../lib/translationTarget'; -import type { CapsulePickerDeps, CapsulePickerMenu } from './capsulePickerMenu'; +import { CapsulePickerMenu, type CapsulePickerDeps } from './capsulePickerMenu'; import { useCapsulePickerMenu } from './useCapsulePickerMenu'; import './CapsuleStyles.css'; @@ -27,12 +27,13 @@ export const CapsuleTranslationBadge = memo(function CapsuleTranslationBadge({ visible = true, processing = false, }: { - pickerController: CapsulePickerMenu; + pickerController?: CapsulePickerMenu; visible?: boolean; processing?: boolean; }) { const { t, i18n } = useTranslation(); const reduced = useReducedMotion(); + const [standalonePicker] = useState(() => pickerController ?? new CapsulePickerMenu()); const [snapshot, setSnapshot] = useState(null); const [savedTarget, setSavedTarget] = useState(''); const [busy, setBusy] = useState(false); @@ -120,7 +121,7 @@ export const CapsuleTranslationBadge = memo(function CapsuleTranslationBadge({ }, [snapshot?.sessionId]); const menu = useCapsulePickerMenu({ - controller: pickerController, + controller: pickerController ?? standalonePicker, kind: 'language', setNativeMenu, anchor, @@ -199,7 +200,7 @@ export const CapsuleTranslationBadge = memo(function CapsuleTranslationBadge({ onChange={(value) => void change(value)} side="top" popupStyle={{ width: 240 }} - popupClassName="ol-capsule-language-popup" + popupClassName="ol-capsule-picker-popup" /> diff --git a/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts b/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts new file mode 100644 index 000000000..d06f00d7b --- /dev/null +++ b/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts @@ -0,0 +1,108 @@ +import type { CapsuleStyleMenuRequest, DictationStyleTarget, StylePack } from '../../api/contracts'; +import { + capsuleOutputStyleLabel, + CapsuleStylePickerRequests, + projectCapsuleOutputStyle, + sameCapsuleOutputStyle, + styleMenuKeyAction, + stylePickerRequestForSession, +} from './capsuleOutputStyle'; + +function expect(actual: unknown, expected: unknown) { + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + throw new Error(`Expected ${JSON.stringify(expected)}, received ${JSON.stringify(actual)}`); + } +} + +const request = { requestId: '13', sessionId: 'recording-a' }; +const frame = { + state: 'recording', + stylePackId: 'builtin.formal', + stylePackName: '正式表达', + skipAutoStyle: true, +} as const; +const style = { packId: 'builtin.formal', name: '正式表达' }; + +expect(projectCapsuleOutputStyle({ ...frame, skipAutoStyle: false }), null); +expect(projectCapsuleOutputStyle({ ...frame, state: 'idle' }), null); +expect(projectCapsuleOutputStyle({ ...frame, selectionPolish: true }), null); +expect(projectCapsuleOutputStyle({ ...frame, qa: true }), null); +expect(projectCapsuleOutputStyle(frame), style); +expect(projectCapsuleOutputStyle({ ...frame, state: 'polishing' }), style); +expect(sameCapsuleOutputStyle(projectCapsuleOutputStyle(frame), style), true); +expect(sameCapsuleOutputStyle(projectCapsuleOutputStyle(frame), null), false); + +const labels = { raw: 'Verbatim', light: 'Light', structured: 'Structured', formal: 'Formal' }; +expect(capsuleOutputStyleLabel(style, labels), 'Formal'); +expect(capsuleOutputStyleLabel({ ...style, name: ' My writing ' }, labels), 'My writing'); +expect(capsuleOutputStyleLabel({ ...style, name: null }, labels), 'Formal'); +expect(capsuleOutputStyleLabel({ packId: 'installed-pack-id', name: null }, labels), null); + +expect(stylePickerRequestForSession(request, request.sessionId, false), null); +expect(stylePickerRequestForSession(request, undefined, true), null); +expect(stylePickerRequestForSession(request, 'wrong-recording', true), null); +expect(stylePickerRequestForSession(null, request.sessionId, true), null); +expect(stylePickerRequestForSession(request, request.sessionId, true), request); + +const pack: StylePack = { + id: 'builtin.formal', + name: '正式表达', + description: '', + kind: 'builtin', + baseMode: 'formal', + version: '1.0.0', + selectionPrompt: '', + voiceEditPrompt: '', + prompt: '', + examples: [], + tags: [], + enabled: true, + active: true, +}; +const packs: StylePack[] = [ + { ...pack, id: 'installed', name: 'Editorial', kind: 'imported' }, + pack, + { ...pack, id: 'builtin.raw', name: '原文', baseMode: 'raw' }, +]; +const target: DictationStyleTarget = { + sessionId: request.sessionId, + selection: { mode: 'skipAuto' }, + skipAutoStyle: true, + stylePackId: 'installed', + stylePackName: 'Editorial', + polishStylePackId: 'builtin.formal', + availableStyles: packs, + mutable: true, +}; +const requests = new CapsuleStylePickerRequests(); +expect(requests.take(request, { ...target, mutable: false }), null); +expect(requests.take(request, { ...target, sessionId: 'old-recording' }), null); +expect(requests.take(request, { ...target, selection: { mode: 'automatic' } }), null); +expect(requests.take(request, target), 'builtin.formal'); +expect(requests.take(request, target), null); +expect(requests.take({ ...request, requestId: '14' }, target), 'builtin.formal'); +expect( + requests.take({ ...request, requestId: '15' }, { ...target, polishStylePackId: null }), + 'installed', +); +expect(requests.take(request, target), null); + +const successor: CapsuleStyleMenuRequest = { requestId: '2', sessionId: 'recording-b' }; +expect(requests.take(successor, { ...target, sessionId: successor.sessionId }), 'builtin.formal'); + +expect(styleMenuKeyAction({ key: 'ArrowDown', repeat: true }, packs, 'builtin.formal'), { + type: 'highlight', + stylePackId: 'builtin.raw', +}); +expect(styleMenuKeyAction({ key: 'ArrowUp', repeat: false }, packs, 'installed'), { + type: 'highlight', + stylePackId: 'builtin.raw', +}); +expect(styleMenuKeyAction({ key: 'Enter', repeat: false }, packs, 'installed'), { + type: 'select', + stylePackId: 'installed', +}); +expect(styleMenuKeyAction({ key: 'Escape', repeat: false }, [], ''), { type: 'close' }); +expect(styleMenuKeyAction({ key: 'Enter', repeat: false }, packs, 'removed'), undefined); +expect(styleMenuKeyAction({ key: 'Enter', repeat: true }, packs, 'installed'), undefined); +expect(styleMenuKeyAction({ key: 'Escape', repeat: true }, [], ''), undefined); diff --git a/openless-all/app/src/features/capsule/capsuleOutputStyle.ts b/openless-all/app/src/features/capsule/capsuleOutputStyle.ts new file mode 100644 index 000000000..c77d5c2f5 --- /dev/null +++ b/openless-all/app/src/features/capsule/capsuleOutputStyle.ts @@ -0,0 +1,126 @@ +import type { + CapsulePayload, + CapsuleStyleMenuKey, + CapsuleStyleMenuRequest, + DictationStyleTarget, + PolishMode, +} from '../../api/contracts'; +import { stylePackDisplayName } from '../../lib/stylePackPresentation'; + +export interface CapsuleOutputStyle { + packId: string | null; + name: string | null; +} + +export function sameCapsuleOutputStyle( + current: CapsuleOutputStyle | null, + next: CapsuleOutputStyle | null, +) { + return ( + current === next || + (current !== null && + next !== null && + current.packId === next.packId && + current.name === next.name) + ); +} + +export function projectCapsuleOutputStyle( + frame: Pick< + CapsulePayload, + | 'state' + | 'qa' + | 'selectionPolish' + | 'operating' + | 'skipAutoStyle' + | 'stylePackId' + | 'stylePackName' + >, +): CapsuleOutputStyle | null { + const capturing = frame.state === 'recording'; + if ( + !frame.skipAutoStyle || + frame.qa || + frame.selectionPolish || + frame.operating || + !(capturing || frame.state === 'transcribing' || frame.state === 'polishing') + ) + return null; + return { + packId: frame.stylePackId ?? null, + name: frame.stylePackName?.trim() || null, + }; +} + +export function capsuleOutputStyleLabel( + style: CapsuleOutputStyle, + labels: Record, +) { + const mode = (['raw', 'light', 'structured', 'formal'] as const).find( + (mode) => style.packId === `builtin.${mode}`, + ); + if (!mode) return style.name; + if (!style.name) return labels[mode]; + return stylePackDisplayName( + { id: `builtin.${mode}`, kind: 'builtin', baseMode: mode, name: style.name }, + labels, + ); +} + +export function stylePickerRequestForSession( + request: CapsuleStyleMenuRequest | null, + captureSessionId: string | undefined, + enabled: boolean, +) { + return enabled && request?.sessionId === captureSessionId ? request : null; +} + +export class CapsuleStylePickerRequests { + private sessionId: string | undefined; + private consumed = new Set(); + + hasConsumed(intent: CapsuleStyleMenuRequest) { + return this.sessionId === intent.sessionId && this.consumed.has(intent.requestId); + } + + take(intent: CapsuleStyleMenuRequest, target: DictationStyleTarget) { + if ( + this.hasConsumed(intent) || + intent.sessionId !== target.sessionId || + !target.mutable || + target.selection.mode !== 'skipAuto' + ) + return null; + const styles = target.availableStyles; + const initial = + styles.find(({ id }) => id === target.polishStylePackId) ?? + styles.find(({ id }) => id === target.stylePackId) ?? + styles[0]; + if (!initial) return null; + if (this.sessionId !== intent.sessionId) { + this.sessionId = intent.sessionId; + this.consumed.clear(); + } + this.consumed.add(intent.requestId); + return initial.id; + } +} + +export type StyleMenuKeyAction = + { type: 'close' } | { type: 'highlight' | 'select'; stylePackId: string }; + +export function styleMenuKeyAction( + { key, repeat }: Pick, + availableStyles: ReadonlyArray<{ id: string }>, + highlightedId: string, +): StyleMenuKeyAction | undefined { + if ((key === 'Escape' || key === 'Enter') && repeat) return; + if (key === 'Escape') return { type: 'close' }; + const index = availableStyles.findIndex(({ id }) => id === highlightedId); + if (index < 0) return; + if (key === 'Enter') return { type: 'select', stylePackId: highlightedId }; + if (key !== 'ArrowUp' && key !== 'ArrowDown') return; + const step = key === 'ArrowUp' ? -1 : 1; + const next = (index + step + availableStyles.length) % availableStyles.length; + return { type: 'highlight', stylePackId: availableStyles[next].id }; +} diff --git a/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts b/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts index 25ab1be50..447e44818 100644 --- a/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts +++ b/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts @@ -1,4 +1,5 @@ import { CapsulePickerMenu, type CapsulePickerDeps } from './capsulePickerMenu'; +import type { CapsuleStyleMenuKey, CapsuleStyleMenuOwner } from '../../api/contracts'; function expect(actual: unknown, expected: unknown) { if (JSON.stringify(actual) !== JSON.stringify(expected)) { @@ -36,18 +37,133 @@ await controller.open({ ...style, sessionId: 'next', requestId: 'open-2' }, deps controller.close('style'); await controller.open({ ...language, sessionId: 'next' }, deps); expect(log, [ - 'language:true:first', 'render:true', 'render:false', 'language:false:first', - 'style:true:first', 'render:true', 'render:false', 'style:false:first', - 'style:true:next', 'render:true', 'render:false', 'style:false:next', - 'language:true:next', 'render:true', + 'language:true:first', + 'render:true', + 'render:false', + 'language:false:first', + 'style:true:first', + 'render:true', + 'render:false', + 'style:false:first', + 'style:true:next', + 'render:true', + 'render:false', + 'style:false:next', + 'language:true:next', + 'render:true', ]); +const inputController = new CapsulePickerMenu(); +const nativeOwner: CapsuleStyleMenuOwner = { + sessionId: style.sessionId, + menuId: 'menu-1', + windowLabel: 'capsule', + keyboardAvailable: true, +}; +const key: CapsuleStyleMenuKey = { + sessionId: style.sessionId, + menuId: nativeOwner.menuId, + key: 'ArrowDown', + repeat: false, +}; +const received: string[] = []; +const closedByFrontend: string[] = []; +let startReserve = () => {}; +let finishReserve = (_: CapsuleStyleMenuOwner) => {}; +const reserveStarted = new Promise((resolve) => { + startReserve = resolve; +}); +const reserve = inputController.open(style, { + ...deps, + setNativeMenu: async (open, _, reserved) => { + if (!open) { + closedByFrontend.push(reserved!.menuId); + return; + } + return new Promise((resolve) => { + finishReserve = resolve; + startReserve(); + }); + }, +}); +await reserveStarted; +inputController.receiveStyleKey({ ...key, menuId: 'menu-old' }); +inputController.receiveStyleKey(key); +inputController.receiveStyleClose({ ...key, menuId: 'menu-old' }); +finishReserve(nativeOwner); +await reserve; +expect(received, []); +inputController.enableStyleKeys(style.sessionId, style.requestId, (event) => + received.push(event.key), +); +expect(received, ['ArrowDown']); +inputController.receiveStyleKey({ ...key, sessionId: 'previous' }); +inputController.receiveStyleKey({ ...key, menuId: 'menu-old' }); +inputController.receiveStyleClose({ ...key, menuId: 'menu-old' }); +inputController.receiveStyleKey({ ...key, key: 'ArrowUp' }); +expect(received, ['ArrowDown', 'ArrowUp']); + +// A foreground move can revoke ownership without focusing or blurring the WebView. +inputController.receiveStyleClose(nativeOwner); +inputController.receiveStyleClose(nativeOwner); +inputController.receiveStyleKey(key); +expect(inputController.owns('style', style.sessionId, style.requestId), false); +expect(received, ['ArrowDown', 'ArrowUp']); + +const nativeDeps: CapsulePickerDeps = { + ...deps, + setNativeMenu: async (open, owner, reserved) => { + if (open) return { ...nativeOwner, menuId: owner.requestId!, keyboardAvailable: false }; + if (reserved) closedByFrontend.push(reserved.menuId); + }, +}; +const replacement = { ...style, requestId: 'menu-2' }; +await inputController.open(replacement, nativeDeps); +inputController.receiveStyleClose(nativeOwner); +inputController.enableStyleKeys(style.sessionId, replacement.requestId, (event) => + received.push(event.key), +); +inputController.receiveStyleKey({ ...key, menuId: replacement.requestId }); +expect(received, ['ArrowDown', 'ArrowUp']); +expect(inputController.owns('style', style.sessionId, replacement.requestId), true); +expect(closedByFrontend, []); +inputController.close('style'); +inputController.receiveStyleClose({ ...nativeOwner, menuId: replacement.requestId }); +await inputController.open(language, deps); +expect(closedByFrontend, ['menu-2']); + +const closedBeforeResponse = new CapsulePickerMenu(); +let acknowledgeReservation = (_: CapsuleStyleMenuOwner) => {}; +const hostClosedEarly = closedBeforeResponse.open(style, { + ...nativeDeps, + setNativeMenu: async (open, _, reserved) => { + if (!open) { + if (reserved) closedByFrontend.push(reserved.menuId); + return; + } + return new Promise((resolve) => { + acknowledgeReservation = resolve; + }); + }, + onOpenChange: (open) => received.push(`render:${open}`), +}); +await new Promise((resolve) => setTimeout(resolve, 0)); +closedBeforeResponse.receiveStyleClose(nativeOwner); +acknowledgeReservation(nativeOwner); +await hostClosedEarly; +await closedBeforeResponse.open(language, deps); +expect(received, ['ArrowDown', 'ArrowUp', 'render:false']); +expect(closedByFrontend, ['menu-2']); + log.length = 0; const openingController = new CapsulePickerMenu(); let finishGeometry: () => void = () => {}; const opening = openingController.open(style, { ...deps, - waitForGeometry: () => new Promise((resolve) => { finishGeometry = resolve; }), + waitForGeometry: () => + new Promise((resolve) => { + finishGeometry = resolve; + }), }); await new Promise((resolve) => setTimeout(resolve, 0)); openingController.handleKeydown('style', { @@ -58,6 +174,10 @@ finishGeometry(); await opening; await openingController.open(language, deps); expect(log, [ - 'style:true:first', 'escape', 'render:false', 'style:false:first', - 'language:true:first', 'render:true', + 'style:true:first', + 'escape', + 'render:false', + 'style:false:first', + 'language:true:first', + 'render:true', ]); diff --git a/openless-all/app/src/features/capsule/capsulePickerMenu.ts b/openless-all/app/src/features/capsule/capsulePickerMenu.ts index 276bb2b65..880d385eb 100644 --- a/openless-all/app/src/features/capsule/capsulePickerMenu.ts +++ b/openless-all/app/src/features/capsule/capsulePickerMenu.ts @@ -1,3 +1,9 @@ +import type { + CapsuleStyleMenuIdentity, + CapsuleStyleMenuKey, + CapsuleStyleMenuOwner, +} from '../../api/contracts'; + /** * Session-bound lifecycle shared by the capsule's language and style pickers. * @@ -22,7 +28,11 @@ export interface CapsulePickerOwner { export interface CapsulePickerDeps { /** Reserve (`true`) or restore (`false`) the native headroom for a session. */ - setNativeMenu: (open: boolean, owner: CapsulePickerOwner) => Promise; + setNativeMenu: ( + open: boolean, + owner: CapsulePickerOwner, + nativeOwner?: CapsuleStyleMenuOwner, + ) => Promise; /** Whether a native host owns the geometry; the browser preview has none. */ native: boolean; /** Resolves once the anchor and viewport can hold the popup. */ @@ -38,6 +48,12 @@ interface Reservation extends CapsulePickerOwner { abort: AbortController; nativeWriteStarted: boolean; mounted: boolean; + nativeOwner?: CapsuleStyleMenuOwner; + styleInput?: { + keys: CapsuleStyleMenuKey[]; + closedMenuIds: Set; + receiveKey?: (event: CapsuleStyleMenuKey) => void; + }; } export class CapsulePickerMenu { @@ -66,6 +82,47 @@ export class CapsulePickerMenu { } } + receiveStyleKey(event: CapsuleStyleMenuKey) { + const owner = this.styleReservation(event); + if (!owner?.styleInput || owner.nativeOwner?.keyboardAvailable === false) return; + const input = owner.styleInput; + if (input.receiveKey) { + input.receiveKey(event); + } else if (input.keys.length < 64) { + // The host can route keys as soon as it reserves geometry, before the + // response returns or React has mounted the list. + input.keys.push(event); + } + } + + receiveStyleClose(event: CapsuleStyleMenuIdentity) { + const owner = this.styleReservation(event); + if (!owner) return; + if (owner.nativeOwner) { + owner.nativeWriteStarted = false; + this.close('style'); + } else { + owner.styleInput?.closedMenuIds.add(event.menuId); + } + } + + enableStyleKeys( + sessionId: string, + requestId: string, + receiveKey: (event: CapsuleStyleMenuKey) => void, + ) { + const owner = this.reservation; + if ( + !owner?.mounted || + !owner.styleInput || + !owner.nativeOwner?.keyboardAvailable || + !this.owns('style', sessionId, requestId) + ) + return; + owner.styleInput.receiveKey = receiveKey; + for (const key of owner.styleInput.keys.splice(0)) this.receiveStyleKey(key); + } + async open(request: CapsulePickerOwner, deps: CapsulePickerDeps) { const previous = this.reservation; if ( @@ -85,6 +142,7 @@ export class CapsulePickerMenu { abort: new AbortController(), nativeWriteStarted: false, mounted: false, + styleInput: request.kind === 'style' ? { keys: [], closedMenuIds: new Set() } : undefined, }; this.reservation = owner; try { @@ -92,8 +150,15 @@ export class CapsulePickerMenu { await this.enqueue(async () => { if (owner.abort.signal.aborted) return; owner.nativeWriteStarted = true; - await deps.setNativeMenu(true, owner); + const nativeOwner = await deps.setNativeMenu(true, owner); + if (!nativeOwner) return; + owner.nativeOwner = nativeOwner; + if (owner.styleInput?.closedMenuIds.has(nativeOwner.menuId)) { + owner.nativeWriteStarted = false; + if (this.reservation === owner) this.close(owner.kind); + } }); + if (owner.abort.signal.aborted) return; await deps.waitForGeometry(owner.abort.signal); } if (this.reservation !== owner || owner.abort.signal.aborted) return; @@ -147,6 +212,17 @@ export class CapsulePickerMenu { if (this.exiting?.kind === kind) this.release(this.exiting); } + private styleReservation(event: CapsuleStyleMenuIdentity) { + const owner = this.reservation; + if ( + owner?.styleInput && + owner.nativeWriteStarted && + owner.sessionId === event.sessionId && + (!owner.nativeOwner || owner.nativeOwner.menuId === event.menuId) + ) + return owner; + } + private enqueue(operation: () => Promise) { const result = this.tail.catch(() => undefined).then(operation); this.tail = result; @@ -159,10 +235,8 @@ export class CapsulePickerMenu { void this.enqueue(async () => { if (owner.nativeWriteStarted) { owner.nativeWriteStarted = false; - await owner.deps.setNativeMenu(false, owner); + await owner.deps.setNativeMenu(false, owner, owner.nativeOwner); } - }).catch((error) => - console.warn('[capsule] failed to restore picker menu geometry', error), - ); + }).catch((error) => console.warn('[capsule] failed to restore picker menu geometry', error)); } } diff --git a/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts b/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts index 705357296..6b120ba90 100644 --- a/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts +++ b/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts @@ -70,7 +70,7 @@ export function useCapsulePickerMenu({ useEffect(() => { const onKeydown = (event: KeyboardEvent) => controller.handleKeydown(kind, event); window.addEventListener('blur', close); - window.addEventListener('keydown', onKeydown); + if (kind === 'language') window.addEventListener('keydown', onKeydown); return () => { window.removeEventListener('blur', close); window.removeEventListener('keydown', onKeydown); diff --git a/openless-all/app/src/lib/ipc/dictation.ts b/openless-all/app/src/lib/ipc/dictation.ts index 4c0aeea88..4ac657fa6 100644 --- a/openless-all/app/src/lib/ipc/dictation.ts +++ b/openless-all/app/src/lib/ipc/dictation.ts @@ -1,7 +1,13 @@ import { previewHistory } from '../../preview/history'; import { isDesktop } from './platform-exports'; import { invokeOrMock, isTauriNow, platformCapabilities, requireBackendReady } from './shared'; -import type { CapsuleSnapshot, DictationStyleSelection, DictationStyleTarget } from '../types'; +import type { + CapsuleSnapshot, + CapsuleStyleMenuOwner, + CapsuleStyleMenuRequest, + DictationStyleSelection, + DictationStyleTarget, +} from '../types'; export function startDictation(): Promise { return invokeOrMock('start_dictation', undefined, () => { @@ -95,7 +101,19 @@ export function setCapsuleLanguageMenu(open: boolean, sessionId: string): Promis 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); +export function getCapsuleStyleMenuRequest(): Promise { + return invokeOrMock('get_capsule_style_menu_request', undefined, () => null); +} + +/** Shares headroom with the language popup and binds input/close to the returned menu ID. */ +export function setCapsuleStyleMenu( + open: boolean, + sessionId: string, + owner?: { requestId?: string; menuId?: string }, +): Promise { + return invokeOrMock( + 'set_capsule_style_menu', + { open, sessionId, requestId: owner?.requestId, menuId: owner?.menuId }, + () => null, + ); } diff --git a/openless-all/app/src/lib/ipc/index.ts b/openless-all/app/src/lib/ipc/index.ts index ffd9a062c..5a5106277 100644 --- a/openless-all/app/src/lib/ipc/index.ts +++ b/openless-all/app/src/lib/ipc/index.ts @@ -103,6 +103,7 @@ export { setCapsuleTranscriptVisible, handleWindowHotkeyEvent, getDictationStyleTarget, + getCapsuleStyleMenuRequest, updateDictationStyle, setCapsuleStyleMenu, } from './dictation'; diff --git a/openless-all/app/src/lib/types.ts b/openless-all/app/src/lib/types.ts index 7286a588b..56cda25ad 100644 --- a/openless-all/app/src/lib/types.ts +++ b/openless-all/app/src/lib/types.ts @@ -858,6 +858,26 @@ export type CapsuleState = /** Recording capsule style: 'siri' = flowing Siri light-effect version (default); 'classic' = Openless classic pill version. */ export type CapsuleStyle = 'siri' | 'classic' | 'typeless'; +export interface CapsuleStyleMenuRequest { + sessionId: string; + requestId: string; +} + +export interface CapsuleStyleMenuIdentity { + sessionId: string; + menuId: string; +} + +export interface CapsuleStyleMenuOwner extends CapsuleStyleMenuIdentity { + windowLabel: string; + keyboardAvailable: boolean; +} + +export interface CapsuleStyleMenuKey extends CapsuleStyleMenuIdentity { + key: 'ArrowUp' | 'ArrowDown' | 'Enter' | 'Escape'; + repeat: boolean; +} + export interface CapsulePayload { qa?: boolean; /** Session generation that owns this capsule frame. */ From 1195ed320e96dee8e565c68e1de890da29a1a801 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:28:42 +0800 Subject: [PATCH 06/13] chore(ipc): audit the desktop style menu getter --- .../app/scripts/shared-backend-wire-contract.test.mjs | 1 + openless-all/harmony/ipc-audit.json | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) 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 4316ff435..af6237b5b 100644 --- a/openless-all/app/scripts/shared-backend-wire-contract.test.mjs +++ b/openless-all/app/scripts/shared-backend-wire-contract.test.mjs @@ -777,6 +777,7 @@ for (const field of ['skipAutoStyleHotkey', 'skipAutoStylePickerEnabled']) { for (const command of [ 'get_dictation_style_target', 'update_dictation_style', + 'get_capsule_style_menu_request', 'set_capsule_style_menu', ]) { assert.ok(styleIpc.includes(`'${command}'`)); diff --git a/openless-all/harmony/ipc-audit.json b/openless-all/harmony/ipc-audit.json index 84ca3eecb..224082176 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": 194, + "total": 195, "wired": 108, - "missing": 86, + "missing": 87, "commands": [ { "name": "accept_pending_correction", @@ -466,6 +466,13 @@ ], "implementation": "unimplemented" }, + { + "name": "get_capsule_style_menu_request", + "calledFrom": [ + "src/lib/ipc/dictation.ts" + ], + "implementation": "unimplemented" + }, { "name": "get_credentials", "calledFrom": [ From 580e1c97521a09029abe054a140fc48f99345982 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:51:32 +0800 Subject: [PATCH 07/13] fix(capsule): quietly discard stale style picker requests --- .../skip-auto-style-ui-contract.test.mjs | 2 + .../features/capsule/CapsuleStyleBadge.tsx | 24 ++-- .../capsule/capsuleOutputStyle.test.ts | 8 ++ .../features/capsule/capsuleOutputStyle.ts | 9 ++ .../capsule/capsulePickerMenu.test.ts | 115 +++++++++++++++++- .../src/features/capsule/capsulePickerMenu.ts | 40 +++++- .../features/capsule/useCapsulePickerMenu.ts | 7 +- 7 files changed, 191 insertions(+), 14 deletions(-) diff --git a/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs b/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs index bacb95c09..cbdd6fbe1 100644 --- a/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs +++ b/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs @@ -47,6 +47,8 @@ assert.match( /setCapsuleStyleMenu\(false, sessionId, \{ menuId: nativeOwner\.menuId \}\)/, ); assert.match(styleBadge, /await getCapsuleStyleMenuRequest\(\)/); +assert.match(styleBadge, /setRequest\(\(current\) => forgetStylePickerRequest\(current, stale\)\)/); +assert.match(styleBadge, /setLoaded\(\(current\) => forgetStylePickerRequest\(current, stale\)\)/); assert.match( styleBadge, /updateDictationStyle\(intent\.sessionId, \{\s*mode: 'stylePack',\s*stylePackId,?\s*\}\)/, diff --git a/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx b/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx index 9b58025d7..ea264b68e 100644 --- a/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx +++ b/openless-all/app/src/features/capsule/CapsuleStyleBadge.tsx @@ -20,6 +20,7 @@ import { usePopupViewport } from '../../ui/layout/AppViewport'; import { capsuleOutputStyleLabel, CapsuleStylePickerRequests, + forgetStylePickerRequest, styleMenuKeyAction, stylePickerRequestForSession, type CapsuleOutputStyle, @@ -51,10 +52,9 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ const [windowLabel, setWindowLabel] = useState(); const [request, setRequest] = useState(null); const [requests] = useState(() => new CapsuleStylePickerRequests()); - const [loaded, setLoaded] = useState<{ - requestId: string; - target: DictationStyleTarget; - } | null>(null); + const [loaded, setLoaded] = useState< + (CapsuleStyleMenuRequest & { target: DictationStyleTarget }) | null + >(null); const [error, setError] = useState(false); const [saving, setSaving] = useState(false); const choice = useRef(); @@ -77,7 +77,7 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ return; if ( !(await events.styleMenuRequests((next) => { - if (next.sessionId !== captureSessionId) return; + if (next.sessionId !== captureSessionId || requests.hasConsumed(next)) return; requestRevision += 1; setRequest(next); })) @@ -89,7 +89,9 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ if ( !disposed && requestRevision === revisionAtRead && - pending?.sessionId === captureSessionId + pending && + pending.sessionId === captureSessionId && + !requests.hasConsumed(pending) ) { setRequest(pending); } @@ -100,7 +102,7 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ disposed = true; events.dispose(); }; - }, [captureSessionId, pickerController, pickerEnabled]); + }, [captureSessionId, pickerController, pickerEnabled, requests]); const intent = stylePickerRequestForSession( request, @@ -110,7 +112,7 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ const requestId = intent?.requestId; const sessionId = intent?.sessionId; const target = - requestId && loaded?.requestId === requestId && loaded.target.sessionId === sessionId + requestId && loaded?.requestId === requestId && loaded.sessionId === sessionId ? loaded.target : null; const setNativeMenu = useCallback( @@ -136,6 +138,10 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ visible: Boolean(intent), setNativeMenu, onFailure: () => setError(true), + onStaleStyleRequest: (stale) => { + setRequest((current) => forgetStylePickerRequest(current, stale)); + setLoaded((current) => forgetStylePickerRequest(current, stale)); + }, }); useEffect(() => { @@ -156,7 +162,7 @@ export const CapsuleStyleBadge = memo(function CapsuleStyleBadge({ return; } if (next.sessionId === sessionId && next.selection.mode === 'skipAuto') { - setLoaded({ requestId, target: next }); + setLoaded({ sessionId, requestId, target: next }); } } catch { if (!disposed) setError(true); diff --git a/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts b/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts index d06f00d7b..0c4a95d59 100644 --- a/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts +++ b/openless-all/app/src/features/capsule/capsuleOutputStyle.test.ts @@ -2,6 +2,7 @@ import type { CapsuleStyleMenuRequest, DictationStyleTarget, StylePack } from '. import { capsuleOutputStyleLabel, CapsuleStylePickerRequests, + forgetStylePickerRequest, projectCapsuleOutputStyle, sameCapsuleOutputStyle, styleMenuKeyAction, @@ -75,6 +76,13 @@ const target: DictationStyleTarget = { mutable: true, }; const requests = new CapsuleStylePickerRequests(); +const loadedRequest = { ...request, target }; +const newerLoadedRequest = { ...loadedRequest, requestId: '14' }; +const otherSessionRequest = { ...request, sessionId: 'recording-b' }; +expect(forgetStylePickerRequest(request, request), null); +expect(forgetStylePickerRequest(loadedRequest, request), null); +expect(forgetStylePickerRequest(newerLoadedRequest, request), newerLoadedRequest); +expect(forgetStylePickerRequest(otherSessionRequest, request), otherSessionRequest); expect(requests.take(request, { ...target, mutable: false }), null); expect(requests.take(request, { ...target, sessionId: 'old-recording' }), null); expect(requests.take(request, { ...target, selection: { mode: 'automatic' } }), null); diff --git a/openless-all/app/src/features/capsule/capsuleOutputStyle.ts b/openless-all/app/src/features/capsule/capsuleOutputStyle.ts index c77d5c2f5..accb7bb6d 100644 --- a/openless-all/app/src/features/capsule/capsuleOutputStyle.ts +++ b/openless-all/app/src/features/capsule/capsuleOutputStyle.ts @@ -75,6 +75,15 @@ export function stylePickerRequestForSession( return enabled && request?.sessionId === captureSessionId ? request : null; } +export function forgetStylePickerRequest( + current: T | null, + stale: CapsuleStyleMenuRequest, +): T | null { + return current?.sessionId === stale.sessionId && current.requestId === stale.requestId + ? null + : current; +} + export class CapsuleStylePickerRequests { private sessionId: string | undefined; private consumed = new Set(); diff --git a/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts b/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts index 447e44818..1b666b42c 100644 --- a/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts +++ b/openless-all/app/src/features/capsule/capsulePickerMenu.test.ts @@ -1,5 +1,10 @@ import { CapsulePickerMenu, type CapsulePickerDeps } from './capsulePickerMenu'; -import type { CapsuleStyleMenuKey, CapsuleStyleMenuOwner } from '../../api/contracts'; +import { forgetStylePickerRequest } from './capsuleOutputStyle'; +import type { + CapsuleStyleMenuKey, + CapsuleStyleMenuOwner, + CapsuleStyleMenuRequest, +} from '../../api/contracts'; function expect(actual: unknown, expected: unknown) { if (JSON.stringify(actual) !== JSON.stringify(expected)) { @@ -53,6 +58,114 @@ expect(log, [ 'render:true', ]); +for (const [error, stale] of [ + ['capsule_style_request_stale', true], + [{ code: 'capsule_style_menu_reservation_stale', message: 'Reservation expired' }, true], + [new Error('capsule_style_menu_reservation_stale'), true], + ['recording_style_required', false], + ['capsule_style_menu_target_unavailable', false], + ['geometry failed: capsule_style_request_stale', false], + [{ code: 'permission_denied', message: 'capsule_style_request_stale' }, false], +] as const) { + const menu = new CapsulePickerMenu(); + const events: string[] = []; + await menu.open(style, { + ...deps, + setNativeMenu: async (open) => { + events.push(open ? 'reserve' : 'release'); + if (open) throw error; + }, + waitForGeometry: async () => { + events.push('geometry'); + }, + onOpenChange: (open) => events.push(`render:${open}`), + onFailure: () => events.push('error'), + onStaleStyleRequest: (request) => events.push(`stale:${request.sessionId}:${request.requestId}`), + }); + // A subsequent reservation drains any queued cleanup before the assertion. + await menu.open(language, deps); + expect( + events, + stale + ? ['reserve', 'render:false', 'stale:first:open-1'] + : ['reserve', 'render:false', 'error', 'release'], + ); +} + +// The host invalidates an outstanding reservation while a fresh hotkey +// request in the same session arrives. Rejecting the old reply must leave +// the fresh request and geometry untouched. +const raceMenu = new CapsulePickerMenu(); +const raceEvents: string[] = []; +let currentRequest: CapsuleStyleMenuRequest | null = style; +let rejectOld = (_: unknown) => {}; +let startOld = () => {}; +const oldStarted = new Promise((resolve) => { + startOld = resolve; +}); +const oldOpen = raceMenu.open(style, { + ...deps, + setNativeMenu: async (open) => { + raceEvents.push(open ? 'old:reserve' : 'old:release'); + if (!open) return; + await new Promise((_, reject) => { + rejectOld = reject; + startOld(); + }); + }, + waitForGeometry: async () => { + raceEvents.push('old:geometry'); + }, + onOpenChange: (open) => raceEvents.push(`old:render:${open}`), + onFailure: () => raceEvents.push('old:error'), + onStaleStyleRequest: (request) => { + currentRequest = forgetStylePickerRequest(currentRequest, request); + raceEvents.push(`old:stale:${request.requestId}`); + }, +}); +await oldStarted; +const fresh = { ...style, requestId: 'open-2' }; +currentRequest = fresh; +const freshOpen = raceMenu.open(fresh, { + ...deps, + setNativeMenu: async (open, _, reserved) => { + if (!open) { + raceEvents.push(`fresh:release:${reserved?.menuId}`); + throw 'capsule_style_menu_reservation_stale'; + } + raceEvents.push('fresh:reserve'); + return { + sessionId: fresh.sessionId, + menuId: 'fresh-menu', + windowLabel: 'capsule', + keyboardAvailable: true, + }; + }, + onOpenChange: (open) => raceEvents.push(`fresh:render:${open}`), + onStaleStyleRequest: (request) => { + currentRequest = forgetStylePickerRequest(currentRequest, request); + raceEvents.push(`fresh:stale:${request.requestId}`); + }, +}); +rejectOld('capsule_style_request_stale'); +await Promise.all([oldOpen, freshOpen]); +raceMenu.receiveStyleClose({ sessionId: style.sessionId, menuId: 'stale-menu' }); +expect(currentRequest, fresh); +expect(raceMenu.owns('style', fresh.sessionId, fresh.requestId), true); +expect(raceEvents, [ + 'old:reserve', + 'old:render:false', + 'old:stale:open-1', + 'fresh:reserve', + 'fresh:render:true', +]); +raceEvents.length = 0; +raceMenu.close('style'); +await raceMenu.open(language, deps); +expect(currentRequest, null); +expect(raceMenu.sessionForChoice('language'), language.sessionId); +expect(raceEvents, ['fresh:render:false', 'fresh:release:fresh-menu', 'fresh:stale:open-2']); + const inputController = new CapsulePickerMenu(); const nativeOwner: CapsuleStyleMenuOwner = { sessionId: style.sessionId, diff --git a/openless-all/app/src/features/capsule/capsulePickerMenu.ts b/openless-all/app/src/features/capsule/capsulePickerMenu.ts index 880d385eb..c1c2ad666 100644 --- a/openless-all/app/src/features/capsule/capsulePickerMenu.ts +++ b/openless-all/app/src/features/capsule/capsulePickerMenu.ts @@ -2,6 +2,7 @@ import type { CapsuleStyleMenuIdentity, CapsuleStyleMenuKey, CapsuleStyleMenuOwner, + CapsuleStyleMenuRequest, } from '../../api/contracts'; /** @@ -41,6 +42,8 @@ export interface CapsulePickerDeps { onOpenChange: (open: boolean) => void; /** An opening request failed while it was still the current one. */ onFailure: () => void; + /** The host discarded this particular style request or owner. */ + onStaleStyleRequest?: (request: CapsuleStyleMenuRequest) => void; } interface Reservation extends CapsulePickerOwner { @@ -150,7 +153,13 @@ export class CapsulePickerMenu { await this.enqueue(async () => { if (owner.abort.signal.aborted) return; owner.nativeWriteStarted = true; - const nativeOwner = await deps.setNativeMenu(true, owner); + let nativeOwner: CapsuleStyleMenuOwner | void; + try { + nativeOwner = await deps.setNativeMenu(true, owner); + } catch (error) { + if (this.discardStaleStyleReservation(owner, error)) return; + throw error; + } if (!nativeOwner) return; owner.nativeOwner = nativeOwner; if (owner.styleInput?.closedMenuIds.has(nativeOwner.menuId)) { @@ -229,6 +238,29 @@ export class CapsulePickerMenu { return result; } + private discardStaleStyleReservation(owner: Reservation, error: unknown): boolean { + if (owner.kind !== 'style') return false; + // Tauri's Result<_, String> rejects with a bare code. Use a structured + // code if present, and compare both forms exactly. + const code = + typeof error === 'object' && error !== null && 'code' in error + ? error.code + : error instanceof Error + ? error.message + : error; + if (code !== 'capsule_style_request_stale' && code !== 'capsule_style_menu_reservation_stale') { + return false; + } + // The host owns any rollback. This also prevents an already queued close + // for a superseded reservation from issuing a native write. + owner.nativeWriteStarted = false; + if (this.reservation === owner) this.close('style'); + if (owner.requestId !== undefined) { + owner.deps.onStaleStyleRequest?.({ sessionId: owner.sessionId, requestId: owner.requestId }); + } + return true; + } + private release(owner: Reservation) { if (this.exiting === owner) this.exiting = undefined; owner.abort.abort(); @@ -237,6 +269,10 @@ export class CapsulePickerMenu { owner.nativeWriteStarted = false; await owner.deps.setNativeMenu(false, owner, owner.nativeOwner); } - }).catch((error) => console.warn('[capsule] failed to restore picker menu geometry', error)); + }).catch((error) => { + if (!this.discardStaleStyleReservation(owner, error)) { + console.warn('[capsule] failed to restore picker menu geometry', error); + } + }); } } diff --git a/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts b/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts index 6b120ba90..0c05416b3 100644 --- a/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts +++ b/openless-all/app/src/features/capsule/useCapsulePickerMenu.ts @@ -17,6 +17,7 @@ export function useCapsulePickerMenu({ visible, setNativeMenu, onFailure, + onStaleStyleRequest, }: { controller: CapsulePickerMenu; kind: CapsulePickerKind; @@ -25,11 +26,12 @@ export function useCapsulePickerMenu({ visible: boolean; setNativeMenu: CapsulePickerDeps['setNativeMenu']; onFailure: () => void; + onStaleStyleRequest?: CapsulePickerDeps['onStaleStyleRequest']; }) { const { boundary } = useAppViewport(); const [open, setOpen] = useState(false); - const config = useRef({ visible, target, boundary, onFailure }); - config.current = { visible, target, boundary, onFailure }; + const config = useRef({ visible, target, boundary, onFailure, onStaleStyleRequest }); + config.current = { visible, target, boundary, onFailure, onStaleStyleRequest }; const close = useCallback(() => controller.close(kind), [controller, kind]); const openMenu = useCallback( @@ -43,6 +45,7 @@ export function useCapsulePickerMenu({ setNativeMenu, onOpenChange: setOpen, onFailure: () => config.current.onFailure(), + onStaleStyleRequest: (request) => config.current.onStaleStyleRequest?.(request), waitForGeometry: async (signal) => { const viewport = current.boundary ?? document.documentElement; await waitForViewportGeometry( From 76a2f8fe05c96844669b0f873853a763b93f2252 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:14:17 +0800 Subject: [PATCH 08/13] fix(capsule): fence picker requests across core style transitions --- .../app/crates/openless-core/src/api.rs | 64 ++++- .../capsule-style-menu-host-contract.test.mjs | 15 +- .../backend-tests/tests/capsule_style_menu.rs | 270 ++++++++++++++++-- .../app/src-tauri/src/capsule_style_menu.rs | 179 +++++++++--- .../src-tauri/src/coordinator/style_menu.rs | 23 +- openless-all/app/src-tauri/src/hotkey.rs | 4 +- .../app/src-tauri/src/tauri_events.rs | 6 + 7 files changed, 472 insertions(+), 89 deletions(-) diff --git a/openless-all/app/crates/openless-core/src/api.rs b/openless-all/app/crates/openless-core/src/api.rs index 94d1e211f..674fb4ac7 100644 --- a/openless-all/app/crates/openless-core/src/api.rs +++ b/openless-all/app/crates/openless-core/src/api.rs @@ -1832,6 +1832,9 @@ struct MutableState { /// by every stop entry; no Host latch survives into the next session. dictation_translation_requested: Option, dictation_style_selection: Option, + /// Internal host-intent fence. Never reset or serialized into a UI frame. + dictation_style_epoch: u64, + dictation_style_picker_enabled: bool, /// 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, @@ -1849,6 +1852,16 @@ struct SubmittedDictation { } impl MutableState { + fn advance_dictation_style_epoch(&mut self) { + self.dictation_style_epoch = self.dictation_style_epoch.checked_add(1) + .expect("dictation style epoch exhausted"); + } + fn retire_dictation_style(&mut self, session: SessionId) { + if self.dictation.session_id == Some(session) + && matches!(self.dictation.phase, DictationPhase::Starting | DictationPhase::Recording) { + self.advance_dictation_style_epoch(); + } + } fn processing_snapshots(&self) -> Vec { let mut tasks: Vec<_> = self.processing_dictations.values().collect(); tasks.sort_by_key(|task| task.submitted_at); @@ -2570,6 +2583,7 @@ impl EngineProgressSink for BackendEngineProgress { EngineProgress::RecordingFault(error) => { let mut state = self.state.write().expect("backend state lock poisoned"); ensure_capture_session(&state, session_id)?; + state.retire_dictation_style(session_id); state.dictation.phase = DictationPhase::Failed; state.dictation.message = Some(error.message); self.events.publish( @@ -2595,6 +2609,7 @@ impl EngineProgressSink for BackendEngineProgress { EngineStage::Polishing => DictationPhase::Polishing, }; if state.session(session_id).unwrap().phase != phase { + state.retire_dictation_style(session_id); state.session_mut(session_id).unwrap().phase = phase; self.events.publish( Some(session_id), @@ -3678,6 +3693,8 @@ impl OpenLessBackend { dictation_start_output_target: None, dictation_translation_requested: None, dictation_style_selection: None, + dictation_style_epoch: 0, + dictation_style_picker_enabled: repositories.preferences.get().skip_auto_style_picker_enabled, dictation_style_needs_update: false, dictation_destination_changed: false, credentials: CredentialsStatus::default(), @@ -5722,7 +5739,8 @@ impl OpenLessBackend { context.output_target == DictationOutputTarget::QuickNote }); self.events.publish(None, BackendEventKind::BackendStopping); - if active_session.is_some() { + if let Some(active) = active_session { + state.retire_dictation_style(active); state.dictation.phase = DictationPhase::Cancelled; self.events.publish( state.dictation.session_id, @@ -6509,6 +6527,19 @@ impl OpenLessBackend { Self::style_target(&state) } + /// Rust host-only receipt/view; the public style DTO and IPC stay unchanged. + /// Target, epoch and picker eligibility come from the same state lock. + pub fn dictation_style_target_with_epoch(&self) -> Option<(DictationStyleTarget, u64, bool)> { + let state = self.state.read().expect("backend state lock poisoned"); + Some((Self::style_target(&state)?, state.dictation_style_epoch, + state.dictation_style_picker_enabled)) + } + + /// Also available when the session has ended, to fence an absent host view. + pub fn dictation_style_epoch(&self) -> u64 { + self.state.read().expect("backend state lock poisoned").dictation_style_epoch + } + fn style_target(state: &MutableState) -> Option { let context = state.dictation_context.as_ref(); let selection = state.dictation_style_selection.clone() @@ -6531,13 +6562,21 @@ impl OpenLessBackend { session_id: SessionId, selection: DictationStyleSelection, ) -> Result { - self.change_dictation_style(session_id, Some(selection)) + self.change_dictation_style(session_id, Some(selection)).map(|(target, _)| target) } pub fn toggle_dictation_style_for_session( &self, session_id: SessionId, ) -> Result { + self.toggle_dictation_style_with_epoch(session_id).map(|(target, _)| target) + } + + /// A true hotkey must use this receipt, never mutate then read a newer epoch. + pub fn toggle_dictation_style_with_epoch( + &self, + session_id: SessionId, + ) -> Result<(DictationStyleTarget, u64), BackendError> { self.change_dictation_style(session_id, None) } @@ -6545,7 +6584,7 @@ impl OpenLessBackend { &self, session_id: SessionId, selection: Option, - ) -> Result { + ) -> Result<(DictationStyleTarget, u64), BackendError> { let mut state = self.state.write().expect("backend state lock poisoned"); ensure_running(&state)?; if state.dictation.session_id != Some(session_id) @@ -6567,13 +6606,14 @@ impl OpenLessBackend { } else if matches!(&selection, DictationStyleSelection::StylePack { .. }) { return Err(BackendError::new(BackendErrorCode::InvalidState, "recording style list is not ready")); } + if previous != selection { state.advance_dictation_style_epoch(); } 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) + Ok((result, state.dictation_style_epoch)) } /// Explicitly retarget this recording and remember the choice. Ordinary settings @@ -7772,6 +7812,17 @@ impl OpenLessBackend { } fn publish_preferences_changed(&self) { + { + // All preferences entry points converge here before publishing. + // Observe picker off/on under the same fence as style mutations, + // even when the Host misses both intermediate settings events. + let mut state = self.state.write().expect("backend state lock poisoned"); + let enabled = self.preferences.get().skip_auto_style_picker_enabled; + if enabled != state.dictation_style_picker_enabled { + state.advance_dictation_style_epoch(); + state.dictation_style_picker_enabled = enabled; + } + } let revision = self.preferences_revision.fetch_add(1, Ordering::AcqRel) + 1; self.events.publish( None, @@ -8772,6 +8823,7 @@ impl OpenLessBackend { ..DictationStateSnapshot::default() }; state.dictation_start_output_target = Some(options.output_target); + state.advance_dictation_style_epoch(); 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. @@ -9337,6 +9389,7 @@ impl OpenLessBackend { }); state.dictation_context = Some(Arc::clone(&context)); state.dictation.translation_active = context.polish.translation_active; + state.retire_dictation_style(session_id); state.dictation.phase = DictationPhase::Transcribing; self.main_dictation_trace .record(session_id, format_args!("stage=finalization_started")); @@ -10148,6 +10201,7 @@ impl OpenLessBackend { if state.dictation.session_id != Some(session_id) { return; } + state.retire_dictation_style(session_id); state.dictation = DictationStateSnapshot::default(); state.dictation_context = None; state.dictation_style_selection = None; @@ -10479,6 +10533,7 @@ impl OpenLessBackend { .dictation_context .as_ref() .is_some_and(|context| context.output_target == DictationOutputTarget::QuickNote); + state.retire_dictation_style(active); state.dictation.phase = DictationPhase::Cancelled; self.main_dictation_trace .record(active, format_args!("stage=terminal phase=cancelled")); @@ -10926,6 +10981,7 @@ impl OpenLessBackend { error.message ); let mut state = self.state.write().expect("backend state lock poisoned"); + state.retire_dictation_style(session_id); let Some(snapshot) = state.session_mut(session_id) else { return; }; diff --git a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs index e45f9bc22..b87a5db79 100644 --- a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs +++ b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs @@ -6,6 +6,8 @@ const [commands, lib, hotkeys, loops, bridge, host, menu, selection] = await Pro read('coordinator/hotkey_loops.rs'), read('coordinator/style_menu.rs'), read('tauri_coordinator_host.rs'), read('capsule_style_menu.rs'), read('selection.rs'), ]); +const core = await readFile(new URL('../crates/openless-core/src/api.rs', import.meta.url), 'utf8'); +const appEvents = await read('tauri_events.rs'); assert.match(lib, /commands::get_capsule_style_menu_request/); assert.match(commands, /pub fn get_capsule_style_menu_request[^]*?capsule_label\(window.label\(\)\)/); assert.match(commands, /pub async fn set_capsule_style_menu[^]*?request_id: Option,[^]*?menu_id: Option/); @@ -14,7 +16,7 @@ const programmatic = commands.slice(commands.indexOf('pub fn update_dictation_st assert.doesNotMatch(programmatic, /hotkey_toggled|handle_skip_auto_style_hotkey/); assert.equal((loops.match(/handle_skip_auto_style_hotkey\(&inner, /g) ?? []).length, 2, 'modifier and custom-combination hotkeys share one provenance boundary'); -assert.match(bridge, /toggle_dictation_style_for_session\(session_id\)[^]*?menu::hotkey_toggled\(&target\)/); +assert.match(bridge, /toggle_dictation_style_with_epoch\(session_id\)[^]*?menu::hotkey_toggled\(&target, epoch\)/); assert.match(bridge, /DictationPhase::Starting \| openless_core::DictationPhase::Recording/); assert.match(bridge, /DictationOutputTarget::AskComposer[^]*?DictationOutputTarget::Qa[^]*?DictationOutputTarget::VoiceEdit/); assert.match(bridge, /mutable: target.mutable && surface_available/); @@ -25,6 +27,17 @@ assert.match(selection, /pub\(crate\) fn capture_capsule_menu_input_target[^]*?t assert.match(menu, /keyboard_available: c.keyboard_available && c.focus.is_some\(\)/); assert.match(menu, /target.selection != DictationStyleSelection::SkipAuto/); assert.match(menu, /c\.picker_enabled && c\.skip_auto/); +assert.match(bridge, /dictation_style_target_with_epoch\(\)/); +assert.match(bridge, /configure_fenced/); +assert.match(menu, /c.style_epoch == style_epoch/); +assert.match(menu, /c.style_epoch == active.style_epoch/); +assert.match(menu, /before != after/); +assert.match(menu, /fn drain_key/); +assert.match(core, /fn change_dictation_style[^]*?let mut state = self.state.write\(\)[^]*?previous != selection[^]*?state.advance_dictation_style_epoch\(\)[^]*?Ok\(\(result, state.dictation_style_epoch\)\)/, + 'all style mutation entry points return their own epoch under the mutation lock'); +assert.match(core, /fn publish_preferences_changed[^]*?enabled != state.dictation_style_picker_enabled[^]*?state.advance_dictation_style_epoch\(\)/); +assert.match(appEvents, /project_current_style\(&mut snapshot, ¤t.dictation\)/, + 'late live-session app frames project the current style before presenting a capsule'); assert.match(menu, /label == "capsule"/); for (const event of ['request', 'key', 'closed']) { assert.match(host, new RegExp(`emit_to\\([^;]*"capsule:style-menu-${event}"`)); diff --git a/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs b/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs index 314141082..4d9fe0845 100644 --- a/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs +++ b/openless-all/app/src-tauri/backend-tests/tests/capsule_style_menu.rs @@ -3,12 +3,61 @@ #[path = "../../src/capsule_style_menu.rs"] mod capsule_style_menu; +use std::sync::{Arc, Mutex, atomic::{AtomicUsize, Ordering}}; +use capsule_style_menu as menu; +use openless_core::{BackendConfig, BackendDependencies, DictationStartOptions, + DictationStyleSelection as Selection, OpenLessBackend, SessionId}; + +fn actual_toggle(core: &OpenLessBackend, session: SessionId) -> (openless_core::DictationStyleTarget, u64) { + // Exactly the atomic Core mutation/receipt used by the native coordinator. + core.toggle_dictation_style_with_epoch(session).unwrap() +} +fn request(core: &OpenLessBackend, session: SessionId) -> (menu::Request, openless_core::DictationStyleTarget, u64) { + core.update_dictation_style(session, Selection::Automatic).unwrap(); + let (target, epoch) = actual_toggle(core, session); + (menu::hotkey_toggled(&target, epoch).unwrap(), target, epoch) +} +fn open(request: &menu::Request) -> menu::Owner { + let owner = menu::reservation("capsule", request.session_id, Some(&request.request_id)).unwrap(); + menu::commit(owner.clone(), Some(&request.request_id)).unwrap(); + owner +} +fn automatic_skip(core: &OpenLessBackend, session: SessionId) { + // No refresh, menu callback, or broadcast consumption between these calls. + core.update_dictation_style(session, Selection::Automatic).unwrap(); + core.update_dictation_style(session, Selection::SkipAuto).unwrap(); +} +fn delayed_events(events: &mut openless_core::EventSubscription) -> Vec { + let mut delayed = Vec::new(); + loop { + match events.try_recv() { + Ok(event) => delayed.push(event), + Err(openless_core::EventRecvError::Empty) => break, + Err(error) => panic!("unexpected event replay failure: {error}"), + } + } + delayed +} +fn deliver(events: &[openless_core::BackendEvent]) { + for event in events { + if matches!(&event.kind, openless_core::BackendEventKind::DictationStateChanged(_) + | openless_core::BackendEventKind::PreferencesChanged(_)) { + // Production event handling refreshes from Core, never the payload. + menu::refresh(); + } + } +} +fn set_picker(core: &OpenLessBackend, enabled: bool) { + let mut prefs = core.get_preferences(); + prefs.skip_auto_style_picker_enabled = enabled; + core.update_settings(prefs, openless_core::SettingsUpdateOptions::STRICT, + &openless_core::NoopSettingsRuntime).unwrap(); +} + +// One fixture owns the process-global production Runtime throughout these real +// Core sequences; the module's other tests use independent, local State values. #[tokio::test] -async fn ordinary_skip_start_and_programmatic_switch_never_create_hotkey_open_intent() { - use std::sync::Arc; - use capsule_style_menu as menu; - use openless_core::{BackendConfig, BackendDependencies, DictationStartOptions, - DictationStyleSelection as Selection, OpenLessBackend}; +async fn real_core_style_mutations_fence_pending_prepared_active_and_late_host_delivery() { let directory = tempfile::tempdir().unwrap(); let mut dependencies = BackendDependencies::unsupported(); dependencies.host_actions = Arc::new(openless_core::testing::RecordingHostActions::default()); @@ -20,41 +69,210 @@ async fn ordinary_skip_start_and_programmatic_switch_never_create_hotkey_open_in data_dir: directory.path().to_owned(), ..Default::default() }, dependencies).unwrap()); backend.start().await.unwrap(); - let mut prefs = backend.get_preferences(); - prefs.skip_auto_style_picker_enabled = true; - backend.update_settings(prefs, openless_core::SettingsUpdateOptions::STRICT, - &openless_core::NoopSettingsRuntime).unwrap(); + set_picker(&backend, true); let source = Arc::downgrade(&backend); - menu::configure(Arc::new(move || { + let fence = Arc::downgrade(&backend); + let disturb = Arc::new(AtomicUsize::new(0)); + let source_disturb = disturb.clone(); + let output = Arc::new(Mutex::new(Vec::new())); + let sink = output.clone(); + menu::configure_fenced(Arc::new(move || { let core = source.upgrade()?; if !matches!(core.snapshot().dictation.phase, openless_core::DictationPhase::Starting | openless_core::DictationPhase::Recording) { return None; } - let target = core.dictation_style_target()?; - Some(menu::Context { session_id: target.session_id, mutable: target.mutable, - skip_auto: target.skip_auto_style, picker_enabled: true, keyboard_available: true, + let (target, style_epoch, picker_enabled) = core.dictation_style_target_with_epoch()?; + let disturbance = source_disturb.load(Ordering::SeqCst); + if disturbance != 0 { + if disturbance == 1 { source_disturb.store(0, Ordering::SeqCst); } + // A real Core transition occurs after taking a view, just like an + // asynchronous native focus query crossing an API transaction. + automatic_skip(&core, target.session_id); + } + Some(menu::Context { session_id: target.session_id, style_epoch, mutable: target.mutable, + skip_auto: target.skip_auto_style, picker_enabled, keyboard_available: true, focus: Some(menu::Focus(1, 1)), blocked_keys: [false; 4] }) - }), Arc::new(|_| true)); + }), Arc::new(move |event| { sink.lock().unwrap().push(event); true }), + Arc::new(move || fence.upgrade().unwrap().dictation_style_epoch())); let session = backend.start_dictation_with_options(DictationStartOptions { skip_auto_style: true, ..Default::default() }).await.unwrap(); menu::refresh(); - assert!(backend.dictation_style_target().unwrap().skip_auto_style); assert!(menu::pending("capsule").is_none(), "ordinary skipAuto start has no hotkey provenance"); + automatic_skip(&backend, session); + assert!(menu::pending("capsule").is_none(), "programmatic changes alone cannot open a menu"); + let unchanged = backend.dictation_style_epoch(); + backend.update_dictation_style(session, Selection::SkipAuto).unwrap(); + assert_eq!(unchanged, backend.dictation_style_epoch(), "an idempotent write is not a style transition"); + + // R1: r1 exists, but Host observes neither intermediate Core frame. Reading + // latest SkipAuto=true must not resurrect the previous request or token. + let (r1, old_target, old_epoch) = request(&backend, session); + let mut events = backend.subscribe(); + automatic_skip(&backend, session); + assert!(backend.dictation_style_epoch() > old_epoch); + assert!(menu::pending("capsule").is_none()); + assert_eq!(menu::reservation("capsule", session, Some(&r1.request_id)).unwrap_err(), + "capsule_style_request_stale"); + assert!(!menu::key(menu::Key::ArrowDown, true, false, false)); + assert!(!menu::key(menu::Key::ArrowDown, false, false, false)); + assert!(menu::hotkey_toggled(&old_target, old_epoch).is_none()); + let delayed = delayed_events(&mut events); + assert!(delayed.iter().any(|event| matches!(&event.kind, + openless_core::BackendEventKind::DictationStateChanged(state) if !state.skip_auto_style))); + assert!(delayed.iter().any(|event| matches!(&event.kind, + openless_core::BackendEventKind::DictationStateChanged(state) if state.skip_auto_style))); + deliver(&delayed); + assert!(menu::pending("capsule").is_none()); + // Also reject directly at prepare, before any getter/refresh cleans up r1. + let (stale_prepare, _, _) = request(&backend, session); + automatic_skip(&backend, session); + assert_eq!(menu::reservation("capsule", session, Some(&stale_prepare.request_id)).unwrap_err(), + "capsule_style_request_stale"); + + // Geometry reservation completed, but native commit is delayed across the + // same real Core transitions. The old reservation must not gain ownership. + let (prepared_request, _, _) = request(&backend, session); + let prepared = menu::reservation("capsule", session, Some(&prepared_request.request_id)).unwrap(); + automatic_skip(&backend, session); + assert_eq!(menu::commit(prepared, Some(&prepared_request.request_id)).unwrap_err(), + "capsule_style_menu_reservation_stale"); + assert!(menu::pending("capsule").is_none()); + assert!(!menu::key(menu::Key::Enter, true, false, false)); + assert!(!menu::key(menu::Key::Enter, false, false, false)); + + // An active owner is fenced on the very next key/owner check, without first + // consuming a state event. Retain captured releases, never steal passed ups. + let (active_request, _, _) = request(&backend, session); + let active = open(&active_request); + assert!(menu::key(menu::Key::Enter, true, false, false)); + assert!(!menu::key(menu::Key::Escape, true, false, true)); + let old_key = output.lock().unwrap().iter().find_map(|event| match event { + menu::Event::Key(key) if key.menu_id == active.menu_id => Some(key.clone()), _ => None, + }).unwrap(); + automatic_skip(&backend, session); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + assert!(!menu::owner_current(&active)); + assert!(!menu::is_owner(&old_key)); + assert!(menu::key(menu::Key::Enter, false, false, false)); + assert!(!menu::key(menu::Key::Escape, false, false, false)); + + let (automatic_request, _, _) = request(&backend, session); + let automatic_owner = open(&automatic_request); backend.update_dictation_style(session, Selection::Automatic).unwrap(); + assert!(!menu::owner_current(&automatic_owner)); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); backend.update_dictation_style(session, Selection::SkipAuto).unwrap(); - menu::refresh(); - assert!(menu::pending("capsule").is_none(), "programmatic switches have no hotkey provenance"); - let automatic = backend.toggle_dictation_style_for_session(session).unwrap(); - assert!(menu::hotkey_toggled(&automatic).is_none()); - let skipped = backend.toggle_dictation_style_for_session(session).unwrap(); - let request = menu::hotkey_toggled(&skipped).unwrap(); - let owner = menu::reservation("capsule", session, Some(&request.request_id)).unwrap(); - menu::commit(owner.clone(), Some(&request.request_id)).unwrap(); - assert!(menu::owner_current(&owner)); + + // A new *real mutation receipt* can open again; old broadcasts and both + // kinds of old hotkey receipt must not cancel or reopen that newer owner. + let (old_auto, old_auto_epoch) = actual_toggle(&backend, session); + let (new_skip, new_epoch) = actual_toggle(&backend, session); + let current_request = menu::hotkey_toggled(&new_skip, new_epoch).unwrap(); + let current = open(¤t_request); + set_picker(&backend, true); + assert_eq!(new_epoch, backend.dictation_style_epoch(), "unchanged picker settings retain the current epoch"); + deliver(&delayed); + let mut old_automatic_frame = delayed.iter().find_map(|event| match &event.kind { + openless_core::BackendEventKind::DictationStateChanged(state) if !state.skip_auto_style => + Some(state.clone()), + _ => None, + }).unwrap(); + let old_phase = old_automatic_frame.phase; + let old_translation = old_automatic_frame.translation_active; + menu::project_current_style(&mut old_automatic_frame, &backend.snapshot().dictation); + assert!(old_automatic_frame.skip_auto_style, "a late app frame cannot hide the current style badge"); + assert_eq!(old_automatic_frame.phase, old_phase); + assert_eq!(old_automatic_frame.translation_active, old_translation); + assert!(menu::hotkey_toggled(&old_auto, old_auto_epoch).is_none()); + assert!(menu::hotkey_toggled(&old_target, old_epoch).is_none()); + assert!(menu::owner_current(¤t)); + assert!(!menu::close("capsule", session, &active.menu_id)); + assert!(menu::owner_current(¤t)); + assert!(menu::key(menu::Key::ArrowDown, true, false, false)); + assert!(menu::key(menu::Key::ArrowDown, false, false, false)); + assert!(menu::close("capsule", session, ¤t.menu_id)); + assert!(menu::hotkey_toggled(&new_skip, new_epoch).is_none(), "closed receipt cannot reopen"); + assert!(menu::pending("capsule").is_none()); + + // A stale native-context snapshot is rejected against the cheap Core fence; + // continuous changes decline fresh keys but still drain existing pairs. + let (racing_request, _, _) = request(&backend, session); + disturb.store(1, Ordering::SeqCst); + assert!(menu::pending("capsule").is_none()); + assert_eq!(menu::reservation("capsule", session, Some(&racing_request.request_id)).unwrap_err(), + "capsule_style_request_stale"); + let (unstable_request, _, _) = request(&backend, session); + let unstable_owner = open(&unstable_request); + assert!(menu::key(menu::Key::Enter, true, false, false)); + assert!(!menu::key(menu::Key::Escape, true, false, true)); + disturb.store(2, Ordering::SeqCst); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(menu::key(menu::Key::Enter, false, false, false)); + assert!(!menu::key(menu::Key::Escape, false, false, false)); + disturb.store(0, Ordering::SeqCst); + assert!(!menu::owner_current(&unstable_owner)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + + // Turning the picker off/on is also remembered even with delayed settings + // events, in pending, prepared and active stages of the real protocol. + for stage in 0..4 { + let (r, _, _) = request(&backend, session); + let owner = (stage != 0).then(|| menu::reservation("capsule", session, Some(&r.request_id)).unwrap()); + if stage >= 2 { + menu::commit(owner.clone().unwrap(), Some(&r.request_id)).unwrap(); + assert!(menu::key(menu::Key::Enter, true, false, false)); + assert!(!menu::key(menu::Key::Escape, true, false, true)); + } + set_picker(&backend, false); + if stage == 3 { + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + } + set_picker(&backend, true); + assert!(menu::pending("capsule").is_none()); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + assert_eq!(menu::reservation("capsule", session, Some(&r.request_id)).unwrap_err(), + "capsule_style_request_stale"); + if let Some(owner) = owner { + assert!(!menu::owner_current(&owner)); + assert_eq!(menu::commit(owner, Some(&r.request_id)).unwrap_err(), + "capsule_style_menu_reservation_stale"); + } + if stage >= 2 { + assert!(menu::key(menu::Key::Enter, false, false, false)); + assert!(!menu::key(menu::Key::Escape, false, false, false)); + } + } + + // Cancellation removes qualification, with the same retained pair rules. + let (last, last_target, last_epoch) = request(&backend, session); + let last_owner = open(&last); + assert!(menu::key(menu::Key::Enter, true, false, false)); + assert!(!menu::key(menu::Key::Escape, true, false, true)); + let before_cancel = backend.dictation_style_epoch(); backend.cancel_dictation(Some(session)).await.unwrap(); + assert!(backend.dictation_style_epoch() > before_cancel, "session retirement fences in-flight native views"); + assert_eq!(menu::reservation("capsule", session, Some(&last.request_id)).unwrap_err(), + "capsule_style_request_stale"); + assert!(!menu::owner_current(&last_owner)); + assert!(menu::key(menu::Key::Enter, false, false, false)); + assert!(!menu::key(menu::Key::Escape, false, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + let next = backend.start_dictation_with_options(DictationStartOptions::default()).await.unwrap(); + let (next_request, _, _) = request(&backend, next); + let next_owner = open(&next_request); + let ended_session_events = delayed_events(&mut events); + deliver(&ended_session_events); + assert!(menu::hotkey_toggled(&last_target, last_epoch).is_none()); + assert!(!menu::close("capsule", session, &last_owner.menu_id)); + assert!(menu::owner_current(&next_owner)); + backend.cancel_dictation(Some(next)).await.unwrap(); menu::refresh(); - assert!(!menu::owner_current(&owner)); - assert!(menu::pending("capsule").is_none()); + assert!(!menu::owner_current(&next_owner)); menu::invalidate(); menu::configure(Arc::new(|| None), Arc::new(|_| false)); backend.shutdown().await.unwrap(); diff --git a/openless-all/app/src-tauri/src/capsule_style_menu.rs b/openless-all/app/src-tauri/src/capsule_style_menu.rs index 217de51ef..239a588be 100644 --- a/openless-all/app/src-tauri/src/capsule_style_menu.rs +++ b/openless-all/app/src-tauri/src/capsule_style_menu.rs @@ -2,7 +2,7 @@ //! synthetic input: a captured down is drained with its own physical release. use std::sync::{Arc, OnceLock}; use parking_lot::{Mutex, RwLock}; -use openless_core::{DictationStyleSelection, DictationStyleTarget, SessionId}; +use openless_core::{DictationPhase, DictationStateSnapshot, DictationStyleSelection, DictationStyleTarget, SessionId}; use serde::Serialize; #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -66,6 +66,7 @@ pub(crate) struct Focus(pub u64, pub u64); #[derive(Clone)] pub(crate) struct Context { pub session_id: SessionId, + pub style_epoch: u64, pub mutable: bool, pub skip_auto: bool, pub picker_enabled: bool, @@ -90,15 +91,16 @@ pub(crate) fn blocked_keys(target: &openless_core::HotkeyRuntimeTarget) -> [bool blocked } -struct Pending { request: Request, focus: Option } -struct Active { owner: Owner, request_id: Option, focus: Option } -struct Prepared { owner: Owner, focus: Option } +struct Pending { request: Request, style_epoch: u64, focus: Option } +struct Active { owner: Owner, request_id: Option, style_epoch: u64, focus: Option } +struct Prepared { owner: Owner, style_epoch: u64, focus: Option } #[derive(Default, Clone)] struct Press { down: bool, captured: bool, menu_id: Option } #[derive(Default)] pub(crate) struct State { serial: u64, + last_hotkey_epoch: Option, pending: Option, active: Option, prepared: Option, @@ -117,36 +119,50 @@ impl State { self.serial = self.serial.checked_add(1).expect("style menu sequence exhausted"); self.serial.to_string() } + fn invalidate_before(&mut self, epoch: u64) { + if self.pending.as_ref().is_some_and(|p| p.style_epoch < epoch) { self.pending = None; } + if self.prepared.as_ref().is_some_and(|p| p.style_epoch < epoch) { self.prepared = None; } + if self.active.as_ref().is_some_and(|a| a.style_epoch < epoch) { self.revoke(); } + // This fence is authoritative even if the native view is unstable. + // Keep presses, and never revoke a record from the current/newer epoch. + } fn reconcile(&mut self, context: Option<&Context>) { if self.prepared.as_ref().is_some_and(|prepared| !context.is_some_and(|c| - c.session_id == prepared.owner.session_id && c.mutable && c.focus == prepared.focus)) { + c.session_id == prepared.owner.session_id && c.mutable && c.picker_enabled + && c.style_epoch == prepared.style_epoch && c.focus == prepared.focus)) { self.prepared = None; } if self.pending.as_ref().is_some_and(|pending| !context.is_some_and(|c| c.session_id == pending.request.session_id && c.skip_auto && c.picker_enabled - && c.focus == pending.focus)) { + && c.style_epoch == pending.style_epoch && c.focus == pending.focus)) { self.pending = None; } if self.active.as_ref().is_some_and(|active| !context.is_some_and(|c| - c.session_id == active.owner.session_id && c.mutable && c.focus == active.focus + c.session_id == active.owner.session_id && c.mutable && c.picker_enabled + && c.style_epoch == active.style_epoch && c.focus == active.focus && (!active.owner.keyboard_available || c.keyboard_available))) { self.revoke(); } // presses deliberately survive invalidation: previously swallowed downs // still own their releases, while passed downs never acquire an owner. } - fn hotkey_toggled(&mut self, target: &DictationStyleTarget, context: Option<&Context>) -> Option { + fn hotkey_toggled(&mut self, target: &DictationStyleTarget, style_epoch: u64, + context: Option<&Context>) -> Option { + // A delayed mutation receipt must never clear a newer request/owner. + let c = context.filter(|c| c.session_id == target.session_id && c.style_epoch == style_epoch)?; + if self.last_hotkey_epoch.is_some_and(|epoch| epoch >= style_epoch) { return None; } self.reconcile(context); + self.last_hotkey_epoch = Some(style_epoch); if target.selection != DictationStyleSelection::SkipAuto { self.pending = None; self.prepared = None; self.revoke(); return None; } - let c = context.filter(|c| c.session_id == target.session_id && c.picker_enabled && c.skip_auto)?; + if !(c.picker_enabled && c.skip_auto) { return None; } self.prepared = None; let request = Request { session_id: target.session_id, request_id: self.next_id() }; - self.pending = Some(Pending { request: request.clone(), focus: c.focus }); + self.pending = Some(Pending { request: request.clone(), style_epoch, focus: c.focus }); Some(request) } fn pending(&mut self, label: &str, context: Option<&Context>) -> Option { @@ -158,9 +174,6 @@ impl State { ) -> Result { self.reconcile(context); if !capsule_label(label) { return Err("capsule_window_required".into()); } - let c = context.filter(|c| c.session_id == session && c.mutable) - .ok_or("recording_style_required")?; - if c.focus.is_none() { return Err("capsule_style_menu_target_unavailable".into()); } if let Some(request_id) = request { if let Some(active) = self.active.as_ref().filter(|active| active.owner.window_label == label && active.owner.session_id == session @@ -172,20 +185,28 @@ impl State { return Err("capsule_style_request_stale".into()); } } + let c = context.filter(|c| c.session_id == session && c.mutable && c.picker_enabled) + .ok_or("recording_style_required")?; + if c.focus.is_none() { return Err("capsule_style_menu_target_unavailable".into()); } let owner = Owner { session_id: session, menu_id: self.next_id(), window_label: label.into(), keyboard_available: c.keyboard_available && c.focus.is_some() }; - self.prepared = Some(Prepared { owner: owner.clone(), focus: c.focus }); + self.prepared = Some(Prepared { owner: owner.clone(), style_epoch: c.style_epoch, focus: c.focus }); Ok(owner) } fn commit( &mut self, owner: Owner, request: Option<&str>, context: Option<&Context>, ) -> Result<(), String> { self.reconcile(context); - let c = context.filter(|c| c.session_id == owner.session_id && c.mutable) - .ok_or("recording_style_required")?; + if self.active.as_ref().is_some_and(|active| active.owner == owner + && active.request_id.as_deref() == request) { return Ok(()); } + // A reservation that lost its original qualification is a cancellation, + // including when the Core session no longer supplies any Context. + let prepared = self.prepared.as_ref().filter(|prepared| prepared.owner == owner) + .ok_or("capsule_style_menu_reservation_stale")?; + let c = context.filter(|c| c.session_id == owner.session_id && c.mutable + && c.picker_enabled && c.style_epoch == prepared.style_epoch) + .ok_or("capsule_style_menu_reservation_stale")?; if let Some(id) = request { - if self.active.as_ref().is_some_and(|active| active.owner == owner - && active.request_id.as_deref() == Some(id)) { return Ok(()); } if owner.window_label != "capsule" || !self.pending.as_ref().is_some_and(|pending| pending.request.session_id == owner.session_id && pending.request.request_id == id) { return Err("capsule_style_request_stale".into()); @@ -198,7 +219,8 @@ impl State { self.prepared = None; self.pending = None; if self.active.as_ref().is_some_and(|active| active.owner != owner) { self.revoke(); } - self.active = Some(Active { owner, request_id: request.map(str::to_owned), focus: c.focus }); + self.active = Some(Active { owner, request_id: request.map(str::to_owned), + style_epoch: c.style_epoch, focus: c.focus }); Ok(()) } fn close(&mut self, label: &str, session: SessionId, menu_id: &str) -> bool { @@ -241,10 +263,18 @@ impl State { self.presses[index].menu_id = Some(menu_id); true } + /// Without a stable Core view, decline fresh downs but retain the physical + /// pair decision already made for a held key. Never invalidate a newer owner. + fn drain_key(&mut self, key: Key, down: bool) -> bool { + let press = &mut self.presses[key.index()]; + let captured = press.captured; + if down { press.down = true; } else { *press = Press::default(); } + captured + } fn key_event(&self, key: Key, repeat: bool, context: Option<&Context>) -> Option { let c = context.filter(|c| c.keyboard_available && !c.blocked_keys[key.index()])?; let active = self.active.as_ref().filter(|a| a.owner.keyboard_available && a.focus.is_some() - && c.session_id == a.owner.session_id && c.focus == a.focus)?; + && c.session_id == a.owner.session_id && c.style_epoch == a.style_epoch && c.focus == a.focus)?; Some(KeyEvent { session_id: active.owner.session_id, menu_id: active.owner.menu_id.clone(), window_label: active.owner.window_label.clone(), key, repeat }) } @@ -255,53 +285,107 @@ pub(crate) fn capsule_label(label: &str) -> bool { .is_some_and(|suffix| !suffix.is_empty() && suffix.chars().all(|c| c.is_ascii_digit())) } +/// A delayed Automatic frame must not hide the badge and close a newer picker. +/// Preserve existing phase/audio/job and translation presentation semantics. +pub(crate) fn project_current_style(frame: &mut DictationStateSnapshot, current: &DictationStateSnapshot) { + if current.session_id.is_some() && frame.session_id == current.session_id + && matches!(current.phase, DictationPhase::Starting | DictationPhase::Recording) { + frame.skip_auto_style = current.skip_auto_style; + frame.style_pack_id = current.style_pack_id.clone(); + frame.style_pack_name = current.style_pack_name.clone(); + } +} + type Source = Arc Option + Send + Sync>; type Sink = Arc bool + Send + Sync>; +type EpochSource = Arc u64 + Send + Sync>; #[derive(Default)] -struct Runtime { state: Mutex, source: RwLock>, sink: RwLock> } +struct Runtime { + state: Mutex, + source: RwLock>, + sink: RwLock>, + epoch: RwLock>, +} static RUNTIME: OnceLock = OnceLock::new(); fn runtime() -> &'static Runtime { RUNTIME.get_or_init(Runtime::default) } fn context() -> Option { let source = runtime().source.read().clone()?; source() } +#[cfg(test)] pub(crate) fn configure(source: Source, sink: Sink) { *runtime().source.write() = Some(source); *runtime().sink.write() = Some(sink); + *runtime().epoch.write() = None; } -fn with_state(operation: impl FnOnce(&mut State, Option<&Context>) -> T) -> T { - let context = context(); +pub(crate) fn configure_fenced(source: Source, sink: Sink, epoch: EpochSource) { + *runtime().source.write() = Some(source); + *runtime().sink.write() = Some(sink); + *runtime().epoch.write() = Some(epoch); +} +fn flush_closed(closed: Vec) { + let sink = runtime().sink.read().clone(); + for event in closed { + if let Some(sink) = &sink { let _ = sink(Event::Closed(event)); } + } +} +fn with_state_unchecked(operation: impl FnOnce(&mut State) -> T) -> T { let (result, closed) = { let mut state = runtime().state.lock(); - let result = operation(&mut state, context.as_ref()); + let result = operation(&mut state); (result, std::mem::take(&mut state.closed)) }; - let sink = runtime().sink.read().clone(); - for event in closed { - if let Some(sink) = &sink { let _ = sink(Event::Closed(event)); } + flush_closed(closed); + result +} +fn with_state(operation: impl FnOnce(&mut State, Option<&Context>) -> T, + stale: impl FnOnce() -> T) -> T { + let epoch = runtime().epoch.read().clone(); + // Native focus checks stay outside the menu lock. Before applying their + // result, recheck the cheap Core-only fence *under* that lock. This also + // prevents an older absent view from revoking a newer session/menu. + let before = epoch.as_ref().map(|source| source()); + let context = context(); + let mut state = runtime().state.lock(); + let after = epoch.as_ref().map(|source| source()); + if before != after || context.as_ref().is_some_and(|c| + after.is_some_and(|current| c.style_epoch != current)) { + if let Some(current) = after { state.invalidate_before(current); } + let closed = std::mem::take(&mut state.closed); + drop(state); + flush_closed(closed); + // Do not repeat a native focus query on a keyboard-hook deadline. + // Decline fresh input; only the existing physical pair may be drained. + return stale(); } + let result = operation(&mut state, context.as_ref()); + let closed = std::mem::take(&mut state.closed); + drop(state); + flush_closed(closed); result } -pub(crate) fn hotkey_toggled(target: &DictationStyleTarget) -> Option { - with_state(|state, context| state.hotkey_toggled(target, context)) +pub(crate) fn hotkey_toggled(target: &DictationStyleTarget, epoch: u64) -> Option { + with_state(|state, context| state.hotkey_toggled(target, epoch, context), || None) } pub(crate) fn pending(label: &str) -> Option { - with_state(|state, context| state.pending(label, context)) + with_state(|state, context| state.pending(label, context), || None) } pub(crate) fn reservation(label: &str, session: SessionId, request: Option<&str>) -> Result { - with_state(|state, context| state.reservation(label, session, request, context)) + with_state(|state, context| state.reservation(label, session, request, context), + || Err(if request.is_some() { "capsule_style_request_stale" } else { "capsule_style_menu_reservation_stale" }.into())) } pub(crate) fn commit(owner: Owner, request: Option<&str>) -> Result<(), String> { - with_state(|state, context| state.commit(owner, request, context)) + with_state(|state, context| state.commit(owner, request, context), + || Err("capsule_style_menu_reservation_stale".into())) } pub(crate) fn close(label: &str, session: SessionId, menu_id: &str) -> bool { - with_state(|state, _| state.close(label, session, menu_id)) + with_state_unchecked(|state| state.close(label, session, menu_id)) } pub(crate) fn invalidate() { - with_state(|state, _| { state.pending = None; state.prepared = None; state.revoke(); }); + with_state_unchecked(|state| { state.pending = None; state.prepared = None; state.revoke(); }); } pub(crate) fn window_lost(label: &str) { - with_state(|state, _| { + with_state_unchecked(|state| { if label == "capsule" { state.pending = None; } if state.prepared.as_ref().is_some_and(|p| p.owner.window_label == label) { state.prepared = None; } if state.active.as_ref().is_some_and(|a| a.owner.window_label == label) { state.revoke(); } @@ -311,30 +395,31 @@ pub(crate) fn owner_current(owner: &Owner) -> bool { with_state(|state, context| { state.reconcile(context); state.active.as_ref().is_some_and(|active| active.owner == *owner) - }) + }, || false) } pub(crate) fn refresh() { // Ordinary audio/state traffic must not query foreground windows when // there is no picker intent or owner to validate. { let state = runtime().state.lock(); - if state.pending.is_none() && state.active.is_none() { return; } + if state.pending.is_none() && state.active.is_none() && state.prepared.is_none() { return; } } - with_state(|state, context| state.reconcile(context)); + with_state(|state, context| state.reconcile(context), || ()); } pub(crate) fn is_owner(event: &KeyEvent) -> bool { - with_state(|state, context| state.is_owner(event, context)) + with_state(|state, context| state.is_owner(event, context), || false) } pub(crate) fn key(key: Key, down: bool, repeat: bool, modified: bool) -> bool { { let mut state = runtime().state.lock(); if state.pending.is_none() && state.active.is_none() { - return state.key(key, down, repeat, modified, None, &|_| false); + return state.drain_key(key, down); } } let sink = runtime().sink.read().clone(); with_state(|state, context| state.key(key, down, repeat, modified, context, &|event| - sink.as_ref().is_some_and(|sink| sink(Event::Key(event))))) + sink.as_ref().is_some_and(|sink| sink(Event::Key(event)))), + || runtime().state.lock().drain_key(key, down)) } #[cfg(test)] @@ -343,7 +428,7 @@ mod tests { use std::cell::RefCell; fn context() -> Context { - Context { session_id: SessionId::new(), mutable: true, skip_auto: true, + Context { session_id: SessionId::new(), style_epoch: 1, mutable: true, skip_auto: true, picker_enabled: true, keyboard_available: true, focus: Some(Focus(9, 1)), blocked_keys: [false; 4] } } @@ -370,7 +455,7 @@ mod tests { // create an intent; only the explicit native-provenance method can. state.reconcile(Some(&c)); assert!(state.pending("capsule", Some(&c)).is_none()); - let request = state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), Some(&c)).unwrap(); + let request = state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), c.style_epoch, Some(&c)).unwrap(); for _ in 0..3 { assert_eq!(state.pending("capsule", Some(&c)), Some(request.clone())); } @@ -398,7 +483,7 @@ mod tests { for reason in 0..5 { let mut state = State::default(); let c = context(); - state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), Some(&c)).unwrap(); + state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), c.style_epoch, Some(&c)).unwrap(); let mut changed = c.clone(); match reason { 0 => changed.skip_auto = false, @@ -411,11 +496,11 @@ mod tests { } let mut state = State::default(); let c = context(); - assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::Automatic), Some(&c)).is_none()); - assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::StylePack { style_pack_id: "x".into() }), Some(&c)).is_none()); + assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::Automatic), c.style_epoch, Some(&c)).is_none()); + assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::StylePack { style_pack_id: "x".into() }), c.style_epoch, Some(&c)).is_none()); let mut disabled = c.clone(); disabled.picker_enabled = false; - assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), Some(&disabled)).is_none()); + assert!(state.hotkey_toggled(&target(&c, DictationStyleSelection::SkipAuto), c.style_epoch, Some(&disabled)).is_none()); } #[test] diff --git a/openless-all/app/src-tauri/src/coordinator/style_menu.rs b/openless-all/app/src-tauri/src/coordinator/style_menu.rs index 68d908fc6..461cd40a4 100644 --- a/openless-all/app/src-tauri/src/coordinator/style_menu.rs +++ b/openless-all/app/src-tauri/src/coordinator/style_menu.rs @@ -56,8 +56,9 @@ impl FocusState { pub(super) fn configure_style_menu(inner: &Arc) { let source = Arc::downgrade(inner); let sink = Arc::downgrade(inner); + let epoch = Arc::downgrade(inner); let focus = Mutex::new(FocusState::default()); - menu::configure(Arc::new(move || { + menu::configure_fenced(Arc::new(move || { let inner = source.upgrade()?; let snapshot = inner.backend.snapshot(); if !matches!(snapshot.dictation.phase, @@ -71,19 +72,22 @@ pub(super) fn configure_style_menu(inner: &Arc) { )) || inner.selection_polish_capsule_active.load(Ordering::SeqCst) { return None; } - let target = inner.backend.dictation_style_target()?; + // Query native focus first; then read current Core readiness and the + // capsule surface, so a slow AX/UIA query cannot replay Starting over + // an owner that has already mounted in this same style epoch. + let (focus, target_verified) = focus.lock().current() + .map(|(focus, verified)| (Some(focus), verified)).unwrap_or((None, false)); + let (target, style_epoch, picker_enabled) = inner.backend.dictation_style_target_with_epoch()?; if snapshot.dictation.session_id != Some(target.session_id) { return None; } let surface_available = inner.host.style_menu_surface_available(target.session_id); let keyboard_available = cfg!(any(target_os = "macos", target_os = "windows")) && !inner.shortcut_recording_active.load(Ordering::SeqCst) && inner.hotkey.try_lock().is_some_and(|monitor| monitor.is_some()) && surface_available; - let (focus, target_verified) = focus.lock().current() - .map(|(focus, verified)| (Some(focus), verified)).unwrap_or((None, false)); Some(Context { - session_id: target.session_id, mutable: target.mutable && surface_available, + session_id: target.session_id, style_epoch, mutable: target.mutable && surface_available, skip_auto: target.skip_auto_style, - picker_enabled: inner.backend.get_preferences().skip_auto_style_picker_enabled, + picker_enabled, // Window/control identity is the insertion adapter's existing // native proof (AX on macOS, HWND/UIA on Windows). Missing permission // or an unverifiable input target yields mouse-only ownership. @@ -92,14 +96,15 @@ pub(super) fn configure_style_menu(inner: &Arc) { }) }), Arc::new(move |event| { sink.upgrade().is_some_and(|inner| inner.host.queue_style_menu_event(event)) - })); + }), Arc::new(move || epoch.upgrade() + .map(|inner| inner.backend.dictation_style_epoch()).unwrap_or(u64::MAX))); } /// Only the two native hotkey consumers call this. Programmatic style changes /// and ordinary start options never pass through this provenance boundary. pub(super) fn handle_skip_auto_style_hotkey(inner: &Arc, session_id: openless_core::SessionId) { - if let Ok(target) = inner.backend.toggle_dictation_style_for_session(session_id) { - if let Some(request) = menu::hotkey_toggled(&target) { + if let Ok((target, epoch)) = inner.backend.toggle_dictation_style_with_epoch(session_id) { + if let Some(request) = menu::hotkey_toggled(&target, epoch) { let _ = inner.host.queue_style_menu_event(Event::Request(request)); } } diff --git a/openless-all/app/src-tauri/src/hotkey.rs b/openless-all/app/src-tauri/src/hotkey.rs index 6b8a04752..df5544296 100644 --- a/openless-all/app/src-tauri/src/hotkey.rs +++ b/openless-all/app/src-tauri/src/hotkey.rs @@ -1766,7 +1766,7 @@ pub(crate) mod platform { let _guard = crate::side_aware_combo::TEST_MONITOR_LOCK.blocking_lock(); let session = openless_core::SessionId::new(); let live = Arc::new(parking_lot::Mutex::new(Some(menu::Context { - session_id: session, mutable: false, skip_auto: true, picker_enabled: true, + session_id: session, style_epoch: 1, mutable: false, skip_auto: true, picker_enabled: true, keyboard_available: true, focus: Some(Focus(3, 1)), blocked_keys: [false; 4], }))); let source = live.clone(); @@ -1791,7 +1791,7 @@ pub(crate) mod platform { session_id: session, selection: openless_core::DictationStyleSelection::SkipAuto, skip_auto_style: true, mutable: false, style_pack_id: None, style_pack_name: None, polish_style_pack_id: None, available_styles: vec![], - }).unwrap(); + }, 1).unwrap(); assert!(menu::reservation("capsule", session, Some(&request.request_id)).is_err()); // A down passed before the menu has no matching captured up. assert!(!menu_callback(&ctx, 126, true, 0, false)); diff --git a/openless-all/app/src-tauri/src/tauri_events.rs b/openless-all/app/src-tauri/src/tauri_events.rs index e4b423581..2beb3ad19 100644 --- a/openless-all/app/src-tauri/src/tauri_events.rs +++ b/openless-all/app/src-tauri/src/tauri_events.rs @@ -206,6 +206,12 @@ async fn forward_legacy_event( if current.dictation.session_id.is_none() && current.processing_dictations.first().is_some_and(|job| job.session_id != snapshot.session_id) { return; } + #[cfg(not(mobile))] + let snapshot = { + let mut snapshot = snapshot; + crate::capsule_style_menu::project_current_style(&mut snapshot, ¤t.dictation); + snapshot + }; capsule_owners.transcription_notice = None; if snapshot.phase != DictationPhase::Idle { capsule_owners.qa_voice = None; From 67634fa777bd65a15b63f9af184be8df6e94cb9b Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:33:58 +0800 Subject: [PATCH 09/13] fix(capsule): classify stale style requests before command precheck --- .../capsule-style-menu-host-contract.test.mjs | 9 + .../tests/capsule_picker_command.rs | 174 ++++++++++++++++++ .../src-tauri/src/commands/capsule_picker.rs | 19 ++ .../app/src-tauri/src/commands/dictation.rs | 25 ++- 4 files changed, 213 insertions(+), 14 deletions(-) create mode 100644 openless-all/app/src-tauri/backend-tests/tests/capsule_picker_command.rs create mode 100644 openless-all/app/src-tauri/src/commands/capsule_picker.rs diff --git a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs index b87a5db79..9dd8259fb 100644 --- a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs +++ b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs @@ -8,10 +8,19 @@ const [commands, lib, hotkeys, loops, bridge, host, menu, selection] = await Pro ]); const core = await readFile(new URL('../crates/openless-core/src/api.rs', import.meta.url), 'utf8'); const appEvents = await read('tauri_events.rs'); +const pickerCommand = await read('commands/capsule_picker.rs'); assert.match(lib, /commands::get_capsule_style_menu_request/); assert.match(commands, /pub fn get_capsule_style_menu_request[^]*?capsule_label\(window.label\(\)\)/); assert.match(commands, /pub async fn set_capsule_style_menu[^]*?request_id: Option,[^]*?menu_id: Option/); assert.match(commands, /capsule\.set_style_menu_open\(label, session_id, open, request_id, menu_id\)/); +assert.match(commands, /capsule_picker::dispatch\(&core, session_id, open, style,[^]*?capsule\.set_style_menu_open/); +const pickerImpl = commands.slice(commands.indexOf('async fn set_capsule_picker_menu_impl')); +assert.doesNotMatch(pickerImpl, /dictation_style_target|recording_style_required/, + 'command admission must let request-aware style reservation classify stale sessions first'); +assert.match(pickerCommand, /if open && !style && !core.dictation_translation_target\(\)/); +assert.match(pickerCommand, /active.mutable && active.session_id == session_id/); +assert.match(pickerCommand, /return Err\("recording_translation_required".into\(\)\)/); +assert.doesNotMatch(pickerCommand, /dictation_style_target|recording_style_required/); const programmatic = commands.slice(commands.indexOf('pub fn update_dictation_style'), commands.indexOf('pub async fn start_dictation')); assert.doesNotMatch(programmatic, /hotkey_toggled|handle_skip_auto_style_hotkey/); assert.equal((loops.match(/handle_skip_auto_style_hotkey\(&inner, /g) ?? []).length, 2, diff --git a/openless-all/app/src-tauri/backend-tests/tests/capsule_picker_command.rs b/openless-all/app/src-tauri/backend-tests/tests/capsule_picker_command.rs new file mode 100644 index 000000000..58a8cf936 --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/capsule_picker_command.rs @@ -0,0 +1,174 @@ +//! Run the command's production admission helper before the real reservation. +#![allow(dead_code)] +#[path = "../../src/capsule_style_menu.rs"] +mod capsule_style_menu; +#[path = "../../src/commands/capsule_picker.rs"] +mod capsule_picker; + +use std::sync::{Arc, atomic::{AtomicBool, AtomicUsize, Ordering}}; +use capsule_style_menu as menu; +use openless_core::{BackendConfig, BackendDependencies, DictationStartOptions, + OpenLessBackend, SessionId}; + +struct PendingContext { + entered: Arc, + release: Arc, +} +impl openless_core::HostContextAdapter for PendingContext { + fn capture(&self, _: bool) -> futures_util::future::BoxFuture<'static, + Result> { + let entered = self.entered.clone(); + let release = self.release.clone(); + Box::pin(async move { + entered.notify_one(); + release.notified().await; + Ok(openless_core::HostContextCapture::default()) + }) + } +} + +fn style_open( + core: &OpenLessBackend, session: SessionId, request: Option<&str>, geometry: &AtomicUsize, +) -> Result { + capsule_picker::dispatch(core, session, true, true, || { + let owner = menu::reservation("capsule", session, request)?; + // Same ordering as set_style_menu_open: no native geometry before + // successful reservation; commit only after geometry succeeds. + geometry.fetch_add(1, Ordering::SeqCst); + menu::commit(owner.clone(), request)?; + Ok(owner) + }) +} + +fn translation( + core: &OpenLessBackend, session: SessionId, open: bool, geometry: &AtomicUsize, +) -> Result<(), String> { + capsule_picker::dispatch(core, session, open, false, || { + geometry.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) +} + +#[tokio::test] +async fn command_precheck_classifies_old_style_requests_before_geometry() { + let directory = tempfile::tempdir().unwrap(); + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let mut dependencies = BackendDependencies::unsupported(); + dependencies.host_actions = Arc::new(openless_core::testing::RecordingHostActions::default()); + dependencies.dictation_engine = Arc::new(openless_core::testing::FixtureDictationEngine::successful("", "")); + dependencies.text_inserter = Arc::new(openless_core::testing::FixtureTextInserter::with_outcome( + openless_core::InsertOutcome::Inserted, + )); + dependencies.services.host_context = Arc::new(PendingContext { + entered: entered.clone(), release: release.clone(), + }); + let backend = Arc::new(OpenLessBackend::new(BackendConfig { + data_dir: directory.path().to_owned(), ..Default::default() + }, dependencies).unwrap()); + backend.start().await.unwrap(); + let mut prefs = backend.get_preferences(); + prefs.skip_auto_style_picker_enabled = true; + prefs.translation_target_language = "English".into(); + prefs.working_languages = vec!["简体中文".into()]; + backend.update_settings(prefs, openless_core::SettingsUpdateOptions::STRICT, + &openless_core::NoopSettingsRuntime).unwrap(); + let source = Arc::downgrade(&backend); + let fence = Arc::downgrade(&backend); + let focus_available = Arc::new(AtomicBool::new(true)); + let source_focus = focus_available.clone(); + menu::configure_fenced(Arc::new(move || { + let core = source.upgrade()?; + if !matches!(core.snapshot().dictation.phase, openless_core::DictationPhase::Starting + | openless_core::DictationPhase::Recording) { return None; } + let (target, style_epoch, picker_enabled) = core.dictation_style_target_with_epoch()?; + Some(menu::Context { + session_id: target.session_id, style_epoch, mutable: target.mutable, + skip_auto: target.skip_auto_style, picker_enabled, keyboard_available: true, + focus: source_focus.load(Ordering::SeqCst).then_some(menu::Focus(1, 1)), + blocked_keys: [false; 4], + }) + }), Arc::new(|_| true), Arc::new(move || fence.upgrade().unwrap().dictation_style_epoch())); + let geometry = AtomicUsize::new(0); + let translation_geometry = AtomicUsize::new(0); + let start = tokio::spawn({ + let backend = backend.clone(); + async move { backend.start_dictation_with_options(DictationStartOptions { + translation_requested: true, ..Default::default() + }).await } + }); + entered.notified().await; + let session = backend.snapshot().dictation.session_id.unwrap(); + assert_eq!(backend.snapshot().dictation.phase, openless_core::DictationPhase::Starting); + let (target, epoch) = backend.toggle_dictation_style_with_epoch(session).unwrap(); + let request = menu::hotkey_toggled(&target, epoch).unwrap(); + assert_eq!(style_open(&backend, session, Some(&request.request_id), &geometry).unwrap_err(), + "recording_style_required", "a current pending request is genuinely not ready"); + assert_eq!(geometry.load(Ordering::SeqCst), 0); + assert_eq!(translation(&backend, session, true, &translation_geometry).unwrap_err(), + "recording_translation_required"); + assert_eq!(translation_geometry.load(Ordering::SeqCst), 0); + release.notify_one(); + assert_eq!(start.await.unwrap().unwrap(), session); + assert!(backend.dictation_translation_target().unwrap().mutable); + translation(&backend, session, true, &translation_geometry).unwrap(); + assert_eq!(translation_geometry.load(Ordering::SeqCst), 1); + + focus_available.store(false, Ordering::SeqCst); + assert_eq!(style_open(&backend, session, None, &geometry).unwrap_err(), + "capsule_style_menu_target_unavailable", "real target/permission failures stay visible"); + focus_available.store(true, Ordering::SeqCst); + // Generate a fresh actual receipt after focus invalidated the earlier one. + backend.toggle_dictation_style_with_epoch(session).unwrap(); + let (target, epoch) = backend.toggle_dictation_style_with_epoch(session).unwrap(); + let request = menu::hotkey_toggled(&target, epoch).unwrap(); + assert_eq!(capsule_picker::dispatch(&backend, session, true, true, || { + menu::reservation("capsule", session, Some(&request.request_id))?; + Err::<(), String>("native_geometry_failed".into()) + }).unwrap_err(), "native_geometry_failed"); + let owner = style_open(&backend, session, Some(&request.request_id), &geometry).unwrap(); + assert_eq!(geometry.load(Ordering::SeqCst), 1); + backend.toggle_dictation_style_with_epoch(session).unwrap(); + let (target, epoch) = backend.toggle_dictation_style_with_epoch(session).unwrap(); + let request = menu::hotkey_toggled(&target, epoch).unwrap(); + assert_eq!(menu::pending("capsule"), Some(request.clone())); + backend.cancel_dictation(Some(session)).await.unwrap(); + assert_eq!(style_open(&backend, session, Some(&request.request_id), &geometry).unwrap_err(), + "capsule_style_request_stale", "ended request must reach request-aware classification"); + assert_eq!(style_open(&backend, session, None, &geometry).unwrap_err(), + "recording_style_required", "explicit no-token errors are not silenced"); + assert_eq!(translation(&backend, session, true, &translation_geometry).unwrap_err(), + "recording_translation_required"); + translation(&backend, session, false, &translation_geometry).unwrap(); + assert_eq!(translation_geometry.load(Ordering::SeqCst), 2, "translation close bypasses open precheck"); + assert_eq!(geometry.load(Ordering::SeqCst), 1, "stale/no-token failures never reserve geometry"); + + let next_start = tokio::spawn({ + let backend = backend.clone(); + async move { backend.start_dictation().await } + }); + entered.notified().await; + let next = backend.snapshot().dictation.session_id.unwrap(); + release.notify_one(); + assert_eq!(next_start.await.unwrap().unwrap(), next); + assert_ne!(next, session); + assert_eq!(style_open(&backend, session, Some(&request.request_id), &geometry).unwrap_err(), + "capsule_style_request_stale", "old session request stays stale after replacement"); + assert_eq!(style_open(&backend, session, None, &geometry).unwrap_err(), "recording_style_required"); + assert_eq!(translation(&backend, session, true, &translation_geometry).unwrap_err(), + "recording_translation_required"); + assert_eq!(geometry.load(Ordering::SeqCst), 1); + let (target, epoch) = backend.toggle_dictation_style_with_epoch(next).unwrap(); + let next_request = menu::hotkey_toggled(&target, epoch).unwrap(); + let next_owner = style_open(&backend, next, Some(&next_request.request_id), &geometry).unwrap(); + assert_eq!(geometry.load(Ordering::SeqCst), 2, "a valid new request can reserve geometry"); + assert!(!capsule_picker::dispatch(&backend, session, false, true, || + Ok(menu::close("capsule", session, &owner.menu_id))).unwrap()); + assert!(menu::owner_current(&next_owner), "old close cannot release replacement owner"); + assert!(capsule_picker::dispatch(&backend, next, false, true, || + Ok(menu::close("capsule", next, &next_owner.menu_id))).unwrap()); + backend.cancel_dictation(Some(next)).await.unwrap(); + menu::invalidate(); + menu::configure(Arc::new(|| None), Arc::new(|_| false)); + backend.shutdown().await.unwrap(); +} diff --git a/openless-all/app/src-tauri/src/commands/capsule_picker.rs b/openless-all/app/src-tauri/src/commands/capsule_picker.rs new file mode 100644 index 000000000..654f00f81 --- /dev/null +++ b/openless-all/app/src-tauri/src/commands/capsule_picker.rs @@ -0,0 +1,19 @@ +//! Command-side admission before the existing native picker operation. +use openless_core::{OpenLessBackend, SessionId}; + +pub(super) fn dispatch( + core: &OpenLessBackend, + session_id: SessionId, + open: bool, + style: bool, + operation: impl FnOnce() -> Result, +) -> Result { + // Style admission belongs to its request-aware reservation: checking only + // current editability here would misclassify an ended/replaced request. + // Keep translation's existing precheck and let close retain its owner check. + if open && !style && !core.dictation_translation_target() + .is_some_and(|active| active.mutable && active.session_id == session_id) { + return Err("recording_translation_required".into()); + } + operation() +} diff --git a/openless-all/app/src-tauri/src/commands/dictation.rs b/openless-all/app/src-tauri/src/commands/dictation.rs index 6f4086759..f16dc8c35 100644 --- a/openless-all/app/src-tauri/src/commands/dictation.rs +++ b/openless-all/app/src-tauri/src/commands/dictation.rs @@ -1,5 +1,9 @@ use super::*; +#[cfg(not(mobile))] +#[path = "capsule_picker.rs"] +mod capsule_picker; + #[tauri::command] pub async fn get_startup_snapshot( core: CoreState<'_>, @@ -288,20 +292,13 @@ async fn set_capsule_picker_menu_impl( .ok_or("capsule_window_unavailable")?; let (send, receive) = tokio::sync::oneshot::channel(); capsule.run_on_main_thread(move |capsule| { - 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 result = if style { - capsule.set_style_menu_open(label, session_id, open, request_id, menu_id) - } else { - capsule.set_translation_menu_open(label, session_id, open).map(|_| None) - }; + let result = capsule_picker::dispatch(&core, session_id, open, style, || { + if style { + capsule.set_style_menu_open(label, session_id, open, request_id, menu_id) + } else { + capsule.set_translation_menu_open(label, session_id, open).map(|_| None) + } + }); let _ = send.send(result); })?; receive From 4db060a1d8d0df886ca745c28c3d8f32c3723869 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:02:03 +0800 Subject: [PATCH 10/13] fix(capsule): preserve language popup and replay contracts --- .../app/scripts/capsule-ready-replay.test.mjs | 23 +++++++++++++++---- .../skip-auto-style-ui-contract.test.mjs | 4 ++++ .../capsule/CapsuleTranslationBadge.tsx | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/openless-all/app/scripts/capsule-ready-replay.test.mjs b/openless-all/app/scripts/capsule-ready-replay.test.mjs index cd7a1d0ac..08b9700a3 100644 --- a/openless-all/app/scripts/capsule-ready-replay.test.mjs +++ b/openless-all/app/scripts/capsule-ready-replay.test.mjs @@ -47,6 +47,7 @@ function compileStandalone(relativePath) { } const auxiliaryEventsCode = compileStandalone('../src/runtime/windows/auxiliaryEvents.ts'); const dictationEventsCode = compileStandalone('../src/api/dictation.ts'); +const outputStyleCode = compileStandalone('../src/features/capsule/capsuleOutputStyle.ts'); function bindNativeAdapter(scope, tauri = true) { const runtime = { @@ -71,6 +72,8 @@ vm.runInNewContext( compile(readFileSync(new URL('../src/lib/backendEvent.ts', import.meta.url), 'utf8')), backend, ); +const outputStyle = { exports: {} }; +vm.runInNewContext(outputStyleCode, outputStyle); const effectCode = compile(`globalThis.replayEffect = (${effect});`); const railSource = readFileSync( new URL('../src/features/capsule/LiveTranscriptPill.tsx', import.meta.url), @@ -178,10 +181,11 @@ function mount({ const writes = []; const warnings = []; const traceCalls = []; - const values = { setState: 'idle', setLocalAsrText: '' }; + const values = { setState: 'idle', setLocalAsrText: '', setOutputStyle: null }; let requests = 0; const scope = { ...backend.exports, + ...outputStyle.exports, isTauri: true, isTauriHost: () => true, capsuleStateFirstLogged: true, @@ -250,6 +254,7 @@ function mount({ 'setMessage', 'setLocalAsrText', 'setTranslation', + 'setOutputStyle', 'setWarming', 'setSelectionPolish', 'setQa', @@ -261,7 +266,8 @@ function mount({ 'setEnabled', 'setFontSize', ]) { - scope[name] = (value) => { + scope[name] = (update) => { + const value = typeof update === 'function' ? update(values[name]) : update; values[name] = value; writes.push([name, value]); }; @@ -305,10 +311,16 @@ function transcript(view, sequence, text, sessionId = 'session') { // A lazy mirror replays a session whose starting event already happened. { - const view = mount({ snapshot: () => frame() }); - await until(() => view.values.setState === 'recording'); + const style = { skipAutoStyle: true, stylePackId: 'builtin.formal', stylePackName: 'Formal' }; + const view = mount({ snapshot: () => frame(style) }); + await until( + () => view.values.setOutputStyle?.packId === style.stylePackId || view.warnings.length > 0, + ); + assert.equal(view.warnings.length, 0, view.warnings.map(([, error]) => String(error)).join('\n')); + assert.equal(view.values.setState, 'recording'); + assert.equal(view.values.setOutputStyle.name, 'Formal'); assert.equal(view.values.setLocalAsrText, 'existing text'); - view.emit('capsule:state', { state: 'recording', sessionId: 'session' }); + view.emit('capsule:state', { ...style, state: 'recording', sessionId: 'session' }); assert.equal(view.values.setLocalAsrText, 'existing text'); transcript(view, 11, 'updated text'); assert.equal(view.values.setLocalAsrText, 'updated text'); @@ -319,6 +331,7 @@ function transcript(view, sequence, text, sessionId = 'session') { }); view.emit('capsule:state', { state: 'done', sessionId: 'session' }); assert.equal(view.values.setLocalAsrText, ''); + assert.equal(view.values.setOutputStyle, null); release(view); } diff --git a/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs b/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs index cbdd6fbe1..f3d4f8e45 100644 --- a/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs +++ b/openless-all/app/scripts/skip-auto-style-ui-contract.test.mjs @@ -38,6 +38,10 @@ assert.match(capsule, / void change(value)} side="top" popupStyle={{ width: 240 }} - popupClassName="ol-capsule-picker-popup" + popupClassName="ol-capsule-picker-popup ol-capsule-language-popup" /> From b816d8babcbe88a1bc2d337430cb0c869622533f Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:24:00 +0800 Subject: [PATCH 11/13] ci: refresh style picker checks against beta From 128b4469336d6b73be503f16c8a16e891c045919 Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:50:54 +0800 Subject: [PATCH 12/13] fix(capsule): observe Windows menu focus on a dedicated MTA --- .../capsule-style-menu-host-contract.test.mjs | 29 + .../app/src-tauri/backend-tests/Cargo.lock | 1 + .../app/src-tauri/backend-tests/Cargo.toml | 3 +- .../tests/capsule_windows_focus.rs | 423 ++++++++++++++ .../app/src-tauri/src/capsule_style_menu.rs | 16 +- .../src-tauri/src/coordinator/style_menu.rs | 69 ++- .../coordinator/style_menu/windows_focus.rs | 526 ++++++++++++++++++ 7 files changed, 1048 insertions(+), 19 deletions(-) create mode 100644 openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs create mode 100644 openless-all/app/src-tauri/src/coordinator/style_menu/windows_focus.rs diff --git a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs index 9dd8259fb..ee1771612 100644 --- a/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs +++ b/openless-all/app/scripts/capsule-style-menu-host-contract.test.mjs @@ -9,6 +9,7 @@ const [commands, lib, hotkeys, loops, bridge, host, menu, selection] = await Pro const core = await readFile(new URL('../crates/openless-core/src/api.rs', import.meta.url), 'utf8'); const appEvents = await read('tauri_events.rs'); const pickerCommand = await read('commands/capsule_picker.rs'); +const windowsFocus = await read('coordinator/style_menu/windows_focus.rs'); assert.match(lib, /commands::get_capsule_style_menu_request/); assert.match(commands, /pub fn get_capsule_style_menu_request[^]*?capsule_label\(window.label\(\)\)/); assert.match(commands, /pub async fn set_capsule_style_menu[^]*?request_id: Option,[^]*?menu_id: Option/); @@ -32,6 +33,34 @@ assert.match(bridge, /mutable: target.mutable && surface_available/); assert.match(host, /payload.state == CapsuleState::Recording && !payload.qa && !payload.selection_polish/); assert.match(bridge, /capsule_menu_input_target_is_current\(target\)/); assert.match(bridge, /capture_capsule_menu_input_target\(\)/); +assert.match(bridge, /#\[cfg\(not\(target_os = "windows"\)\)\]\s*impl FocusState/, + 'Windows must never run the caller-apartment selection/UIA helper'); +assert.match(bridge, /windows_focus::Owner::start\(\)/); +assert.match(bridge, /owner.submit\(windows_focus::Scope/); +assert.match(windowsFocus, /name\("capsule-focus-mta".into\(\)\)/); +assert.match(windowsFocus, /CoInitializeEx\(None, COINIT_MULTITHREADED\)/); +const focusRead = windowsFocus.slice(windowsFocus.indexOf('pub(crate) fn current('), + windowsFocus.indexOf('pub(crate) fn submit(')); +assert.doesNotMatch(focusRead, /CoInitialize|GetFocusedElement|CompareElements|recv|sleep|join/, + 'STA getters, reservations, main delivery and hooks read proofs without waiting for UIA'); +assert.match(focusRead, /proof.scope != scope/); +assert.match(focusRead, /proof.event != event/); +assert.match(focusRead, /proof.queried.elapsed\(\) > PROOF_LIFETIME/); +assert.match(focusRead, /Native::current\(\) != Some\(proof.native\)/); +assert.match(windowsFocus, /EVENT_SYSTEM_FOREGROUND, EVENT_OBJECT_FOCUS/); +assert.match(windowsFocus, /AddFocusChangedEventHandler/); +assert.match(windowsFocus, /CompareElements\(old, new\)/); +assert.match(windowsFocus, /Native::current\(\) == Some\(request.origin\)/); +assert.match(windowsFocus, /request.queued.elapsed\(\) <= PROOF_LIFETIME/); +assert.match(windowsFocus, /shared\s*\.demand\s*\.lock\(\)\s*\.as_ref\(\)\s*\.is_some_and/); +assert.match(bridge, /configure_focus_fenced/); +assert.match(menu, /focus_before != focus_after/); +assert.match(windowsFocus, /old.queried.elapsed\(\) <= PROOF_LIFETIME/); +assert.match(windowsFocus, /if !identity_same \|\| !continuous/); +assert.match(windowsFocus, /shared.notify\(\)/); +assert.match(windowsFocus, /wanted.epoch > request.scope.epoch/); +assert.doesNotMatch(windowsFocus, /SetFocus\(|SetForegroundWindow\(|SendInput|GetText|CurrentValue/, + 'the observer neither activates a window nor reads or synthesizes text/input'); assert.match(selection, /pub\(crate\) fn capture_capsule_menu_input_target[^]*?target.strict_input_target = true/); assert.match(menu, /keyboard_available: c.keyboard_available && c.focus.is_some\(\)/); assert.match(menu, /target.selection != DictationStyleSelection::SkipAuto/); diff --git a/openless-all/app/src-tauri/backend-tests/Cargo.lock b/openless-all/app/src-tauri/backend-tests/Cargo.lock index 1ad0507af..87bb03a29 100644 --- a/openless-all/app/src-tauri/backend-tests/Cargo.lock +++ b/openless-all/app/src-tauri/backend-tests/Cargo.lock @@ -1987,6 +1987,7 @@ dependencies = [ "url", "uuid", "windows 0.58.0", + "windows-core 0.58.0", "x509-parser", ] diff --git a/openless-all/app/src-tauri/backend-tests/Cargo.toml b/openless-all/app/src-tauri/backend-tests/Cargo.toml index 5dbf2354f..c93a2205c 100644 --- a/openless-all/app/src-tauri/backend-tests/Cargo.toml +++ b/openless-all/app/src-tauri/backend-tests/Cargo.toml @@ -42,7 +42,8 @@ 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"] } +windows-core = "0.58" +windows = { version = "0.58", features = ["implement", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Accessibility", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse"] } [target.'cfg(target_os = "linux")'.dev-dependencies] # Exercise the production recorder worker without the retired Linux Tauri host. diff --git a/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs b/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs new file mode 100644 index 000000000..7fcd8b726 --- /dev/null +++ b/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs @@ -0,0 +1,423 @@ +//! Windows runtime gate: real STA windows, real UIA and production MTA owner. +//! Requires an interactive Windows test desktop; missing UIA/focus is a failure. +#![cfg(target_os = "windows")] +#![allow(dead_code)] +#[path = "../../src/capsule_style_menu.rs"] +mod capsule_style_menu; +#[path = "../../src/coordinator/style_menu/windows_focus.rs"] +mod windows_focus; + +use capsule_style_menu as menu; +use std::{ + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc, Arc, + }, + time::{Duration, Instant}, +}; +use windows::{ + core::w, + Win32::{ + Foundation::HWND, + System::Com::{ + CoGetApartmentType, CoInitializeEx, CoUninitialize, APTTYPE, APTTYPEQUALIFIER, + APTTYPE_MTA, APTTYPE_STA, COINIT_APARTMENTTHREADED, + }, + UI::{ + Input::KeyboardAndMouse::{GetFocus, SetFocus}, + WindowsAndMessaging::*, + }, + }, +}; + +fn pump() { + unsafe { + let mut message = MSG::default(); + for _ in 0..64 { + if !PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() { + break; + } + let _ = TranslateMessage(&message); + DispatchMessageW(&message); + } + } +} +fn until(mut ready: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + pump(); + if ready() { + return; + } + std::thread::sleep(Duration::from_millis(5)); + } + panic!("real Windows UIA/focus runtime did not become ready on this desktop"); +} +fn receive(receiver: &mpsc::Receiver) -> T { + let mut value = None; + until(|| { + value = receiver.try_recv().ok(); + value.is_some() + }); + value.unwrap() +} +fn apartment() -> APTTYPE { + let (mut kind, mut qualifier) = (APTTYPE::default(), APTTYPEQUALIFIER::default()); + unsafe { + CoGetApartmentType(&mut kind, &mut qualifier).unwrap(); + } + kind +} +struct Desktop { + window: HWND, + first: HWND, + second: HWND, +} +impl Desktop { + unsafe fn new() -> Self { + CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().unwrap(); + let window = CreateWindowExW( + WINDOW_EX_STYLE::default(), + w!("STATIC"), + w!("capsule focus runtime"), + WS_OVERLAPPEDWINDOW | WS_VISIBLE, + 100, + 100, + 420, + 220, + None, + None, + None, + None, + ) + .unwrap(); + let edit = |y| { + CreateWindowExW( + WINDOW_EX_STYLE::default(), + w!("EDIT"), + w!(""), + WS_CHILD | WS_VISIBLE | WS_TABSTOP, + 10, + y, + 200, + 30, + window, + None, + None, + None, + ) + .unwrap() + }; + let (first, second) = (edit(10), edit(60)); + let _ = SetForegroundWindow(window); + let _ = SetFocus(first); + Self { + window, + first, + second, + } + } +} +impl Drop for Desktop { + fn drop(&mut self) { + unsafe { + let _ = DestroyWindow(self.window); + CoUninitialize(); + } + } +} +fn target(scope: windows_focus::Scope) -> openless_core::DictationStyleTarget { + openless_core::DictationStyleTarget { + session_id: scope.session, + selection: openless_core::DictationStyleSelection::SkipAuto, + skip_auto_style: true, + mutable: true, + style_pack_id: None, + style_pack_name: None, + polish_style_pack_id: None, + available_styles: vec![], + } +} +fn issue(owner: &windows_focus::Owner, scope: windows_focus::Scope) -> menu::Request { + let (send, receive_result) = mpsc::channel(); + assert!(owner.submit(scope, move || { + assert_eq!( + apartment(), + APTTYPE_MTA, + "UIA and request capture share the dedicated MTA" + ); + send.send(menu::hotkey_toggled(&target(scope), scope.epoch)) + .unwrap(); + })); + receive(&receive_result).expect("verified unchanged target must produce a request") +} + +#[test] +fn real_sta_getter_reserve_delivery_and_late_mta_completion_preserve_focus_ownership() { + let desktop = unsafe { Desktop::new() }; + assert_eq!( + unsafe { GetForegroundWindow() }, + desktop.window, + "test requires the controlled foreground desktop" + ); + assert_eq!(unsafe { GetFocus() }, desktop.first); + assert_eq!(apartment(), APTTYPE_STA); + let owner = windows_focus::Owner::start().unwrap(); + let scope = windows_focus::Scope { + session: openless_core::SessionId::new(), + epoch: 1, + }; + let live = Arc::new(parking_lot::Mutex::new(scope)); + let source_scope = live.clone(); + let source_owner = owner.clone(); + let epoch = Arc::new(AtomicU64::new(scope.epoch)); + let source_epoch = epoch.clone(); + let revision = owner.clone(); + menu::configure_focus_fenced( + Arc::new(move || { + let scope = *source_scope.lock(); + let (serial, process, verified) = source_owner.current(scope)?; + Some(menu::Context { + session_id: scope.session, + style_epoch: scope.epoch, + mutable: true, + skip_auto: true, + picker_enabled: true, + keyboard_available: verified, + focus: Some(menu::Focus(serial, process)), + blocked_keys: [false; 4], + }) + }), + Arc::new(|_| true), + Arc::new(move || source_epoch.load(Ordering::Acquire)), + Arc::new(move || revision.revision()), + ); + owner.set_observer(Arc::new(menu::refresh)); + until(|| { + owner + .current(scope) + .is_some_and(|(_, _, verified)| verified) + }); + let request = issue(&owner, scope); + // These are the production calls made by STA request delivery, getter, + // reservation, geometry completion, watch and queued key delivery. + assert_eq!(menu::pending("capsule"), Some(request.clone())); + let reserved = menu::reservation("capsule", scope.session, Some(&request.request_id)).unwrap(); + assert!( + reserved.keyboard_available, + "real UIA proof must survive the STA handoff" + ); + menu::commit(reserved.clone(), Some(&request.request_id)).unwrap(); + menu::refresh(); + assert!(menu::owner_current(&reserved)); + assert!(menu::key(menu::Key::Enter, true, false, false)); + assert!(!menu::key(menu::Key::Escape, true, false, true)); + let key = menu::KeyEvent { + session_id: scope.session, + menu_id: reserved.menu_id.clone(), + window_label: "capsule".into(), + key: menu::Key::Enter, + repeat: false, + }; + assert!(menu::is_owner(&key)); + assert_eq!( + apartment(), + APTTYPE_STA, + "STA must never be reinitialized to MTA" + ); + + unsafe { + let _ = SetFocus(desktop.second); + } + assert!( + !menu::owner_current(&reserved), + "HWND focus change rejects immediately, without waiting for UIA" + ); + assert!(!menu::is_owner(&key)); + assert!(menu::key(menu::Key::Enter, false, false, false)); + assert!(!menu::key(menu::Key::Escape, false, false, false)); + assert!(!menu::key(menu::Key::ArrowDown, true, false, false)); + assert!(!menu::key(menu::Key::ArrowDown, false, false, false)); + assert!(menu::reservation("capsule", scope.session, Some(&request.request_id)).is_err()); + + // Hold a real owner job, then replace the Core receipt while it is late. + // The old COM completion must not authorize that new session/epoch. + let (entered, began) = mpsc::channel(); + let (release, resume) = mpsc::channel(); + until(|| { + owner + .current(scope) + .is_some_and(|(_, _, verified)| verified) + }); + assert!(owner.submit(scope, move || { + entered.send(()).unwrap(); + resume.recv_timeout(Duration::from_secs(3)).unwrap(); + })); + receive(&began); + let obsolete_ran = Arc::new(AtomicBool::new(false)); + let obsolete_job = obsolete_ran.clone(); + assert!(owner.submit(scope, move || { + obsolete_job.store(true, Ordering::Release); + let _ = menu::hotkey_toggled(&target(scope), scope.epoch); + })); + unsafe { + let _ = SetFocus(desktop.first); + } + let next = windows_focus::Scope { + session: openless_core::SessionId::new(), + epoch: 2, + }; + *live.lock() = next; + epoch.store(next.epoch, Ordering::Release); + assert!(owner.current(next).is_none()); + menu::refresh(); + release.send(()).unwrap(); + until(|| owner.current(next).is_some_and(|(_, _, verified)| verified)); + assert!( + !obsolete_ran.load(Ordering::Acquire), + "queued work cannot retarget to another native control" + ); + assert!( + menu::pending("capsule").is_none(), + "fresh proof alone never resurrects a request" + ); + assert!(!menu::owner_current(&reserved)); + let next_request = issue(&owner, next); + let next_owner = + menu::reservation("capsule", next.session, Some(&next_request.request_id)).unwrap(); + menu::commit(next_owner.clone(), Some(&next_request.request_id)).unwrap(); + assert!(!menu::close("capsule", scope.session, &reserved.menu_id)); + assert!(menu::owner_current(&next_owner)); + assert!(menu::close("capsule", next.session, &next_owner.menu_id)); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + assert_eq!(apartment(), APTTYPE_STA); + + // A blocked/late owner must not grant an unlimited cached keyboard lease. + let fresh = windows_focus::Scope { + session: next.session, + epoch: 3, + }; + *live.lock() = fresh; + epoch.store(fresh.epoch, Ordering::Release); + until(|| { + owner + .current(fresh) + .is_some_and(|(_, _, verified)| verified) + }); + let fresh_request = issue(&owner, fresh); + let fresh_owner = + menu::reservation("capsule", fresh.session, Some(&fresh_request.request_id)).unwrap(); + menu::commit(fresh_owner.clone(), Some(&fresh_request.request_id)).unwrap(); + assert!(menu::key(menu::Key::Enter, true, false, false)); + let (entered, began) = mpsc::channel(); + let (release, resume) = mpsc::channel(); + assert!(owner.submit(fresh, move || { + entered.send(()).unwrap(); + resume.recv_timeout(Duration::from_secs(3)).unwrap(); + })); + receive(&began); + std::thread::sleep(Duration::from_millis(180)); + assert!( + owner.current(fresh).is_none(), + "stalled UIA proof expires even with unchanged HWND" + ); + assert!(!menu::owner_current(&fresh_owner)); + assert!(menu::key(menu::Key::Enter, false, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); + assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); + release.send(()).unwrap(); + until(|| { + owner + .current(fresh) + .is_some_and(|(_, _, verified)| verified) + }); + assert!(menu::pending("capsule").is_none()); + assert!(!menu::owner_current(&fresh_owner)); + + // Expiry also breaks a prepared token when no UI reader observed the gap. + let prepared_scope = windows_focus::Scope { + session: fresh.session, + epoch: 4, + }; + *live.lock() = prepared_scope; + epoch.store(prepared_scope.epoch, Ordering::Release); + until(|| { + owner + .current(prepared_scope) + .is_some_and(|(_, _, verified)| verified) + }); + let pending = issue(&owner, prepared_scope); + let prepared = + menu::reservation("capsule", prepared_scope.session, Some(&pending.request_id)).unwrap(); + let (entered, began) = mpsc::channel(); + let (release, resume) = mpsc::channel(); + assert!(owner.submit(prepared_scope, move || { + entered.send(()).unwrap(); + resume.recv_timeout(Duration::from_secs(3)).unwrap(); + })); + receive(&began); + std::thread::sleep(Duration::from_millis(180)); + release.send(()).unwrap(); + until(|| { + owner + .current(prepared_scope) + .is_some_and(|(_, _, verified)| verified) + }); + assert_eq!( + menu::commit(prepared, Some(&pending.request_id)).unwrap_err(), + "capsule_style_menu_reservation_stale" + ); + menu::invalidate(); + menu::configure(Arc::new(|| None), Arc::new(|_| false)); + drop(owner); + + // Real HWND/event ownership still applies when UIA cannot be established. + // This test-only seam disables UIA creation, not the production native + // focus capture, event hooks, COM owner runtime or protocol. + let fallback = windows_focus::Owner::without_uia_for_test().unwrap(); + let source = fallback.clone(); + let fallback_scope = windows_focus::Scope { + session: openless_core::SessionId::new(), + epoch: 5, + }; + let revision = fallback.clone(); + menu::configure_focus_fenced( + Arc::new(move || { + let (serial, process, verified) = source.current(fallback_scope)?; + Some(menu::Context { + session_id: fallback_scope.session, + style_epoch: fallback_scope.epoch, + mutable: true, + skip_auto: true, + picker_enabled: true, + keyboard_available: verified, + focus: Some(menu::Focus(serial, process)), + blocked_keys: [false; 4], + }) + }), + Arc::new(|_| true), + Arc::new(move || fallback_scope.epoch), + Arc::new(move || revision.revision()), + ); + fallback.set_observer(Arc::new(menu::refresh)); + until(|| { + fallback + .current(fallback_scope) + .is_some_and(|(_, _, verified)| !verified) + }); + let request = issue(&fallback, fallback_scope); + let mouse = + menu::reservation("capsule", fallback_scope.session, Some(&request.request_id)).unwrap(); + assert!(!mouse.keyboard_available); + menu::commit(mouse.clone(), Some(&request.request_id)).unwrap(); + assert!(!menu::key(menu::Key::Enter, true, false, false)); + unsafe { + let _ = SetFocus(desktop.second); + } + assert!(!menu::owner_current(&mouse)); + assert!(!menu::key(menu::Key::Enter, false, false, false)); + assert_eq!(apartment(), APTTYPE_STA); + menu::invalidate(); + menu::configure(Arc::new(|| None), Arc::new(|_| false)); +} diff --git a/openless-all/app/src-tauri/src/capsule_style_menu.rs b/openless-all/app/src-tauri/src/capsule_style_menu.rs index 239a588be..271a37a2b 100644 --- a/openless-all/app/src-tauri/src/capsule_style_menu.rs +++ b/openless-all/app/src-tauri/src/capsule_style_menu.rs @@ -299,12 +299,14 @@ pub(crate) fn project_current_style(frame: &mut DictationStateSnapshot, current: type Source = Arc Option + Send + Sync>; type Sink = Arc bool + Send + Sync>; type EpochSource = Arc u64 + Send + Sync>; +type FocusRevision = Arc (u64, u64) + Send + Sync>; #[derive(Default)] struct Runtime { state: Mutex, source: RwLock>, sink: RwLock>, epoch: RwLock>, + focus_revision: RwLock>, } static RUNTIME: OnceLock = OnceLock::new(); fn runtime() -> &'static Runtime { RUNTIME.get_or_init(Runtime::default) } @@ -317,11 +319,18 @@ pub(crate) fn configure(source: Source, sink: Sink) { *runtime().source.write() = Some(source); *runtime().sink.write() = Some(sink); *runtime().epoch.write() = None; + *runtime().focus_revision.write() = None; } pub(crate) fn configure_fenced(source: Source, sink: Sink, epoch: EpochSource) { *runtime().source.write() = Some(source); *runtime().sink.write() = Some(sink); *runtime().epoch.write() = Some(epoch); + *runtime().focus_revision.write() = None; +} +#[cfg(target_os = "windows")] +pub(crate) fn configure_focus_fenced(source: Source, sink: Sink, epoch: EpochSource, focus: FocusRevision) { + configure_fenced(source, sink, epoch); + *runtime().focus_revision.write() = Some(focus); } fn flush_closed(closed: Vec) { let sink = runtime().sink.read().clone(); @@ -341,14 +350,17 @@ fn with_state_unchecked(operation: impl FnOnce(&mut State) -> T) -> T { fn with_state(operation: impl FnOnce(&mut State, Option<&Context>) -> T, stale: impl FnOnce() -> T) -> T { let epoch = runtime().epoch.read().clone(); + let focus_revision = runtime().focus_revision.read().clone(); // Native focus checks stay outside the menu lock. Before applying their - // result, recheck the cheap Core-only fence *under* that lock. This also + // result, recheck cheap Core/focus revision fences *under* that lock. This also // prevents an older absent view from revoking a newer session/menu. let before = epoch.as_ref().map(|source| source()); + let focus_before = focus_revision.as_ref().map(|source| source()); let context = context(); let mut state = runtime().state.lock(); let after = epoch.as_ref().map(|source| source()); - if before != after || context.as_ref().is_some_and(|c| + let focus_after = focus_revision.as_ref().map(|source| source()); + if before != after || focus_before != focus_after || context.as_ref().is_some_and(|c| after.is_some_and(|current| c.style_epoch != current)) { if let Some(current) = after { state.invalidate_before(current); } let closed = std::mem::take(&mut state.closed); diff --git a/openless-all/app/src-tauri/src/coordinator/style_menu.rs b/openless-all/app/src-tauri/src/coordinator/style_menu.rs index 461cd40a4..cab536360 100644 --- a/openless-all/app/src-tauri/src/coordinator/style_menu.rs +++ b/openless-all/app/src-tauri/src/coordinator/style_menu.rs @@ -2,6 +2,13 @@ use super::*; use crate::capsule_style_menu::{self as menu, Context, Event, Focus}; +#[cfg(target_os = "windows")] +#[path = "style_menu/windows_focus.rs"] +mod windows_focus; +#[cfg(target_os = "windows")] +static WINDOWS_FOCUS: std::sync::OnceLock>> = std::sync::OnceLock::new(); + +#[cfg(not(target_os = "windows"))] fn foreground() -> Option { #[cfg(target_os = "macos")] { @@ -10,29 +17,19 @@ fn foreground() -> Option { Some(Focus((u64::from(pid) << 32) | u64::from(window), crate::ask_window::active_space_epoch())) } - #[cfg(target_os = "windows")] - { - use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; - unsafe { - let window = GetForegroundWindow(); - if window.0.is_null() { return None; } - let mut pid = 0; - GetWindowThreadProcessId(window, Some(&mut pid)); - (pid != 0 && GetForegroundWindow() == window) - .then_some(Focus(window.0 as usize as u64, u64::from(pid))) - } - } #[cfg(not(any(target_os = "macos", target_os = "windows")))] { None } } #[derive(Default)] +#[cfg(not(target_os = "windows"))] struct FocusState { serial: u64, native: Option, target: Option, } +#[cfg(not(target_os = "windows"))] impl FocusState { fn current(&mut self) -> Option<(Focus, bool)> { let native = foreground()?; @@ -57,8 +54,16 @@ pub(super) fn configure_style_menu(inner: &Arc) { let source = Arc::downgrade(inner); let sink = Arc::downgrade(inner); let epoch = Arc::downgrade(inner); + #[cfg(not(target_os = "windows"))] let focus = Mutex::new(FocusState::default()); - menu::configure_fenced(Arc::new(move || { + #[cfg(target_os = "windows")] + let focus = windows_focus::Owner::start().map_err(|error| + log::warn!("[capsule] focus owner unavailable: {error}")).ok(); + #[cfg(target_os = "windows")] + { *WINDOWS_FOCUS.get_or_init(|| Mutex::new(None)).lock() = focus.clone(); } + #[cfg(target_os = "windows")] + let focus_revision = focus.clone(); + let source = Arc::new(move || { let inner = source.upgrade()?; let snapshot = inner.backend.snapshot(); if !matches!(snapshot.dictation.phase, @@ -75,9 +80,15 @@ pub(super) fn configure_style_menu(inner: &Arc) { // Query native focus first; then read current Core readiness and the // capsule surface, so a slow AX/UIA query cannot replay Starting over // an owner that has already mounted in this same style epoch. + #[cfg(not(target_os = "windows"))] let (focus, target_verified) = focus.lock().current() .map(|(focus, verified)| (Some(focus), verified)).unwrap_or((None, false)); let (target, style_epoch, picker_enabled) = inner.backend.dictation_style_target_with_epoch()?; + #[cfg(target_os = "windows")] + let (focus, target_verified) = focus.as_ref() + .and_then(|focus| focus.current(windows_focus::Scope { session: target.session_id, epoch: style_epoch })) + .map(|(serial, process, verified)| (Some(Focus(serial, process)), verified)) + .unwrap_or((None, false)); if snapshot.dictation.session_id != Some(target.session_id) { return None; } let surface_available = inner.host.style_menu_surface_available(target.session_id); let keyboard_available = cfg!(any(target_os = "macos", target_os = "windows")) @@ -94,16 +105,42 @@ pub(super) fn configure_style_menu(inner: &Arc) { keyboard_available: keyboard_available && target_verified, focus, blocked_keys: menu::blocked_keys(&hotkey_runtime_target(&inner)), }) - }), Arc::new(move |event| { + }); + let sink = Arc::new(move |event| { sink.upgrade().is_some_and(|inner| inner.host.queue_style_menu_event(event)) - }), Arc::new(move || epoch.upgrade() - .map(|inner| inner.backend.dictation_style_epoch()).unwrap_or(u64::MAX))); + }); + let epoch = Arc::new(move || epoch.upgrade() + .map(|inner| inner.backend.dictation_style_epoch()).unwrap_or(u64::MAX)); + #[cfg(not(target_os = "windows"))] + menu::configure_fenced(source, sink, epoch); + #[cfg(target_os = "windows")] + { + let observer = focus_revision.clone(); + menu::configure_focus_fenced(source, sink, epoch, Arc::new(move || + focus_revision.as_ref().map(|focus| focus.revision()).unwrap_or((u64::MAX, u64::MAX)))); + if let Some(owner) = observer { owner.set_observer(Arc::new(menu::refresh)); } + } } /// Only the two native hotkey consumers call this. Programmatic style changes /// and ordinary start options never pass through this provenance boundary. pub(super) fn handle_skip_auto_style_hotkey(inner: &Arc, session_id: openless_core::SessionId) { if let Ok((target, epoch)) = inner.backend.toggle_dictation_style_with_epoch(session_id) { + #[cfg(target_os = "windows")] + { + let owner = WINDOWS_FOCUS.get().and_then(|slot| slot.lock().clone()); + let weak = Arc::downgrade(inner); + if let Some(owner) = owner { + let _ = owner.submit(windows_focus::Scope { session: session_id, epoch }, move || { + if let Some(inner) = weak.upgrade() { + if let Some(request) = menu::hotkey_toggled(&target, epoch) { + let _ = inner.host.queue_style_menu_event(Event::Request(request)); + } + } + }); + } + } + #[cfg(not(target_os = "windows"))] if let Some(request) = menu::hotkey_toggled(&target, epoch) { let _ = inner.host.queue_style_menu_event(Event::Request(request)); } diff --git a/openless-all/app/src-tauri/src/coordinator/style_menu/windows_focus.rs b/openless-all/app/src-tauri/src/coordinator/style_menu/windows_focus.rs new file mode 100644 index 000000000..531353f77 --- /dev/null +++ b/openless-all/app/src-tauri/src/coordinator/style_menu/windows_focus.rs @@ -0,0 +1,526 @@ +//! UIA belongs exclusively to this non-UI MTA. Readers never wait for COM. +//! Published proofs expire and are fenced by native focus events and HWND identity. +use openless_core::SessionId; +use parking_lot::Mutex; +use std::{ + cell::RefCell, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + mpsc, Arc, + }, + thread, + time::{Duration, Instant}, +}; +use windows::{ + core::{implement, Interface, Result as WinResult}, + Win32::{ + Foundation::HWND, + System::Com::{ + CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER, + COINIT_MULTITHREADED, + }, + UI::{Accessibility::*, WindowsAndMessaging::*}, + }, +}; + +const TICK: Duration = Duration::from_millis(25); +const PROOF_LIFETIME: Duration = Duration::from_millis(150); +const DEMAND_LIFETIME: Duration = Duration::from_millis(200); +const QUERY_MS: u32 = 80; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Scope { + pub session: SessionId, + pub epoch: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Native { + window: usize, + process: u32, + thread: u32, + control: usize, + control_process: u32, + control_thread: u32, +} +impl Native { + fn current() -> Option { + unsafe { + let window = GetForegroundWindow(); + if window.0.is_null() { + return None; + } + let mut process = 0; + let thread = GetWindowThreadProcessId(window, Some(&mut process)); + let mut info = GUITHREADINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + if thread == 0 + || process == 0 + || GetGUIThreadInfo(thread, &mut info).is_err() + || info.hwndFocus.0.is_null() + { + return None; + } + let mut control_process = 0; + let control_thread = + GetWindowThreadProcessId(info.hwndFocus, Some(&mut control_process)); + if control_thread == 0 || control_process != process || GetForegroundWindow() != window + { + return None; + } + Some(Self { + window: window.0 as usize, + process, + thread, + control: info.hwndFocus.0 as usize, + control_process, + control_thread, + }) + } + } +} + +#[derive(Clone, Copy)] +struct Proof { + scope: Scope, + native: Native, + event: u64, + serial: u64, + queried: Instant, + verified: bool, +} +struct Shared { + proof: Mutex>, + demand: Mutex>, + events: Arc, + publication: AtomicU64, + observer: Mutex>>, + stopped: AtomicBool, +} +impl Shared { + fn clear(&self) { + let mut proof = self.proof.lock(); + if proof.take().is_some() { + self.publication.fetch_add(1, Ordering::AcqRel); + } + } + fn notify(&self) { + let observer = self.observer.lock().clone(); + if let Some(observer) = observer { + observer(); + } + } +} +type Job = Box; +struct Request { + scope: Scope, + queued: Instant, + origin: Native, + event: u64, + job: Job, +} +struct Handle { + shared: Arc, + sender: mpsc::SyncSender, + thread: thread::Thread, +} +impl Drop for Handle { + fn drop(&mut self) { + self.shared.stopped.store(true, Ordering::Release); + self.shared.clear(); + self.thread.unpark(); + } +} +#[derive(Clone)] +pub(crate) struct Owner(Arc); +impl Owner { + pub(crate) fn start() -> std::io::Result { + Self::start_with_uia(true) + } + fn start_with_uia(allow_uia: bool) -> std::io::Result { + let shared = Arc::new(Shared { + proof: Mutex::new(None), + demand: Mutex::new(None), + events: Arc::new(AtomicU64::new(0)), + publication: AtomicU64::new(0), + observer: Mutex::new(None), + stopped: AtomicBool::new(false), + }); + let (sender, receiver) = mpsc::sync_channel::(8); + let worker = shared.clone(); + let thread = thread::Builder::new() + .name("capsule-focus-mta".into()) + .spawn(move || { + run(&worker, receiver, allow_uia); + worker.stopped.store(true, Ordering::Release); + worker.clear(); + worker.notify(); + })?; + Ok(Self(Arc::new(Handle { + shared, + sender, + thread: thread.thread().clone(), + }))) + } + #[cfg(test)] + #[allow(dead_code)] + pub(crate) fn without_uia_for_test() -> std::io::Result { + Self::start_with_uia(false) + } + pub(crate) fn revision(&self) -> (u64, u64) { + ( + self.0.shared.events.load(Ordering::Acquire), + self.0.shared.publication.load(Ordering::Acquire), + ) + } + pub(crate) fn set_observer(&self, observer: Arc) { + *self.0.shared.observer.lock() = Some(observer); + } + /// Only value data crosses threads; no UIA interface leaves the owner. + pub(crate) fn current(&self, scope: Scope) -> Option<(u64, u64, bool)> { + let shared = &self.0.shared; + if shared.stopped.load(Ordering::Acquire) { + return None; + } + { + let mut demand = shared.demand.lock(); + if demand.as_ref().is_some_and(|(newer, _)| { + newer.epoch > scope.epoch + || (newer.epoch == scope.epoch && newer.session != scope.session) + }) { + return None; + } + *demand = Some((scope, Instant::now())); + } + if thread::current().id() != self.0.thread.id() { + self.0.thread.unpark(); + } + let proof = (*shared.proof.lock())?; + let event = shared.events.load(Ordering::Acquire); + if proof.scope != scope + || proof.event != event + || proof.queried.elapsed() > PROOF_LIFETIME + || Native::current() != Some(proof.native) + || shared.events.load(Ordering::Acquire) != event + { + return None; + } + Some(( + proof.serial, + u64::from(proof.native.process), + proof.verified, + )) + } + /// Initial hotkey capture must complete on the owner before creating intent. + /// Neither the Tauri UI thread nor a keyboard hook waits on this job. + pub(crate) fn submit(&self, scope: Scope, job: impl FnOnce() + Send + 'static) -> bool { + if self.0.shared.stopped.load(Ordering::Acquire) { + return false; + } + let Some(origin) = Native::current() else { + return false; + }; + let event = self.0.shared.events.load(Ordering::Acquire); + let accepted = self + .0 + .sender + .try_send(Request { + scope, + queued: Instant::now(), + origin, + event, + job: Box::new(job), + }) + .is_ok(); + if accepted { + self.0.thread.unpark(); + } + accepted + } +} + +thread_local! { + static EVENTS: RefCell>> = const { RefCell::new(None) }; +} +unsafe extern "system" fn focus_changed( + _: HWINEVENTHOOK, + _: u32, + _: HWND, + _: i32, + _: i32, + _: u32, + _: u32, +) { + EVENTS.with(|slot| { + if let Some(epoch) = slot.borrow().as_ref() { + epoch.fetch_add(1, Ordering::AcqRel); + } + }); +} +#[implement(IUIAutomationFocusChangedEventHandler)] +struct Changed(Arc); +impl IUIAutomationFocusChangedEventHandler_Impl for Changed_Impl { + fn HandleFocusChangedEvent(&self, _: Option<&IUIAutomationElement>) -> WinResult<()> { + // Callback threads only invalidate; they never call back into UIA. + self.0.fetch_add(1, Ordering::AcqRel); + Ok(()) + } +} +struct Apartment; +impl Drop for Apartment { + fn drop(&mut self) { + unsafe { CoUninitialize() } + } +} +struct Platform { + uia: Option, + handler: Option, + hooks: Vec, + _apartment: Apartment, +} +impl Platform { + fn new(events: Arc, allow_uia: bool) -> Option { + unsafe { + // Only this freshly created thread initializes COM. Never change + // the apartment of a caller (especially Tauri's STA/OLE thread). + CoInitializeEx(None, COINIT_MULTITHREADED).ok().ok()?; + let mut platform = Self { + uia: None, + handler: None, + hooks: vec![], + _apartment: Apartment, + }; + EVENTS.with(|slot| *slot.borrow_mut() = Some(events.clone())); + for event in [EVENT_SYSTEM_FOREGROUND, EVENT_OBJECT_FOCUS] { + let hook = SetWinEventHook( + event, + event, + None, + Some(focus_changed), + 0, + 0, + WINEVENT_OUTOFCONTEXT, + ); + if hook.is_invalid() { + return None; + } + platform.hooks.push(hook); + } + // UIA unavailable -> native HWND-bound mouse-only proof. This is + // permission/provider failure on the owner, never an STA error. + let setup = || -> WinResult<(IUIAutomation, IUIAutomationFocusChangedEventHandler)> { + let uia: IUIAutomation = + CoCreateInstance(&CUIAutomation8, None, CLSCTX_INPROC_SERVER)?; + let timeouts: IUIAutomation2 = uia.cast()?; + timeouts.SetConnectionTimeout(QUERY_MS)?; + timeouts.SetTransactionTimeout(QUERY_MS)?; + let handler: IUIAutomationFocusChangedEventHandler = Changed(events).into(); + uia.AddFocusChangedEventHandler(None, &handler)?; + Ok((uia, handler)) + }; + if allow_uia { + if let Ok((uia, handler)) = setup() { + platform.uia = Some(uia); + platform.handler = Some(handler); + } + } + Some(platform) + } + } + fn poll(&self) { + unsafe { + let mut message = MSG::default(); + for _ in 0..64 { + if !PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() { + break; + } + let _ = TranslateMessage(&message); + DispatchMessageW(&message); + } + } + } + fn focused(&self, native: Native) -> Option { + unsafe { + let element = self.uia.as_ref()?.GetFocusedElement().ok()?; + if element.CurrentProcessId().ok()? != native.process as i32 + || element.CurrentIsPassword().ok()?.as_bool() + { + return None; + } + Some(element) + } + } +} +impl Drop for Platform { + fn drop(&mut self) { + unsafe { + if let (Some(uia), Some(handler)) = (&self.uia, &self.handler) { + let _ = uia.RemoveFocusChangedEventHandler(handler); + } + for hook in &self.hooks { + let _ = UnhookWinEvent(*hook); + } + } + EVENTS.with(|slot| *slot.borrow_mut() = None); + } +} +struct Captured { + native: Native, + event: u64, + element: Option, +} +fn capture( + platform: &Platform, + shared: &Shared, + scope: Scope, + serial: &mut u64, + captured: &mut Option, +) { + let queried = Instant::now(); + let event = shared.events.load(Ordering::Acquire); + let Some(native) = Native::current() else { + shared.clear(); + *captured = None; + return; + }; + let element = platform.focused(native); + // Deliver queued WinEvents before comparing the before/after fence. + platform.poll(); + if shared.stopped.load(Ordering::Acquire) + || queried.elapsed() > PROOF_LIFETIME + || shared.events.load(Ordering::Acquire) != event + || Native::current() != Some(native) + { + shared.clear(); + return; + } + // A gap in proof validity is a new ownership generation even when the + // same HWND/control comes back. A prepared/active menu cannot revive just + // because no reader happened to observe the expired interval. + let identity_same = captured.as_ref().is_some_and(|old| { + old.native == native + && old.event == event + && match (&old.element, &element, &platform.uia) { + (Some(old), Some(new), Some(uia)) => unsafe { + uia.CompareElements(old, new) + .is_ok_and(|same| same.as_bool()) + }, + (None, None, _) => true, + _ => false, + } + }); + let continuous = shared + .proof + .lock() + .as_ref() + .is_some_and(|old| old.queried.elapsed() <= PROOF_LIFETIME); + if !identity_same || !continuous { + *serial = serial + .checked_add(1) + .expect("capsule focus serial exhausted"); + } + let mut proof = Proof { + scope, + native, + event, + serial: *serial, + queried, + verified: element.is_some(), + }; + *captured = Some(Captured { + native, + event, + element, + }); + // No old-scope completion can publish over a newer submitted demand. + if shared + .demand + .lock() + .as_ref() + .is_some_and(|(wanted, _)| *wanted == scope) + && shared.events.load(Ordering::Acquire) == event + && Native::current() == Some(native) + && queried.elapsed() <= PROOF_LIFETIME + { + let mut slot = shared.proof.lock(); + if slot + .as_ref() + .is_some_and(|old| old.serial == proof.serial && old.queried.elapsed() > PROOF_LIFETIME) + { + *serial = serial + .checked_add(1) + .expect("capsule focus serial exhausted"); + proof.serial = *serial; + } + let changed = slot.as_ref().is_none_or(|old| { + old.scope != proof.scope + || old.serial != proof.serial + || old.event != proof.event + || old.verified != proof.verified + || old.queried.elapsed() > PROOF_LIFETIME + }); + *slot = Some(proof); + if changed { + shared.publication.fetch_add(1, Ordering::AcqRel); + } + } +} +fn run(shared: &Shared, receiver: mpsc::Receiver, allow_uia: bool) { + let Some(platform) = Platform::new(shared.events.clone(), allow_uia) else { + log::warn!("[capsule] MTA focus owner initialization failed; input ownership unavailable"); + return; + }; + let (mut serial, mut captured) = (0, None); + while !shared.stopped.load(Ordering::Acquire) { + platform.poll(); + match receiver.try_recv() { + Ok(request) => { + if request.queued.elapsed() <= PROOF_LIFETIME + && shared.events.load(Ordering::Acquire) == request.event + && Native::current() == Some(request.origin) + { + { + let mut demand = shared.demand.lock(); + if demand.as_ref().is_some_and(|(wanted, _)| { + wanted.epoch > request.scope.epoch + || (wanted.epoch == request.scope.epoch + && wanted.session != request.scope.session) + }) { + continue; + } + *demand = Some((request.scope, Instant::now())); + } + capture(&platform, shared, request.scope, &mut serial, &mut captured); + let proof_current = shared.proof.lock().as_ref().is_some_and(|proof| { + proof.scope == request.scope + && proof.event == request.event + && proof.queried.elapsed() <= PROOF_LIFETIME + }); + if !shared.stopped.load(Ordering::Acquire) + && shared.events.load(Ordering::Acquire) == request.event + && Native::current() == Some(request.origin) + && proof_current + { + (request.job)(); + } + } + } + Err(mpsc::TryRecvError::Disconnected) => break, + Err(mpsc::TryRecvError::Empty) => {} + } + let demand = *shared.demand.lock(); + if let Some((scope, _)) = demand.filter(|(_, touched)| touched.elapsed() <= DEMAND_LIFETIME) + { + capture(&platform, shared, scope, &mut serial, &mut captured); + } else { + shared.clear(); + captured = None; + } + // Reconcile on the owner too: a transient invalid view must not stop + // the main-thread watch and leave stale geometry/UI without cleanup. + shared.notify(); + thread::park_timeout(TICK); + } +} From 8ad4db71d209cdd369753cc86ac9534080a8d3ee Mon Sep 17 00:00:00 2001 From: appergb <192432815+appergb@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:18:57 +0800 Subject: [PATCH 13/13] test(capsule): preserve MAINSTA identity in Windows runtime fixture --- .../tests/capsule_windows_focus.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs b/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs index 7fcd8b726..1ff3f401a 100644 --- a/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs +++ b/openless-all/app/src-tauri/backend-tests/tests/capsule_windows_focus.rs @@ -21,7 +21,7 @@ use windows::{ Foundation::HWND, System::Com::{ CoGetApartmentType, CoInitializeEx, CoUninitialize, APTTYPE, APTTYPEQUALIFIER, - APTTYPE_MTA, APTTYPE_STA, COINIT_APARTMENTTHREADED, + APTTYPE_MAINSTA, APTTYPE_MTA, APTTYPE_STA, COINIT_APARTMENTTHREADED, }, UI::{ Input::KeyboardAndMouse::{GetFocus, SetFocus}, @@ -69,6 +69,7 @@ fn apartment() -> APTTYPE { kind } struct Desktop { + apartment: APTTYPE, window: HWND, first: HWND, second: HWND, @@ -76,6 +77,13 @@ struct Desktop { impl Desktop { unsafe fn new() -> Self { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().unwrap(); + let initial_apartment = apartment(); + // COM distinguishes the process's main STA from other STAs. Both + // must stay exactly as initialized throughout the UI-side checks. + assert!( + initial_apartment == APTTYPE_STA || initial_apartment == APTTYPE_MAINSTA, + "UI test thread must initialize as STA or MAINSTA, got {initial_apartment:?}" + ); let window = CreateWindowExW( WINDOW_EX_STYLE::default(), w!("STATIC"), @@ -112,6 +120,7 @@ impl Desktop { let _ = SetForegroundWindow(window); let _ = SetFocus(first); Self { + apartment: initial_apartment, window, first, second, @@ -161,7 +170,7 @@ fn real_sta_getter_reserve_delivery_and_late_mta_completion_preserve_focus_owner "test requires the controlled foreground desktop" ); assert_eq!(unsafe { GetFocus() }, desktop.first); - assert_eq!(apartment(), APTTYPE_STA); + assert_eq!(apartment(), desktop.apartment); let owner = windows_focus::Owner::start().unwrap(); let scope = windows_focus::Scope { session: openless_core::SessionId::new(), @@ -222,7 +231,7 @@ fn real_sta_getter_reserve_delivery_and_late_mta_completion_preserve_focus_owner assert!(menu::is_owner(&key)); assert_eq!( apartment(), - APTTYPE_STA, + desktop.apartment, "STA must never be reinitialized to MTA" ); @@ -291,7 +300,7 @@ fn real_sta_getter_reserve_delivery_and_late_mta_completion_preserve_focus_owner assert!(menu::close("capsule", next.session, &next_owner.menu_id)); assert!(!menu::key(menu::Key::ArrowUp, true, false, false)); assert!(!menu::key(menu::Key::ArrowUp, false, false, false)); - assert_eq!(apartment(), APTTYPE_STA); + assert_eq!(apartment(), desktop.apartment); // A blocked/late owner must not grant an unlimited cached keyboard lease. let fresh = windows_focus::Scope { @@ -417,7 +426,7 @@ fn real_sta_getter_reserve_delivery_and_late_mta_completion_preserve_focus_owner } assert!(!menu::owner_current(&mouse)); assert!(!menu::key(menu::Key::Enter, false, false, false)); - assert_eq!(apartment(), APTTYPE_STA); + assert_eq!(apartment(), desktop.apartment); menu::invalidate(); menu::configure(Arc::new(|| None), Arc::new(|_| false)); }