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..5f2c1e201 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', '975px'); 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,126 @@ 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', '0px'); + 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); + expect((await draft.boundingBox())!.height).toBeGreaterThan(24); + + // 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', '975px'); + await expect(panel).toHaveCSS('height', '415px'); + 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']); +}); diff --git a/openless-all/app/e2e/aux-window-geometry.spec.ts b/openless-all/app/e2e/aux-window-geometry.spec.ts index 11573df70..197100713 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; diff --git a/openless-all/app/e2e/capsule-reference-motion.spec.ts b/openless-all/app/e2e/capsule-reference-motion.spec.ts index 20fabb604..cd57eb8ee 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', '975px'); + await expect(host).toHaveCSS('height', '415px'); 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', '975px'); 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', '415px'); expect(errors).toEqual([]); }); diff --git a/openless-all/app/e2e/desktop-onboarding.spec.ts b/openless-all/app/e2e/desktop-onboarding.spec.ts index 48650561e..12e814e62 100644 --- a/openless-all/app/e2e/desktop-onboarding.spec.ts +++ b/openless-all/app/e2e/desktop-onboarding.spec.ts @@ -230,6 +230,8 @@ test('text reveals progressively without shifting layout and input focus uses an const input = page.getByRole('textbox', { name: '怎么称呼你?(选填)' }); await input.click(); await expect(input).toHaveCSS('outline-style', 'none'); + await expect(input).toHaveCSS('padding-inline-start', '12px'); + await expect(input).toHaveCSS('padding-inline-end', '12px'); const before = (await input.boundingBox())!; const reveal = await page.locator('.ol-reveal-glyph').evaluateAll((elements) => elements @@ -253,6 +255,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..25e9a2800 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,8 +66,8 @@ 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.width = `${width ?? (expanded ? 975 : 480)}px`; + host.style.height = `${height ?? (expanded ? 415 : 80)}px`; host.style.bottom = expanded ? '48px' : '8px'; }, target: { @@ -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..0ac7b1dc8 100644 --- a/openless-all/app/e2e/fixtures/native-overview.tsx +++ b/openless-all/app/e2e/fixtures/native-overview.tsx @@ -61,6 +61,14 @@ mockIPC( }); return value; } + case 'get_activity_app_icons': { + if ((args as { year: number }).year !== year) throw new Error('Expected current year'); + return params.has('icons') + ? { + Editor: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a2Z0AAAAASUVORK5CYII=', + } + : {}; + } case 'get_activity_apps': { if ((args as { year: number }).year !== year) throw new Error('Expected current year'); if (dashboard) { diff --git a/openless-all/app/e2e/interaction-polish.spec.ts b/openless-all/app/e2e/interaction-polish.spec.ts index f36bc7cd4..4a26c6ba7 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; @@ -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')); }); @@ -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', '0px'); + 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..4667bb347 100644 --- a/openless-all/app/e2e/native-overview.spec.ts +++ b/openless-all/app/e2e/native-overview.spec.ts @@ -41,6 +41,31 @@ test('native overview paints cached activity and discards an app list invalidate await expect(appReads).toHaveText('3'); }); +for (const platform of ['MacIntel', 'Win32']) { + test(`ranked apps show native images and a fallback 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`); + await page.getByRole('button', { name: 'Complete initial activity read' }).click(); + const chips = page.locator('.ol-gha-app-chips'); + const editor = chips.locator('.ol-gha-app-chip[title="Editor"]'); + await expect(editor).toContainText('Editor2'); + const icon = editor.locator('img'); + await expect(icon).toBeVisible(); + await expect + .poll(() => icon.evaluate((image: HTMLImageElement) => image.naturalWidth)) + .toBe(1); + await expect( + chips.locator('.ol-gha-app-chip[title="Browser"] .ol-gha-app-icon svg'), + ).toBeVisible(); + await page.locator('.ol-gha-toggle').click(); + await expect( + page.locator('.ol-gha-app-row').filter({ hasText: 'Editor' }).locator('img'), + ).toBeVisible(); + }); +} + async function expectDashboardFits(page: Page) { const dashboard = page.locator('.ol-overview-dashboard'); await expect(dashboard).toBeVisible(); diff --git a/openless-all/app/e2e/settings-appearance-layout.spec.ts b/openless-all/app/e2e/settings-appearance-layout.spec.ts index 615d2ee79..d189d8b19 100644 --- a/openless-all/app/e2e/settings-appearance-layout.spec.ts +++ b/openless-all/app/e2e/settings-appearance-layout.spec.ts @@ -91,3 +91,25 @@ 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).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/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/scripts/message-follow-reader.test.mjs b/openless-all/app/scripts/message-follow-reader.test.mjs index 7066439ac..1df3de05f 100644 --- a/openless-all/app/scripts/message-follow-reader.test.mjs +++ b/openless-all/app/scripts/message-follow-reader.test.mjs @@ -44,7 +44,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 diff --git a/openless-all/app/scripts/qa-panel-runtime.test.mjs b/openless-all/app/scripts/qa-panel-runtime.test.mjs index 6bdde5078..5b29722db 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( @@ -222,7 +232,6 @@ function context(native = true, embedded = false) { stopDeepSeekReading: () => { calls.stopReading++; }, - qaSources: (body) => ({ body, sources: [] }), qaCancelTurn: async () => { calls.cancelTurn++; return pending.cancelTurn?.promise; @@ -300,7 +309,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 +343,8 @@ function context(native = true, embedded = false) { events, keys, composer, + responses, + committedTurns, closePanel, beginConversation, }; @@ -347,9 +365,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 +381,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 +504,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 +590,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 +602,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 +637,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 +799,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 +822,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/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..17a1fb7ef --- /dev/null +++ b/openless-all/app/src-tauri/src/qa_window_geometry.rs @@ -0,0 +1,162 @@ +//! 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; +// 1950 × 830 at 2× display scale. Keep a shared scale when fitting smaller work areas. +const QA_WINDOW_EXPANDED_WIDTH: f64 = 975.0; +const QA_WINDOW_EXPANDED_HEIGHT: f64 = 415.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; +/// 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; + +// 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 available_width = (frame.width - 32.0).max(1.0); + let available_height = (frame.height - 32.0 - QA_WINDOW_EXPANDED_BOTTOM_INSET).max(1.0); + (available_width / QA_WINDOW_EXPANDED_WIDTH) + .min(available_height / QA_WINDOW_EXPANDED_HEIGHT) + .min(1.0) + }); + ( + 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 && 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 { + 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), + ); + } + 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), (975.0, 415.0)); + for (width, height) in [(800.0, 700.0), (1280.0, 480.0)] { + let (w, h) = fit(width, height); + assert!(w <= width - 32.0 + 1e-6); + assert!(h <= height - 164.0 + 1e-6); + assert!((w / h - 1950.0 / 830.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, 975.0, 415.0, false, true); + assert_eq!(expanded, (-947.5, 325.0)); + assert_eq!( + qa_resize_origin(expanded.0, expanded.1, 975.0, 415.0, 975.0, 415.0, true, true), + expanded + ); + assert_eq!( + qa_resize_origin(expanded.0, expanded.1, 975.0, 415.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, + }; + let small = LogicalMonitorFrame { + width: 460.0, + height: 250.0, + ..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/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/features/onboarding/DesktopOnboarding.tsx b/openless-all/app/src/features/onboarding/DesktopOnboarding.tsx index 5ffe90de4..be41abbc7 100644 --- a/openless-all/app/src/features/onboarding/DesktopOnboarding.tsx +++ b/openless-all/app/src/features/onboarding/DesktopOnboarding.tsx @@ -15,21 +15,12 @@ import { ModelSetupDialog } from './ModelSetupDialog'; import { ShortcutRecorder } from '../../components/ShortcutRecorder'; import { RevealText } from '../../components/ui/RevealText'; import { TransitionViewport } from '../../components/ui/TransitionViewport'; -import { setLocalePreference, SUPPORTED_LOCALES, type SupportedLocale } from '../../i18n'; +import { setLocalePreference } from '../../i18n'; +import { InterfaceLanguagePicker } from '../../ui/controls/InterfaceLanguagePicker'; import { ProviderLeaveContext } from '../providers/ProviderForm'; import './desktop-onboarding.css'; import { granted, useDesktopGuide } from './useDesktopGuide'; -const localeLabels = [ - '简体中文', - '繁體中文', - 'English', - '日本語', - '한국어', - 'Español', - 'Français', - 'Deutsch', -]; export function DesktopOnboarding({ onComplete }: { onComplete: () => void | Promise }) { const { t, @@ -378,24 +369,20 @@ export function DesktopOnboarding({ onComplete }: { onComplete: () => void | Pro />
{preview ? t('desktopGuide.preview') : ''} - + includeSystem={false} + side="top" + /> +
diff --git a/openless-all/app/src/features/onboarding/desktop-onboarding.css b/openless-all/app/src/features/onboarding/desktop-onboarding.css index 1cdf2bd93..103a1dcdf 100644 --- a/openless-all/app/src/features/onboarding/desktop-onboarding.css +++ b/openless-all/app/src/features/onboarding/desktop-onboarding.css @@ -85,9 +85,10 @@ background: transparent; color: inherit; border-radius: 0; - padding: 11px 0; + padding: 11px 12px; font: inherit; font-size: 14px; + line-height: 1.5; } .ol-guide button, .ol-guide select { @@ -254,13 +255,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 { 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/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..fa704de7e 100644 --- a/openless-all/app/src/features/qa/QaPanel.tsx +++ b/openless-all/app/src/features/qa/QaPanel.tsx @@ -1,24 +1,9 @@ // 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'; +import { 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 { CheckIcon, CopyIcon, XIcon } from 'lucide-react'; import { MessageScroller, MessageScrollerButton, @@ -29,8 +14,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 +46,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; @@ -82,7 +64,7 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: 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 +108,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 +128,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); }; @@ -495,7 +477,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 +513,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'); } @@ -759,14 +742,6 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: 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 +756,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 ( - {messages.map((message, index) => ( - - ))} - {status === 'thinking' && ( - -
- - {streamingAnswer && ( - - )} -
-
- )} + {turns} {status === 'error' && ( @@ -1010,7 +997,7 @@ export function QaPanel({ embedded = false, onRequestClose, onRequestDismiss }: )}
- { + if (isTauri && !embedded) void chatPanelFocusKeyboard().catch(() => undefined); + }} onCancelTurn={() => void cancelTurnForSession(currentSession)} cancelBusy={cancelBusy} - t={t} + available={isTauri} />
@@ -1035,219 +1024,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'); +function QaUserMessage({ message }: { message: QaChatMessage }) { + const { selection, question } = splitQaUserMessage(message); 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; - 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..73f1ef9bd --- /dev/null +++ b/openless-all/app/src/features/qa/QaPromptBox.tsx @@ -0,0 +1,109 @@ +import { useRef, type ReactNode } from 'react'; +import { ArrowUpIcon, SquareIcon } from 'lucide-react'; +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; +} + +export function QaPromptBox({ + value, + label, + placeholder, + actions, + feedback, + disabled, + readOnly, + sendDisabled, + sendLabel, + stop, + onChange, + onSubmit, + onRequestKeyboard, +}: QaPromptBoxProps) { + const composing = useRef(false); + const canSend = !disabled && !readOnly && !sendDisabled && !stop && !!value.trim(); + return ( +
{ + event.preventDefault(); + if (canSend && !composing.current) onSubmit(); + }} + > +
+