diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21133e9..55fabd2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,47 @@ jobs: - name: cargo test run: cargo test --workspace + # P2/P3 compile evidence: the unix platform impls must at least type-check + # on their target OS. Runtime behavior is still real-device-unverified — + # see docs/PLATFORMS.md for the honest status matrix. + rust-unix: + name: cargo check (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + + - name: Install Rust (stable) + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - name: Tauri system deps (Linux) + if: matrix.os == 'ubuntu-latest' + run: | + sudo apt-get update + sudo apt-get install -y \ + pkg-config libglib2.0-dev libgtk-3-dev \ + libwebkit2gtk-4.1-dev libayatana-appindicator3-dev \ + librsvg2-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev + + - name: Rust cache + uses: Swatinem/rust-cache@v2 + + - name: cargo check (workspace, all targets) + run: cargo check --workspace --all-targets + + - name: cargo clippy + run: cargo clippy --workspace --all-targets + + # Service unit tests (hotkey parser, IPC debounce) — no display needed. + - name: cargo test (service) + run: cargo test -p service + frontend: name: frontend static checks runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index a7a9250..564e13d 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,6 @@ Thumbs.db desktop.ini .idea/ .vscode/ -docs/ ############### # Rust / Cargo # @@ -63,3 +62,4 @@ nul *.bak implementation_plan.md task.md +tests/e2e/__pycache__/ diff --git a/.loom/design/task-brief-readme-release-and-crossplatform.md b/.loom/design/task-brief-readme-release-and-crossplatform.md new file mode 100644 index 0000000..44259d4 --- /dev/null +++ b/.loom/design/task-brief-readme-release-and-crossplatform.md @@ -0,0 +1,205 @@ +# Devin Brief: README 门面重写 + Release notes + Linux/macOS 跨平台实现(P1-P3) + +## 项目 +`/home/haa/sites/promptkey`,当前 `master` HEAD `baa37fe`(2.0.4 已发布)。新建分支 `feat/readme-release-notes-and-cross-platform`。 + +## 背景 + +用户已装 2.0.4,轮盘、拖拽排序都已验收通过。现在要求两件事: + +1. **仓库门面全面更新** —— README 重写、Release notes 写好、截图、设计文档、组件说明、功能清单。README 现有 146 行但内容是 2.0 早期状态,多处已过时。 +2. **Linux 和 macOS 也要做** —— 用户原话:「而且linux,macos也要做...当然要写好因为没有测试,不确定能否正常使用」。 + +用户明确知道**没有真机测试**,所以要求"写好"即:**工程质量要扎实、文档要诚实标注验证状态、不能假装已测**。 + +`.loom/design/CROSS_PLATFORM_PLAN.md`(125 行)已有详尽计划,**先读完再动手**,按其 P1-P4 阶段推进,本轮做到 P3。 + +--- + +# 任务总览 + +## Task A:跨平台实现(P1 抽象 + P2 Linux-X11 + P3 macOS) + +### P1:抽 trait + Windows 加固(必做) + +`.loom/design/CROSS_PLATFORM_PLAN.md:32` 已给出结构判断: + +- `injector` / `hotkey` / `context` 三个模块正好对应三个 trait 抽象 +- service 主循环除 `HWND` 类型外本身平台中立 +- **`AppContext.window_handle` 需改为 `u64`/`isize` 不透明句柄**(Windows 存 HWND bit,macOS 存 AXUIElement ref 或 0) + +要求: +- 抽出 `Injector` / `Context` / `Hotkey` 三个 trait,Windows 实现迁到 `*_impl` 后不动逻辑 +- **Windows 行为必须零变化** —— 这是已验收的可用版本,任何回归都是 P0 +- 保留 service 内嵌线程架构(`src/main.rs:95-98`),**不做独立守护进程** + +### P2:Linux-X11(必做) + +按 plan §3: +| 能力 | 选择 | +|---|---| +| 全局热键 | `global-hotkey`(X11 稳定) | +| 剪贴板 | `arboard`(X11 Tier-1) | +| 注入 | `enigo`(x11rb 后端) | +| 前台上下文 | X11 焦点窗口查询 | +| 自动启动 | `~/.config/autostart/promptkey.desktop`(XDG Autostart),不引入 systemd user unit | + +**Wayland 检测**:检测到 Wayland 会话时,**明确提示降级**("当前会话为 Wayland,自动注入需额外授权"),但管理功能全可用。 + +打包:`tauri build` 原生产出 `.deb` + `.AppImage`。 + +### P3:macOS(必做) + +按 plan §3 与 §3 的 UX 阻塞点: +- 注入:**AX API**(`AXUIElement`)为主,剪贴板兜底 +- 全局热键:macOS 原生(`global-hotkey` 的 macos 后端或 CGEventTap,你论证选型) +- 剪贴板:`arboard`(macOS Tier-1) +- **首启 AX 授权引导页(必须做)**:`AXIsProcessTrustedWithOptions(prompt=true)` 弹系统对话框 + 应用内权限状态轮询 + **权限缺失时降级为"复制到剪贴板"模式** +- 自动启动:`SMLoginItemSetEnabled` 或 `plugin-autostart` +- 图标:macOS `.icns`(`iconutil` 从 iconset 生成,脚本化);tray icon 单独做**单色可模板化**版本(macOS template image 要求) +- 打包:`.dmg` / `.app`;**公证需付费账号,文档说明** + +### P4 Wayland 增强(可选,本轮可不做) + +`ashpd` GlobalShortcuts portal + `ydotool` opt-in。**如果时间/风险不允许,明确列为"未做"并写清原因**,不要留半成品。 + +--- + +## Task B:README 全面重写 + +现有 README 的问题: +- 功能描述停在 2.0 早期(如默认热键写 `Ctrl+Alt+A`,实际是 `Ctrl+Alt+Q`) +- 没有截图 +- 没有设计文档/组件说明 +- 没有 2.0.x 的新功能(点按录制式热键录入、链路诊断、pointer 拖拽排序、模板库、capabilities 修复等) +- 没有跨平台章节(Linux/macOS 状态与限制必须诚实写) + +### 必须包含 + +1. **Hero 区** —— 一句话定位 + logo + badges(保持现有风格,更新技术栈徽章:加 Linux/macOS) +2. **功能特性** —— 按 2.0.4 实际功能重写,**逐条与代码核对**,不写不存在的功能 +3. **截图区** —— 见 Task C +4. **快速开始** —— 安装(Windows/Linux/macOS 三平台分别说明)+ 使用 + 默认热键表(**热键值必须与代码一致,去核实**) +5. **配置说明** —— 配置项名称与代码核对 +6. **从源码构建** —— 三平台分别写 +7. **项目结构** —— 更新到当前真实结构(注意 `src/` 与 `service/` 的实际划分、`capabilities/` 目录、`.loom/` 设计文档位置) +8. **设计文档索引** —— 链接 `.loom/design/` 下的研究/设计文档,每个一两句摘要 +9. **组件说明** —— 见 Task D +10. **平台支持矩阵** —— 诚实标注每个平台的能力与验证状态(**见"诚实性要求"**) +11. **更新日志** —— 链接 CHANGELOG.md +12. **贡献/致谢** —— 保留现有结尾风格 + +## Task C:截图(重要,但不能造假) + +**没有真机运行环境,禁止用"看起来像"的假图。** + +允许的做法(按优先级): +1. **从 e2e 截图产物来** —— `tests/e2e/wheel_sort_drag_e2e.py` 等测试会产出截图,检查是否有可用产物,挑选/命名后放入 `docs/screenshots/` +2. **从原型 HTML 渲染** —— `.loom/design/prototypes/` 下四个 HTML,用 Playwright headless 截图,**在 README 中明确标注"原型渲染,非最终产品截图"** +3. **ASCII/结构图** —— 用 mermaid 画架构图、轮盘交互流程图 + +**每个截图/图必须带 `alt` 文字**。 + +如果某个图只能给原型示意,**在图片下方明确标注**。宁可少而真,不要多而假。 + +## Task D:组件说明(新增 `docs/COMPONENTS.md`) + +前端是 vanilla ES module + 设计系统,需要一份组件清单让人能接手: + +- **模块划分** —— `src/js/` 下每个文件的职责(app/store/dom/toast/theme/icons/i18n/wheel/hotkey_recorder + views/*) +- **设计系统** —— 色彩 tokens(明暗双主题)、间距、圆角、字号层级、动效规范。**从 `src/styles.css` 实际提取**,不要编 +- **组件** —— 按钮体系(`.btn`/`.btn-primary`/`.btn-ghost`/`.mini-link`)、开关(`.switch`)、分段控件(`.seg`)、抽屉(`.drawer`)、toast、热键录入器、轮盘(`.petal`/`.glass`/`.center`)、状态行(`.hk-state`)、错误横幅(`.env-err`)—— 每个说明用途 + 关键 class + 使用时注意 +- **i18n 机制** —— 运行时切换怎么做的,新增语言要怎么加 +- **图标** —— 图标从哪来(lucide + 品牌图标),怎么加新图标 +- **测试资产** —— `tests/e2e/` 四个 e2e 各自覆盖什么,怎么跑 + +## Task E:Release notes 写好 2.0.0-2.0.4 + +`gh release edit` 或 API 更新 **v2.0.0 / v2.0.1 / v2.0.2 / v2.0.3 / v2.0.4** 五个 Release 的 notes。 + +要求: +- 每个版本写清:**做了什么、为什么、验证到什么程度** +- **2.0.1-2.0.4 是修 bug 的版本,notes 里要写清症状与根因**(这对用户和理解者都有价值),例如 2.0.2 的 `present_wheel` emit 顺序、2.0.3 的 capabilities 缺失、2.0.4 的拖拽排序 +- 保持诚实:**未真机验证的能力要标注** +- 格式统一,风格专业(可参考 GitHub 上成熟项目的 release notes) + +## Task F:文档清单核对 + +除 README + COMPONENTS.md 外,确认以下文档状态并补全: +- `CHANGELOG.md` —— 更新到 2.0.4,格式统一 +- `.loom/design/` 下的设计文档 —— 在 README 里做索引,**但不要搬位置** +- 跨平台的页面(Linux 构建、macOS 公证、Wayland 降级)写清楚,放 README 的平台章节或独立 `docs/PLATFORMS.md` + +--- + +# 诚实性要求(最高优先级) + +用户原话:「**当然要写好因为没有测试,不确定能否正常使用**」 + +这意味着: + +1. **绝不宣称"已测试通过"** —— Linux/macOS 路径本机没跑过(本机是 Linux 但项目当前 build 依赖 Windows-only crate,CI 是否覆盖 Linux 由你核实并报告) +2. **README 平台支持矩阵必须分三列写清**:功能支持性 / 打包产物 / **验证状态**(✅ 已实机验证 / ⚠️ 代码就绪未验证 / ❌ 不支持) +3. **Wayland 限制、macOS 授权摩擦、未公证** 都要明说,不藏在脚注 +4. **CI 如果不覆盖 Linux/macOS,明确说"CI 未覆盖"**,并评估是否该加(如果要加,告诉我成本,不要擅自加一堆跑不通的 job) +5. 你做的任何截图,如果是原型渲染的,**标注原型** + +--- + +# 硬约束 + +- 无 cargo,本机不编译。**CI 必须全绿** +- Windows 行为**零回归** —— P1 抽 trait 时尤其小心,这是已验收的可用版本 +- Playwright 全绿;如为跨平台加了新测试,也要跑 +- 遵守设计系统与 i18n(新文案中英双语) +- 文档里的每个技术声明都要**能在代码里找到依据** +- **不要动 `capabilities/` 的既有结论** +- commit 规范:可多个 commit(按 P1/P2/P3/README/COMPONENTS/RELEASE-NOTES 分开),push,PR `--base master`,**不合并** +- 遵守 LOOM 流程 + +--- + +## 最终交付 + +``` +## 跨平台实现(P1/P2/P3) +(每阶段:做了什么、选型理由、**验证到什么程度**(编译?CI?真机?)、遗留风险) +### P4 状态 +(做了/没做,原因) + +## README 重写 +(新增哪些章节;逐条核对过哪些过时内容并修正——特别是热键值;截图来源清单) + +## COMPONENTS.md +(模块/设计系统/组件/i18n/图标/测试 六部分摘要) + +## Release notes +(5 个版本 notes 的要点;诚实性怎么体现的) + +## 验证状态汇总 +(一张表:能力 × 平台 × 验证状态;CI 覆盖情况;**哪些是本机绝对测不了的**) + +## 用户在 Linux/macOS 上首次使用的预期 +(会看到什么;Wayland 会话什么表现;macOS 首次授权流程;出问题时怎么反馈) + +## 未编译验证清单 +``` + +```json +COMPLETION_NOTIFY +source: assistant +task: promptkey-readme-release-and-crossplatform +deliverables: +- P1 traits extracted with zero Windows regression +- P2 Linux-X11 implemented (global-hotkey + arboard + enigo + XDG autostart) +- P3 macOS implemented (AX inject + permission onboarding + icns + template tray) +- Wayland/macOS limits documented honestly with verification status matrix +- README fully rewritten with verified facts, screenshots (real or clearly-labelled prototypes), design docs index +- docs/COMPONENTS.md covering modules, design system, components, i18n, icons, tests +- CHANGELOG.md updated to 2.0.4 +- release notes rewritten for v2.0.0-v2.0.4 with symptom→root-cause honesty +- CI green, no fabricated test claims +- branch feat/readme-release-notes-and-cross-platform + PR against master (not merged) +status: success +errors: none +``` diff --git a/.loom/design/task-brief-wheel-drag-refresh.md b/.loom/design/task-brief-wheel-drag-refresh.md new file mode 100644 index 0000000..f4f46db --- /dev/null +++ b/.loom/design/task-brief-wheel-drag-refresh.md @@ -0,0 +1,118 @@ +# Devin Brief: 拖拽提交后 UI 不刷新(P0,Linux 真机实测抓到) + +## 项目 +`/home/haa/sites/promptkey`,当前 `master` HEAD `baa37fe`(2.0.4)。新建分支 `fix/wheel-drag-commit-no-refresh`。 + +## 背景 + +我在 **Linux 上用 Playwright 真实驱动前端**(mock `__TAURI__` IPC),跑完整个冒烟套件。16/17 通过,**抓到一个 P0 真 bug** —— 这正是你在 Windows 上装 2.0.4 后拖排序会遇到的"拖了没反应"。 + +## 实测证据(完整链路,逐环都有) + +``` +MID-DRAG: {target row gets `.dragging`, insertion slot appears} ✅ 交互识别正常 +AFTER DROP: set_pin_order 收到 { ids: [2, 1] } ✅ 顺序计算完全正确 +FINAL DOM: #wheelMirror 顺序仍是 ["1","2"] ❌ 提交后没有重新渲染 +``` + +**即:拖拽逻辑对、提交参数对,唯一断点是"提交成功后 UI 没刷新"。** + +这解释了为什么 2.0.4 的 e2e 用例声称"断言 DOM reorder + `set_pin_order` 被调用"却全绿 —— 见下方"测试盲区"。 + +## 疑似位置 + +`src/js/views/prompts.js` 的拖拽提交函数(PR #14 的 pointer 实现,约 `commitPinOrder` / drop handler 一带): + +```js +try { + await ipc('set_pin_order', { ids: pins }); + await loadPrompts(); rebuildIndex(); renderPrompts(); // ← 这条链看起来有,但实测没生效 +} catch { /* toasted */ } +``` + +请先**逐行读实际代码**,查清为什么刷新没发生。至少这几种可能,请逐一证伪/证实: + +1. **刷新被调用了但抛错被 catch 吞掉**(`loadPrompts` 内部依赖某个 mock 里没有的东西,或某个调用 throw) +2. **`renderPrompts()` 只重渲染 `#grid`,根本不碰 `#wheelMirror`** —— 那顺序就永远不更新。**这个可能性最大,优先查** +3. `wheelPrompts()` 的排序在 `wheelSort !== 'manual'` 时不认 `inject_order`,mock 切了 manual 但真实路径有问题 +4. 提交后 `state.prompts` 被替换但 mirror 的渲染走的是别的缓存 +5. drop 之后某个 return 提前退出,刷新语句根本没执行到 + +## 修复要求 + +1. **提交成功后 `#wheelMirror` 必须立即反映新顺序**(不需要刷新页面、不需要切页面再切回) +2. **顺序要真的持久化** —— 重载页面后顺序不变(我的 mock 里已实现"真后端"语义,能验证这点) +3. **失败时回滚视觉状态**:IPC 失败要恢复到拖拽前的顺序,不能停在中间态 +4. 我实测发现:**拖拽必须按在 `.drag` 句柄上才触发**(按行 body 无效)—— 这是 PR #14 的合理设计,**不要改掉**,但请在交付里确认这是有意为之,并考虑要不要给用户更明显的视觉提示(句柄 hover/光标变化),你论证 + +## 附带:修测试盲区(必须) + +2.0.4 的 e2e 号称断言"DOM reorder",却漏掉了这个 bug。原因是: + +- e2e 的 mock `set_pin_order` 返回 `null`,**不真的持久化顺序** +- 且断言只看"调用发生",**没断言松手后 DOM 顺序真的变了** + +请修 `tests/e2e/wheel_sort_drag_e2e.py`: + +1. mock 的 `set_pin_order` 必须**真的写回顺序**(真后端语义) +2. 断言必须包含:**松手后 `#wheelMirror` 的 DOM 顺序确实变化** +3. 再断言一次 `set_pin_order` 收到的 `ids` 顺序 = DOM 新顺序 +4. 加一个失败回滚用例:mock `set_pin_order` reject → UI 恢复原顺序 +5. 加一个"刷新后顺序仍在"用例(重新 load 页面) + +--- + +# 硬约束 + +- **我在 Linux 上给你复现步骤**(见下),你可以自己复现验证 +- 无 cargo,本机不编译,CI 全绿即可 +- 不得回归 Windows 行为 +- 一个 commit `fix(wheel): re-render mirror after pin order commit`,push,PR `--base master`,**不合并** +- 遵守 LOOM 流程 + +## 我在 Linux 上的复现方式(你可以照做) + +```bash +cd /home/haa/sites/promptkey/src && python3 -m http.server 8913 # 后台起静态服务 +# 然后用 Playwright + mock __TAURI__(mock 必须实现 set_pin_order 真写回) +# 我的冒烟脚本在 /tmp/pk_linux_smoke.py,可直接参考或复用 +``` + +关键:**mock 一定要让 `set_pin_order` 真的更新数据**,否则这个 bug 测不出来(这正是原 e2e 漏掉它的原因)。 + +--- + +## 最终交付 + +``` +## 根因 +(为什么提交后不刷新,逐行证据) + +## 修复 +(改了什么;为什么这样改) + +## 测试盲区修正 +(e2e 怎么改的;现在能抓住这个 bug 吗——**请真的跑一次证明**) + +## 复现验证 +(你在 Linux 上跑的证据:拖拽前/中/后 DOM + set_pin_order 参数 + 刷新后顺序) + +## 顺带观察 +(拖拽句柄的视觉提示、以及你发现的任何其他问题) +``` + +```json +COMPLETION_NOTIFY +source: assistant +task: promptkey-wheel-drag-refresh +deliverables: +- root cause of "commits but UI never re-renders" proven with code lines +- mirror re-renders immediately after successful commit and survives reload +- failure rolls back visual order +- e2e mock now persists order and asserts post-drop DOM order + received ids + reload persistence + rollback +- e2e actually re-run to prove it now catches the bug (or would have) +- CI green +- branch fix/wheel-drag-commit-no-refresh + PR against master (not merged) +status: success +errors: none +``` diff --git a/.loom/state.json b/.loom/state.json index 599279e..071268f 100644 --- a/.loom/state.json +++ b/.loom/state.json @@ -4,7 +4,7 @@ "name": "promptkey", "status": "complete", "created_at": "2026-10-06T08:16:56.246Z", - "updated_at": "2026-10-07T06:08:09.960Z" + "updated_at": "2026-10-07T07:38:06.890Z" }, "understanding": { "confirmed": [ diff --git a/.loom/tasks.json b/.loom/tasks.json index aa4929b..3dca522 100644 --- a/.loom/tasks.json +++ b/.loom/tasks.json @@ -1034,6 +1034,190 @@ "created_at": "2026-10-07T05:55:04.721Z", "updated_at": "2026-10-07T06:08:09.959Z", "completed_at": "2026-10-07T06:08:09.959Z" + }, + { + "id": "TASK-011", + "title": "Cross-platform impl (P2 Linux-X11 + P3 macOS) + README/release-notes/docs overhaul", + "outcome": "service + GUI compile and run on Windows/Linux-X11/macOS with honest degradation (Wayland warn, macOS AX onboarding); IPC works via Unix sockets; README rewritten against verified facts; docs/COMPONENTS.md + docs/PLATFORMS.md added; CHANGELOG covers 2.0.3+2.0.4; release notes v2.0.0-v2.0.4 rewritten with symptom→root-cause; zero Windows behavior regression.", + "acceptance": [ + { + "criterion": "cargo check -p service passes on Linux with new enigo/arboard/x11rb/global-hotkey impls", + "verify_by": "cargo check -p service (local rustup toolchain)", + "evidence": "cargo check --workspace local + CI ubuntu job green; deps resolved: global-hotkey 0.6.4, arboard 3.6.1, enigo 0.6.1, x11rb 0.13.2" + }, + { + "criterion": "Windows code paths unchanged behaviorally: windows_impl files untouched except cfg gating", + "verify_by": "git diff review of service/src/**/windows_impl.rs and shared mod files", + "evidence": "git diff: windows_impl.rs files show no logic edits; IPC debounce/retry semantics preserved (unix twin test added, windows test kept); Windows CI check/clippy/test green" + }, + { + "criterion": "GUI-side IPC (selector listener + inject client) works on unix domain sockets; named-pipe path untouched on Windows", + "verify_by": "code review; cargo check -p service + cargo check where sysdeps allow", + "evidence": "ipc_listener.rs + inject_pipe_client.rs dual transports; service inject_server_uds.rs mirrors one-line protocol; UDS paths from platform:: endpoints with 0700/0600 perms" + }, + { + "criterion": "Platform status surfaces honestly: Wayland warning + macOS AX permission request UI, zh+en i18n", + "verify_by": "e2e-style browser screenshot of settings platform section; node --check passes", + "evidence": "settings.js refreshPlatformState renders status_json() (os/session/notes); wayland_degraded/no_display/ax_permission_missing localized zh+en; AX row appears only on ax_permission_missing with Grant button re-triggering system prompt" + }, + { + "criterion": "Icons: icons/ PNG set + icon.icns + monochrome template tray generated from brand master; tauri.conf.json updated", + "verify_by": "file inventory + icon format header check", + "evidence": "scripts/make_icons.py derives PNGs + real PNG-payload .icns (file(1)-verified) + tray-template.png silhouette from 1024px master; tauri.conf.json icon list + macOS icon_as_template wired" + }, + { + "criterion": "CI: new linux+macos cargo check jobs green; existing windows check/clippy/test + playwright e2e green", + "verify_by": "gh run view on pushed branch", + "evidence": "gh run 37587905594: 5/5 success (win check+clippy+test, ubuntu check, macos check, frontend static, playwright e2e)" + }, + { + "criterion": "README states only verified facts (hotkeys Ctrl+Alt+Space / Ctrl+Alt+Q etc.), platform matrix with verification column, labelled screenshots", + "verify_by": "manual review against code", + "evidence": "README verified against code: quick hotkey default is Ctrl+Alt+A (config/mod.rs:121 — brief's Ctrl+Alt+Q was test-fixture data, corrected); matrix has explicit verification column; 3 screenshots are real UI headless renders, provenance-labeled" + }, + { + "criterion": "docs/COMPONENTS.md covers modules/design-system/components/i18n/icons/tests from real code", + "verify_by": "manual review", + "evidence": "COMPONENTS.md: tokens extracted from styles.css :root, all classes cited with line refs, i18n/icons mechanics documented from source" + }, + { + "criterion": "Release notes v2.0.0-v2.0.4 updated via gh with symptom→root-cause and verification status", + "verify_by": "gh release view", + "evidence": "gh release edit applied to all 5 tags; each notes file has symptom/root-cause/fix + explicit verification state" + } + ], + "done_when": [], + "boundaries": [ + "No Wayland-native injection/hotkey (P4 out of scope; documented)", + "No notarized macOS build (no paid account; documented)", + "capabilities/ existing conclusions not modified (autostart wrapped as app commands, no new plugin perms needed)", + "Windows behavior must not regress — windows_impl logic untouched" + ], + "depends_on": [], + "reads": [ + ".loom/design/CROSS_PLATFORM_PLAN.md", + ".loom/design/task-brief-readme-release-and-crossplatform.md", + "service/src/injector/mod.rs", + "service/src/hotkey/mod.rs", + "service/src/context/mod.rs", + "service/src/ipc/mod.rs", + "service/src/ipc/inject_server.rs", + "src/main.rs", + "src/ipc_listener.rs", + "src/inject_pipe_client.rs", + "service/src/config/mod.rs", + "tauri.conf.json", + "src/js/views/settings.js", + "src/index.html", + "src/styles.css", + "src/js/i18n/zh-CN.js", + "src/js/i18n/en-US.js", + ".github/workflows/ci.yml", + ".github/workflows/release.yml", + "README.md", + "CHANGELOG.md", + "tests/e2e/no_tauri_e2e.py", + "tests/e2e/hotkey_recorder_e2e.py" + ], + "touches": [ + "service/src/", + "src/", + "Cargo.toml", + "service/Cargo.toml", + "tauri.conf.json", + "capabilities/", + ".github/workflows/", + "icons/", + "scripts/make_icons.py", + "README.md", + "CHANGELOG.md", + "docs/COMPONENTS.md", + "docs/PLATFORMS.md", + "docs/screenshots/", + ".loom/" + ], + "implements": "cross-platform-plan", + "design_exemption": "", + "capability_hooks": [ + { + "node": "injection-engine#C3", + "at": "clipboard+paste injector on linux/macos", + "must_produce": "clipboard restore + secure-field gate parity or honest gap doc" + }, + { + "node": "injection-engine#C5", + "at": "wayland session detection", + "must_produce": "detect + user-visible degrade notice" + } + ], + "capability_exemption": "README/COMPONENTS/release-notes portions are documentation work over already-confirmed dossiers; no new professional judgment surface.", + "integrity_version": 1, + "covers": [], + "status": "done", + "progress": { + "completed": [ + "P1 traits extracted; windows_impl logic untouched (diff-verified)", + "P2 Linux-X11: x11rb context + enigo/XTEST injector + global-hotkey + arboard + UDS IPC + XDG autostart + Wayland degrade", + "P3 macOS: AX injector + clipboard fallback + AXIsProcessTrusted onboarding + NSWorkspace context + icns/template tray + LaunchAgent", + "GUI: platform status surface + AX permission row + autostart toggle + bilingual i18n + null-safe status", + "README rewrite + docs/PLATFORMS.md + docs/COMPONENTS.md + CHANGELOG 2.0.3 filled", + "Release notes v2.0.0-v2.0.4 rewritten via gh (symptom→root-cause)", + "Local verify: cargo check --workspace, clippy, service tests 9/9, playwright 4 suites 62/62", + "CI rust-check job added for win/ubuntu/macos; macOS compile iteratively fixed (unsafe extern, features)" + ], + "current": "complete", + "next": "" + }, + "evidence": [ + "PR #15 feat/readme-release-notes-and-cross-platform → master (open, not merged). CI run 37587905594: all 5 jobs green on Windows+Linux+macOS.", + "cargo check --workspace clean locally (Linux w/ GTK sysroot); service tests 9/9; Playwright 4 suites: 22+10+17+13=62/62 locally and CI-green.", + "macOS compile was iterated via CI (unsafe-extern edition-2024, macos_ax visibility, macos-private-api + image-png features) — now green.", + { + "type": "acceptance_results", + "results": [ + { + "criterion": "cargo check -p service passes on Linux with new enigo/arboard/x11rb/global-hotkey impls", + "evidence": "cargo check --workspace local + CI ubuntu job green; deps resolved: global-hotkey 0.6.4, arboard 3.6.1, enigo 0.6.1, x11rb 0.13.2" + }, + { + "criterion": "Windows code paths unchanged behaviorally: windows_impl files untouched except cfg gating", + "evidence": "git diff: windows_impl.rs files show no logic edits; IPC debounce/retry semantics preserved (unix twin test added, windows test kept); Windows CI check/clippy/test green" + }, + { + "criterion": "GUI-side IPC (selector listener + inject client) works on unix domain sockets; named-pipe path untouched on Windows", + "evidence": "ipc_listener.rs + inject_pipe_client.rs dual transports; service inject_server_uds.rs mirrors one-line protocol; UDS paths from platform:: endpoints with 0700/0600 perms" + }, + { + "criterion": "Platform status surfaces honestly: Wayland warning + macOS AX permission request UI, zh+en i18n", + "evidence": "settings.js refreshPlatformState renders status_json() (os/session/notes); wayland_degraded/no_display/ax_permission_missing localized zh+en; AX row appears only on ax_permission_missing with Grant button re-triggering system prompt" + }, + { + "criterion": "Icons: icons/ PNG set + icon.icns + monochrome template tray generated from brand master; tauri.conf.json updated", + "evidence": "scripts/make_icons.py derives PNGs + real PNG-payload .icns (file(1)-verified) + tray-template.png silhouette from 1024px master; tauri.conf.json icon list + macOS icon_as_template wired" + }, + { + "criterion": "CI: new linux+macos cargo check jobs green; existing windows check/clippy/test + playwright e2e green", + "evidence": "gh run 37587905594: 5/5 success (win check+clippy+test, ubuntu check, macos check, frontend static, playwright e2e)" + }, + { + "criterion": "README states only verified facts (hotkeys Ctrl+Alt+Space / Ctrl+Alt+Q etc.), platform matrix with verification column, labelled screenshots", + "evidence": "README verified against code: quick hotkey default is Ctrl+Alt+A (config/mod.rs:121 — brief's Ctrl+Alt+Q was test-fixture data, corrected); matrix has explicit verification column; 3 screenshots are real UI headless renders, provenance-labeled" + }, + { + "criterion": "docs/COMPONENTS.md covers modules/design-system/components/i18n/icons/tests from real code", + "evidence": "COMPONENTS.md: tokens extracted from styles.css :root, all classes cited with line refs, i18n/icons mechanics documented from source" + }, + { + "criterion": "Release notes v2.0.0-v2.0.4 updated via gh with symptom→root-cause and verification status", + "evidence": "gh release edit applied to all 5 tags; each notes file has symptom/root-cause/fix + explicit verification state" + } + ], + "at": "2026-10-07T07:38:06.884Z" + } + ], + "created_at": "2026-10-07T06:47:00.011Z", + "updated_at": "2026-10-07T07:38:06.889Z", + "completed_at": "2026-10-07T07:38:06.889Z" } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 10d72d6..4ebaff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,43 @@ 后端字段保留,且保存时会把原值透传回去,避免一次普通编辑顺手抹掉刚排好的顺序。 +## 2.0.3 — 2026-10-07 + +补丁版本。修复自 2.0.0 起**装机后两轮修复都没命中的根因**:Tauri 2 capabilities 整个缺失。 + +### 症状 + +2.0.1 / 2.0.2 装机后始终存在: + +- 轮盘永远不显示(按热键毫无反应,但直注可以) +- 热键录制器提交时被拒 + +### 根因 + +**Tauri 2 把 IPC 改成了白名单制**:`tauri.conf.json` 没有 `app.security.capabilities`, +仓库根也没有 `capabilities/` 目录,生成的 `gen/schemas/capabilities.json` 是空对象。 +没有 capability,`window.__TAURI__` **根本不会注入到 webview**——所有 `invoke()`/`event.listen()` 都断。 + +链条很隐蔽: + +- 轮盘 `loadPrompts()` → `hasTauri()` false → 静默空转,轮盘窗口弹出一个吃点击的透明壳 +- 录制器 `onCommit` → `ipc('apply_settings')` → `hasTauri()` false → throw +- **直注却能用**——它完全在 service 内部执行,不经过 Tauri IPC,是个误导性线索 +- Playwright e2e 全绿也帮了倒忙:测试是手动 mock `__TAURI__` 的,掩盖了真实环境的缺失 + +`withGlobalTauri: true` 是 Tauri 1 遗留配置,只决定 `__TAURI__` 是否全局,**不授予 IPC 权限**。 + +### 修复 + +- 新建 `capabilities/default.json`:`main` + `wheel-panel` 两个 webview 的最小权限集 + (`core:default` + window set-position/hide) +- 新增 `scripts/check_capabilities.mjs` 静态检查脚本并接入 CI——JS 调用的每条 IPC 都必须在 + capabilities 里有对应权限,防止再次「代码有、权限没」 +- 主界面与轮盘各加环境错误横幅(`env-err`):`__TAURI__` 未注入或权限被拒时**直接显示**, + 不再是静默失败的透明壳 + +--- + ## 2.0.2 — 2026-10-07 补丁版本。修复 2.0.1 装机后暴露的两个阻塞性问题。 diff --git a/Cargo.lock b/Cargo.lock index 565cccc..f2f1907 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -118,6 +118,26 @@ version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100" +[[package]] +name = "arboard" +version = "3.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.2", + "objc2-app-kit 0.3.1", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.1", + "parking_lot", + "percent-encoding", + "windows-sys 0.60.2", + "x11rb", +] + [[package]] name = "ashpd" version = "0.9.2" @@ -310,6 +330,17 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "auto-launch" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f012b8cc0c850f34117ec8252a44418f2e34a2cf501de89e29b241ae5f79471" +dependencies = [ + "dirs 4.0.0", + "thiserror 1.0.69", + "winreg 0.10.1", +] + [[package]] name = "autocfg" version = "1.5.0" @@ -437,6 +468,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.10.1" @@ -571,7 +608,16 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-link 0.2.0", + "windows-link 0.2.1", +] + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", ] [[package]] @@ -644,6 +690,19 @@ dependencies = [ "libc", ] +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.9.4", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + [[package]] name = "core-graphics-types" version = "0.2.0" @@ -707,6 +766,12 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.6" @@ -833,13 +898,33 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys 0.3.7", +] + [[package]] name = "dirs" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "dirs-sys", + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users 0.4.6", + "winapi", ] [[package]] @@ -850,7 +935,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users", + "redox_users 0.5.2", "windows-sys 0.61.0", ] @@ -972,7 +1057,7 @@ dependencies = [ "rustc_version", "toml 0.9.5", "vswhom", - "winreg", + "winreg 0.55.0", ] [[package]] @@ -996,6 +1081,28 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3d8a32ae18130a3c84dd492d4215c3d913c3b07c6b63c2eb3eb7ff1101ab7bf" +[[package]] +name = "enigo" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71c6c56e50f7acae2906a0dcbb34529ca647e40421119ad5d12e7f8ba6e50010" +dependencies = [ + "core-foundation", + "core-graphics 0.25.0", + "foreign-types-shared", + "libc", + "log", + "nom", + "objc2 0.6.2", + "objc2-app-kit 0.3.1", + "objc2-foundation 0.3.1", + "serde", + "windows 0.61.3", + "x11rb", + "xkbcommon", + "xkeysym", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -1066,6 +1173,12 @@ dependencies = [ "windows-sys 0.61.0", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + [[package]] name = "event-listener" version = "5.4.1" @@ -1105,6 +1218,12 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -1395,6 +1514,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link 0.2.1", +] + [[package]] name = "getrandom" version = "0.1.16" @@ -1520,6 +1649,22 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +[[package]] +name = "global-hotkey" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fbb3a4e56c901ee66c190fdb3fa08344e6d09593cc6c61f8eb9add7144b271" +dependencies = [ + "crossbeam-channel", + "keyboard-types", + "objc2 0.6.2", + "objc2-app-kit 0.3.1", + "once_cell", + "thiserror 2.0.16", + "windows-sys 0.59.0", + "x11-dl", +] + [[package]] name = "gobject-sys" version = "0.18.0" @@ -1583,6 +1728,17 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -1765,7 +1921,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc50b891e4acf8fe0e71ef88ec43ad82ee07b3810ad09de10f1d01f072ed4b98" dependencies = [ "byteorder", - "png", + "png 0.17.16", ] [[package]] @@ -1881,6 +2037,20 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2205,6 +2375,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + [[package]] name = "markup5ever" version = "0.14.1" @@ -2242,6 +2421,15 @@ version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + [[package]] name = "memoffset" version = "0.9.1" @@ -2278,6 +2466,16 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "muda" version = "0.17.1" @@ -2293,7 +2491,7 @@ dependencies = [ "objc2-core-foundation", "objc2-foundation 0.3.1", "once_cell", - "png", + "png 0.17.16", "serde", "thiserror 2.0.16", "windows-sys 0.60.2", @@ -2353,6 +2551,15 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "ntapi" version = "0.4.1" @@ -2399,6 +2606,15 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + [[package]] name = "objc-sys" version = "0.3.5" @@ -2991,6 +3207,19 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.9.4", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + [[package]] name = "polling" version = "3.10.0" @@ -3121,15 +3350,30 @@ dependencies = [ "sysinfo", "tauri", "tauri-build", + "tauri-plugin-autostart", "tauri-plugin-dialog", "tauri-plugin-fs", "tauri-plugin-shell", "tauri-plugin-single-instance", "tokio", + "ureq", + "url", "windows 0.52.0", "winres", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.37.5" @@ -3279,6 +3523,17 @@ dependencies = [ "bitflags 2.9.4", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror 1.0.69", +] + [[package]] name = "redox_users" version = "0.5.2" @@ -3397,6 +3652,20 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rusqlite" version = "0.32.1" @@ -3439,6 +3708,41 @@ dependencies = [ "windows-sys 0.61.0", ] +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -3716,14 +4020,21 @@ dependencies = [ name = "service" version = "0.1.0" dependencies = [ + "arboard", + "core-foundation", + "enigo", "env_logger", + "global-hotkey", + "libc", "log", + "objc", "rusqlite", "serde", "serde_json", "serde_yaml", "tokio", "windows 0.58.0", + "x11rb", ] [[package]] @@ -3853,7 +4164,7 @@ checksum = "18051cdd562e792cad055119e0cdb2cfc137e44e3987532e0f9659a77931bb08" dependencies = [ "bytemuck", "cfg_aliases", - "core-graphics", + "core-graphics 0.24.0", "foreign-types", "js-sys", "log", @@ -3936,6 +4247,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.7" @@ -4026,7 +4343,7 @@ dependencies = [ "bitflags 2.9.4", "block2 0.6.1", "core-foundation", - "core-graphics", + "core-graphics 0.24.0", "crossbeam-channel", "dispatch", "dlopen2", @@ -4083,7 +4400,7 @@ dependencies = [ "anyhow", "bytes", "cookie", - "dirs", + "dirs 6.0.0", "dunce", "embed_plist", "getrandom 0.3.3", @@ -4091,6 +4408,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http", + "image", "jni", "libc", "log", @@ -4134,7 +4452,7 @@ checksum = "9c432ccc9ff661803dab74c6cd78de11026a578a9307610bbc39d3c55be7943f" dependencies = [ "anyhow", "cargo_toml", - "dirs", + "dirs 6.0.0", "glob", "heck 0.5.0", "json-patch", @@ -4159,7 +4477,7 @@ dependencies = [ "ico", "json-patch", "plist", - "png", + "png 0.17.16", "proc-macro2", "quote", "semver", @@ -4206,6 +4524,20 @@ dependencies = [ "walkdir", ] +[[package]] +name = "tauri-plugin-autostart" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70" +dependencies = [ + "auto-launch", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.16", +] + [[package]] name = "tauri-plugin-dialog" version = "2.4.0" @@ -4446,6 +4778,20 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.43" @@ -4707,7 +5053,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0d92153331e7d02ec09137538996a7786fe679c629c279e82a6be762b7e6fe2" dependencies = [ "crossbeam-channel", - "dirs", + "dirs 6.0.0", "libappindicator", "muda", "objc2 0.6.2", @@ -4716,7 +5062,7 @@ dependencies = [ "objc2-core-graphics", "objc2-foundation 0.3.1", "once_cell", - "png", + "png 0.17.16", "serde", "thiserror 2.0.16", "windows-sys 0.59.0", @@ -4810,6 +5156,28 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64 0.22.1", + "flate2", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + [[package]] name = "url" version = "2.5.7" @@ -5150,6 +5518,24 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webview2-com" version = "0.38.0" @@ -5186,6 +5572,12 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "winapi" version = "0.3.9" @@ -5317,7 +5709,7 @@ checksum = "57fe7168f7de578d2d8a05b07fd61870d2e73b4020e9f49aa00da8471723497c" dependencies = [ "windows-implement 0.60.0", "windows-interface 0.59.1", - "windows-link 0.2.0", + "windows-link 0.2.1", "windows-result 0.4.0", "windows-strings 0.5.0", ] @@ -5385,9 +5777,9 @@ checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" [[package]] name = "windows-link" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-numerics" @@ -5423,7 +5815,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f" dependencies = [ - "windows-link 0.2.0", + "windows-link 0.2.1", ] [[package]] @@ -5451,7 +5843,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda" dependencies = [ - "windows-link 0.2.0", + "windows-link 0.2.1", ] [[package]] @@ -5505,7 +5897,7 @@ version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e201184e40b2ede64bc2ea34968b28e33622acdbbf37104f0e4a33f7abe657aa" dependencies = [ - "windows-link 0.2.0", + "windows-link 0.2.1", ] [[package]] @@ -5586,7 +5978,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69e061eb0a22b4a1d778ad70f7575ec7845490abb35b08fa320df7895882cacb" dependencies = [ - "windows-link 0.2.0", + "windows-link 0.2.1", ] [[package]] @@ -5784,6 +6176,15 @@ version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "winreg" version = "0.55.0" @@ -5825,7 +6226,7 @@ dependencies = [ "block2 0.6.1", "cookie", "crossbeam-channel", - "dirs", + "dirs 6.0.0", "dpi", "dunce", "gdkx11", @@ -5881,6 +6282,23 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + [[package]] name = "xdg-home" version = "1.3.0" @@ -5891,6 +6309,23 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "xkbcommon" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + [[package]] name = "yoke" version = "0.8.0" @@ -6021,6 +6456,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.2" @@ -6054,6 +6495,21 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + [[package]] name = "zvariant" version = "4.0.0" diff --git a/Cargo.toml b/Cargo.toml index 7389ef7..77334d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,9 +51,20 @@ windows = { version = "0.52", features = ["Win32_UI_WindowsAndMessaging", "Win32 [target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies] tauri-plugin-single-instance = "2.0.0" +# Launch-at-login across all three OSes: XDG autostart file on Linux, +# SMAppService LaunchAgent on macOS, registry Run key on Windows. +tauri-plugin-autostart = "2.0.0" sysinfo = "0.30.0" rusqlite = { version = "0.32", features = ["bundled"] } +# macOS-only additions — kept off the Windows/Linux dependency trees. +# `macos-private-api` is required for WebviewWindowBuilder::transparent on +# macOS (the wheel overlay); it calls an undocumented WKWebView API, which +# is acceptable here because the app ships unsigned/un-notarized outside +# the App Store. `image-png` unlocks Image::from_bytes for the tray icon. +[target.'cfg(target_os = "macos")'.dependencies] +tauri = { version = "2.0.0", features = ["macos-private-api", "image-png"] } + [features] # this feature is used for production builds or when `devPath` points to the filesystem # DO NOT REMOVE!! diff --git a/README.md b/README.md index 1fd9617..405f29d 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ [![Rust](https://img.shields.io/badge/rust-%23000000.svg?style=for-the-badge&logo=rust&logoColor=white)](https://www.rust-lang.org/) [![Tauri](https://img.shields.io/badge/tauri-%2324C8DB.svg?style=for-the-badge&logo=tauri&logoColor=%23FFFFFF)](https://tauri.app/) [![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white)](https://www.microsoft.com/windows/) +[![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black)](https://www.kernel.org/) +[![macOS](https://img.shields.io/badge/macOS-000000?style=for-the-badge&logo=apple&logoColor=white)](https://www.apple.com/macos/) [![License](https://img.shields.io/badge/license-MIT-blue.svg?style=for-the-badge)](LICENSE) [![SQLite](https://img.shields.io/badge/sqlite-%2307405e.svg?style=for-the-badge&logo=sqlite&logoColor=white)](https://www.sqlite.org/) @@ -16,7 +18,7 @@ [![CSS3](https://img.shields.io/badge/css3-%231572B6.svg?style=for-the-badge&logo=css3&logoColor=white)](https://developer.mozilla.org/docs/Web/CSS) [![JavaScript](https://img.shields.io/badge/javascript-%23323330.svg?style=for-the-badge&logo=javascript&logoColor=%23F7DF1E)](https://developer.mozilla.org/docs/Web/JavaScript) -**[下载最新版本](https://github.com/Haaaiawd/PromptKey/releases/latest)** | **[更新日志](CHANGELOG.md)** +**[下载最新版本](https://github.com/Haaaiawd/PromptKey/releases/latest)** | **[更新日志](CHANGELOG.md)** | **[平台支持](docs/PLATFORMS.md)** | **[组件说明](docs/COMPONENTS.md)** @@ -28,41 +30,87 @@ PromptKey 是一个专为 AI 重度用户设计的系统级提示词管理器: ### 核心功能 -- **🎡 光标轮盘** — 热键呼出跟随鼠标的 280px 径向轮盘,无边框透明窗口,多显示器下正确落位,失焦自动隐藏 -- **📌 Pin 即轮盘** — 置顶是提示词的内联属性,轮盘就是置顶集合的实时投影,无需单独维护 +- **🎡 光标轮盘** — 热键呼出跟随光标的 280px 径向轮盘(无边框透明 320px 悬浮窗),多显示器下自动避让屏幕边缘,失焦自动隐藏 +- **⌨️ 按键录制式热键录入** — 设置页点击输入框后直接按下组合键即可录入(按物理键位而非字符),支持 F1–F24、方向键、小键盘、OEM 标点;非法组合(无修饰键/语法错误/系统冲突)明确拒绝并回滚 +- **📌 Pin 即轮盘** — 置顶是提示词的内联属性,轮盘就是置顶集合的实时投影;排序支持自动(frecency)与手动指针拖拽两种模式 - **⚡ 默认直注** — 第二组热键跳过轮盘,直接注入「默认提示词」(固定指定 / 最近使用,可选) -- **📚 模板库** — 内置中英精选包,支持 URL / 本地文件导入、导出分享包 +- **🔍 打开即搜索** — 轮盘弹出后直接敲字过滤,不再受 6 格限制;数字键 1–9 直选 +- **📚 模板库** — 内置 7 个中英精选包一键导入,支持 URL / 本地文件导入、导出分享包 - **🧩 模板变量** — `{{变量}}` 注入前表单填写;`{{clipboard}}` `{{date}}` `{{time}}` 自动填充 - **🌓 设计系统** — 明暗双主题 + 中英双语运行时切换 +- **🩺 链路诊断** — 设置页一键逐环快照(引擎 / 热键 / IPC / 监听 / 轮盘窗口),轮盘唤不出时断在哪一环一眼可见 ### 注入与安全 -- **💉 双策略注入** — 剪贴板粘贴为主,SendInput 逐键模拟兜底(应对禁止粘贴的场景) -- **🔒 密码框门禁** — 焦点在密码/安全输入框时拒绝注入(ES_PASSWORD + UIA IsPassword 双重只读探测) -- **📋 剪贴板保护** — 注入前备份剪贴板**全部格式**,用后恢复;遇到无法备份的格式自动改用 SendInput,不污染用户数据 +- **💉 双策略注入** — 剪贴板粘贴为主,逐键模拟兜底(Windows 为 SendInput,Linux 为 XTEST,macOS 为剪贴板+⌘V) +- **🔒 密码框门禁** — 焦点在密码/安全输入框时拒绝注入(ES_PASSWORD + UIA IsPassword 双重只读探测,Windows) +- **📋 剪贴板保护** — 注入前备份剪贴板**全部格式**,用后恢复;无法备份时自动改用逐键模拟,不污染用户数据 - **🌐 SSRF 防护** — URL 导入强制 https、逐跳校验重定向、拒绝内网/回环/云元数据地址 - **📊 真实日志** — 每次注入记录真实成败、所用策略与耗时 +- **🖥️ 平台状态可见** — 设置页显示当前 OS / 会话类型 / 能力状态(Wayland 降级、macOS 权限缺失都会明确提示而非静默失败) -## 💻 系统要求 +## 📸 截图 -- Windows 10 / 11(x64) -- 已安装 **WebView2 Runtime**(Windows 11 与多数 Windows 10 自带;安装包不自动安装) -- 安装包未做代码签名,SmartScreen 提示「未知发布者」属正常,选择「仍要运行」 +> 以下截图为**真实界面**在无头 Chromium 中的渲染结果(与端到端测试同机制加载 `src/` 静态资源,`__TAURI__` 桥接数据为桩)。所见即交付的前端代码,非设计原型。 + +**主界面 · 提示词管理**(置顶集合即轮盘内容) + +![主界面:提示词列表、置顶星标、卡片视图(真实界面无头渲染,数据为桩)](docs/screenshots/prompts-view.png) + +**轮盘**(热键呼出时的悬浮轮盘) + +![轮盘:六条置顶提示词呈环形排布,中央 Esc 提示(真实界面无头渲染)](docs/screenshots/wheel-overlay.png) + +**设置页**(平台状态、热键录制、链路诊断) + +![设置页:平台状态行、热键录制输入框、开机启动、链路诊断(真实界面无头渲染)](docs/screenshots/settings-view.png) + +## 💻 平台支持 + +| 平台 | 状态 | 产物 | 验证情况 | +|------|------|------|----------| +| **Windows 10/11 x64** | ✅ 完整支持 | NSIS / MSI | **已实机验收**(2.0.4 轮盘、注入、拖拽排序均经用户实测) | +| **Linux (X11)** | ⚠️ 代码就绪 | AppImage / deb | **编译通过 + 单测/E2E 通过,未做真机验证**;X11 注入/热键/上下文已实现,真机行为待确认 | +| **Linux (Wayland)** | ⚠️ 降级可用 | 同上 | 管理/剪贴板可用;X11 路径只能到达 XWayland 客户端,**原生 Wayland 窗口的自动注入未支持**,界面会明确提示降级 | +| **macOS** | ⚠️ 代码就绪 | app / dmg | **编译路径就绪,未做真机验证**;AX 注入 + 剪贴板兜底已实现,需授予「辅助功能」权限 | + +> ⚠️ **诚实声明**:Windows 是唯一经过真机验收的平台。Linux/macOS 的实现经过编译验证与单元/E2E 测试,但**从未在真机上运行过**——首次使用可能遇到我们尚未发现的问题,欢迎反馈(见文末)。CI 会验证 Linux/macOS 的编译,但不验证运行时行为。 + +各平台的实现细节、限制与未验证清单见 **[docs/PLATFORMS.md](docs/PLATFORMS.md)**。 ## 🚀 快速开始 -### 安装 +### Windows 1. 从 [Releases](https://github.com/Haaaiawd/PromptKey/releases/latest) 下载 `PromptKey_x.x.x_x64-setup.exe`(NSIS,中英双语安装向导)或 `.msi` -2. 运行安装包,按向导完成安装 +2. 需要 **WebView2 Runtime**(Windows 11 与多数 Windows 10 自带;安装包不自动安装) +3. 安装包未做代码签名,SmartScreen 提示「未知发布者」属正常,选择「仍要运行」 + +### Linux + +```bash +# AppImage:赋予执行权限后直接运行 +chmod +x PromptKey-*.AppImage && ./PromptKey-*.AppImage + +# deb +sudo dpkg -i promptkey_*.deb +``` + +- 需要 X11 会话(或接受 Wayland 降级行为);运行时依赖 WebKitGTK。 +- XWayland 下大部分能力可用;纯 Wayland 会话会在设置页显示「当前会话为 Wayland,自动注入能力受限」。 + +### macOS + +1. 打开 `.dmg`,拖入 Applications。 +2. **首次使用会请求「辅助功能」权限**:未授权时自动注入会降级为「复制到剪贴板 + 提示」。可在 设置 → 辅助功能权限 行重新触发系统授权对话框。 +3. 未公证(需付费开发者账号):首次打开可能被 Gatekeeper 拦截,右键 → 打开 即可绕过。 ### 使用 -1. **启动应用** — 开始菜单或桌面快捷方式 -2. **添加提示词** — 「提示词」页点击新建;勾选 📌 置顶即进入轮盘 -3. **呼出轮盘** — 默认 `Ctrl+Alt+Space`,轮盘出现在光标处 -4. **选择注入** — 点击扇区或按数字键;含 `{{变量}}` 的模板会先弹出填写表单 -5. **默认直注** — `Ctrl+Alt+A` 直接注入默认提示词(在设置里可改为固定指定某条) +1. **添加提示词** —「提示词」页点击新建;勾选 ⭐ 置顶即进入轮盘 +2. **呼出轮盘** — 默认 `Ctrl+Alt+Space`,轮盘出现在光标处 +3. **选择注入** — 点击扇区或按数字键;含 `{{变量}}` 的模板会先弹出填写表单 +4. **默认直注** — `Ctrl+Alt+A` 直接注入默认提示词(设置里可改为固定指定某条) ### 默认热键 @@ -71,16 +119,23 @@ PromptKey 是一个专为 AI 重度用户设计的系统级提示词管理器: | `Ctrl+Alt+Space` | 呼出轮盘 | | `Ctrl+Alt+A` | 直接注入默认提示词 | | `1-9` | 轮盘内选择 | -| `Esc` | 关闭轮盘 | +| `Esc` | 关闭轮盘 / 取消热键录制 | + +> 热键在设置页以**按键录制**方式修改:点击输入框 → 按下组合键 → 提交时若组合被占用或注册失败会明确提示并回滚。修改后服务平滑重启生效。 ## ⚙️ 配置 -``` -%APPDATA%/PromptKey/config.yaml # 配置(热键、注入开关、数据库路径) -%APPDATA%/PromptKey/promptmgr.db # SQLite 数据库 -``` +配置与数据库路径按平台约定存放(`service/src/platform/mod.rs`): -主要配置项:`hotkey`、`quick_hotkey`、`injection.allow_clipboard` / `restore_clipboard` / `secure_gate`、`database_path`。设置页可图形化修改,保存后服务平滑重启生效。 +| 平台 | 路径 | +|------|------| +| Windows | `%APPDATA%\PromptKey\config.yaml`、`%APPDATA%\PromptKey\promptmgr.db` | +| macOS | `~/Library/Application Support/PromptKey/config.yaml`、同目录 `promptmgr.db` | +| Linux | `${XDG_CONFIG_HOME:-~/.config}/promptkey/config.yaml`、同目录 `promptmgr.db` | + +主要配置项:`hotkey`、`quick_hotkey`、`database_path`、`injection.order` / `allow_clipboard` / `restore_clipboard` / `secure_gate` / `debug_mode` / `max_retries`、`applications.<进程名>`(按应用注入策略)。绝大多数项可在设置页图形化修改。 + +进程内 IPC:Windows 用命名管道(`\\.\pipe\promptkey_selector` / `promptkey_inject`),Linux/macOS 用 Unix domain socket(位于 `$XDG_RUNTIME_DIR` 或 `$TMPDIR/promptkey-$UID/`,目录 0700、socket 0600)。 ## 🛠️ 从源码构建 @@ -88,48 +143,94 @@ PromptKey 是一个专为 AI 重度用户设计的系统级提示词管理器: - **Rust stable ≥ 1.85**(`service/` 使用 edition 2024) - **Node.js LTS**(仅用于安装 Tauri CLI;前端为纯 HTML/CSS/JS,无构建步骤) -- Windows 10/11 ```bash git clone https://github.com/Haaaiawd/PromptKey.git cd PromptKey - npm install -g @tauri-apps/cli # 或 cargo install tauri-cli --version "^2" +``` + +**Windows**:直接 `cargo run` / `tauri build`(产出 NSIS + MSI)。 -cargo run # 开发模式运行 -tauri build # 产出 NSIS + MSI 安装包(target/release/bundle/) +**Linux**(Debian/Ubuntu 需先装 Tauri 系统依赖): + +```bash +sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev +cargo run # 开发模式 +tauri build # 产出 .deb + .AppImage(target/release/bundle/) ``` -CI/CD:PR 与 master push 运行 `cargo check`/`clippy`/`test` + 前端静态检查;推送 `v*` tag 自动构建并发布 GitHub Release(见 `.github/workflows/`)。 +**macOS**:`cargo run` / `tauri build`(产出 `.app` + `.dmg`)。公证需付费 Apple Developer 账号,`tauri.conf.json` 未配置签名。 + +CI/CD:PR 与 master push 运行 `cargo check`/`clippy`/`test`(Windows + Linux + macOS)+ 前端静态检查;推送 `v*` tag 自动构建并发布 GitHub Release(见 `.github/workflows/`)。 ### 项目结构 ``` PromptKey/ ├── src/ # Tauri GUI(Rust 主进程 + 纯前端) -│ ├── main.rs # Tauri 命令、托盘、轮盘窗口、pack 导入导出 -│ ├── ipc_listener.rs # 命名管道监听(service → GUI) -│ ├── inject_pipe_client.rs # 注入请求客户端(GUI → service) +│ ├── main.rs # Tauri 命令、托盘、轮盘窗口、pack 导入导出、平台状态命令 +│ ├── ipc_listener.rs # IPC 服务端:命名管道(Windows)/ UDS(Linux/macOS),service → GUI +│ ├── inject_pipe_client.rs # IPC 客户端:GUI → service 注入请求 │ ├── index.html / js/ # 主界面(提示词/模板库/记录/设置 四页) │ ├── wheel.html / wheel.css / js/wheel.js # 轮盘 -│ ├── packs/ # 内置模板包 + manifest +│ ├── packs/ # 内置模板包 + manifest(7 个中英包) │ └── icons/ # lucide + 品牌图标 ├── service/ # 内嵌引擎(workspace 成员,edition 2024) │ └── src/ -│ ├── main.rs # 引擎主循环、模板渲染、注入调度 -│ ├── injector/ # Injector trait + Windows 实现(剪贴板/SendInput) -│ ├── context/ # Context trait + Windows 前台上下文 -│ ├── hotkey/ # Hotkey trait + Windows 消息循环 -│ ├── ipc/ # 命名管道服务端 -│ ├── config/ # YAML 配置 +│ ├── main.rs # 引擎主循环、模板渲染、注入调度(平台中立) +│ ├── platform/ # OS/会话探测、各平台路径、IPC 端点、状态上报 +│ ├── injector/ # Injector trait + Windows / X11 / macOS-AX 实现 +│ ├── context/ # Context trait + Windows / X11 / macOS 前台上下文 +│ ├── hotkey/ # Hotkey trait + Windows 消息循环 / global-hotkey(unix) +│ ├── ipc/ # 命名管道 + Unix domain socket 服务端 +│ ├── config/ # YAML 配置(前向兼容未知键) │ └── db.rs # SQLite -├── tauri.conf.json # Tauri 配置(版本号权威来源) +├── capabilities/ # Tauri IPC 权限(main + wheel-panel 两个 webview) +├── tests/e2e/ # Playwright 端到端测试(stub __TAURI__,4 套件 60+ 断言) +├── docs/ # PLATFORMS.md / COMPONENTS.md / screenshots/ +├── scripts/ # make_icons.py(多平台图标)/ screenshots.py / check_capabilities.mjs +├── blueprint/ # 历史 PRD / RFC / 复杂度审计(1.x → 2.0 演进档案) +├── .loom/design/ # 现行设计文档(见下方索引) └── .github/workflows/ # CI + Release ``` +## 📐 设计文档索引 + +现行设计与研究文档在 `.loom/design/`(小写同名文件是别名指针): + +| 文档 | 内容 | +|------|------| +| [INJECTION_RESEARCH.md](.loom/design/INJECTION_RESEARCH.md) | 三平台注入机制调研与选型(剪贴板/逐键/AX 的依据) | +| [CROSS_PLATFORM_PLAN.md](.loom/design/CROSS_PLATFORM_PLAN.md) | 跨平台工程化计划:P1 trait 抽象 → P2 Linux-X11 → P3 macOS → P4 Wayland | +| [UI_UX_REDESIGN.md](.loom/design/UI_UX_REDESIGN.md) + [prototypes/](.loom/design/prototypes/) | 2.0 界面革新设计 + 4 个可交互原型 | +| [MERGE_ARCHITECTURE.md](.loom/design/MERGE_ARCHITECTURE.md) | 「提示词 + 轮盘」合并架构(pin 即轮盘) | +| [MARKET_DECISION.md](.loom/design/MARKET_DECISION.md) | 模板库(原市场)的产品决策 | +| [REVIEW_FINDINGS.md](.loom/design/REVIEW_FINDINGS.md) | 多轮 Devin Review 发现项与修复记录 | +| [task-brief-*.md](.loom/design/) | 各补丁版本的任务简报 | + +补充文档:[docs/PLATFORMS.md](docs/PLATFORMS.md)(平台实现与验证状态)、[docs/COMPONENTS.md](docs/COMPONENTS.md)(前端模块与设计系统)、`blueprint/`(1.x 历史 PRD/RFC 档案)。 + +## 🧪 测试 + +```bash +cargo test -p service # Rust 单元测试(热键解析、配置、IPC 等) +python3 tests/e2e/.py # Playwright 端到端(需 playwright + chromium) +``` + +`tests/e2e/` 四个套件:`hotkey_recorder`(录入交互)、`hotkey_status`(冲突/引擎故障状态与回滚)、`wheel_sort_drag`(指针拖拽排序)、`no_tauri`(无桥接环境降级)。均通过 stub `__TAURI__` 加载真实前端运行。 + +## 🔧 故障排查 + +- **热键按了没反应**:设置页 →「链路诊断」逐环定位(引擎/热键/IPC/轮盘窗口);热键状态行直接显示 已生效/被占用/不支持/未注册。 +- **轮盘唤不出**:看诊断中「监听 → wheel-show → 轮盘窗口」三环。 +- **Linux 注入无效**:确认会话类型(设置页平台状态);Wayland 会话当前降级。 +- **macOS 注入失败**:设置页检查辅助功能权限,点「Grant/授权」重新触发系统对话框。 +- **日志**:设置页「记录」页查看每次注入的真实成败、策略与耗时;`injection.debug_mode` 可开详细日志。 + ## 📋 更新日志 -见 [CHANGELOG.md](CHANGELOG.md)。 +见 [CHANGELOG.md](CHANGELOG.md)。各版本发布说明见 [Releases](https://github.com/Haaaiawd/PromptKey/releases)。 --- diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md new file mode 100644 index 0000000..f934f5a --- /dev/null +++ b/docs/COMPONENTS.md @@ -0,0 +1,135 @@ +# 前端组件与模块说明 + +PromptKey 前端是**纯 HTML/CSS/JS(ES modules)**,无构建步骤、无框架。 +主界面 `src/index.html` + `src/styles.css` + `src/js/`;轮盘 `src/wheel.html` + `src/wheel.css` + `src/js/wheel.js`。 +两个 webview 各自加载一份前端代码,通过 `__TAURI__` 桥接与 Rust 后端通信。 + +--- + +## 1. 模块划分(`src/js/`) + +| 文件 | 职责 | +|------|------| +| `app.js` | 入口与外壳:视图路由、导航、`error`/`unhandledrejection` 全局兜底 toast、环境探测横幅 | +| `store.js` | 共享状态(`state.prompts` 等)+ **`ipc()` 守卫**(超时/无声开关/失败自动 toast)+ 数据派生(`wheelPrompts`、frecency 排序、`extractVars`/`renderVars` 模板变量、Fuse 搜索索引) | +| `dom.js` | DOM 小工具:`$`/`$$` 选择器、`esc()` HTML 转义、`storage` localStorage 封装 | +| `toast.js` | 通知队列:`toast('ok'|'err'|'info', msg)`,容器 `#toasts` | +| `theme.js` | 主题:`auto/light/dark`,`data-theme` attribute + `prefers-color-scheme` 媒体查询;`refreshTheme()` 供轮盘窗口重读 | +| `i18n.js` | 运行时中英切换(见 §4) | +| `icons.js` | 生成文件——Lucide v1.48 SVG path 表 + `icon(name,size)` 渲染(见 §5) | +| `hotkey_recorder.js` | 热键录入器(见 §3);`comboFromEvent` 等纯函数可单测 | +| `wheel.js` | 轮盘窗口全部逻辑:监听 `wheel-show`/`wheel-hide`、`prepare()` 拉数据、`render()` 排花瓣、键盘/指针选择、变量表单、`envErr` IPC 失败可见化 | +| `views/prompts.js` | 提示词页:卡片/列表视图、搜索、标签筛选、编辑抽屉、⭐置顶、**指针拖拽排序** | +| `views/library.js` | 模板库页:内置包导入、URL/文件导入(SSRF 防护在后端)、导出 | +| `views/log.js` | 记录页:注入日志列表、空态 | +| `views/settings.js` | 设置页:热键录入+状态行、保存/回滚、链路诊断、**平台状态/AX 权限/开机启动** | + +i18n 字典:`src/js/i18n/zh-CN.js`、`en-US.js`。 + +## 2. 设计系统(`src/styles.css` `:root`) + +全部从 `styles.css`/`wheel.css` 实际提取。明暗双主题通过 `body[data-theme]` 覆盖变量。 + +### 色彩 tokens + +| token | dark | light | 用途 | +|-------|------|-------|------| +| `--bg-app` / `--bg-surface` / `--bg-elevated` | `#09090b`/`#18181b`/`#27272a` | `#f4f4f5`/`#fff`/`#fff` | 应用底/面板/抬起面 | +| `--border` / `--border-strong` | `#27272a`/`#3f3f46` | `#e4e4e7`/`#d4d4d8` | 分隔/强调边 | +| `--text-primary` / `--text-secondary` / `--text-muted` | `#fafafa`/`#a1a1aa`/`#71717a` | `#18181b`/`#52525b`/`#a1a1aa` | 三级文字 | +| `--accent` / `--accent-hover` / `--accent-soft` | `#3b82f6`/`#2563eb`/15% 透明 | `#2563eb`/`#1d4ed8`/10% 透明 | 主色 | +| `--success` / `--danger` / `--warning` | `#22c55e`/`#ef4444`/`#f59e0b` | `#16a34a`/`#dc2626`/`#d97706` | 状态色 | +| `--focus-ring` | accent 45% | accent 35% | `:focus-visible` 外描边 | + +### 间距 / 圆角 / 字号 / 动效 + +- 间距:`--sp-1…--sp-12` = 4/8/12/16/20/24/32/48px +- 圆角:`--r-sm:6` `--r-md:10` `--r-lg:14` `--r-pill:999` +- 字号:`--fs-caption:11` `--fs-small:12` `--fs-body:13` `--fs-title:15` `--fs-head:20` `--fs-hero:26` +- 动效:`--dur-fast:100ms` `--dur-normal:180ms` `--dur-slow:280ms`;缓动 `--ease-out` / `--ease-pop`(轮盘开合用 pop)。 +- 全局过渡:背景/边框/文字色统一 `var(--dur-normal)`;遵循系统 `prefers-reduced-motion`。 +- 工具类:`.hidden`(`display:none!important`,**隐藏元素一律用它,`hidden` 属性会被 `.set-row{display:flex}` 等覆盖**)、`.flex-spacer`、`.ico`(图标容器,`ico-sm` 14px)。 + +## 3. 组件清单 + +### 按钮体系(styles.css:116-126) +- `.btn` 基础按钮;`.btn-primary` 主操作;`.btn-danger` 危险操作;`.btn-ghost` 无边弱按钮;`.btn-icon` 方形图标钮。 +- `.mini-link` 虚线下划线的微型文字链(次要操作)。 +- `:disabled` 统一 `opacity:.45`。 + +### 开关 `.switch` +iOS 风格拨杆:``,JS 里 `classList.toggle('on')`。 +用于设置页「开机启动」等布尔项(见 `settings.js` `#swAutostart`)。 + +### 分段控件 `.seg`(styles.css:68-72) +`
外观主题
+
开机自启动
登录后自动在后台运行
+
+ +

平台

+
平台状态
+

全局热键

呼出轮盘
diff --git a/src/inject_pipe_client.rs b/src/inject_pipe_client.rs index e143229..789890c 100644 --- a/src/inject_pipe_client.rs +++ b/src/inject_pipe_client.rs @@ -1,36 +1,44 @@ -// TW004: GUI IPC Client for Inject Pipe -// Sends INJECT_PROMPT:{id}\n messages to Service via Named Pipe +// TW004: GUI IPC Client for Inject endpoint +// Sends INJECT_PROMPT:{id}\n messages to Service. +// Windows: named pipe opened via OpenOptions. Unix: domain socket connect — +// same line protocol either way; endpoint from service::platform. -use std::fs::OpenOptions; use std::io::Write; -const PIPE_NAME: &str = r"\\.\pipe\promptkey_inject"; - -/// Send inject request to Service -/// Returns Ok(()) if message sent successfully -pub fn send_inject_request(prompt_id: i32) -> Result<(), Box> { - // Open named pipe as client - let mut pipe = OpenOptions::new().write(true).open(PIPE_NAME)?; +fn open_writer() -> Result, Box> { + write_to(&service::platform::inject_endpoint()) +} - // Format message: INJECT_PROMPT:{id}\n - let message = format!("INJECT_PROMPT:{}\n", prompt_id); +#[cfg(windows)] +fn write_to(endpoint: &str) -> Result, Box> { + let pipe = std::fs::OpenOptions::new().write(true).open(endpoint)?; + Ok(Box::new(pipe)) +} - // Write and flush - pipe.write_all(message.as_bytes())?; - pipe.flush()?; +#[cfg(unix)] +fn write_to(endpoint: &str) -> Result, Box> { + let stream = std::os::unix::net::UnixStream::connect(endpoint)?; + Ok(Box::new(stream)) +} +fn send(message: String) -> Result<(), Box> { + let mut w = open_writer()?; + w.write_all(message.as_bytes())?; + w.flush()?; Ok(()) } +/// Send inject request to Service +/// Returns Ok(()) if message sent successfully +pub fn send_inject_request(prompt_id: i32) -> Result<(), Box> { + send(format!("INJECT_PROMPT:{}\n", prompt_id)) +} + /// Phase 2 D5: send inject request with collected {{var}} values /// Format: INJECT_PROMPT:{id}:VARS:{urlencoded_json}\n pub fn send_inject_request_vars(prompt_id: i32, vars_json: String) -> Result<(), Box> { - let mut pipe = OpenOptions::new().write(true).open(PIPE_NAME)?; // vars_json may contain ':' so it's delimited by the third ':'-prefix - let message = format!("INJECT_PROMPT:{}:VARS:{}\n", prompt_id, vars_json); - pipe.write_all(message.as_bytes())?; - pipe.flush()?; - Ok(()) + send(format!("INJECT_PROMPT:{}:VARS:{}\n", prompt_id, vars_json)) } #[cfg(test)] diff --git a/src/ipc_listener.rs b/src/ipc_listener.rs index c27f0ca..e1df67f 100644 --- a/src/ipc_listener.rs +++ b/src/ipc_listener.rs @@ -1,14 +1,17 @@ // IPC Listener Module - GUI Server for Service Communication // T1-010: Implement IPC Listener in GUI +// +// Same line-framed protocol on every OS; only the transport differs: +// Windows — named pipe (tokio::net::windows::named_pipe) +// Unix — unix domain socket (tokio::net::UnixListener) +// The endpoint itself comes from service::platform::selector_endpoint(). use serde::Serialize; use std::sync::Mutex; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tauri::AppHandle; use tokio::io::AsyncReadExt; -use tokio::net::windows::named_pipe::ServerOptions; -const PIPE_NAME: &str = r"\\.\pipe\promptkey_selector"; /// Commands are one line; read until '\n' or EOF, bounded so a hostile or /// confused client cannot grow the buffer forever. const MAX_MESSAGE_BYTES: usize = 8192; @@ -87,80 +90,159 @@ pub fn listener_state() -> PipeListenerState { }) } +/// One inbound command line → action. Shared by both transports. +fn handle_message(msg: &str, app: &AppHandle) { + if msg.is_empty() { + return; + } + println!("[IPC] Received: {}", msg); + update(|st| { + st.messages_handled += 1; + st.last_message = Some(msg.to_string()); + st.last_message_at_ms = Some(epoch_ms()); + }); + if msg == "SHOW_WHEEL" { + // Phase 2: wheel window follows the cursor (positioned in + // main.rs). present_wheel records its own outcome. + if let Err(e) = crate::present_wheel(app) { + record_error(format_args!("present_wheel failed: {}", e)); + } + } +} + pub fn start_ipc_listener(app: AppHandle) { + let endpoint = service::platform::selector_endpoint(); tauri::async_runtime::spawn(async move { - println!("[IPC] Starting listener on {}", PIPE_NAME); + println!("[IPC] Starting listener on {}", endpoint); + run(app, &endpoint).await; + }); +} - loop { - // Create a fresh pipe instance for the next connection. - // first_pipe_instance(false) is REQUIRED here: true sets - // FILE_FLAG_FIRST_PIPE_INSTANCE, which fails on every create - // after the first — this loop creates one instance per - // connection, so only the non-first variant can work. - let mut server = match ServerOptions::new() - .first_pipe_instance(false) - .create(PIPE_NAME) - { - Ok(s) => s, - Err(e) => { - // Retrying forever is fine — but only via STATE is a - // persistently-failing create() visible to the user. - record_error(format_args!("create {} failed: {}", PIPE_NAME, e)); - tokio::time::sleep(Duration::from_secs(1)).await; - continue; - } - }; - update(|st| { - st.alive = true; - st.instances_created += 1; - }); - - // Wait for client to connect - if let Err(e) = server.connect().await { - record_error(format_args!("connect failed: {}", e)); +/* ---------------- Windows: named-pipe server ---------------- */ + +#[cfg(windows)] +async fn run(app: AppHandle, endpoint: &str) { + use tokio::net::windows::named_pipe::ServerOptions; + + loop { + // Create a fresh pipe instance for the next connection. + // first_pipe_instance(false) is REQUIRED here: true sets + // FILE_FLAG_FIRST_PIPE_INSTANCE, which fails on every create + // after the first — this loop creates one instance per + // connection, so only the non-first variant can work. + let mut server = match ServerOptions::new() + .first_pipe_instance(false) + .create(endpoint) + { + Ok(s) => s, + Err(e) => { + // Retrying forever is fine — but only via STATE is a + // persistently-failing create() visible to the user. + record_error(format_args!("create {} failed: {}", endpoint, e)); + tokio::time::sleep(Duration::from_secs(1)).await; continue; } - update(|st| st.connects_served += 1); - println!("[IPC] Client connected"); - - // Read the command line: until '\n' or EOF, bounded. A byte-mode - // pipe can split a short write; a single read() is not a frame. - let mut buf: Vec = Vec::with_capacity(128); - let mut chunk = [0u8; 512]; - loop { - match server.read(&mut chunk).await { - Ok(0) => break, // client closed - Ok(n) => { - buf.extend_from_slice(&chunk[..n]); - if buf.contains(&b'\n') || buf.len() >= MAX_MESSAGE_BYTES { - break; - } - } - Err(e) => { - record_error(format_args!("read failed: {}", e)); + }; + update(|st| { + st.alive = true; + st.instances_created += 1; + }); + + // Wait for client to connect + if let Err(e) = server.connect().await { + record_error(format_args!("connect failed: {}", e)); + continue; + } + update(|st| st.connects_served += 1); + println!("[IPC] Client connected"); + + // Read the command line: until '\n' or EOF, bounded. A byte-mode + // pipe can split a short write; a single read() is not a frame. + let mut buf: Vec = Vec::with_capacity(128); + let mut chunk = [0u8; 512]; + loop { + match server.read(&mut chunk).await { + Ok(0) => break, // client closed + Ok(n) => { + buf.extend_from_slice(&chunk[..n]); + if buf.contains(&b'\n') || buf.len() >= MAX_MESSAGE_BYTES { break; } } + Err(e) => { + record_error(format_args!("read failed: {}", e)); + break; + } } + } + + let msg = String::from_utf8_lossy(&buf).trim().to_string(); + handle_message(&msg, &app); + // The served instance is dropped here; the next loop iteration + // creates the next listening instance. + } +} + +/* ---------------- Unix: domain-socket server ---------------- */ + +#[cfg(unix)] +async fn run(app: AppHandle, endpoint: &str) { + use tokio::net::UnixListener; - let msg = String::from_utf8_lossy(&buf).trim().to_string(); - if !msg.is_empty() { - println!("[IPC] Received: {}", msg); - update(|st| { - st.messages_handled += 1; - st.last_message = Some(msg.clone()); - st.last_message_at_ms = Some(epoch_ms()); - }); - if msg == "SHOW_WHEEL" { - // Phase 2: wheel window follows the cursor (positioned in - // main.rs). present_wheel records its own outcome. - if let Err(e) = crate::present_wheel(&app) { - record_error(format_args!("present_wheel failed: {}", e)); + // A stale socket file blocks bind; only our own uid can sit here + // (the runtime dir is created 0700 by service::platform). + let _ = std::fs::remove_file(endpoint); + let listener = match UnixListener::bind(endpoint) { + Ok(l) => l, + Err(e) => { + record_error(format_args!("bind {} failed: {}", endpoint, e)); + return; + } + }; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(endpoint, std::fs::Permissions::from_mode(0o600)); + } + update(|st| st.alive = true); + st_instances_tick(); + + loop { + let (mut stream, _) = match listener.accept().await { + Ok(v) => v, + Err(e) => { + record_error(format_args!("accept failed: {}", e)); + tokio::time::sleep(Duration::from_secs(1)).await; + continue; + } + }; + update(|st| st.connects_served += 1); + + let mut buf: Vec = Vec::with_capacity(128); + let mut chunk = [0u8; 512]; + loop { + match stream.read(&mut chunk).await { + Ok(0) => break, + Ok(n) => { + buf.extend_from_slice(&chunk[..n]); + if buf.contains(&b'\n') || buf.len() >= MAX_MESSAGE_BYTES { + break; } } + Err(e) => { + record_error(format_args!("read failed: {}", e)); + break; + } } - // The served instance is dropped here; the next loop iteration - // creates the next listening instance. } - }); + + let msg = String::from_utf8_lossy(&buf).trim().to_string(); + handle_message(&msg, &app); + } +} + +/// Keep `instances_created` meaningful on unix (one listener, many accepts). +#[cfg(unix)] +fn st_instances_tick() { + update(|st| st.instances_created += 1); } diff --git a/src/js/i18n/en-US.js b/src/js/i18n/en-US.js index 07dba31..40f4fd9 100644 --- a/src/js/i18n/en-US.js +++ b/src/js/i18n/en-US.js @@ -138,6 +138,19 @@ export default { "inj.gate": "Secure-field detection", "inj.gateSub": "Refuse injection into password fields", + "set.platform": "Platform", + "plat.autostart": "Launch at login", + "plat.autostartSub": "Run PromptKey in the background after sign-in", + "plat.status": "Platform status", + "plat.statusFail": "Could not read platform status", + "plat.ok": "all features available", + "plat.wayland": "Wayland session — automatic injection needs extra authorization; management unaffected", + "plat.noDisplay": "no display server detected — hotkeys and injection unavailable", + "plat.axMissing": "Accessibility permission missing — injection falls back to clipboard copy", + "plat.axTitle": "Accessibility permission", + "plat.axSub": "Auto-injection requires Accessibility access; without it PromptKey falls back to copying to the clipboard", + "plat.axGrant": "Grant", + "set.data": "Data", "data.io": "Import / Export", "data.ioSub": "promptkey-pack JSON format", diff --git a/src/js/i18n/zh-CN.js b/src/js/i18n/zh-CN.js index 9c8578e..0d52a99 100644 --- a/src/js/i18n/zh-CN.js +++ b/src/js/i18n/zh-CN.js @@ -138,6 +138,19 @@ export default { "inj.gate": "安全控件检测", "inj.gateSub": "检测到密码框时拒绝注入", + "set.platform": "平台", + "plat.autostart": "开机自启动", + "plat.autostartSub": "登录后自动在后台运行", + "plat.status": "平台状态", + "plat.statusFail": "无法读取平台状态", + "plat.ok": "全部功能可用", + "plat.wayland": "当前会话为 Wayland,自动注入需额外授权 — 管理功能不受影响", + "plat.noDisplay": "未检测到显示服务器 — 热键与自动注入不可用", + "plat.axMissing": "缺少辅助功能权限 — 注入已降级为复制到剪贴板", + "plat.axTitle": "辅助功能权限", + "plat.axSub": "自动注入需要辅助功能权限;未授权时将降级为复制到剪贴板", + "plat.axGrant": "去授权", + "set.data": "数据", "data.io": "导入 / 导出", "data.ioSub": "promptkey-pack JSON 格式", diff --git a/src/js/views/settings.js b/src/js/views/settings.js index 1adec9b..149aa5b 100644 --- a/src/js/views/settings.js +++ b/src/js/views/settings.js @@ -22,6 +22,12 @@ export async function renderSettings() { if ($('#swGate')) $('#swGate').classList.toggle('on', s.secure_gate !== false); } catch { /* leave defaults */ } + // launch-at-login reflects the OS registration, not a stored preference + try { + const on = await ipc('get_launch_at_login', {}, { silent: true }); + if ($('#swAutostart')) $('#swAutostart').classList.toggle('on', !!on); + } catch { /* leave off */ } + // default prompt selector const sel = $('#defaultPromptSel'); if (sel) { @@ -39,9 +45,42 @@ export async function renderSettings() { } refreshHotkeyStates(); + refreshPlatformState(); } function esc0(s) { return String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); } +// Platform capability surface: shows Wayland degradation / headless sessions / +// missing macOS Accessibility permission instead of letting the user discover +// it via a dead hotkey. The raw status JSON stays on hover for bug reports. +async function refreshPlatformState() { + const el = $('#platformState'); + const axRow = $('#axPermRow'); + if (!el) return; + let p; + try { + p = await ipc('get_platform_status', {}, { silent: true }); + } catch { + p = null; + } + if (!p || typeof p !== 'object') { + el.className = 'sub hk-state err'; + el.textContent = t('plat.statusFail'); + return; + } + const osLabel = { windows: 'Windows', macos: 'macOS', linux: 'Linux' }[p.os] || p.os; + const sessLabel = { x11: 'X11', wayland: 'Wayland', native: '', unknown: '?' }[p.session] ?? p.session; + const notes = Array.isArray(p.notes) ? p.notes : []; + let cls = 'ok', msg = t('plat.ok'); + if (notes.includes('wayland_degraded')) { cls = 'warn'; msg = t('plat.wayland'); } + else if (notes.includes('no_display')) { cls = 'err'; msg = t('plat.noDisplay'); } + else if (notes.includes('ax_permission_missing')) { cls = 'warn'; msg = t('plat.axMissing'); } + el.className = `sub hk-state ${cls}`; + el.textContent = `${osLabel}${sessLabel ? ' · ' + sessLabel : ''} · ${msg}`; + el.title = JSON.stringify(p); + // `.set-row{display:flex}` beats the `hidden` attribute — use the class. + if (axRow) axRow.classList.toggle('hidden', !notes.includes('ax_permission_missing')); +} + // Self-check surface: shows what the engine ACTUALLY registered per hotkey — // ok / conflict / unsupported / failed / not_registered. A dead engine or a // rejected RegisterHotKey is visible here instead of silent. @@ -167,6 +206,24 @@ export function wireSettings({ syncShell }) { ['#swClipboard', '#swRestore', '#swGate'].forEach(id => $(id)?.addEventListener('click', e => { e.currentTarget.classList.toggle('on'); saveHotkeys(); })); + // Launch-at-login: flip the OS registration (XDG .desktop / LaunchAgent / + // registry Run). Roll the switch back when the platform call fails. + $('#swAutostart')?.addEventListener('click', async e => { + const on = e.currentTarget.classList.toggle('on'); + try { + await ipc('set_launch_at_login', { enabled: on }); + } catch { + e.currentTarget.classList.toggle('on', !on); + } + }); + + // macOS AX onboarding: the system prompt deep-links to Settings; granting + // happens on Apple's side, so re-poll the status instead of trusting a return. + $('#btnAxPerm')?.addEventListener('click', async () => { + try { await ipc('request_ax_permission', {}, { silent: true }); } catch { /* toasted */ } + setTimeout(refreshPlatformState, 1000); + }); + $('#defaultPromptSel')?.addEventListener('change', async e => { const v = e.target.value; try { diff --git a/src/main.rs b/src/main.rs index 5476ab9..7ec4402 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,8 +12,7 @@ use serde::{Deserialize, Serialize}; use std::time::Duration; // 服务进程句柄 -#[cfg(windows)] -mod ipc_listener; // named pipes (tokio::net::windows) are Windows-only +mod ipc_listener; // service→GUI listener: named pipe (Windows) / unix socket (elsewhere) mod inject_pipe_client; // TW004: GUI → Service injection command client @@ -153,7 +152,15 @@ fn main() { let mut builder = tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_dialog::init()) - .plugin(tauri_plugin_fs::init()); + .plugin(tauri_plugin_fs::init()) + // Launch-at-login: registry Run key (Windows), XDG autostart + // ~/.config/autostart/promptkey.desktop (Linux), SMAppService + // LaunchAgent (macOS) — all via the plugin, wrapped by our own + // set/get_launch_at_login commands so no capability change is needed. + .plugin(tauri_plugin_autostart::init( + tauri_plugin_autostart::MacosLauncher::LaunchAgent, + None, + )); // 为桌面平台添加单实例插件 #[cfg(any(target_os = "macos", windows, target_os = "linux"))] @@ -200,6 +207,10 @@ fn main() { trigger_wheel_injection, // TW005: PromptWheel injection trigger trigger_wheel_injection_vars, // Phase2: inject with {{var}} values show_wheel_window, // TW012: Show PromptWheel window (cursor-following) + get_platform_status, // P2/P3: Wayland/AX capability surface + request_ax_permission, // P3: macOS Accessibility onboarding + get_launch_at_login, // P2/P3: autostart state (XDG/LaunchAgent/registry) + set_launch_at_login, diagnose_hotkey_pipeline, // P0 fix: locate where the hotkey→wheel chain breaks present_main_window_new_prompt, // D4 fix: wheel quick-create hands off to the main editor create_prompt, @@ -222,15 +233,26 @@ fn main() { let quit_i = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?; let show_i = MenuItem::with_id(app, "show", "显示/隐藏", true, None::<&str>)?; - // T1-010: Start IPC Listener (named pipe → Windows-only) - #[cfg(windows)] + // T1-010: Start IPC Listener (named pipe on Windows, unix socket elsewhere) ipc_listener::start_ipc_listener(app.handle().clone()); let menu = Menu::with_items(app, &[&show_i, &quit_i])?; // 创建系统托盘图标 - let _tray = TrayIconBuilder::new() - .icon(app.default_window_icon().unwrap().clone()) + // macOS menu-bar icons must be monochrome "template" images — a + // colored icon renders as a dark blob that ignores light/dark + // switching. scripts/make_icons.py emits the silhouette variant. + #[cfg(target_os = "macos")] + let tray_builder = TrayIconBuilder::new() + .icon( + tauri::image::Image::from_bytes(include_bytes!("icons/brand/tray-template.png")) + .expect("tray-template.png must decode"), + ) + .icon_as_template(true); + #[cfg(not(target_os = "macos"))] + let tray_builder = TrayIconBuilder::new() + .icon(app.default_window_icon().unwrap().clone()); + let _tray = tray_builder .menu(&menu) .on_menu_event(|app, event| match event.id.as_ref() { "quit" => { @@ -610,7 +632,7 @@ fn diagnose_hotkey_pipeline(app: AppHandle) -> Result service::EngineState::Stopped => ("stopped", None), }; - #[cfg(windows)] + // Real listener on every platform now (named pipe / unix socket). let (listener, listener_alive, listener_last_msg_at) = { let st = ipc_listener::listener_state(); ( @@ -619,12 +641,6 @@ fn diagnose_hotkey_pipeline(app: AppHandle) -> Result st.last_message_at_ms, ) }; - #[cfg(not(windows))] - let (listener, listener_alive, listener_last_msg_at) = ( - serde_json::json!({ "alive": false, "platform": "named pipes are Windows-only" }), - false, - None, - ); let last_send = service::ipc::last_wheel_send(); let last_send_json = serde_json::to_value(&last_send).unwrap_or_default(); @@ -648,16 +664,8 @@ fn diagnose_hotkey_pipeline(app: AppHandle) -> Result if engine != "running" { hints.push("engine_not_running".into()); } - #[cfg(windows)] - { - if !listener_alive { - hints.push("listener_not_running".into()); - } - } - #[cfg(not(windows))] - { - let _ = listener_last_msg_at; - hints.push("unsupported_platform".into()); + if !listener_alive { + hints.push("listener_not_running".into()); } if let Some(s) = &last_send { if s.kind == "open_failed" || s.kind == "write_failed" { @@ -717,6 +725,52 @@ fn show_wheel_window(app: AppHandle) -> Result<(), String> { present_wheel(&app) } +/// Platform capability surface for the settings UI: os, session (x11/wayland/ +/// native), per-capability state, machine-keyed `notes` the JS localizes — +/// "wayland_degraded", "no_display", "ax_permission_missing". +#[tauri::command] +fn get_platform_status() -> Result { + Ok(service::platform::status_json()) +} + +/// macOS only: show the system Accessibility-permission prompt. Returns the +/// CURRENT trust state — granting still requires the user to flip the switch +/// in System Settings, and the UI keeps polling `get_platform_status`. +#[tauri::command] +fn request_ax_permission() -> Result { + #[cfg(target_os = "macos")] + { + Ok(service::injector::request_ax_trust()) + } + #[cfg(not(target_os = "macos"))] + { + // No such permission elsewhere — report "granted" so the UI hides + // the banner instead of pretending there's a state to manage. + Ok(true) + } +} + +/// Launch-at-login state — backed by tauri-plugin-autostart +/// (XDG autostart on Linux, LaunchAgent on macOS, registry Run on Windows). +#[tauri::command] +fn get_launch_at_login(app: AppHandle) -> Result { + use tauri_plugin_autostart::ManagerExt; + app.autolaunch() + .is_enabled() + .map_err(|e| format!("读取自启状态失败: {}", e)) +} + +#[tauri::command] +fn set_launch_at_login(app: AppHandle, enabled: bool) -> Result<(), String> { + use tauri_plugin_autostart::ManagerExt; + let m = app.autolaunch(); + if enabled { + m.enable().map_err(|e| format!("开启自启失败: {}", e)) + } else { + m.disable().map_err(|e| format!("关闭自启失败: {}", e)) + } +} + // Phase 2 D4 fix: the wheel's quick-create gesture cannot author a prompt body // inside a transient 320px overlay, so it hands the typed filter text to the // main window's editor instead of fabricating a record. The drawer enforces @@ -1386,8 +1440,9 @@ fn default_true() -> bool { true } fn default_uia_value_pattern_mode() -> String { "overwrite".into() } fn config_path() -> Result { - let appdata = std::env::var("APPDATA").map_err(|e| format!("读取APPDATA失败: {}", e))?; - let dir = std::path::Path::new(&appdata).join("PromptKey"); + // Platform-aware: %APPDATA%\PromptKey on Windows, XDG config on Linux, + // ~/Library/Application Support on macOS — same dir the service uses. + let dir = service::platform::app_config_dir()?; std::fs::create_dir_all(&dir).map_err(|e| format!("创建配置目录失败: {}", e))?; Ok(dir.join("config.yaml")) } @@ -1399,12 +1454,8 @@ fn load_or_default_config() -> Result { let cfg: AppConfig = serde_yaml::from_str(&s).map_err(|e| format!("解析配置失败: {}", e))?; Ok(cfg) } else { - // database_path 默认与服务一致 - let database_path = if let Ok(appdata) = std::env::var("APPDATA") { - format!("{}\\PromptKey\\promptmgr.db", appdata) - } else { - "promptmgr.db".to_string() - }; + // database_path 默认与服务一致 (platform::default_database_path) + let database_path = service::platform::default_database_path(); Ok(AppConfig { hotkey: default_hotkey(), quick_hotkey: default_quick_hotkey(), diff --git a/tauri.conf.json b/tauri.conf.json index 1751d06..dda0a74 100644 --- a/tauri.conf.json +++ b/tauri.conf.json @@ -28,8 +28,16 @@ "active": true, "targets": "all", "icon": [ - "PromptKey.ico" + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.icns", + "icons/icon.ico", + "icons/icon.png" ], + "category": "Utility", + "shortDescription": "Radial prompt injection", + "longDescription": "PromptKey is a global-hotkey prompt manager: a radial wheel surfaces your prompt library at the cursor and injects it into the focused app.", "externalBin": [], "windows": { "webviewInstallMode": {