diff --git a/docs/ATTRIBUTION.md b/docs/ATTRIBUTION.md new file mode 100644 index 000000000..d45898632 --- /dev/null +++ b/docs/ATTRIBUTION.md @@ -0,0 +1,14 @@ +# Component attribution + +## Rare UI GitHub Activity + +The overview yearly activity card is a port of Rare UI's GitHub Activity component. + +- Page: https://rareui.com/components/githubactivity +- Upstream: https://github.com/swamimalode07/rare-ui +- License: MIT License + Commons Clause +- Copyright (c) 2026 Swami Malode + +The port keeps the original geometry: 11px cells, 3px gap, 28px corner radius, 16px padding, week and month layout, the hover tooltip, and the expandable bottom panel. Local dictation counts replace GitHub contributions. The software with the most voice input (name and count) replaces repositories. Cells are not redrawn or resized to fit a narrow column. + +The in-app credit is Settings → About and updates → Component credits. The repository READMEs (`openless-all/README.md` and `openless-all/README.zh.md`) carry the same credit. diff --git a/docs/architecture.md b/docs/architecture.md index 736e07c51..2ca55230c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ Android 侧:`src-tauri/src/android/`(JNI/桥接)+ `android/`(aidl、kotl ```mermaid flowchart TB - React["React 页面 / 窗口"] --> IPC["src/lib/ipc · typed wrapper"] + React["React 页面 / 窗口"] --> IPC["src/api + src/runtime · typed commands"] IPC --> Tauri["Tauri commands / coordinator / core_adapters"] Egui["egui UI"] --> Linux["LinuxHost / LinuxBackendBuilder"] Tauri --> Core["OpenLessBackend · Core"] @@ -34,13 +34,13 @@ flowchart TB Events --> Linux ``` -- 桌面:React → 类型化 IPC 门面(`src/lib/ipc/`)→ Tauri command → Core;Core 事件由 Host 转发回界面。 +- 桌面:React → 分域 API(`src/api/`)与宿主传输(`src/runtime/`)→ Tauri command → Core;Core 事件由 Host 转发回界面。 - Linux:egui UI → `LinuxHost`(`lib.rs`:`snapshot` / `subscribe` / `save_settings` / `drain_events` 等)→ `OpenLessBackend` → Core,类型化 Rust 接口,不经 IPC。 - 浏览器预览:provider 公开目录由 Core 生成到 `src/lib/ipc/provider-descriptors.generated.json`(`cargo run --locked -p openless-core --example export_provider_descriptors` 重新生成;只含公开元数据,无凭据);原生端走同一受启动合同保护的 IPC。 - 语言目录:`contract/language-catalog.json` 是工作语言原生名、识别代码与 Apple locale 的单一来源;React `languageCatalog.ts` 和 Core `language_catalog.rs` 读取同一份数据,识别服务仍在运行时判断具体语种是否可用。界面语言独立保存在 `ol.locale`,启动和切换经既有 `set_remote_locale` 将解析后的语言同步给原生托盘与手机远程输入页。 - 旧 React command/event 名称只保留在 Tauri 兼容 Adapter;跨平台合同以 `contract/backend-2.0.json` 为准。 -启动时,`src/App.tsx` 经 `src/lib/ipc/shared.ts` 请求 `get_startup_snapshot`,校验合同版本和 backend 运行状态后进入业务界面。Core 事件定义在 `events.rs`,Tauri 的转译入口为 `src-tauri/src/tauri_events.rs`,Linux 直接订阅类型化事件。 +启动时,`src/app/App.tsx` 由 `src/runtime/transport.ts` 等待原生桥,调用 `get_startup_snapshot` 校验合同版本和后台运行状态后进入业务界面。浏览器预览由 `src/preview/` 提供独立适配。Core 事件定义在 `events.rs`,Tauri 的转译入口为 `src-tauri/src/tauri_events.rs`,Linux 直接订阅类型化事件。 听写主链由 `dictation_engine.rs` 管理:触发会话 → 录音/ASR → 清理与润色 → Host 插入 → 历史与事件。Host 音频处理 worker 在原生采样停止后通过 FIFO Shutdown 排空并退出,不能依赖 CPAL 回调中所有 sender 都析构才结束,否则指定麦克风时可能堵住停止与后续多模态请求。Tauri 在 `coordinator/dictation_core.rs` 接入该链路;本地 ASR 的模型管理归 Core,原生执行实现分别位于 Host。取消、失败和旧会话事件处理也属于该业务链,而不是页面各自实现。 @@ -72,7 +72,7 @@ Tauri 在 `src-tauri/src/coordinator.rs` 构造 Core,`core_adapters.rs` 组装 ## 5. 窗口体系 -`src-tauri/tauri.conf.json` 声明 `main`、`capsule` 两个窗口。`src/main.tsx` 读取 `?window=`,`src/App.tsx` 按类型加载胶囊、`qa`(含复用它的「润色结果」模式)、`selection-voice-intent`、`less-computer` 和 `less-computer-glow`;未指定类型时进入主界面。各 WebView 共用前端入口,重页面按需加载;移动端再依据平台能力选择布局。Linux 单实例由 `linux-egui/src/single_instance.rs` 守护并转发启动意图。 +`src-tauri/tauri.conf.json` 声明 `main`、`capsule` 两个窗口。`src/app/bootstrap.tsx` 读取 `?window=`,`src/app/windowRoutes.tsx` 分派胶囊、Windows 转写轨、`qa`(含复用它的「润色结果」模式)、语音编辑和选区意图。Less Computer 的兼容路由保持空界面;无辅助类型时进入主界面。各 WebView 共用前端入口,重页面按需加载;移动端再依据平台能力选择布局。Linux 单实例由 `linux-egui/src/single_instance.rs` 守护并转发启动意图。 主窗口默认逻辑尺寸为 1300×835,允许用户调整;macOS 原生窗口按钮左侧和顶部均留出 16px,前端保留 44px 拖动区。桌面侧栏宽 226px,主内容从版本行下方开始,设置面板单独限制高度并在内部滚动。 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,缺少真机或已有宿主缺口按平台和场景列出。 diff --git a/docs/structure.md b/docs/structure.md index 9c7c7c504..fb223fc71 100644 --- a/docs/structure.md +++ b/docs/structure.md @@ -37,10 +37,11 @@ openless-src/ Git 仓库、分支与发布边界 | 任务 | 入口 | 相关边界 | | --- | --- | --- | -| 启动与窗口分支 | `src/main.tsx`、`src/App.tsx` | typed IPC 启动快照;Tauri 配置与运行时窗口 | -| 主界面、页面与设置 | `src/components/FloatingShell.tsx`、`src/pages/`、`src/pages/settings/` | `src/state/` 组织界面状态;业务规则归 Core | -| 多语言、主题、组件 | `src/i18n/`、`src/styles/`、`src/components/` | 八种界面语言;tokens/global 样式 | -| 新增或调整 IPC | `src/lib/ipc/`、`src-tauri/src/commands/`、`src-tauri/src/lib.rs` | Rust/TypeScript 类型、注册、事件与 `contract/` 同步 | +| 启动与窗口分支 | `src/app/bootstrap.tsx`、`src/app/windowRoutes.tsx`、`src/app/startup.ts` | `src/runtime/` 识别宿主并完成启动握手,Android 嵌入面板由 `src/app/useAndroidPanels.ts` 管理 | +| 主界面、页面与设置 | `src/app/shell/`、`src/features/` | 导航和窗口布局在 app,业务界面按领域组织(设置、渠道、历史、模型、胶囊、更新等);兼容入口位于 `src/pages/` 和 `src/components/` | +| 多语言、主题、组件 | `src/i18n/`、`src/ui/`、`src/styles/` | 每窗一个 AppViewport;内容与浮层共享可见边界 | +| 共享快照、偏好和预览 | `src/data/`、`src/preview/` | data 管理读写次序;preview 提供浏览器的设备预设、模拟数据和事件 | +| 新增或调整 IPC | `src/api/`、`src/runtime/`、`src-tauri/src/commands/` | React 通过分域 API 读写;Rust/TypeScript 类型、注册、事件与 `contract/` 同步 | | 共享业务入口 | `crates/openless-core/src/api.rs` | `events.rs`、`ports.rs`、`domains.rs`、`config.rs` | | 听写和服务 | Core `dictation_engine.rs`、`provider_*`、`asr/`、`polish.rs` | Host 的录音、插入和本地模型适配 | | 历史、词库、纠错、风格包 | Core `history.rs`、`vocabulary.rs`、`correction.rs`、`style_pack_store.rs` | Tauri `persistence/` 与对应 command | diff --git a/openless-all/README.md b/openless-all/README.md index 66343d709..dac458590 100644 --- a/openless-all/README.md +++ b/openless-all/README.md @@ -210,6 +210,10 @@ Optional: Manual workflow runs can still produce ad-hoc signed test builds, but tagged macOS releases fail if signing/notarization secrets are missing. +## Third-party components + +The overview yearly activity card ports [Rare UI GitHub Activity](https://rareui.com/components/githubactivity) (Copyright (c) 2026 Swami Malode). The license is MIT plus the Commons Clause. Cell size, gap, radius, padding, month labels, tooltip, and the expandable panel stay with the upstream component; local dictation counts replace GitHub contributions, and the apps with the most voice input replace repositories. The same credit is in the app under Settings → About and updates → Component credits. See [docs/ATTRIBUTION.md](../docs/ATTRIBUTION.md). + ## Ignored Local Output The following are intentionally local-only: diff --git a/openless-all/README.zh.md b/openless-all/README.zh.md index 52b89fd98..e4975b8af 100644 --- a/openless-all/README.zh.md +++ b/openless-all/README.zh.md @@ -198,6 +198,10 @@ python3 scripts/package-ipa.py \ 手动触发的工作流仍可生成 ad-hoc 签名的测试构建,但若缺少签名/公证 secrets,带标签的 macOS 发布将会失败。 +## 第三方组件 + +概览页的年度活动卡片移植自 [Rare UI GitHub Activity](https://rareui.com/components/githubactivity)(Copyright (c) 2026 Swami Malode)。许可是 MIT 加 Commons Clause。格子尺寸、间距、圆角、内边距、月份标签、悬浮提示和可展开面板保持上游组件;本地听写次数替换 GitHub 提交,语音输入最多的软件替换仓库。应用内署名在「设置 → 关于与更新 → 组件来源」。详见 [docs/ATTRIBUTION.md](../docs/ATTRIBUTION.md)。 + ## 忽略的本地输出 以下内容有意仅保留在本地: diff --git a/openless-all/app/android/frontend/components/AndroidPermissionsPanel.tsx b/openless-all/app/android/frontend/components/AndroidPermissionsPanel.tsx index f1ff9dcaa..8789a1d25 100644 --- a/openless-all/app/android/frontend/components/AndroidPermissionsPanel.tsx +++ b/openless-all/app/android/frontend/components/AndroidPermissionsPanel.tsx @@ -2,8 +2,9 @@ import { useEffect, useRef, useState, type CSSProperties } from 'react'; import { useTranslation } from 'react-i18next'; import type { TFunction } from 'i18next'; import { Icon } from '../../../src/components/Icon'; -import { getSettings, setSettings } from '../../../src/lib/ipc/settings'; -import type { UserPreferences } from '../../../src/lib/types'; +import { useHotkeySettings } from '../../../src/data/preferences'; +import { useInteraction } from '../../../src/ui/overlays/InteractionProvider'; +import type { UserPreferences } from '../../../src/api/contracts'; import { Btn, Pill } from '../../../src/pages/_atoms'; import { SettingRow } from '../../../src/pages/settings/shared'; import { useLayoutStack, useConservativeLayout } from '../../../src/lib/useMobileLayout'; @@ -29,43 +30,6 @@ import type { } from '../lib/androidTypes'; import { clampAndroidOverlaySize, normalizeAndroidOverlayTrigger } from '../lib/androidTypes'; -type AndroidPrefsSlice = Pick; - -function pickAndroidPrefs(settings: UserPreferences): AndroidPrefsSlice { - return { - androidInsertStrategy: settings.androidInsertStrategy, - androidOverlayTrigger: settings.androidOverlayTrigger, - androidOverlayActivationMode: settings.androidOverlayActivationMode, - androidOverlayLeftSwipeAction: settings.androidOverlayLeftSwipeAction, - androidOverlayCancelSwipeDirection: settings.androidOverlayCancelSwipeDirection, - androidOverlayGestureActions: settings.androidOverlayGestureActions, - androidOverlaySizeDp: settings.androidOverlaySizeDp, - }; -} - -let androidOverlaySaveQueue = Promise.resolve(); - -function enqueueAndroidOverlaySave(task: () => Promise): Promise { - const run = androidOverlaySaveQueue.then(task); - androidOverlaySaveQueue = run.then( - () => undefined, - () => undefined, - ); - return run; -} - -function persistAndroidOverlayPrefs(patch: Partial): Promise { - return enqueueAndroidOverlaySave(async () => { - const settings = await getSettings(); - const next = { - ...settings, - ...patch, - }; - await setSettings(next); - return pickAndroidPrefs(next); - }); -} - type AndroidPermissionsPanelMode = 'all' | 'permissionsOnly' | 'accessibility' | 'overlayPermission' | 'overlayConfig'; @@ -75,6 +39,10 @@ interface AndroidPermissionsPanelProps { export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPanelProps) { const { t } = useTranslation(); + const { prefs: androidPrefs, updatePrefs } = useHotkeySettings(); + const { confirm } = useInteraction(); + const [actionError, setActionError] = useState(false); + const reportFailure = () => setActionError(true); const baseLayoutStack = useLayoutStack(); const conservative = useConservativeLayout(); const layoutStack = baseLayoutStack || conservative; @@ -85,22 +53,23 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane const [shizukuRecoveryMessageKey, setShizukuRecoveryMessageKey] = useState(null); const [shizukuActionMessageKey, setShizukuActionMessageKey] = useState(null); const [shizukuRecoveryPending, setShizukuRecoveryPending] = useState(false); - const [androidPrefs, setAndroidPrefs] = useState | null>(null); const [sizeDraft, setSizeDraft] = useState(null); + const draftSizeRef = useRef(null); + const draftRevision = useRef(0); const sizeDebounceRef = useRef(null); - const sizePendingRef = useRef(false); + const recovery = useRef(false); + const loaded = useRef(false); + const refreshRevision = useRef(0); + const migratedLegacyTrigger = useRef(false); const refreshAndroid = async () => { - const [overlayResult, accessibilityResult, shizukuResult, settingsResult] = - await Promise.allSettled([ - getAndroidOverlayStatus(), - getAndroidAccessibilityStatus(), - getAndroidShizukuStatus(), - getSettings(), - ]); + const request = ++refreshRevision.current; + const [overlayResult, accessibilityResult, shizukuResult] = await Promise.allSettled([ + getAndroidOverlayStatus(), + getAndroidAccessibilityStatus(), + getAndroidShizukuStatus(), + ]); + if (!loaded.current || refreshRevision.current !== request) return; if (overlayResult.status === 'fulfilled') { setAndroidOverlay(overlayResult.value); } @@ -120,32 +89,38 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane return shizuku; }); } - if (settingsResult.status === 'fulfilled') { - let migratedSettings = settingsResult.value; - if (migratedSettings.androidOverlayTrigger === 'keyboard') { - const migratedPrefs = await persistAndroidOverlayPrefs({ - androidOverlayTrigger: normalizeAndroidOverlayTrigger( - migratedSettings.androidOverlayTrigger, - ), - }); - migratedSettings = { ...migratedSettings, ...migratedPrefs }; - } - setAndroidPrefs(pickAndroidPrefs(migratedSettings)); - } }; const handleRecoverAccessibility = async () => { - if (shizukuRecoveryPending) return; - const confirmed = window.confirm(t('settings.permissions.androidShizukuRecoverConfirm')); - if (!confirmed) return; - setShizukuActionMessageKey(null); + if (recovery.current) return; + recovery.current = true; setShizukuRecoveryPending(true); try { + const confirmed = await confirm({ + title: t('settings.permissions.androidShizukuRecoverConfirm'), + tone: 'danger', + }); + if (!confirmed) return; + setActionError(false); + setShizukuActionMessageKey(null); const result = await recoverAndroidAccessibility(true); - setShizukuRecoveryMessageKey(result.messageKey); + if (loaded.current) setShizukuRecoveryMessageKey(result.messageKey); await refreshAndroid(); + } catch { + if (loaded.current) reportFailure(); } finally { - setShizukuRecoveryPending(false); + recovery.current = false; + if (loaded.current) setShizukuRecoveryPending(false); + } + }; + + const requestAndRefresh = async (action: () => Promise) => { + setActionError(false); + try { + await action(); + await refreshAndroid(); + } catch { + if (loaded.current) reportFailure(); } }; @@ -157,6 +132,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane null; useEffect(() => { + loaded.current = true; void refreshAndroid(); const androidId = window.setInterval(refreshAndroid, 3000); const onFocus = () => { @@ -164,112 +140,90 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane }; window.addEventListener('focus', onFocus); return () => { + loaded.current = false; + refreshRevision.current += 1; + if (sizeDebounceRef.current != null) clearTimeout(sizeDebounceRef.current); window.clearInterval(androidId); window.removeEventListener('focus', onFocus); }; }, []); useEffect(() => { - if (sizePendingRef.current) return; - if (androidPrefs?.androidOverlaySizeDp != null) { - setSizeDraft(androidPrefs.androidOverlaySizeDp); - } - }, [androidPrefs?.androidOverlaySizeDp]); - - useEffect(() => { - return () => { - if (sizeDebounceRef.current) clearTimeout(sizeDebounceRef.current); - }; - }, []); + if (androidPrefs?.androidOverlayTrigger !== 'keyboard' || migratedLegacyTrigger.current) return; + migratedLegacyTrigger.current = true; + void updatePrefs((current) => + current.androidOverlayTrigger === 'keyboard' + ? { ...current, androidOverlayTrigger: normalizeAndroidOverlayTrigger('keyboard') } + : current, + ).catch(reportFailure); + }, [androidPrefs?.androidOverlayTrigger, updatePrefs]); + + const finishSizeDraft = (revision: number) => { + if (draftRevision.current !== revision) return; + draftSizeRef.current = null; + if (loaded.current) setSizeDraft(null); + }; - const saveAndroidOverlaySize = async (value: number) => { - const clamped = clampAndroidOverlaySize(value); + const saveAndroidOverlaySize = async (value: number, revision: number) => { + setActionError(false); try { - const nextPrefs = await persistAndroidOverlayPrefs({ androidOverlaySizeDp: clamped }); - setAndroidPrefs((prev) => (prev ? { ...prev, ...nextPrefs } : nextPrefs)); - setSizeDraft(clamped); - } catch (error) { - console.error('[android] failed to save overlay size', error); - const settings = await getSettings(); - const rolledBack = settings.androidOverlaySizeDp; - const safeDraft = rolledBack != null ? clampAndroidOverlaySize(rolledBack) : null; - setAndroidPrefs((prev) => (prev ? { ...prev, androidOverlaySizeDp: rolledBack } : null)); - setSizeDraft(safeDraft); + await updatePrefs((current) => ({ ...current, androidOverlaySizeDp: value })); + } catch { + if (loaded.current) reportFailure(); } finally { - sizePendingRef.current = false; + finishSizeDraft(revision); } }; - const scheduleAndroidOverlaySizeSave = (value: number) => { - if (sizeDebounceRef.current) clearTimeout(sizeDebounceRef.current); + const handleAndroidOverlaySizeChange = (value: number) => { + const clamped = clampAndroidOverlaySize(value); + const revision = ++draftRevision.current; + draftSizeRef.current = clamped; + setSizeDraft(clamped); + if (sizeDebounceRef.current != null) clearTimeout(sizeDebounceRef.current); sizeDebounceRef.current = window.setTimeout(() => { sizeDebounceRef.current = null; - void saveAndroidOverlaySize(value); + void saveAndroidOverlaySize(clamped, revision); }, 200); }; - const flushAndroidOverlaySizeSave = (value: number) => { - const hasDebounce = sizeDebounceRef.current != null; - const hasPending = sizePendingRef.current; - if (!hasDebounce && !hasPending) return; - - if (sizeDebounceRef.current) { - clearTimeout(sizeDebounceRef.current); - sizeDebounceRef.current = null; - } - - const clamped = clampAndroidOverlaySize(value); - const committed = androidPrefs?.androidOverlaySizeDp; - if (committed != null && clamped === committed) { - sizePendingRef.current = false; - return; - } - - void saveAndroidOverlaySize(clamped); - }; - - const handleAndroidOverlaySizeChange = (value: number) => { - const clamped = clampAndroidOverlaySize(value); - sizePendingRef.current = true; - setSizeDraft(clamped); - scheduleAndroidOverlaySizeSave(clamped); + const flushAndroidOverlaySizeSave = () => { + if (sizeDebounceRef.current == null || draftSizeRef.current === null) return; + clearTimeout(sizeDebounceRef.current); + sizeDebounceRef.current = null; + void saveAndroidOverlaySize(draftSizeRef.current, draftRevision.current); }; const updateAndroidPref = async ( key: K, - value: UserPreferences[K], + value: UserPreferences[K] | ((current: UserPreferences) => UserPreferences[K]), ) => { - if (key !== 'androidOverlaySizeDp' && sizeDebounceRef.current) { + const revision = draftRevision.current; + const oldDraft = sizeDebounceRef.current == null ? null : draftSizeRef.current; + if (sizeDebounceRef.current != null) { clearTimeout(sizeDebounceRef.current); sizeDebounceRef.current = null; } - - const patch: Partial = { - [key]: - key === 'androidOverlayTrigger' - ? normalizeAndroidOverlayTrigger(value as AndroidOverlayTrigger) - : value, - }; - - if (key !== 'androidOverlaySizeDp') { - const committedSize = androidPrefs?.androidOverlaySizeDp; - const draftSize = sizeDraft; - if (sizePendingRef.current || (draftSize != null && draftSize !== committedSize)) { - patch.androidOverlaySizeDp = clampAndroidOverlaySize(draftSize ?? committedSize ?? 72); - } - sizePendingRef.current = false; - } - + setActionError(false); try { - const nextPrefs = await persistAndroidOverlayPrefs(patch); - setAndroidPrefs(nextPrefs); - if (patch.androidOverlaySizeDp != null) { - setSizeDraft(nextPrefs.androidOverlaySizeDp); - } - await refreshAndroid(); - } catch (error) { - console.error('[android] failed to save overlay pref', error); + // Compute the edit from the latest optimistic preferences in the shared + // gate; fields saved by the onboarding or settings shell stay intact. + await updatePrefs((current) => { + const next = typeof value === 'function' ? value(current) : value; + return { + ...current, + [key]: + key === 'androidOverlayTrigger' + ? normalizeAndroidOverlayTrigger(next as AndroidOverlayTrigger) + : next, + ...(oldDraft === null ? {} : { androidOverlaySizeDp: oldDraft }), + }; + }); await refreshAndroid(); + } catch { + if (loaded.current) reportFailure(); + } finally { + if (oldDraft !== null) finishSizeDraft(revision); } }; @@ -300,6 +254,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane return ( <> + {actionError &&

{t('common.operationFailed')}

} {showOverlayPermission && (
@@ -321,7 +276,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane variant="ghost" size="sm" onClick={() => { - void requestAndroidOverlayPermission().then(refreshAndroid); + void requestAndRefresh(requestAndroidOverlayPermission); }} > {t('settings.permissions.grant')} @@ -361,7 +316,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane variant="ghost" size="sm" onClick={() => { - void requestAndroidAccessibilityPermission().then(refreshAndroid); + void requestAndRefresh(requestAndroidAccessibilityPermission); }} > {t('settings.permissions.openSystem')} @@ -416,11 +371,11 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane onClick={() => { setShizukuRecoveryMessageKey(null); setShizukuActionMessageKey(null); - void openShizukuApp().then((result) => { - if (!result.launched) { + void requestAndRefresh(async () => { + const result = await openShizukuApp(); + if (!result.launched && loaded.current) { setShizukuActionMessageKey(result.messageKey); } - return refreshAndroid(); }); }} > @@ -434,11 +389,11 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane onClick={() => { setShizukuRecoveryMessageKey(null); setShizukuActionMessageKey(null); - void requestAndroidShizukuPermission().then((result) => { - if (!result.launched) { + void requestAndRefresh(async () => { + const result = await requestAndroidShizukuPermission(); + if (!result.launched && loaded.current) { setShizukuActionMessageKey(result.messageKey); } - return refreshAndroid(); }); }} > @@ -471,7 +426,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane variant="ghost" size="sm" onClick={() => { - void requestAndroidAccessibilityPermission().then(refreshAndroid); + void requestAndRefresh(requestAndroidAccessibilityPermission); }} > {t('settings.permissions.openSystem')} @@ -525,6 +480,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane }} > { void updateAndroidPref( @@ -602,6 +559,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane }} > { - const actions = androidPrefs?.androidOverlayGestureActions ?? { - up: 'cancel', - down: 'none', - left: 'translation', - right: 'qa', - }; - void updateAndroidPref('androidOverlayGestureActions', { - ...actions, - [direction]: event.target.value as AndroidOverlayGestureAction, - }); + const action = event.currentTarget.value as AndroidOverlayGestureAction; + void updateAndroidPref('androidOverlayGestureActions', (current) => ({ + ...(current.androidOverlayGestureActions ?? { + up: 'cancel', + down: 'none', + left: 'translation', + right: 'qa', + }), + [direction]: action, + })); }} style={selectStyle} > @@ -711,6 +670,7 @@ export function AndroidPermissionsPanel({ mode = 'all' }: AndroidPermissionsPane > { handleAndroidOverlaySizeChange(Number(event.target.value)); }} - onPointerUp={(event) => { - flushAndroidOverlaySizeSave(Number(event.currentTarget.value)); - }} - onTouchEnd={(event) => { - flushAndroidOverlaySizeSave(Number(event.currentTarget.value)); - }} - onBlur={(event) => { - flushAndroidOverlaySizeSave(Number(event.currentTarget.value)); - }} + onPointerUp={flushAndroidOverlaySizeSave} + onTouchEnd={flushAndroidOverlaySizeSave} + onBlur={flushAndroidOverlaySizeSave} style={{ flex: 1, minWidth: 0 }} /> page.locator('.ol-onboarding-layer > div'); const next = (page: Page) => page.getByRole('button', { name: '下一步', exact: true }); const back = (page: Page) => page.getByRole('button', { name: '上一步', exact: true }); @@ -16,7 +17,9 @@ async function reachOverlayConfig(page: Page) { // These are the production AndroidPermissionsPanel controls, not filler content. await expect(page.getByRole('combobox')).toHaveCount(7); await expect(page.getByRole('slider')).toHaveValue('72'); - await surface(page).evaluate((element) => { element.scrollTop = 0; }); + await surface(page).evaluate((element) => { + element.scrollTop = 0; + }); } async function expectBoundedOverflow(page: Page) { @@ -49,8 +52,13 @@ async function wheelTo(page: Page, target: Locator) { expect(await fullyInViewport(target, page)).toBe(true); } -for (const viewport of [{ width: 390, height: 600 }, { width: 740, height: 360 }]) { - test(`Android tall overlay card scrolls and retains navigation at ${viewport.width}x${viewport.height}`, async ({ page }) => { +for (const viewport of [ + { width: 390, height: 600 }, + { width: 740, height: 360 }, +]) { + test(`Android tall overlay card scrolls and retains navigation at ${viewport.width}x${viewport.height}`, async ({ + page, + }) => { await page.setViewportSize(viewport); const errors: string[] = []; page.on('pageerror', (error) => errors.push(error.message)); @@ -80,8 +88,14 @@ for (const viewport of [{ width: 390, height: 600 }, { width: 740, height: 360 } test.describe('Android native touch scrolling', () => { test.use({ viewport: { width: 390, height: 600 }, hasTouch: true }); - test('swiping the production card reaches its last control and navigation', async ({ page, browserName }) => { - test.skip(browserName !== 'chromium', 'Android WebView touch input is exercised through Chromium CDP'); + test('swiping the production card reaches its last control and navigation', async ({ + page, + browserName, + }) => { + test.skip( + browserName !== 'chromium', + 'Android WebView touch input is exercised through Chromium CDP', + ); const errors: string[] = []; page.on('pageerror', (error) => errors.push(error.message)); await reachOverlayConfig(page); @@ -91,11 +105,13 @@ test.describe('Android native touch scrolling', () => { // Real browser input, not synthetic DOM TouchEvents or a scrollTop assignment. // Stay on card padding, away from native selects and the size slider. await session.send('Input.dispatchTouchEvent', { - type: 'touchStart', touchPoints: [{ x: 24, y: 520 }], + type: 'touchStart', + touchPoints: [{ x: 24, y: 520 }], }); for (let y = 480; y >= 160; y -= 40) { await session.send('Input.dispatchTouchEvent', { - type: 'touchMove', touchPoints: [{ x: 24, y }], + type: 'touchMove', + touchPoints: [{ x: 24, y }], }); await page.waitForTimeout(20); } @@ -127,3 +143,28 @@ test.describe('Android native touch scrolling', () => { } }); }); + +test('Android overlay changes use shared field writes and roll back on failure', async ({ + page, +}) => { + await reachOverlayConfig(page); + const activation = page + .locator('select') + .filter({ has: page.locator('option[value="long_press"]') }); + await expect(activation).toHaveValue('tap'); + await page.evaluate(() => (window as any).androidGuideFixture.rejectNextWrite()); + await activation.selectOption('long_press'); + await expect(page.getByRole('alert')).toContainText('操作失败'); + await expect(activation).toHaveValue('tap'); + await activation.selectOption('long_press'); + await expect + .poll(() => page.evaluate(() => (window as any).androidGuideFixture.writes)) + .toEqual([ + { '/androidOverlayActivationMode': 'long_press' }, + { '/androidOverlayActivationMode': 'long_press' }, + ]); + await expect(activation).toHaveValue('long_press'); + expect(await page.evaluate(() => (window as any).androidGuideFixture.calls)).not.toContain( + 'set_settings', + ); +}); diff --git a/openless-all/app/e2e/ask-anything.spec.ts b/openless-all/app/e2e/ask-anything.spec.ts index b8a7666a2..1dab6e601 100644 --- a/openless-all/app/e2e/ask-anything.spec.ts +++ b/openless-all/app/e2e/ask-anything.spec.ts @@ -1,5 +1,6 @@ +import { fixtureOrigin } from './support/server'; import { expect, test, type Page } from '@playwright/test'; -const fixture = 'http://127.0.0.1:5326/e2e/fixtures/capsule-motion.html'; +const fixture = `${fixtureOrigin}/e2e/fixtures/capsule-motion.html`; async function emit(page: Page, event: string, payload: unknown) { await page.evaluate((v) => (window as any).fixture.emit(v.event, v.payload), { event, payload }); } diff --git a/openless-all/app/e2e/aux-window-geometry.spec.ts b/openless-all/app/e2e/aux-window-geometry.spec.ts new file mode 100644 index 000000000..2c5d5e99b --- /dev/null +++ b/openless-all/app/e2e/aux-window-geometry.spec.ts @@ -0,0 +1,121 @@ +import { fixtureOrigin } from './support/server'; +import { expect, test } from '@playwright/test'; + +const fixture = `${fixtureOrigin}/e2e/fixtures/capsule-motion.html`; + +test.use({ reducedMotion: 'reduce' }); + +test('QA waits for observed geometry after acknowledgment and discards a closing layout', async ({ + page, +}) => { + await page.goto(fixture + '?qa'); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + const host = page.locator('#native-host'); + await page.evaluate(() => { + const bridge = (window as any).fixture; + bridge.holdQaGeometry = true; + bridge.emit('qa:state', { kind: 'recording', sessionId: 'old', messages: [] }); + bridge.emit('qa:state', { + kind: 'answer', + sessionId: 'old', + messages: [{ role: 'assistant', text: 'Old result' }], + }); + }); + await expect.poll(() => page.evaluate(() => (window as any).fixture.sizes.at(-1))).toBe(true); + 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 expect(page.locator('.qa-answer-panel')).toBeVisible(); + await expect(host).toHaveCSS('height', '220px'); + + await page.evaluate(() => { + const bridge = (window as any).fixture; + bridge.emit('chat-panel:closing', {}); + bridge.emit('chat-panel:shown', {}); + bridge.emit('qa:state', { kind: 'recording', sessionId: 'new', messages: [] }); + }); + await expect.poll(() => page.evaluate(() => (window as any).fixture.sizes.at(-1))).toBe(false); + await expect(page.locator('.ol-default-capsule')).toBeHidden(); + await page.evaluate(() => (window as any).fixture.applyQaGeometry(false)); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + await expect(page.locator('.qa-answer-panel')).toHaveCount(0); +}); + +test('QA keeps a reachable close action when the host rejects expansion', async ({ page }) => { + await page.goto(fixture + '?qa'); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + await page.evaluate(() => { + const bridge = (window as any).fixture; + bridge.rejectQaExpansion = true; + bridge.emit('qa:state', { kind: 'recording', sessionId: 'failed', messages: [] }); + bridge.emit('qa:state', { + kind: 'answer', + sessionId: 'failed', + messages: [{ role: 'assistant', text: 'Answer' }], + }); + }); + const alert = page.locator('.qa-layout-failure'); + await expect(alert).toBeVisible(); + await expect(page.locator('#native-host')).toHaveCSS('height', '80px'); + await alert.getByRole('button').click(); + const closing = page.locator('.qa-capsule-shell.is-closing'); + await expect(closing).toHaveAttribute('inert', ''); + await expect(closing).toHaveCSS('opacity', '0'); +}); + +test('language menu waits for drawable room and releases its own reservation on Escape', async ({ + page, +}) => { + await page.setViewportSize({ width: 460, height: 92 }); + await page.goto(fixture); + await expect(page.locator('.ol-default-capsule')).toBeVisible(); + await page.evaluate(() => (window as any).fixture.setCapsule({ translation: true })); + const picker = page.getByRole('combobox', { name: '翻译目标语言' }); + await expect(picker).toBeEnabled(); + await picker.click(); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.menuChanges.at(-1)?.open)) + .toBe(true); + await expect(page.getByRole('listbox')).toHaveCount(0); + await page.keyboard.press('Escape'); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.menuChanges.at(-1)?.open)) + .toBe(false); + await picker.click(); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.menuChanges.at(-1)?.open)) + .toBe(true); + await page.setViewportSize({ width: 460, height: 415 }); + const list = page.getByRole('listbox'); + await expect(list).toBeVisible(); + expect((await list.boundingBox())!.height).toBeGreaterThan(150); + await page.keyboard.press('Escape'); + await expect(list).toHaveCount(0); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.menuChanges.at(-1))) + .toEqual({ + open: false, + sessionId: 'recording-a', + }); +}); + +test('the fallback card exposes Copy only after its presentation fits', async ({ page }) => { + await page.setViewportSize({ width: 360, height: 112 }); + await page.goto(fixture + '?fallback'); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.fallbackReports.length)) + .toBe(1); + const report = await page.evaluate(() => (window as any).fixture.fallbackReports[0]); + expect(report.presentationId).toBe(23); + expect(report.height).toBeGreaterThan(112); + const waiting = page.locator('[data-layout=waiting]'); + await expect(waiting).toHaveCSS('visibility', 'hidden'); + await page.setViewportSize({ width: 360, height: report.height + 1 }); + const ready = page.locator('[data-layout=ready]'); + await expect(ready).toBeVisible(); + await ready.getByRole('button').first().click(); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.copiedFallback.at(-1))) + .toBe('待复制的长文本。\n'.repeat(36)); +}); diff --git a/openless-all/app/e2e/capsule-input-ownership.spec.ts b/openless-all/app/e2e/capsule-input-ownership.spec.ts index 2bdd7f740..707548be2 100644 --- a/openless-all/app/e2e/capsule-input-ownership.spec.ts +++ b/openless-all/app/e2e/capsule-input-ownership.spec.ts @@ -1,9 +1,10 @@ +import { fixtureOrigin } from './support/server'; import { expect, test } from '@playwright/test'; test('the real Mac capsule keeps controls interactive during continuous animation', async ({ page, }) => { - await page.goto('http://127.0.0.1:5326/e2e/fixtures/capsule-motion.html?full&os=mac'); + await page.goto(`${fixtureOrigin}/e2e/fixtures/capsule-motion.html?full&os=mac`); await page.waitForFunction(() => (window as any).fixture.hasListener('capsule:state')); await page.evaluate(() => { const fixture = (window as any).fixture; @@ -52,10 +53,9 @@ test('the real Mac capsule keeps controls interactive during continuous animatio .toBe(true); await confirm.click(); await cancel.click(); - await expect.poll(() => page.evaluate(() => (window as any).fixture.dictationActions)).toEqual([ - 'stop_dictation', - 'cancel_dictation', - ]); + await expect + .poll(() => page.evaluate(() => (window as any).fixture.dictationActions)) + .toEqual(['stop_dictation', 'cancel_dictation']); await page.locator('.ol-classic-translation [role="combobox"]').click(); await expect(page.getByRole('listbox')).toBeVisible(); await page diff --git a/openless-all/app/e2e/capsule-live-display.spec.ts b/openless-all/app/e2e/capsule-live-display.spec.ts index 2ad79d868..9a03e2d25 100644 --- a/openless-all/app/e2e/capsule-live-display.spec.ts +++ b/openless-all/app/e2e/capsule-live-display.spec.ts @@ -1,6 +1,7 @@ +import { fixtureOrigin } from './support/server'; import { expect, test } from '@playwright/test'; -const fixture = 'http://127.0.0.1:5326/e2e/fixtures/capsule-motion.html'; +const fixture = `${fixtureOrigin}/e2e/fixtures/capsule-motion.html`; for (const rail of [false, true]) { test(`hidden mirror cleanup cannot restart the live ${rail ? 'transcript rail' : 'capsule'}`, async ({ diff --git a/openless-all/app/e2e/capsule-reference-motion.spec.ts b/openless-all/app/e2e/capsule-reference-motion.spec.ts index 5817a83da..adc883604 100644 --- a/openless-all/app/e2e/capsule-reference-motion.spec.ts +++ b/openless-all/app/e2e/capsule-reference-motion.spec.ts @@ -1,5 +1,6 @@ +import { fixtureOrigin } from './support/server'; import { expect, test, type Page } from '@playwright/test'; -const fixture = 'http://127.0.0.1:5326/e2e/fixtures/capsule-motion.html'; +const fixture = `${fixtureOrigin}/e2e/fixtures/capsule-motion.html`; async function patch(page: Page, value: Record) { await page.locator('.ol-default-capsule').waitFor(); await page.evaluate((value) => (window as any).fixture.setCapsule(value), value); diff --git a/openless-all/app/e2e/capsule-theme.spec.ts b/openless-all/app/e2e/capsule-theme.spec.ts index 067499133..1bd972fb3 100644 --- a/openless-all/app/e2e/capsule-theme.spec.ts +++ b/openless-all/app/e2e/capsule-theme.spec.ts @@ -1,6 +1,7 @@ +import { fixtureOrigin } from './support/server'; import { expect, test, type Page } from '@playwright/test'; -const fixture = 'http://127.0.0.1:5326/e2e/fixtures/capsule-motion.html?themeSync=1'; +const fixture = `${fixtureOrigin}/e2e/fixtures/capsule-motion.html?themeSync=1`; async function preference(page: Page, theme: 'light' | 'dark' | 'system') { await page.evaluate((theme) => (window as any).fixture.setTheme(theme), theme); } diff --git a/openless-all/app/e2e/channel-draft.spec.ts b/openless-all/app/e2e/channel-draft.spec.ts new file mode 100644 index 000000000..83522a37c --- /dev/null +++ b/openless-all/app/e2e/channel-draft.spec.ts @@ -0,0 +1,88 @@ +import { expect, test, type Page } from '@playwright/test'; +import { fixtureOrigin } from './support/server'; + +interface ChannelFixture { + calls: string[]; + reject(): void; + hold(): void; + release(): void; + forceClose(): void; +} + +declare global { + interface Window { + channelFixture: ChannelFixture; + } +} + +async function openEditor(page: Page) { + await page.goto(`${fixtureOrigin}/e2e/fixtures/channel-draft.html`); + const editor = page.getByRole('dialog', { name: '编辑渠道' }); + const credential = editor.getByLabel('API 密钥', { exact: true }); + const provider = editor.getByRole('combobox', { name: '供应商' }); + await expect(credential).toBeEnabled(); + return { editor, credential, provider }; +} + +test('provider changes only after the old credential is saved; a failed write keeps the draft', async ({ + page, +}) => { + const { editor, credential, provider } = await openEditor(page); + await page.evaluate(() => window.channelFixture.reject()); + await credential.fill('fixture credential'); + await provider.click(); + await page.getByRole('option', { name: 'DeepSeek', exact: true }).click(); + await expect(editor.getByRole('alert')).toContainText('操作失败'); + await expect(credential).toHaveValue('fixture credential'); + await expect(provider).not.toContainText('DeepSeek'); + const calls = () => page.evaluate(() => window.channelFixture.calls as string[]); + expect(await calls()).not.toContain('provider:deepseek'); + + await page.evaluate(() => window.channelFixture.release()); + await provider.click(); + await page.getByRole('option', { name: 'DeepSeek', exact: true }).click(); + await expect(provider).toContainText('DeepSeek'); + const saved = await calls(); + expect(saved.filter((call) => call === 'provider:deepseek')).toHaveLength(1); + expect(saved.indexOf('credential-committed')).toBeLessThan(saved.indexOf('provider:deepseek')); +}); + +test('invalid protocol settings block a provider switch without discarding the draft', async ({ + page, +}) => { + const { editor, provider } = await openEditor(page); + const limit = editor.getByRole('spinbutton', { name: '最大输出 tokens' }); + await expect(limit).toBeEnabled(); + await limit.fill('0'); + await provider.click(); + await page.getByRole('option', { name: 'DeepSeek', exact: true }).click(); + await expect(editor.getByRole('alert').filter({ hasText: '操作失败' })).toBeVisible(); + await expect(limit).toHaveValue('0'); + await expect(provider).not.toContainText('DeepSeek'); + expect(await page.evaluate(() => window.channelFixture.calls)).not.toContain('provider:deepseek'); +}); + +for (const exit of ['close', 'unmount'] as const) { + test(`a queued provider switch cannot commit after editor ${exit}`, async ({ page }) => { + const { editor, credential, provider } = await openEditor(page); + await page.evaluate(() => window.channelFixture.hold()); + await credential.fill('held fixture credential'); + await provider.click(); + await page.getByRole('option', { name: 'DeepSeek', exact: true }).click(); + await expect(provider).toBeDisabled(); + if (exit === 'close') { + await editor.getByRole('button', { name: '关闭' }).first().click(); + } else { + await page.evaluate(() => window.channelFixture.forceClose()); + await expect(page.getByText('Editor closed')).toBeVisible(); + } + await page.evaluate(() => window.channelFixture.release()); + await expect(page.getByText('Editor closed')).toBeVisible(); + await expect + .poll(() => page.evaluate(() => window.channelFixture.calls)) + .toContain('credential-committed'); + expect(await page.evaluate(() => window.channelFixture.calls)).not.toContain( + 'provider:deepseek', + ); + }); +} diff --git a/openless-all/app/e2e/clipboard-feedback.spec.ts b/openless-all/app/e2e/clipboard-feedback.spec.ts new file mode 100644 index 000000000..82438673f --- /dev/null +++ b/openless-all/app/e2e/clipboard-feedback.spec.ts @@ -0,0 +1,32 @@ +import { expect, test } from '@playwright/test'; +import { fixtureOrigin } from './support/server'; + +test('remote input and About only report a copy once the native clipboard accepts it', async ({ + page, +}) => { + await page.goto(`${fixtureOrigin}/e2e/fixtures/startup-gate.html?os=win&clipboard`); + await page.getByRole('button', { name: '设置', exact: true }).click(); + const settings = page.getByRole('dialog', { name: '设置', exact: true }); + await settings.getByRole('button', { name: /^手机与远程输入/ }).click(); + const fingerprintCopy = settings.getByRole('button', { name: '复制完整指纹' }); + await fingerprintCopy.click(); + await expect(page.locator('.ol-notification-card').filter({ hasText: '操作失败' })).toBeVisible(); + await expect(fingerprintCopy).toBeVisible(); + + await page.evaluate(() => (window as any).startupFixture.allowClipboard(true)); + await fingerprintCopy.click(); + await expect(settings.getByRole('button', { name: '指纹已复制' })).toBeVisible(); + + await settings + .getByRole('navigation', { name: '设置分类' }) + .getByRole('button', { name: '关于与更新', exact: true }) + .click(); + const code = settings.locator('kbd').getByText('1078960553'); + const qq = code.locator('..').getByRole('button'); + await page.evaluate(() => (window as any).startupFixture.allowClipboard(false)); + await qq.click(); + await expect(settings.getByText('已复制', { exact: true })).toHaveCount(0); + await page.evaluate(() => (window as any).startupFixture.allowClipboard(true)); + await qq.click(); + await expect(settings.getByText('已复制', { exact: true })).toBeVisible(); +}); diff --git a/openless-all/app/e2e/content-actions.spec.ts b/openless-all/app/e2e/content-actions.spec.ts new file mode 100644 index 000000000..951a9b054 --- /dev/null +++ b/openless-all/app/e2e/content-actions.spec.ts @@ -0,0 +1,46 @@ +import { expect, test } from '@playwright/test'; + +test('dictionary deletion waits for confirmation and keeps selection after cancellation', async ({ + page, +}) => { + await page.goto('/'); + await page.getByRole('button', { name: '词典', exact: true }).click(); + const dictionary = page.locator('[data-ol-page="vocab"]'); + await expect(dictionary).toHaveAttribute('data-transition-phase', 'settled'); + await dictionary.getByRole('button', { name: '选择', exact: true }).click(); + await dictionary.getByRole('checkbox', { name: '选择当前结果' }).check(); + const remove = dictionary.getByRole('button', { name: /^删除已选/ }); + await remove.click(); + const confirmation = page.getByRole('dialog', { name: /^删除已选/ }); + await confirmation.getByRole('button', { name: '取消', exact: true }).click(); + await expect(remove).toBeFocused(); + await expect(remove).toBeVisible(); + await remove.click(); + await confirmation.getByRole('button', { name: '删除', exact: true }).click(); + await expect(remove).toHaveCount(0); + await expect(dictionary.getByRole('checkbox', { name: '选择当前结果' })).toBeDisabled(); +}); + +test('style editor retains its draft when discard is cancelled', async ({ page }) => { + await page.goto('/'); + await page.getByRole('button', { name: '风格', exact: true }).click(); + await page.getByRole('button', { name: '润色模式', exact: true }).click(); + const style = page.locator('[data-ol-page="style"]'); + await expect(style).toHaveAttribute('data-transition-phase', 'settled'); + await style + .getByRole('button', { name: '编辑', exact: true }) + .and(style.locator('button:enabled')) + .first() + .click(); + const editor = style.getByRole('dialog', { name: /编辑/ }); + const prompt = editor.locator('textarea:visible').first(); + await expect(prompt).toBeVisible(); + await prompt.fill('A draft that should survive a cancelled discard.'); + await editor.getByRole('button', { name: '关闭', exact: true }).click(); + const discard = page.getByRole('dialog', { name: '放弃修改?' }); + await discard.getByRole('button', { name: '取消', exact: true }).click(); + await expect(prompt).toHaveValue('A draft that should survive a cancelled discard.'); + await editor.getByRole('button', { name: '关闭', exact: true }).click(); + await discard.getByRole('button', { name: '确认', exact: true }).click(); + await expect(editor).not.toBeVisible(); +}); diff --git a/openless-all/app/e2e/control-geometry-regressions.spec.ts b/openless-all/app/e2e/control-geometry-regressions.spec.ts index f3ba12a22..82181f2c7 100644 --- a/openless-all/app/e2e/control-geometry-regressions.spec.ts +++ b/openless-all/app/e2e/control-geometry-regressions.spec.ts @@ -1,10 +1,11 @@ +import { fixtureOrigin } from './support/server'; import { expect, test } from '@playwright/test'; import { openCapsuleStyleSettings, settleNavigation } from './support/navigation'; test('recording capsule retains its size and original pill geometry with translation', async ({ page, }) => { - await page.goto('http://127.0.0.1:5326/e2e/fixtures/capsule-motion.html?full&os=mac'); + await page.goto(`${fixtureOrigin}/e2e/fixtures/capsule-motion.html?full&os=mac`); await page.waitForFunction(() => (window as any).fixture.hasListener('capsule:state')); await page.evaluate(() => (window as any).fixture.emit('capsule:state', { @@ -167,7 +168,7 @@ test('history list keeps its rounded surface and native trackpad scrolling; corr }); test('the WebKit fallback preserves capsule, switch and popup exceptions', async ({ page }) => { - await page.goto('http://127.0.0.1:5326/e2e/fixtures/refinements.html'); + await page.goto(`${fixtureOrigin}/e2e/fixtures/refinements.html`); const result = await page.evaluate(async () => { const css = await (await fetch('/src/styles/continuous-corners.css?direct')).text(); const source = document.createElement('style'); diff --git a/openless-all/app/e2e/desktop-onboarding.spec.ts b/openless-all/app/e2e/desktop-onboarding.spec.ts index 024ba3855..48650561e 100644 --- a/openless-all/app/e2e/desktop-onboarding.spec.ts +++ b/openless-all/app/e2e/desktop-onboarding.spec.ts @@ -1,3 +1,4 @@ +import { fixtureOrigin } from './support/server'; import { expect, test, type Page } from '@playwright/test'; const active = (page: Page) => @@ -109,7 +110,7 @@ test('a narrow reduced-motion guide preserves controls, answers, and keyboard fo await expect(active(page).getByRole('textbox')).toBeVisible(); }); -const fixtureUrl = 'http://127.0.0.1:5326/e2e/fixtures/desktop-onboarding.html?os=mac'; +const fixtureUrl = `${fixtureOrigin}/e2e/fixtures/desktop-onboarding.html?os=mac`; test('Windows opens microphone settings, refreshes on return, and permits deferral without a device', async ({ page, }) => { diff --git a/openless-all/app/e2e/entry-routes.spec.ts b/openless-all/app/e2e/entry-routes.spec.ts new file mode 100644 index 000000000..2810e03eb --- /dev/null +++ b/openless-all/app/e2e/entry-routes.spec.ts @@ -0,0 +1,49 @@ +import { expect, test } from '@playwright/test'; + +const profiles = [ + { os: 'mac', width: 1300, height: 835 }, + { os: 'win', width: 1240, height: 800 }, + { os: 'android', width: 412, height: 892 }, + { os: 'harmony', width: 420, height: 900 }, +] as const; + +test('framed browser profiles use their content size and preserve unscaled root coordinates', async ({ + page, +}) => { + await page.setViewportSize({ width: 800, height: 700 }); + await page.addInitScript(() => { + localStorage.setItem('ol-font-scale', 'large'); + localStorage.setItem('ol.theme', 'light'); + }); + + for (const { os, width, height } of profiles) { + await page.goto(`/?os=${os}&frame=1`); + const frame = page.locator('.ol-preview-frame'); + const boundary = page.locator('.ol-app-viewport'); + await expect(page.locator('html')).toHaveAttribute('data-ol-platform', os); + await expect(boundary.locator('.ol-winchrome')).toBeVisible(); + expect(await boundary.boundingBox()).toMatchObject({ width, height }); + expect(await frame.boundingBox()).toMatchObject({ width, height }); + expect( + await boundary.evaluate((element) => + getComputedStyle(element).getPropertyValue('--ol-interface-scale').trim(), + ), + ).toBe('1.1'); + expect( + await page.locator('html').evaluate((element) => element.style.getPropertyValue('zoom')), + ).toBe(''); + if (width > 800) expect((await boundary.boundingBox())?.x).toBe(0); + const mobileNav = boundary.locator('.ol-mobile-bottom-nav'); + await expect(mobileNav).toHaveCount(os === 'android' || os === 'harmony' ? 1 : 0); + } +}); + +test('auxiliary routes ignore the main window zoom preference and preview frame', async ({ + page, +}) => { + await page.addInitScript(() => localStorage.setItem('ol-font-scale', 'large')); + await page.goto('/?window=voice-edit&frame=1'); + await expect(page.locator('.ol-voice-edit-window')).toBeVisible(); + await expect(page.locator('.ol-preview-frame')).toHaveCount(0); + await expect(page.locator('.ol-app-viewport')).toHaveAttribute('data-ol-scale', 'fixed'); +}); diff --git a/openless-all/app/e2e/fixtures/android-onboarding.tsx b/openless-all/app/e2e/fixtures/android-onboarding.tsx index 6296c2d17..49cb5efe6 100644 --- a/openless-all/app/e2e/fixtures/android-onboarding.tsx +++ b/openless-all/app/e2e/fixtures/android-onboarding.tsx @@ -1,18 +1,31 @@ import React, { useState } from 'react'; +import { AppViewport } from '../../src/ui/layout/AppViewport'; +import { InteractionProvider } from '../../src/ui/overlays/InteractionProvider'; +import type { UserPreferences } from '../../src/api/contracts'; import { createRoot } from 'react-dom/client'; import '../../src/styles/tokens.css'; import '../../src/styles/global.css'; import '../../src/styles/refinements.css'; -import '../../src/styles/desktop-onboarding.css'; +import '../../src/features/onboarding/desktop-onboarding.css'; let mocks: typeof import('../../src/lib/ipc/mock-data'); const calls: string[] = []; +const writes: Array> = []; +let settings: UserPreferences; +let revision = 0; +let rejectWrite = false; Object.assign(window, { - androidGuideFixture: { calls }, + androidGuideFixture: { + calls, + writes, + rejectNextWrite: () => { + rejectWrite = true; + }, + }, __TAURI_EVENT_PLUGIN_INTERNALS__: { unregisterListener() {} }, __TAURI_INTERNALS__: { transformCallback: () => 1, - invoke: async (command: string) => { + invoke: async (command: string, args?: { edits?: Record }) => { calls.push(command); if (command === 'get_startup_snapshot') return { contractVersion: '2.0.0', backend: { running: true } }; @@ -29,20 +42,37 @@ Object.assign(window, { messageKey: 'not_installed', accessibility: { registered: true, operational: true, messageKey: '' }, }; - if (command === 'get_settings') return mocks.mockSettings; + if (command === 'get_settings') return structuredClone(settings); if (command === 'get_settings_snapshot') - return { preferences: mocks.mockSettings, revision: 0 }; + return { preferences: structuredClone(settings), revision }; + if (command === 'update_setting_fields') { + const edits = args?.edits ?? {}; + writes.push(edits); + if (rejectWrite) { + rejectWrite = false; + throw new Error('Fixture rejected the preference write'); + } + for (const [path, value] of Object.entries(edits)) { + const keys = path.slice(1).split('/'); + let target = settings as unknown as Record; + for (const key of keys.slice(0, -1)) target = target[key] as Record; + target[keys[keys.length - 1]] = value; + } + return { preferences: structuredClone(settings), revision: ++revision }; + } if (command === 'get_hotkey_capability') return mocks.mockHotkeyCapability; // Keep the real provider step populated so advancing does not open an editor. if (command === 'list_channels') - return [{ - id: 'groq', - name: 'Groq', - providerType: 'groq', - enabled: true, - order: 0, - lastTest: null, - }]; + return [ + { + id: 'groq', + name: 'Groq', + providerType: 'groq', + enabled: true, + order: 0, + lastTest: null, + }, + ]; if (command === 'list_provider_descriptors') return []; if (command === 'read_credential') return ''; return null; @@ -50,6 +80,7 @@ Object.assign(window, { }, }); mocks = await import('../../src/lib/ipc/mock-data'); +settings = structuredClone(mocks.mockSettings); const [{ Onboarding }, { HotkeySettingsProvider }, { i18nReady }] = await Promise.all([ import('../../src/components/Onboarding'), import('../../src/state/HotkeySettingsContext'), @@ -61,7 +92,7 @@ function Fixture() { const [completed, setCompleted] = useState(false); return ( - {/* Match App.tsx's containing block and layer. Import the production layer CSS + {/* Match MainWindow's containing block and layer. Import the production layer CSS above; a flex test wrapper would hide the broken flex: 1 sizing contract. */}
{completed ? ( @@ -77,6 +108,10 @@ function Fixture() { } createRoot(document.getElementById('root')!).render( - + + + + + , ); diff --git a/openless-all/app/e2e/fixtures/capsule-motion.tsx b/openless-all/app/e2e/fixtures/capsule-motion.tsx index ca8dd2bd0..f4af4ce49 100644 --- a/openless-all/app/e2e/fixtures/capsule-motion.tsx +++ b/openless-all/app/e2e/fixtures/capsule-motion.tsx @@ -4,6 +4,7 @@ import { createRoot } from 'react-dom/client'; import type { CapsuleState, ThemeMode } from '../../src/lib/types'; import '../../src/styles/tokens.css'; import '../../src/styles/global.css'; +import { AppViewport } from '../../src/ui/layout/AppViewport'; const callbacks = new Map void>(); const listeners = new Map>(); @@ -45,6 +46,17 @@ const bridge = { bridge.emit('prefs:changed', { themeMode }); }, sizes: [] as boolean[], + holdQaGeometry: false, + fallbackReports: [] as { presentationId: number; height: number }[], + copiedFallback: [] as string[], + rejectQaExpansion: false, + applyQaGeometry(expanded: boolean, width?: number, height?: number) { + const host = document.querySelector('#native-host'); + if (!host) return; + host.style.width = `${width ?? (expanded ? 760 : 480)}px`; + host.style.height = `${height ?? (expanded ? 416 : 80)}px`; + host.style.bottom = expanded ? '48px' : '8px'; + }, target: { sessionId: 'recording-a', targetLanguage: 'English', @@ -145,15 +157,19 @@ window.__TAURI_INTERNALS__ = { bridge.emit('prefs:changed', {}); return { ...bridge.target }; } + if (command === 'report_insert_fallback_card_height') { + bridge.fallbackReports.push(args); + return; + } + if (command === 'copy_text_to_clipboard') { + bridge.copiedFallback.push(args.text); + return; + } if (command === 'qa_get_snapshot') return { kind: 'idle', messages: [] }; if (command === 'qa_window_set_expanded') { bridge.sizes.push(args.expanded); - const host = document.querySelector('#native-host'); - if (host) { - host.style.width = args.expanded ? '760px' : '480px'; - host.style.height = args.expanded ? '416px' : '80px'; - host.style.bottom = args.expanded ? '48px' : '8px'; - } + if (args.expanded && bridge.rejectQaExpansion) throw new Error('native resize failed'); + if (!bridge.holdQaGeometry) bridge.applyQaGeometry(args.expanded); return; } if (command === 'qa_window_dismiss') bridge.emit('chat-panel:closing', {}); @@ -163,6 +179,7 @@ window.__TAURI_INTERNALS__ = { Object.assign(window, { __TAURI_EVENT_PLUGIN_INTERNALS__: { unregisterListener() {} } }); const { i18nReady } = await import('../../src/i18n'); await i18nReady; +const { InsertFallbackCard } = await import('../../src/features/capsule/InsertFallbackCard'); const { OpenLessPill } = await import('../../src/components/OpenLessCapsule'); const { CapsuleTranslationBadge, CapsuleTranscriptOverlay } = await import('../../src/components/LiveTranscriptPill'); @@ -211,7 +228,17 @@ function CapsuleFixture() { } document.body.style.background = '#0b1215'; createRoot(document.getElementById('root')!).render( - params.has('rail') ? ( + params.has('fallback') ? ( + + + + ) : params.has('rail') ? ( ) : params.has('full') ? (
- + + +
) : ( - + + + ), ); diff --git a/openless-all/app/e2e/fixtures/channel-draft.html b/openless-all/app/e2e/fixtures/channel-draft.html new file mode 100644 index 000000000..be8a89c34 --- /dev/null +++ b/openless-all/app/e2e/fixtures/channel-draft.html @@ -0,0 +1,11 @@ + + + + + + + +
+ + + diff --git a/openless-all/app/e2e/fixtures/channel-draft.tsx b/openless-all/app/e2e/fixtures/channel-draft.tsx new file mode 100644 index 000000000..e7e0b6667 --- /dev/null +++ b/openless-all/app/e2e/fixtures/channel-draft.tsx @@ -0,0 +1,122 @@ +import React, { useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import type { Channel } from '../../src/api/providers'; +import type { PresetOption } from '../../src/features/providers/channelCatalog'; +import '../../src/styles/tokens.css'; +import '../../src/styles/global.css'; +import '../../src/styles/refinements.css'; + +const calls: string[] = []; +const credentials = new Map(); +let disposition: 'accept' | 'reject' | 'hold' = 'accept'; +let settle: (() => void) | undefined; +const fixture = { + calls, + reject: () => { + disposition = 'reject'; + }, + hold: () => { + disposition = 'hold'; + }, + release: () => { + disposition = 'accept'; + settle?.(); + }, +}; +let mockSettings: Awaited>; +let getPreviewProfile: typeof import('../../src/preview/profiles').getPreviewProfile; +Object.assign(window, { + channelFixture: fixture, + __TAURI_INTERNALS__: { + transformCallback: () => 1, + async invoke(command: string, args: Record = {}) { + if (command === 'get_startup_snapshot') { + return { contractVersion: '2.0.0', backend: { running: true } }; + } + if (command === 'get_settings_snapshot') return { revision: 0, preferences: mockSettings }; + if (command === 'get_platform_capabilities') return getPreviewProfile('mac').capabilities; + if (command === 'get_hotkey_capability') return getPreviewProfile('mac').hotkeyCapability; + if (command === 'read_credential') return credentials.get(args.account) ?? null; + if (command === 'set_credential') { + if (args.account.endsWith('api_key')) { + calls.push('credential-start'); + if (disposition === 'hold') + await new Promise((resolve) => { + settle = resolve; + }); + if (disposition === 'reject') { + calls.push('credential-rejected'); + throw new Error('Fixture keychain refused the write'); + } + calls.push('credential-committed'); + } + credentials.set(args.account, args.value); + } + if (command === 'set_channel_provider_type') calls.push(`provider:${args.providerType}`); + return null; + }, + }, + __TAURI_EVENT_PLUGIN_INTERNALS__: { unregisterListener() {} }, +}); + +const [channelModule, preferenceModule, viewportModule, translationModule, profiles, mocks] = + await Promise.all([ + import('../../src/features/providers/ChannelEditor'), + import('../../src/data/preferences'), + import('../../src/ui/layout/AppViewport'), + import('../../src/i18n'), + import('../../src/preview/profiles'), + import('../../src/lib/ipc/mock-data'), + ]); +getPreviewProfile = profiles.getPreviewProfile; +mockSettings = structuredClone(mocks.mockSettings); +await translationModule.i18nReady; +const { ChannelEditor } = channelModule; +const { HotkeySettingsProvider } = preferenceModule; +const { AppViewport } = viewportModule; + +const channel: Channel = { + id: 'fixture-channel', + name: 'Fixture channel', + order: 0, + providerType: 'custom', + enabled: true, + lastTest: null, +}; +const presets: PresetOption[] = [ + { + id: 'custom', + nameKey: 'custom', + authRequirement: 'api_key', + defaultRequestFormat: 'messages', + supportedRequestFormats: ['messages'], + }, + { id: 'deepseek', nameKey: 'deepseek', authRequirement: 'api_key' }, +]; +function Fixture() { + const [open, setOpen] = useState(true); + Object.assign(fixture, { forceClose: () => setOpen(false) }); + return ( + + + {open ? ( + setOpen(false)} + onChanged={() => { + calls.push('refreshed'); + }} + onUserMutation={() => {}} + /> + ) : ( +

Editor closed

+ )} +
+
+ ); +} +createRoot(document.getElementById('root')!).render(); diff --git a/openless-all/app/e2e/fixtures/desktop-onboarding.tsx b/openless-all/app/e2e/fixtures/desktop-onboarding.tsx index 14ae122b7..aeeebe730 100644 --- a/openless-all/app/e2e/fixtures/desktop-onboarding.tsx +++ b/openless-all/app/e2e/fixtures/desktop-onboarding.tsx @@ -6,8 +6,17 @@ import '../../src/styles/global.css'; import '../../src/styles/refinements.css'; let prefs: typeof import('../../src/lib/ipc/mock-data').mockSettings; -let mockHotkeyCapability: typeof import('../../src/lib/ipc/mock-data').mockHotkeyCapability; +let mockHotkeyCapability: import('../../src/api/contracts').HotkeyCapability | null; let mockCredentialsStatus: typeof import('../../src/lib/ipc/mock-data').mockCredentialsStatus; +const fixtureOS = new URLSearchParams(location.search).get('os') === 'win' ? 'win' : 'mac'; +Object.defineProperty(navigator, 'platform', { + configurable: true, + value: fixtureOS === 'win' ? 'Win32' : 'MacIntel', +}); +Object.defineProperty(navigator, 'userAgent', { + configurable: true, + value: fixtureOS === 'win' ? 'Windows' : 'Macintosh', +}); const calls: string[] = []; const fixture = { microphone: 'denied', @@ -60,7 +69,8 @@ Object.assign(window, { }); const mocks = await import('../../src/lib/ipc/mock-data'); prefs = structuredClone(mocks.mockSettings); -mockHotkeyCapability = mocks.mockHotkeyCapability; +const { getPreviewProfile } = await import('../../src/preview/profiles'); +mockHotkeyCapability = getPreviewProfile(fixtureOS).hotkeyCapability; mockCredentialsStatus = mocks.mockCredentialsStatus; const [{ DesktopOnboarding }, { HotkeySettingsProvider }, { i18nReady }] = await Promise.all([ import('../../src/components/DesktopOnboarding'), diff --git a/openless-all/app/e2e/fixtures/refinements.tsx b/openless-all/app/e2e/fixtures/refinements.tsx index 52189a5e8..93e8e041d 100644 --- a/openless-all/app/e2e/fixtures/refinements.tsx +++ b/openless-all/app/e2e/fixtures/refinements.tsx @@ -7,6 +7,7 @@ import { initInteractionMode } from '../../src/lib/interactionMode'; import { Toggle } from '../../src/pages/settings/shared'; import { Collapse, ExpandableText } from '../../src/components/ui/Disclosure'; import { SelectLite } from '../../src/components/ui/SelectLite'; +import { AppViewport } from '../../src/ui/layout/AppViewport'; import { PresenceModal } from '../../src/components/ui/Modal'; import { ChoiceChips } from '../../src/components/ui/ChoiceChips'; import { DismissibleCard } from '../../src/components/ui/DismissibleCard'; @@ -188,7 +189,9 @@ initInteractionMode(); void i18nReady.then(() => createRoot(document.getElementById('root')!).render( - + + + , ), ); diff --git a/openless-all/app/e2e/fixtures/startup-gate.tsx b/openless-all/app/e2e/fixtures/startup-gate.tsx index 697dd0ac2..13c8993db 100644 --- a/openless-all/app/e2e/fixtures/startup-gate.tsx +++ b/openless-all/app/e2e/fixtures/startup-gate.tsx @@ -1,11 +1,30 @@ import React from 'react'; import { createRoot } from 'react-dom/client'; -import type { CredentialsStatus } from '../../src/lib/types'; +import type { CredentialsStatus } from '../../src/api/contracts'; +import type { VoiceEditSnapshot } from '../../src/api/voice-edit'; import '../../src/styles/tokens.css'; import '../../src/styles/global.css'; +import '../../src/styles/overlays.css'; +import '../../src/styles/refinements.css'; const params = new URLSearchParams(location.search); const mode = params.get('credentials'); +const android = params.get('os') === 'android'; +const exerciseClipboard = params.has('clipboard'); +let clipboardAllowed = false; +if (android) localStorage.setItem('openless.androidSetupWizardComplete', '1'); +let voice: VoiceEditSnapshot | null = null; +const cancelRequests: Array<{ id?: string; resolve: () => void; reject: (reason: Error) => void }> = + []; +const callbacks = new Map void>(); +const subscriptions = new Map(); +let callbackId = 0; +let listenerId = 0; +const emit = (event: string, payload: unknown) => { + for (const [id, listener] of subscriptions) { + if (listener.event === event) callbacks.get(listener.callbackId)?.({ id, event, payload }); + } +}; const calls: string[] = []; const pending: { resolve: (value: CredentialsStatus) => void; reject: (error: Error) => void }[] = []; @@ -18,17 +37,54 @@ const status = (configured: boolean) => ({ }); Object.assign(window, { - __TAURI_EVENT_PLUGIN_INTERNALS__: { unregisterListener() {} }, + __TAURI_EVENT_PLUGIN_INTERNALS__: { + unregisterListener: (_event: string, id: number) => subscriptions.delete(id), + }, startupFixture: { calls, + allowClipboard: (allowed: boolean) => { + clipboardAllowed = allowed; + }, + emit, + listening: (event: string) => + [...subscriptions.values()].some((listener) => listener.event === event), + showVoice: (sessionId: string) => { + voice = { + sessionId, + phase: 'preview', + target: { kind: 'full_field' }, + context: { + fieldText: '', + dictatedSegment: '', + draft: sessionId, + preview: sessionId, + turns: [], + }, + }; + emit('voice-edit:show', {}); + }, + pendingCancels: () => cancelRequests.map((request) => request.id), + finishCancel: (succeed: boolean) => { + const request = cancelRequests.shift(); + if (!request) throw new Error('No pending voice dismissal'); + if (succeed) request.resolve(); + else request.reject(new Error('Microphone is still busy')); + }, resolve: () => pending.splice(0).forEach(({ resolve }) => resolve(status(false))), reject: () => pending.splice(0).forEach(({ reject }) => reject(new Error('Late store failure'))), }, __TAURI_INTERNALS__: { metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, - transformCallback: () => 1, - invoke: async (command: string) => { + transformCallback: (callback: (value: unknown) => void) => { + const id = ++callbackId; + callbacks.set(id, callback); + return id; + }, + invoke: async ( + command: string, + args?: { event?: string; handler?: number; sessionId?: string }, + ) => { calls.push(command); if (command === 'get_startup_snapshot') return { @@ -36,10 +92,45 @@ Object.assign(window, { backend: { running: true }, }; if (command === 'get_platform_capabilities') - return { platform: 'desktop', supportsDesktopHotkey: true }; - if (command === 'get_settings') return mocks.mockSettings; + return { platform: android ? 'android' : 'desktop', supportsDesktopHotkey: !android }; + if (command === 'plugin:event|listen') { + const id = ++listenerId; + subscriptions.set(id, { event: args!.event!, callbackId: args!.handler! }); + return id; + } + if (command === 'get_voice_edit_state') return voice; + if (command === 'qa_get_snapshot') return { kind: 'idle', messages: [] }; + if (command === 'qa_window_dismiss') { + emit('qa:dismiss', {}); + return; + } + if (command === 'cancel_voice_edit_session') { + const id = args?.sessionId; + await new Promise((resolve, reject) => cancelRequests.push({ id, resolve, reject })); + if (voice && voice.sessionId === id) voice = null; + return null; + } + if (command === 'get_settings') + return { ...mocks.mockSettings, remoteInputEnabled: exerciseClipboard }; if (command === 'get_settings_snapshot') - return { preferences: mocks.mockSettings, revision: 0 }; + return { + preferences: { ...mocks.mockSettings, remoteInputEnabled: exerciseClipboard }, + revision: 0, + }; + if (exerciseClipboard && command === 'get_remote_input_status') + return { + running: true, + starting: false, + port: 8443, + urlsStale: false, + urls: ['https://192.0.2.10:8443'], + pin: '000001', + caFingerprintSha256: 'a'.repeat(64), + }; + if (exerciseClipboard && command === 'copy_text_to_clipboard') { + if (!clipboardAllowed) throw new Error('Clipboard write rejected'); + return; + } if (command === 'get_hotkey_capability') return mocks.mockHotkeyCapability; if (command === 'get_hotkey_status') return { state: 'ready' }; if (command === 'check_microphone_permission' || command === 'check_accessibility_permission') @@ -59,21 +150,12 @@ Object.assign(window, { }); mocks = await import('../../src/lib/ipc/mock-data'); const [{ App }, { i18nReady }] = await Promise.all([ - import('../../src/App'), + import('../../src/app/App'), import('../../src/i18n'), ]); await i18nReady; createRoot(document.getElementById('root')!).render( - + , ); diff --git a/openless-all/app/e2e/fixtures/updates-interactions.html b/openless-all/app/e2e/fixtures/updates-interactions.html new file mode 100644 index 000000000..44893f164 --- /dev/null +++ b/openless-all/app/e2e/fixtures/updates-interactions.html @@ -0,0 +1,11 @@ + + + + + Update window interactions + + +
+ + + diff --git a/openless-all/app/e2e/fixtures/updates-interactions.tsx b/openless-all/app/e2e/fixtures/updates-interactions.tsx new file mode 100644 index 000000000..8a0e2782e --- /dev/null +++ b/openless-all/app/e2e/fixtures/updates-interactions.tsx @@ -0,0 +1,96 @@ +import { StrictMode, useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import '../../src/styles/tokens.css'; +import '../../src/styles/global.css'; +import '../../src/styles/overlays.css'; +import '../../src/styles/refinements.css'; + +const writes: { command: string; args: unknown }[] = []; +let finishDownload: () => void = () => {}; +let nextCallback = 0; +const fixture = { + writes, + hideManual: () => {}, + checkInBackground: () => {}, + failDownload: false, + finishDownload: () => finishDownload(), +}; +Object.assign(window, { updateFixture: fixture }); +window.__TAURI_INTERNALS__ = { + transformCallback: () => ++nextCallback, + unregisterCallback() {}, + async invoke(command: string, args: unknown) { + writes.push({ command, args }); + if (command === 'get_startup_snapshot') + return { contractVersion: '2.0.0', backend: { running: true } }; + if (command === 'get_platform_capabilities') + return { platform: 'desktop', supportsAutoUpdate: true }; + if (command === 'app_check_update_with_channel') { + return { + rid: 19, + currentVersion: '2.0.1-beta.1', + version: '2.0.1', + rawJson: { url: 'https://example.test/update' }, + }; + } + if (command === 'plugin:updater|download') { + if (fixture.failDownload) throw new Error('network unavailable'); + await new Promise((resolve) => { + finishDownload = resolve; + }); + return 42; + } + return null; + }, +}; + +const { i18nReady } = await import('../../src/i18n'); +await i18nReady; +const { UpdateDialog, useAutoUpdate } = await import('../../src/components/AutoUpdate'); +const { AppViewport } = await import('../../src/ui/layout/AppViewport'); +const { InteractionProvider, useInteraction } = + await import('../../src/ui/overlays/InteractionProvider'); + +function Updates({ background }: { background: boolean }) { + const model = useAutoUpdate(background); + if (background) + fixture.checkInBackground = () => { + void model.checkForUpdates('stable'); + }; + return ( + <> + + + + ); +} + +function Fixture() { + const [manual, setManual] = useState(true); + const { confirm } = useInteraction(); + fixture.hideManual = () => setManual(false); + return ( +
+ + + {manual && } +
+ ); +} + +createRoot(document.querySelector('#root')!).render( + + + + + + + , +); diff --git a/openless-all/app/e2e/fixtures/viewport-interactions.html b/openless-all/app/e2e/fixtures/viewport-interactions.html new file mode 100644 index 000000000..52f80b3d6 --- /dev/null +++ b/openless-all/app/e2e/fixtures/viewport-interactions.html @@ -0,0 +1,11 @@ + + + + + Window viewport and interactions + + +
+ + + diff --git a/openless-all/app/e2e/fixtures/viewport-interactions.tsx b/openless-all/app/e2e/fixtures/viewport-interactions.tsx new file mode 100644 index 000000000..01b89139b --- /dev/null +++ b/openless-all/app/e2e/fixtures/viewport-interactions.tsx @@ -0,0 +1,221 @@ +import { StrictMode, useEffect, useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import { applyFontScale, type FontScaleId } from '../../src/lib/fontScale'; +import { i18nReady } from '../../src/i18n'; +import { GitHubActivity, type Contribution } from '../../src/ui/controls/GitHubActivity'; +import { Select } from '../../src/ui/controls/Select'; +import { SelectLite } from '../../src/ui/controls/SelectLite'; +import { Segmented } from '../../src/ui/controls/Segmented'; +import { AppViewport, PreviewFrame } from '../../src/ui/layout'; +import { + InteractionProvider, + Modal, + Tooltip, + TooltipProvider, + useInteraction, +} from '../../src/ui/overlays'; + +import '../../src/styles/tokens.css'; +import '../../src/styles/global.css'; +import '../../src/styles/overlays.css'; +import '../../src/styles/refinements.css'; + +const params = new URLSearchParams(location.search); +const options = Array.from({ length: 48 }, (_, index) => ({ + label: `Choice ${index + 1}`, + value: String(index), +})); +const contributions: Contribution[] = Array.from({ length: 365 }, (_, index) => ({ + date: new Date(Date.UTC(2025, 0, 1 + index)).toISOString().slice(0, 10), + count: index, + level: index % 4 === 0 ? 4 : 1, +})); +const apps = Array.from({ length: 35 }, (_, index) => ({ + name: `Application ${index + 1}`, + count: 99 - index, +})); + +const fixture = window as typeof window & { + dialogResolve?: (value: string) => void; + askAgain?: () => void; + disposePage?: () => void; +}; + +function ScopedPage({ result }: { result: (message: string) => void }) { + const { confirm } = useInteraction(); + return ( + + ); +} + +function Scene() { + const [selected, setSelected] = useState('2'); + const [segment, setSegment] = useState('short'); + const [results, setResults] = useState([]); + const [panel, setPanel] = useState(false); + const [scope, setScope] = useState(true); + const interaction = useInteraction(); + const result = (entry: string) => setResults((current) => [...current, entry]); + const ask = (title: string) => + void interaction + .confirm({ + title, + tone: 'danger', + description: + title === 'Long prompt' + ? 'Long detail with translated text. '.repeat(164) + : 'Choose carefully.', + confirmLabel: 'Proceed with change', + cancelLabel: 'Keep unchanged', + }) + .then((accepted) => result(`${title}:${accepted}`)); + + useEffect(() => { + fixture.askAgain = () => ask('New prompt'); + fixture.disposePage = () => setScope(false); + return () => { + delete fixture.askAgain; + delete fixture.disposePage; + }; + }); + + if (params.has('activity')) { + return ( +
+ +
+ ); + } + + return ( +
+
+ + + + + ; + }, + }) + .then((answer) => result(`dialog:${answer}`)) + } + > + Custom dialog + + + {scope && } +
+
+ {results.map((entry, index) => ( +
{entry}
+ ))} +
+ +
+ + Hover for information + + setName(event.target.value)} - maxLength={40} - placeholder={t('desktopGuide.name')} - aria-label={t('desktopGuide.name')} - autoComplete="given-name" - /> - - {!preview && ( -
- -
- )} - - )} - {isPermission && ( - <> -
- {id === 'microphone' ? : } - - {t(`desktopGuide.${granted(permission) ? 'allowed' : 'pending'}`)} - - {granted(permission) && ( - - )} -
-

- {permission === 'noDevice' - ? t('desktopGuide.unavailable') - : id === 'microphone' && os === 'win' && !granted(permission) - ? t('desktopGuide.windowsMicrophoneHint') - : t(`desktopGuide.${id}Hint`)} -

- - )} - {id === 'mode' && ( - <> -
- {(['traditional', 'multimodal'] as const).map((mode) => ( - - ))} -
- - )} - {(id === 'recognition' || id === 'polish') && ( - <> -
- - {t( - `desktopGuide.${serviceConfigured ? 'configured' : 'notConfigured'}`, - )} - - -
- - )} - {id === 'shortcut' && ( - <> -
- - {prefs && ( - { - await setDictationHotkey(binding); - await refreshPreferences(); - }} - /> - )} -
-

- {t( - `desktopGuide.${os === 'win' ? 'windowsShortcutHint' : 'shortcutHint'}`, - )} -

- {prefs && ( -

- {getHotkeyUsageHint(prefs.hotkey, undefined, prefs.dictationHotkey)} -

- )} - - )} - {id === 'finish' && ( - <> -
- {steps - .filter((item) => !['welcome', 'mode', 'finish'].includes(item)) - .map((item) => ( -
- {title(item)} - - {t( - `desktopGuide.${progress.answers[item] === 'done' ? 'allSet' : 'deferred'}`, - )} - -
- ))} -
- {deferred.length > 0 && ( -

{t('desktopGuide.finishPending')}

- )} - - )} - {(error || preferencesError) && ( -
- {error || t('desktopGuide.saveError')} - -
- )} - {storageError && ( -

- {t('desktopGuide.storageError')} -

- )} - - )} - - ); - })} - -
-
-
- {step !== 'welcome' && step !== 'finish' && ( - - )} - {isPermission && !preview && !granted(permission) && ( - - )} - -
-
- {index > 0 && ( - - )} - {t('desktopGuide.step', { current: index + 1, total: steps.length })} -
-
-
- { - setCredentials(await getCredentials()); - setEditing(false); - }} - /> -
- {preview ? t('desktopGuide.preview') : ''} - -
-
- - ); -} +export * from '../features/onboarding/DesktopOnboarding'; diff --git a/openless-all/app/src/components/FloatingShell.tsx b/openless-all/app/src/components/FloatingShell.tsx index af87b16ad..ffe55ea88 100644 --- a/openless-all/app/src/components/FloatingShell.tsx +++ b/openless-all/app/src/components/FloatingShell.tsx @@ -1,1231 +1 @@ -// Main window shell: sidebar navigation, page switching, mobile panels, and the -// settings modal. Pages share preference state; business reads/writes go to Core via typed IPC. - -import { - lazy, - Suspense, - useEffect, - useRef, - useState, - type ComponentType, - type CSSProperties, -} from 'react'; -import { afterPaint } from '../lib/startupMetrics'; -import { guideFinishedThisSession } from '../lib/desktopOnboarding'; -import { useTranslation } from 'react-i18next'; -import { Icon } from './Icon'; -import { Tooltip } from './Tooltip'; -import { WindowChrome, detectOS, type OS } from './WindowChrome'; -import { SettingsModal, type SettingsSectionId } from './SettingsModal'; -import type { ServiceViewId } from '../pages/settings/navigation'; -import { CloudSyncSetupPrompt } from './CloudSyncSetupPrompt'; -import { Overview } from '../pages/Overview'; -const History = lazy(() => import('../pages/History').then((m) => ({ default: m.History }))); -const Usage = lazy(() => import('../pages/Usage').then((m) => ({ default: m.Usage }))); -const Vocab = lazy(() => import('../pages/Vocab').then((m) => ({ default: m.Vocab }))); -const Style = lazy(() => import('../pages/Style').then((m) => ({ default: m.Style }))); -const Marketplace = lazy(() => - import('../pages/Marketplace').then((m) => ({ default: m.Marketplace })), -); -const Translation = lazy(() => - import('../pages/Translation').then((m) => ({ default: m.Translation })), -); -const SelectionAsk = lazy(() => - import('../pages/SelectionAsk').then((m) => ({ default: m.SelectionAsk })), -); -const QuickNote = lazy(() => import('../pages/QuickNote').then((m) => ({ default: m.QuickNote }))); -const Corrections = lazy(() => - import('../pages/Corrections').then((m) => ({ default: m.Corrections })), -); -import { IS_BETA_BUILD } from '../lib/appVersion'; -import { - HOTKEY_MODE_MIGRATION_ACK_KEY, - HOTKEY_MODE_MIGRATION_DEFERRED_KEY, - shouldShowHotkeyModeMigrationPrompt, -} from '../lib/hotkeyMigration'; -import { useExitMount } from '../lib/useExitMount'; -import { useOverlayMotion } from '../lib/motion'; -import { TransitionViewport } from './ui/TransitionViewport'; -import { getCredentials } from '../lib/ipc'; -import { - PROVIDER_SETUP_PROMPT_DEFERRED_KEY, - shouldShowProviderSetupPrompt, -} from '../lib/providerSetup'; -import { MobileMoreSheet } from './MobileMoreSheet'; -import { MobileStyleSheet } from './MobileStyleSheet'; -import { subItemLabelKey } from '../lib/navLabels'; -import { applyStackedLayoutFromPrefs } from '../lib/stackedLayout'; -import { applyConservativeLayout } from '../lib/conservativeLayout'; -import { useMobileLayout, useConservativeLayout } from '../lib/useMobileLayout'; -import { useHotkeySettings } from '../state/HotkeySettingsContext'; -import { useAppState, type AppTab } from '../state/useAppState'; - -const MORE_TAB_IDS: AppTab[] = ['vocab', 'translation', 'selectionAsk', 'quickNote', 'corrections']; -const STYLE_TAB_IDS: AppTab[] = ['style', 'marketplace']; - -/** Reserve the native traffic-light strip before the sidebar's version row. */ -const MAC_TRAFFIC_LIGHT_CLEARANCE = 44; -const SIDEBAR_WIDTH = 226; - -/** tab → page component map (renders main content; decoupled from the sidebar tree, includes pages not listed there directly). */ -const PAGE_CMP: Record, ComponentType> = { - overview: Overview, - history: History, - usage: Usage, - vocab: Vocab, - style: Style, - marketplace: Marketplace, - translation: Translation, - selectionAsk: SelectionAsk, - quickNote: QuickNote, - corrections: Corrections, -}; - -/** Main nav: direct entries and expandable groups; page components resolve through PAGE_CMP. */ -type NavNode = - | { kind: 'item'; id: AppTab; icon: string } - | { kind: 'group'; key: string; icon: string; children: Array<{ id: AppTab }> }; - -const NAV_TREE: NavNode[] = [ - { kind: 'item', id: 'overview', icon: 'overview' }, - { kind: 'item', id: 'history', icon: 'history' }, - { kind: 'item', id: 'vocab', icon: 'vocab' }, - { - kind: 'group', - key: 'style', - icon: 'style', - children: [{ id: 'style' }, { id: 'marketplace' }], - }, - { - kind: 'group', - key: 'tools', - icon: 'selectionAsk', - children: [ - { id: 'translation' }, - { id: 'selectionAsk' }, - { id: 'quickNote' }, - { id: 'corrections' }, - ], - }, -]; - -interface FloatingShellProps { - os?: OS; - initialTab?: AppTab; - initialSettings?: boolean; -} - -export function FloatingShell({ - os: osProp, - initialTab = 'overview', - initialSettings = false, -}: FloatingShellProps) { - const os = osProp ?? detectOS(); - return ( - - - - ); -} - -function FloatingShellBody({ - os, - initialTab, - initialSettings, -}: { - os: OS; - initialTab: AppTab; - initialSettings: boolean; -}) { - const { t } = useTranslation(); - const mobile = useMobileLayout(); - const conservative = useConservativeLayout(); - const { prefs } = useHotkeySettings(); - const { currentTab, setCurrentTab, settingsOpen, setSettingsOpen } = useAppState( - initialTab, - initialSettings, - ); - const [settingsInitialSection, setSettingsInitialSection] = useState< - SettingsSectionId | undefined - >(); - const [settingsInitialServiceView, setSettingsInitialServiceView] = useState(); - const [providerPromptOpen, setProviderPromptOpen] = useState(false); - const [hotkeyModePromptOpen, setHotkeyModePromptOpen] = useState(false); - const settingsMount = useExitMount(settingsOpen); - const providerPromptMount = useExitMount(providerPromptOpen); - const hotkeyPromptMount = useExitMount(hotkeyModePromptOpen); - const [moreOpen, setMoreOpen] = useState(false); - const [styleOpen, setStyleOpen] = useState(false); - const shellRef = useRef(null); - - // The dialog records and moves focus before its background becomes inert. - useEffect(() => { - if (shellRef.current) shellRef.current.inert = settingsMount.mounted; - }, [settingsMount.mounted]); - - const pageRef = useRef(null); - const displayTab = currentTab; - - // Already applied before React mounts; no first-frame scale jump. - useEffect(() => { - if (prefs) return afterPaint('interactive'); - }, [!!prefs]); - - useEffect(() => { - applyStackedLayoutFromPrefs(prefs?.stackedRowLayout); - applyConservativeLayout(prefs?.conservativeLayout === true); - }, [prefs?.stackedRowLayout, prefs?.conservativeLayout]); - - const Page = PAGE_CMP[displayTab as Exclude] ?? Overview; - - // Group expansion: default-expand the group containing the current page; the user - // toggles via group titles. - const groupOfTab = (tab: AppTab): string | null => { - for (const node of NAV_TREE) { - if (node.kind === 'group' && node.children.some((c) => c.id === tab)) return node.key; - } - return null; - }; - const [openGroups, setOpenGroups] = useState>(() => { - const active = groupOfTab(currentTab); - return active ? { [active]: true } : {}; - }); - // Auto-expand the group when landing on one of its pages (e.g. jumping straight to - // marketplace from the capsule). - useEffect(() => { - const active = groupOfTab(currentTab); - if (active) setOpenGroups((prev) => (prev[active] ? prev : { ...prev, [active]: true })); - }, [currentTab]); - const toggleGroup = (key: string) => setOpenGroups((prev) => ({ ...prev, [key]: !prev[key] })); - - useEffect(() => { - let cancelled = false; - (async () => { - try { - const credentials = await getCredentials(); - const promptDeferredValue = window.sessionStorage.getItem( - PROVIDER_SETUP_PROMPT_DEFERRED_KEY, - ); - if (!cancelled && shouldShowProviderSetupPrompt(credentials, promptDeferredValue)) { - setProviderPromptOpen(true); - } - } catch (error) { - // A locked/unavailable credential store is not an unconfigured provider. - console.warn('[startup] credential status unavailable', error); - } - })(); - return () => { - cancelled = true; - }; - }, []); - - useEffect(() => { - const acknowledgedValue = window.localStorage.getItem(HOTKEY_MODE_MIGRATION_ACK_KEY); - const deferredValue = window.sessionStorage.getItem(HOTKEY_MODE_MIGRATION_DEFERRED_KEY); - if (shouldShowHotkeyModeMigrationPrompt(acknowledgedValue, deferredValue)) { - setHotkeyModePromptOpen(true); - } - }, []); - - // The old NAVIGATE_LOCAL_ASR_EVENT listener is obsolete: the standalone "model - // settings" tab is gone — model management now renders via in - // Settings → Services, all in one place. - - const rememberProviderPrompt = () => { - window.sessionStorage.setItem(PROVIDER_SETUP_PROMPT_DEFERRED_KEY, '1'); - setProviderPromptOpen(false); - }; - - const deferHotkeyModePrompt = () => { - window.sessionStorage.setItem(HOTKEY_MODE_MIGRATION_DEFERRED_KEY, '1'); - setHotkeyModePromptOpen(false); - }; - - const openSettings = (section?: SettingsSectionId, serviceView?: ServiceViewId) => { - setSettingsInitialSection(section); - setSettingsInitialServiceView(serviceView); - setSettingsOpen(true); - setMoreOpen(false); - setStyleOpen(false); - }; - - // Platform-appropriate settings shortcut. - useEffect(() => { - const onKeyDown = (e: KeyboardEvent) => { - if ((os === 'mac' ? e.metaKey : e.ctrlKey) && e.key === ',') { - e.preventDefault(); - openSettings(); - } - }; - window.addEventListener('keydown', onKeyDown, true); - return () => window.removeEventListener('keydown', onKeyDown, true); - }, [os]); - - const openProviderSettings = () => { - rememberProviderPrompt(); - openSettings('services'); - }; - - const openHotkeyRecordingSettings = () => { - window.localStorage.setItem(HOTKEY_MODE_MIGRATION_ACK_KEY, '1'); - setHotkeyModePromptOpen(false); - openSettings('general'); - }; - - const mobileTitle = settingsOpen ? t('shell.footer.settings') : t(subItemLabelKey(currentTab)); - const moreTabActive = MORE_TAB_IDS.includes(currentTab); - const styleTabActive = STYLE_TAB_IDS.includes(currentTab); - - return ( - // Window content flush to the top; macOS reserves the traffic-light strip inside - // the sidebar only. -
- {mobile && ( -
{ - if (element) element.inert = settingsOpen; - }} - style={{ display: 'contents' }} - > - openSettings()} - settingsActive={settingsOpen} - /> -
- )} - - {/* Main shell — flush with the frosted backplate (no separate float). */} -
- {/* Sidebar — desktop / wide only. */} - {!mobile && ( - - )} - - {/* Main content — one flat solid block (feedback: the right side is a single - slab, no rounding, not a floating card). Solid surface, no margin, no - rounding, no shadow, flush to the window edge, separated from the sidebar - only by the sidebar's border-right. mac rounding comes from the native - window clip. */} -
-
- {/* Padding and overflow live on the transitioning page wrapper: - - naturally-sized pages (Overview / Vocab / Style): the wrapper scrolls - when the page content overflows - - height:100% pages (History's two columns): 100% resolves against the - wrapper's fixed height so each column's own overflow:auto can scroll */} - - {displayTab === 'overview' ? ( - setCurrentTab('history')} - onOpenSettings={openSettings} - /> - ) : ( -
- {displayTab === 'selectionAsk' ? ( - openSettings('shortcuts')} /> - ) : ( - - )} -
- )} -
-
-
-
- - {mobile && ( - <> - {!settingsOpen && !styleOpen && !moreOpen && ( - { - setMoreOpen(false); - setStyleOpen(false); - setCurrentTab(id); - }} - onOpenStyle={() => { - setMoreOpen(false); - setStyleOpen(true); - }} - onOpenMore={() => { - setStyleOpen(false); - setMoreOpen(true); - }} - /> - )} - setStyleOpen(false)} - onSelectTab={(id) => { - setStyleOpen(false); - setCurrentTab(id); - }} - /> - setMoreOpen(false)} - onSelectTab={setCurrentTab} - onOpenSettings={() => openSettings()} - /> - - )} - - {/* Settings modal — rendered inside this window; settingsMount gates the exit animation */} - {settingsMount.mounted && ( - - )} - - {providerPromptMount.mounted ? ( - { - rememberProviderPrompt(); - openSettings('privacy'); - }} - /> - ) : hotkeyPromptMount.mounted ? ( - - ) : null} - openSettings('privacy')} - /> - {/* Enter keyframes shared by tab switching, the provider prompt, and the footer popover */} - -
- ); -} - -// Warm likely destinations on hover/focus; React.lazy shares the module cache. -function preloadPage(tab: AppTab) { - const load = - tab === 'history' - ? import('../pages/History') - : tab === 'vocab' - ? import('../pages/Vocab') - : tab === 'style' - ? import('../pages/Style') - : tab === 'marketplace' - ? import('../pages/Marketplace') - : tab === 'translation' - ? import('../pages/Translation') - : tab === 'selectionAsk' - ? import('../pages/SelectionAsk') - : null; - void load?.catch(() => {}); // The normal lazy boundary owns visible load errors. -} - -const MOBILE_BOTTOM_TABS: Array<{ id: AppTab; icon: string }> = [ - { id: 'overview', icon: 'overview' }, - { id: 'history', icon: 'history' }, -]; - -function MobileTopBar({ - title, - onOpenSettings, - settingsActive, -}: { - title: string; - onOpenSettings: () => void; - settingsActive: boolean; -}) { - const { t } = useTranslation(); - return ( -
-
- - - {title} - -
- -
- ); -} - -function MobileBottomNav({ - currentTab, - moreOpen, - moreTabActive, - styleOpen, - styleTabActive, - settingsOpen, - onSelectTab, - onOpenStyle, - onOpenMore, -}: { - currentTab: AppTab; - moreOpen: boolean; - moreTabActive: boolean; - styleOpen: boolean; - styleTabActive: boolean; - settingsOpen: boolean; - onSelectTab: (tab: AppTab) => void; - onOpenStyle: () => void; - onOpenMore: () => void; -}) { - const { t } = useTranslation(); - const moreActive = moreOpen || moreTabActive; - const styleActive = !settingsOpen && (styleOpen || styleTabActive); - - return ( - - ); -} - -const mobileNavBtnStyle: CSSProperties = { - flex: 1, - minWidth: 0, - display: 'flex', - flexDirection: 'column', - alignItems: 'center', - justifyContent: 'center', - gap: 4, - padding: '6px 4px', - border: 0, - borderRadius: 10, - background: 'transparent', - fontFamily: 'inherit', - cursor: 'default', -}; - -/** Base style for sidebar nav buttons (shared by flat items / group titles / children; children override paddingLeft). - * Layout only: colour, background and cursor come from the .ol-sidebar-surface rules. */ -const navBtnStyle: CSSProperties = { - display: 'flex', - alignItems: 'center', - gap: 10, - width: '100%', - padding: '8px 10px', - borderRadius: 8, - border: 0, - // (After the Codex sidebar): 15px nav text, 16px icons — closer to the reference design. - fontFamily: 'inherit', - fontSize: 15, - textAlign: 'left', -}; - -function ProviderSetupPrompt({ - closing = false, - onLater, - onOpenSettings, - onRestore, -}: { - closing?: boolean; - onLater: () => void; - onOpenSettings: () => void; - onRestore: () => void; -}) { - const { t } = useTranslation(); - const overlayRef = useRef(null); - const cardRef = useRef(null); - useOverlayMotion(overlayRef, closing, 'backdrop'); - useOverlayMotion(cardRef, closing); - return ( -
-
-
-
- -
-
- {t('shell.providerPrompt.title')} -
-
-
- {t('shell.providerPrompt.body')} -
- -
- - -
-
-
- ); -} - -function HotkeyModeMigrationPrompt({ - closing = false, - onLater, - onOpenSettings, -}: { - closing?: boolean; - onLater: () => void; - onOpenSettings: () => void; -}) { - const { t } = useTranslation(); - const overlayRef = useRef(null); - const cardRef = useRef(null); - useOverlayMotion(overlayRef, closing, 'backdrop'); - useOverlayMotion(cardRef, closing); - return ( -
-
-
-
- -
-
- {t('shell.hotkeyModePrompt.title')} -
-
-
- {t('shell.hotkeyModePrompt.body')} -
-
- - -
-
-
- ); -} +export { FloatingShell } from '../app/shell/FloatingShell'; diff --git a/openless-all/app/src/components/GithubLoginModal.tsx b/openless-all/app/src/components/GithubLoginModal.tsx index bb64a012a..5d34c4d8e 100644 --- a/openless-all/app/src/components/GithubLoginModal.tsx +++ b/openless-all/app/src/components/GithubLoginModal.tsx @@ -1,373 +1 @@ -import { isHarmonyHost, invokeHarmony } from '../lib/harmonyBridge'; -// GitHub login modal — the style marketplace and extension marketplace share one -// login UI. GitHub OAuth Device Flow: start on open → show the user code and wait -// for browser authorization → poll until authorized. All phases share one minHeight -// container so the window size stays constant — no more small-then-larger jump. - -import { useCallback, useEffect, useId, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { CircleCheckIcon, XIcon } from 'lucide-react'; -import { - githubDeviceFlowCancel, - githubDeviceFlowPoll, - githubDeviceFlowStart, - githubFlowExpiresAt, - githubPollIntervalMs, - githubSlowDownIntervalMs, - openExternal, -} from '../lib/ipc'; -import { Btn } from '../pages/_atoms'; -import { Modal } from './ui/Modal'; - -type Phase = - | { kind: 'starting' } - | { - kind: 'pending'; - userCode: string; - verificationUri: string; - flowId: string; - intervalMs: number; - expiresAt: number; - } - | { kind: 'success'; login: string } - | { kind: 'error'; message: string }; - -interface GithubLoginModalProps { - onClose: () => void; - /** Called on successful authorization (receives the GitHub login). */ - onSuccess: (login: string) => void; - /** Exit animation driven by the caller's useExitMount. */ - closing?: boolean; - overlayClassName?: string; -} - -export function GithubLoginModal({ - onClose, - onSuccess, - closing = false, - overlayClassName, -}: GithubLoginModalProps) { - const { t } = useTranslation(); - const titleId = useId(); - const [phase, setPhase] = useState({ kind: 'starting' }); - const [copied, setCopied] = useState(false); - const cancelledRef = useRef(false); - const beginGenerationRef = useRef(0); - const activeFlowIdRef = useRef(undefined); - // Hold callbacks in refs so the poll effect depends only on phase and doesn't - // restart on parent re-renders. - const onSuccessRef = useRef(onSuccess); - const onCloseRef = useRef(onClose); - useEffect(() => { - onSuccessRef.current = onSuccess; - onCloseRef.current = onClose; - }); - - const cancelActiveFlow = useCallback(async () => { - const flowId = activeFlowIdRef.current; - activeFlowIdRef.current = undefined; - try { - await githubDeviceFlowCancel(flowId); - } catch { - /* best effort */ - } - }, []); - - const begin = useCallback(async () => { - const generation = ++beginGenerationRef.current; - cancelledRef.current = false; - setPhase({ kind: 'starting' }); - try { - await cancelActiveFlow(); - if (cancelledRef.current || generation !== beginGenerationRef.current) return; - const start = await githubDeviceFlowStart(); - if (cancelledRef.current || generation !== beginGenerationRef.current) { - await githubDeviceFlowCancel(start.flowId).catch(() => undefined); - return; - } - activeFlowIdRef.current = start.flowId; - setPhase({ - kind: 'pending', - userCode: start.userCode, - verificationUri: start.verificationUri, - flowId: start.flowId, - intervalMs: githubPollIntervalMs(start.interval), - expiresAt: githubFlowExpiresAt(Date.now(), start.expiresIn), - }); - // Open the browser automatically; failure is non-fatal, the user can copy manually. - try { - await openExternal(start.verificationUri); - } catch { - /* manual fallback */ - } - } catch (err) { - if (cancelledRef.current) return; - setPhase({ kind: 'error', message: err instanceof Error ? err.message : String(err) }); - } - }, [cancelActiveFlow]); - - // Start the login immediately on open. - useEffect(() => { - void begin(); - return () => { - cancelledRef.current = true; - beginGenerationRef.current += 1; - void cancelActiveFlow(); - }; - }, [begin, cancelActiveFlow]); - - // Poll the backend during the pending phase. - useEffect(() => { - if (phase.kind !== 'pending') return; - let cancelled = false; - let timer: number | null = null; - let interval = phase.intervalMs; - const { flowId, expiresAt } = phase; - const tick = async () => { - if (cancelled) return; - if (Date.now() >= expiresAt) { - await githubDeviceFlowCancel(flowId).catch(() => undefined); - activeFlowIdRef.current = undefined; - if (!cancelled) { - setPhase({ - kind: 'error', - message: t('marketplace.oauth.expiredError', { - defaultValue: 'GitHub authorization expired. Start again.', - }), - }); - } - return; - } - try { - const res = await githubDeviceFlowPoll(flowId); - if (cancelled) return; - if (res.kind === 'authorized') { - activeFlowIdRef.current = undefined; - setPhase({ kind: 'success', login: res.login }); - onSuccessRef.current(res.login); - window.setTimeout(() => { - if (!cancelled) onCloseRef.current(); - }, 1200); - } else if (res.kind === 'slowDown') { - interval = githubSlowDownIntervalMs(interval); - timer = window.setTimeout(tick, Math.min(interval, Math.max(0, expiresAt - Date.now()))); - } else if (res.kind === 'pending') { - timer = window.setTimeout(tick, Math.min(interval, Math.max(0, expiresAt - Date.now()))); - } else { - activeFlowIdRef.current = undefined; - setPhase({ kind: 'error', message: res.message }); - } - } catch (err) { - if (cancelled) return; - setPhase({ kind: 'error', message: err instanceof Error ? err.message : String(err) }); - } - }; - timer = window.setTimeout(tick, interval); - return () => { - cancelled = true; - if (timer != null) window.clearTimeout(timer); - }; - }, [phase, t]); - - const close = () => { - cancelledRef.current = true; - beginGenerationRef.current += 1; - void cancelActiveFlow().finally(onClose); - }; - - const copyCode = async () => { - if (phase.kind !== 'pending') return; - try { - if (isHarmonyHost) await invokeHarmony('copy_text', { text: phase.userCode }); - else await navigator.clipboard.writeText(phase.userCode); - setCopied(true); - window.setTimeout(() => setCopied(false), 1500); - } catch { - /* clipboard unavailable */ - } - }; - - return ( - -
-

- {t('marketplace.oauth.title')} -

- -
- - {/* Fixed min height — shared by all phases, keeping the window size constant. */} -
- {phase.kind === 'starting' && ( -
- {t('marketplace.oauth.generating')} -
- )} - - {phase.kind === 'pending' && ( -
-
- {t('marketplace.oauth.browserHint', { uri: phase.verificationUri })} -
-
- - {phase.userCode} - - void copyCode()}> - {copied ? t('marketplace.oauth.copied') : t('marketplace.oauth.copyBtn')} - -
-
- void openExternal(phase.verificationUri)} - > - {t('marketplace.oauth.openBrowserBtn')} - - - {t('marketplace.oauth.cancelBtn')} - -
-
- - {t('marketplace.oauth.waiting')} -
- -
- )} - - {phase.kind === 'success' && ( -
-
- -
- {t('marketplace.oauth.successAs', { login: phase.login })} -
-
-
- )} - - {phase.kind === 'error' && ( -
-
- {phase.message} -
-
- - {t('marketplace.oauth.closeBtn')} - - void begin()}> - {t('marketplace.oauth.retryBtn')} - -
-
- )} -
-
- ); -} +export * from '../features/accounts/GithubLoginModal'; diff --git a/openless-all/app/src/components/GlobalDownloadProgress.tsx b/openless-all/app/src/components/GlobalDownloadProgress.tsx index cc35eaf66..1ca9ebb56 100644 --- a/openless-all/app/src/components/GlobalDownloadProgress.tsx +++ b/openless-all/app/src/components/GlobalDownloadProgress.tsx @@ -1,191 +1 @@ -// Host jobs outlive settings. Experimental downloads use the same authoritative -// snapshot and cancellation route as their switches, not the retired Qwen API. -import { lazy, Suspense, useEffect, useRef, useState } from 'react'; -import { createPortal } from 'react-dom'; -import { useTranslation } from 'react-i18next'; -import { isTauri } from '../lib/ipc'; -import { - cancelFoundryLocalAsrPrepare, - cancelLocalAsrDownload, - cancelSherpaOnnxAsrDownload, - type FoundryPrepareProgress, - type LocalAsrDownloadProgress, -} from '../lib/localAsr'; -import { - downloadPercent, - experimentalAsrModelFromDownloadId, - experimentalAsrName, - type ExperimentalAsrModel, -} from '../lib/experimentalAsr'; -import { useExperimentalAsr } from '../lib/useExperimentalAsr'; -import { detectOS } from './WindowChrome'; -const DownloadProgressCards = lazy(() => import('./DownloadProgressCards')); - -type Engine = 'qwen3' | 'sherpa' | 'foundry' | 'experimental'; -export interface ProgressItem { - key: string; - id: string; - name: string; - percent: number | null; - engine: Engine; - model?: ExperimentalAsrModel; - phase?: string; -} -const TERMINAL = new Set(['finished', 'cancelled', 'failed']); - -export function GlobalDownloadProgress() { - const { t } = useTranslation(); - const experimental = useExperimentalAsr( - (document.documentElement.dataset.olPlatform ?? detectOS()) === 'mac', - ); - const [items, setItems] = useState>({}); - const [pending, setPending] = useState([]); - const [errors, setErrors] = useState>({}); - const cancelledJobs = useRef(new Set()); - const activated = useRef(false); - - useEffect(() => { - if (!isTauri) return; - const unlistens: Array<() => void> = []; - let cancelled = false; - const update = (item: ProgressItem, phase: string) => { - if (cancelled) return; - if (phase === 'started' || TERMINAL.has(phase)) cancelledJobs.current.delete(item.key); - setItems((previous) => { - if (TERMINAL.has(phase)) { - const next = { ...previous }; - delete next[item.key]; - return next; - } - if (cancelledJobs.current.has(item.key)) return previous; - return { ...previous, [item.key]: item }; - }); - }; - void (async () => { - const { listen } = await import('@tauri-apps/api/event'); - const subscribe = async (event: string, handler: (payload: T) => void) => { - const off = await listen(event, ({ payload }) => { - if (!cancelled) handler(payload); - }); - if (cancelled) off(); - else unlistens.push(off); - }; - const download = (engine: 'qwen3' | 'sherpa') => (p: LocalAsrDownloadProgress) => { - // Generic model-store progress also includes experiments. Their IDs are - // not legacy model IDs and must never reach cancelLocalAsrDownload(). - if (experimentalAsrModelFromDownloadId(p.modelId)) return; - update( - { - key: `${engine}:${p.modelId}`, - id: p.modelId, - name: p.modelId, - percent: p.bytesTotal > 0 ? (p.bytesDownloaded / p.bytesTotal) * 100 : null, - engine, - }, - p.phase, - ); - }; - const results = await Promise.allSettled([ - subscribe('local-asr-download-progress', download('qwen3')), - subscribe( - 'sherpa-onnx-asr-download-progress', - download('sherpa'), - ), - subscribe('foundry-local-asr-prepare-progress', (p) => { - update( - { - key: `foundry:${p.modelAlias}`, - id: p.modelAlias, - name: p.label || p.modelAlias, - percent: p.percent ?? null, - engine: 'foundry', - }, - p.phase, - ); - }), - ]); - for (const result of results) - if (result.status === 'rejected') - console.warn('[global-download-progress] subscribe failed', result.reason); - })().catch((error) => console.warn('[global-download-progress] subscribe failed', error)); - return () => { - cancelled = true; - for (const off of unlistens) off(); - }; - }, []); - - const handleCancel = async (item: ProgressItem) => { - if (pending.includes(item.key)) return; - setPending((previous) => [...previous, item.key]); - setErrors((previous) => { - const next = { ...previous }; - delete next[item.key]; - return next; - }); - // Generic/Sherpa events have a Started boundary to admit a later retry. - // Foundry has no such event; keep its card until the native terminal event - // rather than fencing all future prepares for the same model alias. - if (item.engine === 'qwen3' || item.engine === 'sherpa') cancelledJobs.current.add(item.key); - try { - if (item.engine === 'experimental' && item.model) - await experimental.toggle(item.model, false); - else if (item.engine === 'qwen3') await cancelLocalAsrDownload(item.id); - else if (item.engine === 'sherpa') await cancelSherpaOnnxAsrDownload(item.id); - else await cancelFoundryLocalAsrPrepare(); - if (item.engine !== 'foundry') { - setItems((previous) => { - const next = { ...previous }; - delete next[item.key]; - return next; - }); - } - } catch (error) { - cancelledJobs.current.delete(item.key); - setErrors((previous) => ({ ...previous, [item.key]: String(error) })); - } finally { - setPending((previous) => previous.filter((key) => key !== item.key)); - } - }; - const visible: ProgressItem[] = [ - ...Object.values(items), - ...experimental.models - .filter( - (status) => - status.enabled && (status.phase === 'downloading' || status.phase === 'preparing'), - ) - .map((status): ProgressItem => ({ - key: `experimental:${status.model}`, - id: status.model, - model: status.model, - name: experimentalAsrName(status.model), - engine: 'experimental', - phase: status.phase, - percent: - status.phase === 'downloading' && status.downloadedBytes > 0 - ? downloadPercent(status) - : null, - })), - ]; - - if (visible.length) activated.current = true; - if (!activated.current) return null; - return createPortal( - - {t('localAsr.downloading')} -
- ) : null - } - > - `experimental:${model}`)]} - onCancel={handleCancel} - /> - , - document.body, - ); -} +export * from '../features/downloads/GlobalDownloadProgress'; diff --git a/openless-all/app/src/components/HarmonyDictation.tsx b/openless-all/app/src/components/HarmonyDictation.tsx index 6b7da33d9..7a02ab2ad 100644 --- a/openless-all/app/src/components/HarmonyDictation.tsx +++ b/openless-all/app/src/components/HarmonyDictation.tsx @@ -1,156 +1 @@ -import { useEffect, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { invokeHarmony } from '../lib/harmonyBridge'; -import { copyTextToClipboard } from '../lib/ipc'; -import { Btn, Card } from '../pages/_atoms'; - -interface VoiceState { - phase: 'idle' | 'starting' | 'recording' | 'processing' | 'cancelling'; - level: number; - error: string; -} -interface VoiceResult { - rawText: string; - polishedText: string; -} - -export function HarmonyDictation({ onComplete }: { onComplete: () => void }) { - const { t } = useTranslation(); - const [state, setState] = useState({ phase: 'idle', level: 0, error: '' }); - const [result, setResult] = useState(''); - const [copied, setCopied] = useState(false); - const generation = useRef(0); - const active = useRef(false); - const busy = useRef(false); - useEffect(() => { - const update = (event: Event) => { - const next = (event as CustomEvent).detail; - if ( - next && - ['idle', 'starting', 'recording', 'processing', 'cancelling'].includes(next.phase) - ) { - active.current = next.phase !== 'idle'; - setState(next); - } - }; - window.addEventListener('openless:harmony-dictation', update); - return () => { - generation.current++; - window.removeEventListener('openless:harmony-dictation', update); - if (active.current) void invokeHarmony('cancel_dictation').catch(() => {}); - }; - }, []); - - const record = async () => { - if (busy.current) return; - busy.current = true; - const epoch = ++generation.current; - const stopping = state.phase === 'recording'; - active.current = true; - setState({ phase: stopping ? 'processing' : 'starting', level: 0, error: '' }); - if (!stopping) { - setResult(''); - setCopied(false); - } - try { - if (stopping) { - const reply = await invokeHarmony('stop_dictation'); - if (epoch !== generation.current) return; - active.current = false; - setResult(reply.polishedText || reply.rawText); - setState({ phase: 'idle', level: 0, error: '' }); - onComplete(); - } else { - await invokeHarmony('start_dictation'); - if (epoch === generation.current) setState({ phase: 'recording', level: 0, error: '' }); - } - } catch (error) { - if (epoch === generation.current) { - active.current = false; - setState({ phase: 'idle', level: 0, error: String(error) }); - } - } finally { - if (epoch === generation.current) busy.current = false; - } - }; - const cancel = async () => { - const epoch = ++generation.current; - busy.current = true; - setState({ phase: 'cancelling', level: 0, error: '' }); - try { - await invokeHarmony('cancel_dictation'); - } catch (error) { - if (epoch === generation.current) setState({ phase: 'idle', level: 0, error: String(error) }); - return; - } finally { - if (epoch === generation.current) { - busy.current = false; - active.current = false; - } - } - if (epoch === generation.current) setState({ phase: 'idle', level: 0, error: '' }); - }; - const copy = async () => { - try { - await copyTextToClipboard(result); - setCopied(true); - } catch (error) { - setState((old) => ({ ...old, error: String(error) })); - } - }; - const waiting = ['starting', 'processing', 'cancelling'].includes(state.phase); - return ( - -
- {t('overview.inAppDictation.title')} - - {t(`overview.inAppDictation.${waiting ? 'processing' : state.phase}`)} - - void record()} disabled={waiting}> - {t(`overview.inAppDictation.${state.phase === 'recording' ? 'stop' : 'start'}`)} - - {state.phase !== 'idle' && ( - void cancel()} - > - {t('common.cancel')} - - )} -
- {state.phase === 'recording' && ( - - )} - {state.error && ( -
- {state.error} -
- )} - {result && ( -
-
- {result} -
- void copy()}> - {t(copied ? 'common.copied' : 'common.copy')} - -
- )} -
- ); -} +export * from '../features/dictation/HarmonyDictation'; diff --git a/openless-all/app/src/components/InsertFallbackCard.tsx b/openless-all/app/src/components/InsertFallbackCard.tsx index 3a785527f..535d40852 100644 --- a/openless-all/app/src/components/InsertFallbackCard.tsx +++ b/openless-all/app/src/components/InsertFallbackCard.tsx @@ -1,217 +1 @@ -// Fallback card for "this text didn't make it in", shown at the bottom-right of the -// screen. Displays the FULL text (whatever landed on screen is only a partial), pauses -// its TTL while hovered, and copies via the backend: the button deliberately -// preventDefaults so it never steals focus, and navigator.clipboard throws -// "Document is not focused" on an unfocused document. No title — the text plus a Copy -// button is self-explanatory; payload.reason is logged only, never displayed. - -import { useEffect, useLayoutEffect, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { - copyTextToClipboard, - dismissInsertFallbackCard, - reportInsertFallbackCardHeight, -} from '../lib/ipc'; -import { - nextFallbackCardHeightReport, - type FallbackCardHeightReport, -} from '../lib/insertFallbackLayout'; -import type { InsertFallbackCardPayload } from '../lib/types'; - -/// Auto-dismiss delay. Double the vocab card's 10s — this one needs reading. -const TTL_MS = 20_000; -/// How long the button stays on "Copied" after a successful copy. -const COPIED_FEEDBACK_MS = 1_600; -/// Max body lines before scrolling inside the card. -/// Native windows measure real DOM height; these layout constants are no longer -/// maintained in parallel. -const MAX_LINES = 8; -const LINE_HEIGHT = 18; - -interface InsertFallbackCardProps { - payload: InsertFallbackCardPayload; -} - -export function InsertFallbackCard({ payload }: InsertFallbackCardProps) { - const { t } = useTranslation(); - const [copied, setCopied] = useState(false); - const [copyFailed, setCopyFailed] = useState(false); - const [paused, setPaused] = useState(false); - const timerRef = useRef(null); - const cardRootRef = useRef(null); - const lastHeightReportRef = useRef(null); - - useLayoutEffect(() => { - const element = cardRootRef.current; - if (!element) return undefined; - let cancelled = false; - - const reportHeight = () => { - const report = nextFallbackCardHeightReport( - lastHeightReportRef.current, - payload.presentationId, - element.getBoundingClientRect().height, - ); - if (!report) return; - lastHeightReportRef.current = report; - void reportInsertFallbackCardHeight(report.presentationId, report.height).catch(() => { - // On transient IPC failure, clear the report so a later ResizeObserver tick retries. - if ( - !cancelled && - lastHeightReportRef.current?.presentationId === report.presentationId && - lastHeightReportRef.current.height === report.height - ) { - lastHeightReportRef.current = null; - } - }); - }; - - lastHeightReportRef.current = null; - reportHeight(); - if (typeof ResizeObserver === 'undefined') return undefined; - const observer = new ResizeObserver(reportHeight); - observer.observe(element); - return () => { - cancelled = true; - observer.disconnect(); - }; - }, [payload.presentationId]); - - // TTL countdown. Paused on hover: the cursor on the card means it's being read. - useEffect(() => { - if (paused) return; - if (timerRef.current) clearTimeout(timerRef.current); - timerRef.current = window.setTimeout(() => { - void dismissInsertFallbackCard(); - }, TTL_MS); - return () => { - if (timerRef.current) clearTimeout(timerRef.current); - }; - }, [paused, payload.text]); - - const copy = async () => { - try { - await copyTextToClipboard(payload.text); - setCopied(true); - setCopyFailed(false); - window.setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS); - } catch { - // Copy failure must be surfaced — this card is the last line of defense against - // losing the text; failing silently again would leave the user no way to get it. - setCopyFailed(true); - } - }; - - return ( -
setPaused(true)} - onMouseLeave={() => setPaused(false)} - > -
-
- {payload.text} -
- -
- void copy()} - /> - void dismissInsertFallbackCard()} - /> -
-
-
- ); -} - -/// Buttons reuse the capsule's confirm/cancel palette; a labeled wide button because -/// "Copy" needs words, not just an icon. -function TextButton({ - label, - primary, - onClick, -}: { - label: string; - primary?: boolean; - onClick: () => void; -}) { - return ( - - ); -} +export * from '../features/capsule/InsertFallbackCard'; diff --git a/openless-all/app/src/components/LearnVocabulary.tsx b/openless-all/app/src/components/LearnVocabulary.tsx index 7ab2bad6c..b5da79512 100644 --- a/openless-all/app/src/components/LearnVocabulary.tsx +++ b/openless-all/app/src/components/LearnVocabulary.tsx @@ -1,87 +1 @@ -import { useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { addLearnedVocab } from '../lib/ipc/vocab'; -import { Btn } from '../pages/_atoms'; -import { inputStyle } from '../pages/settings/shared'; - -/** An explicit, cross-platform alternative when a host editor cannot be read. */ -export function LearnVocabulary() { - const { t } = useTranslation(); - const [open, setOpen] = useState(false); - const [phrase, setPhrase] = useState(''); - const [busy, setBusy] = useState(false); - const [message, setMessage] = useState(''); - const save = async () => { - if (busy || !phrase.trim()) return; - setBusy(true); - setMessage(''); - try { - await addLearnedVocab(phrase.trim()); - setPhrase(''); - setOpen(false); - setMessage(t('vocabLearning.saved', '已记住,可在词典中管理')); - } catch (error) { - setMessage(t('vocabLearning.failed', '保存失败:{{error}}', { error: String(error) })); - } finally { - setBusy(false); - } - }; - return ( -
- {!open ? ( - { - setOpen(true); - setMessage(''); - }} - > - {t('vocabLearning.open', '记住词汇')} - - ) : ( -
{ - if (e.key === 'Enter' && !e.nativeEvent.isComposing) { - e.preventDefault(); - void save(); - } - }} - > - -
- void save()}> - {t('vocabLearning.confirm', '确认加入词典')} - - { - setOpen(false); - setPhrase(''); - setMessage(''); - }} - > - {t('common.cancel')} - -
-
- )} - {message && ( -
- {message} -
- )} -
- ); -} +export * from '../features/vocabulary-learning/LearnVocabulary'; diff --git a/openless-all/app/src/components/LiveTranscriptPill.tsx b/openless-all/app/src/components/LiveTranscriptPill.tsx index 21e23d89b..68bfa9e18 100644 --- a/openless-all/app/src/components/LiveTranscriptPill.tsx +++ b/openless-all/app/src/components/LiveTranscriptPill.tsx @@ -1,563 +1 @@ -import { measureTabularDigit } from '../lib/tabularTextMetrics'; -import { animate, motion, useMotionValue, useReducedMotion, useTransform } from 'framer-motion'; -import { useEffect, useMemo, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import './CapsuleStyles.css'; -import { - INSERT_TEXT_MOTION, - appendedBirthAdvance, - clampInsertContentWidth, - diffInsertWindowUnits, - firstBornIndex, - planCapsuleInsertMotion, - INSERT_TEXT_RENDER_WINDOW, - planCharDelays, - prefixWidths, - rightAnchoredPositions, - selectInsertRenderWindow, - type InsertUnit, -} from '../lib/insertTextAnimation'; -import { Icon } from './Icon'; -import { - applyTranscriptEvent, - applyTranscriptSessionId, - applyTranscriptSnapshot, - beginTranscriptGeneration, - clearTranscriptText, - createTranscriptViewState, - shouldRetryTranscriptSnapshot, - type BackendEvent, - type TranscriptViewState, -} from '../lib/backendEvent'; -import { capsuleTranscriptFontSize, visibleCapsuleTranscript } from '../lib/capsuleTranscript'; -import { getCapsuleTranscriptRailHeight, parseCapsuleStyle } from '../lib/capsuleLayout'; -import { getSettings } from '../lib/ipc/settings'; -import { getCapsuleSnapshot, isTauri } from '../lib/ipc'; -import type { - CapsulePayload, - CapsuleSnapshot, - CapsuleState, - CapsuleStyle, - UserPreferences, -} from '../lib/types'; - -export type LiveTranscriptTone = 'frost' | 'dark'; - -export { CapsuleTranslationBadge } from './CapsuleTranslationBadge'; - -export interface LiveTranscriptPillProps { - text: string; - tone?: LiveTranscriptTone; - stageWidth: number; - maxWidth: number; - minWidth?: number; - height?: number; - onCancel?: () => void; - onConfirm?: () => void; - cancelEnabled?: boolean; - confirmEnabled?: boolean; - cancelLabel?: string; - confirmLabel?: string; - controlSize?: number; - fontSize?: number; -} - -const FONT_SIZE = 16; -const DEFAULT_PILL_HEIGHT = 40; - -let measureCanvas: HTMLCanvasElement | null = null; - -function getSansFont(): string { - if (typeof window === 'undefined') return 'system-ui, sans-serif'; - const token = getComputedStyle(document.documentElement) - .getPropertyValue('--ol-font-sans') - .trim(); - return token || 'system-ui, sans-serif'; -} - -function measureGlyphWidth(glyph: string, fontSize: number): number { - if (typeof document === 'undefined') { - return Math.max(fontSize * 0.92, glyph.length * fontSize); - } - if (!measureCanvas) measureCanvas = document.createElement('canvas'); - const ctx = measureCanvas.getContext('2d'); - if (!ctx) return fontSize; - const weight = - getComputedStyle(document.documentElement).getPropertyValue('--ol-font-weight-medium').trim() || - '500'; - ctx.font = `${weight} ${fontSize}px ${getSansFont()}`; - const raw = - measureTabularDigit(glyph, ctx.font) ?? ctx.measureText(glyph === ' ' ? '\u00a0' : glyph).width; - return Math.max(1, raw) + INSERT_TEXT_MOTION.glyphGapPx; -} - -export interface CapsuleTranscriptRailProps { - text: string; - tone?: LiveTranscriptTone; - stageWidth: number; - maxWidth: number; - height?: number; - fontSize?: number; -} - -/** Transcript is deliberately a sibling rail: the capsule body remains responsible for audio feedback and controls. */ -export function CapsuleTranscriptRail({ - text, - tone = 'frost', - stageWidth, - maxWidth, - height = DEFAULT_PILL_HEIGHT, - fontSize = FONT_SIZE, -}: CapsuleTranscriptRailProps) { - const liveText = text.trim(); - if (!liveText) return null; - return ( -
- -
- ); -} - -/** - * Windows renders the transcript in a separate, permanently click-through HWND. - * The capsule HWND can therefore keep a small, reliable native hit region for - * its controls while this rail never participates in cross-process hit testing. - */ -export function CapsuleTranscriptOverlay() { - const { t } = useTranslation(); - const [state, setState] = useState('idle'); - const [style, setStyle] = useState('classic'); - const [text, setText] = useState(''); - const [enabled, setEnabled] = useState(true); - const [fontSize, setFontSize] = useState(14); - const [selectionPolish, setSelectionPolish] = useState(false); - const [translation, setTranslation] = useState(false); - const transcriptRef = useRef(createTranscriptViewState()); - const stateRef = useRef('idle'); - const snapshotRetryDelays = [0, 16, 32, 64, 128, 256] as const; - - useEffect(() => { - if (!isTauri) return; - let cancelled = false; - let unlisten: (() => void) | undefined; - (async () => { - const { listen } = await import('@tauri-apps/api/event'); - const { getCurrentWebviewWindow } = await import('@tauri-apps/api/webviewWindow'); - if (cancelled) return; - const target = { kind: 'WebviewWindow' as const, label: getCurrentWebviewWindow().label }; - const replayActiveSessionTranscript = async (sessionId: string) => { - const snapshot = await getCapsuleSnapshot(); - if (cancelled || !snapshot || snapshot.sessionId !== sessionId) return; - const current = transcriptRef.current; - if (shouldRetryTranscriptSnapshot(current, snapshot)) return; - const next = applyTranscriptSnapshot(current, snapshot); - if (next === current) return; - transcriptRef.current = next; - setText(next.text); - }; - const stateHandle = await listen( - 'capsule:state', - (event) => { - const payload = event.payload; - const previousState = stateRef.current; - const previousTranscript = transcriptRef.current; - const sessionTranscript = applyTranscriptSessionId(previousTranscript, payload.sessionId); - const sessionChanged = sessionTranscript !== previousTranscript; - transcriptRef.current = sessionTranscript; - stateRef.current = payload.state; - setState(payload.state); - if (payload.capsuleStyle) setStyle(parseCapsuleStyle(payload.capsuleStyle) ?? 'classic'); - setSelectionPolish(payload.selectionPolish === true); - setTranslation(payload.translation === true); - const sessionId = payload.sessionId; - const reactivatedSession = - payload.state === 'recording' && - previousState !== 'recording' && - !sessionChanged && - !previousTranscript.sessionStartObserved && - sessionId != null && - sessionTranscript.sessionId === sessionId; - if (reactivatedSession) { - void replayActiveSessionTranscript(sessionId); - } else if ( - payload.state === 'recording' && - previousState !== 'recording' && - !sessionChanged - ) { - transcriptRef.current = beginTranscriptGeneration(transcriptRef.current); - setText(transcriptRef.current.text); - } else if (sessionChanged) { - setText(sessionTranscript.text); - } - if (['idle', 'done', 'cancelled', 'error'].includes(payload.state)) { - transcriptRef.current = clearTranscriptText(transcriptRef.current); - setText(''); - } - }, - { target }, - ); - const transcriptHandle = await listen('backend:event', (event) => { - const next = applyTranscriptEvent(transcriptRef.current, event.payload); - transcriptRef.current = next; - setText(next.text); - }); - const preferenceHandle = await listen('prefs:changed', (event) => { - setEnabled(event.payload.capsuleTranscriptEnabled ?? true); - setFontSize(capsuleTranscriptFontSize(event.payload.capsuleTranscriptFontSize)); - if (event.payload.capsuleStyle) - setStyle(parseCapsuleStyle(event.payload.capsuleStyle) ?? 'classic'); - }); - const applySnapshot = ( - snapshot: CapsuleSnapshot, - fallbackStyle: CapsuleStyle, - ): 'retry' | 'done' => { - const previousTranscript = transcriptRef.current; - if (shouldRetryTranscriptSnapshot(previousTranscript, snapshot)) return 'retry'; - const nextTranscript = applyTranscriptSnapshot(previousTranscript, snapshot); - if (nextTranscript === previousTranscript) return 'done'; - const sessionChanged = - snapshot.sessionId !== null && snapshot.sessionId !== previousTranscript.sessionId; - transcriptRef.current = nextTranscript; - setText(nextTranscript.text); - - const previousState = stateRef.current; - stateRef.current = snapshot.state; - setState(snapshot.state); - setStyle(parseCapsuleStyle(snapshot.capsuleStyle ?? fallbackStyle) ?? 'classic'); - setSelectionPolish(snapshot.selectionPolish === true); - setTranslation(snapshot.translation === true); - if (snapshot.state === 'recording' && previousState !== 'recording' && !sessionChanged) { - transcriptRef.current = beginTranscriptGeneration(transcriptRef.current); - setText(transcriptRef.current.text); - } - if (['idle', 'done', 'cancelled', 'error'].includes(snapshot.state)) { - transcriptRef.current = clearTranscriptText(transcriptRef.current); - setText(''); - } - return 'done'; - }; - const replaySnapshot = async (fallbackStyle: CapsuleStyle) => { - for (const delayMs of snapshotRetryDelays) { - if (cancelled) return; - if (delayMs > 0) { - await new Promise((resolve) => window.setTimeout(resolve, delayMs)); - } - if (cancelled) return; - const snapshot = await getCapsuleSnapshot(); - if (cancelled) return; - if (!snapshot) continue; - if (applySnapshot(snapshot, fallbackStyle) === 'done') return; - } - }; - if (cancelled) { - stateHandle(); - transcriptHandle(); - preferenceHandle(); - } else { - unlisten = () => { - stateHandle(); - transcriptHandle(); - preferenceHandle(); - }; - const preferences = await getSettings(); - if (!cancelled) { - setEnabled(preferences.capsuleTranscriptEnabled ?? true); - setFontSize(capsuleTranscriptFontSize(preferences.capsuleTranscriptFontSize)); - setStyle(parseCapsuleStyle(preferences.capsuleStyle) ?? 'classic'); - await replaySnapshot(preferences.capsuleStyle); - } - } - })().catch((error) => console.warn('[capsule-rail] subscription failed', error)); - return () => { - cancelled = true; - unlisten?.(); - }; - }, []); - - const liveText = visibleCapsuleTranscript(text, enabled, state, selectionPolish); - const typeless = style === 'typeless'; - const railHeight = getCapsuleTranscriptRailHeight(style); - return ( -
- - {translation && !selectionPolish && typeless && ( -
- {t('capsule.translating')} -
- )} -
- ); -} - -export function LiveTranscriptPill({ - text, - tone = 'frost', - stageWidth, - maxWidth, - minWidth = INSERT_TEXT_MOTION.minWidth, - height = DEFAULT_PILL_HEIGHT, - onCancel, - onConfirm, - cancelEnabled = true, - confirmEnabled = true, - cancelLabel, - confirmLabel, - controlSize = 28, - fontSize = FONT_SIZE, -}: LiveTranscriptPillProps) { - const reduceMotion = useReducedMotion(); - const hasControls = Boolean(onCancel || onConfirm); - const padX = INSERT_TEXT_MOTION.padX + (hasControls ? controlSize + 6 : 0); - const pillMinWidth = hasControls ? Math.max(minWidth, controlSize * 2 + 72) : minWidth; - const [units, setUnits] = useState(() => diffInsertWindowUnits([], text)); - const [seenText, setSeenText] = useState(text); - if (text !== seenText) { - setSeenText(text); - setUnits((prev) => diffInsertWindowUnits(prev, text)); - } - - const renderWindow = useMemo( - () => - selectInsertRenderWindow( - units, - (glyph) => measureGlyphWidth(glyph, fontSize), - maxWidth, - padX, - INSERT_TEXT_RENDER_WINDOW, - ), - [units, fontSize, maxWidth, padX], - ); - const renderUnits = renderWindow.units; - const widths = renderWindow.widths; - const contentWidth = useMemo( - () => - clampInsertContentWidth( - widths.reduce((sum, width) => sum + width, 0), - maxWidth, - padX, - ), - [widths, maxWidth, padX], - ); - const positions = useMemo(() => rightAnchoredPositions(widths), [widths]); - // Start appended glyphs beyond the old tail, so they never appear on top of - // retained text while the displacement spring is still gathering speed. - const birthAdvance = appendedBirthAdvance(renderUnits, widths); - const originIndex = firstBornIndex(renderUnits); - const starts = useMemo(() => prefixWidths(widths), [widths]); - const originX = (starts[originIndex] ?? 0) + (widths[originIndex] ?? 0) / 2; - const insertedCount = renderUnits.filter((unit) => unit.born).length; - const delays = useMemo( - () => planCharDelays(widths, originIndex, insertedCount), - [widths, originIndex, insertedCount], - ); - const plan = useMemo( - () => - planCapsuleInsertMotion({ - stageWidth, - contentWidth, - originX, - minWidth: pillMinWidth, - maxWidth, - padX, - }), - [stageWidth, contentWidth, originX, pillMinWidth, maxWidth, padX], - ); - - const widthMv = useMotionValue(pillMinWidth); - const rightEdgeMv = useMotionValue(stageWidth / 2 + pillMinWidth / 2); - // Delayed recentering may otherwise push a large batch beyond the native - // WebView's left edge. Constrain the rendered frame, not spring momentum. - const visibleRightMv = useTransform([rightEdgeMv, widthMv], ([right, width]) => - Math.max(Number(width), Math.min(stageWidth, Number(right))), - ); - const leftMv = useTransform( - [visibleRightMv, widthMv], - ([right, width]) => Number(right) - Number(width), - ); - const trackRightMv = useTransform(visibleRightMv, (right) => stageWidth - Number(right) + padX); - - const trackWidthMv = useTransform(widthMv, (width) => Math.max(1, width - padX * 2)); - - useEffect(() => { - if (reduceMotion) { - widthMv.set(plan.width); - rightEdgeMv.set(plan.rightEdge); - return undefined; - } - const widthAnim = animate(widthMv, plan.width, { - type: 'spring', - ...INSERT_TEXT_MOTION.widthSpring, - delay: plan.widthDelayMs / 1000, - }); - const rightAnim = animate(rightEdgeMv, plan.rightEdge, { - type: 'spring', - ...INSERT_TEXT_MOTION.recenterSpring, - delay: plan.recenterDelayMs / 1000, - }); - return () => { - widthAnim.stop(); - rightAnim.stop(); - }; - }, [ - plan.width, - plan.rightEdge, - plan.widthDelayMs, - plan.recenterDelayMs, - reduceMotion, - rightEdgeMv, - widthMv, - ]); - - const overflowing = contentWidth + padX * 2 >= maxWidth - 0.5; - - return ( -
- - {onCancel && ( - - )} - {onConfirm && ( - - )} - - - {renderUnits.map((unit, index) => ( - - ))} - - - {text} - -
- ); -} - -/** Birth timing belongs to this keyed glyph, not to later recognition revisions. */ -function TranscriptGlyph({ - text, - delay, - reduceMotion, -}: { - text: string; - delay: number; - reduceMotion: boolean; -}) { - const [birthDelay] = useState(delay); - return ( - - {text === ' ' ? '\u00a0' : text} - - ); -} +export * from '../features/capsule/LiveTranscriptPill'; diff --git a/openless-all/app/src/components/MobileMoreSheet.tsx b/openless-all/app/src/components/MobileMoreSheet.tsx index 60b7a5f40..477d30928 100644 --- a/openless-all/app/src/components/MobileMoreSheet.tsx +++ b/openless-all/app/src/components/MobileMoreSheet.tsx @@ -1,170 +1 @@ -import { useRef, type CSSProperties } from 'react'; -import { useExitMount } from '../lib/useExitMount'; -import { useOverlayMotion } from '../lib/motion'; -import { useTranslation } from 'react-i18next'; -import { Icon } from './Icon'; -import type { AppTab } from '../state/useAppState'; - -const MORE_TABS: Array<{ id: AppTab; icon: string }> = [ - { id: 'vocab', icon: 'vocab' }, - { id: 'translation', icon: 'translate' }, - { id: 'selectionAsk', icon: 'selectionAsk' }, - { id: 'quickNote', icon: 'history' }, - { id: 'corrections', icon: 'filter' }, -]; - -interface MobileMoreSheetProps { - open: boolean; - currentTab: AppTab; - onClose: () => void; - onSelectTab: (tab: AppTab) => void; - onOpenSettings: () => void; -} - -export function MobileMoreSheet({ - open, - currentTab, - onClose, - onSelectTab, - onOpenSettings, -}: MobileMoreSheetProps) { - const { t } = useTranslation(); - const { mounted, closing } = useExitMount(open); - const overlayRef = useRef(null); - const cardRef = useRef(null); - useOverlayMotion(overlayRef, closing, 'backdrop', mounted); - useOverlayMotion(cardRef, closing, 'sheet', mounted); - if (!mounted) return null; - - return ( -
-
e.stopPropagation()} - style={{ - background: 'var(--ol-surface)', - borderTopLeftRadius: 'var(--ol-radius)', - borderTopRightRadius: 'var(--ol-radius)', - border: '0.5px solid var(--ol-line)', - padding: '12px 12px calc(12px + env(safe-area-inset-bottom, 0px))', - boxShadow: '0 -8px 32px -8px rgba(15,17,22,0.18)', - }} - > -
- - {t('nav.more')} - - -
-
- {MORE_TABS.map((item) => { - const active = currentTab === item.id; - return ( - - ); - })} - -
-
-
- ); -} - -const iconBtnStyle: CSSProperties = { - width: 32, - height: 32, - border: 0, - borderRadius: 'var(--ol-radius)', - background: 'transparent', - color: 'var(--ol-ink-3)', - display: 'inline-flex', - alignItems: 'center', - justifyContent: 'center', - cursor: 'default', -}; - -const rowBtnStyle: CSSProperties = { - display: 'flex', - width: '100%', - boxSizing: 'border-box', - minWidth: 0, - flexWrap: 'nowrap', - alignItems: 'center', - gap: 12, - padding: '12px 14px', - borderRadius: 'var(--ol-r-md)', - border: 0, - background: 'transparent', - fontFamily: 'inherit', - fontSize: 14, - cursor: 'default', - textAlign: 'left', -}; - -const rowLabelStyle: CSSProperties = { - flex: 1, - minWidth: 0, - overflow: 'hidden', - textOverflow: 'ellipsis', - whiteSpace: 'nowrap', -}; +export { MobileMoreSheet } from '../app/shell/MobileMoreSheet'; diff --git a/openless-all/app/src/components/MobileStyleSheet.tsx b/openless-all/app/src/components/MobileStyleSheet.tsx index 8a9c1bd68..2c87efcb5 100644 --- a/openless-all/app/src/components/MobileStyleSheet.tsx +++ b/openless-all/app/src/components/MobileStyleSheet.tsx @@ -1,153 +1 @@ -import { useRef, type CSSProperties } from 'react'; -import { useExitMount } from '../lib/useExitMount'; -import { useOverlayMotion } from '../lib/motion'; -import { useTranslation } from 'react-i18next'; -import { Icon } from './Icon'; -import { subItemLabelKey } from '../lib/navLabels'; -import type { AppTab } from '../state/useAppState'; - -const STYLE_TABS: Array<{ id: AppTab; icon: string }> = [ - { id: 'style', icon: 'style' }, - { id: 'marketplace', icon: 'sparkle' }, -]; - -interface MobileStyleSheetProps { - open: boolean; - currentTab: AppTab; - onClose: () => void; - onSelectTab: (tab: AppTab) => void; -} - -export function MobileStyleSheet({ - open, - currentTab, - onClose, - onSelectTab, -}: MobileStyleSheetProps) { - const { t } = useTranslation(); - const { mounted, closing } = useExitMount(open); - const overlayRef = useRef(null); - const cardRef = useRef(null); - useOverlayMotion(overlayRef, closing, 'backdrop', mounted); - useOverlayMotion(cardRef, closing, 'sheet', mounted); - if (!mounted) return null; - - return ( -
-
e.stopPropagation()} - style={{ - background: 'var(--ol-surface)', - borderTopLeftRadius: 'var(--ol-radius)', - borderTopRightRadius: 'var(--ol-radius)', - border: '0.5px solid var(--ol-line)', - padding: '12px 12px calc(12px + env(safe-area-inset-bottom, 0px))', - boxShadow: '0 -8px 32px -8px rgba(15,17,22,0.18)', - }} - > -
- - {t('nav.group.style')} - - -
-
- {STYLE_TABS.map((item) => { - const active = currentTab === item.id; - return ( - - ); - })} -
-
-
- ); -} - -const iconBtnStyle: CSSProperties = { - width: 32, - height: 32, - border: 0, - borderRadius: 'var(--ol-radius)', - background: 'transparent', - color: 'var(--ol-ink-3)', - display: 'inline-flex', - alignItems: 'center', - justifyContent: 'center', - cursor: 'default', -}; - -const rowBtnStyle: CSSProperties = { - display: 'flex', - width: '100%', - boxSizing: 'border-box', - minWidth: 0, - flexWrap: 'nowrap', - alignItems: 'center', - gap: 12, - padding: '12px 14px', - borderRadius: 'var(--ol-r-md)', - border: 0, - background: 'transparent', - fontFamily: 'inherit', - fontSize: 14, - cursor: 'default', - textAlign: 'left', -}; - -const rowLabelStyle: CSSProperties = { - flex: 1, - minWidth: 0, - overflow: 'hidden', - textOverflow: 'ellipsis', - whiteSpace: 'nowrap', -}; +export { MobileStyleSheet } from '../app/shell/MobileStyleSheet'; diff --git a/openless-all/app/src/components/NotificationCenter.tsx b/openless-all/app/src/components/NotificationCenter.tsx new file mode 100644 index 000000000..4d89c6f22 --- /dev/null +++ b/openless-all/app/src/components/NotificationCenter.tsx @@ -0,0 +1 @@ +export { NotificationCenter } from '../ui/feedback/NotificationCenter'; diff --git a/openless-all/app/src/components/Onboarding.tsx b/openless-all/app/src/components/Onboarding.tsx index 1c6ef5de4..92c70aa27 100644 --- a/openless-all/app/src/components/Onboarding.tsx +++ b/openless-all/app/src/components/Onboarding.tsx @@ -1,451 +1 @@ -// Onboarding.tsx — first-run permission and service setup. - -import { useEffect, useMemo, useState, type ReactNode } from 'react'; -import { useTranslation } from 'react-i18next'; -import { AndroidPermissionsPanel } from '@android/components/AndroidPermissionsPanel'; -import { - checkAndroidMicrophoneAccess, - requestAndroidMicrophoneAccess, -} from '@android/lib/androidMicrophonePermission'; -import { getPlatformCapabilities, openSystemSettings } from '../lib/ipc'; -import type { PermissionStatus, PlatformCapabilities } from '../lib/types'; -import { ProvidersSection } from '../pages/settings/ChannelList'; -import { DesktopOnboarding } from './DesktopOnboarding'; - -interface OnboardingProps { - onComplete: () => void | Promise; -} - -type AndroidStepId = - 'microphone' | 'accessibility' | 'overlayPermission' | 'overlayConfig' | 'asr' | 'llm'; - -export function Onboarding({ onComplete }: OnboardingProps) { - const { t } = useTranslation(); - const [platformCaps, setPlatformCaps] = useState(null); - - useEffect(() => { - void getPlatformCapabilities().then(setPlatformCaps); - }, []); - - if (!platformCaps) { - return ; - } - - if (platformCaps.platform === 'android') { - return ; - } - - return ; -} - -function AndroidOnboarding({ onComplete }: OnboardingProps) { - const { t } = useTranslation(); - const [stepIndex, setStepIndex] = useState(0); - - const steps = useMemo>( - () => [ - { - id: 'microphone', - title: t('onboarding.androidSteps.microphoneTitle'), - desc: t('onboarding.androidSteps.microphoneDesc'), - }, - { - id: 'accessibility', - title: t('onboarding.androidSteps.accessibilityTitle'), - desc: t('onboarding.androidSteps.accessibilityDesc'), - }, - { - id: 'overlayPermission', - title: t('onboarding.androidSteps.overlayPermissionTitle'), - desc: t('onboarding.androidSteps.overlayPermissionDesc'), - }, - { - id: 'overlayConfig', - title: t('onboarding.androidSteps.overlayConfigTitle'), - desc: t('onboarding.androidSteps.overlayConfigDesc'), - }, - { - id: 'asr', - title: t('onboarding.androidSteps.asrTitle'), - desc: t('onboarding.androidSteps.asrDesc'), - }, - { - id: 'llm', - title: t('onboarding.androidSteps.llmTitle'), - desc: t('onboarding.androidSteps.llmDesc'), - }, - ], - [t], - ); - - const current = steps[stepIndex] ?? steps[0]; - const isFirst = stepIndex === 0; - const isLast = stepIndex === steps.length - 1; - - const goNext = () => { - if (isLast) { - onComplete(); - return; - } - setStepIndex((value) => Math.min(value + 1, steps.length - 1)); - }; - - return ( - -
- - -
- {steps.map((step, index) => ( -
- ))} -
- -
-
-
- {t('onboarding.androidStepCounter', { current: stepIndex + 1, total: steps.length })} -
-
- {current.title} -
-
- {current.desc} -
-
- - -
- -
- - -
- - -
- - ); -} - -function AndroidStepContent({ step }: { step: AndroidStepId }) { - if (step === 'microphone') { - return ; - } - if (step === 'accessibility') { - return ( - - - - ); - } - if (step === 'overlayPermission') { - return ( - - - - ); - } - if (step === 'overlayConfig') { - return ( - - - - ); - } - if (step === 'asr') { - return ; - } - return ; -} - -function AndroidMicrophoneStep() { - const { t } = useTranslation(); - const [status, setStatus] = useState('notDetermined'); - const [busy, setBusy] = useState(false); - - const refresh = async () => { - setStatus(await checkAndroidMicrophoneAccess()); - }; - - useEffect(() => { - void refresh(); - // issue #470: purely event-driven, no high-frequency polling. Refresh on window - // refocus / re-visible (granting always goes through System Settings and back). - const onFocus = () => { - void refresh(); - }; - const onVisibility = () => { - if (document.visibilityState === 'visible') void refresh(); - }; - window.addEventListener('focus', onFocus); - document.addEventListener('visibilitychange', onVisibility); - return () => { - window.removeEventListener('focus', onFocus); - document.removeEventListener('visibilitychange', onVisibility); - }; - }, []); - - const request = async () => { - setBusy(true); - try { - if (status === 'denied' || status === 'restricted') { - await openSystemSettings('microphone'); - } else { - setStatus(await requestAndroidMicrophoneAccess()); - } - await refresh(); - } finally { - setBusy(false); - } - }; - - const granted = status === 'granted' || status === 'notApplicable'; - return ( - -
-
-
- {t('onboarding.micTitle')} -
-
- {t('onboarding.micDesc')} -
-
- -
- -
- ); -} - -function OnboardingLoading({ label }: { label: string }) { - return ( -
- {label} -
- ); -} - -function OnboardingSurface({ children }: { children: ReactNode }) { - return ( -
- {children} -
- ); -} - -function BrandHeader({ - title, - desc, - compact = false, -}: { - title: string; - desc: string; - compact?: boolean; -}) { - return ( -
- OpenLess -
-
- {title} -
-
- {desc} -
-
-
- ); -} - -function AndroidStepCard({ children }: { children: ReactNode }) { - return ( -
- {children} -
- ); -} - -function StatusBadge({ granted, label }: { granted: boolean; label: string }) { - return ( - - {label} - - ); -} - -const primaryButtonStyle = { - flex: 1, - minHeight: 42, - padding: '10px 14px', - fontSize: 13, - fontWeight: 'var(--ol-font-weight-semibold)', - fontFamily: 'inherit', - border: 0, - borderRadius: 'var(--ol-r-md)', - background: 'var(--ol-primary-solid-bg)', - color: 'var(--ol-primary-solid-ink)', - cursor: 'default', -} as const; - -const secondaryButtonStyle = { - flex: 1, - minHeight: 42, - padding: '10px 14px', - fontSize: 13, - fontWeight: 'var(--ol-font-weight-semibold)', - fontFamily: 'inherit', - border: '0.5px solid var(--ol-line-strong)', - borderRadius: 'var(--ol-r-md)', - background: 'var(--ol-surface)', - color: 'var(--ol-ink-2)', - cursor: 'default', -} as const; - -const plainButtonStyle = { - width: '100%', - padding: '10px 14px', - fontSize: 12.5, - fontWeight: 'var(--ol-font-weight-medium)', - fontFamily: 'inherit', - border: 0, - borderRadius: 'var(--ol-control-radius)', - background: 'transparent', - color: 'var(--ol-ink-4)', - cursor: 'default', -} as const; +export * from '../features/onboarding/Onboarding'; diff --git a/openless-all/app/src/components/OpenLessCapsule.css b/openless-all/app/src/components/OpenLessCapsule.css index b96d8eef3..2486f5c1b 100644 --- a/openless-all/app/src/components/OpenLessCapsule.css +++ b/openless-all/app/src/components/OpenLessCapsule.css @@ -1,177 +1 @@ -/* Compact geometry with a theme-aware frosted surface and readable blue controls. */ -.ol-default-capsule { - position: relative; - height: 32px; - flex: 0 0 auto; - isolation: isolate; - overflow: hidden; - border-radius: 999px; - color-scheme: var(--ol-pill-scheme); - color: var(--ol-pill-ink); - font-family: var(--ol-font-sans); - box-shadow: 0 3px 10px var(--ol-pill-shadow); - transform-origin: center bottom; -} -.ol-default-capsule::before { - content: ''; - position: absolute; - inset: 0; - z-index: -2; - background: var(--ol-pill-fill); - backdrop-filter: blur(16px) saturate(140%); - -webkit-backdrop-filter: blur(16px) saturate(140%); - box-shadow: inset 0 1px 0 var(--ol-pill-highlight); - border: 1px solid var(--ol-pill-border); - border-radius: inherit; -} -.ol-default-capsule::after { - content: ''; - position: absolute; - inset: 0; - z-index: -1; - border-radius: inherit; - background: var(--ol-pill-sweep); - transform: translateX(-100%); - pointer-events: none; -} -.ol-default-capsule[data-processing='true']::after { - animation: ol-capsule-sweep 2.4s linear infinite; -} -/* Reference processing fill travels left→right; it is not a pulsing spinner. */ -@keyframes ol-capsule-sweep { - 0% { - transform: translateX(-100%); - } - 85%, - 100% { - transform: translateX(0); - } -} -.ol-default-capsule[data-translation='true']::before { - box-shadow: inset 0 4px 7px -3px rgb(37 99 235 / 65%); -} -.ol-default-recording { - position: absolute; - top: 0; - left: 50%; - width: 116px; - height: 32px; - transform: translateX(-50%); - display: flex; - align-items: center; - justify-content: center; - transition: opacity 90ms linear 60ms; -} -.ol-default-recording[aria-hidden='true'] { - opacity: 0; - pointer-events: none; -} -.ol-default-action { - position: absolute; - top: 4px; - display: grid; - place-items: center; - width: 24px; - height: 24px; - padding: 0; - border: 0; - border-radius: 50%; - background: var(--ol-pill-cancel); - color: var(--ol-pill-cancel-ink); - cursor: pointer; - transition: - opacity 80ms linear, - background-color 100ms ease; -} -.ol-default-cancel { - left: 4px; -} -.ol-default-confirm { - right: 4px; - color: #fff; - background: var(--ol-pill-confirm); -} -.ol-default-action[aria-hidden='true'] { - opacity: 0; - pointer-events: none; -} -.ol-default-capsule[data-processing='true'] .ol-default-action { - transition-delay: 50ms; -} -.ol-default-action:focus-visible, -.ol-default-processing-cancel:focus-visible { - outline: 2px solid var(--ol-pill-ink); - outline-offset: -2px; -} -.ol-default-action:active:not(:disabled) { - scale: 0.92; -} -@media (hover: hover) and (pointer: fine) { - .ol-default-cancel:hover:not(:disabled) { - background: var(--ol-pill-cancel-hover); - } - .ol-default-confirm:hover:not(:disabled) { - background: var(--ol-pill-confirm-hover); - } -} -.ol-default-status { - position: absolute; - inset: 0; - display: flex; - align-items: center; - justify-content: center; - padding: 0 14px; - pointer-events: none; - font-size: 12px; - font-weight: calc(500 + var(--ol-font-weight-offset)); - opacity: 1; - transition: opacity 80ms linear 120ms; -} -.ol-default-status[aria-hidden='true'] { - opacity: 0; - transition-delay: 0ms; -} -.ol-default-status > span { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.ol-default-capsule[data-error='true'] .ol-default-status { - color: var(--ol-pill-error); -} -.ol-default-processing-cancel { - position: absolute; - inset: 0; - width: 100%; - height: 100%; - padding: 0; - border: 0; - border-radius: inherit; - background: transparent; - cursor: pointer; -} -.ol-default-waveform { - display: flex; - align-items: center; - justify-content: center; - gap: 2px; - width: 40px; - height: 18px; -} -.ol-default-waveform > span { - width: 1.5px; - height: 1.5px; - flex: 0 0 1.5px; - border-radius: 999px; - background: var(--ol-pill-ink); -} -@media (prefers-reduced-motion: reduce) { - .ol-default-capsule::after { - animation: none !important; - } - .ol-default-recording, - .ol-default-action, - .ol-default-status { - transition: none; - } -} +@import '../features/capsule/OpenLessCapsule.css'; diff --git a/openless-all/app/src/components/OpenLessCapsule.tsx b/openless-all/app/src/components/OpenLessCapsule.tsx index ac5afb903..f5b5b1e32 100644 --- a/openless-all/app/src/components/OpenLessCapsule.tsx +++ b/openless-all/app/src/components/OpenLessCapsule.tsx @@ -1,227 +1 @@ -import { motion } from 'framer-motion'; -import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Icon } from './Icon'; -import { VoiceOrbStage } from './VoiceOrbStage'; -import { useReducedMotion } from '../lib/motion'; -import type { OS } from './WindowChrome'; -import type { CapsuleState, CapsuleStyle } from '../lib/types'; -import './CapsuleStyles.css'; -import './OpenLessCapsule.css'; - -// Measured from the 60 fps reference: 232×64 physical pixels at 2×. -const ENVELOPE = [0.22, 0.34, 0.48, 0.65, 0.82, 1, 0.82, 0.65, 0.48, 0.34, 0.22]; -const MORPH = { duration: 0.22, ease: [0.22, 1, 0.36, 1] as const }; -export const DEFAULT_CAPSULE_EXIT_MS = 180; - -function useCapsulePresence(ref: RefObject, leaving: boolean, preview: boolean) { - const reduced = useReducedMotion(); - const interrupted = useRef(null); - useLayoutEffect(() => { - const node = ref.current; - if (!node) return; - const visible = { opacity: 1, transform: 'none', filter: 'none' }; - const hidden = { - opacity: 0, - transform: `translateY(${leaving ? 5 : 6}px)`, - filter: `blur(${leaving ? 3 : 4}px)`, - }; - const target = leaving ? hidden : visible; - const apply = () => { - Object.assign(node.style, target, { willChange: '' }); - }; - if (preview || reduced || typeof node.animate !== 'function') { - interrupted.current = null; - apply(); - return; - } - const from = interrupted.current ?? (leaving ? visible : hidden); - interrupted.current = null; - node.style.willChange = 'opacity, transform, filter'; - const animation = node.animate([from, target], { - duration: leaving ? DEFAULT_CAPSULE_EXIT_MS : 240, - easing: 'cubic-bezier(0.22, 1, 0.36, 1)', - fill: 'both', - }); - animation.id = 'ol-capsule-presence'; - let cancelled = false; - void animation.finished - .then(() => { - if (cancelled) return; - apply(); - animation.cancel(); - }) - .catch(() => {}); - return () => { - cancelled = true; - const painted = getComputedStyle(node); - interrupted.current = { - opacity: painted.opacity, - transform: painted.transform, - filter: painted.filter, - }; - Object.assign(node.style, interrupted.current, { willChange: '' }); - animation.cancel(); - }; - }, [ref, leaving, preview, reduced]); -} - -export function CapsuleWaveform({ level, active = true }: { level: number; active?: boolean }) { - const root = useRef(null); - const input = useRef(level); - input.current = level; - const reduced = useReducedMotion(); - useEffect(() => { - const bars = root.current?.children; - if (!bars) return; - let frame = 0; - let previous = 0; - let smoothed = 0; - const draw = (now: number) => { - const dt = previous ? Math.min(now - previous, 50) : 16; - previous = now; - const voice = active ? Math.min(1, Math.max(0, (input.current - 0.008) / 0.32)) : 0; - smoothed += (voice - smoothed) * (1 - Math.exp(-dt / (voice > smoothed ? 35 : 90))); - ENVELOPE.forEach((envelope, index) => { - // The centre stays strongest; neighbouring bars do not move as one rigid icon. - const ripple = reduced ? 1 : 0.86 + 0.14 * Math.sin(now / 85 + index * 0.8); - (bars[index] as HTMLElement).style.height = - `${1.5 + 14.5 * Math.pow(smoothed, 0.6) * envelope * ripple}px`; - }); - if (active && !reduced) frame = requestAnimationFrame(draw); - }; - draw(performance.now()); - return () => cancelAnimationFrame(frame); - }, [active, reduced, reduced ? level : undefined]); - return ( -
- + 1 spins faster - * while thinking, settling back to standard speed at the end. - */ - speed?: number; - /** orb only: true = the six dots merge into one circle at the center (insert-complete outro). */ - merging?: boolean; - className?: string; - style?: CSSProperties; -} - -/** Internal render resolution scale (multiplied by devicePixelRatio); demo value — lower saves GPU. */ -const RENDER_SCALE = 0.75; - -/** - * Wave "collapse" level during warming: uResolved parks at this low value — the wave - * gathers toward the center, clearly not expanded (reads as "loading, not ready"). - * Once the mic is ready, uResolved rises to 1 and the wave expands into the full - * voice wave as the sole "ready to speak" signal. Low enough to look unformed, but - * not 0 (0 is the thinking state's center orb; avoid that collision). - */ -const WARMING_RESOLVED = 0.2; - -// Exported for chat/orbFeed (shared orb render source: one GL context mirrored to -// several small avatars). -export const VERTEX_SRC = 'attribute vec2 aPos; void main(){ gl_Position=vec4(aPos,0.0,1.0); }'; - -const WAVE_FRAGMENT_SRC = ` -precision highp float; -uniform vec2 iResolution; uniform float iTime; -uniform float uResolved; -uniform float uLevel; -const float PI = 3.14159265359; -const float AMPLITUDE=0.32, FREQ=1.1, ABER_FREQ=1.0, SPEED=2.4, WAVE_SCALE=0.6; -const float ABERRATION=2.6, THICKNESS=3.0, INTENSITY=2., FALLOFF=1.7; -const float EDGE_MASK=0.4, EDGE_INSET=0.0, BAND_FILL=30000.0, BAND_THICK=0.08, SOFTNESS=2.5; -const float LOW_AMP=6.0, LOW_INT=1.5, MID_ABER=0.8, MID_ABAMP=0.05, MID_SOFT=0.4; -const float HIGH_ABER=0.5, HIGH_ABAMP=0.06, UNRES_SCALE=0.14; -vec3 spectral4(int s){ float x=float(s); - return clamp(vec3(abs(x-3.0)-1.0, 2.0-abs(x-2.0), 2.0-abs(x-4.0)), 0.0, 1.0); } -void main(){ - vec2 R=iResolution.xy; float aspect=R.x/R.y; - vec2 p=(gl_FragCoord.xy+0.5)*2.0/R-1.0; p.x*=aspect; - float yScreen=p.y; p/=max(WAVE_SCALE,0.1); - float t=iTime; - float dv=clamp(uLevel,0.0,1.0); - float low =clamp(0.45+0.45*sin(t*0.8)*sin(t*0.37+1.0),0.0,1.0)*dv; - float mid =clamp(0.40+0.40*sin(t*1.7+2.0)*sin(t*0.53),0.0,1.0)*dv; - float high=clamp(0.30+0.30*sin(t*2.9+4.0)*sin(t*0.71+2.0),0.0,1.0)*dv; - float res=clamp(uResolved,0.0,1.0); - float drift=mod(t,20.0*PI)*SPEED; - /* Converge = "edges shrink toward the center": wave x-coords stretch as res drops, - pushing the visible ripples from both ends toward the center, instead of - flattening in place while the phase keeps running sideways (pulse feel). - The orb distance field still uses the unscaled p to stay a perfect circle. */ - vec2 pw=p; pw.x*=mix(5.0,1.0,res); - float xN=pw.x/max(aspect,1.0); - float env=cos(PI*0.5*min(abs(0.9*xN),1.0)); env*=env; - float A1=(AMPLITUDE*mix(0.14,1.0,dv))+0.01*low*LOW_AMP; - float A2=A1+mid*MID_ABAMP+high*HIGH_ABAMP; - float AB=(ABERRATION+mid*MID_ABER+high*HIGH_ABER)*res; - float th=mix(0.1,0.01*THICKNESS,res); - float inten=mix(0.1,0.01*(INTENSITY+low*LOW_INT),res); - float soft=0.01*res*max(0.0,SOFTNESS+mid*MID_SOFT); - float dUnres=max(length(p)-mix(0.14,UNRES_SCALE,res),0.0); - float yMain=A1*env*res*sin(pw.x*FREQ+drift); - float bandFillTh=max(BAND_THICK,1e-4); - float bandAmt=1e-4*BAND_FILL*inten; - vec3 num=vec3(0.0),den=vec3(0.0); - for(int s=0;s<4;s++){ - vec3 hue=mix(vec3(1.0),spectral4(s),res); den+=hue; - float ab=mix(-AB,AB,float(s)/3.0); - float yL=A2*env*res*sin(pw.x*ABER_FREQ+drift+ab); - float d=mix(dUnres,abs(p.y-yL),res); - float lor=mix(1.0/(1.0+(0.02*d)*(0.02*d)),1.0,res); - float line=inten/(sqrt(d*d+soft*soft)+th); - float lo=min(yMain,yL),hi=max(yMain,yL); - float dBand=max(0.0,max(p.y-hi,lo-p.y)); - float band=bandAmt/(dBand+bandFillTh); - num+=hue*lor*(line+band); - } - vec3 col=num/den; - float dM=mix(dUnres,abs(p.y-yMain),res); - float lorM=mix(1.0/(1.0+(0.02*dM)*(0.02*dM)),1.0,res); - /* Original boost=(1-res)*(14*low+4): the converged orb's big halo would fill the - transparent window and get hard-clipped into a straight edge at the border. - Toned down — the transition collapses inward, never outward. */ - float boost=(1.0-res)*(3.0*low+1.2); - col+=0.5*inten*(lorM+boost)/(sqrt(dM*dM+soft*soft)+th); - col=pow(max(col,0.0),vec3(1.5)); - float emT=clamp((abs(yScreen)-1.0+EDGE_INSET)/(-max(EDGE_MASK,1e-4)),0.0,1.0); - float em=emT*emT*(3.0-2.0*emT); - float gauss=exp(-pow(xN*FALLOFF,2.0)); - /* Edge mask active throughout (in the original it stops working as res→0, letting leftover wave leak out the sides mid-collapse). */ - col*=em*gauss; - col*=mix(0.55,1.0,res); - float a=clamp(max(col.r,max(col.g,col.b)),0.0,1.0); - gl_FragColor=vec4(col,a); -}`; - -// Two deliberate changes vs the original siriFluidDotsCore: -// 1. Removed the 12s gather→burst explosion — the shockwave hits the square canvas -// edge and gets hard-clipped; thinking keeps pure rotation + metaball fusion. -// 2. Gathering is now an entrance driven by the uGather uniform: 1 = all six dots -// merged at the center (visually the orb the wave converges into), 0 = spread -// into a ring — the wave's converged orb smoothly "melts" into the thinking dots -// with no jump or pop-in impact. -export const ORB_FRAGMENT_SRC = ` -precision highp float; -uniform vec2 iResolution; uniform float iTime; -uniform float uGather; -const float TAU=6.28318530718; -const int N=6; -const float SMOOTH_K=0.08, INTENSITY=0.0025, FALLOFF_P=1.35, FADE_START=0.02, FADE_END=0.56; -const float ABERR=0.005; const vec3 SPECTRAL=vec3(0.0,0.5,1.0)*ABERR; -const float HUE_SPEED=0.06, COLOR_K=0.5, SAT=0.01, HUE_SPAN=0.667; -const float MERGE_PERIOD=6.0, STAGGER=0.33, HOLD=0.0; -const float W=4.6, L=3.2, PIERCE=0.12, RECOIL=0.035, REC_LAG=0.11; -const float GATHER_R=0.008, GATHER_DIM=0.85; -float hash11(float n){ return fract(sin(n*127.1+311.7)*43758.5453); } -float settleWL(float tau,float w,float l){ if(tau<=0.0) return 0.0; return 1.0-exp(-l*tau)*cos(w*tau); } -float settle(float tau){ return settleWL(tau,W,L); } -float smin(float a,float b,float k){ float h=max(k-abs(a-b),0.0)/k; return min(a,b)-h*h*k*0.25; } -vec3 hue2rgb(float h){ h=fract(h); - float r=clamp(abs(h*6.0-3.0)-1.0,0.0,1.0); - float g=clamp(2.0-abs(h*6.0-2.0),0.0,1.0); - float b=clamp(2.0-abs(h*6.0-4.0),0.0,1.0); - return vec3(r,g,b); } -float dotR(float fi,float seed,float t){ return 0.036+0.010*sin(t*1.3+seed*TAU)+0.005*sin(t*2.4+fi*1.3); } -float dotSD(vec2 p,vec2 pos,float r,float t,float fi,float shapeDamp){ - vec2 d=p-pos; - float sq=0.075*(0.5+0.5*sin(t*0.9+fi*2.0))*shapeDamp; - float ca=cos(t*0.35+fi),sa=sin(t*0.35+fi); - d=mat2(ca,-sa,sa,ca)*d; - d*=vec2(1.0+sq,1.0-sq); - return length(d)-r; } -vec3 scene(vec2 p,float t){ - float k=floor(t/MERGE_PERIOD); - float u=fract(t/MERGE_PERIOD); - float te=u*MERGE_PERIOD; - float gC=clamp(uGather,0.0,1.0); - float gBright=mix(1.0,GATHER_DIM,gC)*(1.0+0.30*gC); - vec3 total3=vec3(1e5); - vec3 cAcc=vec3(0.0); - float wAcc=1e-6; - for(int i=0;i(null); - const reducedMotion = useReducedMotion(); - const redrawRef = useRef<(() => void) | null>(null); - // 60Hz level updates go through a ref bridge: render only syncs the value and the - // draw loop reads it in rAF, so the GL pipeline is never rebuilt for prop changes. - const levelRef = useRef(0); - const resolvedRef = useRef(1); - const speedRef = useRef(1); - const mergingRef = useRef(0); - const warmingRef = useRef(0); - const warmupMsRef = useRef(150); - levelRef.current = Math.min(1, Math.max(0, level ?? 0)); - resolvedRef.current = resolved === false ? 0 : 1; - speedRef.current = speed ?? 1; - mergingRef.current = merging === true ? 1 : 0; - warmingRef.current = warming === true ? 1 : 0; - warmupMsRef.current = warmupMs ?? 150; - - useLayoutEffect(() => { - if (reducedMotion) redrawRef.current?.(); - }, [level, resolved, warming, warmupMs, speed, merging, reducedMotion]); - - useEffect(() => { - const host = hostRef.current; - if (!host) return undefined; - // Create a new canvas per effect: unmount deliberately loseContext-es to release - // GPU, and the browser always returns the same (now dead) context for the same - // canvas — rebuilding the pipeline on the old canvas fails entirely when React - // reuses the DOM node (StrictMode double-mount / mode-switch effect rerun; - // "compile failed: null"). New canvas = new context, bypassing it completely. - const canvas = document.createElement('canvas'); - canvas.style.cssText = 'display:block;width:100%;height:100%;pointer-events:none;'; - host.appendChild(canvas); - const gl = canvas.getContext('webgl', { - alpha: true, - premultipliedAlpha: true, - antialias: false, - }); - if (!gl) { - canvas.remove(); - return undefined; - } - - const compile = (type: number, src: string): WebGLShader | null => { - const shader = gl.createShader(type); - if (!shader) return null; - gl.shaderSource(shader, src); - gl.compileShader(shader); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.error('[SiriGL] shader compile failed:', gl.getShaderInfoLog(shader)); - gl.deleteShader(shader); - return null; - } - return shader; - }; - - const vs = compile(gl.VERTEX_SHADER, VERTEX_SRC); - const fs = compile(gl.FRAGMENT_SHADER, mode === 'wave' ? WAVE_FRAGMENT_SRC : ORB_FRAGMENT_SRC); - if (!vs || !fs) { - releaseWebGL(gl, { shaders: [vs, fs] }); - canvas.remove(); - return undefined; - } - const program = gl.createProgram(); - if (!program) { - releaseWebGL(gl, { shaders: [vs, fs] }); - canvas.remove(); - return undefined; - } - gl.attachShader(program, vs); - gl.attachShader(program, fs); - gl.linkProgram(program); - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - console.error('[SiriGL] program link failed:', gl.getProgramInfoLog(program)); - releaseWebGL(gl, { program, shaders: [vs, fs] }); - canvas.remove(); - return undefined; - } - gl.useProgram(program); - - const buffer = gl.createBuffer(); - if (!buffer) { - releaseWebGL(gl, { program, shaders: [vs, fs] }); - canvas.remove(); - return undefined; - } - gl.bindBuffer(gl.ARRAY_BUFFER, buffer); - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); - const aPos = gl.getAttribLocation(program, 'aPos'); - gl.enableVertexAttribArray(aPos); - gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0); - - const uResolution = gl.getUniformLocation(program, 'iResolution'); - const uTime = gl.getUniformLocation(program, 'iTime'); - const uResolvedLoc = gl.getUniformLocation(program, 'uResolved'); - const uLevelLoc = gl.getUniformLocation(program, 'uLevel'); - const uGatherLoc = gl.getUniformLocation(program, 'uGather'); - - // Draw-side easing state: level attacks fast / releases slow (VU-meter feel), - // resolved approaches exponentially ("slowly converging"). Shader time accumulates - // as dt×speed (not wall clock), so speed changes are jump-free. - // uGather lifecycle for orb: on entrance gather=1, all dots merged at the center - // (catching the orb the wave collapsed into) → after a beat, slowly spread from - // the center into a rotating ring → when merging=true, decisively merge back into - // one center circle (k=4) and vanish with the fade. - const GATHER_HOLD_S = 0.3; - let smoothLevel = 0; - // While warming, start from the collapsed state on mount (unformed = loading) to - // avoid the jarring "expand briefly then collapse"; expand to resolvedRef once the - // mic is ready. - let smoothResolved = warmingRef.current > 0.5 ? WARMING_RESOLVED : resolvedRef.current; - // Predicted expand progress (0=collapsed, 1=expanded): warming entrances climb from 0; non-warming starts at 1. - let warmProgress = warmingRef.current > 0.5 ? 0 : 1; - let smoothSpeed = speedRef.current; - let gather = 1; - let shaderTime = 0; - let elapsed = 0; - let raf = 0; - let last = performance.now(); - let inViewport = true; - let w = 1, - h = 1; - const resizeCanvas = () => { - const dpr = Math.min(window.devicePixelRatio || 1, 2) * RENDER_SCALE; - w = Math.max(1, Math.round(canvas.clientWidth * dpr)); - h = Math.max(1, Math.round(canvas.clientHeight * dpr)); - if (canvas.width !== w || canvas.height !== h) { - canvas.width = w; - canvas.height = h; - gl.viewport(0, 0, w, h); - } - }; - resizeCanvas(); - - const frame = (now: number) => { - raf = 0; - if (!inViewport || document.hidden) return; - const dt = reducedMotion ? 0 : Math.min(0.05, (now - last) / 1000); - if (reducedMotion) { - smoothLevel = visualVoice(levelRef.current); - smoothResolved = warmingRef.current > 0.5 ? WARMING_RESOLVED : resolvedRef.current; - warmProgress = warmingRef.current > 0.5 ? 0 : 1; - gather = mergingRef.current > 0.5 ? 1 : 0; - } - last = now; - elapsed += dt; - smoothSpeed += (speedRef.current - smoothSpeed) * (1 - Math.exp(-dt * 2.5)); - shaderTime += dt * smoothSpeed; - const t = shaderTime; - - // In the converged state (resolved→0) level loses meaning; switch to a subdued - // slow-breathing signal to pulse the orb. - const thinking = resolvedRef.current < 0.5; - const warmingNow = warmingRef.current > 0.5; - // Level: warming runs a low-amplitude "loading pulse" (dim, slow, clearly not - // ready), thinking breathes, recording follows the real level. - const target = warmingNow - ? 0.12 + 0.06 * Math.sin(t * 3.0) - : thinking - ? 0.14 + 0.07 * Math.sin(t * 2.2) - : visualVoice(levelRef.current); - const attack = target > smoothLevel ? 14 : 5; - smoothLevel += (target - smoothLevel) * (1 - Math.exp(-dt * attack)); - // Predicted expand: the entrance no longer dead-waits for the ready signal (that - // read as "light up → stutter → suddenly expand") but progresses smoothly from - // the keypress using the historical average load time warmupMs: - // · not ready (warming): warmProgress crawls at warmupMs pace, capped at 0.9 - // (keeping the last stretch for the ready finish); - // · ready (warming→false): quickly complete to 1 — earlier ready = more left, - // visually "expands to full quickly"; - // · very long load: hold at 0.9; a clearly unfilled wave = still not ready. - const warmupSec = Math.max(0.06, warmupMsRef.current / 1000); - if (warmingNow) { - warmProgress = Math.min(0.9, warmProgress + dt / warmupSec); - } else { - warmProgress += (1 - warmProgress) * (1 - Math.exp(-dt * 9)); - } - // resolved: thinking (resolvedRef→0) keeps the original unhurried convergence; - // entrance/recording expands from collapsed (WARMING_RESOLVED) to full via - // warmProgress, with smoothResolved following (warmProgress already sets the - // expand pace). - const targetResolved = thinking - ? resolvedRef.current - : WARMING_RESOLVED + (1 - WARMING_RESOLVED) * warmProgress; - const resolvedK = thinking ? 2.2 : 9.0; - smoothResolved += (targetResolved - smoothResolved) * (1 - Math.exp(-dt * resolvedK)); - // Spreading starts only after the entrance hold; merging (target 1) is fast, spreading (target 0) slow. - if (mergingRef.current === 1) { - gather += (1 - gather) * (1 - Math.exp(-dt * 4.0)); - } else if (elapsed > GATHER_HOLD_S) { - gather += (0 - gather) * (1 - Math.exp(-dt * 1.6)); - } - - gl.uniform2f(uResolution, w, h); - gl.uniform1f(uTime, t); - if (uResolvedLoc) gl.uniform1f(uResolvedLoc, smoothResolved); - if (uLevelLoc) gl.uniform1f(uLevelLoc, smoothLevel); - if (uGatherLoc) gl.uniform1f(uGatherLoc, gather); - gl.drawArrays(gl.TRIANGLES, 0, 3); - if (!reducedMotion) raf = requestAnimationFrame(frame); - }; - // Draw the first frame synchronously (don't wait for the next vsync): visuals - // exist at mount, one frame less hotkey latency. - frame(performance.now()); - const redraw = () => { - cancelAnimationFrame(raf); - last = performance.now(); - frame(last); - }; - // Pause both offscreen previews and hidden windows. Resume one RAF chain only. - const visibility = () => redraw(); - document.addEventListener('visibilitychange', visibility); - const intersection = new IntersectionObserver(([entry]) => { - if (inViewport === entry.isIntersecting) return; - inViewport = entry.isIntersecting; - redraw(); - }); - intersection.observe(host); - redrawRef.current = reducedMotion ? redraw : null; - const resize = new ResizeObserver(() => { - resizeCanvas(); - if (reducedMotion) redraw(); - }); - resize.observe(host); - window.addEventListener('resize', resizeCanvas); - - return () => { - if (redrawRef.current === redraw) redrawRef.current = null; - resize.disconnect(); - intersection.disconnect(); - document.removeEventListener('visibilitychange', visibility); - window.removeEventListener('resize', resizeCanvas); - cancelAnimationFrame(raf); - releaseWebGL(gl, { buffer, program, shaders: [vs, fs] }); - canvas.remove(); - }; - }, [mode, reducedMotion]); - - return ( -
- ); -} +export * from '../features/capsule/SiriGL'; diff --git a/openless-all/app/src/components/Tooltip.css b/openless-all/app/src/components/Tooltip.css index a761e8ca7..000719a2f 100644 --- a/openless-all/app/src/components/Tooltip.css +++ b/openless-all/app/src/components/Tooltip.css @@ -1,89 +1 @@ -/* Floating UI uses viewport coordinates. Cancel the app's root zoom in the portal, - then restore it on the popup so text follows interface size without double-scaling positions. */ -.ol-popup-portal { - zoom: calc(1 / var(--ol-interface-scale, 1)); -} -.ol-tooltip-anchor { - display: grid; - min-width: 0; -} -.ol-hint-trigger { - display: inline; - width: fit-content; - max-width: 100%; - border: 0; - border-radius: var(--ol-radius); - padding: 0; - background: transparent; - color: inherit; - font: inherit; - letter-spacing: inherit; - text-align: start; - text-decoration: underline dotted var(--ol-ink-4); - text-underline-offset: 4px; - text-decoration-thickness: 1px; - cursor: pointer; - touch-action: manipulation; -} -.ol-hint-trigger:focus-visible { - outline: 2px solid var(--ol-blue); - outline-offset: 4px; -} -.ol-tooltip-positioner { - z-index: 10000; -} -.ol-tooltip-positioner[data-anchor-hidden] { - visibility: hidden; -} -.ol-tooltip-bubble { - width: max-content; - zoom: var(--ol-interface-scale, 1); - max-width: min(260px, calc(var(--available-width) / var(--ol-interface-scale, 1))); - max-height: calc(var(--available-height) / var(--ol-interface-scale, 1)); - overflow-y: auto; - padding: 6px 10px; - border: 0.5px solid var(--ol-glass-border); - border-radius: var(--ol-control-radius); - background: var(--ol-glass-bg-strong); - color: var(--ol-ink); - box-shadow: var(--ol-shadow-md); - backdrop-filter: blur(12px) saturate(150%); - -webkit-backdrop-filter: blur(12px) saturate(150%); - font: var(--ol-font-weight-medium) 12px / 1.6 var(--ol-font-sans); - overflow-wrap: anywhere; - transform-origin: var(--transform-origin); - transition: - opacity 125ms ease-out, - transform 125ms ease-out; -} -.ol-tooltip-bubble[data-wrap] { - max-width: min(320px, calc(var(--available-width) / var(--ol-interface-scale, 1))); - padding: 9px 12px; -} -.ol-tooltip-bubble p { - margin: 0; -} -.ol-tooltip-bubble p + p { - margin-top: 8px; -} -.ol-tooltip-bubble[data-starting-style], -.ol-tooltip-bubble[data-ending-style] { - opacity: 0; - transform: scale(0.97); -} -.ol-tooltip-bubble[data-instant], -html[data-ol-input='keyboard'] .ol-tooltip-bubble { - transition: none; -} -@media (prefers-reduced-motion: reduce) { - .ol-tooltip-bubble { - transition: none; - } -} -@media (prefers-reduced-transparency: reduce), (prefers-contrast: more) { - .ol-tooltip-bubble { - background: var(--ol-surface); - backdrop-filter: none; - -webkit-backdrop-filter: none; - } -} +@import '../ui/styles/tooltip.css'; diff --git a/openless-all/app/src/components/Tooltip.tsx b/openless-all/app/src/components/Tooltip.tsx index 0747579fe..ebcb8ee60 100644 --- a/openless-all/app/src/components/Tooltip.tsx +++ b/openless-all/app/src/components/Tooltip.tsx @@ -1,124 +1 @@ -import { useId, useRef, useState, type ReactElement, type ReactNode } from 'react'; -import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'; - -export function TooltipProvider({ children }: { children: ReactNode }) { - return ( - - {children} - - ); -} - -interface TooltipProps { - content: ReactNode; - placement?: 'right' | 'top' | 'bottom'; - wrap?: boolean; - focusable?: boolean; - children: ReactNode; - id?: string; - className?: string; - trigger?: ReactElement; -} - -/** Base UI owns focus, Escape, outside dismissal, collision handling and portal lifetime. */ -export function Tooltip({ - content, - placement = 'right', - wrap = false, - focusable = false, - children, - id, - className, - trigger, -}: TooltipProps) { - const generatedId = useId(); - const triggerId = id ?? generatedId; - const [open, setOpen] = useState(false); - const explicitOpen = useRef(false); - return ( - { - // A tap/keyboard focus isn't a hover. Synthetic mouse-leave events must not - // immediately dismiss it; outside press, blur and Escape still do. - if (!next && details.reason === 'trigger-hover' && explicitOpen.current) { - details.cancel(); - return; - } - if (!next) explicitOpen.current = false; - setOpen(next); - }} - > - : )} - className={['ol-tooltip-anchor', className].filter(Boolean).join(' ')} - delay={200} - closeOnClick={!focusable} - // A real button makes explanatory text available to touch and keyboard users, too. - onClick={ - focusable - ? () => { - explicitOpen.current = true; - setOpen(true); - } - : undefined - } - onBlur={() => { - explicitOpen.current = false; - }} - onFocus={ - focusable - ? (event) => { - // Re-entering by keyboard should work even after Escape dismissed a hover-only hint. - if (event.currentTarget.matches(':focus-visible')) { - explicitOpen.current = true; - setOpen(true); - } - } - : undefined - } - > - {children} - - - - - {content} - - - - - ); -} - -/** The shared explanatory-label pattern: dotted words, no extra help icon. */ -export function Hint({ - children, - content, - id, -}: { - children: ReactNode; - content: ReactNode; - id?: string; -}) { - return ( - - {children} - - ); -} +export * from '../ui/overlays/Tooltip'; diff --git a/openless-all/app/src/components/VocabSuggestionCard.tsx b/openless-all/app/src/components/VocabSuggestionCard.tsx index de328f939..fc2f3ee0b 100644 --- a/openless-all/app/src/components/VocabSuggestionCard.tsx +++ b/openless-all/app/src/components/VocabSuggestionCard.tsx @@ -1,200 +1 @@ -// "Remember this word?" card, popping up at the bottom-right of the screen. A card -// instead of a queue in the vocab page because suggestions matter at the moment of -// correction; bottom-right because the capsule's centered spot covers the line being -// edited. Per-item accept/reject only, no bulk accept: automatic collection measured -// ~4 of 5 wrong on real devices, so eyeballing each one is the only reliable filter. - -import { Icon } from './Icon'; -import { useEffect, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { acceptPendingCorrection, rejectPendingCorrection } from '../lib/ipc'; -import type { PendingCorrection } from '../lib/types'; - -interface VocabSuggestionCardProps { - suggestions: PendingCorrection[]; -} - -export function VocabSuggestionCard({ suggestions }: VocabSuggestionCardProps) { - const { t } = useTranslation(); - // Resolved items vanish from the card immediately — no waiting for a backend echo; - // a click must react. - const [resolved, setResolved] = useState>(new Set()); - const timerRef = useRef(null); - - // Each suggestion has a Core deadline; new suggestions do not extend old ones. - useEffect(() => { - const active = suggestions.filter((suggestion) => !resolved.has(suggestion.id)); - if (active.length === 0) return; - if (timerRef.current) clearTimeout(timerRef.current); - const earliest = Math.min(...active.map((s) => s.expiresAtMs)); - timerRef.current = window.setTimeout( - () => { - const expired = active.filter((s) => s.expiresAtMs <= Date.now()); - setResolved((previous) => new Set([...previous, ...expired.map((s) => s.id)])); - for (const suggestion of active) { - if (suggestion.expiresAtMs <= Date.now()) { - void rejectPendingCorrection(suggestion.id).catch(() => {}); - } - } - }, - Math.max(0, earliest - Date.now()), - ); - return () => { - if (timerRef.current) clearTimeout(timerRef.current); - }; - }, [suggestions, resolved]); - - const visible = suggestions.filter((s) => !resolved.has(s.id)); - if (visible.length === 0) return null; - - // Accept and reject share one optimistic update: hide locally first, restore on - // failure so the user can retry. - const resolve = async (id: string, commit: (id: string) => Promise) => { - setResolved((prev) => new Set(prev).add(id)); - try { - await commit(id); - } catch { - setResolved((prev) => { - const next = new Set(prev); - next.delete(id); - return next; - }); - } - }; - - return ( -
-
-
- {t('vocabCard.title')} -
- -
- {visible.map((s) => ( -
- - {s.pattern} - → - {s.replacement} - - void resolve(s.id, acceptPendingCorrection)} - /> - void resolve(s.id, rejectPendingCorrection)} - /> -
- ))} -
-
-
- ); -} - -/// Accept/reject. Size, colors, and SVG paths copied from the capsule's confirm/cancel -/// pair — the same gesture in one product shouldn't look like two. -function CardButton({ - kind, - label, - onClick, -}: { - kind: 'accept' | 'reject'; - label: string; - onClick: () => void; -}) { - return ( - - ); -} +export * from '../features/vocabulary-learning/VocabSuggestionCard'; diff --git a/openless-all/app/src/components/VoiceOrbStage.tsx b/openless-all/app/src/components/VoiceOrbStage.tsx index 9955e22c4..476660026 100644 --- a/openless-all/app/src/components/VoiceOrbStage.tsx +++ b/openless-all/app/src/components/VoiceOrbStage.tsx @@ -1,137 +1 @@ -import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; -import { useTranslation } from 'react-i18next'; -import { SiriGL } from './SiriGL'; -import { getCapsulePillMetrics } from '../lib/capsuleLayout'; -import type { CapsuleState } from '../lib/types'; -import type { OS } from './WindowChrome'; - -export interface VoiceOrbStageProps { - os: OS; - state: CapsuleState; - level: number; - /** Warming: the wave renders as a standby breathing form, ignoring the real level. See CapsulePayload.warming. */ - warming?: boolean; - /** Average warm→ready duration (ms), driving the predicted expand pace. See SiriGL warmupMs. */ - warmupMs?: number; - message?: string; -} - -/** - * Pure light stage (full siri-glsl clone, no chrome, no buttons, no backdrop): - * - recording: a rainbow spectral voice wave spans the stage, amplitude following - * the real mic level; - * - transcribing / polishing: the wave collapses from both ends toward the center - * while a fluid dot ring fades in and spins faster; - * - done / cancelled: speed falls back to standard, the six dots merge into one - * center circle, and the outer capsule-out fades it away; - * - error: frozen light + a glowing red line explaining why (the only text kept). - * Deliberately no underlay/dark vignette: on a white UI, weaker contrast beats a - * black occlusion. - */ -export function VoiceOrbStage({ - os, - state, - level, - warming, - warmupMs, - message, -}: VoiceOrbStageProps) { - const { t } = useTranslation(); - const metrics = useMemo(() => getCapsulePillMetrics(os), [os]); - - // done / cancelled / error freeze the last phase and fade out; no further switching. - const lastPhaseRef = useRef<'wave' | 'orb'>('wave'); - let phase = lastPhaseRef.current; - if (state === 'recording') phase = 'wave'; - else if (state === 'transcribing' || state === 'polishing') phase = 'orb'; - lastPhaseRef.current = phase; - const isOrb = phase === 'orb'; - - // Perf: unmount the wave's draw loop after its fade fully ends (.55s delay + .6s - // duration) so thinking doesn't run fragments every frame for an invisible canvas. - // Remounts immediately on returning to recording (the driver caches the compiled - // shader; rebuild is near-zero cost). - const [waveAlive, setWaveAlive] = useState(true); - useEffect(() => { - if (!isOrb) { - setWaveAlive(true); - return undefined; - } - const timer = setTimeout(() => setWaveAlive(false), 1300); - return () => clearTimeout(timer); - }, [isOrb]); - - return ( -
- {waveAlive && ( - - )} - {isOrb && ( - - )} - {state === 'error' && {message || t('capsule.error')}} -
- ); -} - -const errorGlowTextStyle: CSSProperties = { - position: 'absolute', - bottom: 24, - left: '50%', - transform: 'translateX(-50%)', - maxWidth: 400, - fontSize: 12, - fontWeight: 'var(--ol-font-weight-semibold)', - lineHeight: 1.4, - textAlign: 'center', - color: 'var(--ol-err)', - padding: '6px 12px', - background: 'var(--ol-capsule-pill-bg)', - border: '1px solid var(--ol-capsule-pill-border)', - borderRadius: 'var(--ol-r-lg)', - whiteSpace: 'nowrap', - overflow: 'hidden', - textOverflow: 'ellipsis', -}; +export { VoiceOrbStage, type VoiceOrbStageProps } from '../features/capsule/VoiceOrbStage'; diff --git a/openless-all/app/src/components/WindowChrome.tsx b/openless-all/app/src/components/WindowChrome.tsx index f3a748e35..df367d75a 100644 --- a/openless-all/app/src/components/WindowChrome.tsx +++ b/openless-all/app/src/components/WindowChrome.tsx @@ -1,89 +1,2 @@ -import { type CSSProperties, type ReactNode } from 'react'; - -export type OS = 'mac' | 'win' | 'android' | 'harmony'; - -export function detectOS(): OS { - if (import.meta.env?.VITE_OPENLESS_PLATFORM === 'harmony') return 'harmony'; - if (typeof navigator === 'undefined') return 'mac'; - const uaDataPlatform = - (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ?? - ''; - const hints = `${navigator.userAgent || ''} ${navigator.platform || ''} ${uaDataPlatform}`; - if (/Mac|iPhone|iPad|iPod/.test(hints)) return 'mac'; - if (/Android/i.test(hints)) return 'android'; - if (/Windows|Win32|Win64/.test(hints)) return 'win'; - return 'mac'; -} - -const MAC_TITLEBAR_HEIGHT = 44; -const MAC_SYSTEM_CONTROLS_RESERVED_WIDTH = 88; -const WIN_CONSOLE_RADIUS = 10; - -interface WindowChromeProps { - os?: OS; - title?: string; - children: ReactNode; - height?: number | string; -} - -export function WindowChrome({ os = 'mac', children, height = 800 }: WindowChromeProps) { - // Windows: with decorations:true the shell draws no radius/border/shadow/titlebar, - // avoiding overlap with the native window. - const shellRadius = - os === 'mac' ? 0 : os === 'win' || os === 'android' || os === 'harmony' ? 0 : 14; - const consoleRadius = os === 'mac' ? 20 : os === 'win' ? WIN_CONSOLE_RADIUS : 0; - const titlebarHeight = os === 'mac' ? MAC_TITLEBAR_HEIGHT : 0; - - const useSolidSurface = os === 'android' || os === 'harmony'; - - return ( -
- {os === 'mac' && ( -
- )} -
{children}
-
- ); -} +export { WindowChrome } from '../app/shell/WindowChrome'; +export { getRuntimeOS as detectOS, type OS } from '../runtime/environment'; diff --git a/openless-all/app/src/components/chat/LiveWaveform.tsx b/openless-all/app/src/components/chat/LiveWaveform.tsx deleted file mode 100644 index e57f1b9d0..000000000 --- a/openless-all/app/src/components/chat/LiveWaveform.tsx +++ /dev/null @@ -1,123 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useReducedMotion } from '../../lib/motion'; - -const BAR_WIDTH = 3; -const BAR_GAP = 3; -const SAMPLE_MS = 70; -const MIN_BAR = 2; - -function clampLevel(level: number): number { - return Number.isFinite(level) ? Math.max(0, Math.min(1, level)) : 0; -} - -/** - * Scrolling history of the real microphone level. Each bar is one sampled - * level (fast attack, slow release); nothing is synthesized while recording. - * `processing` replaces the history with a quiet travelling pulse. - */ -export function LiveWaveform({ - level, - processing = false, - label, -}: { - level: number; - processing?: boolean; - label: string; -}) { - const canvasRef = useRef(null); - const reducedMotion = useReducedMotion(); - const levelRef = useRef(0); - const processingRef = useRef(processing); - levelRef.current = clampLevel(level); - processingRef.current = processing; - - useEffect(() => { - const canvas = canvasRef.current; - const context = canvas?.getContext('2d'); - if (!canvas || !context) return; - let history: number[] = []; - let smoothed = 0; - let lastSample = performance.now(); - let width = 0; - let height = 0; - let color = ''; - let colorAge = 0; - let frame = 0; - - const resize = () => { - const rect = canvas.getBoundingClientRect(); - const ratio = window.devicePixelRatio || 1; - width = rect.width; - height = rect.height; - canvas.width = Math.max(1, Math.round(width * ratio)); - canvas.height = Math.max(1, Math.round(height * ratio)); - context.setTransform(ratio, 0, 0, ratio, 0, 0); - }; - resize(); - const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null; - observer?.observe(canvas); - - const bar = (x: number, amplitude: number, alpha: number) => { - const h = Math.max(MIN_BAR, amplitude * height * 0.92); - const y = (height - h) / 2; - context.globalAlpha = alpha; - context.beginPath(); - if (typeof context.roundRect === 'function') - context.roundRect(x, y, BAR_WIDTH, h, BAR_WIDTH / 2); - else context.rect(x, y, BAR_WIDTH, h); - context.fill(); - }; - - const draw = (now: number) => { - const step = BAR_WIDTH + BAR_GAP; - const capacity = Math.max(1, Math.ceil(width / step) + 1); - if (colorAge-- <= 0) { - color = getComputedStyle(canvas).color; - colorAge = 30; - } - context.clearRect(0, 0, width, height); - context.fillStyle = color; - - if (processingRef.current) { - smoothed = 0; - history = []; - for (let j = 0; j < capacity; j += 1) { - const wave = reducedMotion ? 0.5 : 0.5 + 0.5 * Math.sin(now / 240 - j * 0.45); - bar(width - BAR_WIDTH - j * step, 0.1 + 0.16 * wave, 0.35 + 0.35 * wave); - } - } else { - const target = levelRef.current; - smoothed += (target - smoothed) * (target > smoothed ? 0.6 : 0.2); - if (now - lastSample >= SAMPLE_MS) { - history.push(smoothed); - lastSample = now; - if (history.length > capacity) history = history.slice(-capacity); - } - const drift = reducedMotion ? 0 : Math.min(1, (now - lastSample) / SAMPLE_MS); - for (let j = 0; j < capacity; j += 1) { - const sample = history[history.length - 1 - j] ?? 0; - const amplitude = Math.min(1, Math.sqrt(sample) * 1.08); - const age = j / capacity; - bar(width - BAR_WIDTH - (j + drift) * step, amplitude, 1 - age * 0.65); - } - } - context.globalAlpha = 1; - frame = window.requestAnimationFrame(draw); - }; - frame = window.requestAnimationFrame(draw); - return () => { - window.cancelAnimationFrame(frame); - observer?.disconnect(); - }; - }, [reducedMotion]); - - return ( -
-
- ); -} diff --git a/openless-all/app/src/components/chat/avatars.tsx b/openless-all/app/src/components/chat/avatars.tsx deleted file mode 100644 index 236028e51..000000000 --- a/openless-all/app/src/components/chat/avatars.tsx +++ /dev/null @@ -1,175 +0,0 @@ -// avatars.tsx — thinking animation and avatars. -// -// · ThinkingOrb: the exact same implementation as the capsule's thinking state -// (SiriGL mode="orb", 6 white metaball dots weaving and rotating, thinking -// speed=1.5 matching Capsule.tsx). White dots need a dark backdrop — carried by the -// small dark stage (olchat-orb-stage) to contrast with the panel's off-white -// background. Falls back to a static white-dot ring when WebGL is unavailable. -// · StaticOrbDots: static white-dot ring for settled message avatars (no GL context — -// a live orb per message in long chats would hit the browser's WebGL context limit). -// · UserAvatar: when logged into GitHub (prefs.marketplaceDevLogin), shows the -// github.com/{login}.png avatar; falls back to the GitHub icon when logged out or -// on load failure. Used only by selection ask (QA). - -import { useEffect, useRef, useState } from 'react'; -import { ThinkingDots } from '../ThinkingDots'; -import { SiriGL, isWebGLAvailable } from '../SiriGL'; -import { subscribeOrbFrames } from './orbFeed'; -import { getSettings } from '../../lib/ipc/settings'; -import { isTauri } from '../../lib/ipc/shared'; -import { cn } from './lib/utils'; -import './chat.css'; - -/** Capsule-identical thinking animation (SiriGL orb on a dark stage). */ -export function ThinkingOrb({ size = 56, className }: { size?: number; className?: string }) { - return ( - - {isWebGLAvailable() ? ( - - ) : ( - - )} - - ); -} - -/** - * Capsule thinking animation as an avatar: the rotating orb, identical to the capsule - * (every assistant message avatar spins). No per-avatar GL context — each frame is - * mirrored from the shared render source (orbFeed, the panel's single GL context) to - * a small 2D canvas via drawImage. Falls back to a ThinkingDots ring without WebGL. - */ -export function OrbAvatar({ size = 32 }: { size?: number }) { - const canvasRef = useRef(null); - const [unavailable, setUnavailable] = useState(false); - - useEffect(() => { - const target = canvasRef.current; - if (!target) return undefined; - const dpr = Math.min(window.devicePixelRatio || 1, 2); - target.width = Math.round(size * dpr); - target.height = Math.round(size * dpr); - const ctx = target.getContext('2d'); - if (!ctx) { - setUnavailable(true); - return undefined; - } - let unsubscribe: (() => void) | null = null; - let observer: IntersectionObserver | undefined; - const draw = (source: HTMLCanvasElement) => { - // Center-crop and scale (the source is composed for the capsule; the halo takes - // only ~1/3 of the frame — crop the outer padding so the ring fills the avatar, - // animation unchanged). - const crop = 0.62; - const sw = source.width * crop; - const sh = source.height * crop; - const sx = (source.width - sw) / 2; - const sy = (source.height - sh) / 2; - ctx.clearRect(0, 0, target.width, target.height); - ctx.drawImage(source, sx, sy, sw, sh, 0, 0, target.width, target.height); - }; - const visible = (show: boolean) => { - if (!show) { - unsubscribe?.(); - unsubscribe = null; - return; - } - if (unsubscribe) return; - unsubscribe = subscribeOrbFrames(draw); - if (!unsubscribe) { - observer?.disconnect(); - target.width = 0; - target.height = 0; - setUnavailable(true); - } - }; - if (typeof IntersectionObserver === 'undefined') visible(true); - else { - observer = new IntersectionObserver(([entry]) => visible(entry.isIntersecting)); - observer.observe(target); - } - return () => { - observer?.disconnect(); - unsubscribe?.(); - target.width = 0; - target.height = 0; - }; - }, [size]); - - if (unavailable) { - return ; - } - return ( - - ); -} - -/** - * Current GitHub login (Marketplace upload identity, written to prefs on sign-in in - * Settings). Re-fetches when refreshKey changes — the panel window is a persistent - * webview (reused across hide/show), so a new-session signal drives the refresh to - * track login changes. - */ -export function useGithubLogin(refreshKey?: string | number): string { - const [login, setLogin] = useState(''); - useEffect(() => { - if (!isTauri) return; - let cancelled = false; - getSettings() - .then((prefs) => { - if (!cancelled) setLogin((prefs.marketplaceDevLogin ?? '').trim()); - }) - .catch(() => { - /* Not logged in / read failed: keep the icon fallback. */ - }); - return () => { - cancelled = true; - }; - }, [refreshKey]); - return login; -} - -/** User avatar (QA only): GitHub avatar image, or the GitHub icon when logged out. */ -export function UserAvatar({ login }: { login: string }) { - const [broken, setBroken] = useState(false); - useEffect(() => setBroken(false), [login]); - const showImage = login.length > 0 && !broken; - return showImage ? ( - setBroken(true)} - /> - ) : ( - - - - ); -} - -function GithubMark() { - return ( - - - - ); -} diff --git a/openless-all/app/src/components/chat/lifecycle.ts b/openless-all/app/src/components/chat/lifecycle.ts deleted file mode 100644 index ddc422f4e..000000000 --- a/openless-all/app/src/components/chat/lifecycle.ts +++ /dev/null @@ -1,54 +0,0 @@ -// lifecycle.ts — appear/disappear animation signals for the chat panels (qa / -// less-computer). -// -// The floating window is a persistent webview (reused across hide/show, never -// remounted), so the CSS enter animation plays only on first mount — every later -// wake-up would pop in abruptly. The backend emits lifecycle events on the show/hide -// paths: -// · `chat-panel:shown` → enterEpoch+1 (used as a key to replay olchat-shell-in) -// · `chat-panel:closing` → closing=true (adds olchat-shell-out for the exit; the -// backend actually hides 240ms later; a shown during that window resets it) -// Browser preview (non-Tauri) has no such events; keep the first-mount enter animation. - -import { useEffect, useState } from 'react'; -import { isTauri } from '../../lib/ipc/shared'; - -export function useChatPanelLifecycle(): { enterEpoch: number; closing: boolean } { - const [enterEpoch, setEnterEpoch] = useState(0); - const [closing, setClosing] = useState(false); - - useEffect(() => { - if (!isTauri) return; - let unShown: (() => void) | undefined; - let unClosing: (() => void) | undefined; - let cancelled = false; - (async () => { - try { - const { listen } = await import('@tauri-apps/api/event'); - const shownHandle = await listen('chat-panel:shown', () => { - setClosing(false); - setEnterEpoch((epoch) => epoch + 1); - }); - const closingHandle = await listen('chat-panel:closing', () => { - setClosing(true); - }); - if (cancelled) { - shownHandle(); - closingHandle(); - } else { - unShown = shownHandle; - unClosing = closingHandle; - } - } catch (error) { - console.error('[chat-panel] lifecycle listener setup failed', error); - } - })(); - return () => { - cancelled = true; - unShown?.(); - unClosing?.(); - }; - }, []); - - return { enterEpoch, closing }; -} diff --git a/openless-all/app/src/components/chat/markdown.tsx b/openless-all/app/src/components/chat/markdown.tsx index 084a5fe97..2cfa3092b 100644 --- a/openless-all/app/src/components/chat/markdown.tsx +++ b/openless-all/app/src/components/chat/markdown.tsx @@ -1,68 +1 @@ -// markdown.tsx — assistant markdown body (deduped merge of QaPanel/LessComputerPanel's -// AssistantText): frame-throttled, falls back to plain text on render failure, with -// DOMPurify as a final sanitize pass; new streaming glyphs resolve from blur in 90ms. -// Styled by .olchat-answer (chat.css). - -import { useLayoutEffect, useMemo, useRef } from 'react'; -import DOMPurify from 'dompurify'; -import { useRafThrottle } from '../../lib/useRafThrottle'; -import { renderQaMarkdown, renderQaPlainText } from '../../lib/qaMarkdown'; -import { useReducedMotion } from '../../lib/motion'; -import { - keepProseTailsTogether, - mountTextReveals, - planTextReveal, - type TextRevealState, -} from '../../lib/assistantText'; -import './chat.css'; - -interface AssistantMarkdownProps { - markdown: string; - streaming?: boolean; -} - -export function AssistantMarkdown({ markdown, streaming = false }: AssistantMarkdownProps) { - // Frame-throttled: full parse + DOMPurify per token while streaming is O(n²), and - // long replies get progressively jankier. - const throttled = useRafThrottle(markdown); - // Completion/cancellation must flush the final answer even in a background webview. - const content = streaming ? throttled : markdown; - const reducedMotion = useReducedMotion(); - const body = useRef(null); - const reveal = useRef({ text: '', glyphs: [] }); - const html = useMemo(() => { - let rendered: string; - try { - rendered = renderQaMarkdown(content); - } catch (error) { - console.error('[chat] markdown render failed', error); - rendered = renderQaPlainText(String(content ?? '')); - } - // Extra sanitize pass: qaMarkdown already escapes raw HTML tokens; DOMPurify adds - // one more line of defense. - return DOMPurify.sanitize(rendered, { ADD_ATTR: ['target', 'rel'] }); - }, [content]); - - useLayoutEffect(() => { - const element = body.current; - if (!element) return; - // This subtree is deliberately DOM-owned. Never decorate unsanitized markdown. - element.innerHTML = html; - keepProseTailsTogether(element); - const now = performance.now(); - reveal.current = planTextReveal( - reveal.current, - element.textContent ?? '', - now, - streaming && !reducedMotion, - ); - return mountTextReveals(element, reveal.current.glyphs, now); - }, [html, streaming, reducedMotion]); - - return ( -
-
- {streaming && } -
- ); -} +export * from '../../features/qa/chat/markdown'; diff --git a/openless-all/app/src/components/chat/orbFeed.test.ts b/openless-all/app/src/components/chat/orbFeed.test.ts deleted file mode 100644 index 5d1405e47..000000000 --- a/openless-all/app/src/components/chat/orbFeed.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -function assertEqual(actual: unknown, expected: unknown, message = 'values differ') { - if (actual !== expected) throw new Error(`${message}: ${String(actual)} !== ${String(expected)}`); -} -function assertOk(value: unknown, message = 'expected a truthy value'): asserts value { - if (!value) throw new Error(message); -} -import { subscribeOrbFrames } from './orbFeed'; -import { isWebGLAvailable } from '../SiriGL'; - -type Failure = 'shader' | 'program' | 'link' | 'buffer' | 'none'; -let failure: Failure = 'none'; -let lost = 0; -let deletedShaders = 0; -let deletedPrograms = 0; -let deletedBuffers = 0; -let contexts = 0; -const frames = new Map(); -const listeners = new Map(); -let nextFrame = 0; -const gl = { - VERTEX_SHADER: 1, - FRAGMENT_SHADER: 2, - COMPILE_STATUS: 3, - LINK_STATUS: 4, - ARRAY_BUFFER: 5, - STATIC_DRAW: 6, - FLOAT: 7, - TRIANGLES: 8, - createShader: () => ({}), - shaderSource() {}, - compileShader() {}, - getShaderParameter: () => failure !== 'shader', - getShaderInfoLog: () => 'expected fixture failure', - deleteShader: () => deletedShaders++, - createProgram: () => (failure === 'program' ? null : {}), - attachShader() {}, - linkProgram() {}, - getProgramParameter: () => failure !== 'link', - getProgramInfoLog: () => 'expected fixture failure', - deleteProgram: () => deletedPrograms++, - useProgram() {}, - createBuffer: () => (failure === 'buffer' ? null : {}), - bindBuffer() {}, - bufferData() {}, - getAttribLocation: () => 0, - enableVertexAttribArray() {}, - vertexAttribPointer() {}, - getUniformLocation: () => null, - viewport() {}, - uniform2f() {}, - uniform1f() {}, - drawArrays() {}, - deleteBuffer: () => deletedBuffers++, - getExtension: () => ({ loseContext: () => lost++ }), -}; -const original = Object.getOwnPropertyDescriptor(globalThis, 'document'); -const originalRaf = globalThis.requestAnimationFrame; -const originalCancel = globalThis.cancelAnimationFrame; -const error = console.error; -const doc = { - hidden: false, - createElement: () => ({ - width: 0, - height: 0, - getContext: () => { - contexts++; - return gl; - }, - }), - addEventListener: (name: string, callback: EventListener) => listeners.set(name, callback), - removeEventListener: (name: string) => listeners.delete(name), -}; -Object.defineProperty(globalThis, 'document', { value: doc, configurable: true }); -globalThis.requestAnimationFrame = (callback) => { - const id = ++nextFrame; - frames.set(id, callback); - return id; -}; -globalThis.cancelAnimationFrame = (id) => { - frames.delete(id); -}; -console.error = () => {}; -try { - assertEqual(isWebGLAvailable(), true); - assertEqual(lost, 1, 'the capability probe releases its temporary GPU context'); - assertEqual(isWebGLAvailable(), true); - assertEqual(contexts, 1, 'availability remains a one-shot probe'); - for (const stage of ['shader', 'program', 'link', 'buffer'] as const) { - failure = stage; - const before = lost; - assertEqual( - subscribeOrbFrames(() => {}), - null, - stage, - ); - assertEqual(lost, before + 1, `${stage}: failed initialization releases its context`); - assertEqual(frames.size, 0, `${stage}: no orphan animation loop`); - } - failure = 'none'; - const before = lost; - const stop = subscribeOrbFrames(() => {}); - assertOk(stop); - assertEqual(frames.size, 1); - doc.hidden = true; - listeners.get('visibilitychange')!(new Event('visibilitychange')); - assertEqual(frames.size, 0, 'hidden windows stop drawing'); - doc.hidden = false; - listeners.get('visibilitychange')!(new Event('visibilitychange')); - assertEqual(frames.size, 1, 'resume creates exactly one RAF chain'); - stop(); - stop(); - assertEqual(lost, before + 1, 'last unsubscribe disposes exactly once'); - assertEqual(frames.size, 0); - assertEqual(listeners.size, 0); - assertOk(deletedShaders >= 2 && deletedPrograms >= 1 && deletedBuffers >= 1); - let selfStop: (() => void) | null = null; - selfStop = subscribeOrbFrames(() => selfStop?.()); - const [id, callback] = [...frames.entries()][0]; - frames.delete(id); - callback(performance.now()); - assertEqual(frames.size, 0, 'unsubscribe during a frame cannot resurrect the disposed loop'); - console.log('WebGL probe, failure cleanup, visibility and final subscription lifecycle passed'); -} finally { - console.error = error; - globalThis.requestAnimationFrame = originalRaf; - globalThis.cancelAnimationFrame = originalCancel; - if (original) Object.defineProperty(globalThis, 'document', original); - else Reflect.deleteProperty(globalThis, 'document'); -} diff --git a/openless-all/app/src/components/chat/orbFeed.ts b/openless-all/app/src/components/chat/orbFeed.ts deleted file mode 100644 index 3a5aaceb5..000000000 --- a/openless-all/app/src/components/chat/orbFeed.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { releaseWebGL } from '../../lib/webglResources'; -// orbFeed.ts — shared render source for the capsule's thinking orb. -// -// Requirement: every assistant message avatar shows the rotating capsule thinking -// animation (SiriGL orb, 6 white metaball dots weaving). One SiriGL per avatar means -// one WebGL context per avatar — the browser caps ~16, so long chats would blow up. -// -// Approach: module-level singleton. The first subscriber creates an offscreen canvas -// with the single GL context running the orb loop (shader identical to SiriGL, -// speed=1.5 matching capsule thinking). After each frame it synchronously notifies -// all subscribers, who mirror the source via 2D drawImage onto their own small -// canvas (same-task copy, no preserveDrawingBuffer needed). When the last subscriber -// leaves, stop the loop and release GL resources. With the window hidden, rAF is -// suspended by WebKit/Chromium and the loop naturally pauses. - -import { ORB_FRAGMENT_SRC, VERTEX_SRC } from '../SiriGL'; - -type FrameSubscriber = (source: HTMLCanvasElement) => void; - -/** Source resolution: avatars are at most ~40px@2x; 96 is plenty sharp at negligible render cost. */ -const SOURCE_SIZE = 96; -/** Rotation speed matching the capsule thinking state (Capsule.tsx: transcribing/polishing → speed 1.5). */ -const SPEED = 1.5; - -interface Feed { - canvas: HTMLCanvasElement; - dispose: () => void; -} - -const subscribers = new Set(); -let feed: Feed | null = null; - -function startFeed(): Feed | null { - const canvas = document.createElement('canvas'); - canvas.width = SOURCE_SIZE; - canvas.height = SOURCE_SIZE; - const gl = canvas.getContext('webgl', { - alpha: true, - premultipliedAlpha: true, - antialias: false, - }); - if (!gl) return null; - - const compile = (type: number, src: string): WebGLShader | null => { - const shader = gl.createShader(type); - if (!shader) return null; - gl.shaderSource(shader, src); - gl.compileShader(shader); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.error('[orbFeed] shader compile failed:', gl.getShaderInfoLog(shader)); - gl.deleteShader(shader); - return null; - } - return shader; - }; - - const vs = compile(gl.VERTEX_SHADER, VERTEX_SRC); - const fs = compile(gl.FRAGMENT_SHADER, ORB_FRAGMENT_SRC); - if (!vs || !fs) { - releaseWebGL(gl, { shaders: [vs, fs] }); - return null; - } - const program = gl.createProgram(); - if (!program) { - releaseWebGL(gl, { shaders: [vs, fs] }); - return null; - } - gl.attachShader(program, vs); - gl.attachShader(program, fs); - gl.linkProgram(program); - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - console.error('[orbFeed] program link failed:', gl.getProgramInfoLog(program)); - releaseWebGL(gl, { program, shaders: [vs, fs] }); - return null; - } - gl.useProgram(program); - - const buffer = gl.createBuffer(); - if (!buffer) { - releaseWebGL(gl, { program, shaders: [vs, fs] }); - return null; - } - gl.bindBuffer(gl.ARRAY_BUFFER, buffer); - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); - const aPos = gl.getAttribLocation(program, 'aPos'); - gl.enableVertexAttribArray(aPos); - gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0); - - const uResolution = gl.getUniformLocation(program, 'iResolution'); - const uTime = gl.getUniformLocation(program, 'iTime'); - const uGather = gl.getUniformLocation(program, 'uGather'); - gl.viewport(0, 0, SOURCE_SIZE, SOURCE_SIZE); - - let shaderTime = 0; - let raf = 0; - let last = performance.now(); - let disposed = false; - - const frame = (now: number) => { - raf = 0; - if (disposed || document.hidden) return; - const dt = Math.min(0.05, (now - last) / 1000); - last = now; - shaderTime += dt * SPEED; - gl.uniform2f(uResolution, SOURCE_SIZE, SOURCE_SIZE); - gl.uniform1f(uTime, shaderTime); - // Avatar form stays spread out and rotating (no entrance gather: mirror targets - // mount/unmount anytime). - if (uGather) gl.uniform1f(uGather, 0); - gl.drawArrays(gl.TRIANGLES, 0, 3); - // Notify subscribers to drawImage within the same task — the WebGL frame stays - // valid until this task ends. - for (const cb of subscribers) cb(canvas); - if (!disposed) raf = requestAnimationFrame(frame); - }; - const visibility = () => { - cancelAnimationFrame(raf); - raf = 0; - if (!document.hidden && !disposed) { - last = performance.now(); - raf = requestAnimationFrame(frame); - } - }; - document.addEventListener('visibilitychange', visibility); - visibility(); - - return { - canvas, - dispose() { - disposed = true; - document.removeEventListener('visibilitychange', visibility); - cancelAnimationFrame(raf); - releaseWebGL(gl, { buffer, program, shaders: [vs, fs] }); - canvas.width = 0; - canvas.height = 0; - }, - }; -} - -/** - * Subscribe to the shared orb: called after each frame (arg is the source canvas; - * copy synchronously via drawImage). Returns an unsubscribe function, or null when - * GL is unavailable (caller degrades on its own). - */ -export function subscribeOrbFrames(cb: FrameSubscriber): (() => void) | null { - if (!feed) { - feed = startFeed(); - if (!feed) return null; - } - subscribers.add(cb); - return () => { - subscribers.delete(cb); - if (subscribers.size === 0 && feed) { - feed.dispose(); - feed = null; - } - }; -} diff --git a/openless-all/app/src/components/ui/GitHubActivity.tsx b/openless-all/app/src/components/ui/GitHubActivity.tsx new file mode 100644 index 000000000..ea48d57eb --- /dev/null +++ b/openless-all/app/src/components/ui/GitHubActivity.tsx @@ -0,0 +1,2 @@ +export { default } from '../../ui/controls/GitHubActivity'; +export * from '../../ui/controls/GitHubActivity'; diff --git a/openless-all/app/src/components/ui/Modal.tsx b/openless-all/app/src/components/ui/Modal.tsx index 2e4c161e2..c4c421baa 100644 --- a/openless-all/app/src/components/ui/Modal.tsx +++ b/openless-all/app/src/components/ui/Modal.tsx @@ -1,195 +1 @@ -// Modal — centered dialog: backdrop + card. Marketplace details / upload / my -// listings / GitHub login all share this popup logic instead of each writing its own. -// -// Shared opacity/transform motion preserves the current pose when interrupted. - -import { useEffect, useLayoutEffect, useRef, type CSSProperties, type ReactNode } from 'react'; -import { createPortal } from 'react-dom'; -import { useOverlayMotion } from '../../lib/motion'; -import { useExitMount } from '../../lib/useExitMount'; - -interface ModalProps { - children: ReactNode; - onClose: () => void; - /** Default 50; pass a larger value when stacking (e.g. login above "my listings"). */ - zIndex?: number; - /** Card width, default 'min(560px, 100%)'. */ - width?: string; - /** Dialogs with a fixed title/footer can let the inner content area scroll. */ - style?: CSSProperties; - /** true plays the exit animation; the caller gates unmount timing with - * useExitMount, unmounting after the animation finishes. */ - closing?: boolean; - /** Lets the host window customize overlay/card look (e.g. a rounded floating window needs a rounded overlay). */ - overlayClassName?: string; - labelledBy?: string; - /** `pop` enlarges, overshoots once, then settles. Other dialogs keep the card fade. */ - motionVariant?: 'card' | 'pop'; -} - -const FOCUSABLE = - 'a[href], button:not([disabled]), textarea:not([disabled]), select:not([disabled]), input:not([disabled]):not([type="hidden"]), [tabindex]:not([tabindex="-1"])'; - -// Only the top-most dialog keeps Tab cycling inside itself. -const openModals: symbol[] = []; - -function focusableWithin(root: HTMLElement): HTMLElement[] { - return Array.from(root.querySelectorAll(FOCUSABLE)).filter( - (element) => element.getClientRects().length > 0, - ); -} - -export function Modal({ - children, - onClose, - zIndex = 50, - width = 'min(560px, 100%)', - style, - closing = false, - overlayClassName, - labelledBy, - motionVariant = 'card', -}: ModalProps) { - const cardRef = useRef(null); - const overlayRef = useRef(null); - const closeRef = useRef(onClose); - closeRef.current = onClose; - useOverlayMotion(overlayRef, closing, 'backdrop'); - useOverlayMotion(cardRef, closing, motionVariant); - useLayoutEffect(() => { - if (cardRef.current) cardRef.current.inert = closing; - }, [closing]); - - useEffect(() => { - const id = Symbol('modal'); - openModals.push(id); - const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; - const card = cardRef.current; - if (card && !card.contains(document.activeElement)) card.focus({ preventScroll: true }); - const onKeyDown = (event: KeyboardEvent) => { - if (event.defaultPrevented || !card || openModals[openModals.length - 1] !== id) return; - if (event.key === 'Escape' && !event.isComposing && !card.inert) { - event.preventDefault(); - event.stopPropagation(); - closeRef.current(); - return; - } - if (event.key !== 'Tab') return; - if (card.inert) { - event.preventDefault(); - return; - } - const items = focusableWithin(card); - const active = document.activeElement; - if (items.length === 0) { - event.preventDefault(); - card.focus({ preventScroll: true }); - return; - } - const first = items[0]; - const last = items[items.length - 1]; - if (event.shiftKey) { - if (active === first || active === card || !card.contains(active)) { - event.preventDefault(); - last.focus(); - } - } else if (active === last || !card.contains(active)) { - event.preventDefault(); - first.focus(); - } - }; - document.addEventListener('keydown', onKeyDown); - return () => { - document.removeEventListener('keydown', onKeyDown); - const index = openModals.indexOf(id); - if (index >= 0) openModals.splice(index, 1); - if (previous?.isConnected) previous.focus({ preventScroll: true }); - }; - }, []); - - // Portal to document.body: dialogs often trigger from inside panels (settings / - // marketplace), and the window chrome (WindowChrome) and page containers carry a - // temporary transforms while animating, creating a containing block — rendered in - // place, the backdrop's `position: fixed` would anchor to that ancestor instead of - // the viewport, covering only the triggering panel (e.g. GitHub login floating over - // a still-bright settings page). Portaled out, fixed anchors to the viewport and - // the overlay covers the whole window. Same approach as Tooltip / SelectLite. - return createPortal( -
-
e.stopPropagation()} - style={{ - width, - maxHeight: '85vh', - overflow: 'auto', - borderRadius: 'var(--ol-dialog-radius)', - background: 'var(--ol-surface-raised)', - border: 0, - boxShadow: 'var(--ol-dialog-shadow)', - padding: 24, - outline: 'none', - ...style, - }} - > - {children} -
-
, - document.body, - ); -} - -/** Retain the last render closure (including its data) until exit completes. */ -export function ExitPresence({ - open, - render, -}: { - open: boolean; - render: (closing: boolean) => ReactNode; -}) { - const presence = useExitMount(open); - const previous = useRef(null); - const content = open ? render : previous.current; - useLayoutEffect(() => { - if (open) previous.current = render; - else if (!presence.mounted) previous.current = null; - }); - if (!presence.mounted || !content) return null; - return <>{content(presence.closing)}; -} - -/** Preserve the last visible content while its non-interactive exit finishes. */ -export function PresenceModal({ - open, - render, - ...props -}: Omit & { open: boolean; render: () => ReactNode }) { - return ( - ( - - {render()} - - )} - /> - ); -} +export * from '../../ui/overlays/Modal'; diff --git a/openless-all/app/src/components/ui/Row.tsx b/openless-all/app/src/components/ui/Row.tsx index 18c2eec23..0a362f466 100644 --- a/openless-all/app/src/components/ui/Row.tsx +++ b/openless-all/app/src/components/ui/Row.tsx @@ -1,59 +1,18 @@ -// Row — two-column row used in the Settings modal sub-sections. - import type { ReactNode } from 'react'; -import { useLayoutStack, useConservativeLayout } from '../../lib/useMobileLayout'; +import { SettingRow } from '../../ui/controls/SettingRow'; -interface RowProps { +export function Row({ + label, + desc, + children, +}: { label: string; desc?: string; children: ReactNode; -} - -export function Row({ label, desc, children }: RowProps) { - const baseLayoutStack = useLayoutStack(); - const conservative = useConservativeLayout(); - const stackLayout = baseLayoutStack || conservative; +}) { return ( -
-
-
- {label} -
- {desc && ( -
- {desc} -
- )} -
-
- {children} -
-
+ + {children} + ); } diff --git a/openless-all/app/src/components/ui/Segmented.tsx b/openless-all/app/src/components/ui/Segmented.tsx index 4dcc5775a..de9720a8f 100644 --- a/openless-all/app/src/components/ui/Segmented.tsx +++ b/openless-all/app/src/components/ui/Segmented.tsx @@ -1,65 +1 @@ -import { useRef } from 'react'; -import { useSelectionMotion } from '../../lib/motion'; - -export interface SegmentedOption { - value: T; - label: string; - title?: string; -} - -/** The one segmented control used across Settings: a white track with the controls' - * hairline, and a neutral chip that slides under the selected option. */ -export function Segmented({ - options, - value, - onChange, - label, - disabled = false, - className, - indicatorClassName, -}: { - options: SegmentedOption[]; - value: T; - onChange: (value: T) => void; - label: string; - disabled?: boolean; - className?: string; - /** Extra hook for callers whose tests address the sliding chip directly. */ - indicatorClassName?: string; -}) { - const trackRef = useRef(null); - const indicatorRef = useRef(null); - useSelectionMotion(trackRef, indicatorRef, value); - return ( -
- - {options.map((option) => ( - - ))} -
- ); -} +export * from '../../ui/controls/Segmented'; diff --git a/openless-all/app/src/components/ui/Select.css b/openless-all/app/src/components/ui/Select.css index 497c87998..d77f3a057 100644 --- a/openless-all/app/src/components/ui/Select.css +++ b/openless-all/app/src/components/ui/Select.css @@ -1,165 +1 @@ -.ol-select-trigger { - display: inline-flex; - align-items: center; - justify-content: space-between; - gap: 8px; - height: 32px; - min-width: 160px; - max-width: 100%; - padding: 0 10px; - border: 0.5px solid transparent; - border-radius: var(--ol-control-radius); - background: var(--ol-select-trigger-bg); - color: var(--ol-ink); - font: 12.5px var(--ol-font-sans); - text-align: start; - cursor: default; -} -.ol-select-trigger:focus-visible { - outline: 2px solid var(--ol-blue); - outline-offset: 2px; -} -html[data-ol-input='pointer'] .ol-select-trigger:focus-visible { - outline: none; -} -.ol-select-trigger[data-disabled] { - opacity: 0.5; - cursor: not-allowed; -} -.ol-select-value { - flex: 1; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.ol-select-positioner { - z-index: 9999; -} -.ol-select-popup { - box-sizing: border-box; - display: flex; - flex-direction: column; - zoom: var(--ol-interface-scale, 1); - width: calc(var(--anchor-width, 160px) / var(--ol-interface-scale, 1)); - max-width: calc(var(--available-width, 100vw) / var(--ol-interface-scale, 1)); - max-height: calc(var(--available-height, 100vh) / var(--ol-interface-scale, 1)); - padding: 4px; - border: 0; - border-radius: var(--ol-r-md); - background: var(--ol-select-popover-bg); - color: var(--ol-ink); - box-shadow: - inset 0 0 0 0.5px var(--ol-select-popover-border), - var(--ol-select-popover-shadow); - backdrop-filter: blur(20px) saturate(180%); - -webkit-backdrop-filter: blur(20px) saturate(180%); - font: 12.5px var(--ol-font-sans); - outline: none; - transform-origin: var(--transform-origin); - transition: - opacity 140ms ease-out, - transform 140ms var(--ol-motion-quick); -} -.ol-select-popup[data-starting-style], -.ol-select-popup[data-ending-style] { - opacity: 0; - transform: scale(0.98); -} -.ol-select-list { - /* Bound the first measurement too: positioning variables do not exist until - Base UI measures the popup. An initially unbounded long list flips upward. */ - min-height: 0; - max-height: min( - 280px, - calc(var(--available-height, 100vh) / var(--ol-interface-scale, 1) - 10px) - ); - overflow-y: auto; - overscroll-behavior: contain; -} -.ol-select-item { - display: grid; - grid-template-columns: minmax(0, 1fr) auto 12px; - align-items: center; - gap: 8px; - padding: 7px 10px; - border-radius: var(--ol-r-sm); - font-weight: var(--ol-font-weight-medium); - outline: none; - cursor: default; - user-select: none; -} -.ol-select-item > :first-child { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.ol-select-item[data-highlighted] { - background: var(--ol-select-option-hover-bg); -} -.ol-select-item[data-selected] { - color: var(--ol-choice-active-ink); - font-weight: var(--ol-font-weight-semibold); -} -.ol-select-check { - display: flex; - grid-column: 3; -} -.ol-select-trailing { - display: flex; - align-items: center; - grid-column: 2; -} -.ol-select-item[data-disabled] { - opacity: 0.45; - cursor: not-allowed; -} -.ol-shortcut-popup { - width: 320px; - padding: 10px; -} -.ol-shortcut-popup .ol-shortcut-recording { - border: 0; - background: transparent; -} -.ol-select-search { - flex-shrink: 0; - display: flex; - align-items: center; - gap: 7px; - margin: 1px 1px 4px; - padding: 0 9px; - min-height: 34px; - border: 0.5px solid var(--ol-line-strong); - border-radius: var(--ol-control-radius); - background: var(--ol-select-trigger-bg); -} -.ol-select-search input { - flex: 1; - min-width: 0; - border: 0; - outline: 0; - background: transparent; - color: inherit; - font: inherit; -} -.ol-select-empty { - padding: 18px 10px; - color: var(--ol-ink-4); - text-align: center; -} -.ol-select-empty:empty { - display: none; -} -@media (prefers-reduced-motion: reduce) { - .ol-select-popup { - transition: none; - } -} -@media (prefers-reduced-transparency: reduce), (prefers-contrast: more) { - .ol-select-popup { - background: var(--ol-surface); - backdrop-filter: none; - -webkit-backdrop-filter: none; - } -} +@import '../../ui/styles/select.css'; diff --git a/openless-all/app/src/components/ui/Select.tsx b/openless-all/app/src/components/ui/Select.tsx index c42e364d5..c6d416933 100644 --- a/openless-all/app/src/components/ui/Select.tsx +++ b/openless-all/app/src/components/ui/Select.tsx @@ -1,89 +1 @@ -import { Select as BaseSelect } from '@base-ui/react/select'; -import type { CSSProperties, ReactNode } from 'react'; -import { Icon } from '../Icon'; - -interface SelectProps { - value: string; - onChange: (value: string) => void; - options: readonly { value: string; label: string; disabled?: boolean; trailing?: ReactNode }[]; - ariaLabel?: string; - disabled?: boolean; - placeholder?: string; - style?: CSSProperties; - onOpenChange?: (open: boolean) => void; - open?: boolean; - side?: 'top' | 'bottom'; - popupStyle?: CSSProperties; - popupClassName?: string; -} - -/** Standard Base UI Select; keyboard navigation, typeahead and focus return stay upstream. */ -export function Select({ - value, - onChange, - options, - ariaLabel, - disabled, - placeholder, - style, - onOpenChange, - open, - side = 'bottom', - popupStyle, - popupClassName, -}: SelectProps) { - return ( - { - if (next !== null) onChange(next); - }} - > - - - - - - - - - - - {options.map((option) => ( - - {option.label} - {option.trailing && {option.trailing}} - - - - - ))} - - - - - - ); -} +export * from '../../ui/controls/Select'; diff --git a/openless-all/app/src/components/ui/SelectLite.tsx b/openless-all/app/src/components/ui/SelectLite.tsx index 26d97003a..5e0a257e3 100644 --- a/openless-all/app/src/components/ui/SelectLite.tsx +++ b/openless-all/app/src/components/ui/SelectLite.tsx @@ -1,230 +1 @@ -// Compatibility facade: every dropdown uses Base UI rather than maintaining a -// second positioning, keyboard, focus, scroll and exit-animation implementation. -import { - useCallback, - useEffect, - useMemo, - useRef, - useState, - type CSSProperties, - type ReactNode, -} from 'react'; -import { Combobox } from '@base-ui/react/combobox'; -import { Icon } from '../Icon'; -import { Select } from './Select'; - -export interface SelectOption { - value: string; - label: string; - disabled?: boolean; - /** Stays visible during search, e.g. a custom-input entry. */ - alwaysVisible?: boolean; - trailing?: ReactNode; -} - -interface SelectLiteProps { - value: string; - onChange: (value: string) => void; - options: SelectOption[]; - placeholder?: string; - disabled?: boolean; - style?: CSSProperties; - ariaLabel?: string; - onOpenChange?: (open: boolean) => void; - open?: boolean; - side?: 'top' | 'bottom'; - popupStyle?: CSSProperties; - popupClassName?: string; - searchable?: boolean; - searchPlaceholder?: string; - emptyMessage?: string; -} - -export function SelectLite({ - value, - onChange, - options, - placeholder, - disabled, - style, - ariaLabel, - onOpenChange, - open: controlledOpen, - side = 'bottom', - popupStyle, - popupClassName, - searchable = false, - searchPlaceholder = 'Search…', - emptyMessage = 'No matching options', -}: SelectLiteProps) { - const open = useRef(false); - const onOpenChangeRef = useRef(onOpenChange); - onOpenChangeRef.current = onOpenChange; - const handleOpenChange = useCallback((next: boolean) => { - open.current = next; - onOpenChangeRef.current?.(next); - }, []); - useEffect( - () => () => { - // In particular, release microphone metering when its settings page is left. - if (open.current) onOpenChangeRef.current?.(false); - }, - [], - ); - - if (searchable) { - return ( - - ); - } - return ( - setOrigin(event.currentTarget.value)} + placeholder="https://sync.example.com/" + disabled={working} + style={inputStyle} + /> + + + + {t('cloudSyncE2ee.customServerSave')} + + {notice && ( +

{t(`cloudSyncE2ee.${notice.key}`)}

+ )} +
+ + ); +} + +export function CloudSyncSection() { + const { t, i18n } = useTranslation(); + const { prefs, updatePrefs, refresh } = useHotkeySettings(); + const [status, setStatus] = useState(null); + const [authSignedIn, setAuthSignedIn] = useState(false); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [cancelPending, setCancelPending] = useState(false); + const [notice, setNotice] = useState(null); + const [dialog, setDialog] = useState(null); + const [showLogin, setShowLogin] = useState(false); + const [preparingStep, setPreparingStep] = useState(false); + const [setupReached, setSetupReached] = useState<'password' | 'unlock' | null>(null); + const current = useRef(null); + const watermark = useRef('0'); + const alive = useRef(false); + const loadSequence = useRef(0); + const actionSequence = useRef(0); + const activeAction = useRef(null); + const loginHint = prefs?.marketplaceDevLogin?.trim() ?? ''; + const customServerOrigin = prefs?.syncCustomServerOrigin ?? ''; + + const showError = (error: unknown) => { + if (alive.current) setNotice({ key: `errors.${encryptedSyncErrorKey(error)}`, error: true }); + }; + const acceptStatus = (next: EncryptedSyncStatus): boolean => { + if (!alive.current) return false; + const sequence = syncSequence(next.sequence); + const previous = syncSequence(watermark.current); + if (sequence === null || previous === null || sequence < previous) return false; + const scopeChanged = + current.current && encryptedSyncScope(current.current) !== encryptedSyncScope(next); + current.current = next; + watermark.current = next.sequence; + setStatus(next); + if (scopeChanged) setDialog(null); + return true; + }; + const load = async () => { + const request = ++loadSequence.current; + setLoading(true); + try { + const [auth, next] = await Promise.all([marketplaceAuthStatus(), cloudSyncE2eeStatus()]); + if (!alive.current || request !== loadSequence.current) return; + setAuthSignedIn(auth.signedIn); + acceptStatus(next); + } catch (error) { + if (alive.current && request === loadSequence.current) showError(error); + } finally { + if (alive.current && request === loadSequence.current) setLoading(false); + } + }; + const loadRef = useRef(load); + loadRef.current = load; + const eventsRef = useRef({ + state: (_event: EncryptedSyncEvent) => {}, + conflict: (_event: EncryptedSyncConflictEvent) => {}, + restored: (_event: EncryptedSyncRestoreEvent) => {}, + }); + eventsRef.current = { + state(event) { + if (!alive.current) return; + const sequence = syncSequence(event.sequence); + if (sequence === null || sequence <= (syncSequence(watermark.current) ?? 0n)) return; + const snapshot = current.current; + if ( + !snapshot || + !matchesEncryptedSyncEvent(snapshot, event, watermark.current, false) || + encryptedSyncScope(snapshot) !== encryptedSyncScope(event.status) + ) { + // Never take a different account/vault from an unsolicited event. + void loadRef.current(); + return; + } + if ( + event.sequence !== event.status.sequence || + event.accountId !== (event.status.account?.githubId ?? null) || + event.vaultId !== event.status.vaultId || + event.taskId !== event.status.taskId + ) + return; + acceptStatus(event.status); + }, + conflict(event) { + const snapshot = current.current; + if ( + !alive.current || + !snapshot || + !matchesEncryptedSyncEvent(snapshot, event, watermark.current) + ) + return; + watermark.current = event.sequence; + setDialog({ + kind: 'restore', + preview: event.preview, + enableAfter: false, + scope: encryptedSyncScope(snapshot), + }); + setNotice({ key: 'states.conflict' }); + }, + restored(event) { + const snapshot = current.current; + if ( + !alive.current || + !snapshot || + !matchesEncryptedSyncEvent(snapshot, event, watermark.current) + ) + return; + watermark.current = event.sequence; + setDialog(null); + setNotice({ key: 'restored' }); + // UI-only preferences are applied by the central native restore bridge. + void refresh().catch(showError); + void loadRef.current(); + }, + }; + + useEffect(() => { + alive.current = true; + let disposed = false; + const unlisten: Array<() => void> = []; + const uiPersistenceFailed = (event: Event) => { + if (disposed) return; + // Render only allow-listed stable codes; preserve a denied-vault or busy + // cause instead of replacing every failure with a generic storage error. + showError((event as CustomEvent).detail ?? localError('local_storage_unavailable')); + void loadRef.current(); + }; + window.addEventListener('openless:sync-ui-persistence-failed', uiPersistenceFailed); + void (async () => { + try { + if (isTauriHost()) { + const { listen } = await import('@tauri-apps/api/event'); + for (const [name, kind] of [ + ['cloud-sync-e2ee:state', 'state'], + ['cloud-sync-e2ee:conflict', 'conflict'], + ['cloud-sync-e2ee:restored', 'restored'], + ] as const) { + const stop = await listen(name, (event) => { + if (disposed) return; + if (kind === 'state') eventsRef.current.state(event.payload as EncryptedSyncEvent); + else if (kind === 'conflict') + eventsRef.current.conflict(event.payload as EncryptedSyncConflictEvent); + else eventsRef.current.restored(event.payload as EncryptedSyncRestoreEvent); + }); + if (disposed) { + stop(); + return; + } + unlisten.push(stop); + } + } + } catch (error) { + if (!disposed) showError(error); + } + if (!disposed) await loadRef.current(); + })(); + return () => { + disposed = true; + alive.current = false; + loadSequence.current += 1; + actionSequence.current += 1; + unlisten.forEach((stop) => stop()); + window.removeEventListener('openless:sync-ui-persistence-failed', uiPersistenceFailed); + }; + }, []); + useEffect(() => { + if (alive.current) void loadRef.current(); + }, [loginHint]); + + const perform = async (work: (valid: () => boolean) => Promise) => { + if (activeAction.current !== null || current.current?.syncState === 'syncing') return; + const action = ++actionSequence.current; + activeAction.current = action; + setBusy(true); + setNotice(null); + const valid = () => alive.current && actionSequence.current === action; + try { + await work(valid); + } catch (error) { + if (valid()) { + showError(error); + if (encryptedSyncErrorKey(error) === 'outcomeUnknown') setDialog(null); + void loadRef.current(); + } + } finally { + if (activeAction.current === action) activeAction.current = null; + if (alive.current) setBusy(false); + } + }; + const observedRevision = (): string => { + const revision = current.current?.remoteRevision; + if (revision == null) throw localError('stale_preview'); + return revision; + }; + const previewRestore = async (enableAfter: boolean, valid: () => boolean) => { + const scope = current.current ? encryptedSyncScope(current.current) : null; + const preview = await cloudSyncE2eePreviewRestore(observedRevision()); + if (!valid()) return; + const next = await cloudSyncE2eeStatus(); + if (!valid() || (current.current && encryptedSyncScope(current.current) !== scope)) return; + if (!scope || !matchesRestorePreview(preview, next, scope)) throw localError('stale_preview'); + if (!acceptStatus(next)) return; + setDialog({ kind: 'restore', preview, enableAfter, scope }); + }; + const routePreparation = async ( + prepared: EnablePreparation, + intent: Intent, + valid: () => boolean, + ) => { + if (!valid() || !acceptStatus(prepared.status)) return; + if (prepared.nextStep === 'create') { + if ( + intent !== 'enable' || + prepared.status.hasCloudSnapshot !== false || + prepared.status.remoteRevision === null + ) + throw localError('invalid_response'); + setSetupReached('password'); + setDialog({ kind: 'create', observedRevision: prepared.status.remoteRevision }); + } else if (prepared.nextStep === 'unlock') { + setSetupReached('unlock'); + setDialog({ kind: 'unlock', intent }); + } else if (prepared.nextStep === 'restore_review') { + await previewRestore(intent === 'enable', valid); + } else if (intent === 'restore') { + await previewRestore(false, valid); + } else { + if (intent === 'enable') { + const next = await cloudSyncE2eeSetEnabled(true); + if (!valid()) return; + acceptStatus(next); + if (next.enabled && next.keyState === 'unlocked' && next.hasCloudSnapshot === true) + setSetupReached(null); + } + if (valid()) { + setDialog(null); + setNotice({ key: 'done' }); + } + } + }; + const begin = (intent: Intent) => { + setNotice(null); + if (intent === 'enable' || current.current?.consentVersion !== CONSENT_VERSION) { + setDialog({ kind: 'consent', intent }); + } else { + void perform(async (valid) => routePreparation(await prepareEncryptedSync(), intent, valid)); + } + }; + const simple = (request: () => Promise, signOut = false) => + void perform(async (valid) => { + const next = await request(); + if (!valid() || !acceptStatus(next)) return; + if (signOut) { + try { + const auth = await marketplaceAuthStatus(); + if (valid()) setAuthSignedIn(auth.signedIn); + } catch { + if (valid()) setAuthSignedIn(false); + } + await refresh(); + } + if (next.syncState === 'conflict') { + if (valid()) setNotice({ key: 'states.conflict' }); + await previewRestore(false, valid); + return; + } + if (valid()) { + setDialog(null); + setNotice({ key: 'done' }); + } + }); + const submitPassword = (value: PasswordSubmission) => { + const active = dialog; + if (!active || !['create', 'unlock', 'password'].includes(active.kind)) return; + void perform(async (valid) => { + if (active.kind === 'create') { + const next = await cloudSyncE2eeCreate({ + password: value.password, + passwordConfirmation: value.confirmation, + rememberKey: value.rememberKey, + consentVersion: CONSENT_VERSION, + observedRevision: active.observedRevision, + }); + if (valid() && acceptStatus(next)) { + setDialog(null); + setNotice({ key: 'done' }); + } + } else if (active.kind === 'unlock') { + const next = await cloudSyncE2eeUnlock({ + password: value.password, + rememberKey: value.rememberKey, + }); + if (!valid() || !acceptStatus(next)) return; + await routePreparation(await prepareEncryptedSync(), active.intent, valid); + } else if (active.kind === 'password') { + const next = await cloudSyncE2eeChangePassword({ + currentPassword: value.currentPassword, + newPassword: value.password, + confirmation: value.confirmation, + rememberKey: value.rememberKey, + }); + if (valid() && acceptStatus(next)) { + setDialog(null); + setNotice({ key: 'done' }); + } + } + }); + }; + const applyRestore = (mode: 'replace' | 'merge', conflictChoices: SyncConflictChoice[]) => { + if (dialog?.kind !== 'restore') return; + const { preview, enableAfter, scope } = dialog; + void perform(async (valid) => { + const snapshot = current.current; + if (!matchesRestorePreview(preview, snapshot, scope)) throw localError('stale_preview'); + const next = await cloudSyncE2eeApplyRestore({ + previewId: preview.previewId, + mode, + conflictChoices, + }); + if (!valid() || !acceptStatus(next)) return; + if (enableAfter && !next.enabled) { + const enabled = await cloudSyncE2eeSetEnabled(true); + if (!valid()) return; + acceptStatus(enabled); + } + await refresh(); + if (valid()) { + setDialog(null); + setNotice({ key: 'restored' }); + } + }); + }; + const cancelTask = async () => { + const task = current.current?.taskId; + if (!task || cancelPending) return; + setCancelPending(true); + try { + const next = await cloudSyncE2eeCancel(task); + if (alive.current && acceptStatus(next)) setNotice({ key: 'cancelRequested' }); + } catch (error) { + showError(error); + } finally { + if (alive.current) setCancelPending(false); + } + }; + + const customServerConfigured = Boolean(prefs?.syncCustomServerOrigin?.trim()); + const syncSignedIn = + status?.authState === 'signed_in' && status?.syncState !== 'sign_in_required'; + const identityAvailable = + status?.authState !== 'expired' && + status?.syncState !== 'sign_in_required' && + (syncSignedIn || (Boolean(prefs) && !customServerConfigured && authSignedIn)); + const working = busy || status?.syncState === 'syncing'; + const unlocked = status?.keyState === 'unlocked'; + const available = status !== null; + const lastSync = status?.lastSuccessfulSyncAt ? new Date(status.lastSuccessfulSyncAt) : null; + const lastError = status?.lastError ? encryptedSyncErrorKey(status.lastError) : null; + const noticeError = notice?.error ? notice.key.replace(/^errors\./, '') : null; + const visibleError = noticeError ?? (!notice ? lastError : null); + const focus = status + ? setupFocus(status, identityAvailable, preparingStep, setupReached) + : identityAvailable + ? 'enable' + : 'enable'; + const focusTitle = + focus === 'state' && status + ? `cloudSyncE2ee.states.${status.recoveryRequired ? 'recovery_required' : status.syncState}` + : `cloudSyncE2ee.step${focus[0].toUpperCase()}${focus.slice(1)}Title`; + const focusDetail = + focus === 'state' + ? 'cloudSyncE2ee.stepFollowDetail' + : `cloudSyncE2ee.step${focus[0].toUpperCase()}${focus.slice(1)}Detail`; + const canSync = + !working && + !status?.recoveryRequired && + (Boolean(status?.pendingOperationId) || + (Boolean(status?.enabled) && unlocked && status?.syncState !== 'conflict')); + const dialogTitle = + dialog?.kind === 'create' + ? 'createTitle' + : dialog?.kind === 'unlock' + ? 'unlockTitle' + : dialog?.kind === 'password' + ? 'passwordTitle' + : `${dialog?.kind ?? 'consent'}Title`; + const closeDialog = () => { + if (!working) { + setDialog(null); + setNotice(null); + } + }; + const taskControls = status?.taskId ? ( + void cancelTask()}> + {t('cloudSyncE2ee.cancelTask')} + + ) : null; + + return ( + +
+
+ + + +
+

{t('cloudSyncE2ee.title')}

+

{t('cloudSyncE2ee.description')}

+
+ +
+
+ {t('cloudSyncE2ee.enable')} + (next ? begin('enable') : setDialog({ kind: 'disable' }))} + /> +
+ {loading &&

{t('cloudSyncE2ee.loading')}

} + {!loading && !customServerConfigured && !syncSignedIn && !authSignedIn && ( + setShowLogin(true)} + > + {t('cloudSyncE2ee.signIn')} + + )} + {syncSignedIn && ( +
+ + {t('cloudSyncE2ee.account')} + + {status?.account?.login + ? customServerOrigin.trim() + ? `${status.account.login}@${customServerOrigin + .trim() + .replace(/^[a-z]+:\/\//i, '') + .replace(/\/$/, '')}` + : `@${status.account.login}` + : loginHint + ? `@${loginHint}` + : 'GitHub'} + + simple(cloudSyncE2eeSignOut, true)}> + {t('cloudSyncE2ee.signOut')} + +
+ )} + {status && ( +
+ {t(focusTitle)} +

{t(focusDetail)}

+
+ {t(unlocked ? 'cloudSyncE2ee.keyUnlocked' : 'cloudSyncE2ee.keyLocked')} + {!unlocked && syncSignedIn && ( + begin(status.hasCloudSnapshot ? 'unlock' : 'enable')} + > + {t( + status.hasCloudSnapshot ? 'cloudSyncE2ee.unlock' : 'cloudSyncE2ee.setPassword', + )} + + )} +
+
+ + {t( + status.hasCloudSnapshot === true + ? 'cloudSyncE2ee.hasSnapshot' + : status.hasCloudSnapshot === false + ? 'cloudSyncE2ee.noSnapshot' + : 'cloudSyncE2ee.snapshotUnknown', + )} + + {status.hasCloudSnapshot === false && syncSignedIn && unlocked && ( + begin('enable')} + > + {t('cloudSyncE2ee.setPassword')} + + )} +
+ {lastSync && Number.isFinite(lastSync.getTime()) && ( + + {t('cloudSyncE2ee.lastSync', { + time: lastSync.toLocaleString(i18n.resolvedLanguage ?? i18n.language), + })} + + )} +
+ )} + {syncSignedIn && available && ( +
+ {!unlocked && status?.hasCloudSnapshot && ( + begin('unlock')}> + {t('cloudSyncE2ee.unlock')} + + )} + simple(cloudSyncE2eeSyncNow)} + > + {t( + status?.pendingOperationId ? 'cloudSyncE2ee.checkPending' : 'cloudSyncE2ee.syncNow', + )} + + begin('restore')} + > + {t('cloudSyncE2ee.restore')} + + {unlocked && ( + <> + simple(cloudSyncE2eeLock)}> + {t('cloudSyncE2ee.lock')} + + setDialog({ kind: 'password' })} + > + {t('cloudSyncE2ee.changePassword')} + + + )} + +
+ )} + +
+ {t('cloudSyncE2ee.working')} + {taskControls} +
+
+ +

{notice ? t(`cloudSyncE2ee.${notice.key}`) : ''}

+
+ +
+

+ {t(`cloudSyncE2ee.errors.${visibleError}`)} +

+ {REFRESH_ERRORS.has(visibleError ?? '') && ( + void load()} + > + {t('cloudSyncE2ee.refresh')} + + )} + {(visibleError === 'unlock' || + visibleError === 'invalidPassword' || + visibleError === 'secureStorage') && + identityAvailable && ( + begin(status?.hasCloudSnapshot ? 'unlock' : 'enable')} + > + {t( + status?.hasCloudSnapshot ? 'cloudSyncE2ee.unlock' : 'cloudSyncE2ee.setPassword', + )} + + )} +
+
+ {status?.lastError?.retryAfterSeconds != null && + Number.isSafeInteger(status.lastError.retryAfterSeconds) && + status.lastError.retryAfterSeconds > 0 && + status.lastError.retryAfterSeconds <= 86400 && ( +

{t('cloudSyncE2ee.retryAfter', { seconds: status.lastError.retryAfterSeconds })}

+ )} +

{t('cloudSyncE2ee.passwordWarning')}

+
+ ( + setShowLogin(false)} + onSuccess={(login) => { + setShowLogin(false); + void updatePrefs((value) => ({ ...value, marketplaceDevLogin: login })) + .then(() => loadRef.current()) + .catch(showError); + }} + /> + )} + /> + + dialog && ( + + {notice?.error && ( +

+ {t(`cloudSyncE2ee.${notice.key}`)} +

+ )} + {dialog.kind === 'consent' && ( + { + setNotice(null); + setDialog({ kind: 'protocol', intent: dialog.intent }); + }} + /> + )} + {dialog.kind === 'protocol' && ( + { + setNotice(null); + setDialog(null); + }} + onConfirm={() => { + const intent = dialog.intent; + setNotice(null); + setPreparingStep(true); + setDialog(null); + void perform(async (valid) => { + await routePreparation(await prepareEncryptedSync(), intent, valid); + }).finally(() => { + if (alive.current) setPreparingStep(false); + }); + }} + /> + )} + {(dialog.kind === 'create' || + dialog.kind === 'unlock' || + dialog.kind === 'password') && ( + + )} + {dialog.kind === 'restore' && ( + + )} + {dialog.kind === 'disable' && ( + <> +

{t('cloudSyncE2ee.disableDescription')}

+ simple(() => cloudSyncE2eeSetEnabled(false))} + > + {t('cloudSyncE2ee.confirmDisable')} + + + )} + {dialog.kind === 'delete' && ( + + simple(() => + cloudSyncE2eeDeleteRemote({ + expectedVaultId: dialog.vaultId, + observedRevision: dialog.revision, + confirmed: true, + }), + ) + } + /> + )} + {working && status?.taskId && dialog.kind !== 'protocol' && ( +
+ {t('cloudSyncE2ee.working')} + {taskControls} +
+ )} +
+ ) + } + /> +
+ ); +} + +function ConsentForm({ busy, onConfirm }: { busy: boolean; onConfirm: () => void }) { + const { t } = useTranslation(); + const [consented, setConsented] = useState(false); + return ( +
+

{t('cloudSyncE2ee.consentDescription')}

+
+ + {t('cloudSyncE2ee.scopeSummary')} + +
    + {['preferences', 'credentials', 'personal', 'history', 'device'].map((key) => ( +
  • {t(`cloudSyncE2ee.scope.${key}`)}
  • + ))} +
+

{t('cloudSyncE2ee.scope.excluded')}

+
+ + + {t('cloudSyncE2ee.continue')} + +
+ ); +} + +function ProtocolWarning({ + busy, + onConfirm, + onCancel, +}: { + busy: boolean; + onConfirm: () => void; + onCancel: () => void; +}) { + const { t } = useTranslation(); + const [acknowledged, setAcknowledged] = useState(false); + return ( +
+

+ {t('cloudSyncE2ee.protocolIntro')} +

+
+ {['Password', 'Encryption', 'Excluded'].map((section) => ( +
+

+ {t(`cloudSyncE2ee.protocol${section}Title`)} +

+

+ {t(`cloudSyncE2ee.protocol${section}`)} +

+
+ ))} +
+ +
+ + {t('common.cancel')} + + + {t('cloudSyncE2ee.protocolConfirm')} + +
+
+ ); +} + +function PasswordForm({ + mode, + busy, + onSubmit, +}: { + mode: 'create' | 'unlock' | 'password'; + busy: boolean; + onSubmit: (value: PasswordSubmission) => void; +}) { + const { t } = useTranslation(); + const [password, setPassword] = useState(''); + const [confirmation, setConfirmation] = useState(''); + const [currentPassword, setCurrentPassword] = useState(''); + const [rememberKey, setRememberKey] = useState(true); + const composing = useRef(false); + const creating = mode !== 'unlock'; + const valid = creating + ? syncPasswordMeetsBasicRequirements(password) && + password.normalize('NFC') === confirmation.normalize('NFC') && + (mode !== 'password' || currentPassword.length > 0) + : password.length > 0; + const inputStyle = { + width: '100%', + boxSizing: 'border-box' as const, + border: '1px solid var(--ol-line-strong)', + borderRadius: 'var(--ol-r-md)', + background: 'var(--ol-control-solid)', + color: 'var(--ol-ink)', + padding: '10px 12px', + font: 'inherit', + }; + return ( +
{ + composing.current = true; + }} + onCompositionEnd={() => { + composing.current = false; + }} + onKeyDown={(event) => { + if ( + event.key === 'Enter' && + (composing.current || event.nativeEvent.isComposing || event.keyCode === 229) + ) + event.preventDefault(); + }} + onSubmit={(event) => { + event.preventDefault(); + if (busy || !valid || composing.current) return; + const value = { password, confirmation, currentPassword, rememberKey }; + // Clear controlled inputs immediately, before the async native operation. + setPassword(''); + setConfirmation(''); + setCurrentPassword(''); + onSubmit(value); + }} + > + {mode === 'password' && ( + + )} + + {creating && ( + + )} +

+ {t('cloudSyncE2ee.passwordPolicy')} {t('cloudSyncE2ee.passwordWarning')} +

+ + +
+ ); +} + +function DeleteConfirmation({ + busy, + backupRetentionDays, + onConfirm, +}: { + busy: boolean; + backupRetentionDays: number | null; + onConfirm: () => void; +}) { + const { t } = useTranslation(); + const [confirmed, setConfirmed] = useState(false); + return ( +
+

{t('cloudSyncE2ee.deleteDescription')}

+ {backupRetentionDays !== null && + Number.isSafeInteger(backupRetentionDays) && + backupRetentionDays >= 0 && ( +

{t('cloudSyncE2ee.backupRetention', { days: backupRetentionDays })}

+ )} + + + {t('cloudSyncE2ee.confirmDelete')} + +
+ ); +} + +function SyncDialog({ + title, + closing = false, + busy, + showClose = true, + onClose, + children, +}: { + title: string; + closing?: boolean; + busy: boolean; + showClose?: boolean; + onClose: () => void; + children: ReactNode; +}) { + const { t } = useTranslation(); + const titleId = useId(); + const dialog = useRef(null); + const opener = useRef(document.activeElement); + useEffect(() => { + const previous = opener.current; + const background = + previous instanceof HTMLElement ? previous.closest('[role="dialog"]') : null; + const wasInert = background?.inert ?? false; + if (background) background.inert = true; + return () => { + if (background) background.inert = wasInert; + if (previous instanceof HTMLElement && previous.isConnected) previous.focus(); + }; + }, []); + useEffect(() => { + dialog.current?.focus(); + }, [title]); + return ( + +
{ + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + if (!busy) onClose(); + } + if (event.key !== 'Tab') return; + const controls = Array.from( + dialog.current?.querySelectorAll( + 'button:not(:disabled), input:not(:disabled), summary, [tabindex="0"]', + ) ?? [], + ); + if (controls.length === 0) { + event.preventDefault(); + return; + } + const first = controls[0]; + const last = controls[controls.length - 1]; + if ( + event.shiftKey && + (document.activeElement === first || document.activeElement === dialog.current) + ) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + }} + > +
+

+ {title} +

+ {showClose && ( + + )} +
+ {children} +
+
+ ); +} diff --git a/openless-all/app/src/features/cloud-sync/CloudSyncSetupPrompt.tsx b/openless-all/app/src/features/cloud-sync/CloudSyncSetupPrompt.tsx new file mode 100644 index 000000000..34b93460c --- /dev/null +++ b/openless-all/app/src/features/cloud-sync/CloudSyncSetupPrompt.tsx @@ -0,0 +1,231 @@ +import { useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { CloudIcon, XIcon } from 'lucide-react'; +import { isTauriHost } from '../../runtime/environment'; +import { cloudSyncE2eeClaimSetupPrompt } from '../../api/cloud-sync'; +import { CloudSyncSection } from './CloudSyncSection'; +import { PresenceModal } from '../../ui/overlays/Modal'; + +const PROMPT_EVENTS = new Set([ + 'backend_started', + 'preferences_changed', + 'credentials_changed', + 'dictation_completed', + 'dictation_state_changed', + 'qa_state', + 'selection_state_changed', + 'selection_voice_state_changed', + 'less_computer_event', + 'local_asr_engine_changed', + 'permission_changed', +]); + +/** Core owns eligibility and the durable once-per-installation claim. */ +export function CloudSyncSetupPrompt({ + blocked, + onSetup, +}: { + blocked: boolean; + onSetup: () => void; +}) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const checkRef = useRef(0); + const focusRef = useRef(null); + + useEffect(() => { + if (!isTauriHost() || blocked) return; + let cancelled = false; + let inFlight = false; + let timer: ReturnType | undefined; + let unlisten: (() => void) | undefined; + const check = async () => { + if (cancelled || inFlight || document.visibilityState !== 'visible' || !document.hasFocus()) + return; + inFlight = true; + const request = ++checkRef.current; + try { + const claimed = await cloudSyncE2eeClaimSetupPrompt(); + if ( + !cancelled && + checkRef.current === request && + claimed && + document.visibilityState === 'visible' && + document.hasFocus() + ) + setOpen(true); + } catch { + // Denied credential reads and in-progress saves never consume consent + // or display a misleading configuration-complete message. + } finally { + inFlight = false; + } + }; + const schedule = () => { + if (timer) clearTimeout(timer); + timer = setTimeout(() => { + void check(); + }, 300); + }; + const invalidate = () => { + checkRef.current += 1; + setOpen(false); + }; + const eligibilityChanged = () => { + invalidate(); + schedule(); + }; + void import('@tauri-apps/api/event') + .then(async ({ listen }) => { + const handle = await listen<{ kind: { type: string } }>('backend:event', ({ payload }) => { + if (PROMPT_EVENTS.has(payload.kind.type)) eligibilityChanged(); + }); + if (cancelled) handle(); + else { + unlisten = handle; + schedule(); + } + }) + .catch(() => {}); + window.addEventListener('focus', schedule); + window.addEventListener('blur', invalidate); + document.addEventListener('visibilitychange', eligibilityChanged); + return () => { + cancelled = true; + checkRef.current += 1; + if (timer) clearTimeout(timer); + unlisten?.(); + window.removeEventListener('focus', schedule); + window.removeEventListener('blur', invalidate); + document.removeEventListener('visibilitychange', eligibilityChanged); + }; + }, [blocked]); + + useEffect(() => { + if (!open || blocked) return; + const previous = document.activeElement; + focusRef.current?.focus(); + return () => { + if (previous instanceof HTMLElement) previous.focus(); + }; + }, [open, blocked]); + + // The eligibility gate revokes interaction immediately; keep only the inert + // last frame long enough to fade rather than flashing away. + return ( + setOpen(false)} + width="min(480px, 100%)" + zIndex={75} + render={() => ( +
{ + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + setOpen(false); + } + if (event.key === 'Tab') { + const buttons = [ + ...event.currentTarget.querySelectorAll('button'), + ]; + const last = buttons[buttons.length - 1]; + const next = event.shiftKey ? last : buttons[0]; + if (document.activeElement === (event.shiftKey ? buttons[0] : last)) { + event.preventDefault(); + next?.focus(); + } + } + }} + > +
+ )} + /> + ); +} + +/** Available before API-key setup. Opening this never enables sync or uploads. */ +export function CloudSyncWelcome({ inline = false }: { inline?: boolean }) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + return ( + <> + + setOpen(false)} + width="min(680px, 100%)" + zIndex={50} + render={() => + open && ( + <> +
+ +
+ + + ) + } + /> + + ); +} diff --git a/openless-all/app/src/features/cloud-sync/RestoreReview.tsx b/openless-all/app/src/features/cloud-sync/RestoreReview.tsx new file mode 100644 index 000000000..6fb140100 --- /dev/null +++ b/openless-all/app/src/features/cloud-sync/RestoreReview.tsx @@ -0,0 +1,192 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { RestorePreview, SyncConflictChoice } from '../../api/cloud-sync'; +import { Btn } from '../../pages/_atoms'; + +const categoryKeys = [ + 'preferences', + 'ui_preferences', + 'channels', + 'provider_credentials', + 'dictionary', + 'vocabulary_presets', + 'corrections', + 'style_packs', + 'history', + 'activity', + 'device_profile', +] as const; +function categoryKey(kind: string): string { + return categoryKeys.some((key) => key === kind) ? kind : 'other'; +} +export function RestoreReview({ + preview, + busy, + stale, + onApply, +}: { + preview: RestorePreview; + busy: boolean; + stale: boolean; + onApply: (mode: 'replace' | 'merge', choices: SyncConflictChoice[]) => void; +}) { + const { t } = useTranslation(); + const [mode, setMode] = useState<'replace' | 'merge'>('merge'); + const [reviewed, setReviewed] = useState(false); + const [choices, setChoices] = useState>({}); + const [page, setPage] = useState(0); + const pageSize = 20; + const selected = preview.conflicts.filter( + (conflict) => choices[conflict.id] !== undefined, + ).length; + const complete = mode === 'replace' || selected === preview.conflicts.length; + return ( +
+

{t('cloudSyncE2ee.restoreDescription')}

+ {preview.unconfirmedOperationId && ( +

{t('cloudSyncE2ee.errors.outcomeUnknown')}

+ )} +
    + {Object.entries(preview.counts) + .filter(([, count]) => count > 0) + .map(([kind, count]) => ( +
  • + {t(`cloudSyncE2ee.categories.${categoryKey(kind)}`)}: {count} +
  • + ))} +
+ {preview.deviceSettingsToReview.length > 0 && ( +

{t('cloudSyncE2ee.deviceReview', { count: preview.deviceSettingsToReview.length })}

+ )} +
+ {t('cloudSyncE2ee.restoreMode')} + + +
+ {mode === 'replace' ? ( +

{t('cloudSyncE2ee.replaceWarning')}

+ ) : ( + preview.conflicts.length > 0 && ( + <> +

+ {t('cloudSyncE2ee.conflictProgress', { selected, total: preview.conflicts.length })} +

+ {preview.conflicts + .slice(page * pageSize, (page + 1) * pageSize) + .map((conflict, index) => ( +
+ + {t('cloudSyncE2ee.conflictItem', { + index: page * pageSize + index + 1, + category: t(`cloudSyncE2ee.categories.${categoryKey(conflict.kind)}`), + })} + +

+ {t( + `cloudSyncE2ee.conflictReasons.${['both_modified', 'delete_modify', 'no_common_baseline'].includes(conflict.reason) ? conflict.reason : 'other'}`, + )} +

+
+ {(['local', 'cloud'] as const).map((side) => ( + + ))} +
+
+ ))} + {preview.conflicts.length > pageSize && ( +
+ setPage((value) => value - 1)}> + {t('cloudSyncE2ee.previous')} + + + {page + 1} / {Math.ceil(preview.conflicts.length / pageSize)} + + = preview.conflicts.length || busy} + onClick={() => setPage((value) => value + 1)} + > + {t('cloudSyncE2ee.next')} + +
+ )} + + ) + )} + + {stale && ( +

+ {t('cloudSyncE2ee.errors.changed')} +

+ )} + + onApply( + mode, + mode === 'replace' + ? [] + : preview.conflicts.map((conflict) => ({ + id: conflict.id, + side: choices[conflict.id], + })), + ) + } + > + {t('cloudSyncE2ee.applyRestore')} + +
+ ); +} diff --git a/openless-all/app/src/features/cloud-sync/restoreContext.ts b/openless-all/app/src/features/cloud-sync/restoreContext.ts new file mode 100644 index 000000000..ef554c44c --- /dev/null +++ b/openless-all/app/src/features/cloud-sync/restoreContext.ts @@ -0,0 +1,18 @@ +import { + encryptedSyncScope, + type EncryptedSyncStatus, + type RestorePreview, +} from '../../api/cloud-sync'; + +export function matchesRestorePreview( + preview: RestorePreview, + status: EncryptedSyncStatus | null, + scope: string, +): boolean { + return ( + !!status && + encryptedSyncScope(status) === scope && + preview.observedRevision === status.remoteRevision && + preview.localGeneration === status.localGeneration + ); +} diff --git a/openless-all/app/src/features/corrections/Corrections.tsx b/openless-all/app/src/features/corrections/Corrections.tsx new file mode 100644 index 000000000..4059840dc --- /dev/null +++ b/openless-all/app/src/features/corrections/Corrections.tsx @@ -0,0 +1,223 @@ +import type { CSSProperties } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { CorrectionRule } from '../../api/contracts'; +import { useMobileLayout } from '../../lib/useMobileLayout'; +import { Btn, Card, PageHeader } from '../../pages/_atoms'; +import { useCorrectionRules } from './useCorrectionRules'; + +export function Corrections() { + const { t } = useTranslation(); + const mobile = useMobileLayout(); + const { + busy, + error, + refresh, + onlyLearnedRules, + setOnlyLearnedRules, + rulePatternDraft, + setRulePatternDraft, + ruleReplacementDraft, + setRuleReplacementDraft, + onAddCorrectionRule, + onRemoveCorrectionRule, + onToggleCorrectionRule, + onRemoveAllLearnedRules, + learnedRuleCount, + visibleRules, + } = useCorrectionRules(); + + return ( + <> + + void refresh(true)}> + {t('common.refresh')} + +
+ } + /> + + +
+
+ setRulePatternDraft(e.target.value)} + placeholder={t('vocab.corrections.patternPlaceholder')} + style={{ + height: 32, + padding: '0 10px', + border: '0.5px solid var(--ol-line-strong)', + borderRadius: 'var(--ol-control-radius)', + background: 'var(--ol-surface-2)', + fontFamily: 'inherit', + fontSize: 13, + }} + /> + {!mobile && →} + setRuleReplacementDraft(e.target.value)} + placeholder={t('vocab.corrections.replacementPlaceholder')} + style={{ + height: 32, + padding: '0 10px', + border: '0.5px solid var(--ol-line-strong)', + borderRadius: 'var(--ol-control-radius)', + background: 'var(--ol-surface-2)', + fontFamily: 'inherit', + fontSize: 13, + }} + /> + void onAddCorrectionRule()} + disabled={busy} + style={ + { + '--ol-button-radius': '8px', + justifySelf: mobile ? 'start' : undefined, + } as CSSProperties + } + > + {t('common.add')} + +
+ {learnedRuleCount > 0 && ( +
+ + void onRemoveAllLearnedRules()}> + {t('vocab.corrections.removeAllLearned')} + +
+ )} + {error && ( +
{error}
+ )} +
+ {visibleRules.length === 0 && ( + + {t('vocab.corrections.empty')} + + )} + {visibleRules.map((rule) => ( + void onToggleCorrectionRule(rule)} + onRemove={() => void onRemoveCorrectionRule(rule.id)} + /> + ))} +
+
+
+ + ); +} + +interface CorrectionRuleChipProps { + rule: CorrectionRule; + onToggle: () => void; + onRemove: () => void; +} + +function CorrectionRuleChip({ rule, onToggle, onRemove }: CorrectionRuleChipProps) { + const { t } = useTranslation(); + const enabled = rule.enabled; + return ( + + + {rule.source === 'learned' && ( + + {t('vocab.corrections.learnedBadge')} + + )} + + + ); +} diff --git a/openless-all/app/src/features/corrections/useCorrectionRules.ts b/openless-all/app/src/features/corrections/useCorrectionRules.ts new file mode 100644 index 000000000..af46d043a --- /dev/null +++ b/openless-all/app/src/features/corrections/useCorrectionRules.ts @@ -0,0 +1,156 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { CorrectionRule } from '../../api/contracts'; +import { + addCorrectionRule, + listCorrectionRules, + removeCorrectionRule, + setCorrectionRuleEnabled, +} from '../../api/corrections'; +import { listenVocabularyChanges } from '../../api/vocabulary-events'; +import { useInteraction } from '../../ui/overlays/InteractionProvider'; + +const numberToken = '{num}'; +function supportedRule(pattern: string, replacement: string) { + const [prefix, suffix, ...more] = pattern.split(numberToken); + if (!pattern || more.length || (suffix === undefined && replacement.includes(numberToken))) + return false; + return suffix === undefined || Boolean(prefix || suffix); +} + +const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +export function useCorrectionRules() { + const { t } = useTranslation(); + const { confirm, notify } = useInteraction('corrections'); + const [rules, setRules] = useState([]); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const [onlyLearnedRules, setOnlyLearnedRules] = useState(false); + const [rulePatternDraft, setRulePatternDraft] = useState(''); + const [ruleReplacementDraft, setRuleReplacementDraft] = useState(''); + const writing = useRef(false); + const request = useRef(0); + const refresh = useCallback( + async (withNotice = false) => { + const id = ++request.current; + try { + const snapshot = await listCorrectionRules(); + if (id !== request.current) return; + setRules(snapshot); + if (withNotice) { + setError(null); + notify({ message: t('common.refreshed'), state: 'saved' }); + } + } catch (error) { + if (id !== request.current) return; + setError(errorMessage(error)); + if (withNotice) + notify({ message: t('common.operationFailed'), state: 'failed', durationMs: 3500 }); + } + }, + [notify, t], + ); + const refreshRef = useRef(refresh); + refreshRef.current = refresh; + useEffect(() => { + let disposed = false; + let stop: (() => void) | undefined; + void listenVocabularyChanges(() => { + if (!disposed && !writing.current) void refreshRef.current(); + }) + .then((unlisten) => { + if (disposed) unlisten(); + else stop = unlisten; + }) + .catch((error) => console.warn('[corrections] update listener failed', error)) + .finally(() => { + if (!disposed) void refreshRef.current(); + }); + return () => { + disposed = true; + request.current++; + stop?.(); + }; + }, []); + + const write = async (command: () => Promise, success = t('common.saved')) => { + if (writing.current) return; + writing.current = true; + request.current++; + setBusy(true); + setError(null); + try { + await command(); + notify({ message: success, state: 'saved' }); + } catch (error) { + setError(errorMessage(error)); + } finally { + writing.current = false; + setBusy(false); + await refresh(); + } + }; + + const onAddCorrectionRule = () => { + const pattern = rulePatternDraft.trim(); + const replacement = ruleReplacementDraft.trim(); + if (!pattern) return; + if (!supportedRule(pattern, replacement)) { + setError(t('vocab.corrections.invalid')); + return; + } + return write(async () => { + await addCorrectionRule(pattern, replacement); + setRulePatternDraft((current) => (current.trim() === pattern ? '' : current)); + setRuleReplacementDraft((current) => (current.trim() === replacement ? '' : current)); + }); + }; + + const onRemoveCorrectionRule = (id: string) => write(() => removeCorrectionRule(id)); + + const onToggleCorrectionRule = (rule: CorrectionRule) => + write(() => setCorrectionRuleEnabled(rule.id, !rule.enabled)); + + const learned = rules.filter((rule) => rule.source === 'learned'); + const onRemoveAllLearnedRules = async () => { + if (!learned.length || writing.current) return; + if ( + !(await confirm({ + title: t('vocab.corrections.removeAllLearned'), + description: t('vocab.corrections.onlyLearned', { count: learned.length }), + confirmLabel: t('common.delete'), + tone: 'danger', + })) + ) + return; + await write(async () => { + const errors: unknown[] = []; + for (const { id } of learned) { + try { + await removeCorrectionRule(id); + } catch (error) { + errors.push(error); + } + } + if (errors.length) throw errors[0]; + }); + }; + return { + busy, + error, + refresh, + onlyLearnedRules, + setOnlyLearnedRules, + rulePatternDraft, + setRulePatternDraft, + ruleReplacementDraft, + setRuleReplacementDraft, + onAddCorrectionRule, + onRemoveCorrectionRule, + onToggleCorrectionRule, + onRemoveAllLearnedRules, + learnedRuleCount: learned.length, + visibleRules: onlyLearnedRules ? learned : rules, + }; +} diff --git a/openless-all/app/src/features/dictation/HarmonyDictation.tsx b/openless-all/app/src/features/dictation/HarmonyDictation.tsx new file mode 100644 index 000000000..82bfb6147 --- /dev/null +++ b/openless-all/app/src/features/dictation/HarmonyDictation.tsx @@ -0,0 +1,63 @@ +import { useTranslation } from 'react-i18next'; +import { Btn, Card } from '../../pages/_atoms'; +import { useInAppDictation } from './useInAppDictation'; + +export function HarmonyDictation({ onComplete }: { onComplete: () => void }) { + const { t } = useTranslation(); + const { state, result, copied, record, cancel, copy } = useInAppDictation(onComplete); + const waiting = ['starting', 'processing', 'cancelling'].includes(state.phase); + return ( + +
+ {t('overview.inAppDictation.title')} + + {t(`overview.inAppDictation.${waiting ? 'processing' : state.phase}`)} + + void record()} disabled={waiting}> + {t(`overview.inAppDictation.${state.phase === 'recording' ? 'stop' : 'start'}`)} + + {state.phase !== 'idle' && ( + void cancel()} + > + {t('common.cancel')} + + )} +
+ {state.phase === 'recording' && ( + + )} + {state.error && ( +
+ {state.error} +
+ )} + {result && ( +
+
+ {result} +
+ void copy()}> + {t(copied ? 'common.copied' : 'common.copy')} + +
+ )} +
+ ); +} diff --git a/openless-all/app/src/features/dictation/useInAppDictation.ts b/openless-all/app/src/features/dictation/useInAppDictation.ts new file mode 100644 index 000000000..0cea935e8 --- /dev/null +++ b/openless-all/app/src/features/dictation/useInAppDictation.ts @@ -0,0 +1,112 @@ +import { useEffect, useRef, useState } from 'react'; +import { cancelDictation, startDictation } from '../../api/dictation'; +import { copyTextToClipboard } from '../../api/files'; +import { + finishInAppDictation, + listenInAppDictation, + type VoiceState, +} from '../../api/in-app-dictation'; + +let pendingRelease: Promise | null = null; + +function releaseCapture(): Promise { + pendingRelease ??= cancelDictation().finally(() => { + pendingRelease = null; + }); + return pendingRelease; +} + +export function useInAppDictation(onComplete: () => void) { + const [state, setState] = useState({ phase: 'idle', level: 0, error: '' }); + const [result, setResult] = useState(''); + const [copied, setCopied] = useState(false); + const generation = useRef(0); + const active = useRef(false); + const busy = useRef(false); + const cancelling = useRef(false); + const nativePhase = useRef('idle'); + useEffect(() => { + const unlisten = listenInAppDictation((next) => { + nativePhase.current = next.phase; + active.current = next.phase !== 'idle'; + if (!cancelling.current) setState(next); + }); + return () => { + generation.current++; + unlisten(); + if (active.current) { + void releaseCapture().catch((error) => + console.warn('[dictation] capture release failed', error), + ); + } + }; + }, []); + + const record = async () => { + if (busy.current) return; + busy.current = true; + const epoch = ++generation.current; + const stopping = state.phase === 'recording'; + active.current = true; + setState({ phase: stopping ? 'processing' : 'starting', level: 0, error: '' }); + if (!stopping) { + setResult(''); + setCopied(false); + } + try { + if (stopping) { + const reply = await finishInAppDictation(); + if (epoch !== generation.current) return; + active.current = false; + setResult(reply.polishedText || reply.rawText); + setState({ phase: 'idle', level: 0, error: '' }); + onComplete(); + } else { + if (pendingRelease) await pendingRelease; + if (epoch !== generation.current) return; + await startDictation(); + if (epoch === generation.current) setState({ phase: 'recording', level: 0, error: '' }); + } + } catch (error) { + if (epoch === generation.current) { + const phase = nativePhase.current === 'recording' ? 'recording' : 'idle'; + active.current = phase !== 'idle'; + setState({ phase, level: 0, error: String(error) }); + } + } finally { + if (epoch === generation.current) busy.current = false; + } + }; + const cancel = async () => { + if (cancelling.current) return; + const epoch = ++generation.current; + cancelling.current = true; + busy.current = true; + setState({ phase: 'cancelling', level: 0, error: '' }); + try { + await releaseCapture(); + if (epoch !== generation.current) return; + active.current = false; + setState({ phase: 'idle', level: 0, error: '' }); + } catch (error) { + if (epoch !== generation.current) return; + // Keep cancel/retry reachable when the bridge did not confirm release. + setState({ phase: active.current ? 'recording' : 'idle', level: 0, error: String(error) }); + } finally { + if (epoch === generation.current) { + busy.current = false; + cancelling.current = false; + } + } + }; + const copy = async () => { + const epoch = generation.current; + try { + await copyTextToClipboard(result); + if (epoch === generation.current) setCopied(true); + } catch (error) { + if (epoch === generation.current) setState((old) => ({ ...old, error: String(error) })); + } + }; + return { state, result, copied, record, cancel, copy }; +} diff --git a/openless-all/app/src/components/DownloadProgressCards.tsx b/openless-all/app/src/features/downloads/DownloadProgressCards.tsx similarity index 93% rename from openless-all/app/src/components/DownloadProgressCards.tsx rename to openless-all/app/src/features/downloads/DownloadProgressCards.tsx index 9f30f7d4e..3ddace349 100644 --- a/openless-all/app/src/components/DownloadProgressCards.tsx +++ b/openless-all/app/src/features/downloads/DownloadProgressCards.tsx @@ -2,9 +2,9 @@ // subscription independent of the card rendering and exit lifecycle. import { AnimatePresence, motion } from 'framer-motion'; import { useTranslation } from 'react-i18next'; -import { useReducedMotion } from '../lib/motion'; -import { Icon } from './Icon'; -import type { ProgressItem } from './GlobalDownloadProgress'; +import { useReducedMotion } from '../../lib/motion'; +import { Icon } from '../../components/Icon'; +import type { ProgressItem } from './useDownloadJobs'; export default function DownloadProgressCards({ visible, diff --git a/openless-all/app/src/features/downloads/GlobalDownloadProgress.tsx b/openless-all/app/src/features/downloads/GlobalDownloadProgress.tsx new file mode 100644 index 000000000..7027bfbd0 --- /dev/null +++ b/openless-all/app/src/features/downloads/GlobalDownloadProgress.tsx @@ -0,0 +1,38 @@ +import './downloads.css'; + +// Host jobs outlive settings. Experimental downloads use the same authoritative +// snapshot and cancellation route as their switches, not the retired Qwen API. +import { lazy, Suspense, useRef } from 'react'; +import { ViewportPortal } from '../../ui/layout/AppViewport'; +import { useTranslation } from 'react-i18next'; +import { useDownloadJobs } from './useDownloadJobs'; +export type { ProgressItem } from './useDownloadJobs'; +const DownloadProgressCards = lazy(() => import('./DownloadProgressCards')); + +export function GlobalDownloadProgress() { + const { t } = useTranslation(); + const { visible, pending, errors, handleCancel } = useDownloadJobs(); + const activated = useRef(false); + if (visible.length) activated.current = true; + if (!activated.current) return null; + return ( + + + {t('localAsr.downloading')} +
+ ) : null + } + > + + + + ); +} diff --git a/openless-all/app/src/features/downloads/downloads.css b/openless-all/app/src/features/downloads/downloads.css new file mode 100644 index 000000000..5526655c2 --- /dev/null +++ b/openless-all/app/src/features/downloads/downloads.css @@ -0,0 +1,5 @@ +.ol-viewport-portals > .ol-global-downloads { + position: absolute; + max-width: min(320px, calc(100% - 28px)); + pointer-events: auto; +} diff --git a/openless-all/app/src/features/downloads/useDownloadJobs.ts b/openless-all/app/src/features/downloads/useDownloadJobs.ts new file mode 100644 index 000000000..543da9b6a --- /dev/null +++ b/openless-all/app/src/features/downloads/useDownloadJobs.ts @@ -0,0 +1,180 @@ +import { useEffect, useRef, useState } from 'react'; +import { listenModelProgress } from '../../data/model-progress'; +import { getRuntimeOS, isTauriHost } from '../../runtime/environment'; +import { + cancelFoundryLocalAsrPrepare, + cancelLocalAsrDownload, + cancelSherpaOnnxAsrDownload, + type LocalAsrDownloadProgress, +} from '../../api/local-asr'; +import { + downloadPercent, + experimentalAsrModelFromDownloadId, + experimentalAsrName, + type ExperimentalAsrModel, +} from '../../lib/experimentalAsr'; +import { useExperimentalAsr } from '../../lib/useExperimentalAsr'; + +type Engine = 'qwen3' | 'sherpa' | 'foundry' | 'experimental'; +export interface ProgressItem { + key: string; + id: string; + name: string; + percent: number | null; + engine: Engine; + model?: ExperimentalAsrModel; + phase?: string; +} +const TERMINAL = new Set(['finished', 'cancelled', 'failed']); + +export function useDownloadJobs() { + const experimental = useExperimentalAsr(getRuntimeOS() === 'mac'); + const [items, setItems] = useState>({}); + const [pending, setPending] = useState([]); + const [errors, setErrors] = useState>({}); + const cancelledJobs = useRef(new Set()); + const generations = useRef(new Map()); + const cancelling = useRef(new Map()); + + useEffect(() => { + if (!isTauriHost()) return; + const unlistens: Array<() => void> = []; + let cancelled = false; + const update = (item: ProgressItem, phase: string) => { + if (cancelled) return; + if (phase === 'started') { + generations.current.set(item.key, (generations.current.get(item.key) ?? 0) + 1); + if (cancelling.current.delete(item.key)) { + setPending((previous) => previous.filter((key) => key !== item.key)); + } + } + if (phase === 'started' || TERMINAL.has(phase)) cancelledJobs.current.delete(item.key); + setItems((previous) => { + if (TERMINAL.has(phase)) { + const next = { ...previous }; + delete next[item.key]; + return next; + } + if (cancelledJobs.current.has(item.key)) return previous; + return { ...previous, [item.key]: item }; + }); + }; + void (async () => { + const keep = async (registration: Promise<() => void>) => { + const off = await registration; + if (cancelled) off(); + else unlistens.push(off); + }; + const download = (engine: 'qwen3' | 'sherpa') => (p: LocalAsrDownloadProgress) => { + // Generic model-store progress also includes experiments. Their IDs are + // not legacy model IDs and must never reach cancelLocalAsrDownload(). + if (experimentalAsrModelFromDownloadId(p.modelId)) return; + update( + { + key: `${engine}:${p.modelId}`, + id: p.modelId, + name: p.modelId, + percent: p.bytesTotal > 0 ? (p.bytesDownloaded / p.bytesTotal) * 100 : null, + engine, + }, + p.phase, + ); + }; + const results = await Promise.allSettled([ + keep(listenModelProgress('local-asr-download-progress', download('qwen3'))), + keep(listenModelProgress('sherpa-onnx-asr-download-progress', download('sherpa'))), + keep( + listenModelProgress('foundry-local-asr-prepare-progress', (p) => { + update( + { + key: `foundry:${p.modelAlias}`, + id: p.modelAlias, + name: p.label || p.modelAlias, + percent: p.percent ?? null, + engine: 'foundry', + }, + p.phase, + ); + }), + ), + ]); + for (const result of results) + if (result.status === 'rejected') + console.warn('[global-download-progress] subscribe failed', result.reason); + })().catch((error) => console.warn('[global-download-progress] subscribe failed', error)); + return () => { + cancelled = true; + for (const off of unlistens) off(); + }; + }, []); + + const handleCancel = async (item: ProgressItem) => { + if (cancelling.current.has(item.key)) return; + const token = Symbol(item.key); + cancelling.current.set(item.key, token); + const generation = generations.current.get(item.key); + const isCurrent = () => + cancelling.current.get(item.key) === token && + generations.current.get(item.key) === generation; + setPending((previous) => [...previous, item.key]); + setErrors((previous) => { + const next = { ...previous }; + delete next[item.key]; + return next; + }); + // Generic/Sherpa events have a Started boundary to admit a later retry. + // Foundry has no such event; keep its card until the native terminal event + // rather than fencing all future prepares for the same model alias. + if (item.engine === 'qwen3' || item.engine === 'sherpa') cancelledJobs.current.add(item.key); + try { + if (item.engine === 'experimental' && item.model) + await experimental.toggle(item.model, false); + else if (item.engine === 'qwen3') await cancelLocalAsrDownload(item.id); + else if (item.engine === 'sherpa') await cancelSherpaOnnxAsrDownload(item.id); + else await cancelFoundryLocalAsrPrepare(); + if (isCurrent() && item.engine !== 'foundry') { + setItems((previous) => { + const next = { ...previous }; + delete next[item.key]; + return next; + }); + } + } catch (error) { + if (!isCurrent()) return; + cancelledJobs.current.delete(item.key); + setErrors((previous) => ({ ...previous, [item.key]: String(error) })); + } finally { + if (isCurrent()) { + cancelling.current.delete(item.key); + setPending((previous) => previous.filter((key) => key !== item.key)); + } + } + }; + const visible: ProgressItem[] = [ + ...Object.values(items), + ...experimental.models + .filter( + (status) => + status.enabled && (status.phase === 'downloading' || status.phase === 'preparing'), + ) + .map((status): ProgressItem => ({ + key: `experimental:${status.model}`, + id: status.model, + model: status.model, + name: experimentalAsrName(status.model), + engine: 'experimental', + phase: status.phase, + percent: + status.phase === 'downloading' && status.downloadedBytes > 0 + ? downloadPercent(status) + : null, + })), + ]; + + return { + visible, + errors, + pending: [...pending, ...experimental.pending.map((model) => `experimental:${model}`)], + handleCancel, + }; +} diff --git a/openless-all/app/src/features/history/AudioRecordingPlayer.tsx b/openless-all/app/src/features/history/AudioRecordingPlayer.tsx new file mode 100644 index 000000000..e43caab06 --- /dev/null +++ b/openless-all/app/src/features/history/AudioRecordingPlayer.tsx @@ -0,0 +1,121 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { readAudioRecording } from '../../api/history'; +import { errorMessage } from './presentation'; +import { audioBytes } from './audio'; + +/** Rendered when session.hasAudioRecording is true: loading is triggered by the detail action + * menu, and once bytes arrive it switches to native audio controls. The Blob URL is revoked on + * unmount to avoid leaks. + * `onMissing` fires when the backend returns 'recording not found' (wav pruned), letting the + * parent hide the button for good so the user stops hitting the same error. */ +export function AudioRecordingPlayer({ + sessionId, + onMissing, + playRequest = 0, + onLoadingChange, +}: { + sessionId: string; + onMissing?: () => void; + playRequest?: number; + onLoadingChange?: (loading: boolean) => void; +}) { + const { t } = useTranslation(); + const [blobUrl, setBlobUrl] = useState(null); + const [status, setStatus] = useState<'idle' | 'loading' | 'ready' | 'error'>('idle'); + const [errorText, setErrorText] = useState(null); + const mountedRef = useRef(true); + const blobUrlRef = useRef(null); + const initialPlayRequestRef = useRef(playRequest); + + // Revoke the Blob URL on unmount to avoid a memory leak. + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + onLoadingChange?.(false); + if (blobUrlRef.current) { + URL.revokeObjectURL(blobUrlRef.current); + blobUrlRef.current = null; + } + }; + }, [onLoadingChange]); + + const clearBlobUrl = () => { + if (blobUrlRef.current) { + URL.revokeObjectURL(blobUrlRef.current); + blobUrlRef.current = null; + } + setBlobUrl(null); + }; + + const load = useCallback(async () => { + setStatus('loading'); + setErrorText(null); + onLoadingChange?.(true); + try { + const dataUrl = await readAudioRecording(sessionId); + if (!mountedRef.current) return; + // A Blob URL works in WebKit WebViews where data URLs can decode with zero duration. + const blob = new Blob([audioBytes(dataUrl)], { type: 'audio/wav' }); + const url = URL.createObjectURL(blob); + if (!mountedRef.current) { + URL.revokeObjectURL(url); + return; + } + if (blobUrlRef.current) URL.revokeObjectURL(blobUrlRef.current); + blobUrlRef.current = url; + setBlobUrl(url); + setStatus('ready'); + } catch (error) { + if (!mountedRef.current) return; + console.error('[history] load recording failed', error); + const msg = errorMessage(error); + if (msg.includes('recording not found') || msg.includes('not found')) { + onMissing?.(); + return; + } + setStatus('error'); + setErrorText(msg); + } finally { + if (mountedRef.current) onLoadingChange?.(false); + } + }, [onLoadingChange, onMissing, sessionId]); + + useEffect(() => { + // A newly mounted player may receive an old global counter while the user + // switches history entries. Only a request created after this instance + // mounted is allowed to trigger loading/autoplay. + if (playRequest <= initialPlayRequestRef.current) return; + void load(); + }, [load, playRequest]); + + if (status === 'ready' && blobUrl) { + return ( +
+
+ ); + } + return status === 'loading' || status === 'error' ? ( +
+ {status === 'loading' ? t('history.audioLoading') : errorText} +
+ ) : null; +} diff --git a/openless-all/app/src/features/history/History.tsx b/openless-all/app/src/features/history/History.tsx new file mode 100644 index 000000000..c972495e3 --- /dev/null +++ b/openless-all/app/src/features/history/History.tsx @@ -0,0 +1,282 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { DictationSession, StylePack } from '../../api/contracts'; +import { clearHistory } from '../../api/history'; +import { formatComboLabel } from '../../api/hotkeys'; +import { listStylePacks } from '../../api/style-packs'; +import { historyStore, useHistoryRecords } from '../../data/history'; +import { useHotkeySettings } from '../../data/preferences'; +import { getRuntimeEnvironment, getShortcutPlatform } from '../../runtime/environment'; +import { Btn, Card, PageHeader } from '../../pages/_atoms'; +import { useModalActive } from '../../ui/layout/AppViewport'; +import { useInteraction } from '../../ui/overlays/InteractionProvider'; +import { HistoryDetail } from './HistoryDetail'; +import { HistoryList } from './HistoryList'; +import { errorMessage, styleLabelFor, useModeLabel } from './presentation'; + +const emptyHistory: DictationSession[] = []; + +export function History({ quickNotesOnly = false }: { quickNotesOnly?: boolean } = {}) { + const { t, i18n } = useTranslation(); + const { confirm, notify } = useInteraction(quickNotesOnly ? 'quick-note' : 'history'); + const modalActive = useModalActive(); + const { prefs } = useHotkeySettings(); + const modeLabel = useModeLabel(); + const snapshot = useHistoryRecords(); + const shortKeys = getShortcutPlatform(); + const mobileHost = getRuntimeEnvironment().isMobile; + + const items = useMemo( + () => + quickNotesOnly + ? (snapshot.data?.filter((entry) => entry.source === 'quick_note') ?? emptyHistory) + : (snapshot.data ?? emptyHistory), + [quickNotesOnly, snapshot.data], + ); + const loading = snapshot.data === null && snapshot.loading; + const loadError = snapshot.error === null ? null : errorMessage(snapshot.error); + const [actionError, setActionError] = useState(null); + const [clearing, setClearing] = useState(false); + const [query, setQuery] = useState(''); + const [debouncedQuery, setDebouncedQuery] = useState(''); + const [selectedId, setSelectedId] = useState(null); + const searchInputRef = useRef(null); + const grid = useRef(null); + const [mobile, setMobile] = useState(mobileHost); + const [mobileDetailOpen, setMobileDetailOpen] = useState(false); + const refreshedByUser = useRef(false); + const clearRequest = useRef(false); + + useLayoutEffect(() => { + const panel = grid.current; + if (!panel) return; + const fit = (width: number) => { + const next = mobileHost || width < 690; + setMobile(next); + if (!next) setMobileDetailOpen(true); + }; + fit(panel.clientWidth); + if (typeof ResizeObserver !== 'function') return; + const observer = new ResizeObserver(([entry]) => fit(entry.contentRect.width)); + observer.observe(panel); + return () => observer.disconnect(); + }, [mobileHost]); + + const [allPacks, setAllPacks] = useState(null); + const [packsError, setPacksError] = useState(null); + useEffect(() => { + let cancelled = false; + void listStylePacks().then( + (packs) => { + if (!cancelled) setAllPacks(packs); + }, + (error: unknown) => { + if (!cancelled) setPacksError(errorMessage(error)); + }, + ); + return () => { + cancelled = true; + }; + }, []); + + const refresh = useCallback( + async (withNotice: boolean) => { + if (withNotice && refreshedByUser.current) return; + if (withNotice) refreshedByUser.current = true; + try { + const result = await historyStore.refreshRecords(); + if (withNotice) { + notify( + result.error === null + ? { message: t('common.refreshed'), state: 'saved' } + : { message: t('common.operationFailed'), state: 'failed', durationMs: 3500 }, + ); + } + } finally { + if (withNotice) refreshedByUser.current = false; + } + }, + [notify, t], + ); + + useEffect(() => { + const timer = window.setTimeout(() => setDebouncedQuery(query), 300); + return () => window.clearTimeout(timer); + }, [query]); + + useEffect(() => { + if (modalActive) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.defaultPrevented || event.repeat || event.altKey || event.shiftKey) return; + if (!(shortKeys.isMac ? event.metaKey : event.ctrlKey)) return; + if (event.key.toLowerCase() === 'k' && searchInputRef.current) { + event.preventDefault(); + searchInputRef.current.focus(); + } else if (event.key.toLowerCase() === 'r') { + event.preventDefault(); + void refresh(true); + } + }; + window.addEventListener('keydown', onKeyDown); + return () => window.removeEventListener('keydown', onKeyDown); + }, [modalActive, refresh, shortKeys.isMac]); + + const filtered = useMemo(() => { + const term = debouncedQuery.trim().toLowerCase(); + if (!term) return items; + return items.filter( + ({ rawTranscript, finalText }) => + rawTranscript.toLowerCase().includes(term) || finalText.toLowerCase().includes(term), + ); + }, [items, debouncedQuery]); + const item = filtered.find((entry) => entry.id === selectedId) ?? filtered[0]; + const styleLabel = (entry: DictationSession) => styleLabelFor(entry, allPacks, modeLabel); + const clearableCount = items.filter((entry) => entry.source !== 'quick_note').length; + const binding = quickNotesOnly ? prefs?.quickNoteHotkey : prefs?.dictationHotkey; + + const onClear = async () => { + if (!clearableCount || clearRequest.current) return; + clearRequest.current = true; + try { + if ( + !(await confirm({ + title: t('common.clear'), + description: t('history.confirmClear', { count: clearableCount }), + confirmLabel: t('common.clear'), + cancelLabel: t('common.cancel'), + icon: 'trash', + tone: 'danger', + })) + ) + return; + setClearing(true); + setActionError(null); + await clearHistory(); + notify({ + message: t('history.cleared', { + defaultValue: (i18n.resolvedLanguage ?? i18n.language).startsWith('zh') + ? '已清空历史' + : 'History cleared', + }), + state: 'deleted', + }); + } catch (error) { + const message = t('history.clearFailed', { err: errorMessage(error) }); + setActionError(message); + } finally { + clearRequest.current = false; + setClearing(false); + } + }; + + return ( +
+ + void refresh(true)}> + {t('common.refresh')} + + {!quickNotesOnly && ( + void onClear()} + disabled={clearing || clearableCount === 0} + > + {t('common.clear')} + + )} +
+ } + /> + {actionError && ( +

+ {actionError} +

+ )} +
+ {(!mobile || !mobileDetailOpen) && ( + { + setSelectedId(id); + if (mobile) setMobileDetailOpen(true); + }} + trigger={binding ? formatComboLabel(binding) : ''} + loading={loading} + loadError={loadError} + refresh={refresh} + styleLabel={styleLabel} + /> + )} + {(!mobile || mobileDetailOpen) && + (item ? ( + setMobileDetailOpen(false)} + quickNotesOnly={quickNotesOnly} + styleLabel={styleLabel} + allPacks={allPacks} + packsError={packsError} + notify={notify} + /> + ) : ( + + {mobile && ( + setMobileDetailOpen(false)} + > + {t('history.backToList')} + + )} +

+ {loading + ? t('common.loading') + : loadError + ? t('history.loadFailed', { err: loadError }) + : t('history.selectHint')} +

+
+ ))} +
+ + ); +} diff --git a/openless-all/app/src/features/history/HistoryActionMenu.tsx b/openless-all/app/src/features/history/HistoryActionMenu.tsx new file mode 100644 index 000000000..c714d825a --- /dev/null +++ b/openless-all/app/src/features/history/HistoryActionMenu.tsx @@ -0,0 +1,216 @@ +import { useRef } from 'react'; +import { Menu } from '@base-ui/react/menu'; +import { usePopupViewport } from '../../ui/layout/AppViewport'; +import './history.css'; +import { useTranslation } from 'react-i18next'; +import { Icon } from '../../components/Icon'; + +interface HistoryActionMenuProps { + hasAudioRecording: boolean; + audioLoading: boolean; + showShare: boolean; + canRetranscribe: boolean; + retranscribing: boolean; + canRepolish: boolean; + showSaveDirectory: boolean; + exportDirectory: string; + onPlay: () => void; + onExport: () => void; + onShare: () => void; + onRetranscribe: () => void; + onDelete: () => void | Promise; + onRepolish: () => void; + onChooseSaveDirectory: () => void; + onResetSaveDirectory: () => void; +} + +export function HistoryActionMenu({ + hasAudioRecording, + audioLoading, + showShare, + canRetranscribe, + retranscribing, + canRepolish, + showSaveDirectory, + exportDirectory, + onPlay, + onExport, + onShare, + onRetranscribe, + onDelete, + onRepolish, + onChooseSaveDirectory, + onResetSaveDirectory, +}: HistoryActionMenuProps) { + const { t } = useTranslation(); + const { boundary, container } = usePopupViewport(); + const pendingAction = useRef<(() => void | Promise) | null>(null); + const trigger = useRef(null); + const run = (action: () => void | Promise) => { + pendingAction.current = action; + }; + + return ( + { + if (open || !pendingAction.current) return; + const action = pendingAction.current; + pendingAction.current = null; + // A confirmation must restore focus to the menu trigger, not a removed menu item. + trigger.current?.focus({ preventScroll: true }); + void action(); + }} + > + + + + + + + {hasAudioRecording && ( + <> + run(onPlay)} + /> + run(onExport)} + /> + {showShare && ( + run(onShare)} + /> + )} +
+ + )} + {canRetranscribe && ( + run(onRetranscribe)} + /> + )} + run(onRepolish)} + /> + run(onDelete)} + /> + {showSaveDirectory && ( + <> +
+ run(onChooseSaveDirectory)} + /> + {exportDirectory && ( + run(onResetSaveDirectory)} + /> + )} + + )} + + + + + ); +} + +function HistoryActionMenuItem({ + icon, + label, + detail, + disabled = false, + danger = false, + onClick, +}: { + icon: string; + label: string; + detail?: string; + disabled?: boolean; + danger?: boolean; + onClick: () => void; +}) { + return ( + + + + {label} + {detail && ( + + {detail} + + )} + + + ); +} diff --git a/openless-all/app/src/features/history/HistoryDetail.tsx b/openless-all/app/src/features/history/HistoryDetail.tsx new file mode 100644 index 000000000..b67bc0fc2 --- /dev/null +++ b/openless-all/app/src/features/history/HistoryDetail.tsx @@ -0,0 +1,359 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { DictationSession, StylePack } from '../../api/contracts'; +import type { Interaction } from '../../api/interaction'; +import { LearnVocabulary } from '../../components/LearnVocabulary'; +import { Hint } from '../../components/Tooltip'; +import { AssistantMarkdown } from '../../components/chat/markdown'; +import { canRetranscribeHistoryEntry } from '../../lib/history-retranscribe'; +import { formatHistoryTime } from '../../lib/localeFormat'; +import { getRuntimeOS } from '../../runtime/environment'; +import { useHotkeySettings } from '../../data/preferences'; +import { Btn, Card, Pill } from '../../pages/_atoms'; +import { AudioRecordingPlayer } from './AudioRecordingPlayer'; +import { HistoryActionMenu } from './HistoryActionMenu'; +import { RepolishPanel, HistoryResultCard } from './RepolishPanel'; +import { formatDuration, formatStepDuration, TRUNCATED_PILL_STYLE } from './presentation'; +import { useHistoryEntryActions } from './useHistoryEntryActions'; + +interface Props { + item: DictationSession; + mobile: boolean; + onBack: () => void; + quickNotesOnly: boolean; + styleLabel: (entry: DictationSession) => string; + allPacks: StylePack[] | null; + packsError: string | null; + notify: Interaction['notify']; +} + +export function HistoryDetail({ + item, + mobile, + onBack, + quickNotesOnly, + styleLabel, + allPacks, + packsError, + notify, +}: Props) { + const { t, i18n } = useTranslation(); + const locale = i18n.resolvedLanguage || i18n.language; + const os = getRuntimeOS(); + const { prefs } = useHotkeySettings(); + const [showRawTranscript, setShowRawTranscript] = useState(false); + const [repolishOpen, setRepolishOpen] = useState(false); + const [playbackRequest, setPlaybackRequest] = useState(0); + const [audioLoading, setAudioLoading] = useState(false); + const { + audioMissing, + handleAudioMissing, + actionError, + retranscribing, + retranscriptionResult, + justCopied, + justCopiedRaw, + onCopy, + onExportAudio, + onShareAudio, + onRetranscribe, + onDelete, + onChooseExportDirectory, + onResetExportDirectory, + } = useHistoryEntryActions(item, quickNotesOnly, notify); + + return ( + + {mobile && ( +
+ + {t('history.backToList')} + +
+ )} +
+
+ + {formatHistoryTime(item.createdAt, locale)} + + + + {styleLabel(item)} + + + {item.pipelineMode === 'multimodal' && ( + + {t('history.multimodalPipeline')} + + )} + {/* "Recorded" prefix: distinct from the recognize/polish timings below — + recording time happens before the key release and must not be summed with + the pipeline steps (user feedback: "times don't add up"). */} + + {t('history.recorded', { + duration: formatDuration(item.durationMs, t, locale), + })} + +
+ setPlaybackRequest((request) => request + 1)} + onExport={() => void onExportAudio()} + onShare={() => void onShareAudio()} + onRetranscribe={() => void onRetranscribe()} + onDelete={onDelete} + onRepolish={() => setRepolishOpen(true)} + onChooseSaveDirectory={() => void onChooseExportDirectory()} + onResetSaveDirectory={() => void onResetExportDirectory()} + /> +
+ {/* The key must carry a component prefix: RepolishPanel below is a sibling at the + same level; if both used bare `item.id` the level would have duplicate keys. + React only warns (no error), but reconcile fails to match the old fiber — every + entry switch leaves a stale playback control in the DOM, and a long-open window + can stack up a whole column of them. */} + {actionError && ( +

+ {actionError} +

+ )} + {item.hasAudioRecording && !audioMissing && ( + + )} + {retranscriptionResult?.sessionId === item.id && ( +
+ +
+ )} + {/* Pipeline detail keeps only the recognize / polish steps — left column: step + name, middle column: provider·model, right column: step duration/status. + Insertion is a foreground-delivery detail and is not shown in the note content + area. */} +
+ {(item.asrProvider || item.asrMs != null) && ( + <> + + {t('history.stepAsr')} + + + {[item.asrProvider, item.asrModel].filter(Boolean).join(' · ')} + + + {item.asrMs != null ? formatStepDuration(item.asrMs, t, locale) : ''} + + + )} + {(item.llmProvider || item.llmModel || item.polishMs != null) && ( + <> + {t('history.stepPolish')} + + {[item.llmProvider, item.llmModel].filter(Boolean).join(' · ')} + + + {item.polishMs != null ? formatStepDuration(item.polishMs, t, locale) : ''} + + + )} +
+ {/* Default to showing only the polished result; the raw text can still be + expanded on demand, sparing users two duplicate columns every time. */} +
+ {/* The polish result box is de-blued too: neutral surface-2 fill + thin + outline. */} +
+
+ + + {t('history.stepPolish')} · {styleLabel(item)} + + + + {item.rawTranscript && ( + setShowRawTranscript((visible) => !visible)} + > + {showRawTranscript + ? t('history.hideRaw', '隐藏原文') + : t('history.showRaw', '查看原文')} + + )} + void onCopy(false)} + > + {justCopied ? t('common.copied') : t('common.copy')} + + +
+
+ + +
+
+ {showRawTranscript && ( +
+
+ + {t('history.stepAsr')} + + {item.rawTranscript && ( + void onCopy(true)} + > + {justCopiedRaw ? t('common.copied') : t('common.copy')} + + )} +
+

+ {item.rawTranscript || t('history.rawEmpty')} +

+
+ )} +
+ {/* Repolish: run the LLM again on this entry's raw text. No raw text means + nothing to repolish (failed transcription entries) — the whole block is not + rendered; QA entries' raw text is the question, not text to polish, so they are + not rendered either. The key resets result and state when switching entries, so + the previous entry's result does not linger under the new one; the prefix + distinguishes it from the player's key above (duplicate same-level keys would + leave stale nodes). */} + {repolishOpen && + (item.rawTranscript.trim() || quickNotesOnly) && + item.errorCode !== 'qaSession' && ( + setRepolishOpen(false)} + persistOnApply={quickNotesOnly} + key={`repolish-${item.id}`} + /> + )} +
+ ); +} diff --git a/openless-all/app/src/features/history/HistoryList.tsx b/openless-all/app/src/features/history/HistoryList.tsx new file mode 100644 index 000000000..41ef42102 --- /dev/null +++ b/openless-all/app/src/features/history/HistoryList.tsx @@ -0,0 +1,213 @@ +import type { RefObject } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { DictationSession } from '../../api/contracts'; +import { Icon } from '../../components/Icon'; +import { formatHistoryTime } from '../../lib/localeFormat'; +import { Btn, Card, Pill } from '../../pages/_atoms'; +import { formatDuration, historyTitle, TRUNCATED_PILL_STYLE } from './presentation'; + +interface Props { + searchInputRef: RefObject; + searchShortcut: string; + query: string; + debouncedQuery: string; + onQuery: (query: string) => void; + filtered: DictationSession[]; + selectedId?: string; + onSelect: (id: string) => void; + trigger: string; + loading: boolean; + loadError: string | null; + refresh: (notify: boolean) => Promise; + styleLabel: (session: DictationSession) => string; +} + +export function HistoryList({ + searchInputRef, + searchShortcut, + query, + debouncedQuery, + onQuery, + filtered, + selectedId, + onSelect, + trigger, + loading, + loadError, + refresh, + styleLabel, +}: Props) { + const { t, i18n } = useTranslation(); + const locale = i18n.resolvedLanguage || i18n.language; + return ( + + {/* The left column is one scroll container; the search box sticks to the top with an + opaque background — the list scrolls underneath it. Style filter chips and the + "N entries" count row are dropped; only search remains. */} +
+
+
+ + onQuery(e.target.value)} + placeholder={t('history.searchPlaceholder', { shortcut: searchShortcut })} + aria-label={t('history.searchPlaceholder', { shortcut: searchShortcut })} + style={{ + flex: 1, + minWidth: 0, + outline: 'none', + border: 0, + background: 'transparent', + fontSize: 12, + color: 'var(--ol-ink-1)', + fontFamily: 'inherit', + }} + /> +
+
+
+ {loading && ( +
+ {t('common.loading')} +
+ )} + {!loading && loadError && ( +
+ {t('history.loadFailed', { err: loadError })} + void refresh(true)}> + {t('history.retry')} + +
+ )} + {!loading && !loadError && filtered.length === 0 && ( +
+ {debouncedQuery.trim() + ? t('history.searchNoMatch', { query: debouncedQuery.trim() }) + : t('history.empty', { trigger })} +
+ )} + {filtered.map((s) => ( + + ))} +
+
+
+ ); +} diff --git a/openless-all/app/src/features/history/RepolishPanel.tsx b/openless-all/app/src/features/history/RepolishPanel.tsx new file mode 100644 index 000000000..7ca47850a --- /dev/null +++ b/openless-all/app/src/features/history/RepolishPanel.tsx @@ -0,0 +1,341 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { DictationSession, StylePack } from '../../api/contracts'; +import { applyQuickNoteRepolish } from '../../api/history'; +import { repolish } from '../../api/style-packs'; +import { copyTextToClipboard } from '../../api/files'; +import { AssistantMarkdown } from '../../components/chat/markdown'; +import { Hint } from '../../components/Tooltip'; +import { SelectLite } from '../../components/ui/SelectLite'; +import { Btn, Pill } from '../../pages/_atoms'; +import { + defaultPackId, + packDisplayName, + resolveRepolishRetryPackIdWithFallback, +} from '../../lib/history-repolish'; +import { errorMessage, isTimeout, TRUNCATED_PILL_STYLE, useModeLabel } from './presentation'; + +interface RepolishResult { + /** Key of the result card. Repeated applies of the same style overwrite the previous one + * instead of stacking cards forever. */ + key: string; + title: string; + text: string; +} + +/** + * Repolish panel: run the LLM again on this history entry's **raw text**. + * + * Both entries share one backend channel (`repolish`, stylePackId optional): + * - "Retry with original style" → prefer the id of the pack that produced this entry (falling + * back to the currently active style when the pack is deleted / old history / not loaded). + * Rerunning with the same style is the control experiment that tells whether the previous + * result was model jitter or stable behavior — what the user really wants when they say + * "the AI recognized it wrong". + * - "Apply" → pass the selected pack id, to see the same text in a different style. + * + * Results are shown only for this viewing session and are not written back to the history entry: + * the entry's finalText is "what was actually inserted at the time", a factual record that a + * later trial must not overwrite. The hint at the top of the panel says so directly. + * + * Note this reruns polish only, not recognition — history without an archived recording can only + * use the raw text. The "retranscribe" entry point is open to all legacy ASR entries that still + * have a recording. + */ +export function RepolishPanel({ + session, + mobile, + allPacks, + packsError, + onClose, + persistOnApply, +}: { + session: DictationSession; + mobile: boolean; + /** **All** style packs loaded at the History top level (including disabled); null = loading. */ + allPacks: StylePack[] | null; + packsError: string | null; + onClose: () => void; + persistOnApply: boolean; +}) { + const { t } = useTranslation(); + const MODE_LABEL = useModeLabel(); + const [selectedPackId, setSelectedPackId] = useState(''); + const [running, setRunning] = useState<'retry' | 'apply' | null>(null); + const [applyingKey, setApplyingKey] = useState(null); + const [error, setError] = useState(null); + const [results, setResults] = useState([]); + const canRun = session.rawTranscript.trim().length > 0; + + // List enabled packs only: disabled packs do not participate in polish elsewhere either; + // listing them here would let "Apply" use a style the user believes is turned off. + const packs = useMemo(() => (allPacks ? allPacks.filter((p) => p.enabled) : null), [allPacks]); + + useEffect(() => { + if (!packs) return; + setSelectedPackId((current) => current || defaultPackId(packs)); + }, [packs]); + + const run = async (kind: 'retry' | 'apply') => { + // Retry prefers the original pack that produced this entry; if deleted / old history / not + // loaded, fall back explicitly to the active pack (then the first available one) — keeping + // the frontend label consistent with actual execution instead of letting the backend walk + // its None fallback chain. + const packId = + kind === 'apply' + ? selectedPackId + : resolveRepolishRetryPackIdWithFallback(session, allPacks, packs ?? []); + if (!canRun || (kind === 'apply' && !packId)) return; + setRunning(kind); + setError(null); + try { + const text = await repolish(session.rawTranscript, session.mode, packId); + // Use allPacks rather than packs to look up the name: retrying with a disabled original + // pack still shows its real name in the title. + const pack = packId ? allPacks?.find((p) => p.id === packId) : undefined; + const result: RepolishResult = { + key: packId ?? '__retry__', + title: pack + ? t('history.repolish.resultTitle', { name: packDisplayName(pack, MODE_LABEL) }) + : t('history.repolish.retryResultTitle'), + text, + }; + // The same key overwrites the old result; a new key is prepended — the latest trial stays + // closest to the action area. + setResults((prev) => [result, ...prev.filter((r) => r.key !== result.key)]); + } catch (err) { + console.error('[history] repolish failed', err); + const msg = errorMessage(err); + // The backend passes LLMError::Timeout through as the bare string "timeout"; showing it + // directly tells the user nothing — "Repolish failed: timeout" reads like the feature is + // broken when the actual cause is the current LLM provider not responding within 30s + // (especially common in the free model pool). Use a message the user can act on. + setError( + isTimeout(msg) ? t('history.repolish.timeout') : t('history.repolish.failed', { err: msg }), + ); + } finally { + setRunning(null); + } + }; + + const applyResult = async (result: RepolishResult) => { + if (!persistOnApply) return; + setApplyingKey(result.key); + setError(null); + try { + await applyQuickNoteRepolish( + session.id, + result.text, + result.key === '__retry__' ? (session.stylePackId ?? undefined) : result.key, + ); + setError(null); + } catch (err) { + setError(errorMessage(err)); + } finally { + setApplyingKey(null); + } + }; + + return ( +
+
+ + {t('history.repolish.title')} + + + {results.length > 0 && ( + setResults([])}> + {t('history.repolish.clear')} + + )} + + {t('common.close')} + + +
+ +
0 ? 14 : 0, + }} + > + {!canRun && ( +
+ {t('quickNote.repolishNeedsTranscript', 'Re-transcribe the audio before repolishing.')} +
+ )} + void run('retry')} + > + {running === 'retry' ? t('history.repolish.retrying') : t('history.repolish.retry')} + + + {packsError ? ( + + {t('history.repolish.packsLoadFailed', { err: packsError })} + + ) : packs && packs.length === 0 ? ( + + {t('history.repolish.noPacks')} + + ) : ( + <> + {/* Use the official SelectLite consistently; no more mixing in a native { + const next = { ...draftRef.current, [field]: Number(event.target.value) }; + draftRef.current = next; + setDraft(next); + }} + onPointerUp={() => onChange(draftRef.current)} + onKeyUp={() => onChange(draftRef.current)} + /> + + {draft[field] as number} + {suffix} + +
+ + ); + const stageLabels: Record = { + acousticEchoCancellation: label('aec', 'Echo cancellation'), + noiseReduction: label('noise', 'Noise reduction'), + dereverb: label('dereverb', 'Comb filter'), + equalizer: label('equalizer', 'Equalizer'), + amplifier: label('gain', 'Input gain'), + agc: label('agc', 'Automatic gain'), + vad: label('vad', 'Speech gate'), + }; + const moveStage = (index: number, direction: number) => { + const order = [...draft.processingOrder]; + const target = index + direction; + if (target < 0 || target >= order.length) return; + [order[index], order[target]] = [order[target], order[index]]; + save({ processingOrder: order }); + }; + const body = ( + <> +

+ {label( + 'description', + 'RNNoise is lightweight; PureVox offers model-based noise reduction with higher CPU use. Changes apply to the next recording.', + )} +

+ + save({ aecMode: v as AudioDspConfig['aecMode'] })} + options={[ + { value: 'off', label: label('aecOff', 'Off') }, + { value: 'light', label: label('aecLight', 'Light (low CPU)') }, + { value: 'model', label: label('aecModel', 'Model (stronger)') }, + ]} + /> + + {draft.aecMode === 'model' && + label( + 'aecModelHint', + 'The model cancels more echo but costs about 3x the CPU; prefer Light on older machines.', + )} + {isAndroid() && expanded && } + + save({ noiseReduction: v as AudioDspConfig['noiseReduction'] })} + options={[ + { value: 'off', label: label('off', 'Off') }, + { value: 'rnnoise', label: 'RNNoise' }, + { value: 'purevox', label: 'PureVox 6' }, + { value: 'spectral', label: label('spectral', 'Spectral subtraction') }, + ]} + /> + + {draft.noiseReduction !== 'off' && + slider('noiseStrength', label('strength', 'Noise reduction strength'), 0, 100, '%')} + {slider('gainDb', stageLabels.amplifier, -50, 50, ' dB')} + + save({ agcEnabled: !draft.agcEnabled })} /> + + {draft.agcEnabled && ( + <> + {slider('agcTarget', label('target', 'Target level'), 0, 100, '%')} + {slider('agcAttack', label('attack', 'Attack speed'), 1, 100)} + {slider('agcDecay', label('decay', 'Release speed'), 1, 100)} + + )} + + save({ vadEnabled: !draft.vadEnabled })} /> + + {draft.vadEnabled && + slider('vadThresholdDb', label('threshold', 'Speech gate threshold'), -100, 0, ' dB')} +
+ + {label('tone', 'Tone and room adjustments')} + +

+ {label( + 'combHint', + 'The comb filter follows MicYou’s simple delay subtraction. It can color speech; start at 0%.', + )} +

+ {slider('dereverbLevel', stageLabels.dereverb, 0, 100, '%')} + + save({ equalizerEnabled: !draft.equalizerEnabled })} + /> + + {draft.equalizerEnabled && ( + <> + + ({ + value: key, + label: label(`preset_${key}`, key), + })), + ]} + onChange={(key) => { + const bands = audioEqualizerPresets[key as keyof typeof audioEqualizerPresets]; + if (bands) save({ equalizerBandsDb: [...bands] }); + }} + /> + + {slider('equalizerPreampDb', label('preamp', 'Equalizer preamp'), -20, 20, ' dB')} +
+ {equalizerFrequencies.map((frequency, index) => ( + + ))} +
+ + )} +
+
+ + {label('order', 'Processing order')} + +
    + {draft.processingOrder.map((stage, index) => ( +
  1. + {stageLabels[stage]} + {' '} + +
  2. + ))} +
+
+ + + ); + if (page) return body; + return ( +
setExpanded(event.currentTarget.open)} + > + + {label('title', 'Speech enhancement settings')} + + {body} +
+ ); +} diff --git a/openless-all/app/src/features/input/ExpressionLearningSection.tsx b/openless-all/app/src/features/input/ExpressionLearningSection.tsx new file mode 100644 index 000000000..81cf51b80 --- /dev/null +++ b/openless-all/app/src/features/input/ExpressionLearningSection.tsx @@ -0,0 +1,109 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + clearExpressionProfile, + getExpressionProfile, + type StableExpressionDirection, +} from '../../lib/ipc/expression'; +import { useHotkeySettings } from '../../data/preferences'; +import { Card } from '../../pages/_atoms'; +import { + btnGhostStyle, + ExperimentalSectionTitle, + SettingRow, + Toggle, +} from '../../pages/settings/shared'; + +export function ExpressionLearningSection() { + const { t } = useTranslation(); + const { prefs, updatePrefs } = useHotkeySettings(); + const [directions, setDirections] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(false); + useEffect(() => { + let alive = true; + void getExpressionProfile().then( + (directions) => { + if (alive) setDirections(directions); + }, + () => { + if (alive) setError(true); + }, + ); + return () => { + alive = false; + }; + }, []); + if (!prefs) return null; + return ( + + + {t('settings.expressionLearning.title')} + + + { + setBusy(true); + setError(false); + try { + await updatePrefs((current) => ({ ...current, expressionLearningEnabled: next })); + if (directions === null) setError(true); + } catch { + setError(true); + } finally { + setBusy(false); + } + }} + /> + +

+ {directions === null + ? error + ? '' + : t('common.loading') + : t('settings.expressionLearning.status', { count: directions.length })} +

+ {directions && directions.length > 0 && ( +
    + {directions.map((item) => ( +
  • + {t( + `settings.expressionLearning.${item.feature}${item.direction > 0 ? 'More' : 'Less'}`, + )} +
  • + ))} +
+ )} + +

+ {t('settings.expressionLearning.clearHint')} +

+ {error &&

{t('settings.expressionLearning.error')}

} +
+ ); +} diff --git a/openless-all/app/src/features/input/MicrophoneSelect.tsx b/openless-all/app/src/features/input/MicrophoneSelect.tsx new file mode 100644 index 000000000..f67f51b0d --- /dev/null +++ b/openless-all/app/src/features/input/MicrophoneSelect.tsx @@ -0,0 +1,171 @@ +// Microphone select — reuses the SelectLite "official box" dropdown: opening pops a microphone list where +// the selected item gets a check on the far right with a live level meter to its left. While the dropdown is +// open, the level of the selected device is monitored. + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { isTauriHost } from '../../runtime/environment'; +import { startMicrophoneLevelMonitor, stopMicrophoneLevelMonitor } from '../../api/input'; +import type { MicrophoneDevice } from '../../api/contracts'; +import { SelectLite, type SelectOption } from '../../components/ui/SelectLite'; +import { useMobileLayout } from '../../lib/useMobileLayout'; +import { isHarmonyHost } from '../../lib/harmonyBridge'; + +interface MicrophoneSelectProps { + devices: MicrophoneDevice[]; + /** Currently effective device name; '' = system default. */ + selectedName: string; + onSelect: (name: string) => void; + /** Callback when the dropdown opens — used to refresh the device list. */ + onOpen?: () => void; +} + +export function MicrophoneSelect({ + devices, + selectedName, + onSelect, + onOpen, +}: MicrophoneSelectProps) { + const { t } = useTranslation(); + const mobile = useMobileLayout(); + const [open, setOpen] = useState(false); + const [level, setLevel] = useState(0); + // Serialize start/stop — prevents listener / Rust-side state mismatch on rapid open-close. + const monitorQueueRef = useRef>(Promise.resolve()); + + const enqueueMonitorTask = useCallback((task: () => Promise) => { + const next = monitorQueueRef.current.catch(() => undefined).then(task); + monitorQueueRef.current = next.catch(() => undefined); + return next; + }, []); + + // Monitor the selected device's level while the dropdown is open; stop and reset on close. + useEffect(() => { + if (!open) { + setLevel(0); + return; + } + let unlisten: (() => void) | undefined; + let cancelled = false; + let timer: number | undefined; + + async function start() { + await enqueueMonitorTask(async () => { + try { + if (isHarmonyHost) { + const onLevel = (event: Event) => + setLevel(Math.max(0, Math.min(1, (event as CustomEvent).detail))); + window.addEventListener('openless:harmony-level', onLevel); + unlisten = () => window.removeEventListener('openless:harmony-level', onLevel); + if (!cancelled) await startMicrophoneLevelMonitor(selectedName); + if (cancelled) { + unlisten(); + unlisten = undefined; + await stopMicrophoneLevelMonitor(); + } + } else if (isTauriHost()) { + const { listen } = await import('@tauri-apps/api/event'); + if (cancelled) return; + const stopListening = await listen<{ level: number }>('microphone:level', (event) => { + setLevel(Math.max(0, Math.min(1, event.payload.level ?? 0))); + }); + if (cancelled) { + stopListening(); + return; + } + unlisten = stopListening; + await startMicrophoneLevelMonitor(selectedName); + if (cancelled) { + unlisten?.(); + unlisten = undefined; + await stopMicrophoneLevelMonitor(); + } + } else { + const tick = window.setInterval(() => { + setLevel(0.25 + Math.random() * 0.55); + }, 120); + if (cancelled) { + window.clearInterval(tick); + return; + } + unlisten = () => window.clearInterval(tick); + } + } catch (err) { + console.warn('[settings] microphone level monitor failed', err); + } + }); + } + + timer = window.setTimeout(() => { + void start(); + }, 140); + return () => { + cancelled = true; + if (timer !== undefined) window.clearTimeout(timer); + void enqueueMonitorTask(async () => { + unlisten?.(); + unlisten = undefined; + await stopMicrophoneLevelMonitor(); + }); + }; + }, [enqueueMonitorTask, open, selectedName]); + + // The selected entry (default mic or a device row) carries the level meter on its right; SelectLite appends the check after it. + const options = useMemo(() => { + const meter = ; + return [ + { + value: '', + label: t('settings.recording.microphoneDefault'), + trailing: selectedName === '' ? meter : undefined, + }, + ...devices.map((device) => ({ + value: device.name, + label: device.name, + trailing: selectedName === device.name ? meter : undefined, + })), + ]; + }, [devices, level, selectedName, t]); + + return ( + { + setOpen(next); + if (next) onOpen?.(); + }} + style={{ width: mobile ? '100%' : 200, maxWidth: '100%', minWidth: 0 }} + /> + ); +} + +function LevelMeter({ level }: { level: number }) { + const amplified = Math.min(1, Math.max(0, level * 4.5)); + const bars = [0.4, 0.7, 1, 0.7, 0.4]; + return ( + + {bars.map((weight, index) => { + const intensity = Math.min(1, amplified * (0.85 + weight * 0.35)); + const height = 4 + intensity * (10 * weight); + return ( + 0.08 ? 'var(--ol-blue)' : 'rgba(0,0,0,0.14)', + opacity: 0.4 + intensity * 0.6, + transition: 'height 70ms linear, opacity 90ms ease, background 120ms ease', + }} + /> + ); + })} + + ); +} diff --git a/openless-all/app/src/features/input/PermissionsSection.tsx b/openless-all/app/src/features/input/PermissionsSection.tsx new file mode 100644 index 000000000..61d48cf20 --- /dev/null +++ b/openless-all/app/src/features/input/PermissionsSection.tsx @@ -0,0 +1,385 @@ +// Permissions / connectivity panel: microphone / accessibility / global hotkey / Windows IME / network. +// Normal states use localized labels; failed native checks retain their diagnostic details. + +import { useEffect, useState, type CSSProperties } from 'react'; +import { useTranslation } from 'react-i18next'; +import { AndroidPermissionsPanel } from '@android/components/AndroidPermissionsPanel'; +import { Icon } from '../../components/Icon'; +import { + checkAccessibilityPermission, + checkMicrophonePermission, + openSystemSettings, + requestAccessibilityPermission, + requestMicrophonePermission, + resetAccessibilityPermissionAndRestartApp, +} from '../../api/permissions'; +import { checkNetwork } from '../../api/input'; +import { getHotkeyStatus, getWindowsImeStatus } from '../../api/hotkeys'; +import type { NetworkCheckResult } from '../../api/input'; +import { emitSaved } from '../../lib/savedEvent'; +import { getPlatformCapabilities } from '../../runtime/platform'; +import { useLayoutStack, useConservativeLayout } from '../../lib/useMobileLayout'; +import { + checkAndroidMicrophoneAccess, + requestAndroidMicrophoneAccess, +} from '@android/lib/androidMicrophonePermission'; +import type { + HotkeyStatus, + PermissionStatus, + PlatformCapabilities, + WindowsImeStatus, +} from '../../api/contracts'; +import { useHotkeySettings } from '../../data/preferences'; +import { REOPEN_ONBOARDING_EVENT } from '../../lib/desktopOnboarding'; +import { Btn, Card, Pill } from '../../pages/_atoms'; +import { SettingRow } from '../../pages/settings/shared'; + +const ANDROID_SETUP_WIZARD_COMPLETE_KEY = 'openless.androidSetupWizardComplete'; + +export function PermissionsSection() { + const { t } = useTranslation(); + const [accessibility, setAccessibility] = useState('loading'); + const [microphone, setMicrophone] = useState('loading'); + const [hotkey, setHotkey] = useState(null); + const [windowsIme, setWindowsIme] = useState(null); + const [network, setNetwork] = useState(null); + const [platformCaps, setPlatformCaps] = useState(null); + const { capability } = useHotkeySettings(); + const baseLayoutStack = useLayoutStack(); + const conservative = useConservativeLayout(); + const stackLayout = baseLayoutStack || conservative; + const permissionActionsStyle: CSSProperties = { + display: 'flex', + flexDirection: conservative ? 'column' : 'row', + alignItems: conservative ? 'flex-start' : 'center', + justifyContent: stackLayout ? 'flex-start' : 'flex-end', + width: '100%', + flexWrap: conservative ? 'nowrap' : 'wrap', + minWidth: 0, + gap: 8, + }; + + useEffect(() => { + void getPlatformCapabilities().then(setPlatformCaps); + }, []); + + const refreshPermissions = async () => { + const [a, m] = await Promise.all([ + checkAccessibilityPermission(), + platformCaps?.platform === 'android' + ? checkAndroidMicrophoneAccess() + : checkMicrophonePermission(), + ]); + setAccessibility(a); + setMicrophone(m); + }; + + const refreshHotkey = async () => { + setHotkey(await getHotkeyStatus()); + }; + + const refreshWindowsIme = async () => { + setWindowsIme(await getWindowsImeStatus()); + }; + + const refreshNetwork = async () => { + try { + setNetwork(await checkNetwork()); + } catch { + setNetwork({ online: false, latencyMs: null }); + } + }; + + useEffect(() => { + refreshPermissions(); + if (platformCaps?.supportsDesktopHotkey === true) { + refreshHotkey(); + } + if (platformCaps?.platform !== 'android') { + refreshWindowsIme(); + } + refreshNetwork(); + // issue #470: hotkey status became purely event-driven, removing the per-second poll and + // relying on the focus/visibilitychange refreshes below. The microphone check briefly opens + // an input stream, so per-second probing would flicker the privacy indicator. + const permissionId = window.setInterval(() => { + if (!document.hidden) refreshPermissions(); + }, 10000); + const networkId = window.setInterval(() => { + if (!document.hidden) refreshNetwork(); + }, 30000); + const refreshAll = () => { + refreshPermissions(); + if (platformCaps?.supportsDesktopHotkey === true) { + refreshHotkey(); + } + if (platformCaps?.platform !== 'android') { + refreshWindowsIme(); + } + refreshNetwork(); + }; + const onFocus = () => refreshAll(); + const onVisibility = () => { + if (document.visibilityState === 'visible') refreshAll(); + }; + window.addEventListener('focus', onFocus); + document.addEventListener('visibilitychange', onVisibility); + return () => { + window.clearInterval(permissionId); + window.clearInterval(networkId); + window.removeEventListener('focus', onFocus); + document.removeEventListener('visibilitychange', onVisibility); + }; + }, [platformCaps?.platform, platformCaps?.supportsDesktopHotkey]); + + const reRequestAccessibility = async () => { + const result = await requestAccessibilityPermission(); + // If the TCC prompt was denied (or previously denied and no longer shown), guide the user to system settings. + if (result !== 'granted') { + await openSystemSettings('accessibility'); + } + refreshPermissions(); + }; + + const reRequestMicrophone = async () => { + const isAndroid = platformCaps?.platform === 'android'; + if (isAndroid && (microphone === 'denied' || microphone === 'restricted')) { + await openSystemSettings('microphone'); + await refreshPermissions(); + return; + } + const status = isAndroid + ? await requestAndroidMicrophoneAccess() + : await requestMicrophonePermission(); + setMicrophone(status); + if (!isAndroid && (status === 'denied' || status === 'restricted')) { + await openSystemSettings('microphone'); + } + await refreshPermissions(); + }; + + return ( + +
+
+ {t('settings.permissions.title')} +
+ {platformCaps?.platform === 'desktop' && ( + window.dispatchEvent(new Event(REOPEN_ONBOARDING_EVENT))} + > + {t('desktopGuide.reopen')} + + )} + {platformCaps?.platform === 'android' && ( + { + localStorage.removeItem(ANDROID_SETUP_WIZARD_COMPLETE_KEY); + window.location.reload(); + }} + > + {t('settings.permissions.rerunAndroidSetup')} + + )} +
+ +
+ + {microphone === 'noDevice' ? ( + + {t('common.retry')} + + ) : ( + microphone !== 'granted' && + microphone !== 'notApplicable' && + microphone !== 'loading' && ( + + {microphone === 'denied' || microphone === 'restricted' + ? t('settings.permissions.openSystem') + : t('settings.permissions.grant')} + + ) + )} +
+
+ {capability?.requiresAccessibilityPermission && platformCaps?.platform !== 'android' && ( + +
+ + {accessibility !== 'granted' && + accessibility !== 'notApplicable' && + accessibility !== 'loading' && ( + + {accessibility === 'denied' + ? t('settings.permissions.openSystem') + : t('settings.permissions.grant')} + + )} + {accessibility === 'denied' && ( + { + resetAccessibilityPermissionAndRestartApp().catch((error) => { + console.error('[settings] reset accessibility permission failed', error); + emitSaved('failed', t('common.operationFailed')); + }); + }} + > + {t('settings.permissions.restart')} + + )} +
+
+ )} + {platformCaps?.supportsDesktopHotkey === true && ( + +
+ {hotkey?.state === 'failed' && hotkey.message && ( + + {hotkey.message} + + )} + +
+
+ )} + {platformCaps?.supportsOverlay && platformCaps.platform === 'android' && ( + + )} + {windowsIme?.state !== 'notWindows' && platformCaps?.platform !== 'android' && ( + +
+ {windowsIme && ( + + {t(`settings.permissions.windowsIme.${windowsIme.state}`)} + + )} + +
+
+ )} + +
+ {network && network.latencyMs != null && ( + {network.latencyMs}ms + )} + + {network && !network.online && ( + + {t('common.retry') ?? '重试'} + + )} +
+
+
+ ); +} + +function PermissionPill({ status }: { status: PermissionStatus | 'loading' }) { + const { t } = useTranslation(); + if (status === 'loading') { + return {t('settings.permissions.checking')}; + } + if (status === 'granted') { + return ( + + + {t('settings.permissions.granted')} + + ); + } + if (status === 'notApplicable') { + return {t('settings.permissions.notApplicable')}; + } + if (status === 'noDevice') { + return {t('settings.permissions.micNoDevice')}; + } + if (status === 'denied' || status === 'restricted') { + return {t('settings.permissions.denied')}; + } + return {t('settings.permissions.indeterminate')}; +} + +function HotkeyStatusPill({ status }: { status: HotkeyStatus | null }) { + const { t } = useTranslation(); + if (!status) { + return {t('settings.permissions.checking')}; + } + if (status.state === 'installed') { + return ( + + + {t('settings.permissions.hotkeyInstalled')} + + ); + } + if (status.state === 'starting') { + return {t('settings.permissions.hotkeyStarting')}; + } + return {t('settings.permissions.hotkeyFailed')}; +} + +function WindowsImeStatusPill({ status }: { status: WindowsImeStatus | null }) { + const { t } = useTranslation(); + if (!status) { + return {t('settings.permissions.checking')}; + } + if (status.state === 'installed') { + return ( + + + {t('settings.permissions.windowsImeInstalled')} + + ); + } + return {t('settings.permissions.windowsImeUnavailable')}; +} + +function NetworkStatusPill({ status }: { status: NetworkCheckResult | null }) { + const { t } = useTranslation(); + if (!status) { + return {t('settings.permissions.checking')}; + } + if (status.online) { + return ( + + + {t('settings.permissions.networkOk')} + + ); + } + return {t('settings.permissions.networkOffline') ?? '不可用'}; +} diff --git a/openless-all/app/src/features/input/RecordingInputSection.tsx b/openless-all/app/src/features/input/RecordingInputSection.tsx new file mode 100644 index 000000000..0acf587af --- /dev/null +++ b/openless-all/app/src/features/input/RecordingInputSection.tsx @@ -0,0 +1,945 @@ +// Recording surfaces under General. One mount owns the device listeners. +// `microphone` is capture plus monitoring. `capsule` is the overlay style. +// `text` is insertion, clipboard, and startup. Those pages stay expanded. + +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { CapsuleStylePreview } from '../../components/OpenLessCapsule'; +import { parseCapsuleStyle } from '../../lib/capsuleLayout'; +import { ShortcutRecorder } from '../../components/ShortcutRecorder'; +import { playRecordStartCue } from '../../lib/audioCue'; +import { defaultDictationHotkey } from '../../lib/hotkey'; +import { getSherpaOnnxAsrCatalog } from '../../api/local-asr'; +import { isHotkeyModeMigrationNoticeActive } from '../../lib/hotkeyMigration'; +import { showWindowsSendInputNewlineMode } from '../../lib/windowsKeyboardListToggle'; +import { + isPlainTextInsertionActive, + pasteShortcutForPlainTextToggle, +} from '../../lib/plainTextInsertion'; +import { isTauriHost } from '../../runtime/environment'; +import { + getAutostartEnabled, + listMicrophoneDevices, + listenMicrophoneDeviceChanges, + listenVoiceActivationChanges, + setAutostartEnabled, +} from '../../api/input'; +import { setDictationHotkey } from '../../api/hotkeys'; +import { + isVoiceActivationModelMissing, + VOICE_ACTIVATION_MODEL_ALIAS, +} from '../../lib/voiceActivation'; +import { getPlatformCapabilities, getCachedPlatformCapabilities } from '../../runtime/platform'; +import type { + CapsuleStyle, + HotkeyMode, + MicrophoneDevice, + PasteShortcut, + PlatformCapabilities, + UserPreferences, + WindowsInsertionMode, + WindowsSendInputNewlineMode, + MacosNewlineMode, +} from '../../api/contracts'; +import { useHotkeySettings } from '../../data/preferences'; +import { SelectLite } from '../../components/ui/SelectLite'; + +import { Card, Btn } from '../../pages/_atoms'; +import { Segmented } from '../../components/ui/Segmented'; +import { SectionTitle, SettingRow, Toggle, inputStyle } from '../../pages/settings/shared'; +import { MicrophoneSelect } from './MicrophoneSelect'; +import { getRuntimeOS, type OS } from '../../runtime/environment'; + +/** Selectable silence durations (seconds) for "auto-stop after silence"; see issue #860. */ +const silenceAutoStopOptions = [1, 1.5, 2, 3, 4, 5]; + +export type RecordingSurface = 'microphone' | 'capsule' | 'text'; + +export function RecordingInputSection({ + forcedOs, + onOpenLocalModels, + surface = 'microphone', +}: { + forcedOs?: OS; + onOpenLocalModels?: () => void; + surface?: RecordingSurface; +} = {}) { + const { t } = useTranslation(); + const os = forcedOs ?? getRuntimeOS(); + const { prefs, capability, updatePrefs: savePrefs, refresh } = useHotkeySettings(); + const [platformCaps, setPlatformCaps] = useState( + getCachedPlatformCapabilities, + ); + const [microphoneDevices, setMicrophoneDevices] = useState([]); + const [microphoneDevicesLoaded, setMicrophoneDevicesLoaded] = useState(false); + const [microphoneDevicesError, setMicrophoneDevicesError] = useState(null); + const [voiceActivationModelMissing, setVoiceActivationModelMissing] = useState(false); + const voiceActivationStateObservedRef = useRef(false); + const deviceReadRevision = useRef(0); + + useEffect(() => { + let current = true; + void getPlatformCapabilities() + .then((caps) => { + if (current) setPlatformCaps(caps); + }) + .catch(() => {}); + return () => { + current = false; + }; + }, []); + + const loadMicrophoneDevices = useCallback( + async (signal?: { cancelled: boolean }, options: { showLoading?: boolean } = {}) => { + const request = ++deviceReadRevision.current; + if (options.showLoading ?? true) { + setMicrophoneDevicesLoaded(false); + } + setMicrophoneDevicesError(null); + try { + const devices = await listMicrophoneDevices(); + if (signal?.cancelled || deviceReadRevision.current !== request) return; + setMicrophoneDevices(devices); + setMicrophoneDevicesLoaded(true); + } catch (err) { + console.error('[settings] list microphone devices failed', err); + if (signal?.cancelled || deviceReadRevision.current !== request) return; + setMicrophoneDevices([]); + setMicrophoneDevicesError(err instanceof Error ? err.message : String(err)); + setMicrophoneDevicesLoaded(true); + } + }, + [], + ); + + useEffect(() => { + if (surface !== 'microphone') return; + const signal = { cancelled: false }; + let unlisten: (() => void) | undefined; + void (async () => { + try { + const stop = await listenMicrophoneDeviceChanges(() => { + if (!signal.cancelled) void loadMicrophoneDevices(signal, { showLoading: false }); + }); + if (signal.cancelled) stop(); + else unlisten = stop; + } catch (error) { + console.warn('[settings] microphone device subscription failed', error); + } + if (!signal.cancelled) await loadMicrophoneDevices(signal); + })(); + return () => { + signal.cancelled = true; + unlisten?.(); + }; + }, [loadMicrophoneDevices, surface]); + + useEffect(() => { + if (!isTauriHost() || os !== 'win') { + setVoiceActivationModelMissing(false); + return; + } + let cancelled = false; + let unlisten: (() => void) | undefined; + void listenVoiceActivationChanges((state) => { + if (cancelled) return; + voiceActivationStateObservedRef.current = true; + setVoiceActivationModelMissing(isVoiceActivationModelMissing(state)); + }) + .then((stop) => { + if (cancelled) stop(); + else unlisten = stop; + }) + .catch((error) => console.warn('[settings] voice activation subscription failed', error)); + return () => { + cancelled = true; + unlisten?.(); + }; + }, [os]); + + useEffect(() => { + if (os !== 'win' || !prefs?.voiceActivationEnabled) { + voiceActivationStateObservedRef.current = false; + setVoiceActivationModelMissing(false); + return; + } + voiceActivationStateObservedRef.current = false; + let cancelled = false; + void getSherpaOnnxAsrCatalog() + .then((catalog) => { + if (cancelled || voiceActivationStateObservedRef.current) return; + const model = catalog.find(({ alias }) => alias === VOICE_ACTIVATION_MODEL_ALIAS); + setVoiceActivationModelMissing(model?.cached === false); + }) + .catch(() => { + // The runtime event remains authoritative when the catalog cannot be read. + }); + return () => { + cancelled = true; + }; + }, [os, prefs?.voiceActivationEnabled]); + + useEffect(() => { + if (!prefs?.voiceActivationEnabled) setVoiceActivationModelMissing(false); + }, [prefs?.voiceActivationEnabled]); + + const saveWindowsInsertionPrefs = useCallback( + async (nextPrefs: UserPreferences) => { + try { + await savePrefs(nextPrefs); + } catch (error) { + // The shared settings provider already reports the save failure and + // rolls back its optimistic update; do not replace it with an obsolete + // keyboard-list error when changing the insertion method. + console.error('[settings] Windows insertion pref save failed', error); + await refresh(); + } + }, + [savePrefs, refresh], + ); + + // Read from the cached platform capabilities so the recording controls don't + // disappear for a frame on return. + const showDesktopHotkey = platformCaps?.supportsDesktopHotkey === true; + + if (!prefs || !capability) { + return ( + +
{t('common.loading')}
+
+ ); + } + + const isAndroid = platformCaps?.platform === 'android'; + const showDesktopInsert = showDesktopHotkey; + const showDesktopStartup = showDesktopHotkey; + const plainTextInsertionOn = isPlainTextInsertionActive(os === 'win', prefs.pasteShortcut); + const effectiveCapsuleDisplayMode = + os === 'win' || + prefs.capsuleDisplayMode === 'cursorScreen' || + prefs.capsuleDisplayMode === 'allScreens' + ? (prefs.capsuleDisplayMode ?? 'cursorScreen') + : 'cursorScreen'; + + const onCapsuleDisplayModeChange = (next: UserPreferences['capsuleDisplayMode']) => + savePrefs({ ...prefs, capsuleDisplayMode: next }); + + const onModeChange = (mode: HotkeyMode) => + savePrefs({ ...prefs, hotkey: { ...prefs.hotkey, mode } }); + const onShowCapsuleChange = (showCapsule: boolean) => savePrefs({ ...prefs, showCapsule }); + const onMuteDuringRecordingChange = (muteDuringRecording: boolean) => + savePrefs({ ...prefs, muteDuringRecording }); + const onAudioCueChange = (audioCueOnRecord: boolean) => savePrefs({ ...prefs, audioCueOnRecord }); + const onLowLatencyDictationChange = (lowLatencyDictationEnabled: boolean) => + savePrefs({ ...prefs, lowLatencyDictationEnabled }); + const onMicrophoneDeviceChange = (microphoneDeviceName: string) => + savePrefs({ ...prefs, microphoneDeviceName }); + const onRestoreClipboardChange = (restoreClipboardAfterPaste: boolean) => + savePrefs({ ...prefs, restoreClipboardAfterPaste }); + const onPasteShortcutChange = (pasteShortcut: PasteShortcut) => + savePrefs({ ...prefs, pasteShortcut }); + const onPlainTextInsertionChange = (on: boolean) => + savePrefs({ ...prefs, pasteShortcut: pasteShortcutForPlainTextToggle(on) }); + const onAllowNonTsfFallbackChange = (allowNonTsfInsertionFallback: boolean) => + savePrefs({ ...prefs, allowNonTsfInsertionFallback }); + const onWindowsInsertionModeChange = (windowsInsertionMode: WindowsInsertionMode) => + void saveWindowsInsertionPrefs({ + ...prefs, + windowsInsertionMode, + windowsSendInputInsertionOnly: windowsInsertionMode === 'sendInput', + }); + const onWindowsSendInputNewlineModeChange = ( + windowsSendInputNewlineMode: WindowsSendInputNewlineMode, + ) => savePrefs({ ...prefs, windowsSendInputNewlineMode }); + const onMacosNewlineModeChange = (macosNewlineMode: MacosNewlineMode) => + savePrefs({ ...prefs, macosNewlineMode }); + const onStartMinimizedChange = (startMinimized: boolean) => + savePrefs({ ...prefs, startMinimized }); + const onAutoUpdateCheckChange = (autoUpdateCheck: boolean) => + savePrefs({ ...prefs, autoUpdateCheck }); + + const choices: Array<[HotkeyMode, string]> = [ + ['toggle', t('settings.recording.modeToggle')], + ['hold', t('settings.recording.modeHold')], + ['auto', t('settings.recording.modeAuto')], + ]; + const preferredMicrophoneAvailable = Boolean( + prefs.microphoneDeviceName && + microphoneDevices.some((device) => device.name === prefs.microphoneDeviceName), + ); + const effectiveMicrophoneDeviceName = + prefs.microphoneDeviceName && (!microphoneDevicesLoaded || preferredMicrophoneAvailable) + ? prefs.microphoneDeviceName + : ''; + + return ( + <> + {surface === 'microphone' && ( + + + {t('settings.recording.captureGroupTitle')} + + {isHotkeyModeMigrationNoticeActive() && showDesktopHotkey && ( +
+
+ {t('settings.recording.migrationNoticeTitle')} +
+
+ {t('settings.recording.migrationNoticeDesc')} +
+
+ )} + {showDesktopHotkey && ( + + { + await setDictationHotkey(null); + await refresh(); + }} + onSave={async (binding) => { + await setDictationHotkey(binding); + // setDictationHotkey has already persisted and broadcast the preference + // change on the backend; refresh here to pull the latest, avoiding a full + // overwrite from the local snapshot that would clobber other preference + // changes made in the meantime. + await refresh(); + }} + onReset={async () => { + const binding = defaultDictationHotkey(); + await setDictationHotkey(binding); + await refresh(); + }} + /> + + )} + {showDesktopHotkey && ( + + ({ value, label }))} + /> + + )} + {showDesktopHotkey && ( + // "Auto-stop after silence" is only available in toggle mode. The outer container + // always renders: switching the mode from hold/auto to toggle pulls the whole + // group out from below, and switching away collapses it — the same grid 0fr→1fr + // animation as the toggle-controlled seconds row, no more "sudden pop-in". While + // collapsed the content stays in the DOM (overflow hidden), height animates to 0 + // and takes no layout space; inert removes the collapsed controls from tab order + // and the a11y tree (same as Collapsible; pr_agent feedback). +
+
+ + {/* The toggle row holds only the Toggle: move the seconds dropdown out of + this row to avoid jitter from the row widening when toggled. */} + savePrefs({ ...prefs, silenceAutoStopEnabled: next })} + /> + + {/* When enabled, expand the "silence duration" selector row below. Expand/collapse + uses a grid 0fr→1fr transition (nested in the outer container, pulled + out/collapsed together with it). The final height is fixed (SettingRow's own + height), so repeated toggling never jumps. */} +
+
+ + {/* Same visuals as the microphone dropdown: SelectLite default trigger + background + fixed 200px width → right edge aligns with "MacBook Air + Microphone" (control areas share the same start and width). */} + + savePrefs({ ...prefs, silenceAutoStopSeconds: Number(next) }) + } + options={silenceAutoStopOptions.map((value) => ({ + value: String(value), + label: t('settings.recording.silenceAutoStopSecondsValue', { value }), + }))} + ariaLabel={t('settings.recording.silenceAutoStopSecondsLabel')} + style={{ width: 200, maxWidth: '100%', minWidth: 0 }} + /> + +
+
+
+
+ )} + +
+ { + void loadMicrophoneDevices(undefined, { showLoading: false }); + }} + /> + {microphoneDevicesError && ( +
+ {t('settings.recording.microphoneLoadError', { message: microphoneDevicesError })} +
+ )} +
+
+
+ )} + + {surface === 'capsule' && !isAndroid && ( + + {t('settings.recording.capsuleGroupTitle')} + + + + {(os === 'mac' || os === 'win') && ( + + + void onCapsuleDisplayModeChange(next as UserPreferences['capsuleDisplayMode']) + } + options={[ + { + value: 'cursorScreen', + label: t('settings.recording.capsuleDisplayCursorScreen'), + }, + ...(os === 'win' + ? [ + { + value: 'primaryScreen', + label: t('settings.recording.capsuleDisplayPrimaryScreen'), + }, + { + value: 'foregroundWindowScreen', + label: t('settings.recording.capsuleDisplayForegroundWindowScreen'), + }, + ] + : []), + { value: 'allScreens', label: t('settings.recording.capsuleDisplayAllScreens') }, + ]} + ariaLabel={t('settings.recording.capsuleDisplayModeLabel')} + style={{ maxWidth: 240, minWidth: 200 }} + /> + + )} + +
+ savePrefs({ ...prefs, capsuleStyle: next as CapsuleStyle })} + label={t('settings.recording.capsuleStyleLabel')} + className="ol-capsule-style-segmented" + /> + +
+
+ <> + + savePrefs({ ...prefs, capsuleTranscriptEnabled: next })} + /> + + {(prefs.capsuleTranscriptEnabled ?? true) && ( + + + savePrefs({ ...prefs, capsuleTranscriptFontSize: Number(next) }) + } + options={[12, 14, 16, 18, 20].map((size) => ({ + value: String(size), + label: `${size}px`, + }))} + ariaLabel={t('settings.recording.capsuleTranscriptFontSize')} + /> + + )} + +
+ )} + + {surface === 'microphone' && ( + + {t('settings.recording.recognitionGroupTitle')} + + savePrefs({ ...prefs, stableTranscriptionEnabled: next })} + /> + + {showDesktopHotkey && os === 'win' && ( + <> + + + + + savePrefs({ ...prefs, voiceActivationEnabled: next })} + /> + + {prefs.voiceActivationEnabled && ( +
+
+ {t('settings.recording.voiceActivationLocalOnly')} +
+ {voiceActivationModelMissing && ( +
+ + {t('settings.recording.voiceActivationModelMissing')} + + {onOpenLocalModels && ( + + {t('settings.recording.voiceActivationDownloadZipformer')} + + )} +
+ )} + + savePrefs({ ...prefs, voiceActivationWakeEnabled: next })} + /> + + {prefs.voiceActivationWakeEnabled && ( + + savePrefs({ + ...prefs, + voiceActivationWakePhrase: event.currentTarget.value, + }) + } + style={{ ...inputStyle, width: '100%', margin: '2px 0 8px' }} + /> + )} + + + savePrefs({ ...prefs, voiceActivationFinishEnabled: next }) + } + /> + + {prefs.voiceActivationFinishEnabled && ( + + savePrefs({ + ...prefs, + voiceActivationFinishPhrase: event.currentTarget.value, + }) + } + style={{ ...inputStyle, width: '100%', margin: '2px 0 8px' }} + /> + )} + + + savePrefs({ ...prefs, voiceActivationTimeoutEnabled: next }) + } + /> + + {prefs.voiceActivationTimeoutEnabled && ( + + savePrefs({ + ...prefs, + voiceActivationTimeoutSeconds: Math.max( + 5, + Math.min(300, Number(event.currentTarget.value) || 30), + ), + }) + } + style={{ ...inputStyle, width: 90, marginTop: 2 }} + /> + )} +
+ )} + + )} + + + + +
+ + +
+
+
+ )} + + {surface === 'text' && showDesktopInsert && ( + + {t('settings.recording.insertGroupTitle')} + + + + {capability.adapter !== 'macEventTap' && ( + + onPasteShortcutChange(next as PasteShortcut)} + // Plain-text insertion owns Shift+Insert, so this control stays read-only. + disabled={plainTextInsertionOn} + options={ + plainTextInsertionOn + ? [ + { + value: 'shiftInsert', + label: t('settings.recording.pasteShortcutShiftInsert'), + }, + ] + : [ + { value: 'ctrlV', label: t('settings.recording.pasteShortcutCtrlV') }, + { + value: 'ctrlShiftV', + label: t('settings.recording.pasteShortcutCtrlShiftV'), + }, + ] + } + ariaLabel={t('settings.recording.pasteShortcutLabel')} + style={{ ...inputStyle, maxWidth: 220 }} + /> + + )} + {os === 'win' && capability.adapter !== 'macEventTap' && ( + + + + )} + {capability.adapter === 'windowsLowLevel' && ( + + onWindowsInsertionModeChange(next as WindowsInsertionMode)} + options={[ + { value: 'tsf', label: t('settings.recording.windowsInsertionModeTsf') }, + { + value: 'sendInput', + label: t('settings.recording.windowsInsertionModeSendInput'), + }, + { value: 'paste', label: t('settings.recording.windowsInsertionModePaste') }, + ]} + ariaLabel={t('settings.recording.windowsInsertionModeLabel')} + style={{ ...inputStyle, maxWidth: 260 }} + /> + + )} + {capability.adapter === 'windowsLowLevel' && + showWindowsSendInputNewlineMode( + prefs.windowsInsertionMode, + prefs.windowsSendInputInsertionOnly, + ) && ( + + + onWindowsSendInputNewlineModeChange(next as WindowsSendInputNewlineMode) + } + options={[ + { + value: 'enter', + label: t('settings.recording.windowsSendInputNewlineModeEnter'), + }, + { + value: 'shiftEnter', + label: t('settings.recording.windowsSendInputNewlineModeShiftEnter'), + }, + { + value: 'crlf', + label: t('settings.recording.windowsSendInputNewlineModeCrLf'), + }, + ]} + ariaLabel={t('settings.recording.windowsSendInputNewlineModeLabel')} + style={{ ...inputStyle, maxWidth: 260 }} + /> + + )} + {capability.adapter === 'macEventTap' && prefs.streamingInsert && ( + + onMacosNewlineModeChange(next as MacosNewlineMode)} + options={[ + { value: 'auto', label: t('settings.recording.macosNewlineModeAuto') }, + { + value: 'shiftReturn', + label: t('settings.recording.macosNewlineModeShiftReturn'), + }, + { value: 'lineFeed', label: t('settings.recording.macosNewlineModeLineFeed') }, + { value: 'return', label: t('settings.recording.macosNewlineModeReturn') }, + ]} + ariaLabel={t('settings.recording.macosNewlineModeLabel')} + style={{ ...inputStyle, maxWidth: 260 }} + /> + + )} + {capability.adapter === 'windowsLowLevel' && ( + + + + )} + {/* Streaming input: as the polish SSE stream arrives, keystrokes are simulated + character by character at the cursor to cut perceived latency. Falls back + automatically to one-shot insertion when conditions aren't met. It's an + "insertion behavior", hence grouped here. */} + + void savePrefs({ ...prefs, streamingInsert: next })} + /> + + + void savePrefs({ ...prefs, streamingInsertSaveClipboard: next })} + /> + + + )} + {surface === 'text' && showDesktopStartup && ( + + {t('settings.recording.startupGroupTitle')} + + + + + + + + + )} + + ); +} + +// Autostart state is owned by the operating system; it is intentionally not mirrored in prefs. +function AutostartRow() { + const { t } = useTranslation(); + const [enabled, setEnabled] = useState(false); + const [loaded, setLoaded] = useState(false); + // Error shown to the user when switching the plist / registry fails. null = no failure / + // the last operation succeeded. + const [error, setError] = useState(null); + + useEffect(() => { + if (!isTauriHost()) { + setLoaded(true); + return; + } + let cancelled = false; + getAutostartEnabled() + .then((v: boolean) => { + if (!cancelled) { + setEnabled(v); + setLoaded(true); + } + }) + .catch((err: unknown) => { + console.error('[autostart] isEnabled failed', err); + if (!cancelled) setLoaded(true); + }); + return () => { + cancelled = true; + }; + }, []); + + const onToggle = async (next: boolean) => { + setEnabled(next); + setError(null); + try { + await setAutostartEnabled(next); + } catch (err) { + console.error('[autostart] toggle failed', err); + setEnabled(!next); + setError(err instanceof Error ? err.message : String(err)); + } + }; + + return ( + +
+ {loaded ? : null} + {error && ( +
+ {t('settings.recording.startupAtBootError', { message: error })} +
+ )} +
+
+ ); +} diff --git a/openless-all/app/src/features/input/SelectionWorkspaceExtraControlsDialog.tsx b/openless-all/app/src/features/input/SelectionWorkspaceExtraControlsDialog.tsx new file mode 100644 index 000000000..ec676d093 --- /dev/null +++ b/openless-all/app/src/features/input/SelectionWorkspaceExtraControlsDialog.tsx @@ -0,0 +1,292 @@ +import { X } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import type { ReactNode } from 'react'; +import type { EditPlanFormat, UserPreferences } from '../../api/contracts'; +import { PresenceModal } from '../../components/ui/Modal'; +import { Segmented } from '../../components/ui/Segmented'; +import { useMobileLayout } from '../../lib/useMobileLayout'; +import { Toggle, inputStyle } from '../../pages/settings/shared'; + +const editPlanFormatOptions: Array<{ value: EditPlanFormat }> = [ + { value: 'xml' }, + { value: 'json' }, +]; + +interface SelectionWorkspaceExtraControlsDialogProps { + open: boolean; + autoIntent: boolean; + keywordsText: string; + editPlanFormat: EditPlanFormat; + editSystemPrompt: string; + updatePrefs: ( + next: UserPreferences | ((current: UserPreferences) => UserPreferences), + ) => Promise; + onClose: () => void; +} + +export function SelectionWorkspaceExtraControlsDialog({ + open, + autoIntent, + keywordsText, + editPlanFormat, + editSystemPrompt, + updatePrefs, + onClose, +}: SelectionWorkspaceExtraControlsDialogProps) { + const { t } = useTranslation(); + + return ( + ( +
+
+
+

+ {t('settings.selectionWorkspace.extraControls')} +

+

+ {t('settings.selectionWorkspace.extraControlsDesc')} +

+
+ +
+ +
+ + + void updatePrefs((current) => ({ + ...current, + selectionVoiceIntentMode: next ? 'auto' : 'heuristic', + })) + } + /> + + + {!autoIntent && ( + +