From 31bf9b862ebd419efbd98ea2a6ee765500ea5e06 Mon Sep 17 00:00:00 2001 From: Limin Wang Date: Thu, 19 Nov 2026 10:25:10 -0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(panorama):=20=E5=BE=85=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=87=8C=E7=9A=84=E3=80=8C=E4=BF=AE=E5=A4=8D=E3=80=8D?= =?UTF-8?q?=E2=80=94=E2=80=94=E5=9C=A8=E9=A1=B5=E9=9D=A2=E4=B8=8A=E7=BB=99?= =?UTF-8?q?=E8=81=94=E5=8A=A8=E9=80=9A=E9=81=93=E8=A3=85=20hooks=EF=BC=8C?= =?UTF-8?q?=E5=85=B3=E9=80=9A=E9=81=93=E6=97=B6=E5=8D=B8=E6=8E=89=E8=87=AA?= =?UTF-8?q?=E5=B7=B1=E7=9A=84=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pet/panorama/actions.py:页面动作的处理器;repair_hooks 只认两条 hooked 通道,调管理器 「已同意、装」那一半,本机装完重探 Windows 一侧,WSL 后台装、install_finished 到了再重探 - service:actions 登记表、run_action(界面线程)、refresh(side) 只重探一侧不开浏览器 - routes:POST /api/actions/<名字>;model.quest 带 action;sources 给缺 hooks 的待处理项挂动作 - 页面:repair.js(confirm → api.post → 结果写在按钮上)、interact.js 待处理与磁贴详情出按钮、 boot.js 的 api.post - AgentLinkManager:set_enabled 拆成「问」和 install_hooks_consented「装」;apply_config 停 hooked 通道时卸自己的 hooks(_uninstall_hooks,别的实例还在用就留着) - app:构造 PanoramaService 时登记 repair_hooks - ADR 0006 补记;docs/config-panorama「动作」一节;session-fish;路线图 M4 第六项打勾;CHANGELOG Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 1 + docs/adr/0006-writing-hooks-needs-consent.md | 6 ++ docs/config-panorama.md | 37 +++++++- docs/roadmap.md | 2 +- docs/session-fish.md | 9 +- pet/agent_link.py | 92 ++++++++++++-------- pet/app.py | 11 ++- pet/locale/en.json | 13 ++- pet/locale/zh.json | 13 ++- pet/panorama/actions.py | 57 ++++++++++++ pet/panorama/model.py | 5 +- pet/panorama/page/app.css | 1 + pet/panorama/page/boot.js | 24 ++--- pet/panorama/page/interact.js | 11 ++- pet/panorama/page/repair.js | 25 ++++++ pet/panorama/render.py | 6 +- pet/panorama/routes.py | 18 ++++ pet/panorama/service.py | 61 ++++++++++++- pet/panorama/sources.py | 8 +- tests/test_claude_hooks_missing.py | 54 ++++++++++++ tests/test_panorama_actions.py | 66 ++++++++++++++ tests/test_panorama_entry.py | 5 +- tests/test_panorama_page.py | 54 ++++++++++++ tests/test_panorama_service.py | 29 ++++++ tests/test_panorama_settings_routes.py | 27 ++++++ tests/test_panorama_sources.py | 9 ++ 26 files changed, 572 insertions(+), 72 deletions(-) create mode 100644 pet/panorama/actions.py create mode 100644 pet/panorama/page/repair.js create mode 100644 tests/test_panorama_actions.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 663b2ac8..73950417 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ## 2026-11 +- 11-19 配置全景的待处理里,「联动开着但没有 hooks」那一条有了「修复」按钮:确认一次就把 hooks 装回去,图上那条断线随即变回来(WSL 那条在后台装,装完自己更新)。从页面或设置进程关掉联动通道时,肥鱼自己装的 hooks 也会一起卸掉,和右键菜单关闭一样 - 11-19 Claude Code 联动、会话小鱼、「最近的对话」的设置搬到了配置全景(四块磁贴各带「设置」)。「最近的对话」最多留几天 / 几条这两项以前只能手改 config.json,现在也能改了。右键「Agent 联动」里只剩开关:上限 / 保留天数 / 配色 / 字号 / 桂冠 / 行数那六个子菜单换成一条「会话小鱼设置…」 - 11-18 右键菜单更短了:「播放动画」「切换角色」「播放速率」「大小」收进了「肥鱼控制」子菜单最上面一组。自己改过菜单编排的不受影响 - 11-18 右键菜单去掉了「快捷启动」和「工具与帮助」(里面只剩一个打开上游仓库的「GitHub 项目页」),设置窗口「菜单」里的「快捷启动」一栏也一起删了。旧的菜单编排里有这几项的,下次加载自动清掉 diff --git a/docs/adr/0006-writing-hooks-needs-consent.md b/docs/adr/0006-writing-hooks-needs-consent.md index 17ea51ce..0bcf260a 100644 --- a/docs/adr/0006-writing-hooks-needs-consent.md +++ b/docs/adr/0006-writing-hooks-needs-consent.md @@ -23,3 +23,9 @@ - 全新安装之后「联动开着但没有 hooks」是常态,直到用户同意一次。 - 运行中被卸掉的 hooks,要到下次启动肥鱼或重新开关联动才会提示。 - hook 事件表加了新事件,老用户会看到缺失提示,重新同意一次才装上。 + +## 补记(2026-11-19) + +配置全景的待处理里有了「修复」按钮:同意框是页面上的 `confirm()`,文案和上面那个弹窗一样,点「取消」什么都不发; +点「确定」才 `POST /api/actions/repair_hooks`,主进程只做「装」那一半(`install_hooks_consented`)。这仍是「用户明确同意之后才写」 +那一条路,只是同意框从桌面搬到了用户正看着的页面。打开通道的开关(菜单或页面)照旧只起监视器,不写 hooks。 diff --git a/docs/config-panorama.md b/docs/config-panorama.md index 48bfe834..07f20de1 100644 --- a/docs/config-panorama.md +++ b/docs/config-panorama.md @@ -240,8 +240,41 @@ sequenceDiagram 开关留在菜单(通道、每个会话一只小鱼、记录最近的对话),上限 / 保留天数 / 配色 / 字号 / 桂冠 / 行数换成一条「会话小鱼设置…」 (`SpriteMenuFacade.open_session_fish_settings` → `open_config_panorama(focus="session_fish")`,会话小鱼自己的菜单同一条)。 页面改完的生效链:`_apply_external_config_change` → 各窗 `refresh_pet_settings` → `AgentLinkManager.apply_config` 启停监视器 -(**从不写 hooks**,ADR 0006;装 hooks 的「修复」动作是下一步);`OverlayShell.refresh_settings` → `_sync_session_settings`: -关掉开关在场的会话小鱼离场、核对一次名册(保留天数)、换桂冠、岛上列表重取,「最近的对话」的保留天数 / 条数真变了才重扫一遍 transcript。 +(**从不写 hooks**,ADR 0006;hooked 通道「在跑 → 停」时顺带卸掉肥鱼自己装的 hooks,和菜单关闭一样); +`OverlayShell.refresh_settings` → `_sync_session_settings`:关掉开关在场的会话小鱼离场、核对一次名册(保留天数)、换桂冠、 +岛上列表重取,「最近的对话」的保留天数 / 条数真变了才重扫一遍 transcript。 + +### 动作:待处理里的「修复」 + +页面上第一个**不是改设置、而是请主进程做一件事**的入口(2026-11-19):联动开着、那一侧的 `settings.json` 里却没有肥鱼的 hooks 时, +待处理里那一条和 `settings.json` 磁贴的详情各出一个「修复」按钮。 + +```mermaid +sequenceDiagram + participant P as 页面(repair.js) + participant H as 本机服务 + participant G as 主进程界面线程 + participant F as ~/.claude/settings.json + P->>P: confirm():同意文案(同右键菜单那条路的 Qt 弹框);取消什么都不发 + P->>H: POST /api/actions/repair_hooks {agent: claude | claude_wsl} + H->>G: on_gui(和改设置同一条路) + G->>F: AgentLinkManager.install_hooks_consented(agent) + Note over G: 本机当场写 → installed;WSL 后台起 wsl.exe → pending,装完发 install_finished + G-->>P: {state: installed | pending | failed} + G->>G: 装好的那一侧重探一次(PanoramaService.refresh(side)),发布,页面原地重画,那条线变回来 +``` + +- **动作是独立的 POST,不藏在 PATCH 设置里**:打开通道的开关永远只是起监视器,装 hooks 永远是另一次明确的点击(ADR 0006 的决定不变, + 只是同意框从桌面搬到了用户正看着的页面;ADR 末尾有补记)。服务端拿到请求就视为「用户点了是」,只调管理器的「装」那一半 + (`install_hooks_consented`),不再弹 Qt 的问题框;菜单那条路仍是 `set_enabled` 先问再调同一个「装」。 +- **登记**:`actions.py` 里一个处理器 `handler(body) -> dict`,应用构造 `PanoramaService` 时传 `actions={"repair_hooks": ...}`; + 路由 `POST /api/actions/<名字>` 把它转到界面线程。处理器自己校验参数(只认两条 hooked 通道,400 `bad_agent`;没有管理器 503 + `no_manager`),不认识的名字 404,处理器出错 500 `action_failed`。以后「重新测试连接」走同一个口。 +- **装完重探**:`_republish` 只重读功能、不重探,而 hooks 在不在是探针读文件得来的。`PanoramaService.refresh(side)` 只重探一侧 + (`win` 重跑 Windows 探针、接上上一次的 WSL 结果;`wsl` 只换那一半),在后台线程里,不开浏览器;一轮完整采集正在路上就不另起。 + WSL 那条装完由 `install_finished` 信号触发重探(处理器对同一个管理器只接一次)。 +- **页面**:`repair.js` 的 `actionButton` / `runAction`;结果写在按钮上(`installed` / `pending` / `failed` 可再点 / 连不上可再点)。 + 离线快照里按钮是灰的。待处理项在数据里多一个 `action: {name, agent, side}`(`Graph.quest(..., action=)`),别的待处理项没有。 ```mermaid flowchart LR diff --git a/docs/roadmap.md b/docs/roadmap.md index 7590809c..9f57a34a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -102,7 +102,7 @@ flowchart LR - [x] 个人助理 - [x] 会话记忆蒸馏(个人侧与公司侧) - [x] ~~文件解读、看屏幕~~ 2026-11-18 定:不搬,两个功能整个删掉([ADR 0016](adr/0016-drop-screen-watching-and-file-interpret.md)) -- [ ] Claude Code 联动与 hooks 修复动作 +- [x] Claude Code 联动与 hooks 修复动作 - [ ] 模型服务列表与密钥、连接测试 ### M5 能编辑:记忆与知识 diff --git a/docs/session-fish.md b/docs/session-fish.md index 65784de1..243fce97 100644 --- a/docs/session-fish.md +++ b/docs/session-fish.md @@ -151,8 +151,13 @@ stateDiagram-v2 - 一个通道的监视器从「没在跑」变成「在跑」时查一次:延迟 5 s,后台线程只读(WSL 是一次 `wsl.exe`),结果经 `hooks_checked` 信号回 GUI 线程。 延迟是因为气泡只发给可见的窗,本机检查不到 1 ms 就有结论,那时鱼还没出场。已经在跑的通道、别的设置变化引起的 `apply_config` 不再查。 -- 缺任何一个事件就冒一条气泡(也进灵动岛的消息记录),并在右键 → Agent 联动里那个通道下面多一条修复项。 - 修复项 = `repair_hooks` = `set_enabled(通道, True)`:弹的是同一个同意框,点「否」什么都不写、联动也不会被关。 +- 缺任何一个事件就冒一条气泡(也进灵动岛的消息记录),并在右键 → Agent 联动里那个通道下面多一条修复项;配置全景的待处理里 + 那一条和 `settings.json` 磁贴也出「修复」按钮(2026-11-19,见[配置全景](config-panorama.md)的「动作」)。 + 菜单的修复项 = `repair_hooks` = `set_enabled(通道, True)`:弹的是同一个同意框,点「否」什么都不写、联动也不会被关。 + 页面的「修复」= 页面上先 `confirm()` 同一段文案,再 `POST /api/actions/repair_hooks` → `install_hooks_consented(通道)`: + 只管「装」那一半,不再弹 Qt 的框。两条路写文件的代码是同一段。 +- 通道从别处(配置全景、设置进程)被关掉:`apply_config` 停监视器时顺带卸掉肥鱼自己装的 hooks(只在「在跑 → 停」这一次转换上做, + 别的实例还在用就留着),和菜单关闭的语义一致。 - 判断不了就不说:那一侧没有 `~/.claude`、WSL 没响应、`settings.json` 不是合法 JSON。 - 每个通道一个轮次计数,装好或通道停下时加一;迟到的检查结论对不上轮次就丢,避免装好之后又冒一条过期提示。 - 只看有没有肥鱼的条目,不核对条目指向的路径。旧 `PetWindow` 的菜单没有修复项(只修崩溃的约定),气泡有。 diff --git a/pet/agent_link.py b/pet/agent_link.py index 2c1bda9d..99232b9c 100644 --- a/pet/agent_link.py +++ b/pet/agent_link.py @@ -2923,6 +2923,10 @@ def apply_config(self) -> None: elif not should_run and monitor._running: monitor.stop() self._forget_hooks_state(key) + if key in self._HOOKED_AGENTS: + # 通道从别处(配置全景、设置进程)被关掉:和菜单关闭一样卸掉肥鱼自己装的 hooks(同意文案里写着 + # 「关闭联动时会自动移除」)。只在「在跑 → 停」这一次转换上做,启动时的 apply_config 不碰文件。 + self._uninstall_hooks(key) self._refresh_moved_hooks(agent_cfg) # ---------------------------------------------------------- 联动开着、hooks 在不在 @@ -2939,6 +2943,50 @@ def repair_hooks(self, agent_key: str) -> bool: return False return self.set_enabled(agent_key, True) + def install_hooks_consented(self, agent_key: str) -> str: + """用户**已经同意**(菜单那条路的 Qt 弹框,或配置全景页面上的确认框):把肥鱼的 hooks 装进这个通道的 settings.json。 + + ADR 0006:这是唯一写 hooks 的地方,调用方必须先拿到同意。本机当场写,返回 ``installed`` / ``failed``; + WSL 要起 wsl.exe,后台装,返回 ``pending``,装完经 ``install_finished`` 回来(``_on_install_finished`` 成功时 + 顺带把通道开上并清掉「缺 hooks」的标记)。不靠 hooks 的通道没有可装的:``failed``。""" + if agent_key == "claude": + if not ClaudeCodeMonitor.install_hooks(self.monitors["claude"].events_file): + return "failed" + self._note_hooks_installed("claude") + return "installed" + if agent_key == "claude_wsl": + # wsl.exe 每次调用上百毫秒、发行版冷启动要几秒:走后台线程,调用方先回去, + # 配置完成后自动开启并气泡告知(同 DSH 安装的编排) + self._install_token += 1 + token = self._install_token + self._install_pending["claude_wsl"] = token + if hasattr(self.win, "show_bubble"): + self.win.show_bubble("正在配置 WSL 里的 Claude Code hooks…", duration_ms=4000) + threading.Thread(target=self._install_claude_wsl_worker, args=(token,), daemon=True, + name="claude-wsl-hooks-install").start() + return "pending" + return "failed" + + def _uninstall_hooks(self, agent_key: str) -> None: + """卸掉肥鱼自己装的 hooks(只删带标记的条目,用户自有配置不碰);别的多开实例还在用就留着(hooks 是全局状态)。 + WSL 那条要调 wsl.exe:后台做,失败只记日志(hook 命令对缺失的脚本 / 目录是空操作,残留条目不会让 Claude Code 报错)。""" + if agent_key == "claude": + if self._other_instances_enabled("claude"): + log.info("其他实例仍在使用 Claude 联动,保留 hooks") + elif not ClaudeCodeMonitor.uninstall_hooks(): + log.warning("Claude hooks 卸载未完全成功(配置已关闭,hooks 可能残留)") + if hasattr(self.win, "show_bubble"): + name = self.AGENT_NAMES.get(agent_key, agent_key) + self.win.show_bubble(self._dialogue("bridge.uninstall.failed", "Claude hooks 卸载未完全成功,可手动检查 ~/.claude/settings.json", name=name), duration_ms=6000) + elif agent_key == "claude_wsl": + self._install_pending.pop("claude_wsl", None) + self._install_token += 1 + if self._other_instances_enabled("claude_wsl"): + log.info("其他实例仍在使用 WSL Claude 联动,保留 hooks") + else: + threading.Thread(target=ClaudeCodeMonitor.uninstall_wsl_hooks, daemon=True, + name="claude-wsl-hooks-uninstall").start() + def _schedule_hooks_check(self, agent_key: str) -> None: """通道刚起来:稍后在后台查一次它的 hooks 在不在。 @@ -3155,14 +3203,13 @@ def set_enabled(self, agent_key: str, enabled: bool) -> bool: ) if res != QMessageBox.StandardButton.Yes: return False - if not ClaudeCodeMonitor.install_hooks(self.monitors["claude"].events_file): + if self.install_hooks_consented("claude") != "installed": QMessageBox.warning( self.win if hasattr(self.win, "winId") else None, "开启 Claude Code 联动", "hooks 配置写入失败,联动未开启。\n可查看日志了解详情。", ) return False - self._note_hooks_installed("claude") elif agent_key == "claude_wsl": res = QMessageBox.question( self.win if hasattr(self.win, "winId") else None, @@ -3174,18 +3221,7 @@ def set_enabled(self, agent_key: str, enabled: bool) -> bool: ) if res != QMessageBox.StandardButton.Yes: return False - # wsl.exe 每次调用上百毫秒、发行版冷启动要几秒:走后台线程, - # 菜单先回弹,配置完成后自动开启并气泡告知(同 DSH 安装的编排) - self._install_token += 1 - token = self._install_token - self._install_pending["claude_wsl"] = token - if hasattr(self.win, "show_bubble"): - self.win.show_bubble("正在配置 WSL 里的 Claude Code hooks…", duration_ms=4000) - import threading - threading.Thread( - target=self._install_claude_wsl_worker, args=(token,), daemon=True, - name="claude-wsl-hooks-install", - ).start() + self.install_hooks_consented("claude_wsl") # 后台装;菜单先回弹,装完自动开启并气泡告知 return False elif agent_key == "dsh": res = QMessageBox.question( @@ -3216,29 +3252,11 @@ def set_enabled(self, agent_key: str, enabled: bool) -> bool: if agent_key == "dsh": self._install_pending.pop("dsh", None) self._install_token += 1 - # 关闭联动时移除我们注入的内容(只删自己的,用户自有配置不碰); - # 其他多开实例仍在使用则保留(hooks/插件是全局状态) - if agent_key == "claude": - if self._other_instances_enabled("claude"): - log.info("其他实例仍在使用 Claude 联动,保留 hooks") - elif not ClaudeCodeMonitor.uninstall_hooks(): - log.warning("Claude hooks 卸载未完全成功(配置已关闭,hooks 可能残留)") - if hasattr(self.win, "show_bubble"): - name = self.AGENT_NAMES.get(agent_key, agent_key) - self.win.show_bubble(self._dialogue("bridge.uninstall.failed", "Claude hooks 卸载未完全成功,可手动检查 ~/.claude/settings.json", name=name), duration_ms=6000) - elif agent_key == "claude_wsl": - self._install_pending.pop("claude_wsl", None) - self._install_token += 1 - if self._other_instances_enabled("claude_wsl"): - log.info("其他实例仍在使用 WSL Claude 联动,保留 hooks") - else: - # 卸载同样要调 wsl.exe:后台做,失败只记日志(hook 命令对缺失的 - # 脚本/目录是空操作,残留条目不会让 Claude Code 报错) - import threading - threading.Thread( - target=ClaudeCodeMonitor.uninstall_wsl_hooks, daemon=True, - name="claude-wsl-hooks-uninstall", - ).start() + # 关闭联动时移除我们注入的内容(只删自己的,用户自有配置不碰);其他多开实例仍在使用则保留。 + # hooked 通道由下面 apply_config 停监视器时顺带卸(在跑 → 停);监视器本来就没在跑的,这里补一下。 + if agent_key in self._HOOKED_AGENTS: + if not self.monitors[agent_key]._running: + self._uninstall_hooks(agent_key) elif agent_key == "dsh": if self._other_instances_enabled("dsh"): log.info("其他实例仍在使用 DSH 联动,保留桥接插件") diff --git a/pet/app.py b/pet/app.py index 448d991c..df3fac8f 100644 --- a/pet/app.py +++ b/pet/app.py @@ -3464,11 +3464,16 @@ def open_config_panorama(self, focus: str = "") -> None: ``focus``:页面画完就直接翻到的那一组设置(设置窗口里「到配置全景里改」经指令通道传来)。""" service = getattr(self, "_panorama_service", None) if service is None or not shiboken6.isValid(service): + from .panorama import actions as panorama_actions from .panorama.service import PanoramaService - # apply:页面改了设置之后跑的应用链,和设置进程存盘后主进程走的是同一条 - service = self._panorama_service = PanoramaService(self.config, health=self._panorama_health, - apply=self._apply_external_config_change, parent=self.app) + # apply:页面改了设置之后跑的应用链,和设置进程存盘后主进程走的是同一条。 + # actions:页面上的动作——「修复」给联动通道装 hooks(同意框在页面上,ADR 0006),装完只重探那一侧。 + service = self._panorama_service = PanoramaService( + self.config, health=self._panorama_health, apply=self._apply_external_config_change, parent=self.app, + actions={"repair_hooks": panorama_actions.repair_hooks( + lambda: getattr(getattr(self, "_shared", None), "agent_link", None), + lambda side: self._panorama_service.refresh(side))}) service.open(focus=focus) def _panorama_health(self) -> tuple[str, str]: diff --git a/pet/locale/en.json b/pet/locale/en.json index cee06bf0..ec4f8612 100644 --- a/pet/locale/en.json +++ b/pet/locale/en.json @@ -1026,7 +1026,7 @@ "menu.shared.one_fish_per_session": "One fish per session", "menu.shared.agent_link": "Agent link", "menu.shared.repair_agent_hooks": "Hooks missing: set up again…", - "agent_link.hooks_missing": "The {name} link is on, but its settings.json lacks the pet's hooks (missing events: {n}), so its status will not arrive. Right-click → Agent link to set them up again.", + "agent_link.hooks_missing": "The {name} link is on, but its settings.json lacks the pet's hooks (missing events: {n}), so its status will not arrive. Right-click → Agent link to set them up again, or press Repair in the config panorama's to-do list.", "menu.shared.every_value_min": "Every {value} min", "menu.shared.check_interval": "Check interval", "menu.shared.check_automatically_while_i_m": "Check automatically while I'm at the computer", @@ -2420,5 +2420,14 @@ "panorama.feature.session_history": "Recent chats", "panorama.note.session_fish": "Fed by link events: one fish per running Claude Code session, frozen once the process is gone", "panorama.note.session_history": "The list on the island: where each session was opened, path and title only", - "menu.shared.session_fish_settings": "Session fish settings…" + "menu.shared.session_fish_settings": "Session fish settings…", + "panorama.ui.repair": "Repair", + "panorama.ui.repair_confirm_win": "Write the fish's event hooks into this machine's ~/.claude/settings.json?\n\nWhile Claude Code works they append the time, event name, session ID and tool name to the fish's local data folder, which the fish uses to update the session fish. Only the fish's own entries are touched; your existing hooks stay. Turning the link off removes them again.", + "panorama.ui.repair_confirm_wsl": "Write the fish's event hooks into the default WSL distro's ~/.claude/settings.json?\n\nWritten through wsl.exe; events go only to the fish's local data folder and carry just the time, event name, session ID and tool name. Only the fish's own entries are touched; your existing hooks stay. Turning the link off removes them again.", + "panorama.ui.repair_working": "Configuring…", + "panorama.ui.repair_installed": "Installed; the map updates in a moment", + "panorama.ui.repair_pending": "Configuring inside WSL; the map updates when it lands", + "panorama.ui.repair_failed": "Could not write it; see the fish log, then try again", + "panorama.ui.repair_lost": "Lost the fish; try again", + "panorama.ui.action_needs_service": "Repair works only on the page opened from the fish; this is the offline snapshot" } diff --git a/pet/locale/zh.json b/pet/locale/zh.json index 6924ffdb..273cd1ec 100644 --- a/pet/locale/zh.json +++ b/pet/locale/zh.json @@ -1018,7 +1018,7 @@ "menu.shared.one_fish_per_session": "每个会话一只小鱼", "menu.shared.agent_link": "Agent 联动", "menu.shared.repair_agent_hooks": "缺 hooks,点此重新配置…", - "agent_link.hooks_missing": "{name} 联动开着,但它的 settings.json 里缺肥鱼的 hooks({n} 个事件),状态收不全。右键 → Agent 联动 里可以重新配置。", + "agent_link.hooks_missing": "{name} 联动开着,但它的 settings.json 里缺肥鱼的 hooks({n} 个事件),状态收不全。右键 → Agent 联动 里可以重新配置,配置全景的待处理里也有「修复」。", "menu.shared.every_value_min": "每 {value} 分钟", "menu.shared.check_interval": "检查间隔", "menu.shared.check_automatically_while_i_m": "电脑在用时自动检查", @@ -2412,5 +2412,14 @@ "panorama.feature.session_history": "最近的对话", "panorama.note.session_fish": "吃联动事件:每个在用的 Claude Code 会话一只小鱼,进程不在了就冻结", "panorama.note.session_history": "灵动岛上的列表:每个会话在哪打开的,只存路径和标题", - "menu.shared.session_fish_settings": "会话小鱼设置…" + "menu.shared.session_fish_settings": "会话小鱼设置…", + "panorama.ui.repair": "修复", + "panorama.ui.repair_confirm_win": "要把肥鱼的事件 hooks 写进本机的 ~/.claude/settings.json 吗?\n\n它们在 Claude Code 干活时把时间、事件名、会话 ID 和工具名写到本机肥鱼目录,肥鱼据此同步会话小鱼的状态。只动肥鱼自己的条目,你已有的 hooks 不碰;关掉联动时会自动移除。", + "panorama.ui.repair_confirm_wsl": "要把肥鱼的事件 hooks 写进 WSL 默认发行版的 ~/.claude/settings.json 吗?\n\n经 wsl.exe 写入,事件只写到本机肥鱼目录,内容仅有时间、事件名、会话 ID 和工具名。只动肥鱼自己的条目,你已有的 hooks 不碰;关掉联动时会自动移除。", + "panorama.ui.repair_working": "正在配置…", + "panorama.ui.repair_installed": "已装好,图上马上更新", + "panorama.ui.repair_pending": "WSL 里正在配置,装完图上自己更新", + "panorama.ui.repair_failed": "没写进去,看肥鱼日志;再试一次", + "panorama.ui.repair_lost": "连不上肥鱼了;再试一次", + "panorama.ui.action_needs_service": "从肥鱼里点「配置全景」打开的页面才能修复;这是离线快照" } diff --git a/pet/panorama/actions.py b/pet/panorama/actions.py new file mode 100644 index 00000000..c0592d1c --- /dev/null +++ b/pet/panorama/actions.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +"""配置全景页面上的**动作**:不是改一项设置,而是请主进程做一件事。现在只有一个——给联动通道装 hooks。 + +一个动作 = 一个处理器 ``handler(body) -> dict``,由应用构造 ``PanoramaService`` 时登记(``actions={"名字": handler}``), +页面 ``POST /api/actions/<名字>`` 来调;服务把它转到界面线程上跑(和改设置同一条路,见 ``PanoramaService.on_gui``)。 +处理器自己校验参数,拒绝就抛 ``ActionError``(状态码 + 代码),意料之外的异常由服务翻成 500 ``action_failed``。 + +**装 hooks 每次都要用户同意(ADR 0006)。** 同意框在页面上(``repair.js`` 的 ``confirm()``,文案同右键菜单那条路的 Qt 弹框); +这里拿到的请求就是「用户点了是」,于是只调管理器的「装」那一半(``install_hooks_consented``),不再弹 Qt 的问题框。 +打开通道的开关永远只是起监视器,装 hooks 永远是这另一次明确的点击——所以它是独立的 POST,不藏在 PATCH 设置里。 +""" +from __future__ import annotations + +import weakref +from typing import Callable + +#: 要靠 hooks 的两条通道 → 它们在图上的哪一侧(装完重探那一侧) +HOOKED_SIDES = {"claude": "win", "claude_wsl": "wsl"} + + +class ActionError(Exception): + """动作没办成。``status`` 和 ``code`` 给页面。""" + + def __init__(self, status: int, code: str) -> None: + super().__init__(code) + self.status, self.code = status, code + + +def repair_hooks(manager_of: Callable[[], object | None], refresh: Callable[[str], object]) -> Callable[[object], dict]: + """「修复」动作的处理器。``manager_of()`` 给当前的 ``AgentLinkManager``(没有就是 None);``refresh(side)`` 让服务只重探那一侧。 + + 本机那条当场写完 → ``installed``,马上重探本机一侧(那条断线要变回来,而 hooks 在不在是探针读文件得来的)。 + WSL 那条要起 wsl.exe,管理器后台装 → ``pending``;装完它发 ``install_finished``,接到成功的那一下再重探 WSL 一侧。 + 同一个管理器只接一次信号(WeakSet 记着),免得点两次修复、装完重探两遍。写不进去 → ``failed``,什么都不重探。 + """ + watched: "weakref.WeakSet" = weakref.WeakSet() + + def on_finished(agent_key: str, ok: bool, _message: str, _token: int) -> None: + if ok and agent_key == "claude_wsl": + refresh("wsl") + + def run(body) -> dict: + agent = body.get("agent") if isinstance(body, dict) else None + if not isinstance(agent, str) or agent not in HOOKED_SIDES: + raise ActionError(400, "bad_agent") + manager = manager_of() + if manager is None: + raise ActionError(503, "no_manager") + state = str(manager.install_hooks_consented(agent)) + if state == "installed": + refresh(HOOKED_SIDES[agent]) + elif state == "pending" and manager not in watched: + watched.add(manager) + manager.install_finished.connect(on_finished) + return {"agent": agent, "state": state} + + return run diff --git a/pet/panorama/model.py b/pet/panorama/model.py index 7e5a5cb7..9a0ff439 100644 --- a/pet/panorama/model.py +++ b/pet/panorama/model.py @@ -74,10 +74,11 @@ def edge(self, source: str, target: str, line: str, state: str = "ok", label: st raise ValueError(f"bad edge {source}->{target}: state={state} line={line}") self.edges.append({"from": source, "to": target, "line": line, "state": state, "label": label}) - def quest(self, level: str, text: str, node: str) -> None: + def quest(self, level: str, text: str, node: str, action: dict | None = None) -> None: + """``action``:页面上能点的动作 ``{"name", "agent", "side"}``(见 ``actions.py``);没有就只是一条说明。""" if level not in QUEST_LEVELS: raise ValueError(f"bad quest level {level}") - self.quests.append({"sev": level, "text": text, "node": node}) + self.quests.append({"sev": level, "text": text, "node": node, **({"action": action} if action else {})}) def add_fact(self, node_id: str, label: str, value: str) -> None: """给别的来源建的磁贴补一行事实;那块磁贴这次没出现就算了。""" diff --git a/pet/panorama/page/app.css b/pet/panorama/page/app.css index 16047187..16006903 100644 --- a/pet/panorama/page/app.css +++ b/pet/panorama/page/app.css @@ -182,6 +182,7 @@ aside{display:flex;flex-direction:column;gap:14px;position:sticky;top:60px} .list .more dt{color:var(--muted)}.list .more dd{margin:0;word-break:break-word;color:#c5ced8} .quest{display:flex;gap:9px;align-items:flex-start;padding:7px 0;border-top:1px solid #252e38;cursor:pointer;font-size:12.5px} .quest:first-of-type{border-top:0}.quest:hover{color:#fff}.quest .dot{margin-top:4px} +.quest span{flex:1}.btn.mini{padding:2px 8px;font-size:11.5px;flex:none;align-self:center} .hint{color:var(--muted);font-size:12px} .pending{margin:8px 16px 0;padding:6px 12px;background:#2a2410;color:var(--warn);font-size:12.5px;animation:blink 1.6s ease-in-out infinite} .pending.lost{background:#2a1414;color:var(--bad);animation:none} diff --git a/pet/panorama/page/boot.js b/pet/panorama/page/boot.js index 1f81b7ca..edb56bd2 100644 --- a/pet/panorama/page/boot.js +++ b/pet/panorama/page/boot.js @@ -5,7 +5,7 @@ - 本机服务(127.0.0.1 上的页面):令牌从网址的 # 片段里取,马上从地址栏抹掉,之后只放在请求头里; 向 /api/graph 要数据。同一个标签页刷新时令牌从 sessionStorage 里取回。 片段里令牌后面可以跟 &settings=<组>(设置窗口里点「到配置全景里改」时肥鱼这样开):第一张图画完就翻到那一组设置。 - 改设置走 api.patch:JSON、PATCH、带令牌;服务的每一种回答(包括 4xx)都原样交给表单,只有连不上才算失败。 + 改设置走 api.patch、动作走 api.post:JSON、带令牌;服务的每一种回答(包括 4xx)都原样交给调用方,只有连不上才算失败。 拿到第一份之后带着它的编号去「等更新的」(/api/graph?after=编号):服务把请求挂住,有新数据的那一刻才回, 页面原地重画并保留选中状态。标签页藏起来时不等——服务靠这个知道「没人在看」,空闲够久就自停。 @@ -49,15 +49,19 @@ import {start} from './app.js'; return response.json(); }); } - api.patch = function (path, data) { /* 结果是 {status, body};不按状态码抛,只有连不上才 reject */ - var headers = {'Content-Type': 'application/json'}, status = null; - headers[TOKEN_HEADER] = token; - return fetch(path, {method: 'PATCH', headers: headers, body: JSON.stringify(data)}).then(function (response) { - status = response.status; - return response.json(); - }).then(function (body) { return {status: status, body: body || {}}; }, - function (error) { if (status === null) throw error; return {status: status, body: {}}; }); - }; + function send(method) { /* 结果是 {status, body};不按状态码抛,只有连不上才 reject */ + return function (path, data) { + var headers = {'Content-Type': 'application/json'}, status = null; + headers[TOKEN_HEADER] = token; + return fetch(path, {method: method, headers: headers, body: JSON.stringify(data)}).then(function (response) { + status = response.status; + return response.json(); + }).then(function (body) { return {status: status, body: body || {}}; }, + function (error) { if (status === null) throw error; return {status: status, body: {}}; }); + }; + } + api.patch = send('PATCH'); /* 改设置 */ + api.post = send('POST'); /* 动作(待处理里的「修复」) */ var view = null, revision = 0, waiting = false, dead = false; diff --git a/pet/panorama/page/interact.js b/pet/panorama/page/interact.js index b667e3c8..3a1e6487 100644 --- a/pet/panorama/page/interact.js +++ b/pet/panorama/page/interact.js @@ -6,6 +6,7 @@ import {esc} from './util.js'; import {viewer} from './viewer.js'; import {memory} from './memory.js'; import {settingsPanel} from './settings.js'; +import {actionButton, runAction} from './repair.js'; export function interact(M, E, map, kept, api) { const {G, R, N, W, H} = M; @@ -44,6 +45,7 @@ function detail(id) { const box = document.getElementById('detail'); /* 要处理的(坏了、待授权、警告)在前,这台机器上没有的垫底;探测不到的和正常的不分先后,保持数据给的顺序 */ const rank = r => r.state === 'off' ? 2 : r.state === 'ok' || r.state === 'unknown' || r.state === 'live' ? 1 : 0; const rows = (n.items || []).slice().sort((a, b) => rank(a) - rank(b)); + const todo = G.quests.find(q => q.node === id && q.action); /* 这块磁贴有能点的动作(装 hooks):详情里也给一个按钮 */ const nb = (list, key) => list.map(e => ``).join(''); box.innerHTML = `

${esc(k.name || n.kind)} · ${esc(R[n.region].title)}

${esc(n.title)}

${STATE[n.state] || ''}
@@ -51,7 +53,7 @@ function detail(id) { const box = document.getElementById('detail'); ${rows.length ? `
${rows.map(r => `
${esc(r.name)}${esc(r.detail || '')}${r.view ? viewBtn(r.view, r.name, 'peek') : ''}
` + (r.more ? `
${r.more.map(([a, b]) => `
${esc(a)}
${esc(b)}
`).join('')}
` : '')).join('')}
` : ''} ${src.path ? `
${esc(src.path)}${src.key ? '
→ ' + esc(src.key) : ''}
` : ''} -
${n.settings ? `` : ''}${n.view ? viewBtn(n.view, n.title, 'btn') : ''}${n.memory ? `` : ''}${link ? `${esc(S.open_vscode)}` : ''}${src.path ? `` : ''} +
${actionButton(S, todo, api).replace(' mini', '')}${n.settings ? `` : ''}${n.view ? viewBtn(n.view, n.title, 'btn') : ''}${n.memory ? `` : ''}${link ? `${esc(S.open_vscode)}` : ''}${src.path ? `` : ''} ${n.page ? `${esc(S.settings_at.replace('{page}', n.page))}` : ''}
${out.length ? `

${esc(S.uses)}

${nb(out, 'to')}
` : ''} ${inn.length ? `

${esc(S.used_by)}

${nb(inn, 'from')}
` : ''}`; } @@ -62,13 +64,16 @@ function search(text) { const q = text.trim().toLowerCase(); if (!q) return pain paint(new Set(G.nodes.filter(n => [n.title, n.sub, ...(n.lines || []), (G.kinds[n.kind] || {}).name, ...(n.facts || []).reduce((all, f) => all.concat(f), []), ...(n.items || []).map(p => p.name), ...(n.items || []).reduce((all, p) => all.concat((p.more || []).map(m => m[1])), []), (n.source || {}).path, (n.source || {}).key].join(' ').toLowerCase().includes(q)).map(n => n.id)), new Set()); } map.addEventListener('click', ev => { const t = ev.target.closest('.tile'); select(t ? (t.dataset.id === selected ? null : t.dataset.id) : null); }, on); document.getElementById('detail').addEventListener('click', ev => { + const act = ev.target.closest('[data-action]'); if (act) return act.disabled || runAction(api, S, act); const go = ev.target.closest('[data-go]'); if (go) return select(go.dataset.go); const see = ev.target.closest('[data-view]'); if (see) return files.open(see.dataset.view, see.dataset.title); const set = ev.target.closest('[data-settings]'); if (set) return panel.open(set.dataset.settings, set.dataset.title); if (ev.target.closest('[data-memory]')) return memo.open(); const cp = ev.target.closest('[data-copy]'); if (cp) { navigator.clipboard?.writeText(cp.dataset.copy); cp.textContent = S.copied; } }, on); -document.getElementById('quests').innerHTML = !G.quests.length ? `

${esc(S.no_quests)}

` : G.quests.map(q => `
${esc(q.text)}
`).join(''); -document.getElementById('quests').addEventListener('click', ev => { const q = ev.target.closest('[data-go]'); if (q && N[q.dataset.go]) select(q.dataset.go); }, on); +document.getElementById('quests').innerHTML = !G.quests.length ? `

${esc(S.no_quests)}

` : G.quests.map(q => `
${esc(q.text)}${actionButton(S, q, api)}
`).join(''); +document.getElementById('quests').addEventListener('click', ev => { + const act = ev.target.closest('[data-action]'); if (act) return act.disabled || runAction(api, S, act); + const q = ev.target.closest('[data-go]'); if (q && N[q.dataset.go]) select(q.dataset.go); }, on); document.getElementById('lines').innerHTML = Object.entries(G.lines).map(([k, l]) => ``).join(''); document.getElementById('lines').addEventListener('click', ev => { const c = ev.target.closest('[data-line]'); if (!c) return; pickLine(c.dataset.line === lineOn ? null : c.dataset.line); }, on); diff --git a/pet/panorama/page/repair.js b/pet/panorama/page/repair.js new file mode 100644 index 00000000..5fd2732a --- /dev/null +++ b/pet/panorama/page/repair.js @@ -0,0 +1,25 @@ +/* 待处理里的「修复」:页面上能点的第一个动作(装 hooks)。 + + 装 hooks 每次都要用户同意(ADR 0006):先 confirm(),文案和右键菜单那条路的 Qt 弹框一样;点「取消」什么都不发。 + 同意了才 POST /api/actions/<动作>,结果写在按钮上:installed(本机当场装好,服务随后重探、页面原地重画,那条线 + 变回来)/ pending(WSL 在后台装,装完服务自己重探)/ failed(可以再点)。连不上也可以再点。 + 离线快照没有服务,按钮是灰的(interact.js 画的时候就决定了)。 */ +import {esc} from './util.js'; + +/* 一条待处理项(或它指的那块磁贴)的动作按钮;没有动作就是空串 */ +export const actionButton = (S, quest, api) => !quest || !quest.action ? '' : + ``; + +/* 点了按钮:问 → 发 → 把结果写在按钮上。结果是 installed / pending / failed / lost,取消是 null */ +export function runAction(api, S, el) { + const name = el.dataset.action, agent = el.dataset.agent, side = el.dataset.side; + /* 取消:同步地「算完了」(不用 Promise.resolve:测试里的假环境没有微任务队列)*/ + if (!confirm(S['repair_confirm_' + side] || S.repair_confirm_win)) return {then: function (ok) { if (ok) ok(null); return this; }}; + el.disabled = true; el.textContent = S.repair_working; + return api.post('/api/actions/' + encodeURIComponent(name), {agent: agent}).then(r => { + const state = r.status === 200 && r.body && r.body.state ? r.body.state : 'failed'; + el.textContent = S['repair_' + state] || S.repair_failed; + if (state === 'failed') el.disabled = false; + return state; + }, () => { el.textContent = S.repair_lost; el.disabled = false; return 'lost'; }); +} diff --git a/pet/panorama/render.py b/pet/panorama/render.py index 741063c6..79216a5f 100644 --- a/pet/panorama/render.py +++ b/pet/panorama/render.py @@ -30,8 +30,8 @@ #: 页面脚本的原生模块,**按依赖顺序**:被 import 的排在前面,入口 ``boot.js`` 在最后。 #: 本机服务把它们一个个发出去,浏览器按 import 自己装配;离线快照没法这样(``file://`` 页面加载不了模块), #: 所以 ``bundle()`` 按这个顺序把它们拼成一段普通脚本。加模块就在这里登记。 -MODULES = ("util.js", "layout.js", "roads.js", "draw.js", "viewer.js", "memory.js", "form.js", "settings.js", "interact.js", - "app.js", "boot.js") +MODULES = ("util.js", "layout.js", "roads.js", "draw.js", "viewer.js", "memory.js", "form.js", "settings.js", "repair.js", + "interact.js", "app.js", "boot.js") #: 本机服务发的静态文件:名字 → 内容类型。**都不含用户数据**,所以不要令牌。 ASSETS = {**{name: "text/css; charset=utf-8" for name in STYLES}, **{name: "text/javascript; charset=utf-8" for name in MODULES}} @@ -45,6 +45,8 @@ "viewer_truncated", "viewer_managed", "viewer_more", "viewer_binary", "memory_button", "memory_title", "memory_global", "memory_project", "memory_own", "memory_none", "memory_only_flagged", "memory_all", "memory_note", "memory_count", "memory_truncated", "memory_empty", "settings_open", "settings_needs_service", "settings_failed", "settings_unsaved", + "repair", "repair_confirm_win", "repair_confirm_wsl", "repair_working", "repair_installed", "repair_pending", + "repair_failed", "repair_lost", "action_needs_service", *("form_" + key for key in ( "saving", "saved", "stale", "invalid", "busy", "unavailable", "failed", "lost", "save", "revert", "restore_builtin", "using_builtin", "dirty", "custom", "custom_label", "advanced", "err_unknown", "err_type", "err_not_a_choice", diff --git a/pet/panorama/routes.py b/pet/panorama/routes.py index 80e26428..3c875e6c 100644 --- a/pet/panorama/routes.py +++ b/pet/panorama/routes.py @@ -13,6 +13,9 @@ 文件,要令牌。能读哪些由 ``files.py`` 把关;这里只把它的拒绝翻成状态码(``not_viewable`` / ``not_found`` → 404, ``bad_path`` → 400,``unavailable`` → 503:要去 WSL 里读而那边没回话)。没给读取器(``files=None``)时这两个网址不存在。 +- ``POST /api/actions/<动作>``:页面上的一个动作(现在只有 ``repair_hooks``:给联动通道装 hooks),要令牌。处理器在 + ``actions.py``,由应用登记进服务;这里只把 ``ActionError`` 翻成状态码。没给设置入口时这个网址也不存在。 + - ``GET /api/settings/<组>``、``PATCH /api/settings/<组>``、``GET /api/audit``:读、改一组设置,翻审计记录,都要令牌。 这是本机服务第一批**会改东西**的接口。守门检查(来源、令牌、JSON、大小)在 ``server.py``;改之前的每一道校验在 ``settings_api.py``;这里只把结果和拒绝翻成响应。拒绝时除了代码还带着页面用得上的东西(哪几项不对、现在的值)。 @@ -25,6 +28,7 @@ from urllib.parse import parse_qs from . import render +from .actions import ActionError from .feed import Feed from .files import FileError from .settings_api import Busy, SettingsError @@ -77,6 +81,19 @@ def audit(request: Request) -> Response: router.add("GET", "/api/audit", audit) +def _add_action_routes(router: Router, port) -> None: + """``port.run_action(名字, 请求体)``:它自己转到界面线程上去办。""" + def run(request: Request) -> Response: + try: + return Response.json(port.run_action(request.params["name"], request.json())) + except ActionError as exc: + return Response.error(exc.status, exc.code) + except Busy: + return Response.error(503, "busy") + + router.add("POST", "/api/actions/{name}", run) + + def build_router(feed: Feed, *, files=None, settings=None, wait_seconds: float = LONG_POLL_SECONDS) -> Router: router = Router() router.static("/", lambda: render.shell().encode("utf-8"), "text/html; charset=utf-8") @@ -106,4 +123,5 @@ def graph(request: Request) -> Response: _add_file_routes(router, files) if settings is not None: _add_settings_routes(router, settings) + _add_action_routes(router, settings) return router diff --git a/pet/panorama/service.py b/pet/panorama/service.py index 629c24c9..e2e8e887 100644 --- a/pet/panorama/service.py +++ b/pet/panorama/service.py @@ -27,6 +27,7 @@ from PySide6.QtWidgets import QApplication from . import features, probes, render, settings_api, sources +from .actions import ActionError from .feed import Feed from .settings_api import Busy @@ -87,7 +88,7 @@ def __init__(self, config, *, health: Callable[[], tuple[str, str]] | None = Non wsl: Callable[[], dict] | None = None, write: Callable[[dict, Path], Path] | None = None, open_page: Callable[[str], object] | None = None, spawn: Callable | None = None, server=None, apply: Callable[[], object] | None = None, audit=None, - parent: QObject | None = None) -> None: + actions: dict | None = None, parent: QObject | None = None) -> None: super().__init__(parent) self._config = config self._health = health or (lambda: ("unknown", "")) @@ -105,6 +106,7 @@ def __init__(self, config, *, health: Callable[[], tuple[str, str]] | None = Non self._last_wsl_seconds: float | None = None self._apply = apply # 设置改完之后要跑的应用链(应用传进来:_apply_external_config_change) self._audit = audit # 审计记录;不给就用数据目录里那一份(第一次用到时才建) + self.actions: dict = dict(actions or {}) # 页面上的动作:名字 → 处理器(见 actions.py),应用登记 self._last_published: tuple[dict, Path] | None = None # 上一次发布用的事实和快照目录:设置改了之后拿它重画 self._settings_dirty = False # 设置在一轮采集途中被改过:那一轮回来时要按新设置再发布一次 self._focus = "" # 这次打开要直接翻到的那一组设置(只用一次) @@ -280,6 +282,63 @@ def read_audit(self, limit: int) -> list[dict]: """审计记录只读文件,不碰 ``Config``:就在请求线程上读。""" return self._audit_log().read(limit) + def run_action(self, name: str, body) -> dict: + """页面上的一个动作(``POST /api/actions/<名字>``):在界面线程上跑登记好的处理器。不认识的名字 404; + 处理器自己的拒绝(``ActionError``)原样回去;意料之外的异常记日志、回 500。""" + return self.on_gui(lambda: self._run_action(name, body)) + + def _run_action(self, name: str, body) -> dict: + handler = self.actions.get(str(name)) + if handler is None: + raise ActionError(404, "unknown_action") + try: + return handler(body) + except ActionError: + raise + except Exception: # noqa: BLE001 - 处理器出错不能把连接挂死;页面要一个明确的回答 + log.exception("配置全景:动作 %s 出错", name) + raise ActionError(500, "action_failed") from None + + def refresh(self, side: str) -> bool: + """(界面线程)只重探一侧、不开浏览器,再发布一次。装完 hooks 之后用:那条断线要变回来,而 hooks 在不在是探针 + 读文件得来的,``_republish`` 只重读功能、不重探。返回是否发起了。 + + 一轮完整采集正在路上就不另起(它回来时自带新状态);还没发布过也不起(没有页面在看)。``win`` 一侧重探完 + 接上上一次的 WSL 结果和它的耗时;``wsl`` 一侧只换那一半。 + """ + if side not in ("win", "wsl") or self._busy or self._last_published is None: + return False + facts, out_dir = self._last_published + try: + cfg = copy.deepcopy(self._config.data) + cfg_path, health = Path(self._config.path), tuple(self._health()) + except Exception: # noqa: BLE001 + log.exception("配置全景:读取配置失败") + return False + generation = self._generation + + def run() -> None: + try: + if side == "win": + fresh = self._windows(cfg, cfg_path=cfg_path, secret_get=self._secret_get, api_health=health) + fresh["wsl"] = facts.get("wsl", {"pending": True}) + if "wsl_s" in facts.get("timing", {}): + fresh.setdefault("timing", {})["wsl_s"] = facts["timing"]["wsl_s"] + else: + fresh = {**facts, "wsl": self._wsl()} + if generation != self._generation: # 期间开了新的一轮:它的结果更新 + return + self._publish(fresh, out_dir) + except Exception: # noqa: BLE001 - 重探失败:页面留着上一份 + log.exception("配置全景:重探 %s 一侧失败", side) + + try: + self._spawn(run) + except Exception: # noqa: BLE001 + log.exception("配置全景:启动线程失败") + return False + return True + def _write_settings(self, group_id: str, body) -> dict: """(界面线程)改一组设置。真的改了东西之后:跑应用链,再把图上的功能磁贴换成新值发布出去。""" out = settings_api.write(self._config, group_id, body, audit=self._audit_log()) diff --git a/pet/panorama/sources.py b/pet/panorama/sources.py index 2e4ced03..b4bb9165 100644 --- a/pet/panorama/sources.py +++ b/pet/panorama/sources.py @@ -231,8 +231,9 @@ def claude_code_windows(g: Graph, f: dict) -> None: g.edge("cc_win", "plug_win", "config") if items: g.quest("unknown", L("quest.personal_connectors", n=len(items)), "conn_p_rest") - if link_on and not hooks: - g.quest("bad", L("quest.link_no_hooks", side=L("side.win")), "set_win") + if link_on and not hooks: # 页面上能直接「修复」:动作走 POST /api/actions/repair_hooks,先问一次同意(ADR 0006) + g.quest("bad", L("quest.link_no_hooks", side=L("side.win")), "set_win", + action={"name": "repair_hooks", "agent": "claude", "side": "win"}) g.quest("info", L("quest.memory_coverage", n=c["memory_count"], total=c["projects"]), "mem_win") @@ -374,7 +375,8 @@ def claude_code_wsl(g: Graph, f: dict) -> None: if i["state"] == "bad": g.quest("bad", L("quest.connector_failed", name=i["name"], detail=i["detail"]), "conn_w_rest") if link_on and not hooks: - g.quest("bad", L("quest.link_no_hooks", side=L("side.wsl")), "set_wsl") + g.quest("bad", L("quest.link_no_hooks", side=L("side.wsl")), "set_wsl", + action={"name": "repair_hooks", "agent": "claude_wsl", "side": "wsl"}) @source diff --git a/tests/test_claude_hooks_missing.py b/tests/test_claude_hooks_missing.py index c042df51..cc46e239 100644 --- a/tests/test_claude_hooks_missing.py +++ b/tests/test_claude_hooks_missing.py @@ -364,3 +364,57 @@ def test_menu_adds_a_repair_item_under_the_channel_that_lost_its_hooks(tmp_path, def test_menu_is_unchanged_when_nothing_is_missing(tmp_path, monkeypatch): _menu, actions, _pet = _agent_menu(tmp_path, monkeypatch, _MenuPet) assert [label for label in (action.text() for action in actions) if "hooks" in label] == [] + + +# ---------------------------------------------------------------- 配置全景的「修复」:同意框在页面上,这里只管「装」 + +def test_installing_after_consent_given_elsewhere_writes_without_asking_and_clears_the_mark(tmp_path, home, managers, monkeypatch): + """页面上的「修复」已经让用户点过确认框:管理器这一半只装、不再弹 Qt 的问题框(conftest 里它默认答「否」)。""" + path = _write_settings(home, {"hooks": {"Stop": [_USER_HOOK]}}) + mgr, _win = _manager(tmp_path, managers) + assert _pump_until(lambda: bool(mgr.hooks_missing("claude"))) + monkeypatch.setattr(QMessageBox, "question", staticmethod(lambda *a, **k: pytest.fail("不该再问"))) + + assert mgr.install_hooks_consented("claude") == "installed" + + data = json.loads(path.read_text(encoding="utf-8")) + assert claude_hooks.missing_hook_events(data) == [] and data["hooks"]["Stop"][0] == _USER_HOOK + assert mgr.hooks_missing("claude") == () + assert mgr.install_hooks_consented("cursor") == "failed", "不靠 hooks 的通道没有可装的" + + +def test_a_local_install_that_fails_is_reported_not_raised(tmp_path, home, managers, monkeypatch): + _write_settings(home, {}) + mgr, _win = _manager(tmp_path, managers) + monkeypatch.setattr(ClaudeCodeMonitor, "install_hooks", classmethod(lambda cls, events_file: False)) + assert mgr.install_hooks_consented("claude") == "failed" + + +def test_switching_a_hooked_channel_off_through_the_config_removes_only_the_fish_hooks(tmp_path, home, managers): + """页面关掉通道:配置落盘 → apply_config 停监视器,顺带卸掉肥鱼自己装的 hooks(同意文案写着「关闭联动时会自动移除」); + 用户自己的 hook 原样留着。""" + path = _write_settings(home, {"hooks": {"Stop": [_USER_HOOK]}}) + mgr, _win = _manager(tmp_path, managers) + assert mgr.install_hooks_consented("claude") == "installed" + assert claude_hooks.missing_hook_events(json.loads(path.read_text(encoding="utf-8"))) == [] + + mgr.cfg.set("agent_link", {**mgr.cfg.get("agent_link"), "claude": False}) + mgr.apply_config() + + data = json.loads(path.read_text(encoding="utf-8")) + assert data == {"hooks": {"Stop": [_USER_HOOK]}}, "只卸自己的" + assert mgr.monitors["claude"]._running is False + mgr.apply_config() + assert json.loads(path.read_text(encoding="utf-8")) == {"hooks": {"Stop": [_USER_HOOK]}}, "再应用一次不再碰文件" + + +def test_another_instance_still_using_the_channel_keeps_the_hooks_when_this_one_stops(tmp_path, home, managers): + path = _write_settings(home, {}) + mgr, _win = _manager(tmp_path, managers) + assert mgr.install_hooks_consented("claude") == "installed" + (mgr.cfg.dir / "config-pet2.json").write_text(json.dumps({"agent_link": {"claude": True}}), encoding="utf-8") + + mgr.cfg.set("agent_link", {**mgr.cfg.get("agent_link"), "claude": False}) + mgr.apply_config() + + assert claude_hooks.missing_hook_events(json.loads(path.read_text(encoding="utf-8"))) == [], "别的实例还在用:留着" diff --git a/tests/test_panorama_actions.py b/tests/test_panorama_actions.py new file mode 100644 index 00000000..1a60b362 --- /dev/null +++ b/tests/test_panorama_actions.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +"""配置全景页面上的动作(``pet/panorama/actions.py``):现在只有一个——给联动通道装 hooks。 + +动作不是改设置:它让主进程做一件事。这里从动作处理器的公开面测:参数校验、调管理器的「已同意、装」那一半、 +装完让服务只重探那一侧;WSL 那条是后台装,处理器先回 pending,装完的信号到了再重探。 +""" +from __future__ import annotations + +import pytest +from PySide6.QtCore import QObject, Signal + +from pet.panorama import actions + + +class _Manager(QObject): + install_finished = Signal(str, bool, str, int) + + def __init__(self, outcome: str) -> None: + super().__init__() + self.outcome, self.asked = outcome, [] + + def install_hooks_consented(self, agent_key: str) -> str: + self.asked.append(agent_key) + return self.outcome + + +def _handler(manager, refreshed): + return actions.repair_hooks(lambda: manager, refreshed.append) + + +def test_a_local_install_writes_at_once_and_reprobes_the_windows_side(): + manager, refreshed = _Manager("installed"), [] + out = _handler(manager, refreshed)({"agent": "claude"}) + assert out == {"agent": "claude", "state": "installed"} and manager.asked == ["claude"] and refreshed == ["win"] + + +def test_a_wsl_install_is_pending_and_the_wsl_side_is_reprobed_when_the_install_lands(): + manager, refreshed = _Manager("pending"), [] + run = _handler(manager, refreshed) + assert run({"agent": "claude_wsl"}) == {"agent": "claude_wsl", "state": "pending"} and refreshed == [] + manager.install_finished.emit("claude_wsl", False, "no distro", 1) + assert refreshed == [], "没装成就没什么可重探的" + manager.install_finished.emit("claude_wsl", True, "", 2) + assert refreshed == ["wsl"] + run({"agent": "claude_wsl"}) + manager.install_finished.emit("claude_wsl", True, "", 3) + assert refreshed == ["wsl", "wsl"], "同一个管理器只接一次信号,不会一次装完重探两遍" + + +def test_a_failed_install_says_so_and_reprobes_nothing(): + manager, refreshed = _Manager("failed"), [] + assert _handler(manager, refreshed)({"agent": "claude"}) == {"agent": "claude", "state": "failed"} and refreshed == [] + + +@pytest.mark.parametrize("body", [{}, {"agent": "cursor"}, {"agent": 3}, "claude", None]) +def test_only_the_two_hooked_channels_are_accepted(body): + manager, refreshed = _Manager("installed"), [] + with pytest.raises(actions.ActionError) as caught: + _handler(manager, refreshed)(body) + assert (caught.value.status, caught.value.code) == (400, "bad_agent") and manager.asked == [] + + +def test_without_a_link_manager_the_action_is_unavailable(): + with pytest.raises(actions.ActionError) as caught: + actions.repair_hooks(lambda: None, lambda side: None)({"agent": "claude"}) + assert (caught.value.status, caught.value.code) == (503, "no_manager") diff --git a/tests/test_panorama_entry.py b/tests/test_panorama_entry.py index 83c2998d..7142342a 100644 --- a/tests/test_panorama_entry.py +++ b/tests/test_panorama_entry.py @@ -23,8 +23,8 @@ class _FakeService: """替掉真服务:记下被打开了几次、体检结论读到什么,不起线程、不开浏览器。""" made: list = [] - def __init__(self, config, *, health=None, apply=None, parent=None): - self.config, self.health, self.apply, self.opened = config, health, apply, 0 + def __init__(self, config, *, health=None, apply=None, actions=None, parent=None): + self.config, self.health, self.apply, self.actions, self.opened = config, health, apply, dict(actions or {}), 0 _FakeService.made.append(self) def open(self, focus=""): @@ -150,6 +150,7 @@ def test_shell_opens_the_panorama_from_the_island_panel_and_reuses_one_service(t assert len(fake_service.made) == 1 and fake_service.made[0].opened == 1 assert fake_service.made[0].config is shell.config assert fake_service.made[0].apply == shell._apply_external_config_change # 页面改了设置后跑的应用链,和设置进程存盘后的是同一条 + assert set(fake_service.made[0].actions) == {"repair_hooks"} # 页面上的「修复」动作登记进了服务 shell._api_key_monitor.status_changed.emit("bad", "DeepSeek · 认证失败") state, _detail = fake_service.made[0].health() assert state == shell._api_key_monitor.state # 体检结论取自岛上的体检器 diff --git a/tests/test_panorama_page.py b/tests/test_panorama_page.py index 9cb0c92d..009d2381 100644 --- a/tests/test_panorama_page.py +++ b/tests/test_panorama_page.py @@ -621,3 +621,57 @@ def test_pending_snapshot_rereads_its_own_file_a_bounded_number_of_times(engine) first = _boot(engine, setup, "tick();") assert first["reloads"] == 1 and first["hash"] == "1" # 重读次数记在 # 后面 assert _boot(engine, setup + "location.hash = '#40';")["timers"] == 0 # 到头了就不再排下一次 + + +# ───────────────────────── 待处理里的「修复」 ───────────────────────── + +def _no_hooks_graph(): + return sources.build(samples.facts(win=samples.home(hooks={"Stop": {"total": 1, "fish": 0}}))) + + +def test_a_quest_with_an_action_gets_a_repair_button_only_where_there_is_a_service(engine): + i18n.set_language("zh") + graph = _no_hooks_graph() + data = json.dumps(render.page_data(graph), ensure_ascii=False) + served = _evaluate(engine, FAKE_DOM + render.bundle(render.MODULES[:-1]) + f"\nvar size = start({data}, undefined, function () {{}});" + REPORT) + assert served["quests"].count('data-action="repair_hooks"') == 1 and 'data-agent="claude"' in served["quests"] + assert "disabled" not in served["quests"] and ">修复<" in served["quests"] + snapshot = _run(engine, graph) + assert 'data-action="repair_hooks"' in snapshot["quests"] and "disabled" in snapshot["quests"], "离线快照:按钮灰着" + + +REPAIR_HARNESS = """ +var confirms = [], answer = true, posted = [], reply = {status: 200, body: {state: 'installed'}}; +var confirm = function (text) { confirms.push(text); return answer; }; +function done(value, failed) { + return {then: function (ok, err) { var h = failed ? err : ok; if (!h) return done(value, failed); + try { return done(h(value), false); } catch (e) { return done(e, true); } }}; +} +var api = function () {}; api.post = function (path, body) { posted.push({path: path, body: body}); return reply === 'gone' ? done(new Error('gone'), true) : done(reply, false); }; +var el = {dataset: {action: 'repair_hooks', agent: 'claude_wsl', side: 'wsl'}, disabled: false, textContent: '修复'}; +var S = {repair: '修复', repair_confirm_win: 'WIN?', repair_confirm_wsl: 'WSL?', repair_working: '正在配置…', repair_installed: '已装好', + repair_pending: '正在配置 WSL…', repair_failed: '没装成', repair_lost: '连接断了'}; +""" + + +def _repair(engine, steps: str) -> dict: + return _evaluate(engine, FAKE_DOM + REPAIR_HARNESS + render.bundle(("util.js", "repair.js")) + steps + + "\nreturn JSON.stringify({confirms: confirms, posted: posted, text: el.textContent, disabled: el.disabled, out: out});") + + +def test_repair_asks_first_posts_the_agent_and_writes_the_outcome_on_the_button(engine): + out = _repair(engine, "var out = null; runAction(api, S, el).then(function (s) { out = s; });") + assert out["confirms"] == ["WSL?"] and out["posted"] == [{"path": "/api/actions/repair_hooks", "body": {"agent": "claude_wsl"}}] + assert out["out"] == "installed" and out["text"] == "已装好" and out["disabled"] is True + + +def test_declining_the_confirm_posts_nothing(engine): + out = _repair(engine, "answer = false; var out = 'untouched'; runAction(api, S, el).then(function (s) { out = s; });") + assert out["confirms"] == ["WSL?"] and out["posted"] == [] and out["out"] is None and out["text"] == "修复" + + +def test_a_failed_or_lost_repair_lets_the_user_try_again(engine): + out = _repair(engine, "reply = {status: 500, body: {error: 'action_failed'}}; var out = null; runAction(api, S, el).then(function (s) { out = s; });") + assert out["out"] == "failed" and out["text"] == "没装成" and out["disabled"] is False + out = _repair(engine, "reply = 'gone'; var out = null; runAction(api, S, el).then(function (s) { out = s; });") + assert out["out"] == "lost" and out["text"] == "连接断了" and out["disabled"] is False diff --git a/tests/test_panorama_service.py b/tests/test_panorama_service.py index 9072a6ae..38d0390d 100644 --- a/tests/test_panorama_service.py +++ b/tests/test_panorama_service.py @@ -364,3 +364,32 @@ def wait_for_newer(): assert json.loads(box["body"])["revision"] in (3, 4) # 等的人拿到的是它醒来时最新的那份 finally: service.stop() + + +# ───────────────────────── 只重探一侧(装完 hooks 之后那条线要变回来)───────────────────────── + +def test_refresh_reprobes_one_side_publishes_again_and_opens_no_browser(tmp_path): + h = _Harness(tmp_path) + assert h.service.open() and h.finished == [(True, str(tmp_path / "panorama" / render.PAGE_NAME))] + before = h.published()["revision"] + h.log.clear(); h.opened.clear() + h.wsl_result = samples.wsl_home(hooks={"Stop": {"total": 1, "fish": 0}}) + assert h.service.refresh("wsl") is True + after = h.published() + assert after["revision"] == before + 1 and h.log == ["wsl", "write"] and h.opened == [] + assert next(n for n in after["nodes"] if n["id"] == "set_wsl")["state"] == "bad" + h.log.clear() + assert h.service.refresh("win") is True + again = h.published() + assert again["revision"] == after["revision"] + 1 and "wsl" not in h.log, "重探本机不碰 WSL" + assert next(n for n in again["nodes"] if n["id"] == "set_wsl")["state"] == "bad", "上一次 WSL 的结果还在" + assert h.service.refresh("mars") is False + + +def test_refresh_does_nothing_before_the_first_round_or_while_one_is_running(tmp_path): + h = _Harness(tmp_path, spawn=lambda run: h.pending_runs.append(run)) + assert h.service.refresh("win") is False, "还没发布过:没有页面在看" + h.service.open() + assert h.service.refresh("win") is False, "一轮正在路上:它回来时自带新状态" + h.pending_runs.pop()() + assert h.service.refresh("win") is True diff --git a/tests/test_panorama_settings_routes.py b/tests/test_panorama_settings_routes.py index 0c298e84..efa7fb58 100644 --- a/tests/test_panorama_settings_routes.py +++ b/tests/test_panorama_settings_routes.py @@ -252,3 +252,30 @@ def test_audit_limit_is_bounded(stack): assert len(_pump(stack.app, lambda: _send(stack.server, "GET", "/api/audit?limit=2"))[1]["entries"]) == 2 assert len(_pump(stack.app, lambda: _send(stack.server, "GET", "/api/audit?limit=abc"))[1]["entries"]) == 3 assert len(_pump(stack.app, lambda: _send(stack.server, "GET", "/api/audit?limit=-5"))[1]["entries"]) == 3 + + +# ───────────────────────── 动作 ───────────────────────── + +def test_an_action_runs_its_handler_on_the_gui_thread_and_answers_with_its_result(stack): + from pet.panorama.actions import ActionError + + seen = [] + + def echo(body): + seen.append(threading.current_thread() is threading.main_thread()) + if body.get("boom"): + raise ActionError(400, "bad_agent") + return {"state": "installed", "got": body} + + stack.service.actions["echo"] = echo + status, out = _pump(stack.app, lambda: _send(stack.server, "POST", "/api/actions/echo", {"agent": "claude"})) + assert (status, out) == (200, {"state": "installed", "got": {"agent": "claude"}}) and seen == [True] + assert _pump(stack.app, lambda: _send(stack.server, "POST", "/api/actions/echo", {"boom": 1})) == (400, {"error": "bad_agent"}) + assert _pump(stack.app, lambda: _send(stack.server, "POST", "/api/actions/nope", {})) == (404, {"error": "unknown_action"}) + assert _pump(stack.app, lambda: _send(stack.server, "POST", "/api/actions/echo", {}, token=False))[0] == 401 + assert _pump(stack.app, lambda: _send(stack.server, "POST", "/api/actions/echo", {}, origin=False))[0] == 403 + + +def test_a_handler_that_blows_up_is_a_500_not_a_dead_connection(stack): + stack.service.actions["bad"] = lambda body: 1 / 0 + assert _pump(stack.app, lambda: _send(stack.server, "POST", "/api/actions/bad", {})) == (500, {"error": "action_failed"}) diff --git a/tests/test_panorama_sources.py b/tests/test_panorama_sources.py index 448d2c22..7a4840e3 100644 --- a/tests/test_panorama_sources.py +++ b/tests/test_panorama_sources.py @@ -215,3 +215,12 @@ def test_session_fish_and_recent_chats_are_tiles_of_their_own_and_the_link_tiles cfg["agent_link"]["session_history"] = False off = sources.build(samples.facts(cfg=cfg)) assert _node(off, "f_session_fish")["state"] == "off" and _node(off, "f_session_history")["state"] == "off" + + +def test_the_missing_hooks_quest_carries_the_repair_action_for_its_side(): + graph = sources.build(samples.facts(win=samples.home(hooks={"Stop": {"total": 1, "fish": 0}}), + wsl=samples.wsl_home(hooks={"Stop": {"total": 1, "fish": 0}}))) + quests = {q["node"]: q for q in graph["quests"] if q["sev"] == "bad" and "hook" in q["text"]} + assert quests["set_win"]["action"] == {"name": "repair_hooks", "agent": "claude", "side": "win"} + assert quests["set_wsl"]["action"] == {"name": "repair_hooks", "agent": "claude_wsl", "side": "wsl"} + assert all("action" not in q for q in graph["quests"] if q["node"] not in ("set_win", "set_wsl")), "别的待处理项没有动作" From b68c870c7fa335460a029f2c34799fabfa5ece6a Mon Sep 17 00:00:00 2001 From: Limin Wang Date: Thu, 19 Nov 2026 11:56:52 -0800 Subject: [PATCH 2/2] =?UTF-8?q?chore(panorama):=20=E5=8A=A8=E4=BD=9C?= =?UTF-8?q?=E5=AE=8C=E6=88=90=E3=80=81=E9=87=8D=E6=8E=A2=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E3=80=81hooks=20=E5=86=99=E5=85=A5=E5=90=84=E8=AE=B0=E4=B8=80?= =?UTF-8?q?=E8=A1=8C=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 真机点「修复」后 settings.json 与快照都在同一秒改写、hooks 回来了,但日志里一行没有——排障时找不到这次动作的痕迹。 Co-Authored-By: Claude Fable 5.1 --- pet/agent_link.py | 2 ++ pet/panorama/service.py | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/pet/agent_link.py b/pet/agent_link.py index 99232b9c..284d8207 100644 --- a/pet/agent_link.py +++ b/pet/agent_link.py @@ -2951,7 +2951,9 @@ def install_hooks_consented(self, agent_key: str) -> str: 顺带把通道开上并清掉「缺 hooks」的标记)。不靠 hooks 的通道没有可装的:``failed``。""" if agent_key == "claude": if not ClaudeCodeMonitor.install_hooks(self.monitors["claude"].events_file): + log.warning("Claude Code hooks 写入 settings.json 失败") return "failed" + log.info("Claude Code hooks 已写入 settings.json(用户已同意)") self._note_hooks_installed("claude") return "installed" if agent_key == "claude_wsl": diff --git a/pet/panorama/service.py b/pet/panorama/service.py index e2e8e887..1709f5d9 100644 --- a/pet/panorama/service.py +++ b/pet/panorama/service.py @@ -292,12 +292,14 @@ def _run_action(self, name: str, body) -> dict: if handler is None: raise ActionError(404, "unknown_action") try: - return handler(body) + out = handler(body) except ActionError: raise except Exception: # noqa: BLE001 - 处理器出错不能把连接挂死;页面要一个明确的回答 log.exception("配置全景:动作 %s 出错", name) raise ActionError(500, "action_failed") from None + log.info("配置全景:动作 %s 完成(%s)", name, out.get("state", "ok") if isinstance(out, dict) else "ok") + return out def refresh(self, side: str) -> bool: """(界面线程)只重探一侧、不开浏览器,再发布一次。装完 hooks 之后用:那条断线要变回来,而 hooks 在不在是探针 @@ -329,6 +331,7 @@ def run() -> None: if generation != self._generation: # 期间开了新的一轮:它的结果更新 return self._publish(fresh, out_dir) + log.info("配置全景:重探了 %s 一侧,页面已更新", side) except Exception: # noqa: BLE001 - 重探失败:页面留着上一份 log.exception("配置全景:重探 %s 一侧失败", side)