diff --git a/README.md b/README.md index 4c1e9277a..313409726 100644 --- a/README.md +++ b/README.md @@ -493,12 +493,12 @@ This acknowledgement does not imply official endorsement or affiliation. ## Third-party components -The Overview yearly-activity card is a port of **Rare UI**'s [GitHub Activity](https://rareui.com/components/githubactivity) -component (Copyright (c) 2026 Swami Malode, MIT + Commons Clause, attribution required). -The port keeps the upstream layout, week/month maths, tooltip and expandable panel, and -replaces the GitHub data source with local dictation counts. Source: -`openless-all/app/src/components/ui/GitHubActivity.tsx` and `github-activity.css`. -The same credit is shown in Settings → About → Component credits. +The Overview annual activity card adapts calendar and expandable-panel code from **Rare UI**'s +[GitHub Activity](https://rareui.com/components/githubactivity) (Copyright (c) 2026 Swami Malode). +OpenLess supplies its own dictation data, app ranking, and desktop icons. See the +[component attribution and license](docs/ATTRIBUTION.md). The credit is also shown in Settings → About → Component credits. + +The shared password field adapts the animated eye from Rare UI's [Password Input](https://www.rareui.com/components/passwordinput). ## License diff --git a/README.zh.md b/README.zh.md index 3a1b8fe37..b8eae7989 100644 --- a/README.zh.md +++ b/README.zh.md @@ -493,11 +493,11 @@ OpenLess 同样认可并感谢 LinuxDo 社区开放、务实、对开发者友 ## 第三方组件 -概览页的年度活动热力图移植自 **Rare UI** 的 [GitHub Activity](https://rareui.com/components/githubactivity) -组件(Copyright (c) 2026 Swami Malode,MIT + Commons Clause,要求署名)。移植保留上游的布局、 -周/月换算、悬浮提示和可展开面板,只把 GitHub 数据源换成本地听写统计。源码位于 -`openless-all/app/src/components/ui/GitHubActivity.tsx` 与 `github-activity.css`。 -同一署名也出现在「设置 → 关于与更新 → 组件来源」。 +概览页的年度活动卡片改编了 **Rare UI** 的 [GitHub Activity](https://rareui.com/components/githubactivity) +日历和可展开面板代码(Copyright (c) 2026 Swami Malode)。听写数据、应用排名与桌面图标由 OpenLess 提供。 +详情见[组件署名与许可](docs/ATTRIBUTION.md);署名也可在「设置 → 关于与更新 → 组件来源」中查看。 + +共用密码输入框的眼睛动效改编自 Rare UI 的 [Password Input](https://www.rareui.com/components/passwordinput)。 ## 许可证 diff --git a/docs/ATTRIBUTION.md b/docs/ATTRIBUTION.md index d45898632..7e6d2d188 100644 --- a/docs/ATTRIBUTION.md +++ b/docs/ATTRIBUTION.md @@ -2,13 +2,26 @@ ## Rare UI GitHub Activity -The overview yearly activity card is a port of Rare UI's GitHub Activity component. +The Overview annual activity card adapts the calendar and expandable-panel code from Rare UI's GitHub Activity component. OpenLess uses local dictation activity and native desktop app icons instead of GitHub data. The card also supports a fitted calendar and an in-flow ranking panel. - Page: https://rareui.com/components/githubactivity -- Upstream: https://github.com/swamimalode07/rare-ui -- License: MIT License + Commons Clause +- Upstream source: [github-activity.tsx](https://github.com/swamimalode07/rare-ui/blob/main/components/ui/github-activity.tsx) - Copyright (c) 2026 Swami Malode +- License: [MIT + Commons Clause + Attribution](../openless-all/app/public/licenses/rare-ui-LICENSE.txt) -The port keeps the original geometry: 11px cells, 3px gap, 28px corner radius, 16px padding, week and month layout, the hover tooltip, and the expandable bottom panel. Local dictation counts replace GitHub contributions. The software with the most voice input (name and count) replaces repositories. Cells are not redrawn or resized to fit a narrow column. +The adapted component lives in `openless-all/app/src/ui/controls/GitHubActivity.tsx`, with styles in `openless-all/app/src/ui/styles/github-activity.css`. The in-app credit is Settings → About and updates → Component credits. -The in-app credit is Settings → About and updates → Component credits. The repository READMEs (`openless-all/README.md` and `openless-all/README.zh.md`) carry the same credit. +## Rare UI Password Input + +[Password Input](https://www.rareui.com/components/passwordinput) is the visual reference for OpenLess's shared input fields. `openless-all/app/src/ui/controls/PasswordEye.tsx` adapts the animated eye geometry from [password-input.tsx](https://github.com/swamimalode07/rare-ui/blob/main/components/ui/password-input.tsx) (Copyright (c) 2026 Swami Malode, [MIT + Commons Clause + Attribution](../openless-all/app/public/licenses/rare-ui-LICENSE.txt)). OpenLess uses native text rendering and masking, not the demo's per-character overlay or password strength meter. The credit appears in Settings → About and updates → Component credits. + +## Rare UI Toast + +The shared toast surface adapts Rare UI's [Toast](https://www.rareui.com/components/toast) panel, glyphs, and tile transitions from [toast.tsx](https://github.com/swamimalode07/rare-ui/blob/main/components/ui/toast.tsx) (Copyright (c) 2026 Swami Malode, [MIT + Commons Clause + Attribution](../openless-all/app/public/licenses/rare-ui-LICENSE.txt)). OpenLess uses its existing per-window notification controller and viewport instead of Sonner's global store. `useToast()` exposes non-modal variants and task updates; `confirm`, `warn`, and `openDialog` remain separate modal APIs. The credit appears in Settings → About and updates → Component credits. + +## Rare UI AI Prompt Box and Streaming Response + +[AI Prompt Box](https://www.rareui.com/components/promptbox) and +[Streaming Response](https://www.rareui.com/components/streamingresponse) are the +interaction references for OpenLess Ask Anything. The OpenLess implementation uses +its own native shortcut, voice, and streaming contracts rather than the demo's mock backend. diff --git a/openless-all/app/crates/openless-core/src/activity.rs b/openless-all/app/crates/openless-core/src/activity.rs index 3e9d3509c..b905a0e72 100644 --- a/openless-all/app/crates/openless-core/src/activity.rs +++ b/openless-all/app/crates/openless-core/src/activity.rs @@ -8,6 +8,12 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; const ACTIVITY_RETENTION_DAYS: usize = 731; +// Older Windows buckets contain arbitrary document titles with no recoverable app identity. +const ACTIVITY_APPS_FILE: &str = if cfg!(target_os = "windows") { + "activity-apps-v2.json" +} else { + "activity-apps.json" +}; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -109,7 +115,7 @@ impl ActivityStore { } pub fn at_path(path: PathBuf) -> Result { let days = read_days(&path)?; - let apps_path = path.with_file_name("activity-apps.json"); + let apps_path = path.with_file_name(ACTIVITY_APPS_FILE); let apps = match std::fs::read(&apps_path) { Ok(bytes) => serde_json::from_slice(&bytes).ok(), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(BTreeMap::new()), @@ -165,7 +171,7 @@ impl ActivityStore { if let Some(path) = &self.path { let bytes = serde_json::to_vec_pretty(&next) .map_err(|_| persistence_error("encode application activity"))?; - atomic_write(&path.with_file_name("activity-apps.json"), &bytes)?; + atomic_write(&path.with_file_name(ACTIVITY_APPS_FILE), &bytes)?; } *state = Some(next); Ok(()) diff --git a/openless-all/app/crates/openless-core/src/shared_types.rs b/openless-all/app/crates/openless-core/src/shared_types.rs index 4e2d34083..3ce8c2e55 100644 --- a/openless-all/app/crates/openless-core/src/shared_types.rs +++ b/openless-all/app/crates/openless-core/src/shared_types.rs @@ -187,13 +187,13 @@ pub struct FrontApp { /// `FrontApp { name, bundle_id }`. /// /// macOS composes `"Claude (com.anthropic.claudefordesktop)"`; Windows has -/// only window titles, no bundle id. History entries have separate +/// an executable name, not a bundle id. History entries have separate /// `app_name` / `app_bundle_id` fields, so splitting lets the detail page /// show a readable app name instead of gluing the whole bundle id into the /// body text. /// /// Only macOS labels are `"name (bundle.id)"`; on Windows parentheses are -/// part of the title. Callers must pass `is_macos` per platform (production +/// part of the label. Callers must pass `is_macos` per platform (production /// goes through `split_front_app_opt`). Non-macOS labels and labels whose /// bracket structure doesn't parse stay whole as the app name — better a /// verbose display than misreading ordinary parentheses in a window title @@ -231,7 +231,7 @@ pub fn split_front_app_label(label: &str, is_macos: bool) -> FrontApp { /// `Option` convenience wrapper for `split_front_app_label`; keeps the /// platform switch in one place: only macOS display strings are -/// `"name (bundle.id)"`; other platforms (Windows window titles, Linux) +/// `"name (bundle.id)"`; other platforms (Windows, Linux) /// keep the whole string as the name and leave the bundle id empty. pub fn split_front_app_opt(label: Option<&str>) -> FrontApp { label diff --git a/openless-all/app/crates/openless-core/src/usage_ledger.rs b/openless-all/app/crates/openless-core/src/usage_ledger.rs index 9aef15329..3d5d5da36 100644 --- a/openless-all/app/crates/openless-core/src/usage_ledger.rs +++ b/openless-all/app/crates/openless-core/src/usage_ledger.rs @@ -12,8 +12,8 @@ use std::sync::{ }; use uuid::Uuid; -const MAX_RECORDS: usize = 10_000; -const MAX_BYTES: u64 = 8 * 1024 * 1024; +mod retention; +use retention::{merge_retained_records, retention_key, EMPTY_DOCUMENT, MAX_BYTES, MAX_RECORDS}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -238,7 +238,7 @@ impl UsageRecord { } } -#[derive(Serialize, Deserialize)] +#[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct UsageDocument { version: u32, @@ -350,7 +350,7 @@ impl UsageRecorder { impl UsageLedger { /// Replacing an unreadable ledger requires an explicit user reset. pub fn reset(path: PathBuf) -> Result { - atomic_write(&path, br#"{"version":1,"records":[]}"#)?; + atomic_write(&path, EMPTY_DOCUMENT)?; Self::open(path) } @@ -359,10 +359,10 @@ impl UsageLedger { match std::fs::File::open(&path) { Ok(file) => { let mut bytes = Vec::new(); - file.take(MAX_BYTES + 1) + file.take(MAX_BYTES as u64 + 1) .read_to_end(&mut bytes) .map_err(|_| persistence_error("read service usage"))?; - if bytes.len() as u64 > MAX_BYTES { + if bytes.len() > MAX_BYTES { return Err(persistence_error("service usage too large")); } let document: UsageDocument = serde_json::from_slice(&bytes) @@ -379,6 +379,7 @@ impl UsageLedger { return Err(persistence_error("invalid service usage record")); } records = document.records; + records.sort_unstable_by_key(retention_key); } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return Err(persistence_error("read service usage")), @@ -399,9 +400,14 @@ impl UsageLedger { expected_generation: u64, record: UsageRecord, ) -> Result { - if !record.valid() { - return Err(persistence_error("invalid service usage record")); - } + self.merge_records(expected_generation, [record]) + } + + fn merge_records( + &self, + expected_generation: u64, + records: impl IntoIterator, + ) -> Result { let mut state = self .records .lock() @@ -409,23 +415,17 @@ impl UsageLedger { if self.generation.load(Ordering::Acquire) != expected_generation { return Ok(false); } - let mut next = state + let current = state .as_ref() - .ok_or_else(|| persistence_error("service usage needs reload"))? - .clone(); - if next.iter().any(|existing| existing.id == record.id) { + .ok_or_else(|| persistence_error("service usage needs reload"))?; + let Some(update) = merge_retained_records(current, records)? else { return Ok(false); - } - next.push(record); - next.sort_unstable_by_key(|record| record.occurred_at_ms); - if next.len() > MAX_RECORDS { - next.drain(..next.len() - MAX_RECORDS); - } - if let Err(error) = self.persist(&next) { + }; + if let Err(error) = atomic_write(&self.path, &update.encoded) { *state = None; return Err(error); } - *state = Some(next); + *state = Some(update.records); Ok(true) } @@ -446,22 +446,13 @@ impl UsageLedger { if state.is_none() { return Err(persistence_error("service usage needs reload")); } - if let Err(error) = self.persist(&[]) { + if let Err(error) = atomic_write(&self.path, EMPTY_DOCUMENT) { *state = None; return Err(error); } *state = Some(Vec::new()); Ok(()) } - - fn persist(&self, records: &[UsageRecord]) -> Result<(), BackendError> { - let bytes = serde_json::to_vec(&UsageDocument { - version: 1, - records: records.to_vec(), - }) - .map_err(|_| persistence_error("encode service usage"))?; - atomic_write(&self.path, &bytes) - } } #[cfg(test)] @@ -510,6 +501,125 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn usage_record_union_is_idempotent_across_reopen_and_reversed_merges() { + let dir = std::env::temp_dir().join(format!("openless-usage-{}", Uuid::new_v4())); + let a_path = dir.join("a.json"); + let b_path = dir.join("b.json"); + let a = UsageLedger::open(a_path.clone()).unwrap(); + let b = UsageLedger::open(b_path.clone()).unwrap(); + let usage = |input_tokens| UsageRecord { + input_tokens: Some(input_tokens), + ..record() + }; + let merge = |target: &UsageLedger, source: &UsageLedger| { + target + .merge_records(target.generation(), source.list().unwrap()) + .unwrap() + }; + let total = |ledger: &UsageLedger| { + ledger + .list() + .unwrap() + .into_iter() + .map(|event| event.input_tokens.unwrap()) + .sum::() + }; + assert!(a.append(a.generation(), usage(10)).unwrap()); + assert!(b.append(b.generation(), usage(7)).unwrap()); + assert!(merge(&a, &b)); + assert!(merge(&b, &a)); + assert_eq!((total(&a), total(&b)), (17, 17)); + let persisted = std::fs::read(&a_path).unwrap(); + drop(a); + let a = UsageLedger::open(a_path.clone()).unwrap(); + assert!(!merge(&a, &b)); + assert!(!merge(&b, &a)); + assert_eq!(std::fs::read(&a_path).unwrap(), persisted); + assert_eq!((total(&a), total(&b)), (17, 17)); + + assert!(a.append(a.generation(), usage(4)).unwrap()); + assert!(b.append(b.generation(), usage(2)).unwrap()); + assert!(merge(&b, &a)); + assert!(!merge(&b, &a)); + assert!(merge(&a, &b)); + assert!(!merge(&a, &b)); + assert_eq!((total(&a), total(&b)), (23, 23)); + assert_eq!( + std::fs::read(a_path).unwrap(), + std::fs::read(b_path).unwrap() + ); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn conflicting_usage_record_rejects_the_whole_batch() { + let dir = std::env::temp_dir().join(format!("openless-usage-{}", Uuid::new_v4())); + let path = dir.join("usage.json"); + let ledger = UsageLedger::open(path.clone()).unwrap(); + let original = record(); + assert!(ledger + .append(ledger.generation(), original.clone()) + .unwrap()); + let before = std::fs::read(&path).unwrap(); + let conflict = UsageRecord { + input_tokens: Some(1), + ..original.clone() + }; + assert!(ledger + .merge_records(ledger.generation(), [record(), conflict]) + .is_err()); + assert_eq!(ledger.list().unwrap(), vec![original]); + assert_eq!(std::fs::read(path).unwrap(), before); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn byte_retention_is_reopenable_deterministic_and_ignores_evicted_replays() { + let dir = std::env::temp_dir().join(format!("openless-usage-{}", Uuid::new_v4())); + let a_path = dir.join("a.json"); + let b_path = dir.join("b.json"); + let a = UsageLedger::open(a_path.clone()).unwrap(); + let b = UsageLedger::open(b_path.clone()).unwrap(); + let label = Some("x".repeat(160)); + let template = UsageRecord { + provider: label.clone(), + service: label.clone(), + protocol: label.clone(), + channel: label.clone(), + model: label, + ..record() + }; + let records: Vec<_> = (1..=MAX_RECORDS) + .map(|i| UsageRecord { + id: Uuid::from_u128(i as u128), + ..template.clone() + }) + .collect(); + assert!(a.merge_records(a.generation(), records.clone()).unwrap()); + assert!(b + .merge_records(b.generation(), records.into_iter().rev()) + .unwrap()); + let bytes = std::fs::read(&a_path).unwrap(); + assert!(bytes.len() <= MAX_BYTES); + assert_eq!(std::fs::read(b_path).unwrap(), bytes); + drop(a); + let a = UsageLedger::open(a_path).unwrap(); + let saved = a.list().unwrap(); + assert!(saved.len() < MAX_RECORDS); + assert_eq!( + saved.last().unwrap().id, + Uuid::from_u128(MAX_RECORDS as u128) + ); + let evicted = UsageRecord { + id: Uuid::from_u128(1), + ..template + }; + assert!(!a.append(a.generation(), evicted).unwrap()); + assert_eq!(a.list().unwrap(), saved); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn clear_invalidates_old_writers_and_unknown_files_are_preserved() { let dir = std::env::temp_dir().join(format!("openless-usage-{}", Uuid::new_v4())); diff --git a/openless-all/app/crates/openless-core/src/usage_ledger/retention.rs b/openless-all/app/crates/openless-core/src/usage_ledger/retention.rs new file mode 100644 index 000000000..c183161c1 --- /dev/null +++ b/openless-all/app/crates/openless-core/src/usage_ledger/retention.rs @@ -0,0 +1,93 @@ +//! Deterministic union and bounded serialization, without ledger I/O or generation changes. + +use std::collections::{hash_map::Entry, HashMap}; + +use super::UsageRecord; +use crate::errors::BackendError; +use crate::persistence::persistence_error; +use uuid::Uuid; + +pub(super) const MAX_RECORDS: usize = 10_000; +pub(super) const MAX_BYTES: usize = 8 * 1024 * 1024; +const DOCUMENT_PREFIX: &[u8] = br#"{"version":1,"records":["#; +const DOCUMENT_SUFFIX: &[u8] = b"]}"; +pub(super) const EMPTY_DOCUMENT: &[u8] = br#"{"version":1,"records":[]}"#; + +pub(super) struct RetainedUpdate { + pub(super) records: Vec, + pub(super) encoded: Vec, +} + +pub(super) fn merge_retained_records( + current: &[UsageRecord], + records: impl IntoIterator, +) -> Result, BackendError> { + let mut joined: HashMap = current + .iter() + .map(|record| (record.id, record.clone())) + .collect(); + let mut added = false; + for record in records { + if !record.valid() { + return Err(persistence_error("invalid service usage record")); + } + match joined.entry(record.id) { + Entry::Occupied(entry) => { + if entry.get() != &record { + return Err(persistence_error("conflicting service usage record")); + } + } + Entry::Vacant(entry) => { + entry.insert(record); + added = true; + } + } + } + if !added { + return Ok(None); + } + let mut next: Vec<_> = joined.into_values().collect(); + let bytes = encode_retained_records(&mut next)?; + if next.as_slice() == current { + return Ok(None); + } + Ok(Some(RetainedUpdate { + records: next, + encoded: bytes, + })) +} + +pub(super) fn retention_key(record: &UsageRecord) -> (i64, Uuid) { + (record.occurred_at_ms, record.id) +} + +fn encode_retained_records(records: &mut Vec) -> Result, BackendError> { + // A deterministic newest suffix also makes an evicted replay a no-op while + // its newer records remain. A time tie cannot depend on insertion order. + records.sort_unstable_by_key(retention_key); + records.drain(..records.len().saturating_sub(MAX_RECORDS)); + let mut bytes = DOCUMENT_PREFIX.to_vec(); + let mut starts = Vec::with_capacity(records.len()); + for (index, record) in records.iter().enumerate() { + if index != 0 { + bytes.push(b','); + } + starts.push(bytes.len()); + serde_json::to_writer(&mut bytes, record) + .map_err(|_| persistence_error("encode service usage"))?; + } + let keep_from = starts.partition_point(|start| { + DOCUMENT_PREFIX.len() + bytes.len() - start + DOCUMENT_SUFFIX.len() > MAX_BYTES + }); + if let Some(&start) = starts.get(keep_from) { + if keep_from > 0 { + bytes.copy_within(start.., DOCUMENT_PREFIX.len()); + bytes.truncate(DOCUMENT_PREFIX.len() + bytes.len() - start); + } + } else { + bytes.truncate(DOCUMENT_PREFIX.len()); + } + records.drain(..keep_from); + bytes.extend_from_slice(DOCUMENT_SUFFIX); + Ok(bytes) +} diff --git a/openless-all/app/e2e/ask-anything.spec.ts b/openless-all/app/e2e/ask-anything.spec.ts index d9bcd6d7f..bd6c57b72 100644 --- a/openless-all/app/e2e/ask-anything.spec.ts +++ b/openless-all/app/e2e/ask-anything.spec.ts @@ -74,7 +74,7 @@ test('Ask opens a conversation on record, streams activity, and keeps a composer }, info) => { await page.goto(fixture + '?qa'); await page.locator('.ol-default-capsule').waitFor(); - await expect(page.locator('input')).toHaveCount(0); + await expect(page.locator('.qa-prompt textarea')).toHaveCount(0); await emit(page, 'qa:state', { kind: 'recording', sessionId: 'ask-a', @@ -83,7 +83,7 @@ test('Ask opens a conversation on record, streams activity, and keeps a composer }); await expect(page.locator('.qa-answer-panel')).toBeVisible(); await expect(page.locator('.qa-recording-selection')).toContainText('selected source'); - await expect(page.locator('#native-host')).toHaveCSS('width', '720px'); + await expect(page.locator('#native-host')).toHaveCSS('width', '920px'); await emit(page, 'qa:state', { kind: 'thinking', sessionId: 'ask-a', messages: [] }); await emit(page, 'qa:state', { kind: 'activity', @@ -112,7 +112,7 @@ test('Ask opens a conversation on record, streams activity, and keeps a composer await expect(page.locator('.qa-assistant-message')).toContainText('最终回答'); await expect(page.locator('.qa-thought')).toContainText('已思考'); await expect(page.locator('.qa-follow-up')).toHaveCount(0); - await expect(page.locator('.qa-prompt input')).toBeVisible(); + await expect(page.locator('.qa-prompt textarea')).toBeVisible(); await expect(page.locator('.qa-prompt .qa-close')).toHaveCount(0); await page.screenshot({ path: info.outputPath('ask-result.png') }); }); @@ -148,7 +148,7 @@ test('Stop cancels the current turn and retains the open conversation for a foll await expect(page.locator('.qa-answer-panel')).toBeVisible(); await expect(page.locator('.qa-assistant-message')).toContainText('first answer'); await expect(page.getByText('draft answer')).toHaveCount(0); - await expect(page.locator('.qa-prompt input')).toBeEnabled(); + await expect(page.locator('.qa-prompt textarea')).toBeEnabled(); await expect(stop).toHaveCount(0); }); @@ -166,3 +166,171 @@ test('overview is restored and the Ask page remains without the added three-row await expect(page.locator('.ol-recording-key-guide')).toHaveCount(0); await expect(page.getByText('保存历史', { exact: true })).toBeVisible(); }); + +test('the macOS prompt box preserves the draft through the voice chord and allows multiline text', async ({ + page, +}) => { + await page.addInitScript(() => + Object.defineProperty(navigator, 'platform', { value: 'MacIntel' }), + ); + await page.goto(fixture + '?qa'); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + const firstTurn = [ + { role: 'user', content: 'First question' }, + { role: 'assistant', content: 'First answer' }, + ]; + await emit(page, 'qa:state', { kind: 'answer', sessionId: 'first', messages: firstTurn }); + const panel = page.locator('.qa-conversation'); + await expect(panel).toHaveCSS('border-radius', '26px'); + const close = panel.locator('.qa-close'); + await expect(close).toHaveCSS('border-radius', '50%'); + await expect(panel.locator('.qa-window-actions')).toHaveCSS('left', '10px'); + const draft = panel.locator('textarea'); + await draft.fill('typed'); + await draft.press('Space'); + await draft.press('Shift+Enter'); + await draft.press('a'); + const typed = 'typed \na'; + await expect(draft).toHaveValue(typed); + await expect.poll(async () => (await draft.boundingBox())?.height ?? 0).toBeGreaterThan(40); + + // WKWebView does not always expose Fn; the native hook consumes the chord first. + // When a browser reports it, the editor must also not insert a space. + const leakedChordPrevented = await draft.evaluate((editor) => { + const key = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true }); + Object.defineProperty(key, 'getModifierState', { value: (name: string) => name === 'Fn' }); + return !editor.dispatchEvent(key); + }); + expect(leakedChordPrevented).toBe(true); + await emit(page, 'qa:state', { kind: 'recording', sessionId: 'voice', messages: firstTurn }); + await expect(draft).toHaveAttribute('readonly', ''); + await expect(draft).toHaveAttribute('placeholder', '你正在进行语音输入'); + await expect(panel.locator('.voice-waveform-label')).toHaveText('你正在进行语音输入'); + await expect(draft).toHaveValue(typed); + await emit(page, 'qa:state', { kind: 'cancelled', sessionId: 'voice', messages: firstTurn }); + await expect(draft).toBeEditable(); + await expect(draft).toHaveValue(typed); + await draft.press('Enter'); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.qaActions.at(-1))) + .toMatchObject({ + command: 'qa_submit_text', + args: { text: typed, expectedSessionId: 'voice' }, + }); +}); + +test('the Windows conversation clips and scrolls streamed text, and opens live and final source links', async ({ + page, +}) => { + await page.addInitScript(() => { + localStorage.setItem('ol.locale', 'en'); + Object.defineProperty(navigator, 'platform', { value: 'Win32' }); + }); + await page.goto(fixture + '?qa'); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + await emit(page, 'qa:state', { kind: 'recording', sessionId: 'search', messages: [] }); + const panel = page.locator('.qa-conversation'); + const close = panel.locator('.qa-close'); + await expect(panel).toHaveAttribute('data-platform', 'win'); + await expect(panel.locator('.qa-window-actions')).toHaveCSS('right', '10px'); + await expect(close).toHaveCSS('border-radius', '50%'); + await expect(panel.locator('textarea')).toHaveAttribute( + 'placeholder', + 'You are using voice input', + ); + await expect(panel).toHaveCSS('overflow', 'hidden'); + await expect(panel).toHaveCSS('width', '920px'); + await expect(panel).toHaveCSS('height', '800px'); + const question = { role: 'user', content: 'What are the sources?' }; + await emit(page, 'qa:state', { kind: 'thinking', sessionId: 'search', messages: [question] }); + const response = panel.locator('.qa-assistant-message'); + await response.evaluate((element) => element.setAttribute('data-retained', 'yes')); + const firstChunk = 'Some streaming text.\n\n'.repeat(28); + const lastChunk = '\n\n[An inline source](https://example.org/a)'; + await emit(page, 'qa:state', { kind: 'answer_delta', sessionId: 'search', chunk: firstChunk }); + const viewport = panel.locator('[data-slot=message-scroller-viewport]'); + await expect + .poll(() => viewport.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)) + .toBeLessThan(2); + await expect(panel.locator('textarea')).toBeInViewport(); + await viewport.hover(); + await page.mouse.wheel(0, -420); + const jump = panel.getByRole('button', { name: 'Jump to latest' }); + await expect(jump).toBeVisible(); + await expect(jump).toHaveAttribute('data-active', 'true'); + await emit(page, 'qa:state', { kind: 'answer_delta', sessionId: 'search', chunk: lastChunk }); + await expect(response.getByRole('link', { name: 'An inline source' })).toBeAttached(); + expect( + await viewport.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop), + ).toBeGreaterThan(200); + await jump.click(); + await expect + .poll(() => viewport.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)) + .toBeLessThan(2); + await response.getByRole('link', { name: 'An inline source' }).click(); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.externalLinks)) + .toEqual(['https://example.org/a']); + await emit(page, 'qa:state', { + kind: 'answer', + sessionId: 'search', + messages: [ + question, + { + role: 'assistant', + content: `${firstChunk}${lastChunk}\n\n[1]() [2]()`, + }, + ], + }); + await expect(response).toHaveAttribute('data-retained', 'yes'); + const source = response.getByRole('link', { name: '2. example.com (example.com)' }); + await source.click(); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.externalLinks)) + .toEqual(['https://example.org/a', 'https://example.com/b']); +}); + +test('the welcome box docks on first send without remounting the editor', async ({ page }) => { + await page.goto(fixture + '?qa'); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + await emit(page, 'qa:state', { kind: 'thinking', sessionId: 'welcome', messages: [] }); + await expect(page.locator('.qa-thought')).toBeVisible(); + await emit(page, 'qa:state', { kind: 'answer', sessionId: 'welcome', messages: [] }); + const panel = page.locator('.qa-conversation'); + const prompt = panel.locator('.qa-prompt'); + const editor = prompt.locator('textarea'); + await expect(panel.locator('.qa-welcome-title')).toBeVisible(); + await expect(prompt).toHaveCSS('width', '560px'); + await expect(prompt).toHaveCSS('height', '102px'); + await expect + .poll(async () => { + const frame = (await panel.boundingBox())!; + const box = (await prompt.boundingBox())!; + return Math.abs(box.y + box.height / 2 - frame.y - frame.height / 2); + }) + .toBeLessThan(40); + await editor.fill(Array(10).fill('Long draft').join('\n')); + await expect(editor).toHaveCSS('height', '192px'); + await editor.fill('A first question'); + await editor.evaluate((el) => el.setAttribute('data-original-editor', 'yes')); + await editor.press('Enter'); + await expect.poll(() => page.evaluate(() => (window as any).fixture.qaActions.length)).toBe(1); + await emit(page, 'qa:state', { + kind: 'thinking', + sessionId: 'welcome', + messages: [{ role: 'user', content: 'A first question' }], + }); + await expect(panel.locator('.qa-welcome-title')).toHaveCount(0); + await expect(editor).toHaveAttribute('data-original-editor', 'yes'); + await expect(editor).toBeFocused(); + await expect(editor).toBeEditable(); + await editor.fill('Another draft'); + await expect(editor).toHaveValue('Another draft'); + await expect + .poll(async () => { + const frame = (await panel.boundingBox())!; + const box = (await prompt.boundingBox())!; + return Math.abs(frame.y + frame.height - box.y - box.height); + }) + .toBeLessThan(30); +}); diff --git a/openless-all/app/e2e/aux-window-geometry.spec.ts b/openless-all/app/e2e/aux-window-geometry.spec.ts index 11573df70..f98f11c77 100644 --- a/openless-all/app/e2e/aux-window-geometry.spec.ts +++ b/openless-all/app/e2e/aux-window-geometry.spec.ts @@ -9,6 +9,15 @@ test.use({ reducedMotion: 'reduce' }); test('QA waits for observed geometry and reopens without the closed transcript', async ({ page, }) => { + await page.addInitScript(() => { + // Some WebKit resizes update layout without reporting the new boundary. + const NativeResizeObserver = ResizeObserver; + window.ResizeObserver = class extends NativeResizeObserver { + observe(target: Element, options?: ResizeObserverOptions) { + if (!target.matches('.ol-app-viewport')) super.observe(target, options); + } + }; + }); await page.goto(fixture + '?qa'); await expect(page.locator('.ol-default-capsule')).toBeVisible(); const host = page.locator('#native-host'); @@ -27,12 +36,13 @@ test('QA waits for observed geometry and reopens without the closed transcript', await expect(host).toHaveCSS('height', '80px'); await expect(page.locator('.qa-answer-panel')).toBeHidden(); - await page.evaluate(() => (window as any).fixture.applyQaGeometry(true, 320, 220)); + await page.evaluate(() => (window as any).fixture.applyQaGeometry(true, 420, 179)); const answer = page.locator('.qa-answer-panel'); await expect(answer).toBeVisible(); await expect(answer.getByText('Old result', { exact: true })).toBeVisible(); - await expect(host).toHaveCSS('width', '320px'); - await expect(host).toHaveCSS('height', '220px'); + await expect(host).toHaveCSS('width', '420px'); + await expect(host).toHaveCSS('height', '179px'); + await expect(answer.locator('textarea')).toBeInViewport(); await page.evaluate(() => { const bridge = (window as any).fixture; @@ -47,6 +57,60 @@ test('QA waits for observed geometry and reopens without the closed transcript', await expect(page.locator('.ol-default-capsule')).toBeVisible(); }); +test('QA scales the frame and composer together on a large display', async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'no-preference' }); + await page.setViewportSize({ width: 1600, height: 1300 }); + await page.goto(fixture + '?qa'); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + await page.evaluate(() => { + const bridge = (window as any).fixture; + bridge.holdQaGeometry = true; + bridge.emit('qa:state', { kind: 'thinking', sessionId: 'large', messages: [] }); + }); + await expect.poll(() => page.evaluate(() => (window as any).fixture.sizes.at(-1))).toBe(true); + await page.evaluate(() => (window as any).fixture.applyQaGeometry(true, 1380, 1200)); + const panel = page.locator('.qa-conversation'); + await expect(panel.locator('.qa-thought')).toBeVisible(); + await page.evaluate(() => { + (window as any).fixture.emit('qa:state', { kind: 'answer', sessionId: 'large', messages: [] }); + }); + await expect(panel.locator('.qa-welcome-title')).toBeVisible(); + await expect(page.locator('.qa-capsule-shell')).toHaveCSS('opacity', '1'); + await expect(panel.locator('.qa-composer-position')).toHaveCSS('transform', 'none'); + const prompt = panel.locator('.qa-prompt'); + const frame = (await panel.boundingBox())!; + expect(frame.width).toBe(1380); + expect(frame.height).toBe(1200); + expect((await prompt.boundingBox())!.width).toBe(840); + await expect(panel.getByRole('button', { name: '关闭' })).toBeInViewport(); + + await prompt.locator('textarea').fill('Large display question'); + const positions = await prompt.evaluate(async (el) => { + const top = () => el.getBoundingClientRect().y; + const start = top(); + el.querySelector('textarea')!.dispatchEvent( + new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }), + ); + (window as any).fixture.emit('qa:state', { + kind: 'thinking', + sessionId: 'large', + messages: [{ role: 'user', content: 'Large display question' }], + }); + const frames: number[] = []; + const until = performance.now() + 320; + do { + await new Promise((done) => requestAnimationFrame(() => done())); + frames.push(top()); + } while (performance.now() < until); + return { start, frames }; + }); + // The spring must travel down from the welcome position, not jump upward at 1.5×. + expect(Math.min(...positions.frames)).toBeGreaterThan(positions.start - 16); + await expect + .poll(async () => (await prompt.boundingBox())!.y) + .toBeGreaterThan(positions.start + 180); +}); + test('QA keeps a reachable close action when the host rejects expansion', async ({ page }) => { await page.goto(fixture + '?qa'); await expect(page.locator('.ol-default-capsule')).toBeVisible(); diff --git a/openless-all/app/e2e/capsule-reference-motion.spec.ts b/openless-all/app/e2e/capsule-reference-motion.spec.ts index 20fabb604..ca88879de 100644 --- a/openless-all/app/e2e/capsule-reference-motion.spec.ts +++ b/openless-all/app/e2e/capsule-reference-motion.spec.ts @@ -147,14 +147,14 @@ test('QA opens the conversation while recording and starts fresh after close', a await expect(page.locator('.qa-answer-panel')).toBeVisible(); await expect(page.locator('.qa-prompt')).toBeVisible(); const host = page.locator('#native-host'); - await expect(host).toHaveCSS('width', '720px'); - await expect(host).toHaveCSS('height', '380px'); + await expect(host).toHaveCSS('width', '920px'); + await expect(host).toHaveCSS('height', '800px'); await emit(page, 'qa:state', { kind: 'thinking', sessionId: 'a', messages: [messages[0]] }); await expect(page.locator('.qa-thought')).toBeVisible(); await expect(page.locator('.ol-default-capsule')).toHaveCount(0); await emit(page, 'qa:state', { kind: 'answer', sessionId: 'a', messages }); await expect(page.locator('.qa-assistant-message')).toContainText('我会尽力为你解答'); - await expect(host).toHaveCSS('width', '720px'); + await expect(host).toHaveCSS('width', '920px'); await expect(page.locator('.qa-capsule-shell')).toHaveCSS('opacity', '1'); await page.screenshot({ path: info.outputPath('qa-result.png') }); await emit(page, 'chat-panel:closing', {}); @@ -174,7 +174,7 @@ test('QA opens the conversation while recording and starts fresh after close', a await expect(page.locator('.qa-capsule-shell')).not.toHaveClass(/is-closing/); await expect(page.locator('.qa-answer-panel')).toBeVisible(); await expect(page.locator('.qa-assistant-message')).toHaveCount(0); - await expect(host).toHaveCSS('height', '380px'); + await expect(host).toHaveCSS('height', '800px'); expect(errors).toEqual([]); }); diff --git a/openless-all/app/e2e/cloud-sync-dialogs.spec.ts b/openless-all/app/e2e/cloud-sync-dialogs.spec.ts index 00b0d8d68..501af3ea2 100644 --- a/openless-all/app/e2e/cloud-sync-dialogs.spec.ts +++ b/openless-all/app/e2e/cloud-sync-dialogs.spec.ts @@ -91,13 +91,26 @@ test('a new vault waits for matching NFC passwords and confirmed initialization' const confirmation = password.getByLabel('Confirm sync password', { exact: true }); await expect(newPassword).toHaveAttribute('type', 'password'); await expect(confirmation).toHaveAttribute('type', 'password'); + await newPassword.fill('Test credential 🔒'); await newPassword.focus(); + await newPassword.evaluate((input: HTMLInputElement) => input.setSelectionRange(1, 7)); + const getSelection = () => + newPassword.evaluate((input: HTMLInputElement) => [input.selectionStart, input.selectionEnd]); + const frame = newPassword.locator('..'); + const measure = () => + frame.evaluate((node: HTMLElement) => [node.offsetWidth, node.offsetHeight]); + const initialBounds = await measure(); + await expect(frame).not.toContainText('Test credential'); await password.getByRole('button', { name: 'Show password (Sync password)' }).click(); await expect(newPassword).toHaveAttribute('type', 'text'); await expect(newPassword).toBeFocused(); + expect(await getSelection()).toEqual([1, 7]); + expect(await measure()).toEqual(initialBounds); await expect(confirmation).toHaveAttribute('type', 'password'); await password.getByRole('button', { name: 'Hide password (Sync password)' }).click(); await expect(newPassword).toHaveAttribute('type', 'password'); + expect(await getSelection()).toEqual([1, 7]); + await expect(newPassword).toHaveValue('Test credential 🔒'); await newPassword.fill('Aa1short'); await confirmation.fill('Aa1short'); await expect(create).toBeDisabled(); @@ -145,10 +158,12 @@ test('cloud deletion focuses cancel and keeps a failed confirmation open', async await expect(dialog).toHaveCSS('transform', 'none'); const [cancelBox, removeBox] = await dialog .locator('.ol-dialog-footer button') - .evaluateAll((actions) => actions.map((action) => { - const { x, width } = action.getBoundingClientRect(); - return { x, width }; - })); + .evaluateAll((actions) => + actions.map((action) => { + const { x, width } = action.getBoundingClientRect(); + return { x, width }; + }), + ); expect(cancelBox.x).toBeLessThan(removeBox.x); expect(Math.abs(cancelBox.width - removeBox.width)).toBeLessThan(1); await expect(dialog.getByRole('checkbox')).toHaveCount(0); @@ -187,30 +202,37 @@ test('cloud deletion focuses cancel and keeps a failed confirmation open', async await expect(trigger).toBeDisabled(); }); - -test('a declined renewal can inspect and explicitly delete a cold-start backup', async ({ page }) => { +test('a declined renewal can inspect and explicitly delete a cold-start backup', async ({ + page, +}) => { await page.goto('/e2e/fixtures/cloud-sync-dialogs.html?mode=renew-cold'); const renewal = page.getByRole('dialog', { name: /disclosure has changed|updated disclosure/i }); await renewal.getByRole('button', { name: 'Not now' }).click(); expect(await attempts(page)).toEqual([]); await page.getByRole('button', { name: 'View or refresh cloud backup' }).click(); - await expect.poll(() => attempts(page)).toMatchObject([{ command: 'cloud_sync_e2ee_refresh_backup_metadata' }]); + await expect + .poll(() => attempts(page)) + .toMatchObject([{ command: 'cloud_sync_e2ee_refresh_backup_metadata' }]); await page.getByRole('button', { name: 'View or refresh cloud backup' }).click(); await expect.poll(() => attempts(page)).toHaveLength(2); await page.getByRole('button', { name: 'Delete cloud backup', exact: true }).click(); const confirmation = page.getByRole('dialog', { name: 'Delete the encrypted cloud backup?' }); expect(await attempts(page)).toHaveLength(2); await confirmation.getByRole('button', { name: 'Delete cloud backup', exact: true }).click(); - await expect.poll(() => attempts(page)).toMatchObject([ - { command: 'cloud_sync_e2ee_refresh_backup_metadata' }, - { command: 'cloud_sync_e2ee_refresh_backup_metadata' }, - { command: 'cloud_sync_e2ee_delete_remote', args: { expectedVaultId: 'old-vault', observedRevision: '7', confirmed: true } }, - ]); + await expect + .poll(() => attempts(page)) + .toMatchObject([ + { command: 'cloud_sync_e2ee_refresh_backup_metadata' }, + { command: 'cloud_sync_e2ee_refresh_backup_metadata' }, + { + command: 'cloud_sync_e2ee_delete_remote', + args: { expectedVaultId: 'old-vault', observedRevision: '7', confirmed: true }, + }, + ]); await finish(page); await expect(confirmation).toHaveCount(0); }); - test('a disabled old backup can be reviewed and deleted after restart', async ({ page }) => { await page.goto('/e2e/fixtures/cloud-sync-dialogs.html?mode=renew-cold'); const renewal = page.getByRole('dialog', { name: /disclosure has changed|updated disclosure/i }); @@ -219,21 +241,30 @@ test('a disabled old backup can be reviewed and deleted after restart', async ({ await toggle.click(); await page.getByRole('button', { name: 'Turn off sync', exact: true }).click(); await expect(toggle).not.toBeChecked(); - expect(await attempts(page)).toMatchObject([{ command: 'cloud_sync_e2ee_set_enabled', args: { enabled: false } }]); + expect(await attempts(page)).toMatchObject([ + { command: 'cloud_sync_e2ee_set_enabled', args: { enabled: false } }, + ]); await page.reload(); await expect(toggle).not.toBeChecked(); expect(await attempts(page)).toEqual([]); await page.getByRole('button', { name: 'View or refresh cloud backup' }).click(); - await expect.poll(() => attempts(page)).toMatchObject([{ command: 'cloud_sync_e2ee_refresh_backup_metadata' }]); + await expect + .poll(() => attempts(page)) + .toMatchObject([{ command: 'cloud_sync_e2ee_refresh_backup_metadata' }]); await expect(toggle).not.toBeChecked(); await page.getByRole('button', { name: 'Delete cloud backup', exact: true }).click(); const confirmation = page.getByRole('dialog', { name: 'Delete the encrypted cloud backup?' }); expect(await attempts(page)).toHaveLength(1); await confirmation.getByRole('button', { name: 'Delete cloud backup', exact: true }).click(); - await expect.poll(() => attempts(page)).toMatchObject([ - { command: 'cloud_sync_e2ee_refresh_backup_metadata' }, - { command: 'cloud_sync_e2ee_delete_remote', args: { expectedVaultId: 'old-vault', observedRevision: '7', confirmed: true } }, - ]); + await expect + .poll(() => attempts(page)) + .toMatchObject([ + { command: 'cloud_sync_e2ee_refresh_backup_metadata' }, + { + command: 'cloud_sync_e2ee_delete_remote', + args: { expectedVaultId: 'old-vault', observedRevision: '7', confirmed: true }, + }, + ]); await finish(page); await expect(confirmation).toHaveCount(0); await expect(toggle).not.toBeChecked(); diff --git a/openless-all/app/e2e/design-feedback.spec.ts b/openless-all/app/e2e/design-feedback.spec.ts index a83d5207e..3911701f7 100644 --- a/openless-all/app/e2e/design-feedback.spec.ts +++ b/openless-all/app/e2e/design-feedback.spec.ts @@ -57,7 +57,7 @@ test('sidebar items highlight on hover without a transition, and the brand retur await expect(page.getByRole('heading', { name: '今日概览', exact: true })).toBeVisible(); }); -test('channel deletion uses a blocking centered confirmation and a red trash toast', async ({ +test('channel deletion uses a blocking centered confirmation and a success toast', async ({ page, }) => { await openAiSettings(page); @@ -108,12 +108,7 @@ test('channel deletion uses a blocking centered confirmation and a red trash toa await expect(page.locator('.ol-channel-dialog')).toHaveCount(0); const toast = page.locator('.ol-notification-card').filter({ hasText: '已删除' }); await expect(toast).toBeVisible(); - const icon = toast.locator('.ol-notification-icon--deleted'); - await expect(icon).toBeVisible(); - const iconColor = await icon.evaluate((node) => getComputedStyle(node).backgroundColor); - const [red, green] = iconColor.match(/\d+/g)!.map(Number); - expect(red).toBeGreaterThan(200); - expect(green).toBeLessThan(160); + await expect(toast.locator('[data-slot="toast-icon"]')).toHaveAttribute('data-tone', 'success'); }); test('noise reduction uses one slider track', async ({ page }) => { @@ -228,12 +223,7 @@ test('style pack deletion asks once, keeps the pack on cancel, and reports a com await expect(dialog).toHaveCount(0); await expect(pack).toHaveCount(0); await expect(toast).toContainText('创作者口播'); - const icon = toast.locator('.ol-notification-icon--deleted'); - await expect(icon).toBeVisible(); - const iconColor = await icon.evaluate((node) => getComputedStyle(node).backgroundColor); - const [red, green] = iconColor.match(/\d+/g)!.map(Number); - expect(red).toBeGreaterThan(200); - expect(green).toBeLessThan(160); + await expect(toast.locator('[data-slot="toast-icon"]')).toHaveAttribute('data-tone', 'success'); await expect(toast.getByRole('button', { name: '撤销', exact: true })).toHaveCount(0); }); @@ -300,7 +290,7 @@ test('selected segmented options and the overview heatmap stay visible', async ( })); expect(overviewStyle.background).not.toBe('rgba(0, 0, 0, 0)'); expect(overviewStyle.color).not.toBe(overviewStyle.background); - // The yearly card is the ported GitHub Activity component: its heading is the yearly + // The yearly card adapts the GitHub Activity component: its heading is the yearly // count line and its grid is made of real day cells. const dashboard = page.locator('.ol-overview-dashboard'); await expect @@ -310,7 +300,7 @@ test('selected segmented options and the overview heatmap stay visible', async ( await expect(activityCard).toBeVisible(); await expect(activityCard.locator('.ol-gha-heading')).toContainText('次听写'); expect(await activityCard.locator('.ol-gha-cell').count()).toBeGreaterThan(300); - await expect(activityCard.locator('.ol-gha-app-chips')).toBeVisible(); + await expect(activityCard.locator('.ol-gha-app-preview')).toBeVisible(); const cellSize = await activityCard .locator('.ol-gha-cell') .first() diff --git a/openless-all/app/e2e/desktop-onboarding.spec.ts b/openless-all/app/e2e/desktop-onboarding.spec.ts index 48650561e..5503fdede 100644 --- a/openless-all/app/e2e/desktop-onboarding.spec.ts +++ b/openless-all/app/e2e/desktop-onboarding.spec.ts @@ -223,13 +223,18 @@ test('the main action stays in place while the current step moves to the center' expect(Math.abs((await button.boundingBox())!.y - before.y)).toBeLessThan(1); }); -test('text reveals progressively without shifting layout and input focus uses an underline', async ({ +test('text reveals progressively without shifting layout while the name field uses a single focus surface', async ({ page, }) => { await page.goto('/?onboarding=1&os=mac'); const input = page.getByRole('textbox', { name: '怎么称呼你?(选填)' }); await input.click(); await expect(input).toHaveCSS('outline-style', 'none'); + await expect(input).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)'); + const frame = input.locator('..'); + await expect(frame).toHaveClass(/\bol-field\b/); + await expect(frame).toHaveCSS('padding-inline-start', '11px'); + await expect(frame).not.toHaveCSS('border-top-color', 'rgba(0, 0, 0, 0)'); const before = (await input.boundingBox())!; const reveal = await page.locator('.ol-reveal-glyph').evaluateAll((elements) => elements @@ -253,6 +258,29 @@ test('text reveals progressively without shifting layout and input focus uses an expect(Math.abs(before.y - after.y)).toBeLessThan(1); }); +test('onboarding uses the shared searchable language popup above the footer', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 700 }); + await page.goto('/?onboarding=1&os=mac'); + const footer = page.locator('.ol-guide-footer'); + const trigger = footer.locator('.ol-select-trigger'); + await expect(footer.getByText('Language:', { exact: true })).toBeVisible(); + await expect(trigger).toHaveAccessibleName('Language'); + await expect(trigger).toContainText('简体中文'); + await trigger.click(); + const popup = page.locator('.ol-select-positioner[data-side="top"] .ol-select-popup'); + const search = popup.getByPlaceholder('搜索语言…'); + await expect(popup).toBeInViewport({ ratio: 1 }); + await expect(search).toBeFocused(); + await expect(search).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)'); + await search.fill('English'); + await expect(popup.getByRole('option')).toHaveCount(1); + await popup.getByRole('option', { name: 'English' }).click(); + await expect(page.getByRole('heading', { name: 'Hi, this is OpenLess' })).toBeVisible(); + await expect(trigger).toContainText('English'); + await page.reload(); + await expect(trigger).toContainText('English'); +}); + test('model setup stays in its own dialog and returns to the unchanged centered step', async ({ page, }) => { diff --git a/openless-all/app/e2e/fixtures/capsule-motion.tsx b/openless-all/app/e2e/fixtures/capsule-motion.tsx index 534348717..c3025b7f4 100644 --- a/openless-all/app/e2e/fixtures/capsule-motion.tsx +++ b/openless-all/app/e2e/fixtures/capsule-motion.tsx @@ -45,6 +45,7 @@ const bridge = { regionWrites: [] as any[], dictationActions: [] as string[], qaActions: [] as { command: string; args: unknown }[], + externalLinks: [] as string[], pipelineMode: params.get('pipelineMode') === 'deepseek' ? 'deepseek' : 'traditional', hasListener: (event: string) => Boolean(listeners.get(event)?.size), setCapsule: (_: Record) => {}, @@ -65,9 +66,9 @@ const bridge = { const host = document.querySelector('#native-host'); if (!host) return; // Match the native window's nominal dimensions; tests can deliver a work-area clamp. - host.style.width = `${width ?? (expanded ? 720 : 480)}px`; - host.style.height = `${height ?? (expanded ? 380 : 80)}px`; - host.style.bottom = expanded ? '48px' : '8px'; + host.style.width = `${width ?? (expanded ? 920 : 480)}px`; + host.style.height = `${height ?? (expanded ? 800 : 80)}px`; + host.style.bottom = expanded ? '16px' : '8px'; }, target: { sessionId: 'recording-a', @@ -96,6 +97,10 @@ window.__TAURI_INTERNALS__ = { callbacks.delete(id); }, async invoke(command: string, args: any) { + if (command === 'plugin:shell|open') { + bridge.externalLinks.push(args.path); + return; + } if (['qa_cancel_turn', 'qa_stop_recording', 'qa_submit_text'].includes(command)) { bridge.qaActions.push({ command, args }); } diff --git a/openless-all/app/e2e/fixtures/native-overview.tsx b/openless-all/app/e2e/fixtures/native-overview.tsx index 7c38515d0..a9c61069f 100644 --- a/openless-all/app/e2e/fixtures/native-overview.tsx +++ b/openless-all/app/e2e/fixtures/native-overview.tsx @@ -17,6 +17,9 @@ const state = params.get('state'); const profile = getPreviewProfile('mac'); const year = new Date().getFullYear(); const day = `${year}-01-01`; +const icons = params.get('icons'); +const appIcon = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a2Z0AAAAASUVORK5CYII='; let count = 2; let reads = 0; let deferred: (() => void) | undefined; @@ -61,6 +64,16 @@ mockIPC( }); return value; } + case 'get_activity_app_icons': { + if ((args as { year: number }).year !== year) throw new Error('Expected current year'); + return icons !== null + ? { + Editor: appIcon, + Terminal: appIcon, + ...(icons === 'broken' && { Browser: 'data:image/png;base64,AAAA' }), + } + : {}; + } case 'get_activity_apps': { if ((args as { year: number }).year !== year) throw new Error('Expected current year'); if (dashboard) { @@ -70,6 +83,7 @@ mockIPC( } reads++; const rows = [ + ...(icons !== null ? [['Terminal', 1]] : []), ['Browser', 1], ['Editor', count], ]; diff --git a/openless-all/app/e2e/history-store.spec.ts b/openless-all/app/e2e/history-store.spec.ts index bef9864fc..611998d8d 100644 --- a/openless-all/app/e2e/history-store.spec.ts +++ b/openless-all/app/e2e/history-store.spec.ts @@ -14,7 +14,7 @@ test('history writes update every page while recordings, activity and the usage await page.goto('/?os=win'); await expect(page.locator('html')).toHaveAttribute('data-ol-platform', 'win'); const initialHeading = await page.locator('.ol-gha-heading').textContent(); - const initialApps = await page.locator('.ol-gha-app-chips').textContent(); + const initialApps = await page.locator('.ol-gha-app-preview').textContent(); expect(initialHeading).toBeTruthy(); expect(initialApps).toBeTruthy(); await navigate(page, 'history', '历史'); @@ -49,7 +49,7 @@ test('history writes update every page while recordings, activity and the usage await expect(page.locator(`[data-overview-record="${deletedId}"]`)).toHaveCount(0); await expect(page.locator('[data-overview-record]')).toHaveCount(8); await expect(page.locator('.ol-gha-heading')).toHaveText(initialHeading!); - await expect(page.locator('.ol-gha-app-chips')).toHaveText(initialApps!); + await expect(page.locator('.ol-gha-app-preview')).toHaveText(initialApps!); await navigate(page, 'history', '历史'); await page.getByRole('button', { name: '清空', exact: true }).click(); @@ -69,7 +69,7 @@ test('history writes update every page while recordings, activity and the usage await navigate(page, 'overview', '概览'); await expect(page.locator('[data-overview-record]')).toHaveCount(1); await expect(page.locator('.ol-gha-heading')).toHaveText(initialHeading!); - await expect(page.locator('.ol-gha-app-chips')).toHaveText(initialApps!); + await expect(page.locator('.ol-gha-app-preview')).toHaveText(initialApps!); await navigate(page, 'usage', '用量'); await page diff --git a/openless-all/app/e2e/interaction-polish.spec.ts b/openless-all/app/e2e/interaction-polish.spec.ts index f36bc7cd4..4395a9f96 100644 --- a/openless-all/app/e2e/interaction-polish.spec.ts +++ b/openless-all/app/e2e/interaction-polish.spec.ts @@ -65,7 +65,14 @@ test('message follow yields to the reader and resumes at the bottom', async ({ p }); await expect.poll(distance).toBeLessThanOrEqual(1); const held = await viewport.evaluate((node) => { - node.dispatchEvent(new Event('touchmove')); + for (const [type, clientY] of [ + ['touchstart', 20], + ['touchmove', 50], + ] as const) { + const event = new Event(type); + Object.defineProperty(event, 'touches', { value: [{ clientY }] }); + node.dispatchEvent(event); + } node.scrollTop -= 30; node.dispatchEvent(new Event('scroll')); const value = node.scrollTop; @@ -97,7 +104,7 @@ test('QA jump control appears only more than 120 pixels from the latest message' fixture.emit('qa:state', { kind: 'answer', sessionId: 'follow-test', - messages: Array.from({ length: 12 }, (_, index) => ({ + messages: Array.from({ length: 18 }, (_, index) => ({ role: index % 2 ? 'assistant' : 'user', content: `Message ${index}: ${'content '.repeat(30)}`, })), @@ -116,7 +123,7 @@ test('QA jump control appears only more than 120 pixels from the latest message' }); await expect(jump).toHaveAttribute('data-active', 'false'); await viewport.evaluate((node) => { - node.dispatchEvent(new Event('touchmove')); + node.dispatchEvent(new WheelEvent('wheel', { deltaY: -80 })); node.scrollTop = node.scrollHeight - node.clientHeight - 80; node.dispatchEvent(new Event('scroll')); }); @@ -148,7 +155,7 @@ for (const platform of ['mac', 'win'] as const) { fixture.emit('qa:state', { kind: 'answer', sessionId: 'chrome', - messages: Array.from({ length: 12 }, (_, index) => ({ + messages: Array.from({ length: 18 }, (_, index) => ({ role: index % 2 ? 'assistant' : 'user', content: `Message ${index}: ${'content '.repeat(30)}`, })), @@ -158,7 +165,12 @@ for (const platform of ['mac', 'win'] as const) { const header = panel.locator('.qa-answer-header'); await expect(panel).toHaveAttribute('data-platform', platform); await expect(header.locator('h1')).toContainText('Message 0:'); - await expect(header).toHaveCSS('background-color', 'rgb(255, 255, 255)'); + await expect(header).toHaveCSS( + 'background-color', + await panel.evaluate((el) => getComputedStyle(el).backgroundColor), + ); + await expect(panel).toHaveCSS('border-radius', '26px'); + await expect(panel).toHaveCSS('overflow', 'hidden'); await expect(header.locator('.qa-symbol')).toHaveCount(0); const headerBox = (await header.boundingBox())!; const closeBox = (await header.locator('.qa-close').boundingBox())!; @@ -176,8 +188,6 @@ for (const platform of ['mac', 'win'] as const) { el.scrollTop = 0; }); expect(await viewport.evaluate((el) => el.scrollTop)).toBe(0); - expect(await header.evaluate((el) => getComputedStyle(el, '::after').backdropFilter)).toContain( - 'blur', - ); + await expect(panel.locator('.qa-prompt textarea')).toBeInViewport(); }); } diff --git a/openless-all/app/e2e/native-overview.spec.ts b/openless-all/app/e2e/native-overview.spec.ts index 846057da3..7a11e0839 100644 --- a/openless-all/app/e2e/native-overview.spec.ts +++ b/openless-all/app/e2e/native-overview.spec.ts @@ -16,9 +16,9 @@ test('native overview paints cached activity and discards an app list invalidate await page.goto(`${fixtureOrigin}/e2e/fixtures/native-overview.html`); const heading = page.locator('.ol-gha-heading'); await expect(heading).toContainText('30 dictations'); - const chips = page.locator('.ol-gha-app-chips'); - await expect(chips).toContainText('Editor'); - expect(await chips.locator(':scope > *').first().textContent()).toContain('Editor'); + const preview = page.locator('.ol-gha-app-preview'); + await expect(preview).toContainText('Editor'); + expect(await preview.locator(':scope > *').first().textContent()).toContain('Editor'); await page.getByRole('button', { name: 'Complete initial activity read' }).click(); await expect(heading).toContainText('2 dictations'); @@ -34,13 +34,59 @@ test('native overview paints cached activity and discards an app list invalidate await expect(heading).toContainText('43 dictations'); await appReads.click(); await expect(appReads).toHaveText('2'); - await expect(chips).toContainText('Editor2'); + await page.locator('.ol-gha-toggle').click(); + const editor = page.locator('.ol-gha-app-row').filter({ hasText: 'Editor' }); + await expect(editor.locator('.ol-gha-app-count')).toHaveText('2'); await page.getByRole('button', { name: 'Complete old app read' }).click(); - await expect(chips).toContainText('43'); + await expect(editor.locator('.ol-gha-app-count')).toHaveText('43'); await appReads.click(); await expect(appReads).toHaveText('3'); }); +for (const [platform, icons] of [ + ['MacIntel', 'missing'], + ['Win32', 'broken'], +] as const) { + test(`ranked app avatars hide names until expanded and label ${icons} images on ${platform}`, async ({ + page, + }) => { + await page.addInitScript((value) => { + Object.defineProperty(navigator, 'platform', { configurable: true, get: () => value }); + }, platform); + await page.goto(`${fixtureOrigin}/e2e/fixtures/native-overview.html?icons=${icons}`); + await page.getByRole('button', { name: 'Complete initial activity read' }).click(); + const preview = page.locator('.ol-gha-app-preview'); + const editor = preview.getByRole('img', { name: 'Editor' }); + const terminal = preview.getByRole('img', { name: 'Terminal' }); + for (const icon of [editor, terminal]) { + await expect(icon).toBeVisible(); + await expect + .poll(() => icon.evaluate((image: HTMLImageElement) => image.naturalWidth)) + .toBe(1); + } + await expect(preview).toHaveText('Browser'); + await expect(preview.getByRole('img')).toHaveCount(2); + expect((await terminal.boundingBox())!.x).toBeLessThan( + (await editor.boundingBox())!.x + (await editor.boundingBox())!.width, + ); + + const toggle = page.locator('.ol-gha-toggle'); + await toggle.click(); + await expect(toggle).toHaveAttribute('aria-expanded', 'true'); + await expect(preview).toHaveCount(0); + const rows = page.locator('.ol-gha-app-row'); + await expect(rows.locator('.ol-gha-app-name')).toHaveText(['Editor', 'Terminal', 'Browser']); + await expect(rows.locator('.ol-gha-app-count')).toHaveText(['2', '1', '1']); + await expect(rows.first().locator('img')).toBeVisible(); + await expect(rows.last().locator('svg')).toBeVisible(); + + await toggle.click(); + await expect(toggle).toHaveAttribute('aria-expanded', 'false'); + await expect(preview.getByRole('img', { name: 'Editor' })).toBeVisible(); + await expect(preview).toHaveText('Browser'); + }); +} + async function expectDashboardFits(page: Page) { const dashboard = page.locator('.ol-overview-dashboard'); await expect(dashboard).toBeVisible(); diff --git a/openless-all/app/e2e/notifications.spec.ts b/openless-all/app/e2e/notifications.spec.ts index 72a715f94..041589097 100644 --- a/openless-all/app/e2e/notifications.spec.ts +++ b/openless-all/app/e2e/notifications.spec.ts @@ -60,43 +60,22 @@ test('transient confirmations drop from the window top and replace each other', await expect(cards).toHaveCount(1); await expect(cards.first()).toContainText('DeepSeek 配置已保存'); const message = cards.locator('.ol-notification-message'); - expect(await message.evaluate((node) => node.clientHeight)).toBe(18); + expect(await message.evaluate((node) => node.clientHeight)).toBe(20); const box = (await cards.first().boundingBox())!; - // The host is flush with the window edge; the card itself keeps only the safe-area inset. const bounds = (await page.locator('.ol-app-viewport').boundingBox())!; expect(box.y - bounds.y).toBeLessThan(12); - - // Success uses the standard theme blue and the same raised surface as content cards. - const savedIcon = page.locator('.ol-notification-icon--saved'); - const savedBg = await savedIcon.evaluate((node) => getComputedStyle(node).backgroundColor); - const themeBlue = await page.evaluate(() => { - const probe = document.createElement('div'); - probe.style.background = 'var(--ol-accent-solid-bg)'; - document.body.appendChild(probe); - const value = getComputedStyle(probe).backgroundColor; - probe.remove(); - return value; - }); - expect(savedBg).toBe(themeBlue); - const cardBackground = await cards - .first() - .evaluate((node) => getComputedStyle(node).backgroundColor); - const contentCardBackground = await page - .locator('.ol-overview-dashboard .ol-card') - .first() - .evaluate((node) => getComputedStyle(node).backgroundColor); - expect(cardBackground).toBe(contentCardBackground); + expect( + await cards.first().evaluate((node: HTMLElement) => [node.offsetWidth, node.offsetHeight]), + ).toEqual([356, 56]); + const savedIcon = cards.locator('[data-slot="toast-icon"]'); + await expect(savedIcon).toHaveAttribute('data-tone', 'success'); + expect(await savedIcon.evaluate((node: HTMLElement) => node.offsetWidth)).toBe(36); await emitNotifications(page, [{ state: 'deleted', message: '已删除', durationMs: 10000 }]); await expect(cards).toHaveCount(1); await expect(message).toHaveText('已删除'); - expect(await message.evaluate((node) => node.clientHeight)).toBe(18); - const deletedIcon = page.locator('.ol-notification-icon--deleted'); - await expect(deletedIcon).toBeVisible(); - const deletedColor = await deletedIcon.evaluate((node) => getComputedStyle(node).backgroundColor); - const [deletedRed, deletedGreen] = deletedColor.match(/\d+/g)!.map(Number); - expect(deletedRed).toBeGreaterThan(200); - expect(deletedGreen).toBeLessThan(160); + expect(await message.evaluate((node) => node.clientHeight)).toBe(20); + await expect(savedIcon).toHaveAttribute('data-tone', 'success'); }); test('save bridge and independent in-flight saves keep their own lifecycle', async ({ page }) => { diff --git a/openless-all/app/e2e/refinements.spec.ts b/openless-all/app/e2e/refinements.spec.ts index 13e17021f..fd16182c6 100644 --- a/openless-all/app/e2e/refinements.spec.ts +++ b/openless-all/app/e2e/refinements.spec.ts @@ -31,8 +31,10 @@ test('shortcut search remains visible without focus', async ({ page }) => { const search = page.getByRole('searchbox', { name: '搜索命令或按键' }); await expect(search).toHaveCSS('clip-path', 'none'); await expect(search).toHaveCSS('appearance', 'none'); - await expect(search).toHaveCSS('border-radius', '16px'); - const colors = await search.evaluate((element) => ({ + await expect(search).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)'); + const frame = search.locator('..'); + await expect(frame).toHaveCSS('border-radius', '12px'); + const colors = await frame.evaluate((element) => ({ search: getComputedStyle(element).backgroundColor, page: getComputedStyle(element.closest('.ol-settings-content') ?? document.body) .backgroundColor, diff --git a/openless-all/app/e2e/settings-appearance-layout.spec.ts b/openless-all/app/e2e/settings-appearance-layout.spec.ts index 615d2ee79..4c525ed35 100644 --- a/openless-all/app/e2e/settings-appearance-layout.spec.ts +++ b/openless-all/app/e2e/settings-appearance-layout.spec.ts @@ -74,8 +74,10 @@ for (const profile of [ const geometry = await selects.evaluateAll((elements) => elements.map((element) => { const control = element.getBoundingClientRect(); - const label = element.closest('.ol-setting-row')! - .querySelector('.ol-setting-row-label')!.getBoundingClientRect(); + const label = element + .closest('.ol-setting-row')! + .querySelector('.ol-setting-row-label')! + .getBoundingClientRect(); return { x: control.x, width: control.width, @@ -91,3 +93,28 @@ for (const profile of [ } }); } + +test('the settings language popup paints one search field and filters languages', async ({ + page, +}) => { + await page.goto('/?os=mac'); + await page.getByRole('button', { name: '设置', exact: true }).click(); + const dialog = page.getByRole('dialog', { name: '设置', exact: true }); + await dialog.getByRole('button', { name: '外观与语言', exact: true }).click(); + await settleNavigation(dialog); + const language = dialog.locator('.ol-select-trigger[aria-label="语言"]'); + await language.click(); + const popup = page.locator('.ol-select-positioner[data-open] .ol-select-popup'); + const search = popup.getByPlaceholder('搜索语言…'); + await expect(search).toBeFocused(); + await expect(search.locator('..')).toHaveClass(/\bol-field\b/); + await expect(search).toHaveCSS('box-shadow', 'none'); + await expect(search).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)'); + await expect(search).toHaveCSS('border-top-width', '0px'); + await search.fill('Deutsch'); + await expect(popup.getByRole('option')).toHaveCount(1); + await expect(popup.getByRole('option', { name: 'Deutsch' })).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(popup).toHaveCount(0); + await expect(dialog).toBeVisible(); +}); diff --git a/openless-all/app/e2e/settings-feedback.spec.ts b/openless-all/app/e2e/settings-feedback.spec.ts index 57e3695fe..d2aea21c4 100644 --- a/openless-all/app/e2e/settings-feedback.spec.ts +++ b/openless-all/app/e2e/settings-feedback.spec.ts @@ -287,7 +287,15 @@ for (const scale of ['small', 'medium', 'large'] as const) { await expect(notice).toHaveAttribute('data-state', 'saved'); await expect(notice).toHaveAttribute('data-same-operation', 'save'); await expect(notice).toContainText('DeepSeek 配置已保存'); - await expect(notice).toHaveCSS('border-radius', '8px'); + const surface = notice.locator('.ol-toast-panel'); + await expect(surface).toHaveCSS('clip-path', /^path\(/); + expect( + await surface.evaluate((node: HTMLElement) => [ + node.offsetWidth, + node.offsetHeight, + node.style.borderRadius, + ]), + ).toEqual([356, 56, '21px']); await expect(save).toBeEnabled(); expect( await page.evaluate(() => JSON.parse(window.settingsStatusFixture.stored()).apiKey), @@ -295,8 +303,7 @@ for (const scale of ['small', 'medium', 'large'] as const) { await expect(notice).toHaveCSS('transform', 'none'); const box = (await notice.boundingBox())!; const viewport = (await page.locator('.ol-app-viewport').boundingBox())!; - // Font fallback can wrap the label onto two lines in WebKit. Apply the compact - // height budget in rendered pixels at each interface scale. + // Confirm that the scaled card stays within the viewport as well as its CSS box. expect(box.height).toBeLessThanOrEqual(60 * FONT_SCALE_VALUES[scale]); expect(box.x).toBeGreaterThanOrEqual(viewport.x); expect(box.x + box.width).toBeLessThanOrEqual(viewport.x + viewport.width); @@ -318,10 +325,13 @@ test('Sync Now keeps one progress notice until native completion', async ({ page await page.goto('/e2e/fixtures/settings-status.html?theme=dark'); const sync = page.getByRole('button', { name: '立即同步', exact: true }); const warningOffset = () => - page.locator('.ol-cloud-sync-scope').evaluate( - (node) => - node.getBoundingClientRect().top - node.closest('.ol-cloud-sync')!.getBoundingClientRect().top, - ); + page + .locator('.ol-cloud-sync-scope') + .evaluate( + (node) => + node.getBoundingClientRect().top - + node.closest('.ol-cloud-sync')!.getBoundingClientRect().top, + ); await expect(sync).toBeEnabled(); const warningTop = await warningOffset(); await sync.click(); @@ -334,9 +344,10 @@ test('Sync Now keeps one progress notice until native completion', async ({ page await expect(notice).not.toContainText('同步完成'); await waitForSettingsOperation(page, 'sync', 1); const cancel = page.getByRole('button', { name: '取消当前任务', exact: true }); - const noticeCancel = notice.getByRole('button', { name: '取消当前任务', exact: true }); + const noticeCancel = notice.getByRole('button', { name: '取消同步', exact: true }); await expect(noticeCancel).toBeEnabled(); - await expect(cancel).toHaveCount(1); + await expect(cancel).toHaveCount(0); + await expect(noticeCancel).toHaveAttribute('data-action-style', 'cancel-icon'); expect(await warningOffset()).toBeCloseTo(warningTop, 0); await expect .poll(() => page.evaluate(() => window.settingsStatusFixture.canRestoreDuringSync())) @@ -360,6 +371,7 @@ test('Sync Now keeps one progress notice until native completion', async ({ page await sync.click(); await noticeCancel.click(); await expect(notice).toContainText('已请求取消'); + await expect(noticeCancel).toBeDisabled(); await expect(notice.getByRole('progressbar')).toBeVisible(); await expect(cancel).toHaveCount(0); await expect @@ -388,9 +400,7 @@ test('Sync Now keeps one progress notice until native completion', async ({ page ]); }); -test('cloud sync is cancellable from the welcome modal header without a second action', async ({ - page, -}) => { +test('cloud sync keeps keyboard cancellation inside the welcome modal', async ({ page }) => { await page.goto('/e2e/fixtures/settings-status.html?cloudWelcome'); await page.getByRole('button', { name: '从云端恢复', exact: true }).click(); const dialog = page.getByRole('dialog'); @@ -400,11 +410,13 @@ test('cloud sync is cancellable from the welcome modal header without a second a await sync.click(); await waitForSettingsOperation(page, 'sync', 1); await expect(notice.getByRole('progressbar')).toBeVisible(); - await expect(notice.locator('.ol-notification-action')).toHaveCount(0); - await expect(dialog.locator('header').getByRole('button', { name: '取消当前任务' })).toBeEnabled(); - await cancel.focus(); - await expect(cancel).toBeFocused(); - await page.keyboard.press('Enter'); + const toastCancel = notice.getByRole('button', { name: '取消同步', exact: true }); + await expect(toastCancel).toBeEnabled(); + await expect(toastCancel).toHaveAttribute('tabindex', '-1'); + await expect( + dialog.locator('header').getByRole('button', { name: '取消当前任务' }), + ).toBeEnabled(); + await toastCancel.click(); await expect(cancel).toBeDisabled(); await expect .poll(() => page.evaluate(() => window.settingsStatusFixture.cancelledSyncTasks.length)) @@ -413,6 +425,20 @@ test('cloud sync is cancellable from the welcome modal header without a second a await expect(notice).toContainText('任务已取消。'); await expect(cancel).toHaveCount(0); await expect(dialog).toBeVisible(); + + await sync.click(); + await waitForSettingsOperation(page, 'sync', 2); + const loading = notice.and(page.locator('[data-type="loading"]')); + await loading.getByRole('button', { name: '关闭', exact: true }).click(); + await expect(loading).toHaveCount(0); + expect(await page.evaluate(() => window.settingsStatusFixture.cancelledSyncTasks.length)).toBe(1); + await cancel.focus(); + await expect(cancel).toBeFocused(); + await page.keyboard.press('Enter'); + await expect + .poll(() => page.evaluate(() => window.settingsStatusFixture.cancelledSyncTasks.length)) + .toBe(2); + await finishSettingsOperation(page, 'sync', 2); }); async function clickDecisionBackdrop(page: Page) { @@ -586,21 +612,26 @@ test('normal download cancellation is available only outside a modal and before .poll(() => page.evaluate(() => window.settingsStatusFixture.hasDownloadListener())) .toBe(true); await page.evaluate(() => window.settingsStatusFixture.emitDownload('normal-model', 'started')); - const card = page.locator('.ol-download-card[data-download-id="normal-model"]'); - const cancel = card.locator('button'); + const card = page.locator('[data-notification-key="download:qwen3:normal-model"]'); + const cancel = card.getByRole('button', { name: '取消下载', exact: true }); await expect(cancel).toBeEnabled(); + await expect(cancel).toHaveAttribute('title', '取消下载 normal-model'); + await expect(card.locator('.ol-toast-footer')).toHaveCSS('opacity', '0'); + await card.hover(); + await expect(card.locator('.ol-toast-footer')).toHaveCSS('opacity', '1'); await page.getByRole('button', { name: 'Open download modal', exact: true }).click(); await expect(page.getByRole('dialog', { name: 'Download modal' })).toBeVisible(); await expect(cancel).toBeDisabled(); - await expect(card).toHaveCSS('pointer-events', 'none'); await page.keyboard.press('Escape'); await expect(cancel).toBeEnabled(); await page.evaluate(() => { const observer = new MutationObserver(() => { - const exiting = document.querySelector('.ol-download-card[inert]'); + const exiting = document.querySelector( + '[data-notification-key="download:qwen3:normal-model"][inert]', + ); if (!exiting) return; - const button = exiting.querySelector('button')!; + const button = exiting.querySelector('[data-slot="toast-action"]')!; document.body.dataset.downloadExit = JSON.stringify({ disabled: button.disabled, pointerEvents: getComputedStyle(exiting).pointerEvents, @@ -613,7 +644,9 @@ test('normal download cancellation is available only outside a modal and before attributes: true, attributeFilter: ['inert'], }); - const button = document.querySelector('.ol-download-card button')!; + const button = document.querySelector( + '[data-notification-key="download:qwen3:normal-model"] [data-slot="toast-action"]', + )!; const terminal = window.settingsStatusFixture.emitDownload('normal-model', 'finished'); // A host event may invalidate the job before React commits its exit. button.click(); @@ -627,9 +660,28 @@ test('normal download cancellation is available only outside a modal and before expect(await page.evaluate(() => window.settingsStatusFixture.cancelledDownloads)).toEqual([]); await page.evaluate(() => window.settingsStatusFixture.emitDownload('normal-model', 'started')); + await card.getByRole('button', { name: '关闭', exact: true }).click(); + await expect(card).toHaveCount(0); + expect(await page.evaluate(() => window.settingsStatusFixture.cancelledDownloads)).toEqual([]); + await page.evaluate(() => + window.settingsStatusFixture.emitDownload('normal-model', 'downloading'), + ); + await expect(card).toHaveCount(0); + + await page.evaluate(() => window.settingsStatusFixture.emitDownload('normal-model', 'started')); + await card.hover(); await cancel.click(); await expect(card).toHaveCount(0); expect(await page.evaluate(() => window.settingsStatusFixture.cancelledDownloads)).toEqual([ 'normal-model', ]); + + await page.evaluate(() => window.settingsStatusFixture.emitDownload('broken-model', 'started')); + await page.evaluate(() => window.settingsStatusFixture.emitDownload('broken-model', 'failed')); + await expect(page.locator('[data-notification-key="download:qwen3:broken-model"]')).toHaveCount( + 0, + ); + await expect(page.getByRole('alert').filter({ hasText: '模型下载失败' })).toContainText( + 'broken-model', + ); }); diff --git a/openless-all/app/e2e/settings-inputs.spec.ts b/openless-all/app/e2e/settings-inputs.spec.ts index 8fdbcdc75..8630e94f0 100644 --- a/openless-all/app/e2e/settings-inputs.spec.ts +++ b/openless-all/app/e2e/settings-inputs.spec.ts @@ -18,7 +18,8 @@ test('channel fields stay editable right after the editor opens', async ({ page await expect(dialog).toBeVisible(); const name = dialog.locator('input[placeholder*="例如"]').first(); - const apiKey = dialog.locator('input[type="password"]').first(); + const apiKey = dialog.locator('input.ol-field-secret').first(); + await expect(apiKey).toHaveAttribute('type', 'password'); const endpoint = dialog.locator('input[placeholder*="https://"]').first(); const model = dialog.locator('input[placeholder*="模型"], input[placeholder*="Qwen"]').first(); @@ -33,6 +34,22 @@ test('channel fields stay editable right after the editor opens', async ({ page await field.fill(value); await expect(field).toHaveValue(value); } + + for (const field of [name, endpoint, model]) { + const frame = field.locator('..'); + await expect(frame).toHaveClass(/\bol-field\b/); + await expect(frame.getByRole('button')).toHaveCount(0); + } + const secretFrame = apiKey.locator('..'); + const eye = secretFrame.getByRole('button'); + await eye.focus(); + await eye.press('Enter'); + const revealed = secretFrame.locator('input'); + await expect(revealed).toHaveAttribute('type', 'text'); + await expect(revealed).toHaveValue('sk-input-test'); + await expect(eye).toBeFocused(); + await eye.press('Space'); + await expect(revealed).toHaveAttribute('type', 'password'); }); for (const profile of [ diff --git a/openless-all/app/e2e/settings-regressions.spec.ts b/openless-all/app/e2e/settings-regressions.spec.ts index bc359bee9..533016964 100644 --- a/openless-all/app/e2e/settings-regressions.spec.ts +++ b/openless-all/app/e2e/settings-regressions.spec.ts @@ -235,7 +235,7 @@ test('experimental download respects the settings modal and switch-off does not await expect(toggle).toBeEnabled(); const before = (await next.boundingBox())!.y; await toggle.click(); - const card = page.locator('.ol-download-card[data-download-id="sense-voice"]'); + const card = page.locator('[data-notification-key="download:experimental:sense-voice"]'); await expect(card).toBeVisible(); expect(Math.abs((await next.boundingBox())!.y - before)).toBeLessThan(1); const statusText = await sense.locator('.ol-experimental-model-status').evaluate((element) => { @@ -246,7 +246,7 @@ test('experimental download respects the settings modal and switch-off does not return { right: text.right, progressRight: progress.right }; }); expect(Math.abs(statusText.right - statusText.progressRight)).toBeLessThan(2); - await expect(card.getByRole('button', { name: '取消', exact: true })).toBeDisabled(); + await expect(card.getByRole('button', { name: '取消下载', exact: true })).toBeDisabled(); await toggle.click(); await expect(card).toHaveCount(0); await page.waitForTimeout(2100); diff --git a/openless-all/app/e2e/viewport-interactions.spec.ts b/openless-all/app/e2e/viewport-interactions.spec.ts index daebb3fd4..39761a2b6 100644 --- a/openless-all/app/e2e/viewport-interactions.spec.ts +++ b/openless-all/app/e2e/viewport-interactions.spec.ts @@ -154,7 +154,8 @@ for (const [scale, factor] of [ const body = long.locator('.ol-dialog-body'); const lastLine = long.getByTestId('long-detail-end'); const cancel = long.getByRole('button', { name: 'Keep unchanged' }); - await expect.poll(() => body.evaluate((node) => node.scrollHeight - node.clientHeight)) + await expect + .poll(() => body.evaluate((node) => node.scrollHeight - node.clientHeight)) .toBeGreaterThan(0); await expect(lastLine).not.toBeInViewport(); await expect(cancel).toBeInViewport(); @@ -222,7 +223,8 @@ test('warnings wait for acknowledgment and success notifications only show statu await page.getByRole('button', { name: 'Show feedback' }).click(); await expect(page.getByRole('status')).toHaveText('Status only'); const icon = page.locator('.ol-notification-icon'); - await expect(icon).toHaveCSS('background-color', 'rgb(59, 130, 246)'); + await expect(icon).toHaveAttribute('data-tone', 'success'); + await expect(icon).toHaveCSS('background-color', 'rgb(48, 209, 88)'); await page.locator('.ol-notification-close').click(); await expect(page.getByRole('status')).toHaveCount(0); }); diff --git a/openless-all/app/harmony/ipc-audit.json b/openless-all/app/harmony/ipc-audit.json index 1a01e88e2..3487e078b 100644 --- a/openless-all/app/harmony/ipc-audit.json +++ b/openless-all/app/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": 197, + "total": 198, "wired": 108, - "missing": 89, + "missing": 90, "commands": [ { "name": "accept_pending_correction", @@ -431,6 +431,13 @@ ], "implementation": "unimplemented" }, + { + "name": "get_activity_app_icons", + "calledFrom": [ + "src/lib/ipc/history.ts" + ], + "implementation": "unimplemented" + }, { "name": "get_activity_apps", "calledFrom": [ diff --git a/openless-all/app/package-lock.json b/openless-all/app/package-lock.json index 79ec6bd92..d13beda38 100644 --- a/openless-all/app/package-lock.json +++ b/openless-all/app/package-lock.json @@ -18,6 +18,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "dompurify": "^3.4.8", + "figma-squircle": "^1.1.0", "framer-motion": "^12.39.0", "i18next": "^26.0.8", "lucide-react": "^1.23.0", @@ -2340,6 +2341,12 @@ } } }, + "node_modules/figma-squircle": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/figma-squircle/-/figma-squircle-1.1.0.tgz", + "integrity": "sha512-3aa6bOurrsybsuYo1TMRuasBpXgVjgnmOUtZ40il6e1dJF2lhTRq89z7oy1uzKDspbH3630rLZD2UvJqXDiktA==", + "license": "MIT" + }, "node_modules/framer-motion": { "version": "12.43.0", "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.43.0.tgz", diff --git a/openless-all/app/package.json b/openless-all/app/package.json index 8baef4288..885e5513e 100644 --- a/openless-all/app/package.json +++ b/openless-all/app/package.json @@ -46,6 +46,7 @@ "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "dompurify": "^3.4.8", + "figma-squircle": "^1.1.0", "framer-motion": "^12.39.0", "i18next": "^26.0.8", "lucide-react": "^1.23.0", diff --git a/openless-all/app/public/licenses/rare-ui-LICENSE.txt b/openless-all/app/public/licenses/rare-ui-LICENSE.txt new file mode 100644 index 000000000..229ddb907 --- /dev/null +++ b/openless-all/app/public/licenses/rare-ui-LICENSE.txt @@ -0,0 +1,35 @@ +MIT + Commons Clause License Condition v1.0 + Attribution + +Copyright (c) 2026 Swami Malode + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, and distribute the Software as part of an +application, website, or product, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +Attribution Requirement + +Any project that ships any part of the Software must credit Rare UI with a +visible link to https://rareui.com, placed where a visitor or user can find it, +such as a site footer, an about page, a credits screen or a README. The credit +and the copyright notice above must not be removed from the source you copied. + +Commons Clause Restriction + +You may use this Software, including for any commercial purpose, so long as you +do not sell, sublicense, or redistribute the components themselves, whether +alone, in a bundle, or as a ported version. + +No Warranty + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/openless-all/app/scripts/message-follow-reader.test.mjs b/openless-all/app/scripts/message-follow-reader.test.mjs index 7066439ac..e77a25ecc 100644 --- a/openless-all/app/scripts/message-follow-reader.test.mjs +++ b/openless-all/app/scripts/message-follow-reader.test.mjs @@ -4,6 +4,11 @@ import { installMessageFollow } from '../src/lib/messageFollow.ts'; class Viewport extends EventTarget { scrollHeight = 1000; clientHeight = 100; + clientLeft = 0; + clientWidth = 100; + getBoundingClientRect() { + return { left: 0 }; + } position = 900; get scrollTop() { return this.position; @@ -12,6 +17,7 @@ class Viewport extends EventTarget { this.position = Math.max(0, Math.min(value, this.scrollHeight - this.clientHeight)); } } +globalThis.window = new EventTarget(); const viewport = new Viewport(); const content = new EventTarget(); const root = new EventTarget(); @@ -44,7 +50,21 @@ const dispose = installMessageFollow(root); resize(); flush(); assert.equal(viewport.scrollTop, 900); -viewport.dispatchEvent(new Event('touchmove')); +// Resize deliveries can precede the animation frame that moves to the new bottom. +viewport.scrollHeight = 1080; +resize(); +viewport.scrollHeight = 1160; +resize(); +flush(); +assert.equal(viewport.scrollTop, 1060, 'geometry changes do not revoke bottom ownership'); +for (const [type, clientY] of [ + ['touchstart', 20], + ['touchmove', 50], +]) { + const event = new Event(type); + Object.defineProperty(event, 'touches', { value: [{ clientY }] }); + viewport.dispatchEvent(event); +} viewport.scrollTop = 800; viewport.dispatchEvent(new Event('scroll')); // Browser scroll anchoring and a delayed ResizeObserver can put scrollTop beyond @@ -60,6 +80,32 @@ viewport.scrollHeight = 1380; resize(); flush(); assert.equal(viewport.scrollTop, 1280, 'returning to the actual bottom resumes follow'); +// A large upward wheel gesture can already have reached the top at delivery. +viewport.scrollTop = 0; +const wheel = new Event('wheel'); +Object.defineProperty(wheel, 'deltaY', { value: -1400 }); +viewport.dispatchEvent(wheel); +viewport.scrollHeight = 1400; +resize(); +flush(); +assert.equal(viewport.scrollTop, 0, 'streaming must not interrupt a reader at the top'); +viewport.scrollTop = 1300; +viewport.dispatchEvent(new Event('scroll')); + +const down = new Event('pointerdown'); +Object.defineProperties(down, { + button: { value: 0 }, + pointerType: { value: 'mouse' }, + clientX: { value: 103 }, +}); +viewport.dispatchEvent(down); +viewport.scrollTop = 900; +viewport.dispatchEvent(new Event('scroll')); +window.dispatchEvent(new Event('pointerup')); +viewport.scrollHeight = 1500; +resize(); +flush(); +assert.equal(viewport.scrollTop, 900, 'dragging the scrollbar hands follow to the reader'); dispose(); assert(disconnected); assert.equal(frames.size, 0); diff --git a/openless-all/app/scripts/qa-panel-runtime.test.mjs b/openless-all/app/scripts/qa-panel-runtime.test.mjs index 6bdde5078..495fc05e2 100644 --- a/openless-all/app/scripts/qa-panel-runtime.test.mjs +++ b/openless-all/app/scripts/qa-panel-runtime.test.mjs @@ -7,24 +7,34 @@ const app = fileURLToPath(new URL('../', import.meta.url)), require = createRequire(resolve(app, 'package.json')), ts = require('typescript'); const helpers = await import(pathToFileURL(resolve(app, 'src/lib/qaMessage.ts'))); -const source = readFileSync(resolve(app, 'src/features/qa/QaPanel.tsx'), 'utf8'); -const parsed = ts.createSourceFile( - 'QaPanel.tsx', - source, - ts.ScriptTarget.ES2020, - true, - ts.ScriptKind.TSX, -); -const names = parsed.statements - .filter(ts.isImportDeclaration) - .flatMap((n) => - n.importClause?.namedBindings && ts.isNamedImports(n.importClause.namedBindings) - ? n.importClause.namedBindings.elements.map((n) => n.name.text) - : [], +const components = ['QaPanel', 'QaComposer', 'QaPromptBox']; +const parsed = components.map((component) => { + const file = `${component}.tsx`; + return ts.createSourceFile( + file, + readFileSync(resolve(app, 'src/features/qa', file), 'utf8'), + ts.ScriptTarget.ES2020, + true, + ts.ScriptKind.TSX, ); -const body = parsed.statements +}); +const statements = parsed.flatMap((module) => module.statements); +const names = [ + ...new Set( + statements + .filter(ts.isImportDeclaration) + .flatMap((n) => + n.importClause?.namedBindings && ts.isNamedImports(n.importClause.namedBindings) + ? n.importClause.namedBindings.elements + .filter((binding) => !binding.isTypeOnly) + .map((binding) => binding.name.text) + : [], + ), + ), +].filter((name) => !components.includes(name)); +const body = statements .filter((n) => !ts.isImportDeclaration(n)) - .map((n) => n.getFullText(parsed)) + .map((n) => n.getFullText()) .join('\n'); const compiled = ts.transpileModule(body, { compilerOptions: { @@ -37,7 +47,7 @@ const factory = new Function( ...names, 'exports', 'require', - `${compiled};return {QaPanel,Composer,MessageRow,ErrorContent};`, + `${compiled};return {QaPanel,QaComposer,QaPromptBox,QaUserMessage};`, ); function compileModule(file) { const ast = ts.createSourceFile( @@ -205,6 +215,12 @@ function context(native = true, embedded = false) { useState: state, useRef: ref, useEffect: effect, + useLayoutEffect: effect, + useReducedMotion: () => true, + useCallback: (callback) => callback, + MotionConfig: 'motion-config', + motion: { div: 'motion-div', span: 'motion-span' }, + AnimatePresence: 'animate-presence', useTranslation: () => ({ t: (k) => k }), useGithubLogin: () => '', useChatPanelLifecycle: makeLifecycle( @@ -222,7 +238,6 @@ function context(native = true, embedded = false) { stopDeepSeekReading: () => { calls.stopReading++; }, - qaSources: (body) => ({ body, sources: [] }), qaCancelTurn: async () => { calls.cancelTurn++; return pending.cancelTurn?.promise; @@ -241,7 +256,7 @@ function context(native = true, embedded = false) { resize, async (_boundary, _fits, signal) => { if (signal.aborted) throw new DOMException('Layout superseded', 'AbortError'); - return {}; + return { width: 920, height: 800 }; }, {}, ), @@ -300,7 +315,14 @@ function context(native = true, embedded = false) { const emit = (name, payload) => { for (const fn of events.get(name) ?? []) fn(payload); }; - const composer = (tree) => find(tree, (n) => n.type === api.Composer).props; + const composer = (tree) => find(tree, (n) => n.type === api.QaComposer).props; + const responses = (tree) => nodes(tree).filter((node) => node.type === 'QaStreamingResponse'); + const committedTurns = (tree) => + nodes(tree).filter( + (node) => + node.type === api.QaUserMessage || + (node.type === 'QaStreamingResponse' && !node.props.streaming), + ); const closePanel = () => find( render(), @@ -327,6 +349,8 @@ function context(native = true, embedded = false) { events, keys, composer, + responses, + committedTurns, closePanel, beginConversation, }; @@ -347,9 +371,8 @@ await test('browser compact has no demo conversations and cannot execute native const compact = context(false); const tree = compact.render(); assert(!tree.props.className.includes('is-expanded')); - assert( - !nodes(tree).some((n) => n.type === compact.api.Composer || n.type === compact.api.MessageRow), - ); + assert(!nodes(tree).some((n) => n.type === compact.api.QaComposer)); + assert.equal(compact.committedTurns(tree).length, 0); compact.hooks.unmount(); const c = context(false, true); let p = c.composer(c.render()); @@ -364,9 +387,11 @@ await test('browser compact has no demo conversations and cannot execute native assert.equal(c.calls.mic, 0); assert.deepEqual(c.calls.mode, []); const h = new Hooks(), - ui = h.render(() => c.api.Composer(p)); - for (const button of nodes(ui).filter((n) => n.type === 'button')) - assert.equal(button.props.disabled, true); + ui = h.render(() => c.api.QaPromptBox(c.api.QaComposer(p).props)); + assert.equal(find(ui, (n) => n.type === 'textarea').props.disabled, true); + const buttons = nodes(ui).filter((n) => n.type === 'button'); + assert.equal(buttons.length, 3); + for (const button of buttons) assert.equal(button.props.disabled, true); c.hooks.unmount(); }); await test('polish preview expands native window after payload arrives', async () => { @@ -485,7 +510,7 @@ await test('send failure preserves draft and exposes error without a fake user m const tree = c.render(); assert.equal(c.composer(tree).value, 'keep this'); assert.equal(c.composer(tree).status, 'error'); - assert(!nodes(tree).some((n) => n.type === c.api.MessageRow)); + assert.equal(c.committedTurns(tree).length, 0); c.hooks.unmount(); }); await test('cancel during resize prevents queued question and late layout failures do not overwrite reopened compact state', async () => { @@ -571,7 +596,9 @@ await test('stale answer is ignored and final answer replaces streaming buffer e c.emit('qa:state', { kind: 'answer_delta', sessionId: 'new', chunk: 'real ' }); c.emit('qa:state', { kind: 'answer_delta', sessionId: 'new', chunk: 'answer' }); let tree = c.render(); - assert.equal(find(tree, (n) => n.type === 'AssistantMarkdown').props.markdown, 'real answer'); + const [live] = c.responses(tree); + assert.equal(live.props.markdown, 'real answer'); + assert.equal(live.props.streaming, true); c.emit('qa:state', { kind: 'answer', sessionId: 'new', @@ -581,8 +608,11 @@ await test('stale answer is ignored and final answer replaces streaming buffer e ], }); tree = c.render(); - assert(!nodes(tree).some((n) => n.type === 'AssistantMarkdown')); - assert.equal(nodes(tree).filter((n) => n.type === c.api.MessageRow).length, 2); + const [finalAnswer] = c.responses(tree); + assert.equal(c.responses(tree).length, 1); + assert(!finalAnswer.props.streaming); + assert.equal(finalAnswer.props.markdown, 'real answer'); + assert.equal(c.committedTurns(tree).length, 2); c.hooks.unmount(); }); await test('Stop belongs to the presented turn, and repeated clicks cannot cancel a later turn', async () => { @@ -613,7 +643,7 @@ await test('Stop belongs to the presented turn, and repeated clicks cannot cance const next = c.composer(c.render()); assert.equal(next.status, 'thinking'); assert.equal(next.cancelBusy, false); - assert.equal(nodes(c.render()).filter((n) => n.type === c.api.MessageRow).length, 2); + assert.equal(c.committedTurns(c.render()).length, 2); c.hooks.unmount(); }); await test('recording stop commits the recorded question without issuing a turn cancellation', async () => { @@ -775,27 +805,16 @@ await test('composer IME enter, WebKit 229 and form submission guards; genuine e const c = context(); const h = new Hooks(); let sent = 0; - const p = { - value: '中文', - status: 'idle', - level: 0, - voiceActive: false, - selectionPreview: '', - busy: false, - micBusy: false, - embedded: false, - editInstructionMode: false, - onEditInstructionModeChange() {}, - onChange() {}, - onSubmit() { - sent++; - }, - onToggleRecording() {}, - onClose() {}, - t: (k) => k, - }; - const tree = h.render(() => c.api.Composer(p)); - const input = find(tree, (n) => n.type === 'input'); + const tree = h.render(() => + c.api.QaPromptBox({ + value: '中文', + sendDisabled: false, + onSubmit() { + sent++; + }, + }), + ); + const input = find(tree, (n) => n.type === 'textarea'); const key = (extra = {}) => ({ key: 'Enter', keyCode: 13, @@ -809,6 +828,12 @@ await test('composer IME enter, WebKit 229 and form submission guards; genuine e input.props.onCompositionEnd(); input.props.onKeyDown(key({ nativeEvent: { isComposing: true } })); input.props.onKeyDown(key({ keyCode: 229 })); + input.props.onKeyDown( + key({ + shiftKey: true, + preventDefault: () => assert.fail('Shift+Enter must insert a new line'), + }), + ); assert.equal(sent, 0); input.props.onKeyDown(key()); assert.equal(sent, 1); diff --git a/openless-all/app/scripts/ui-followups-contract.test.mjs b/openless-all/app/scripts/ui-followups-contract.test.mjs index 682d46c54..8ef41b4ee 100644 --- a/openless-all/app/scripts/ui-followups-contract.test.mjs +++ b/openless-all/app/scripts/ui-followups-contract.test.mjs @@ -18,6 +18,10 @@ const languageSection = readFileSync( resolve(root, 'src/features/settings/sections/LanguageSection.tsx'), 'utf8', ); +const interfaceLanguagePicker = readFileSync( + resolve(root, 'src/ui/controls/InterfaceLanguagePicker.tsx'), + 'utf8', +); const recordingSection = readFileSync( resolve(root, 'src/features/input/RecordingInputSection.tsx'), 'utf8', @@ -57,6 +61,7 @@ assert.match(insertMotion, /bornBlurPx: 4\.5/); assert.match(insertMotion, /bornFadeMs: 220/); assert.match(themeSection, / +#include + +typedef void (*OpenLessIconReceiver)(void *, const uint8_t *, size_t); + +void openless_macos_activity_app_icon(const char *name, const char *bundleId, + void *output, OpenLessIconReceiver receive) { + @autoreleasepool { + NSWorkspace *workspace = NSWorkspace.sharedWorkspace; + NSString *bundle = bundleId ? [NSString stringWithUTF8String:bundleId] : nil; + NSURL *url = bundle.length ? [workspace URLForApplicationWithBundleIdentifier:bundle] : nil; + NSImage *icon = url ? [workspace iconForFile:url.path] : nil; + if (!icon && !bundle.length && name) { + NSString *label = [NSString stringWithUTF8String:name]; + // Older rankings only have a name. Resolve it only when the running app is unambiguous. + NSRunningApplication *match = nil; + for (NSRunningApplication *app in workspace.runningApplications) { + if (![app.localizedName isEqualToString:label]) continue; + if (match && ![match.bundleURL isEqual:app.bundleURL]) return; + match = app; + } + icon = match.icon; + } + if (!icon) return; + + const NSInteger size = 32; + NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] + initWithBitmapDataPlanes:NULL pixelsWide:size pixelsHigh:size bitsPerSample:8 + samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace + bytesPerRow:0 bitsPerPixel:0]; + if (!bitmap) return; + NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]; + if (!context) return; + [NSGraphicsContext saveGraphicsState]; + [NSGraphicsContext setCurrentContext:context]; + context.imageInterpolation = NSImageInterpolationHigh; + NSRect rect = NSMakeRect(0, 0, size, size); + [[NSColor clearColor] set]; + NSRectFillUsingOperation(rect, NSCompositingOperationCopy); + [icon drawInRect:rect fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0]; + [NSGraphicsContext restoreGraphicsState]; + NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}]; + if (png.length) receive(output, png.bytes, png.length); + } +} diff --git a/openless-all/app/src-tauri/src/activity_app_icon_windows.c b/openless-all/app/src-tauri/src/activity_app_icon_windows.c new file mode 100644 index 000000000..f1473141c --- /dev/null +++ b/openless-all/app/src-tauri/src/activity_app_icon_windows.c @@ -0,0 +1,77 @@ +#define COBJMACROS +#define WIN32_LEAN_AND_MEAN +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0A00 +#endif +#include +#include +#include +#include +#include + +typedef void (*OpenLessIconReceiver)(void *, const uint8_t *, size_t); + +uint32_t openless_windows_activity_app_path(uint32_t pid, wchar_t *path, uint32_t capacity) { + HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!process) return 0; + DWORD length = capacity; + BOOL ok = QueryFullProcessImageNameW(process, 0, path, &length); + CloseHandle(process); + return ok ? length : 0; +} + +void openless_windows_activity_app_icon(const wchar_t *path, void *output, OpenLessIconReceiver receive) { + // This is called on a blocking worker with an executable obtained from a local process. + // Never inspect icon resources on a UNC path or a mapped remote drive. + if (!path[0] || path[1] != L':' || path[2] != L'\\') return; + wchar_t drive[] = {path[0], L':', L'\\', 0}; + UINT driveType = GetDriveTypeW(drive); + if (driveType == DRIVE_REMOTE || driveType == DRIVE_NO_ROOT_DIR || driveType == DRIVE_UNKNOWN) return; + HRESULT apartment = CoInitializeEx(NULL, COINIT_MULTITHREADED); + if (FAILED(apartment) && apartment != RPC_E_CHANGED_MODE) return; + HICON icon = NULL; + IWICImagingFactory *factory = NULL; + IWICBitmap *bitmap = NULL; + IWICBitmapEncoder *encoder = NULL; + IWICBitmapFrameEncode *frame = NULL; + IStream *stream = NULL; + + if (ExtractIconExW(path, 0, &icon, NULL, 1) != 1 || !icon) goto cleanup; + if (FAILED(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, + &IID_IWICImagingFactory, (void **)&factory))) goto cleanup; + if (FAILED(IWICImagingFactory_CreateBitmapFromHICON(factory, icon, &bitmap))) goto cleanup; + UINT width, height; + if (FAILED(IWICBitmap_GetSize(bitmap, &width, &height)) || + !width || !height || width > 256 || height > 256) goto cleanup; + if (FAILED(CreateStreamOnHGlobal(NULL, TRUE, &stream))) goto cleanup; + if (FAILED(IWICImagingFactory_CreateEncoder(factory, &GUID_ContainerFormatPng, NULL, &encoder))) goto cleanup; + if (FAILED(IWICBitmapEncoder_Initialize(encoder, stream, WICBitmapEncoderNoCache))) goto cleanup; + if (FAILED(IWICBitmapEncoder_CreateNewFrame(encoder, &frame, NULL))) goto cleanup; + if (FAILED(IWICBitmapFrameEncode_Initialize(frame, NULL))) goto cleanup; + if (FAILED(IWICBitmapFrameEncode_SetSize(frame, width, height))) goto cleanup; + WICPixelFormatGUID format = GUID_WICPixelFormat32bppBGRA; + if (FAILED(IWICBitmapFrameEncode_SetPixelFormat(frame, &format))) goto cleanup; + if (FAILED(IWICBitmapFrameEncode_WriteSource(frame, (IWICBitmapSource *)bitmap, NULL))) goto cleanup; + if (FAILED(IWICBitmapFrameEncode_Commit(frame))) goto cleanup; + if (FAILED(IWICBitmapEncoder_Commit(encoder))) goto cleanup; + + STATSTG stat; + HGLOBAL memory; + if (FAILED(IStream_Stat(stream, &stat, STATFLAG_NONAME)) || + stat.cbSize.QuadPart > 131072 || !stat.cbSize.QuadPart || + FAILED(GetHGlobalFromStream(stream, &memory))) goto cleanup; + const uint8_t *data = GlobalLock(memory); + if (data) { + receive(output, data, (size_t)stat.cbSize.QuadPart); + GlobalUnlock(memory); + } + +cleanup: + if (frame) IWICBitmapFrameEncode_Release(frame); + if (encoder) IWICBitmapEncoder_Release(encoder); + if (stream) IStream_Release(stream); + if (bitmap) IWICBitmap_Release(bitmap); + if (factory) IWICImagingFactory_Release(factory); + if (icon) DestroyIcon(icon); + if (SUCCEEDED(apartment)) CoUninitialize(); +} diff --git a/openless-all/app/src-tauri/src/activity_app_icons.rs b/openless-all/app/src-tauri/src/activity_app_icons.rs new file mode 100644 index 000000000..00018db4e --- /dev/null +++ b/openless-all/app/src-tauri/src/activity_app_icons.rs @@ -0,0 +1,321 @@ +//! Local desktop app icons. The webview can ask for ranked apps, not arbitrary paths. + +use base64::{engine::general_purpose::STANDARD, Engine}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::io::{Read, Write}; +use std::path::PathBuf; + +const MAX_PNG_BYTES: usize = 128 * 1024; +const PNG_HEADER: &[u8] = b"\x89PNG\r\n\x1a\n"; + +fn cache_path(name: &str) -> Option { + let key = Sha256::digest(name.as_bytes()); + Some( + crate::persistence::data_dir() + .ok()? + .join("activity-app-icons") + .join(format!("{key:x}.png")), + ) +} + +fn read_cached(name: &str) -> Option> { + let mut bytes = Vec::new(); + std::fs::File::open(cache_path(name)?) + .ok()? + .take(MAX_PNG_BYTES as u64 + 1) + .read_to_end(&mut bytes) + .ok()?; + (bytes.len() <= MAX_PNG_BYTES && bytes.starts_with(PNG_HEADER)).then_some(bytes) +} + +fn cache(name: &str, bytes: &[u8]) -> Option<()> { + let path = cache_path(name)?; + let directory = path.parent()?; + std::fs::create_dir_all(directory).ok()?; + let mut tmp = tempfile::NamedTempFile::new_in(directory).ok()?; + tmp.write_all(bytes).ok()?; + tmp.persist(path).ok()?; + Some(()) +} + +unsafe extern "C" fn receive_png(output: *mut c_void, bytes: *const u8, len: usize) { + if !bytes.is_null() && (PNG_HEADER.len()..=MAX_PNG_BYTES).contains(&len) { + // The native callback is synchronous, and the caller owns the output Vec. + let bytes = unsafe { std::slice::from_raw_parts(bytes, len) }; + if bytes.starts_with(PNG_HEADER) { + unsafe { &mut *output.cast::>() }.extend_from_slice(bytes); + } + } +} + +fn data_urls(rows: Vec<(String, Vec)>) -> BTreeMap { + rows.into_iter() + .map(|(name, png)| { + ( + name, + format!("data:image/png;base64,{}", STANDARD.encode(png)), + ) + }) + .collect() +} + +#[cfg(target_os = "macos")] +fn macos_png(name: &str, bundle_id: Option<&str>) -> Option> { + use std::ffi::{c_char, CString}; + unsafe extern "C" { + fn openless_macos_activity_app_icon( + name: *const c_char, + bundle_id: *const c_char, + output: *mut c_void, + receive: unsafe extern "C" fn(*mut c_void, *const u8, usize), + ); + } + let name = CString::new(name).ok()?; + let bundle_id = bundle_id.and_then(|id| CString::new(id).ok()); + let mut png = Vec::::new(); + unsafe { + openless_macos_activity_app_icon( + name.as_ptr(), + bundle_id + .as_ref() + .map_or(std::ptr::null(), |id| id.as_ptr()), + (&mut png as *mut Vec).cast(), + receive_png, + ); + } + (!png.is_empty()).then_some(png) +} + +#[cfg(target_os = "macos")] +#[derive(Debug, PartialEq, Eq)] +struct MacIconRequest { + name: String, + bundle: Option, +} + +#[cfg(target_os = "macos")] +impl MacIconRequest { + fn cache_key(&self) -> String { + match &self.bundle { + Some(id) => format!("mac:bundle:{id}"), + None => format!("mac:name:{}", self.name), + } + } +} + +#[cfg(target_os = "macos")] +fn macos_requests( + names: Vec, + recorded_apps: impl IntoIterator, +) -> Vec { + let mut bundles = BTreeMap::new(); + for (name, id) in recorded_apps { + if names.contains(&name) && !id.is_empty() { + let bundle = bundles.entry(name).or_insert_with(|| Some(id.clone())); + if bundle.as_deref() != Some(id.as_str()) { + *bundle = None; + } + } + } + names + .into_iter() + .filter_map(|name| { + let bundle = match bundles.remove(&name) { + // Ambiguous names must not use a cached icon or a running-app guess. + Some(None) => return None, + found => found.flatten(), + }; + Some(MacIconRequest { name, bundle }) + }) + .collect() +} + +#[cfg(target_os = "macos")] +pub(crate) async fn macos_icons( + app: &tauri::AppHandle, + names: Vec, + recorded_apps: impl IntoIterator, +) -> BTreeMap { + let requests = macos_requests(names, recorded_apps); + let cached = tauri::async_runtime::spawn_blocking(move || { + let mut found = Vec::new(); + let mut missing = Vec::new(); + for request in requests { + if let Some(png) = read_cached(&request.cache_key()) { + found.push((request.name, png)); + } else { + missing.push(request); + } + } + (found, missing) + }) + .await; + let Ok((mut found, missing)) = cached else { + return BTreeMap::new(); + }; + if !missing.is_empty() { + let (send, receive) = tokio::sync::oneshot::channel(); + // AppKit drawing remains on its owning thread. Disk I/O never runs here. + if app + .run_on_main_thread(move || { + let rows: Vec<_> = missing + .into_iter() + .filter_map(|request| { + macos_png(&request.name, request.bundle.as_deref()) + .map(|png| (request, png)) + }) + .collect(); + let _ = send.send(rows); + }) + .is_ok() + { + if let Ok(rows) = receive.await { + if let Ok(mut rows) = tauri::async_runtime::spawn_blocking(move || { + rows.into_iter() + .map(|(request, png)| { + let _ = cache(&request.cache_key(), &png); + (request.name, png) + }) + .collect() + }) + .await + { + found.append(&mut rows); + } + } + } + } + data_urls(found) +} + +#[cfg(all(test, target_os = "macos"))] +mod macos_tests { + use super::*; + + #[test] + fn a_bundle_is_the_cache_identity_and_an_ambiguous_name_is_not_resolved() { + let requests = macos_requests( + vec!["Browser".into(), "Editor".into(), "Legacy".into()], + [ + ("Browser".into(), "com.example.browser".into()), + ("Editor".into(), "com.example.editor1".into()), + ("Editor".into(), "com.example.editor2".into()), + ("Editor".into(), "com.example.editor1".into()), + ], + ); + assert_eq!(requests.len(), 2); + assert_eq!(requests[0].cache_key(), "mac:bundle:com.example.browser"); + assert_eq!(requests[1].cache_key(), "mac:name:Legacy"); + } +} + +#[cfg(target_os = "windows")] +mod windows { + use super::*; + use std::ffi::OsString; + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + use std::path::Path; + use std::sync::{Mutex, OnceLock}; + + unsafe extern "C" { + fn openless_windows_activity_app_path(pid: u32, path: *mut u16, capacity: u32) -> u32; + fn openless_windows_activity_app_icon( + path: *const u16, + output: *mut c_void, + receive: unsafe extern "C" fn(*mut c_void, *const u8, usize), + ); + } + + fn sources() -> &'static Mutex> { + static SOURCES: OnceLock>> = OnceLock::new(); + SOURCES.get_or_init(Mutex::default) + } + + fn process_path(pid: u32) -> Option { + if pid == 0 { + return None; + } + let mut utf16 = vec![0u16; 32768]; + let len = unsafe { + openless_windows_activity_app_path(pid, utf16.as_mut_ptr(), utf16.len() as u32) + }; + (len > 0 && (len as usize) < utf16.len()) + .then(|| PathBuf::from(OsString::from_wide(&utf16[..len as usize]))) + } + + fn png_for(name: &str, path: &Path) -> Option> { + let path: Vec<_> = path.as_os_str().encode_wide().chain([0]).collect(); + let mut png = Vec::::new(); + unsafe { + openless_windows_activity_app_icon( + path.as_ptr(), + (&mut png as *mut Vec).cast(), + receive_png, + ); + } + if png.is_empty() { + return None; + } + let _ = cache(name, &png); + Some(png) + } + + pub(crate) fn app_name_for_pid(pid: u32) -> Option { + let path = process_path(pid)?; + // The executable stem is stable across documents; window titles can contain private text. + let name = path.file_stem()?.to_str()?.to_string(); + if name.is_empty() { + return None; + } + if let Ok(mut sources) = sources().lock() { + if !sources.contains_key(&name) && sources.len() < 256 { + sources.insert(name.clone(), path.clone()); + let name = name.clone(); + // Persist only the icon, not the executable path. This also covers sessions when + // Overview is not visible until after a restart. + tauri::async_runtime::spawn_blocking(move || { + if read_cached(&name).is_none() { + let _ = png_for(&name, &path); + } + }); + } + } + Some(name) + } + + pub(crate) async fn icons(names: Vec) -> BTreeMap { + tauri::async_runtime::spawn_blocking(move || { + let rows = names + .into_iter() + .filter_map(|name| { + let png = read_cached(&name).or_else(|| { + let path = sources().lock().ok()?.get(&name)?.clone(); + png_for(&name, &path) + })?; + Some((name, png)) + }) + .collect(); + data_urls(rows) + }) + .await + .unwrap_or_default() + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn current_process_resolves_to_an_executable_not_a_window_title() { + let path = process_path(std::process::id()).unwrap(); + assert!(path.is_absolute()); + assert!(path.extension().unwrap().eq_ignore_ascii_case("exe")); + assert!(process_path(0).is_none()); + } + } +} + +#[cfg(target_os = "windows")] +pub(crate) use windows::{app_name_for_pid, icons as windows_icons}; diff --git a/openless-all/app/src-tauri/src/commands/history.rs b/openless-all/app/src-tauri/src/commands/history.rs index 7cbc44732..38d8353b3 100644 --- a/openless-all/app/src-tauri/src/commands/history.rs +++ b/openless-all/app/src-tauri/src/commands/history.rs @@ -55,6 +55,42 @@ pub fn get_activity_apps(core: CoreState<'_>, year: u32) -> Result, + year: u32, +) -> Result, String> { + #[cfg(any(target_os = "macos", target_os = "windows"))] + let names: Vec<_> = core + .list_activity_apps(year) + .map_err(|error| error.to_string())? + .into_iter() + .take(5) + .map(|(name, _)| name) + .collect(); + #[cfg(target_os = "macos")] + { + let recorded_apps = core + .list_history() + .unwrap_or_default() + .into_iter() + .filter_map(|record| Some((record.app_name?, record.app_bundle_id?))); + Ok(crate::activity_app_icons::macos_icons(&app, names, recorded_apps).await) + } + #[cfg(target_os = "windows")] + { + let _ = app; + Ok(crate::activity_app_icons::windows_icons(names).await) + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + let _ = (app, core, year); + Ok(std::collections::BTreeMap::new()) + } +} + fn recording_path_candidates(session_id: &str) -> Result<[std::path::PathBuf; 2], String> { if !is_valid_session_id(session_id) { return Err("invalid session id".into()); diff --git a/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs b/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs index 1b964f662..2fc2dbd87 100644 --- a/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs +++ b/openless-all/app/src-tauri/src/coordinator/capsule_focus.rs @@ -56,7 +56,7 @@ pub(crate) fn capture_focus_target() -> Option { /// context for LLM polish/translate so the model can adapt style per app. See issue #116. /// /// macOS uses NSWorkspace.frontmostApplication (public API, no extra permission); -/// Windows reuses the foreground HWND for the window title; Linux and other platforms return None. +/// Windows resolves the executable for the foreground HWND; other platforms return None. pub(crate) fn capture_frontmost_app() -> Option { // This once held an NSWorkspace/Win32 implementation duplicated verbatim from // `selection.rs` (three cfg branches, even the nsstring conversion helper). Consolidated diff --git a/openless-all/app/src-tauri/src/hotkey.rs b/openless-all/app/src-tauri/src/hotkey.rs index 8c200a5d5..9e1b08756 100644 --- a/openless-all/app/src-tauri/src/hotkey.rs +++ b/openless-all/app/src-tauri/src/hotkey.rs @@ -627,6 +627,15 @@ mod platform { const FLAG_MASK_COMMAND: CgEventFlags = 0x0010_0000; const FLAG_MASK_SECONDARY_FN: CgEventFlags = 0x0080_0000; + const SPACE_KEYCODE: i64 = 49; + const FN_KEYCODE: i64 = 63; + const AUTOREPEAT_FIELD: CgEventField = 8; + const SOURCE_USER_DATA_FIELD: CgEventField = 42; + const REPLAYED_SPACE: i64 = 0x4F4C_5350_4143_4501; + const CHORD_GRACE_MS: u64 = 45; + const OTHER_MODIFIERS: CgEventFlags = + FLAG_MASK_SHIFT | FLAG_MASK_CONTROL | FLAG_MASK_ALTERNATE | FLAG_MASK_COMMAND; + const ESC_KEYCODE: i64 = 53; // IOKit hidsystem/IOLLEvent.h + ev_keymap.h. systemDefined subtype 8 carries // auxiliary control keys in data1's high 16 bits; 0..=23 are the scanned @@ -659,6 +668,12 @@ mod platform { fn CGEventTapEnable(tap: CfMachPortRef, enable: bool); fn CGEventGetIntegerValueField(event: CgEventRef, field: CgEventField) -> i64; fn CGEventGetFlags(event: CgEventRef) -> CgEventFlags; + fn CGEventGetTimestamp(event: CgEventRef) -> u64; + fn CGEventCreateCopy(event: CgEventRef) -> CgEventRef; + fn CGEventPost(tap: CgEventTapLocation, event: CgEventRef); + fn CGEventTapPostEvent(proxy: *mut c_void, event: CgEventRef); + fn CGEventSetIntegerValueField(event: CgEventRef, field: CgEventField, value: i64); + } #[link(name = "CoreFoundation", kind = "framework")] @@ -675,6 +690,73 @@ mod platform { static kCFRunLoopCommonModes: CfStringRef; } + use core_foundation::{base::CFRelease, runloop as cf}; + use std::cell::{Cell, RefCell}; + + struct BufferedSpace(CgEventRef); + + impl Drop for BufferedSpace { + fn drop(&mut self) { + unsafe { CFRelease(self.0.cast()) }; + } + } + + fn is_fn_rollover(space_at: u64, fn_at: u64, flags: CgEventFlags) -> bool { + flags & (FLAG_MASK_SECONDARY_FN | OTHER_MODIFIERS) == FLAG_MASK_SECONDARY_FN + && fn_at.abs_diff(space_at) <= CHORD_GRACE_MS * 1_000_000 + } + + // Its timer and event tap are serviced on the same run loop. The timeout + // posts once; a subsequent key flushes directly downstream ahead of that key. + #[derive(Default)] + struct FnSpaceInput { + pending: RefCell>, + timer: Cell, + fn_edge_down: Cell, + owns_fn: Cell, + } + + impl FnSpaceInput { + fn hold(&self, event: CgEventRef) -> bool { + let timer = self.timer.get(); + if timer.is_null() { + return false; + } + let buffered = unsafe { CGEventCreateCopy(event) }; + if buffered.is_null() { + return false; + } + *self.pending.borrow_mut() = Some(BufferedSpace(buffered)); + unsafe { + cf::CFRunLoopTimerSetNextFireDate( + timer, + core_foundation::date::CFAbsoluteTimeGetCurrent() + CHORD_GRACE_MS as f64 / 1000.0, + ); + } + true + } + + fn replay(&self, proxy: Option<*mut c_void>) { + let pending = self.pending.borrow_mut().take(); + if let Some(space) = pending { + crate::recording_companion::observe_space_down(); + unsafe { + if let Some(proxy) = proxy { + CGEventTapPostEvent(proxy, space.0); + } else { + CGEventSetIntegerValueField(space.0, SOURCE_USER_DATA_FIELD, REPLAYED_SPACE); + CGEventPost(SESSION_EVENT_TAP, space.0); + } + } + } + } + } + + extern "C" fn space_timeout(_: cf::CFRunLoopTimerRef, context: *mut c_void) { + let ctx = unsafe { &*(context.cast::()) }; + ctx.fn_space.replay(None); + } + struct CallbackContext { shared: Arc, tx: Sender, @@ -685,11 +767,13 @@ mod platform { /// Under Auto / Toggle, Fn dispatch is deferred until release: short press dispatches, /// long press or function-layer combos are dropped. fn_pressed_at: parking_lot::Mutex>, + fn_space: FnSpaceInput, /// (tap, runloop) refs shared with MacHotkeyAdapter. Tap re-enable on /// TAP_DISABLED_BY_TIMEOUT goes through handles.tap; adapter shutdown uses both locks. handles: Arc, } + // The callback context and its keyboard state are only dereferenced on the owning run loop. unsafe impl Send for CallbackContext {} unsafe impl Sync for CallbackContext {} @@ -714,6 +798,7 @@ mod platform { cancel_tx, combo_tx, fn_pressed_at: parking_lot::Mutex::new(None), + fn_space: FnSpaceInput::default(), handles: Arc::clone(&handles), })); @@ -743,6 +828,26 @@ mod platform { let runloop = CFRunLoopGetCurrent(); *handles.runloop.lock().unwrap() = Some(runloop); CFRunLoopAddSource(runloop, source, kCFRunLoopCommonModes); + let mut timer_context = cf::CFRunLoopTimerContext { + version: 0, + info: context.cast(), + retain: None, + release: None, + copyDescription: None, + }; + let timer = cf::CFRunLoopTimerCreate( + std::ptr::null(), + core_foundation::date::CFAbsoluteTimeGetCurrent() + 86_400.0, + 86_400.0, + 0, + 0, + space_timeout, + &mut timer_context, + ); + if !timer.is_null() { + (*context).fn_space.timer.set(timer); + cf::CFRunLoopAddTimer(runloop.cast(), timer, cf::kCFRunLoopCommonModes); + } CGEventTapEnable(tap, true); log::info!("[hotkey] CGEventTap 已启动"); @@ -751,12 +856,17 @@ mod platform { // MacHotkeyAdapter::shutdown). After it returns, the listener thread drops the context // and exits naturally. CFRunLoopRun(); + if !timer.is_null() { + cf::CFRunLoopTimerInvalidate(timer); + CFRelease(timer.cast()); + } + (*context).fn_space.replay(None); let _ = Box::from_raw(context); } } extern "C" fn tap_callback( - _proxy: *mut c_void, + proxy: *mut c_void, event_type: CgEventType, event: CgEventRef, user_info: *mut c_void, @@ -768,24 +878,71 @@ mod platform { match event_type { TAP_DISABLED_BY_TIMEOUT | TAP_DISABLED_BY_USER_INPUT => { + ctx.fn_space.replay(None); + ctx.fn_space.fn_edge_down.set(false); + ctx.fn_space.owns_fn.set(false); crate::recording_companion::reset_held(); if let Some(tap) = *ctx.handles.tap.lock().unwrap() { unsafe { CGEventTapEnable(tap, true) }; } return event; } - FLAGS_CHANGED => handle_flags_changed(ctx, event), + FLAGS_CHANGED => { + let keycode = unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) }; + let flags = unsafe { CGEventGetFlags(event) }; + let fn_down = flags & FLAG_MASK_SECONDARY_FN != 0; + let late_anchor = keycode == FN_KEYCODE + && ctx.fn_space.pending.borrow().as_ref().is_some_and(|space| unsafe { + is_fn_rollover(CGEventGetTimestamp(space.0), CGEventGetTimestamp(event), flags) + }) + && crate::recording_companion::can_wait_for_fn(); + if !late_anchor { + ctx.fn_space.replay(Some(proxy)); + } + if keycode == FN_KEYCODE { + ctx.fn_space.fn_edge_down.set(fn_down); + if !fn_down { + ctx.fn_space.owns_fn.set(false); + } + } + handle_flags_changed(ctx, keycode, flags, late_anchor); + ctx.fn_space.replay(Some(proxy)); + } KEY_DOWN => { let keycode = unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) }; - if keycode == ESC_KEYCODE && super::capsule_menu_open() { return event; } - if !ctx.shared.recording_active.load(Ordering::SeqCst) - && crate::side_aware_combo::platform::dispatch_keycode( - keycode, - false, - unsafe { CGEventGetFlags(event) }, - true, - ) + if keycode == SPACE_KEYCODE + && unsafe { CGEventGetIntegerValueField(event, SOURCE_USER_DATA_FIELD) } + == REPLAYED_SPACE { + return event; + } + ctx.fn_space.replay(Some(proxy)); + if keycode == ESC_KEYCODE && super::capsule_menu_open() { + return event; + } + let mut flags = unsafe { CGEventGetFlags(event) }; + if keycode == SPACE_KEYCODE && ctx.fn_space.fn_edge_down.get() { + flags |= FLAG_MASK_SECONDARY_FN; + } + let recording_shortcut = ctx.shared.recording_active.load(Ordering::SeqCst); + if !recording_shortcut + && keycode == SPACE_KEYCODE + && flags & (FLAG_MASK_SECONDARY_FN | OTHER_MODIFIERS) == 0 + && unsafe { CGEventGetIntegerValueField(event, AUTOREPEAT_FIELD) } == 0 + && crate::recording_companion::can_wait_for_fn() + && ctx.fn_space.hold(event) + { + return std::ptr::null_mut(); + } + if !recording_shortcut + && crate::side_aware_combo::platform::dispatch_keycode(keycode, false, flags, true) + { + if keycode == SPACE_KEYCODE + && flags & FLAG_MASK_SECONDARY_FN != 0 + && crate::recording_companion::claimed() + { + ctx.fn_space.owns_fn.set(true); + } crate::side_aware_combo::handle_companion_key_down(); note_companion_key_down(ctx); return std::ptr::null_mut(); @@ -799,6 +956,7 @@ mod platform { } } KEY_UP => { + ctx.fn_space.replay(Some(proxy)); let keycode = unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) }; if crate::side_aware_combo::platform::dispatch_keycode( keycode, @@ -813,6 +971,7 @@ mod platform { // systemDefined. While the Fn trigger is held, treat these as function-layer combos — // dictation must not start at the same time. SYSTEM_DEFINED => { + ctx.fn_space.replay(Some(proxy)); handle_system_defined_event(ctx, || system_defined_event_payload(event)); } _ => {} @@ -820,9 +979,12 @@ mod platform { event } - fn handle_flags_changed(ctx: &CallbackContext, event: CgEventRef) { - let flags = unsafe { CGEventGetFlags(event) }; - + fn handle_flags_changed( + ctx: &CallbackContext, + keycode: i64, + flags: CgEventFlags, + late_anchor: bool, + ) { // Recording mode: the browser never delivers Fn keydown to the web layer (the system // modifier is hidden), so ShortcutRecorder cannot capture it. Here the CGEventTap detects // the Fn press edge (keycode 63 + kCGEventFlagMaskSecondaryFn), reports @@ -860,8 +1022,11 @@ mod platform { .store(false, Ordering::SeqCst); } - let keycode = unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) }; crate::side_aware_combo::platform::dispatch_keycode(keycode, true, flags, false); + if late_anchor && crate::recording_companion::event("Space", true) { + drop(ctx.fn_space.pending.borrow_mut().take()); + ctx.fn_space.owns_fn.set(true); + } handle_optional_modifier_trigger( ctx, keycode, @@ -890,7 +1055,10 @@ mod platform { None, ); - handle_dictation_trigger_flags_changed(ctx, keycode, flags, std::time::Instant::now()); + // If Space owned the chord before this Fn edge, do not start a bare dictation press. + if keycode != FN_KEYCODE || !ctx.fn_space.owns_fn.get() { + handle_dictation_trigger_flags_changed(ctx, keycode, flags, std::time::Instant::now()); + } } fn fn_uses_tap_only_semantics(trigger: HotkeyTrigger, mode: HotkeyMode) -> bool { @@ -1204,6 +1372,7 @@ mod platform { cancel_tx, combo_tx, fn_pressed_at: parking_lot::Mutex::new(None), + fn_space: FnSpaceInput::default(), handles: Arc::new(MacShutdownHandles { tap: std::sync::Mutex::new(None), runloop: std::sync::Mutex::new(None), @@ -1320,6 +1489,15 @@ mod platform { assert!(drain(&rx).is_empty()); } + #[test] + fn space_first_rollover_requires_a_nearby_bare_fn_edge() { + let space = 500_000_000; + assert!(is_fn_rollover(space, space + 10_000_000, FLAG_MASK_SECONDARY_FN)); + assert!(!is_fn_rollover(space, space + 46_000_000, FLAG_MASK_SECONDARY_FN)); + assert!(!is_fn_rollover(space, space + 1, FLAG_MASK_SECONDARY_FN | FLAG_MASK_SHIFT)); + assert!(!is_fn_rollover(space, space + 1, 0)); + } + #[test] fn mac_fn_auto_short_tap_dispatches_only_after_release() { let shared = shared(HotkeyTrigger::Fn); diff --git a/openless-all/app/src-tauri/src/lib.rs b/openless-all/app/src-tauri/src/lib.rs index 52e621c03..af0bde8b3 100644 --- a/openless-all/app/src-tauri/src/lib.rs +++ b/openless-all/app/src-tauri/src/lib.rs @@ -24,6 +24,8 @@ compile_error!( ); mod android; +#[cfg(any(target_os = "macos", target_os = "windows"))] +mod activity_app_icons; mod asr; mod audio_mute; #[cfg(test)] @@ -49,6 +51,8 @@ mod native_audio_cue; #[cfg(not(mobile))] mod native_capsule; mod qa_adapter; +mod qa_window_geometry; +use qa_window_geometry::{resize_qa_frame, QA_WINDOW_BOTTOM_INSET, QA_WINDOW_HEIGHT, QA_WINDOW_WIDTH}; mod recording_companion; mod tauri_coordinator_host; // 托盘麦克风设备变更监听:macOS CoreAudio / Windows MMDevice 原生通知(空闲零唤醒), @@ -318,6 +322,7 @@ macro_rules! app_invoke_handler_desktop { commands::clear_history, commands::get_activity_stats, commands::get_activity_apps, + commands::get_activity_app_icons, commands::read_audio_recording, commands::export_audio_recording, commands::retranscribe_recording, @@ -627,6 +632,7 @@ macro_rules! app_invoke_handler_mobile { $crate::commands::clear_history, $crate::commands::get_activity_stats, $crate::commands::get_activity_apps, + $crate::commands::get_activity_app_icons, $crate::commands::read_audio_recording, $crate::commands::export_audio_recording, $crate::commands::retranscribe_recording, @@ -2316,18 +2322,6 @@ fn wait_for_app_activation(app: &AppHandle) { #[cfg(not(target_os = "macos"))] fn wait_for_app_activation(_app: &AppHandle) {} -/// QA records through the shared capsule and keeps its separate answer card open. -const QA_WINDOW_WIDTH: f64 = 480.0; -const QA_WINDOW_HEIGHT: f64 = 80.0; -const QA_WINDOW_EXPANDED_WIDTH: f64 = 720.0; -const QA_WINDOW_EXPANDED_HEIGHT: f64 = 380.0; -/// Reserve room for the independent recording capsule and its context badge. -const QA_WINDOW_BOTTOM_INSET: f64 = 96.0; -/// Expanded answers sit higher so the lower composer does not crowd the recording capsule. -const QA_WINDOW_EXPANDED_BOTTOM_INSET: f64 = 132.0; -const QA_RESULT_BOTTOM_LIFT: f64 = 40.0; -/// Bottom margin reserved for the macOS Dock (same source as the capsule). - #[derive(Clone, Copy, Debug, PartialEq)] struct LogicalMonitorFrame { x: f64, @@ -2870,29 +2864,6 @@ fn position_qa_window(window: &tauri::WebviewWindow) -> ta Ok(()) } -// Preserve a dragged window's centre and baseline; repeated result events must not drift. -fn qa_resize_origin( - x: f64, - y: f64, - old_width: f64, - old_height: f64, - width: f64, - height: f64, - was_expanded: bool, - expanded: bool, -) -> (f64, f64) { - let lift = if expanded { QA_RESULT_BOTTOM_LIFT } else { 0.0 } - - if was_expanded { - QA_RESULT_BOTTOM_LIFT - } else { - 0.0 - }; - ( - x + (old_width - width) / 2.0, - y + old_height - height - lift, - ) -} - /// Called on the native main thread by the restricted QA command. The compact /// state has a genuinely small native frame, so hidden content cannot eat clicks. pub(crate) fn set_qa_window_expanded( @@ -2903,11 +2874,10 @@ pub(crate) fn set_qa_window_expanded( .get_webview_window("qa") .ok_or_else(|| "qa_window_unavailable".to_string())?; let area = chat_window_work_area(&window, false).map_err(|_| "qa_geometry_unavailable")?; - let scale = area.map(|(_, scale)| scale).unwrap_or( - window - .scale_factor() - .map_err(|_| "qa_geometry_unavailable")?, - ); + let scale = match area { + Some((_, scale)) => scale, + None => window.scale_factor().map_err(|_| "qa_geometry_unavailable")?, + }; let position = window .inner_position() .map_err(|_| "qa_geometry_unavailable")? @@ -2916,56 +2886,26 @@ pub(crate) fn set_qa_window_expanded( .inner_size() .map_err(|_| "qa_geometry_unavailable")? .to_logical::(scale); - let was_expanded = current_size.height > QA_WINDOW_HEIGHT + 1.0; - let mut width = if expanded { - QA_WINDOW_EXPANDED_WIDTH - } else { - QA_WINDOW_WIDTH - }; - let mut height = if expanded { - QA_WINDOW_EXPANDED_HEIGHT - } else { - QA_WINDOW_HEIGHT - }; - if let Some((frame, _)) = area { - width = width.min((frame.width - 32.0).max(240.0)); - height = height.min((frame.height - 64.0).max(QA_WINDOW_HEIGHT)); - } - let (mut x, mut y) = qa_resize_origin( - position.x, - position.y, - current_size.width, - current_size.height, - width, - height, - was_expanded, + let frame = resize_qa_frame( + LogicalMonitorFrame { + x: position.x, + y: position.y, + width: current_size.width, + height: current_size.height, + }, + area.map(|(frame, _)| frame), expanded, - ); - if let Some((frame, _)) = area { - x = x.clamp( - frame.x + 16.0, - (frame.x + frame.width - width - 16.0).max(frame.x + 16.0), - ); - let bottom_inset = if expanded { - QA_WINDOW_EXPANDED_BOTTOM_INSET - } else { - QA_WINDOW_BOTTOM_INSET - }; - y = y.clamp( - frame.y + 32.0, - (frame.y + frame.height - height - bottom_inset).max(frame.y + 32.0), - ); - } + )?; window .set_position(tauri::PhysicalPosition::new( - (x * scale).round() as i32, - (y * scale).round() as i32, + (frame.x * scale).round() as i32, + (frame.y * scale).round() as i32, )) .map_err(|_| "qa_position_failed")?; window .set_size(tauri::PhysicalSize::new( - (width * scale).round() as u32, - (height * scale).round() as u32, + (frame.width * scale).round() as u32, + (frame.height * scale).round() as u32, )) .map_err(|_| "qa_resize_failed")?; Ok(()) @@ -4286,21 +4226,6 @@ mod tests { assert_eq!(capsule_visual_height(true), 140.0); } - #[test] - fn qa_resize_preserves_centre_baseline_and_user_position() { - let expanded = - super::qa_resize_origin(-700.0, 700.0, 480.0, 80.0, 720.0, 380.0, false, true); - assert_eq!(expanded, (-820.0, 360.0)); - assert_eq!( - super::qa_resize_origin(expanded.0, expanded.1, 720.0, 380.0, 720.0, 380.0, true, true), - expanded - ); - assert_eq!( - super::qa_resize_origin(expanded.0, expanded.1, 720.0, 380.0, 480.0, 80.0, true, false), - (-700.0, 700.0) - ); - } - #[test] fn logical_monitor_frame_preserves_negative_origin() { let frame = logical_monitor_frame(-2560, 720, 5120, 2880, 2.0); diff --git a/openless-all/app/src-tauri/src/qa_window_geometry.rs b/openless-all/app/src-tauri/src/qa_window_geometry.rs new file mode 100644 index 000000000..51e9678bf --- /dev/null +++ b/openless-all/app/src-tauri/src/qa_window_geometry.rs @@ -0,0 +1,172 @@ +//! Geometry policy for the native Ask Anything window. The caller owns platform I/O. + +use super::LogicalMonitorFrame; + +/// QA records through the shared capsule and keeps its separate answer card open. +pub(super) const QA_WINDOW_WIDTH: f64 = 480.0; +pub(super) const QA_WINDOW_HEIGHT: f64 = 80.0; +// Use logical pixels and a single scale when fitting the work area. +const QA_WINDOW_EXPANDED_WIDTH: f64 = 920.0; +const QA_WINDOW_EXPANDED_HEIGHT: f64 = 800.0; +const QA_REFERENCE_WORK_AREA_WIDTH: f64 = 1440.0; +const QA_REFERENCE_WORK_AREA_HEIGHT: f64 = 900.0; +// Keep the frame usable by the WebView's QA layout gate. +const QA_WINDOW_MIN_WIDTH: f64 = 220.0; +const QA_WINDOW_MIN_EXPANDED_HEIGHT: f64 = 144.0; +/// Reserve room for the independent recording capsule and its context badge. +pub(super) const QA_WINDOW_BOTTOM_INSET: f64 = 96.0; +const QA_WINDOW_EXPANDED_INSET: f64 = 16.0; +const QA_RESULT_BOTTOM_LIFT: f64 = 40.0; + +// Preserve a dragged window's centre and baseline; repeated result events must not drift. +fn qa_resize_origin( + x: f64, + y: f64, + old_width: f64, + old_height: f64, + width: f64, + height: f64, + was_expanded: bool, + expanded: bool, +) -> (f64, f64) { + let lift = if expanded { QA_RESULT_BOTTOM_LIFT } else { 0.0 } + - if was_expanded { + QA_RESULT_BOTTOM_LIFT + } else { + 0.0 + }; + ( + x + (old_width - width) / 2.0, + y + old_height - height - lift, + ) +} + +fn qa_expanded_size(area: Option) -> (f64, f64) { + let fit = area.map_or(1.0, |frame| { + let margin = 2.0 * QA_WINDOW_EXPANDED_INSET; + let available_width = (frame.width - margin).max(1.0); + let available_height = (frame.height - margin).max(1.0); + // Scale on both axes so an ultrawide monitor alone does not enlarge the card. + let preferred = (frame.width / QA_REFERENCE_WORK_AREA_WIDTH) + .min(frame.height / QA_REFERENCE_WORK_AREA_HEIGHT) + .max(1.0); + (available_width / QA_WINDOW_EXPANDED_WIDTH) + .min(available_height / QA_WINDOW_EXPANDED_HEIGHT) + .min(preferred) + }); + ( + QA_WINDOW_EXPANDED_WIDTH * fit, + QA_WINDOW_EXPANDED_HEIGHT * fit, + ) +} + +pub(super) fn resize_qa_frame( + current: LogicalMonitorFrame, + work_area: Option, + expanded: bool, +) -> Result { + let was_expanded = current.height > QA_WINDOW_HEIGHT + 1.0; + let (width, height) = if expanded { + qa_expanded_size(work_area) + } else if let Some(frame) = work_area { + ( + QA_WINDOW_WIDTH.min((frame.width - 32.0).max(240.0)), + QA_WINDOW_HEIGHT, + ) + } else { + (QA_WINDOW_WIDTH, QA_WINDOW_HEIGHT) + }; + if expanded && (width < QA_WINDOW_MIN_WIDTH || height < QA_WINDOW_MIN_EXPANDED_HEIGHT) { + return Err("qa_work_area_too_small"); + } + let (mut x, mut y) = qa_resize_origin( + current.x, + current.y, + current.width, + current.height, + width, + height, + was_expanded, + expanded, + ); + if let Some(frame) = work_area { + let x_min = frame.x + QA_WINDOW_EXPANDED_INSET; + let x_max = frame.x + frame.width - width - QA_WINDOW_EXPANDED_INSET; + x = x.clamp(x_min, x_max.max(x_min)); + let (top_inset, bottom_inset) = if expanded { + (QA_WINDOW_EXPANDED_INSET, QA_WINDOW_EXPANDED_INSET) + } else { + (32.0, QA_WINDOW_BOTTOM_INSET) + }; + let y_min = frame.y + top_inset; + let y_max = frame.y + frame.height - height - bottom_inset; + y = y.clamp(y_min, y_max.max(y_min)); + } + Ok(LogicalMonitorFrame { + x, + y, + width, + height, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expanded_qa_fits_the_work_area_with_a_single_scale() { + let fit = |width, height| { + qa_expanded_size(Some(LogicalMonitorFrame { + x: -1600.0, + y: 20.0, + width, + height, + })) + }; + assert_eq!(fit(1440.0, 900.0), (920.0, 800.0)); + assert_eq!(fit(2160.0, 1350.0), (1380.0, 1200.0)); + assert_eq!(fit(3840.0, 900.0), (920.0, 800.0)); + for (width, height) in [(800.0, 700.0), (1280.0, 480.0), (3840.0, 2160.0)] { + let (w, h) = fit(width, height); + assert!(w <= width - 32.0 + 1e-6); + assert!(h <= height - 32.0 + 1e-6); + assert!((w / h - 920.0 / 800.0).abs() < 1e-6); + } + } + + #[test] + fn qa_resize_preserves_centre_baseline_and_user_position() { + let expanded = qa_resize_origin(-700.0, 700.0, 480.0, 80.0, 920.0, 800.0, false, true); + assert_eq!(expanded, (-920.0, -60.0)); + assert_eq!( + qa_resize_origin(expanded.0, expanded.1, 920.0, 800.0, 920.0, 800.0, true, true), + expanded + ); + assert_eq!( + qa_resize_origin(expanded.0, expanded.1, 920.0, 800.0, 480.0, 80.0, true, false), + (-700.0, 700.0) + ); + } + + #[test] + fn rejects_an_expansion_that_cannot_fit_the_work_area() { + let compact = LogicalMonitorFrame { + x: 0.0, + y: 0.0, + width: 480.0, + height: 80.0, + }; + for (width, height) in [(460.0, 170.0), (1280.0, 215.0)] { + let small = LogicalMonitorFrame { + width, + height, + ..compact + }; + assert_eq!( + resize_qa_frame(compact, Some(small), true).unwrap_err(), + "qa_work_area_too_small" + ); + } + } +} diff --git a/openless-all/app/src-tauri/src/recording_companion.rs b/openless-all/app/src-tauri/src/recording_companion.rs index b25f75d7d..fff79ea39 100644 --- a/openless-all/app/src-tauri/src/recording_companion.rs +++ b/openless-all/app/src-tauri/src/recording_companion.rs @@ -126,6 +126,26 @@ pub(crate) fn sync_fn(pressed: bool) { let mut route = route().lock().unwrap(); route.state.sync_fn(pressed); } +/// Only the default bare Fn+Space chord may capture Space before its anchor arrives. +#[cfg(target_os = "macos")] +pub(crate) fn can_wait_for_fn() -> bool { + let route = route().lock().unwrap(); + !route.suspended + && route.action.is_some() + && route.state.held.is_empty() + && key(&route.state.auxiliary) == "space" + && route.state.recording.as_ref().is_some_and(|binding| { + binding.primary.eq_ignore_ascii_case("fn") && binding.modifiers.is_empty() + }) +} +/// Replayed Space must not become a new chord on autorepeat after its grace window. +#[cfg(target_os = "macos")] +pub(crate) fn observe_space_down() { + let mut route = route().lock().unwrap(); + if !route.suspended { + route.state.held.insert("space".into()); + } +} pub(crate) fn claimed() -> bool { route().lock().unwrap().state.consumed } diff --git a/openless-all/app/src-tauri/src/selection.rs b/openless-all/app/src-tauri/src/selection.rs index df99a5d93..256d832d1 100644 --- a/openless-all/app/src-tauri/src/selection.rs +++ b/openless-all/app/src-tauri/src/selection.rs @@ -64,6 +64,8 @@ pub struct SelectionContext { pub(crate) struct SelectionInsertionTarget { #[cfg(target_os = "windows")] windows: Option, + #[cfg(target_os = "windows")] + windows_app: Option, #[cfg(target_os = "macos")] macos: Option, } @@ -342,9 +344,15 @@ fn capture_selection_source_app_hint() -> Option { pub(crate) fn capture_selection_insertion_target() -> SelectionInsertionTarget { #[cfg(target_os = "windows")] { - return SelectionInsertionTarget { - windows: capture_windows_selection_target(), - }; + use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; + + let foreground = unsafe { GetForegroundWindow() }; + let windows = capture_windows_selection_target_for_window(foreground); + let windows_app = windows.map_or_else( + || windows_app_for_window(foreground), + |target| crate::activity_app_icons::app_name_for_pid(target.foreground_process_id), + ); + return SelectionInsertionTarget { windows, windows_app }; } #[cfg(target_os = "macos")] @@ -970,12 +978,19 @@ fn selection_text_matches(expected: &str, actual: Option<&str>) -> bool { #[cfg(target_os = "windows")] fn capture_windows_selection_target() -> Option { + use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; + capture_windows_selection_target_for_window(unsafe { GetForegroundWindow() }) +} + +#[cfg(target_os = "windows")] +fn capture_windows_selection_target_for_window( + foreground: windows::Win32::Foundation::HWND, +) -> Option { use windows::Win32::UI::WindowsAndMessaging::{ - GetForegroundWindow, GetGUIThreadInfo, GetWindowThreadProcessId, GUITHREADINFO, + GetGUIThreadInfo, GetWindowThreadProcessId, GUITHREADINFO, }; unsafe { - let foreground = GetForegroundWindow(); if foreground.0.is_null() { return None; } @@ -1540,33 +1555,9 @@ pub(crate) fn bundle_id_for_pid(pid: i32) -> Option { } } -#[cfg(target_os = "windows")] -fn windows_window_title(hwnd: windows::Win32::Foundation::HWND) -> Option { - use windows::Win32::UI::WindowsAndMessaging::{GetWindowTextLengthW, GetWindowTextW}; - - unsafe { - let len = GetWindowTextLengthW(hwnd); - if len <= 0 { - return None; - } - let mut buf = vec![0u16; (len + 1) as usize]; - let copied = GetWindowTextW(hwnd, &mut buf); - if copied <= 0 { - return None; - } - let title = String::from_utf16_lossy(&buf[..copied as usize]); - (!title.is_empty()).then_some(title) - } -} - #[cfg(target_os = "windows")] pub(crate) fn front_app_for_target(target: &SelectionInsertionTarget) -> Option { - use windows::Win32::Foundation::HWND; - - target - .windows - .as_ref() - .and_then(|captured| windows_window_title(HWND(captured.foreground_window as *mut _))) + target.windows_app.clone() } #[cfg(target_os = "macos")] @@ -1591,17 +1582,21 @@ pub(crate) fn front_app_for_target(_target: &SelectionInsertionTarget) -> Option } #[cfg(target_os = "windows")] -pub(crate) fn current_front_app_parts() -> (Option, Option) { - use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; +fn windows_app_for_window(hwnd: windows::Win32::Foundation::HWND) -> Option { + use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId; - // Windows has no bundle id concept; the window title is the only identity we get for free. - unsafe { - let hwnd = GetForegroundWindow(); - if hwnd.0.is_null() { - return (None, None); - } - (windows_window_title(hwnd), None) + if hwnd.0.is_null() { + return None; } + let mut pid = 0; + unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) }; + crate::activity_app_icons::app_name_for_pid(pid) +} + +#[cfg(target_os = "windows")] +pub(crate) fn current_front_app_parts() -> (Option, Option) { + use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; + (windows_app_for_window(unsafe { GetForegroundWindow() }), None) } #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))] @@ -1609,7 +1604,7 @@ pub(crate) fn current_front_app_parts() -> (Option, Option) { (None, None) } -/// The foreground app's display string, like `"Safari (com.apple.Safari)"` (the window title on +/// The foreground app's display string, like `"Safari (com.apple.Safari)"` (the executable name on /// Windows). For display / prompt use only; for decisions use [`current_front_app_parts`]. pub(crate) fn current_front_app() -> Option { match current_front_app_parts() { @@ -1813,11 +1808,12 @@ mod tests { #[test] fn windows_requires_a_captured_target_before_contacting_the_provider() { assert!(!selection_insertion_target_is_captured( - &SelectionInsertionTarget { windows: None } + &SelectionInsertionTarget::default() )); assert!(selection_insertion_target_is_captured( &SelectionInsertionTarget { windows: Some(windows_target(10)), + windows_app: None, } )); } diff --git a/openless-all/app/src/api/history.ts b/openless-all/app/src/api/history.ts index e5f64e9c8..3de0a13b2 100644 --- a/openless-all/app/src/api/history.ts +++ b/openless-all/app/src/api/history.ts @@ -7,7 +7,7 @@ import { historyStore } from '../data/history'; import * as commands from '../lib/ipc/history'; export { getActivityApps, type YearlyActivityApps } from '../data/history'; -export { readAudioRecording, type HistoryRetranscriptionResult } from '../lib/ipc/history'; +export { getActivityAppIcons, readAudioRecording, type HistoryRetranscriptionResult } from '../lib/ipc/history'; export function deleteHistoryEntry(id: string): Promise { return historyStore.mutate(() => commands.deleteHistoryEntry(id)); diff --git a/openless-all/app/src/api/interaction/index.ts b/openless-all/app/src/api/interaction/index.ts index acfa8c195..580543e88 100644 --- a/openless-all/app/src/api/interaction/index.ts +++ b/openless-all/app/src/api/interaction/index.ts @@ -21,16 +21,26 @@ export interface WarningOptions { export type NotificationState = 'info' | 'saved' | 'failed' | 'deleting' | 'deleted' | 'saving'; +export type ToastVariant = 'default' | 'success' | 'error' | 'warning' | 'info' | 'loading'; + export interface NotificationOptions { message: string; description?: string; state?: NotificationState; + variant?: ToastVariant; severity?: 'warning' | 'error'; durationMs?: number; key?: string; progress?: boolean; + /** Percent complete when known; absent means indeterminate. */ + progressValue?: number; actionLabel?: string; onAction?: () => void; + actionStyle?: 'cancel-icon' | 'below'; + actionDisabled?: boolean; + actionTitle?: string; + /** A modal may allow a pointer action only when it owns this anchor. */ + actionOwner?: () => HTMLElement | null; } export interface NotificationHandle { diff --git a/openless-all/app/src/components/ExpandingSearch.tsx b/openless-all/app/src/components/ExpandingSearch.tsx index 5e7964d53..b98888d8b 100644 --- a/openless-all/app/src/components/ExpandingSearch.tsx +++ b/openless-all/app/src/components/ExpandingSearch.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import { Icon } from './Icon'; +import { FieldFrame } from '../ui/controls/TextField'; interface ExpandingSearchProps { value: string; @@ -18,10 +19,10 @@ export function ExpandingSearch({ value, onChange, placeholder, label }: Expandi }, [value]); return ( -
+ -
+ ); } diff --git a/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts b/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts index aca79edca..b7c335090 100644 --- a/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts +++ b/openless-all/app/src/features/cloud-sync/CloudSyncSection.test.ts @@ -198,6 +198,7 @@ const dependencies: Record = { }), Icon: 'icon', SyncPasswordField: 'sync-password-field', + TextField: 'input', GithubLoginModal: 'login', StructuredDialog: 'modal', DialogHeader: 'header', @@ -275,11 +276,10 @@ const jsx = (type: unknown, props: Record) => { return props.open ? { type: 'fragment', props: { children: props.children } } : null; return { type, props }; }; -const components = factory( - ...imports.map((name) => dependencies[name]), - {}, - () => ({ jsx, jsxs: jsx }), -); +const components = factory(...imports.map((name) => dependencies[name]), {}, () => ({ + jsx, + jsxs: jsx, +})); assert.equal( components.normalizeCustomServerOrigin(' https://sync.example.com/ '), 'https://sync.example.com', diff --git a/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx b/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx index f80ee9b9b..5070cac5c 100644 --- a/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx +++ b/openless-all/app/src/features/cloud-sync/CloudSyncSection.tsx @@ -1,3 +1,4 @@ +import { TextField } from '../../ui/controls/TextField'; import { useEffect, useId, useRef, useState, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import type { NotificationHandle } from '../../api/interaction'; @@ -242,6 +243,8 @@ export function CustomSyncServerSection() { window.clearInterval(timer); }; }, [status?.syncState]); + const tokenId = useId(); + const originId = useId(); const working = busy || loading || status?.syncState === 'syncing'; const save = () => { if (saving.current || working || !prefs) return; @@ -274,15 +277,6 @@ export function CustomSyncServerSection() { if (alive.current) setBusy(false); }); }; - const inputStyle = { - width: '100%', - boxSizing: 'border-box' as const, - border: '1px solid var(--ol-line-strong)', - borderRadius: 'var(--ol-r-md)', - background: 'var(--ol-control-solid)', - color: 'var(--ol-ink)', - padding: '10px 12px', - }; return (
{t('cloudSyncE2ee.customServerTitle')}

{t('cloudSyncE2ee.customServerHint')}

- -
{loading && ( diff --git a/openless-all/app/src/features/input/RecordingInputSection.tsx b/openless-all/app/src/features/input/RecordingInputSection.tsx index 88ba4c29b..89589ec80 100644 --- a/openless-all/app/src/features/input/RecordingInputSection.tsx +++ b/openless-all/app/src/features/input/RecordingInputSection.tsx @@ -52,6 +52,7 @@ import { Button as Btn } from '../../ui/controls/Button'; import { Segmented } from '../../components/ui/Segmented'; import { SectionTitle } from '../../ui/layout/SectionTitle'; import { SettingRow, Toggle } from '../../ui/controls/SettingRow'; +import { TextField } from '../../ui/controls/TextField'; import { inputStyle } from '../../ui/controls/settingsFieldStyles'; import { MicrophoneSelect } from './MicrophoneSelect'; import { getRuntimeOS, type OS } from '../../runtime/environment'; @@ -672,7 +673,7 @@ export function RecordingInputSection({ /> {prefs.voiceActivationWakeEnabled && ( - @@ -681,7 +682,7 @@ export function RecordingInputSection({ voiceActivationWakePhrase: event.currentTarget.value, }) } - style={{ ...inputStyle, width: '100%', margin: '2px 0 8px' }} + style={{ margin: '2px 0 8px' }} /> )} @@ -693,7 +694,7 @@ export function RecordingInputSection({ /> {prefs.voiceActivationFinishEnabled && ( - @@ -702,7 +703,7 @@ export function RecordingInputSection({ voiceActivationFinishPhrase: event.currentTarget.value, }) } - style={{ ...inputStyle, width: '100%', margin: '2px 0 8px' }} + style={{ margin: '2px 0 8px' }} /> )} @@ -714,7 +715,7 @@ export function RecordingInputSection({ /> {prefs.voiceActivationTimeoutEnabled && ( - )}
diff --git a/openless-all/app/src/features/input/ShortcutsSection.tsx b/openless-all/app/src/features/input/ShortcutsSection.tsx index 49fe599ac..2ca09c911 100644 --- a/openless-all/app/src/features/input/ShortcutsSection.tsx +++ b/openless-all/app/src/features/input/ShortcutsSection.tsx @@ -1,3 +1,4 @@ +import { TextField } from '../../ui/controls/TextField'; import { useDeferredValue, useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { ShortcutRecorder } from '../../components/ShortcutRecorder'; @@ -241,7 +242,7 @@ export function ShortcutsSection() { return (
- )} - {/* ─── The top-right download progress overlay is now global (mounted at the App root, - present on every page) and no longer rendered here; in-page progress still drives - the board's detail bar via progress / sherpaDownloadProgress. ─── */} - {!embedded && ( /* Performance/quality expectation warning — in embedded mode AdvancedSection renders it itself to avoid duplication. */ {/* Top row: search (left) + username/login (center) + close × (right) */}
- {/* Search box (leftmost) */} -
- - setMyPacksQuery(e.target.value)} - autoFocus - style={{ - flex: 1, - outline: 'none', - border: 0, - background: 'transparent', - fontSize: 13, - color: 'var(--ol-ink-1)', - }} - /> -
+ setMyPacksQuery(e.target.value)} + autoFocus + style={{ flex: 1 }} + /> {/* Username + login chip. Click → GitHub OAuth Device Flow. Clicking again while signed in restarts the flow (account switch). */}
diff --git a/openless-all/app/src/features/onboarding/desktop-onboarding.css b/openless-all/app/src/features/onboarding/desktop-onboarding.css index 1cdf2bd93..8a1892da6 100644 --- a/openless-all/app/src/features/onboarding/desktop-onboarding.css +++ b/openless-all/app/src/features/onboarding/desktop-onboarding.css @@ -77,17 +77,9 @@ align-items: center; margin-top: 30px; } -.ol-guide-welcome-form input { +.ol-guide-welcome-form .ol-field { flex: 1; - min-width: 0; - border: 0; - border-bottom: 1px solid var(--ol-line); - background: transparent; - color: inherit; - border-radius: 0; - padding: 11px 0; - font: inherit; - font-size: 14px; + height: 42px; } .ol-guide button, .ol-guide select { @@ -254,13 +246,18 @@ font-size: 11px; flex-shrink: 0; } -.ol-guide-footer select { +.ol-guide-language { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + margin-inline-start: auto; color: var(--ol-ink-2); - background: var(--ol-surface); - border: 1px solid var(--ol-line); - border-radius: var(--ol-surface-radius); - padding: 6px 10px; - max-width: 160px; + font-size: 12.5px; +} +.ol-guide-language .ol-select-trigger { + width: 160px; + min-width: 0; } .ol-onboarding-layer { @@ -316,7 +313,7 @@ .ol-guide-welcome-form { flex-wrap: wrap; } - .ol-guide-welcome-form input { + .ol-guide-welcome-form .ol-field { flex-basis: 100%; } .ol-guide-welcome-form button { @@ -340,20 +337,6 @@ } } -.ol-guide-welcome-form input { - outline: none; - box-shadow: none; - transition: - border-color 200ms ease, - box-shadow 200ms ease; -} -.ol-guide-welcome-form input:focus, -.ol-guide-welcome-form input:focus-visible { - outline: none; - border-bottom-color: var(--ol-ink-2); - box-shadow: 0 1px 0 var(--ol-ink-2); -} - .ol-guide-reply > span { transform-origin: right center; animation: ol-guide-reply-enter 280ms var(--ol-motion-soft); @@ -406,9 +389,6 @@ .ol-guide-welcome-form { margin-top: 32px; } -.ol-guide-welcome-form input { - width: 100%; -} @media (max-width: 700px) { } diff --git a/openless-all/app/src/features/overview/ActivityHeatmap.tsx b/openless-all/app/src/features/overview/ActivityHeatmap.tsx index aad231023..eff86ae8a 100644 --- a/openless-all/app/src/features/overview/ActivityHeatmap.tsx +++ b/openless-all/app/src/features/overview/ActivityHeatmap.tsx @@ -1,13 +1,13 @@ import { useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import type { ActivityDay } from '../../api/contracts'; -import { useActivityApps } from '../../data/history'; import { formatLocaleDecimal, formatLocaleNumber } from '../../lib/localeFormat'; import { GitHubActivity, type Contribution, type ContributionLevel, } from '../../ui/controls/GitHubActivity'; +import { useActivityAppRanking } from './useActivityAppRanking'; import './overview.css'; function localDateKey(date: Date): string { @@ -24,14 +24,7 @@ export function ActivityHeatmap({ const { t, i18n } = useTranslation(); const locale = i18n.resolvedLanguage || i18n.language || 'en'; const year = new Date().getFullYear(); - const apps = useActivityApps(year); - const appRows = - apps.data?.status === 'available' - ? [...apps.data.rows] - .sort(([, left], [, right]) => right - left) - .slice(0, 5) - .map(([name, count]) => ({ name, count })) - : []; + const apps = useActivityAppRanking(year); const data = useMemo(() => { const first = new Date(year, 0, 1); const last = new Date(year, 11, 31); @@ -75,9 +68,9 @@ export function ActivityHeatmap({ ); const appStatus = - apps.error !== null + apps.loadFailed ? t('overview.activityAppsError') - : apps.data?.status === 'unsupported' + : apps.unsupported ? t('overview.activityAppsUnavailable') : null; @@ -122,7 +115,7 @@ export function ActivityHeatmap({ fitToWidth showMonths contributions={data.contributions} - apps={appRows} + apps={apps.rows} accent="var(--ol-accent-solid-bg)" heading={`${t('overview.activityCount', { count: data.total })} · ${year}`} label={t('overview.activityAppsLabel')} diff --git a/openless-all/app/src/features/overview/useActivityAppRanking.ts b/openless-all/app/src/features/overview/useActivityAppRanking.ts new file mode 100644 index 000000000..3072ec176 --- /dev/null +++ b/openless-all/app/src/features/overview/useActivityAppRanking.ts @@ -0,0 +1,44 @@ +import { useEffect, useMemo, useState } from 'react'; +import { getActivityAppIcons } from '../../api/history'; +import { useActivityApps } from '../../data/history'; +import { getRuntimeEnvironment } from '../../runtime/environment'; + +export function useActivityAppRanking(year: number) { + const apps = useActivityApps(year); + const rows = useMemo( + () => + apps.data?.status === 'available' + ? [...apps.data.rows] + .sort(([, left], [, right]) => right - left) + .slice(0, 5) + .map(([name, count]) => ({ name, count })) + : [], + [apps.data], + ); + const { host, os, isMobile } = getRuntimeEnvironment(); + const key = + host === 'tauri' && !isMobile && (os === 'mac' || os === 'win') && rows.length > 0 + ? JSON.stringify([year, rows.map(({ name }) => name).sort()]) + : null; + const [resolved, setResolved] = useState<{ key: string; icons: Record }>(); + useEffect(() => { + if (key === null) return; + let active = true; + void getActivityAppIcons(year) + .then((icons) => { + if (active) setResolved({ key, icons }); + }) + .catch(() => { + // Missing icons (including older hosts) must never hide the ranking. + }); + return () => { + active = false; + }; + }, [key, year]); + const icons = resolved?.key === key ? resolved.icons : undefined; + return { + rows: rows.map((row) => ({ ...row, icon: icons?.[row.name] })), + loadFailed: apps.error !== null, + unsupported: apps.data?.status === 'unsupported', + }; +} diff --git a/openless-all/app/src/features/providers/ChannelEditor.tsx b/openless-all/app/src/features/providers/ChannelEditor.tsx index 0e999e4c1..c357b8c8c 100644 --- a/openless-all/app/src/features/providers/ChannelEditor.tsx +++ b/openless-all/app/src/features/providers/ChannelEditor.tsx @@ -1,3 +1,4 @@ +import { TextField } from '../../ui/controls/TextField'; import { useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { useTranslation } from 'react-i18next'; @@ -344,7 +345,7 @@ export function ChannelEditor({ )} - { @@ -353,7 +354,7 @@ export function ChannelEditor({ }} onBlur={() => void saveName()} placeholder={t('settings.channels.namePlaceholder')} - style={{ ...inputStyle, width: '100%', maxWidth: '100%', height: 38 }} + style={{ height: 38 }} />

{t('settings.channels.nameHint')}

diff --git a/openless-all/app/src/features/providers/CredentialField.tsx b/openless-all/app/src/features/providers/CredentialField.tsx index 02d921d50..6356ee17a 100644 --- a/openless-all/app/src/features/providers/CredentialField.tsx +++ b/openless-all/app/src/features/providers/CredentialField.tsx @@ -1,3 +1,4 @@ +import { TextField } from '../../ui/controls/TextField'; import { useContext, useEffect, @@ -75,7 +76,6 @@ export function CredentialField({ [account, provider], ); const { value, loaded, dirty, status } = useSyncExternalStore(draft.subscribe, draft.snapshot); - const [revealed, setRevealed] = useState(false); const [customModelMode, setCustomModelMode] = useState(false); const onValueChangeRef = useRef(onValueChange); onValueChangeRef.current = onValueChange; @@ -83,7 +83,6 @@ export function CredentialField({ const register = form?.register; useEffect(() => { - setRevealed(false); setCustomModelMode(false); void draft.load(); return () => draft.dispose(); @@ -143,7 +142,6 @@ export function CredentialField({ } }; - const inputType = mask && !revealed ? 'password' : 'text'; const disabled = !loaded || form?.leaving; const showInsecureEndpointWarning = (account === 'ark.endpoint' || account === 'asr.endpoint' || account === 'omni.endpoint') && @@ -215,9 +213,10 @@ export function CredentialField({ }} /> ) : ( - edit(event.target.value)} @@ -225,11 +224,8 @@ export function CredentialField({ disabled={disabled} readOnly={!!endpointPresets && !!presetValue} style={{ - ...inputStyle, flex: 1, height: 38, - minWidth: 0, - maxWidth: '100%', fontFamily: mono ? 'var(--ol-font-mono)' : 'inherit', }} /> @@ -256,22 +252,14 @@ export function CredentialField({ )} {mask && ( )} - {/* readError is a persistent "field unreadable" error and stays in place to tell the user the field is unavailable; other transient states (saving / saved / saveError / copied / copyError) go through emitSaved to the window notification host instead of diff --git a/openless-all/app/src/features/providers/DeepSeekSuiteSection.tsx b/openless-all/app/src/features/providers/DeepSeekSuiteSection.tsx index d8f85bccf..568c6a2f1 100644 --- a/openless-all/app/src/features/providers/DeepSeekSuiteSection.tsx +++ b/openless-all/app/src/features/providers/DeepSeekSuiteSection.tsx @@ -1,3 +1,4 @@ +import { TextField } from '../../ui/controls/TextField'; import { useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { @@ -56,11 +57,11 @@ export function DeepSeekSuiteSection() { {config && ( <> - setConfig({ ...config, apiKey: e.target.value })} diff --git a/openless-all/app/src/features/providers/LlmProtocolFields.tsx b/openless-all/app/src/features/providers/LlmProtocolFields.tsx index c6d6b6c5a..13376871d 100644 --- a/openless-all/app/src/features/providers/LlmProtocolFields.tsx +++ b/openless-all/app/src/features/providers/LlmProtocolFields.tsx @@ -1,3 +1,4 @@ +import { TextField } from '../../ui/controls/TextField'; import { useContext, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { SelectLite } from '../../components/ui/SelectLite'; @@ -6,7 +7,6 @@ import type { LlmRequestFormat } from '../../api/providers'; import { emitSaved } from '../../lib/savedEvent'; import { Button as Btn } from '../../ui/controls/Button'; import { SettingRow, Toggle } from '../../ui/controls/SettingRow'; -import { inputStyle } from '../../ui/controls/settingsFieldStyles'; import { ProviderFormContext } from './ProviderForm'; import { @@ -128,7 +128,7 @@ export function LlmProtocolFields({ const disabled = !loaded || saving || form?.leaving; const numberField = (account: Account, label: string, placeholder: string) => ( - { if (dirty) void save(values); }} - style={{ ...inputStyle, width: '100%', maxWidth: 420 }} + style={{ maxWidth: 420 }} /> ); diff --git a/openless-all/app/src/features/providers/ProvidersSection.tsx b/openless-all/app/src/features/providers/ProvidersSection.tsx index 8135a5120..b2902137c 100644 --- a/openless-all/app/src/features/providers/ProvidersSection.tsx +++ b/openless-all/app/src/features/providers/ProvidersSection.tsx @@ -40,6 +40,7 @@ import { emitSaved } from '../../lib/savedEvent'; import { useConservativeLayout, useLayoutStack } from '../../lib/useMobileLayout'; import { Card } from '../../ui/layout/Card'; import { SectionTitle } from '../../ui/layout/SectionTitle'; +import { TextField } from '../../ui/controls/TextField'; import { SettingRow, Toggle } from '../../ui/controls/SettingRow'; import { inputStyle } from '../../ui/controls/settingsFieldStyles'; import { LocalModelPicker } from '../local-asr/settings/LocalModelPicker'; @@ -976,7 +977,7 @@ function AsrAdvancedOptions({ label={t('settings.providers.asrAdvancedChunkLabel')} desc={t('settings.providers.asrAdvancedChunkHint')} > - { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }} - style={inputStyle} + style={{ maxWidth: 360 }} /> diff --git a/openless-all/app/src/features/qa/QaComposer.tsx b/openless-all/app/src/features/qa/QaComposer.tsx new file mode 100644 index 000000000..3404b2e7b --- /dev/null +++ b/openless-all/app/src/features/qa/QaComposer.tsx @@ -0,0 +1,119 @@ +import { MicIcon, PencilLineIcon, QuoteIcon, SquareIcon } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { QaPromptBox } from './QaPromptBox'; +import { VoiceWaveform } from './chat/VoiceWaveform'; + +export type QaStatus = 'idle' | 'recording' | 'thinking' | 'error'; + +interface QaComposerProps { + value: string; + status: QaStatus; + level: number; + voiceActive: boolean; + selectionPreview: string; + busy: boolean; + micBusy: boolean; + available: boolean; + editInstructionMode: boolean; + onEditInstructionModeChange: (enabled: boolean) => void; + onChange: (value: string) => void; + onSubmit: () => void; + onToggleRecording: () => void; + onRequestKeyboard: () => void; + onCancelTurn: () => void; + cancelBusy: boolean; +} + +export function QaComposer({ + value, + status, + level, + voiceActive, + selectionPreview, + busy, + micBusy, + available, + editInstructionMode, + onEditInstructionModeChange, + onChange, + onSubmit, + onToggleRecording, + onRequestKeyboard, + onCancelTurn, + cancelBusy, +}: QaComposerProps) { + const { t } = useTranslation(); + const recording = status === 'recording'; + const generating = status === 'thinking'; + const voiceLabel = recording + ? t('qa.voiceInputPlaceholder') + : micBusy + ? t('common.loading') + : t('overview.inAppDictation.processing'); + const inputLabel = t('qa.composerPlaceholder'); + + return ( + + + + + } + feedback={ + voiceActive ? ( +
+ + {selectionPreview && ( + + + {selectionPreview} + + )} +
+ ) : !available ? ( + {t('qa.compact.browserUnavailable')} + ) : undefined + } + /> + ); +} diff --git a/openless-all/app/src/features/qa/QaPanel.tsx b/openless-all/app/src/features/qa/QaPanel.tsx index bd4f40961..137862120 100644 --- a/openless-all/app/src/features/qa/QaPanel.tsx +++ b/openless-all/app/src/features/qa/QaPanel.tsx @@ -1,24 +1,10 @@ -// Fn+Space opens this conversation immediately. Closing dismisses the native -// session, so the next press starts a new one; an open panel keeps it and can -// take the next voice turn or a typed message. -import { - useEffect, - useRef, - useState, - type ReactNode, - type KeyboardEvent as ReactKeyboardEvent, -} from 'react'; +// The recording shortcut plus the Ask companion key opens this conversation. +// Closing dismisses the native session; an open panel retains it across turns. +import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; -import { - ArrowUpIcon, - CheckIcon, - CopyIcon, - MicIcon, - PencilLineIcon, - QuoteIcon, - SquareIcon, - XIcon, -} from 'lucide-react'; +import { motion, MotionConfig } from 'framer-motion'; +import { useReducedMotion } from '../../lib/motion'; +import { CheckIcon, CopyIcon, XIcon } from 'lucide-react'; import { MessageScroller, MessageScrollerButton, @@ -29,8 +15,8 @@ import { } from './chat/ui/message-scroller'; import { OpenLessPill } from '../capsule/OpenLessCapsule'; import { QaSurface } from './QaSurface'; -import { VoiceWaveform } from './chat/VoiceWaveform'; -import { AssistantMarkdown } from './chat/markdown'; +import { QaComposer, type QaStatus } from './QaComposer'; +import { QaStreamingResponse } from './QaStreamingResponse'; import { useChatPanelLifecycle } from './chat/lifecycle'; import { chatPanelFocusKeyboard, @@ -61,14 +47,11 @@ import { useQaWindowLayout } from './useQaWindowLayout'; import { acceptQaSessionEvent, splitQaUserMessage } from '../../lib/qaMessage'; import { installMessageFollow } from '../../lib/messageFollow'; import type { QaChatMessage, QaStatePayload } from '../../api/contracts'; -import { QaAnswerFooter } from './QaAnswerFooter'; -import { qaSources } from './qaSources'; import { useQaPipeline } from './useQaPipeline'; import { stopDeepSeekReading } from './DeepSeekReadAloud'; import { copyTextToClipboard } from '../../api/files'; import './qa-panel.css'; -type Status = 'idle' | 'recording' | 'thinking' | 'error'; type Translate = ReturnType['t']; export interface QaPanelProps { embedded?: boolean; @@ -79,10 +62,11 @@ export interface QaPanelProps { export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: QaPanelProps = {}) { const { t } = useTranslation(); const modalActive = useModalActive(); + const reduced = useReducedMotion(); const pipelineMode = useQaPipeline(); const isTauri = isTauriHost(); const [messages, setMessages] = useState([]); - const [status, setStatus] = useState('idle'); + const [status, setStatus] = useState('idle'); const [errorMsg, setErrorMsg] = useState(''); const [selectionPreview, setSelectionPreview] = useState(''); const [composerText, setComposerText] = useState(''); @@ -126,7 +110,7 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: }; const loadPolishResultRef = useRef(loadPolishResult); loadPolishResultRef.current = loadPolishResult; - const statusRef = useRef('idle'); + const statusRef = useRef('idle'); const panelEpoch = useRef(0); const nativeStateEpoch = useRef(0); const submissionRef = useRef(null); @@ -146,7 +130,7 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: const delegatedDismiss = useRef(onRequestDismiss); delegatedDismiss.current = onRequestDismiss; - const changeStatus = (next: Status) => { + const changeStatus = (next: QaStatus) => { statusRef.current = next; setStatus(next); }; @@ -470,6 +454,17 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: nativeWindow: isTauri && !embedded, }); + const scaledStyle = layout.contentScale > 1 ? { zoom: layout.contentScale } : undefined; + // Motion measures projected bounds in viewport pixels but writes transforms + // in local CSS pixels. Do not apply the window's zoom to that delta twice. + const composerPoint = useCallback( + ({ x, y }: { x: number; y: number }) => ({ + x: x / layout.contentScale, + y: y / layout.contentScale, + }), + [layout.contentScale], + ); + const onClose = async () => { if (dismissRef.current) return; const request = Symbol('dismiss'); @@ -495,7 +490,8 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: } }; const onSubmitText = async () => { - const text = composerText.trim(); + const draft = composerText; + const text = draft.trim(); if ( !isTauri || !text || @@ -530,7 +526,7 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: submissionRef.current === request && activeSessionIdRef.current === originSession ) { - setComposerText((current) => current || text); + setComposerText((current) => current || draft); setErrorMsg(t('qa.compact.sendError')); changeStatus('error'); } @@ -753,20 +749,14 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: return () => window.removeEventListener('keydown', onKey); }, [embedded, modalActive, onRequestDismiss]); + const showWelcome = + !submitBusy && messages.length === 0 && status !== 'thinking' && status !== 'error'; const lastRole = messages[messages.length - 1]?.role; const questionLanded = lastRole === 'user' || streamingAnswer.length > 0; const firstQuestion = messages.find((message) => message.role === 'user'); const heading = firstQuestion ? truncate(splitQaUserMessage(firstQuestion).question, 42) : t('qa.title'); - const thoughtByIndex = new Map(); - let assistantCount = 0; - messages.forEach((message, index) => { - if (message.role !== 'assistant') return; - const seconds = thoughts[assistantCount]; - if (seconds) thoughtByIndex.set(index, seconds); - assistantCount += 1; - }); const liveActivity = status === 'thinking' && activity && !streamingAnswer ? activityLabel : undefined; const voiceActive = @@ -781,6 +771,42 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: modeBusy || editApplyBusy; + let assistantCount = 0; + const turns = messages.map((message, index) => { + const id = `m${index}`; + if (message.role === 'user') { + return ( + + + + ); + } + const elapsed = thoughts[assistantCount++]; + return ( + + + + ); + }); + if (status === 'thinking') { + // Use the final answer's slot so finishing the stream doesn't replace the response element. + const id = `m${messages.length}`; + turns.push( + + + , + ); + } + if (layout.failed && !presentationClosing) { return (
@@ -904,11 +931,15 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: {expanded && (
-

{heading}

+ {!showWelcome && ( +

{heading}

+ )}
)}
- void cancelTurnForSession(currentSession)} - cancelBusy={cancelBusy} - t={t} - /> + {showWelcome &&

{t('qa.emptyTitle')}

} + + + { + if (isTauri && !embedded) void chatPanelFocusKeyboard().catch(() => undefined); + }} + onCancelTurn={() => void cancelTurnForSession(currentSession)} + cancelBusy={cancelBusy} + available={isTauri} + /> + +
)} @@ -1035,219 +1042,16 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: ); } -function Composer({ - value, - status, - level, - voiceActive, - selectionPreview, - busy, - micBusy, - embedded, - editInstructionMode, - onEditInstructionModeChange, - onChange, - onSubmit, - onToggleRecording, - onCancelTurn, - cancelBusy, - t, -}: { - value: string; - status: Status; - level: number; - voiceActive: boolean; - selectionPreview: string; - busy: boolean; - micBusy: boolean; - embedded: boolean; - editInstructionMode: boolean; - onEditInstructionModeChange: (enabled: boolean) => void; - onChange: (value: string) => void; - onSubmit: () => void; - onToggleRecording: () => void; - onCancelTurn: () => void; - cancelBusy: boolean; - t: Translate; -}) { - const isTauri = isTauriHost(); - const composingRef = useRef(false); - const recording = status === 'recording'; - const generating = status === 'thinking'; - const onKeyDown = (event: ReactKeyboardEvent) => { - if (event.key !== 'Enter') return; - event.preventDefault(); - if (composingRef.current || event.nativeEvent.isComposing || event.keyCode === 229) return; - if (!busy && isTauri) onSubmit(); - }; - const label = recording - ? t('overview.inAppDictation.recording') - : micBusy - ? t('common.loading') - : t('overview.inAppDictation.processing'); - return ( -
{ - event.preventDefault(); - if (!composingRef.current && !busy && isTauri) onSubmit(); - }} - > -
- onChange(event.currentTarget.value)} - onKeyDown={onKeyDown} - onCompositionStart={() => { - composingRef.current = true; - }} - onCompositionEnd={() => { - composingRef.current = false; - }} - onFocus={() => { - if (isTauri && !embedded) void chatPanelFocusKeyboard().catch(() => undefined); - }} - onPointerDown={() => { - if (isTauri && !embedded) void chatPanelFocusKeyboard().catch(() => undefined); - }} - /> - {!isTauri && {t('qa.compact.browserUnavailable')}} -
-
-
-
- {voiceActive && ( - <> - - {selectionPreview && ( - - - {truncate(selectionPreview, 32)} - - )} - - )} -
- -
- - {generating ? ( - - ) : ( - - )} -
-
- ); -} - -function ThoughtStatus({ - live, - seconds, - activityLabel, - t, -}: { - live: boolean; - seconds: number; - activityLabel?: string; - t: Translate; -}) { - const elapsed = live ? t('qa.thoughtLive', { seconds }) : t('qa.thoughtDone', { seconds }); - const label = live && activityLabel ? `${elapsed} · ${activityLabel}` : elapsed; +function QaUserMessage({ message }: { message: QaChatMessage }) { + const { selection, question } = splitQaUserMessage(message); return ( -
- {live && } - {label} +
+ {selection &&
{truncate(selection, 120)}
} +

{question}

+
); } - -function MessageRow({ - index, - message, - thoughtSeconds, - t, - canReadAloud = false, -}: { - canReadAloud?: boolean; - index: number; - message: QaChatMessage; - thoughtSeconds?: number; - t: Translate; -}) { - const answer = qaSources(message.content); - if (message.role === 'user') { - const { selection, question } = splitQaUserMessage(message); - return ( - -
- {selection &&
{truncate(selection, 120)}
} -

{question}

- -
-
- ); - } - return ( - -
- {thoughtSeconds ? : null} - - -
-
- ); -} function CopyMessage({ text }: { text: string }) { const { t } = useTranslation(); const [copied, setCopied] = useState(false); diff --git a/openless-all/app/src/features/qa/QaPromptBox.tsx b/openless-all/app/src/features/qa/QaPromptBox.tsx new file mode 100644 index 000000000..7c0d710a9 --- /dev/null +++ b/openless-all/app/src/features/qa/QaPromptBox.tsx @@ -0,0 +1,223 @@ +import { AnimatePresence, motion } from 'framer-motion'; +import { ArrowUpIcon, SquareIcon } from 'lucide-react'; +import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'; +import { useReducedMotion } from '../../lib/motion'; +import './qa-prompt-box.css'; + +interface QaPromptBoxProps { + value: string; + label: string; + placeholder: string; + actions?: ReactNode; + feedback?: ReactNode; + disabled?: boolean; + readOnly?: boolean; + sendDisabled: boolean; + sendLabel: string; + stop?: { label: string; disabled: boolean; onClick: () => void }; + onChange: (value: string) => void; + onSubmit: () => void; + onRequestKeyboard: () => void; +} + +interface SentDraft { + text: string; + height: number; + scroll: number; +} + +const transition = { type: 'spring', duration: 0.4, bounce: 0.1 } as const; + +export function QaPromptBox({ + value, + label, + placeholder, + actions, + feedback, + disabled, + readOnly, + sendDisabled, + sendLabel, + stop, + onChange, + onSubmit, + onRequestKeyboard, +}: QaPromptBoxProps) { + const composing = useRef(false); + const input = useRef(null); + const measure = useRef(null); + const submitted = useRef(null); + const [flight, setFlight] = useState(null); + const [height, setHeight] = useState(24); + const reduced = useReducedMotion(); + const canSend = !disabled && !readOnly && !sendDisabled && !stop && !!value.trim(); + const submit = () => { + if (!canSend || composing.current) return; + if (!reduced && input.current) { + submitted.current = { + text: value, + height: input.current.clientHeight, + scroll: input.current.scrollTop, + }; + } + onSubmit(); + }; + + useLayoutEffect(() => { + const field = measure.current; + if (!field) return; + const resize = () => setHeight(field.offsetHeight); + resize(); + const observer = new ResizeObserver(resize); + observer.observe(field); + return () => observer.disconnect(); + }, []); + + useLayoutEffect(() => { + if (!value && submitted.current) { + setFlight(submitted.current); + submitted.current = null; + } else if (value) { + setFlight(null); + } + }, [value]); + + const tokens = flight?.text.split(/(\s+)/) ?? []; + return ( +
{ + event.preventDefault(); + submit(); + }} + > +
+ + + + {!value && !flight && ( + + )} + +