From b1f09429dae32bdd23e5810edb5d53b4167a7338 Mon Sep 17 00:00:00 2001 From: lvbaiqing Date: Tue, 17 Nov 2026 19:41:21 +0800 Subject: [PATCH 01/33] docs: record the approved React refactor plan --- docs/frontend-refactor/context.md | 8 +++++++ docs/frontend-refactor/plan.md | 39 +++++++++++++++++++++++++++++++ docs/frontend-refactor/tasks.md | 13 +++++++++++ 3 files changed, 60 insertions(+) create mode 100644 docs/frontend-refactor/context.md create mode 100644 docs/frontend-refactor/plan.md create mode 100644 docs/frontend-refactor/tasks.md diff --git a/docs/frontend-refactor/context.md b/docs/frontend-refactor/context.md new file mode 100644 index 000000000..27953fc80 --- /dev/null +++ b/docs/frontend-refactor/context.md @@ -0,0 +1,8 @@ +# React 前端重构:现状与证据 + +- 取证基线:Dev-1 c45430f4(2.0.2-dev.4+build.20261115);它比 6d6ced54 仅多旧规划索引。实施基线:最新远端 beta 3bddad3b,与 Dev-1 分叉(4 / 53);不整体带入该分支。逐项核对 d04e6256、205579c7、6d6ced54 的有效 UI 行为及独立功能依赖。参考 Dev-1 上的 .handoff 截图、REVIEW、REQUIREMENTS 和 docs/frontend-unification/README.md。本机实际安装为 2.0.2+build.20261115,不能用于同构建结论。 +- Chromium:Vite 1420 → index.html → public/startup.js → src/main.tsx → App;Playwright 的 5325 路径不启用普通预览框。Tauri dev 同一 Vite,打包使用 dist;macOS WKWebView、Windows WebView2、Android WebView 均运行同一 React。Harmony 由 scripts/build-harmony-frontend.sh 把 IIFE 交给 HAP,Index.ets 用 rawfile 加载,再经 OpenLessHarmonyApi 调用。Android 授权 UI 通过 @android 接入。Linux egui、iOS 原生、Windows 原生边框、宿主/后端拆分、原生输入法及远程输入独立网页不纳入。 +- 主窗口配置 macOS 1300×835、Windows 1240×800,最小各 980×640;需实测内容区。独立窗口路径有胶囊、Windows 转写轨、QA、语音编辑、选区意图;Android QA、语音编辑内嵌。Less Computer 原生仍产生窗口而 React 空白,保留兼容入口,不能假称死代码可删。 +- Dev-1 实测:Chromium 视口 1710×964,应用框 1300×835、左偏移 205px;清空历史遮罩覆盖浏览器整页。普通预览固定 100%,安装版默认 110%;Portal、祖先 overflow/clip-path、CSS zoom 和原生边界分别检查。QA 已有窗口展开请求,胶囊语言菜单按 session 申请尺寸,插入失败卡报告 presentationId。请求返回或等两帧不能直接证明已绘制。 +- Dev-1 Chromium 实测:?os=win 只使根节点为 win,部分页面仍探测 mac,MLX/IME 能力与 ⌘K 错配;mock delete/clear 列表数 8→8→8。历史页、概览、用量各自订阅后台事件;应用排行榜只跟年份更新。Core 写历史、累计活动时可能先后发 HistoryChanged;保留随手记及累计活动。服务账本另计。Harmony 有 openless:harmony-backend-change 以及听写完成,Tauri lag 无专用历史重同步信号。Harmony 清空后遍历旧条目删除音频,随手记条目可保留但音频无法由 React 保证。 +- Dev-1 定向 Playwright 30/32,两个失败是把 110% 下约 848px 的绘制宽度与未缩放 <820px 比较;设计宽约 771px。TypeScript 及 Android IPC、Harmony startup、Windows UI 和 UI follow-up 契约通过。所有证据都应在当前实施基线及最终 SHA 重跑。远端 beta CI 44066898834 的 UI/Windows/macOS/Android/Harmony 检查通过,iOS 用例失败、设备构建取消,Dev-1 无对应 CI。验收不得用 Playwright WebKit 冒充真实 WKWebView。 diff --git a/docs/frontend-refactor/plan.md b/docs/frontend-refactor/plan.md new file mode 100644 index 000000000..be3b408a9 --- /dev/null +++ b/docs/frontend-refactor/plan.md @@ -0,0 +1,39 @@ +# React 前端重构:架构与验收 + +```mermaid +flowchart LR + App["app:启动、窗口路由"] --> Features["features:业务、页面、局部状态"] + Features --> UI["ui:组件、布局、浮层、动效"] + Features --> API["api:有类型的业务操作与交互"] + API --> Data["data:共享快照、同步与写入顺序"] + API --> Runtime["runtime:宿主、能力、窗口、传输"] + Data --> Runtime + Runtime --> Native["Tauri / ArkWeb"] + Runtime --> Preview["preview:平台预设、模拟数据与事件"] +``` + +- 每个 WebView 组装一个环境和 WindowKind。原生使用实际宿主及现有能力握手,桥故障不得回退到 mock;预览统一解析 mac/win/android/harmony,平台、能力、键位、尺寸和设置共享一个来源。保留懒加载、语言就绪、早期主题和字体、静默启动。Android 以单一面板状态机管理 QA/语音编辑/返回键,取消旧会话成功后切换,新代次拒绝旧回包。沿用已有 IPC、DTO、权限和偏好持久化键;使用现有 PreferencesWriteGate 和云恢复流程。 +- 页面走分域 API;跨页快照和读写顺序归 data,选中、草稿、滚动归页面或业务控制器。每个窗口的交互控制器提供 confirm/warn/notify/openDialog;按请求 ID 收尾,现有 supersede 语义,Escape、替换、页面或窗口销毁结算为取消,只有顶层捕获键盘/外点并恢复可用焦点。UI 返回选择,业务层实际提交,成功必须在成功回包后。临时通知与持续警告保留不同语义。系统文件选择、权限及分享走适配器。沿用 Base UI 的 select/combobox/tooltip 及 Rare UI 热力图组件。 +- 历史数据服务先订阅再读快照;Tauri 按 history_changed revision 去重但不忽略不同 revision,Harmony 复用变更信号,调用完成、手动/前台刷新走同一个失效入口。记录、活动、按年应用统计各为查询键,每键最多一条在途读取;失效发生在读取期间需补读,过期结果不得提交。历史和随手记保留动作语义,清空不改累计活动和服务账本。模拟适配先提交数据再发事件,读取返回独立快照;包含普通记录、随手记和活动数据,覆盖活跃录音拒绝。后台事件不发成功通知。 +- 每窗一个未缩放的 AppViewport,内容和 Portal 共用可见边界;内容及浮层面板按同一比例各缩放一次,位置和命中用未缩放视口坐标。用 Base UI 的 container/collisionBoundary;明确滚动所有者,概览的窄小场景在看板内部重排和滚动,保留 11px 格子、3px 间距及署名。连续圆角只作用于装饰或明确变体,焦点与文案不裁切。对照尺寸由实际内容区定义,同 SHA、数据、语言、主题、字号、显示器工作区及操作顺序,测试 90/100/110%、暗/亮、长文本、开闭中、极小窗口和触屏。 +- 原生先用现有 QA 展开、胶囊语言菜单、失败卡高度能力,命令成功后通过首次测量/resize/ResizeObserver 验证当代可绘制和命中区域,再入场;退出先停交互再释放空间。保留工作区、Windows 独立轨、穿透、非激活窗焦点和退出重建语义。越界内容内部滚动或翻转,不能靠隐藏内容、破坏预览或固定延时掩盖。无现有宿主能力的事项单列。 + +| 旧路径(app/src 内) | 目标与职责 | +|---|---| +| main、App、CoreStartupScreen、FloatingShell、WindowChrome、MobileMoreSheet/MobileStyleSheet、useAppState | app/bootstrap/windowRoutes/startup;app/shell/navigation:启动、导航、窗口、Android 面板 | +| SettingsModal、pages/settings/tabs/navigation/shared/各节 | features/settings/shell/sections;导航、搜索、焦点;按外观、输入、权限、服务、模型、数据、更新拆节 | +| ChannelList、ProvidersSection、ProviderForm、CloudSyncSection、RecordingInputSection、ShortcutsSection、RemoteInputSection | features/providers、cloud-sync、input、remote-input;渠道目录、凭据草稿/写队列、恢复/协议、设备与网络控制器 | +| Overview、History、QuickNote、Usage | features/overview、history、quick-note、usage + data/history/usage;概览各指标、列表/详情/菜单/播放器/重转写润色、独立账本 | +| Style、Marketplace、Vocab、Corrections、Translation、SelectionAsk | features/style-packs、marketplace、vocabulary、corrections、translation、selection-guide;查询、编辑草稿、提交、导入导出及反馈拆分 | +| pages/LocalAsr、lib/localAsr* | features/local-asr;目录、下载准备、激活回收、试跑和详情;下载通知消费共享状态 | +| QaPanel、VoiceEditPanel、SelectionVoiceIntentPicker、QaSurface、QaAnswerFooter、DeepSeekReadAloud、chat | features/qa、voice-edit、selection-intent;会话和取消、几何、编辑器、消息和朗读;迁移 Tailwind @source | +| Capsule、CapsuleTranslationBadge、LiveTranscriptPill、OpenLessCapsule、InsertFallbackCard、LearnVocabulary、VocabSuggestionCard、AudioCue、SiriGL | features/capsule、vocabulary-learning;runtime/windows;ui/motion;会话、视图和几何分离 | +| DesktopOnboarding、Onboarding、HarmonyDictation、AutoUpdate*、GlobalDownloadProgress、CloudSyncSetupPrompt、GithubLoginModal | features/onboarding、dictation、updates、downloads、cloud-sync、accounts;保留跨域状态所有者 | +| pages/_atoms、pages/settings/shared、components/ui、Tooltip、ConfirmDialogHost、NotificationCenter、SavedToast | ui/controls/layout/overlays/feedback/motion;基础组件用参数/回调,不直连业务 | +| styles、lib/fontScale/typography/themeMode/motion/useExitMount 等 | ui/styles 和 ui/motion;领域 CSS 随功能,迁移确认可替代的覆盖 | +| lib/ipc、platform、harmonyBridge、backendEvent、types、state/HotkeySettingsContext、android/frontend | api/contracts/domains、runtime/tauri/harmony/windows、data/preferences;保留 @android 约束和 i18n/生成数据归属 | +| lib/mockData、ipc/mock-data*、散落预览参数、e2e support/fixtures | preview/profiles/fixtures/store/adapter;测试专用文件留 e2e | + +清理已证实无效的保守/可读布局空实现、SectionDesc、旧聊天波形和头像生产链。清理前审计脚本、测试、样式、路径和原生路由,不删除实际 SelectionAsk、生成资产或兼容字段。防止用移动 JSX 替代职责拆分。 + +验收覆盖 Chromium、已安装的 macOS WKWebView、Windows WebView2、Android WebView、Harmony ArkWeb 受影响场景,待验证明确列明。保留焦点与可操作性。原生窗口确认不可取得、Harmony 音频清理、后台桥缺失和独立服务账本写入信号分别跟踪,不改后端或容器来规避。 diff --git a/docs/frontend-refactor/tasks.md b/docs/frontend-refactor/tasks.md new file mode 100644 index 000000000..e19e54f7c --- /dev/null +++ b/docs/frontend-refactor/tasks.md @@ -0,0 +1,13 @@ +# React 前端重构:任务与交接 + +| 任务 | 所有权 | 完成/验收 | +|---|---|---| +| T0 基线 | QA 夹具、对照矩阵 | 复跑失败;同构建浏览器与安装版,记录 WebView、内容区、DPI、缩放、数据,观察 DOM/原生/命中 | +| T1 启动、API 和预览 | app/runtime/api/data/preferences/preview(启动路由与构建由集成负责人独占) | 平台能力/键位一致;原生握手、重建、引导、静默启动;预览事件与模拟写 | +| T2 共享 UI | ui/layout/overlays/controls/styles/motion、主窗/设置浮层约定 | Portal 边界、确认取消、Escape、栈、卸载结算和焦点还原;主题、三档缩放、动画/降动效 | +| T3 原生辅助窗口 | runtime/windows 与胶囊、QA、语音编辑、选区、失败卡 | 快速开闭/会话替换、跨屏 DPI、实际内容区/命中、穿透、Android 返回 | +| T4 历史 | api/history、data/history/usage、概览/历史/随手记/用量、preview/store | 两次提交连续事件、旧请求、清空/随手记/累计活动、后台更新、一次反馈、录音中拒绝、年度应用统计 | +| T5 领域拆分 | 设置/渠道/同步/本地 ASR、风格/市集、词库/纠错/翻译、更新与引导 | 按域接 API,草稿、权限、下载/更新、恢复、失败路径,归并组件和样式 | +| T6 集成清理与独立验收 | 构建、导入/资源路径、模块索引、契约和回归 | npm test、格式、Chromium/WebKit、原生窗口及 APK/HAP 验证;失败退回文件负责人再复测 | + +顺序:T0;T1 和 T2 公共接口对齐,随后按互斥领域并行推进 T3/T4/T5;最后 T6。共享文件唯一负责人,移动方包含文件的旧、新路径。接口和路径变更先同步消费者。主 Agent 协调;实现、集成、独立验收均显式派发 GPT-6.1 / high。当前 Dev-1 是取证基线,最新远端 beta 是实施基线,独立未合功能先走各自的 PR;从専枝推送、开 PR、结束并核查各必需 CI,缺少真机或已有宿主缺口按平台和场景列出。 From e4dcedd919b239157be880a7fd17f144ae5b1d16 Mon Sep 17 00:00:00 2001 From: lvbaiqing Date: Tue, 17 Nov 2026 19:50:32 +0800 Subject: [PATCH 02/33] test: add a frontend parity measurement probe --- .../app/e2e/support/refactor-parity.mjs | 271 ++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 openless-all/app/e2e/support/refactor-parity.mjs diff --git a/openless-all/app/e2e/support/refactor-parity.mjs b/openless-all/app/e2e/support/refactor-parity.mjs new file mode 100644 index 000000000..636891e98 --- /dev/null +++ b/openless-all/app/e2e/support/refactor-parity.mjs @@ -0,0 +1,271 @@ +import { mkdir } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; + +// Keep this function self-contained so the same read-only probe runs in a packaged WebView. +export async function readRefactorParity(selectors = {}) { + const html = document.documentElement; + const rect = ({ left, top, width, height }) => ({ x: left, y: top, width, height }); + const name = (node) => + node ? [node.localName, node.id || undefined, node.getAttribute('class') || undefined] : null; + function inspect(node) { + const box = node.getBoundingClientRect(); + const style = getComputedStyle(node); + const points = [ + [box.left + box.width / 2, box.top + box.height / 2], + [box.left + 2, box.top + 2], + [box.right - 2, box.bottom - 2], + ]; + const clippingAncestors = []; + for (let parent = node.parentElement; parent; parent = parent.parentElement) { + const { overflowX, overflowY, clipPath, contain } = getComputedStyle(parent); + if ( + [overflowX, overflowY].some((value) => value !== 'visible') || + clipPath !== 'none' || + /paint|content|strict/.test(contain) + ) { + clippingAncestors.push({ + node: name(parent), + overflowX, + overflowY, + clipPath, + contain, + rect: rect(parent.getBoundingClientRect()), + }); + } + } + return { + rect: rect(box), + intrinsic: { width: node.offsetWidth, height: node.offsetHeight }, + scroll: { width: node.scrollWidth, height: node.scrollHeight }, + paint: { + clipPath: style.clipPath, + cornerShape: style.getPropertyValue('corner-shape'), + borderRadius: style.borderRadius, + color: style.color, + background: style.backgroundColor, + visibility: style.visibility, + pointerEvents: style.pointerEvents, + }, + hit: points.map(([x, y]) => { + const top = document.elementFromPoint(x, y); + return { x, y, selfOrChild: top !== null && node.contains(top), top: name(top) }; + }), + clippingAncestors, + }; + } + + const bridge = window.__TAURI_INTERNALS__; + const label = bridge?.metadata?.currentWindow?.label; + const native = + label && bridge.invoke + ? Object.fromEntries( + await Promise.all( + ['inner_size', 'inner_position', 'outer_size', 'scale_factor'].map(async (key) => { + try { + return [key, await bridge.invoke(`plugin:window|${key}`, { label })]; + } catch { + return [key, null]; + } + }), + ), + ) + : null; + const query = new URLSearchParams(location.search); + const visual = window.visualViewport; + let selectedScale = null; + try { + selectedScale = localStorage.getItem('ol-font-scale'); + } catch { + // Some WebViews cannot read storage for an opaque origin. + } + return { + engine: navigator.userAgent, + host: bridge ? 'tauri' : window.OpenLessHarmonyApi ? 'arkweb' : 'browser', + route: query.get('window') ?? 'main', + windowLabel: label ?? null, + native, + environment: { + platform: html.dataset.olPlatform, + locale: html.lang, + theme: getComputedStyle(html).colorScheme, + layout: html.dataset.olBrowserFrame ?? 'unframed', + webdriver: navigator.webdriver, + selectedScale, + declaredScale: getComputedStyle(html).getPropertyValue('--ol-interface-scale').trim(), + rootZoom: getComputedStyle(html).zoom, + }, + viewport: { + width: innerWidth, + height: innerHeight, + dpr: devicePixelRatio, + visual: visual && { width: visual.width, height: visual.height, scale: visual.scale }, + available: { width: screen.availWidth, height: screen.availHeight }, + }, + focused: name(document.activeElement), + targets: Object.fromEntries( + Object.entries({ + root: '#root', + shell: '.ol-app-shell-bg', + dashboard: '.ol-overview-dashboard', + selected: + '.ol-overview-dashboard [aria-pressed="true"], .ol-overview-segment [aria-pressed="true"]', + heatmap: '.ol-gha', + cell: '.ol-gha-cell', + year: '.ol-overview-year', + overlay: '.ol-dialog-overlay, .ol-modal-backdrop', + dialog: '.ol-confirm-dialog, [role="dialog"]', + ...selectors, + }).map(([key, selector]) => { + const node = document.querySelector(selector); + return [key, node ? inspect(node) : null]; + }), + ), + }; +} + +async function run() { + const { values } = parseArgs({ + options: { + url: { type: 'string' }, + sha: { type: 'string' }, + inspector: { type: 'boolean' }, + selector: { type: 'string', multiple: true }, + ordinary: { type: 'boolean' }, + history: { type: 'boolean' }, + size: { type: 'string', default: '1300x835' }, + dpr: { type: 'string', default: '1' }, + locale: { type: 'string', default: 'zh-CN' }, + theme: { type: 'string', default: 'dark' }, + scale: { type: 'string', multiple: true }, + screenshots: { type: 'string' }, + timezone: { type: 'string', default: 'America/Denver' }, + date: { type: 'string', default: '2026-11-17T19:00:00Z' }, + ready: { type: 'string', default: '.ol-app-shell-bg' }, + }, + }); + const selectors = Object.fromEntries( + (values.selector ?? []).map((option) => { + const colon = option.indexOf(':'); + if (colon < 1 || colon === option.length - 1) throw new Error('--selector requires name:CSS'); + return [option.slice(0, colon), option.slice(colon + 1)]; + }), + ); + if (values.inspector) { + console.log( + `(${readRefactorParity.toString()})(${JSON.stringify(selectors)}).then(JSON.stringify).then(console.log)`, + ); + return; + } + + const [width, height] = values.size.split('x').map(Number); + const deviceScaleFactor = Number(values.dpr); + const scaleIds = { 90: 'small', 100: 'medium', 110: 'large' }; + const url = new URL(values.url ?? 'http://127.0.0.1:1420/?os=mac'); + const scales = values.scale ?? Object.keys(scaleIds); + if ( + !/^[a-f\d]{7,40}$/.test(values.sha ?? '') || + !Number.isInteger(width) || + !Number.isInteger(height) || + width < 1 || + height < 1 || + !Number.isFinite(deviceScaleFactor) || + deviceScaleFactor <= 0 || + !['light', 'dark'].includes(values.theme) || + scales.some((scale) => !scaleIds[scale]) + ) { + throw new Error( + 'Supply --sha and valid --size, --dpr, --theme, and --scale 90|100|110 values.', + ); + } + if (values.history && values.locale !== 'zh-CN') + throw new Error('--history uses the zh-CN button labels.'); + const { chromium } = await import('@playwright/test'); + const browser = await chromium.launch(); + if (values.screenshots) await mkdir(values.screenshots, { recursive: true }); + try { + for (const scale of scales) { + const page = await browser.newPage({ + viewport: { width, height }, + deviceScaleFactor, + locale: values.locale, + colorScheme: values.theme, + timezoneId: values.timezone, + }); + await page.clock.setFixedTime(new Date(values.date)); + await page.addInitScript( + ({ locale, theme, scaleId, ordinary }) => { + localStorage.setItem('ol.locale', locale); + localStorage.setItem('ol.theme', theme); + localStorage.setItem('ol-font-scale', scaleId); + if (ordinary) Object.defineProperty(navigator, 'webdriver', { get: () => false }); + }, + { + locale: values.locale, + theme: values.theme, + scaleId: scaleIds[scale], + ordinary: values.ordinary, + }, + ); + await page.goto(url.toString()); + await page.locator(values.ready).first().waitFor({ state: 'visible' }); + await page.evaluate(async () => { + await document.fonts.ready; + }); + async function capture(stage, systemDialog = null) { + await page.evaluate(async () => { + // Continuous indicators never settle and do not affect these measurements. + const transitions = document + .getAnimations() + .filter( + (animation) => + animation.playState === 'running' && + Number.isFinite(animation.effect?.getComputedTiming().endTime), + ); + await Promise.allSettled(transitions.map((animation) => animation.finished)); + }); + if (values.screenshots) + await page.screenshot({ + path: resolve(values.screenshots, `${stage}-${scale}.png`), + animations: 'disabled', + }); + console.log( + JSON.stringify({ + sha: values.sha, + fixture: 'repository mock (fixed JS date)', + date: values.date, + url: url.toString(), + stage, + requestedScale: Number(scale), + systemDialog, + ...(await page.evaluate(readRefactorParity, selectors)), + }), + ); + } + await capture('initial'); + if (values.history) { + await page + .locator('.ol-sidebar-surface') + .getByRole('button', { name: '历史', exact: true }) + .click(); + let systemDialog = null; + page.once('dialog', async (dialog) => { + systemDialog = dialog.type(); + await dialog.dismiss(); + }); + await page.getByRole('button', { name: '清空', exact: true }).click(); + if (!systemDialog) await page.getByRole('button', { name: '取消', exact: true }).waitFor(); + await capture('clear-confirm', systemDialog); + if (!systemDialog) await page.getByRole('button', { name: '取消', exact: true }).click(); + } + await page.close(); + } + } finally { + await browser.close(); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + await run(); +} From fbcf76c94c8d937990bba3732223509b498c6a00 Mon Sep 17 00:00:00 2001 From: lvbaiqing Date: Tue, 17 Nov 2026 19:55:24 +0800 Subject: [PATCH 03/33] refactor(frontend): centralize the runtime and shared history snapshots --- openless-all/app/src/api/channels.ts | 1 + openless-all/app/src/api/cloud-sync.ts | 2 + openless-all/app/src/api/contracts.ts | 2 + openless-all/app/src/api/corrections.ts | 9 + openless-all/app/src/api/dictation.ts | 2 + openless-all/app/src/api/files.ts | 4 + openless-all/app/src/api/history.ts | 43 +++++ openless-all/app/src/api/hotkeys.ts | 2 + openless-all/app/src/api/input.ts | 3 + openless-all/app/src/api/marketplace.ts | 3 + openless-all/app/src/api/permissions.ts | 9 + openless-all/app/src/api/preferences.ts | 9 + openless-all/app/src/api/providers.ts | 4 + openless-all/app/src/api/qa.ts | 2 + openless-all/app/src/api/selection.ts | 3 + openless-all/app/src/api/startup.ts | 2 + openless-all/app/src/api/style-packs.ts | 1 + openless-all/app/src/api/updates.ts | 1 + openless-all/app/src/api/usage.ts | 9 + openless-all/app/src/api/vocabulary.ts | 9 + openless-all/app/src/api/voice-edit.ts | 1 + openless-all/app/src/data/history.ts | 146 +++++++++++++++ .../app/src/data/preferences-write-gate.ts | 92 ++++++++++ openless-all/app/src/data/preferences.tsx | 168 ++++++++++++++++++ openless-all/app/src/data/snapshot-query.ts | 73 ++++++++ openless-all/app/src/data/usage.ts | 14 ++ openless-all/app/src/lib/harmonyBridge.ts | 4 +- openless-all/app/src/lib/hotkey.ts | 11 +- .../app/src/lib/ipc/asr-credentials.ts | 9 +- openless-all/app/src/lib/ipc/dictation.ts | 10 +- openless-all/app/src/lib/ipc/history.ts | 23 ++- openless-all/app/src/lib/ipc/hotkeys.ts | 15 +- openless-all/app/src/lib/ipc/index.ts | 5 +- openless-all/app/src/lib/ipc/mock-data.ts | 56 ++---- openless-all/app/src/lib/ipc/service-usage.ts | 17 +- openless-all/app/src/lib/ipc/settings.ts | 11 +- openless-all/app/src/lib/ipc/shared.ts | 113 ++---------- openless-all/app/src/lib/ipc/utils.ts | 33 ++-- openless-all/app/src/lib/platform.ts | 141 +-------------- openless-all/app/src/preview/events.ts | 14 ++ openless-all/app/src/preview/history.ts | 149 ++++++++++++++++ openless-all/app/src/preview/profiles.ts | 83 +++++++++ openless-all/app/src/preview/usage.ts | 47 +++++ openless-all/app/src/runtime/domain-events.ts | 39 ++++ openless-all/app/src/runtime/environment.ts | 109 ++++++++++++ openless-all/app/src/runtime/platform.ts | 49 +++++ openless-all/app/src/runtime/transport.ts | 82 +++++++++ .../app/src/state/HotkeySettingsContext.tsx | 168 +----------------- .../app/src/state/preferencesWriteGate.ts | 87 +-------- 49 files changed, 1300 insertions(+), 589 deletions(-) create mode 100644 openless-all/app/src/api/channels.ts create mode 100644 openless-all/app/src/api/cloud-sync.ts create mode 100644 openless-all/app/src/api/contracts.ts create mode 100644 openless-all/app/src/api/corrections.ts create mode 100644 openless-all/app/src/api/dictation.ts create mode 100644 openless-all/app/src/api/files.ts create mode 100644 openless-all/app/src/api/history.ts create mode 100644 openless-all/app/src/api/hotkeys.ts create mode 100644 openless-all/app/src/api/input.ts create mode 100644 openless-all/app/src/api/marketplace.ts create mode 100644 openless-all/app/src/api/permissions.ts create mode 100644 openless-all/app/src/api/preferences.ts create mode 100644 openless-all/app/src/api/providers.ts create mode 100644 openless-all/app/src/api/qa.ts create mode 100644 openless-all/app/src/api/selection.ts create mode 100644 openless-all/app/src/api/startup.ts create mode 100644 openless-all/app/src/api/style-packs.ts create mode 100644 openless-all/app/src/api/updates.ts create mode 100644 openless-all/app/src/api/usage.ts create mode 100644 openless-all/app/src/api/vocabulary.ts create mode 100644 openless-all/app/src/api/voice-edit.ts create mode 100644 openless-all/app/src/data/history.ts create mode 100644 openless-all/app/src/data/preferences-write-gate.ts create mode 100644 openless-all/app/src/data/preferences.tsx create mode 100644 openless-all/app/src/data/snapshot-query.ts create mode 100644 openless-all/app/src/data/usage.ts create mode 100644 openless-all/app/src/preview/events.ts create mode 100644 openless-all/app/src/preview/history.ts create mode 100644 openless-all/app/src/preview/profiles.ts create mode 100644 openless-all/app/src/preview/usage.ts create mode 100644 openless-all/app/src/runtime/domain-events.ts create mode 100644 openless-all/app/src/runtime/environment.ts create mode 100644 openless-all/app/src/runtime/platform.ts create mode 100644 openless-all/app/src/runtime/transport.ts diff --git a/openless-all/app/src/api/channels.ts b/openless-all/app/src/api/channels.ts new file mode 100644 index 000000000..d8c9bb0aa --- /dev/null +++ b/openless-all/app/src/api/channels.ts @@ -0,0 +1 @@ +export * from '../lib/ipc/channels'; diff --git a/openless-all/app/src/api/cloud-sync.ts b/openless-all/app/src/api/cloud-sync.ts new file mode 100644 index 000000000..f328f23f0 --- /dev/null +++ b/openless-all/app/src/api/cloud-sync.ts @@ -0,0 +1,2 @@ +export * from '../lib/ipc/cloud-sync'; +export * from '../lib/ipc/cloud-sync-e2ee'; diff --git a/openless-all/app/src/api/contracts.ts b/openless-all/app/src/api/contracts.ts new file mode 100644 index 000000000..d7d774d67 --- /dev/null +++ b/openless-all/app/src/api/contracts.ts @@ -0,0 +1,2 @@ +export type * from '../lib/types'; +export type { BackendEvent, TranscriptDelta, TranscriptSnapshot } from '../lib/backendEvent'; diff --git a/openless-all/app/src/api/corrections.ts b/openless-all/app/src/api/corrections.ts new file mode 100644 index 000000000..38876a409 --- /dev/null +++ b/openless-all/app/src/api/corrections.ts @@ -0,0 +1,9 @@ +export { + listCorrectionRules, + addCorrectionRule, + acceptPendingCorrection, + rejectPendingCorrection, + dismissVocabSuggestions, + removeCorrectionRule, + setCorrectionRuleEnabled, +} from '../lib/ipc/vocab'; diff --git a/openless-all/app/src/api/dictation.ts b/openless-all/app/src/api/dictation.ts new file mode 100644 index 000000000..1fbb99e75 --- /dev/null +++ b/openless-all/app/src/api/dictation.ts @@ -0,0 +1,2 @@ +export * from '../lib/ipc/dictation'; +export { dismissInsertFallbackCard, reportInsertFallbackCardHeight } from '../lib/ipc/vocab'; diff --git a/openless-all/app/src/api/files.ts b/openless-all/app/src/api/files.ts new file mode 100644 index 000000000..039d039ed --- /dev/null +++ b/openless-all/app/src/api/files.ts @@ -0,0 +1,4 @@ +export { openExternal, exportErrorLog, logClientError, debugReadCursorContext } from '../lib/ipc/utils'; +export { copyTextToClipboard } from '../lib/ipc/vocab'; +export { importStylePackFromZip, exportStylePackToZip } from '../lib/ipc/style-packs'; +export { openAndroidLocalMigration } from '../lib/ipc/local-migration'; diff --git a/openless-all/app/src/api/history.ts b/openless-all/app/src/api/history.ts new file mode 100644 index 000000000..6ef2ddba8 --- /dev/null +++ b/openless-all/app/src/api/history.ts @@ -0,0 +1,43 @@ +import type { ActivityDay, DictationSession } from './contracts'; +import type { QuerySnapshot } from '../data/snapshot-query'; +import { historyStore } from '../data/history'; +import * as commands from '../lib/ipc/history'; + +export { getActivityApps, supportsActivityApps, type YearlyActivityApps } from '../data/history'; +export { + readAudioRecording, + type HistoryRetranscriptionResult, +} from '../lib/ipc/history'; + +export function deleteHistoryEntry(id: string): Promise { + return historyStore.mutate(() => commands.deleteHistoryEntry(id)); +} + +export function clearHistory(): Promise { + return historyStore.mutate(commands.clearHistory); +} + +export function retranscribeRecording(sessionId: string) { + return historyStore.mutate( + () => commands.retranscribeRecording(sessionId), + (result) => result.updatedEntry !== null, + ); +} + +export function applyQuickNoteRepolish(sessionId: string, text: string, stylePackId?: string) { + return historyStore.mutate(() => commands.applyQuickNoteRepolish(sessionId, text, stylePackId)); +} + +function readData({ data, error }: QuerySnapshot): T { + if (error !== null) throw error; + if (data === null) throw new Error('History snapshot is unavailable'); + return data; +} + +export async function listHistory(): Promise { + return readData(await historyStore.records.load()); +} + +export async function getActivityStats(): Promise { + return readData(await historyStore.activity.load()); +} diff --git a/openless-all/app/src/api/hotkeys.ts b/openless-all/app/src/api/hotkeys.ts new file mode 100644 index 000000000..30063b142 --- /dev/null +++ b/openless-all/app/src/api/hotkeys.ts @@ -0,0 +1,2 @@ +export * from '../lib/ipc/hotkeys'; +export * from '../lib/hotkey'; diff --git a/openless-all/app/src/api/input.ts b/openless-all/app/src/api/input.ts new file mode 100644 index 000000000..4b44cc78c --- /dev/null +++ b/openless-all/app/src/api/input.ts @@ -0,0 +1,3 @@ +export * from '../lib/ipc/devices'; +export * from '../lib/ipc/android-audio'; +export * from '../lib/ipc/remote-server'; diff --git a/openless-all/app/src/api/marketplace.ts b/openless-all/app/src/api/marketplace.ts new file mode 100644 index 000000000..27cf6bdad --- /dev/null +++ b/openless-all/app/src/api/marketplace.ts @@ -0,0 +1,3 @@ +export * from '../lib/ipc/marketplace'; +export * from '../lib/ipc/marketplace-cache'; +export * from '../lib/ipc/github-oauth'; diff --git a/openless-all/app/src/api/permissions.ts b/openless-all/app/src/api/permissions.ts new file mode 100644 index 000000000..ddc1785fe --- /dev/null +++ b/openless-all/app/src/api/permissions.ts @@ -0,0 +1,9 @@ +export * from '../lib/ipc/permissions'; +export { + getAndroidOverlayStatus, + requestAndroidOverlayPermission, + showAndroidOverlay, + hideAndroidOverlay, + getAndroidAccessibilityStatus, + requestAndroidAccessibilityPermission, +} from '../lib/ipc/platform-exports'; diff --git a/openless-all/app/src/api/preferences.ts b/openless-all/app/src/api/preferences.ts new file mode 100644 index 000000000..2dc688bf1 --- /dev/null +++ b/openless-all/app/src/api/preferences.ts @@ -0,0 +1,9 @@ +export { + getSettings, + getSettingsSnapshot, + getDefaultStyleSystemPrompts, + updateSettingFields, + setSettings, + type SettingsSnapshot, +} from '../lib/ipc/settings'; +export { listenPreferenceChanges } from '../runtime/domain-events'; diff --git a/openless-all/app/src/api/providers.ts b/openless-all/app/src/api/providers.ts new file mode 100644 index 000000000..5b4ae04a7 --- /dev/null +++ b/openless-all/app/src/api/providers.ts @@ -0,0 +1,4 @@ +export * from '../lib/ipc/providers'; +export * from '../lib/ipc/asr-credentials'; +export * from '../lib/ipc/channels'; +export * from '../lib/ipc/siwc'; diff --git a/openless-all/app/src/api/qa.ts b/openless-all/app/src/api/qa.ts new file mode 100644 index 000000000..d264d6aea --- /dev/null +++ b/openless-all/app/src/api/qa.ts @@ -0,0 +1,2 @@ +export * from '../lib/ipc/qa'; +export { chatPanelFocusKeyboard } from '../lib/ipc/chat-panel'; diff --git a/openless-all/app/src/api/selection.ts b/openless-all/app/src/api/selection.ts new file mode 100644 index 000000000..184c8d7c9 --- /dev/null +++ b/openless-all/app/src/api/selection.ts @@ -0,0 +1,3 @@ +export * from '../lib/ipc/selection-polish-preview'; +export * from '../lib/ipc/selection-voice-preview'; +export * from '../lib/ipc/expression'; diff --git a/openless-all/app/src/api/startup.ts b/openless-all/app/src/api/startup.ts new file mode 100644 index 000000000..063a7749a --- /dev/null +++ b/openless-all/app/src/api/startup.ts @@ -0,0 +1,2 @@ +export { BACKEND_CONTRACT_VERSION, getStartupSnapshot, type StartupSnapshot } from '../lib/ipc/settings'; +export { takeSplashPlayback, SPLASH_MAJOR } from '../lib/ipc/splash'; diff --git a/openless-all/app/src/api/style-packs.ts b/openless-all/app/src/api/style-packs.ts new file mode 100644 index 000000000..9b97654c5 --- /dev/null +++ b/openless-all/app/src/api/style-packs.ts @@ -0,0 +1 @@ +export * from '../lib/ipc/style-packs'; diff --git a/openless-all/app/src/api/updates.ts b/openless-all/app/src/api/updates.ts new file mode 100644 index 000000000..63452b011 --- /dev/null +++ b/openless-all/app/src/api/updates.ts @@ -0,0 +1 @@ +export * from '../lib/ipc/updater'; diff --git a/openless-all/app/src/api/usage.ts b/openless-all/app/src/api/usage.ts new file mode 100644 index 000000000..b5217aec2 --- /dev/null +++ b/openless-all/app/src/api/usage.ts @@ -0,0 +1,9 @@ +import { serviceUsageQuery } from '../data/usage'; +import { clearServiceUsage as clear } from '../lib/ipc/service-usage'; + +export { getServiceUsage, supportsServiceUsage, type ServiceUsageRecord, type ServiceUsageSnapshot } from '../lib/ipc/service-usage'; + +export async function clearServiceUsage(): Promise { + await clear(); + serviceUsageQuery.invalidate(); +} diff --git a/openless-all/app/src/api/vocabulary.ts b/openless-all/app/src/api/vocabulary.ts new file mode 100644 index 000000000..69dceac6f --- /dev/null +++ b/openless-all/app/src/api/vocabulary.ts @@ -0,0 +1,9 @@ +export { + listVocab, + addVocab, + removeVocab, + setVocabEnabled, + updateVocab, + listVocabPresets, + saveVocabPresets, +} from '../lib/ipc/vocab'; diff --git a/openless-all/app/src/api/voice-edit.ts b/openless-all/app/src/api/voice-edit.ts new file mode 100644 index 000000000..02dbc7eb8 --- /dev/null +++ b/openless-all/app/src/api/voice-edit.ts @@ -0,0 +1 @@ +export * from '../lib/ipc/voice-edit-session'; diff --git a/openless-all/app/src/data/history.ts b/openless-all/app/src/data/history.ts new file mode 100644 index 000000000..ef97f52a4 --- /dev/null +++ b/openless-all/app/src/data/history.ts @@ -0,0 +1,146 @@ +import { useSyncExternalStore } from 'react'; +import type { ActivityDay, DictationSession } from '../api/contracts'; +import { getActivityStats, listHistory } from '../lib/ipc/history'; +import { previewHistory } from '../preview/history'; +import { listenHistoryChanges } from '../runtime/domain-events'; +import { isPreviewHost } from '../runtime/environment'; +import { SnapshotQuery } from './snapshot-query'; + +export type YearlyActivityApps = + | { status: 'available'; rows: [name: string, count: number][] } + | { status: 'unsupported' }; + +export function supportsActivityApps(): boolean { + // The current native activity DTO contains counts, characters, and duration only. + return isPreviewHost(); +} + +export async function getActivityApps(year: number): Promise { + return supportsActivityApps() + ? { status: 'available', rows: previewHistory.getActivityApps(year) } + : { status: 'unsupported' }; +} + +interface HistorySource { + listHistory(): Promise; + getActivityStats(): Promise; + getActivityApps(year: number): Promise; + listen(onChange: (revision?: number) => void): Promise<() => void>; +} + +export function createHistoryStore(source: HistorySource) { + let subscribed: Promise<() => void> | null = null; + let writes = 0; + let pendingWrites: Promise | null = null; + let resolveWrites: (() => void) | undefined; + const revisions = new Set(); + const years = new Map>(); + const invalidate = () => { + records.invalidate(); + activity.invalidate(); + for (const query of years.values()) query.invalidate(); + }; + const start = (): Promise<() => void> => { + subscribed ??= source.listen((revision) => { + if (revision !== undefined) { + // Concurrent producers can emit different revisions out of numeric order. + if (revisions.has(revision)) return; + revisions.add(revision); + } + invalidate(); + }).catch((error: unknown) => { + subscribed = null; + throw error; + }); + return subscribed; + }; + const awaitSubscription = async () => { await start(); }; + const records = new SnapshotQuery(source.listHistory, async () => { + await awaitSubscription(); + while (pendingWrites) await pendingWrites; + }); + const activity = new SnapshotQuery(source.getActivityStats, awaitSubscription); + const apps = (year: number) => { + let query = years.get(year); + if (!query) { + query = new SnapshotQuery(() => source.getActivityApps(year), awaitSubscription); + years.set(year, query); + } + return query; + }; + + return { + start: awaitSubscription, + records, + activity, + apps, + invalidate, + refreshRecords: records.refresh, + refreshActivity: activity.refresh, + refreshApps: (year: number) => apps(year).refresh(), + refresh: () => Promise.all([ + records.refresh(), + activity.refresh(), + ...Array.from(years.values(), (query) => query.refresh()), + ]), + async mutate(command: () => Promise, changesRecords: (result: T) => boolean = () => true): Promise { + if (writes++ === 0) pendingWrites = new Promise((resolve) => { resolveWrites = resolve; }); + try { + // Pair any push emitted during the invocation with its post-commit refresh. + // A listener failure must not substitute for the actual command result. + await start().catch(() => undefined); + const result = await command(); + if (changesRecords(result)) records.invalidate(); + return result; + } finally { + if (--writes === 0) { + pendingWrites = null; + resolveWrites?.(); + resolveWrites = undefined; + } + } + }, + }; +} + +export const historyStore = createHistoryStore({ + listHistory, + getActivityStats, + getActivityApps, + listen(onChange) { + return listenHistoryChanges(onChange).then((unlisten) => { + // Keep one native subscription for this WebView; tab switches don't leave a gap. + if (typeof window !== 'undefined') { + const regainFocus = () => { + if (document.visibilityState !== 'hidden') onChange(); + }; + window.addEventListener('focus', regainFocus); + window.addEventListener('pageshow', regainFocus); + document.addEventListener('visibilitychange', regainFocus); + return () => { + unlisten(); + window.removeEventListener('focus', regainFocus); + window.removeEventListener('pageshow', regainFocus); + document.removeEventListener('visibilitychange', regainFocus); + }; + } + return unlisten; + }); + }, +}); + +function useQuery(query: SnapshotQuery) { + return useSyncExternalStore(query.subscribe, query.getSnapshot, query.getSnapshot); +} + +export function useHistoryRecords() { + return useQuery(historyStore.records); +} + +export function useActivityStats() { + return useQuery(historyStore.activity); +} + +export function useActivityApps(year: number) { + return useQuery(historyStore.apps(year)); +} diff --git a/openless-all/app/src/data/preferences-write-gate.ts b/openless-all/app/src/data/preferences-write-gate.ts new file mode 100644 index 000000000..45e86de69 --- /dev/null +++ b/openless-all/app/src/data/preferences-write-gate.ts @@ -0,0 +1,92 @@ +export interface PreferenceSnapshot { + preferences: T; + revision: number; +} +export type PreferenceEdits = Record; + +export function preferenceEdits(previous: unknown, next: unknown, path = ''): PreferenceEdits { + if (JSON.stringify(previous) === JSON.stringify(next)) return {}; + if ( + previous && + next && + typeof previous === 'object' && + typeof next === 'object' && + !Array.isArray(previous) && + !Array.isArray(next) + ) { + const before = previous as Record, + after = next as Record; + return Object.assign( + {}, + ...[...new Set([...Object.keys(before), ...Object.keys(after)])].map((key) => + preferenceEdits( + before[key], + after[key], + `${path}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`, + ), + ), + ); + } + return { [path]: next ?? null }; +} + +function clonePreference(value: T): T { + // Preference values are a JSON wire contract, including on older WebViews. + if (typeof structuredClone === 'function') return structuredClone(value); + return value === undefined ? value : JSON.parse(JSON.stringify(value)) as T; +} + +function applyEdits(value: T, edits: PreferenceEdits): T { + const result = clonePreference(value); + for (const [path, value] of Object.entries(edits)) { + const keys = path + .slice(1) + .split('/') + .map((key) => key.replace(/~1/g, '/').replace(/~0/g, '~')); + let target = result as Record; + let compatible = true; + for (const key of keys.slice(0, -1)) { + const child = target[key]; + if (!child || typeof child !== 'object' || Array.isArray(child)) { + compatible = false; + break; + } + target = child as Record; + } + // A concurrent removal of an optional object wins until the backend rejects this stale edit. + if (compatible) target[keys[keys.length - 1]] = clonePreference(value); + } + return result; +} + +/** Backend revisions order snapshots; pending edits belong to individual requests. */ +export class PreferencesWriteGate { + private saved: PreferenceSnapshot | null = null; + private nextId = 0; + private pending = new Map(); + + receiveIncoming(snapshot: PreferenceSnapshot): T { + if (!this.saved || snapshot.revision >= this.saved.revision) this.saved = snapshot; + return this.current(); + } + + beginWrite(previous: T, next: T) { + const id = ++this.nextId; + const edits = preferenceEdits(previous, next); + this.pending.set(id, edits); + return { id, edits }; + } + + finishWrite(id: number, snapshot?: PreferenceSnapshot): T { + if (snapshot) this.receiveIncoming(snapshot); + this.pending.delete(id); + return this.current(); + } + + current(): T { + if (!this.saved) throw new Error('preferences not loaded'); + let value = this.saved.preferences; + for (const edits of this.pending.values()) value = applyEdits(value, edits); + return value; + } +} diff --git a/openless-all/app/src/data/preferences.tsx b/openless-all/app/src/data/preferences.tsx new file mode 100644 index 000000000..5f5dbad9e --- /dev/null +++ b/openless-all/app/src/data/preferences.tsx @@ -0,0 +1,168 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from 'react'; +import { getHotkeyCapability } from '../api/hotkeys'; +import { getSettingsSnapshot, listenPreferenceChanges, updateSettingFields } from '../api/preferences'; +import type { HotkeyBinding, HotkeyCapability, UserPreferences } from '../api/contracts'; +import { applyThemeFromPreference } from '../lib/themeMode'; +import { applyStackedLayoutFromPrefs } from '../lib/stackedLayout'; +import { applyConservativeLayout } from '../lib/conservativeLayout'; +import { emitSaved } from '../lib/savedEvent'; +import { PreferencesWriteGate } from './preferences-write-gate'; + +interface HotkeySettingsContextValue { + prefs: UserPreferences | null; + hotkey: HotkeyBinding | null; + capability: HotkeyCapability | null; + loading: boolean; + error: string | null; + refresh: () => Promise; + updatePrefs: ( + next: UserPreferences | ((current: UserPreferences) => UserPreferences), + ) => Promise; +} + +const HotkeySettingsContext = createContext(null); + +const errorMessage = (error: unknown) => String(error instanceof Error ? error.message : error); + +export function HotkeySettingsProvider({ children }: { children: ReactNode }) { + const [prefs, setPrefs] = useState(null); + const [capability, setCapability] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const latestPrefsRef = useRef(null); + const persistQueueRef = useRef>(Promise.resolve()); + const gate = useRef(new PreferencesWriteGate()); + const readRequest = useRef | null>(null); + const readAgain = useRef(false); + const mounted = useRef(false); + + const applyPrefs = useCallback((value: UserPreferences) => { + latestPrefsRef.current = value; + if (!mounted.current) return; + setPrefs(value); + applyThemeFromPreference(value.themeMode ?? 'system'); + applyStackedLayoutFromPrefs(value.stackedRowLayout); + applyConservativeLayout(value.conservativeLayout === true); + }, []); + + // Events invalidate the snapshot; values alone cannot identify who wrote them. + const reloadPreferences = useCallback((): Promise => { + readAgain.current = true; + if (readRequest.current) return readRequest.current; + const task = (async () => { + do { + readAgain.current = false; + applyPrefs(gate.current.receiveIncoming(await getSettingsSnapshot())); + } while (readAgain.current); + })().finally(() => { + readRequest.current = null; + }); + readRequest.current = task; + return task; + }, [applyPrefs]); + + const refresh = useCallback(async () => { + setLoading(true); + setError(null); + try { + const [, nextCapability] = await Promise.all([reloadPreferences(), getHotkeyCapability()]); + if (mounted.current) setCapability(nextCapability); + } catch (error) { + if (mounted.current) setError(errorMessage(error)); + } finally { + if (mounted.current) setLoading(false); + } + }, [reloadPreferences]); + + useEffect(() => { + mounted.current = true; + let cancelled = false; + let unlisten: (() => void) | undefined; + void listenPreferenceChanges(() => { + if (cancelled) return; + void reloadPreferences().catch((error) => { + if (!cancelled) setError(errorMessage(error)); + }); + }).then( + (stop) => { + if (cancelled) { + stop(); + return; + } + unlisten = stop; + void refresh(); + }, + (error: unknown) => { + if (cancelled) return; + setError(errorMessage(error)); + setLoading(false); + }, + ); + return () => { + cancelled = true; + mounted.current = false; + unlisten?.(); + }; + }, [refresh, reloadPreferences]); + + const updatePrefs = useCallback( + async (next: UserPreferences | ((current: UserPreferences) => UserPreferences)) => { + const previous = latestPrefsRef.current; + if (!previous) return; + const resolved = typeof next === 'function' ? next(previous) : next; + const write = gate.current.beginWrite(previous, resolved); + if (Object.keys(write.edits).length === 0) { + gate.current.finishWrite(write.id); + return; + } + applyPrefs(gate.current.current()); + const task = persistQueueRef.current + .catch(() => undefined) + .then(async () => { + try { + const saved = await updateSettingFields(write.edits); + applyPrefs(gate.current.finishWrite(write.id, saved)); + } catch (error) { + applyPrefs(gate.current.finishWrite(write.id)); + emitSaved('failed', errorMessage(error)); + throw error; + } + }); + persistQueueRef.current = task; + await task; + }, + [applyPrefs], + ); + + const value = useMemo( + () => ({ + prefs, + hotkey: prefs?.hotkey ?? null, + capability, + loading, + error, + refresh, + updatePrefs, + }), + [capability, error, loading, prefs, refresh, updatePrefs], + ); + + return {children}; +} + +export function useHotkeySettings() { + const value = useContext(HotkeySettingsContext); + if (!value) { + throw new Error('useHotkeySettings must be used within HotkeySettingsProvider'); + } + return value; +} diff --git a/openless-all/app/src/data/snapshot-query.ts b/openless-all/app/src/data/snapshot-query.ts new file mode 100644 index 000000000..6b557933b --- /dev/null +++ b/openless-all/app/src/data/snapshot-query.ts @@ -0,0 +1,73 @@ +export interface QuerySnapshot { + data: T | null; + loading: boolean; + error: unknown; +} + +export class SnapshotQuery { + private snapshot: QuerySnapshot = { data: null, loading: true, error: null }; + private subscribers = new Set<() => void>(); + private wanted = 0; + private published = 0; + private running: Promise> | null = null; + + constructor( + private readonly read: () => Promise, + private readonly beforeRead: () => Promise, + ) {} + + getSnapshot = (): QuerySnapshot => this.snapshot; + + subscribe = (listener: () => void): (() => void) => { + this.subscribers.add(listener); + if (this.wanted === 0) void this.refresh(); + return () => { this.subscribers.delete(listener); }; + }; + + load = (): Promise> => + this.running ?? (this.wanted === 0 ? this.refresh() : Promise.resolve(this.snapshot)); + + refresh = (): Promise> => { + this.wanted++; + return this.run(); + }; + + invalidate(): void { + if (this.wanted > 0) void this.refresh(); + } + + private publish(snapshot: QuerySnapshot): void { + this.snapshot = snapshot; + for (const subscriber of this.subscribers) subscriber(); + } + + private run(): Promise> { + this.running ??= Promise.resolve().then(async () => { + try { + while (this.published !== this.wanted) { + if (!this.snapshot.loading) { + this.publish({ ...this.snapshot, loading: true, error: null }); + } + let generation = this.wanted; + try { + await this.beforeRead(); + generation = this.wanted; + const data = await this.read(); + // Signals invalidate requests even when their actual response arrives later. + if (generation !== this.wanted) continue; + this.published = generation; + this.publish({ data, loading: false, error: null }); + } catch (error) { + if (generation !== this.wanted) continue; + this.published = generation; + this.publish({ ...this.snapshot, loading: false, error }); + } + } + return this.snapshot; + } finally { + this.running = null; + } + }); + return this.running; + } +} diff --git a/openless-all/app/src/data/usage.ts b/openless-all/app/src/data/usage.ts new file mode 100644 index 000000000..6e09b9d36 --- /dev/null +++ b/openless-all/app/src/data/usage.ts @@ -0,0 +1,14 @@ +import { useSyncExternalStore } from 'react'; +import { getServiceUsage } from '../lib/ipc/service-usage'; +import { SnapshotQuery } from './snapshot-query'; + +export const serviceUsageQuery = new SnapshotQuery(getServiceUsage, async () => {}); +export const refreshServiceUsage = serviceUsageQuery.refresh; + +export function useServiceUsage() { + return useSyncExternalStore( + serviceUsageQuery.subscribe, + serviceUsageQuery.getSnapshot, + serviceUsageQuery.getSnapshot, + ); +} diff --git a/openless-all/app/src/lib/harmonyBridge.ts b/openless-all/app/src/lib/harmonyBridge.ts index ac11060eb..64962a7d6 100644 --- a/openless-all/app/src/lib/harmonyBridge.ts +++ b/openless-all/app/src/lib/harmonyBridge.ts @@ -1,4 +1,6 @@ -export const isHarmonyHost = import.meta.env?.VITE_OPENLESS_PLATFORM === 'harmony'; +import { isHarmonyRuntime } from '../runtime/environment'; + +export const isHarmonyHost = isHarmonyRuntime(); declare global { interface Window { diff --git a/openless-all/app/src/lib/hotkey.ts b/openless-all/app/src/lib/hotkey.ts index 6bba81070..e18caebef 100644 --- a/openless-all/app/src/lib/hotkey.ts +++ b/openless-all/app/src/lib/hotkey.ts @@ -1,4 +1,5 @@ import i18n from '../i18n'; +import { getShortcutPlatform } from '../runtime/environment'; import type { ComboBinding, HotkeyBinding, @@ -285,15 +286,7 @@ export function formatComboLabel( return formatComboParts(binding).join(currentPlatform().isMac ? '' : '+'); } -export function currentPlatform(): { isMac: boolean; isWindows: boolean } { - const nav = typeof navigator === 'undefined' ? null : navigator; - const platform = nav?.platform || ''; - const userAgent = nav?.userAgent || ''; - return { - isMac: platform.includes('Mac') || userAgent.includes('Mac'), - isWindows: platform.includes('Win') || userAgent.includes('Windows'), - }; -} +export const currentPlatform = getShortcutPlatform; /** Build side-specific modifier tags from Web KeyboardEvent.code values. */ export function sideModifiersFromPressedCodes(codes: Iterable): string[] { diff --git a/openless-all/app/src/lib/ipc/asr-credentials.ts b/openless-all/app/src/lib/ipc/asr-credentials.ts index 584f85fbf..5a7dd0858 100644 --- a/openless-all/app/src/lib/ipc/asr-credentials.ts +++ b/openless-all/app/src/lib/ipc/asr-credentials.ts @@ -1,6 +1,6 @@ -import { isHarmonyHost } from '../harmonyBridge'; import type { CredentialsStatus } from '../types'; -import { invokeOrMock, isTauri } from './shared'; +import { invokeOrMock } from './shared'; +import { isPreviewHost } from '../../runtime/environment'; import { mockCredentialsStatus, mockCredentialValues } from './mock-data'; import { invalidateMockChannelTest } from './channels'; import { listProviderDescriptors, type LlmRequestFormat } from './providers'; @@ -93,15 +93,14 @@ export async function listProviderModels( channelId?: string, providerType?: string, ): Promise { - if (!isTauri && !isHarmonyHost) { + if (isPreviewHost()) { const descriptor = (await listProviderDescriptors(kind)).find( (item) => item.providerType === providerType, ); if (descriptor?.staticModels.length) return { models: descriptor.staticModels }; } if ( - !isTauri && - !isHarmonyHost && + isPreviewHost() && providerType === 'orcarouter' && (kind === 'llm' || kind === 'asr') ) { diff --git a/openless-all/app/src/lib/ipc/dictation.ts b/openless-all/app/src/lib/ipc/dictation.ts index 512aed043..3ec5ae790 100644 --- a/openless-all/app/src/lib/ipc/dictation.ts +++ b/openless-all/app/src/lib/ipc/dictation.ts @@ -1,22 +1,24 @@ +import { previewHistory } from '../../preview/history'; import { isDesktop } from './platform-exports'; -import { invokeOrMock, isTauriNow, platformCapabilities } from './shared'; +import { invokeOrMock, isTauriNow, platformCapabilities, requireBackendReady } from './shared'; import type { CapsuleSnapshot } from '../types'; export function startDictation(): Promise { - return invokeOrMock('start_dictation', undefined, () => undefined); + return invokeOrMock('start_dictation', undefined, () => { previewHistory.startRecording(); }); } export function stopDictation(): Promise { - return invokeOrMock('stop_dictation', undefined, () => undefined); + return invokeOrMock('stop_dictation', undefined, () => previewHistory.stopRecording()); } export function cancelDictation(): Promise { - return invokeOrMock('cancel_dictation', undefined, () => undefined); + return invokeOrMock('cancel_dictation', undefined, () => previewHistory.cancelRecording()); } export async function setCapsuleTranscriptVisible(visible: boolean): Promise { if (!isDesktop()) return; if (isTauriNow()) { + await requireBackendReady(); const { getCurrentWebviewWindow } = await import('@tauri-apps/api/webviewWindow'); // Mirrors render the shared transcript but never own the primary rail's native layout. // This also prevents a retained/closing mirror's cleanup from hiding the active rail. diff --git a/openless-all/app/src/lib/ipc/history.ts b/openless-all/app/src/lib/ipc/history.ts index 1198e9a87..e507ebf17 100644 --- a/openless-all/app/src/lib/ipc/history.ts +++ b/openless-all/app/src/lib/ipc/history.ts @@ -1,23 +1,23 @@ import type { ActivityDay, DictationSession } from '../types'; import { invokeOrMock } from './shared'; -import { mockActivityDays, mockHistory } from './mock-data'; +import { previewHistory } from '../../preview/history'; export function listHistory(): Promise { - return invokeOrMock('list_history', undefined, () => mockHistory); + return invokeOrMock('list_history', undefined, () => previewHistory.list()); } /** Daily dictation activity counts (ascending by date), the overview page's yearly heatmap data source. Decoupled from the history retention policy. */ export function getActivityStats(): Promise { - return invokeOrMock('get_activity_stats', undefined, () => mockActivityDays); + return invokeOrMock('get_activity_stats', undefined, () => previewHistory.getActivityDays()); } export function deleteHistoryEntry(id: string): Promise { - return invokeOrMock('delete_history_entry', { id }, () => undefined); + return invokeOrMock('delete_history_entry', { id }, () => previewHistory.delete(id)); } export function clearHistory(): Promise { - return invokeOrMock('clear_history', undefined, () => undefined); + return invokeOrMock('clear_history', undefined, () => previewHistory.clear()); } /** Reads the data URL (base64) of a session's original microphone WAV. @@ -25,7 +25,7 @@ export function clearHistory(): Promise { * Returns `data:audio/wav;base64,...`, used directly by the frontend `