diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 7d0d066c2..2d0ddb001 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -1,8 +1,9 @@ -# Library: instructions, MCP servers, skills and RTK +# Library: instructions, MCP servers, skills, hooks and RTK The library keeps what every agent should know in one place: the instructions each agent reads before a conversation, the MCP servers it can -call, and the skills it can load. magpie writes these into each agent's own +call, the skills it can load, and the hooks it runs at points of its turn. +magpie writes these into each agent's own files in that agent's format, and takes back only what it wrote. Everything else in those files stays as it was. Package `internal/library` also gives agents RTK, a CLI that cuts shell output down before the model reads it. @@ -22,14 +23,15 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. | [`skill_from.go`](../../internal/library/skill_from.go), [`library.js`](../../internal/gui/assets/library.js) | | Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skills.go`](../../internal/library/skills.go) | +| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | | Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. | [`backup.go`](../../internal/library/backup.go) | | RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. `rtkSpec.blocked` stops the installer where it would break an agent. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`). | [`rtk.go`](../../internal/library/rtk.go) | ## Runtime path -1. **Edit.** The Library page or `magpie library` calls an exported function such as `SaveServer`, `ServerAgents`, `InstallSkills`, `SkillAgents` or `SetSkillHow`. The skills and servers pages each have Select, Turn all on, Turn all off and Remove all. Select's bar calls `SomeSkillsAgents` or `SomeServersAgents` (`/api/library/{skills,servers}/agents-some`), Turn all on or off calls `EverySkillAgents` or `EveryServerAgents` for the agents shown, and Remove all calls `RemoveSkills` or `RemoveServers`. Each of these is one change that takes every item out as a single removal would (#1027). A row's agent chips start with All (`allChip` in `library.js`), which gives the item to every agent shown that can take it, or takes it from them all; the pickers that choose the agents before an item is added (installing skills from a repository or the market, adding, bringing in or installing a server) have the same All: most start with every agent lit, and one agent alone took a click on each of the others (#1531). +1. **Edit.** The Library page or `magpie library` calls an exported function such as `SaveServer`, `ServerAgents`, `InstallSkills`, `SkillAgents` or `SetSkillHow`. The skills and servers pages each have Select, Turn all on, Turn all off and Remove all. Select's bar calls `SomeSkillsAgents` or `SomeServersAgents` (`/api/library/{skills,servers}/agents-some`), Turn all on or off calls `EverySkillAgents` or `EveryServerAgents` for the agents shown, and Remove all calls `RemoveSkills` or `RemoveServers`. The hooks page has Select and Remove all too (`SomeHooksAgents`, `RemoveHooks`). Each of these is one change that takes every item out as a single removal would (#1027). A row's agent chips start with All (`allChip` in `library.js`), which gives the item to every agent shown that can take it, or takes it from them all; the pickers that choose the agents before an item is added (installing skills from a repository or the market, adding, bringing in or installing a server) have the same All: most start with every agent lit, and one agent alone took a click on each of the others (#1531). 2. **Change.** `change` edits `library.json` under the lock and calls `sync`. -3. **Write.** For each target, `syncInstructions` and `syncMCP` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first. +3. **Write.** For each target, `syncInstructions`, `syncMCP` and `syncHooks` write magpie's part in the agent's format and record it in `Applied`. Skills are linked or copied into the agent's skills folder. A copy edited since it was made is taken into the library first. 4. **Result.** The `Result` lists the agents changed, a `Problem` for each thing that couldn't be given, and the backup folder. ## Constraints and failure behavior @@ -56,6 +58,8 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - Zed's servers go in `context_servers` of the settings.json magpie sets its model in (`agent.zed`: `~/.config/zed` on macOS, `$XDG_CONFIG_HOME/zed` on Linux, `%APPDATA%\Zed` on Windows, or `$MAGPIE_ZED_CONFIG_DIR`), as `command`/`args`/`env` or `url`/`headers` (`ContextServerSettingsContent`, zed-industries/zed 2c99f547). The file is JSONC: it is edited in place, so the user's comments, other settings and own servers stay, and `enabled`, `remote`, `timeout` and `oauth` in magpie's entry are the user's. Zed speaks streamable HTTP only (its `http.rs` only POSTs), so no SSE. An entry Zed's extensions configure (`settings` and no command or url) is never written over: a server by that name is refused for Zed (`mcpFile.foreign`), and asks for another name. Zed reloads the file as it changes. - An agent with no place for an item is refused by `Takes`, never recorded as given it. The refusal lists the agents here that take that item (`takenBy`), and says where it goes instead (`noPlace`): OpenChamber reads OpenCode's global AGENTS.md, skills folder and opencode.json (its server's `shared.js`), so it gets them from OpenCode; Claude Desktop's chat keeps its instructions in its own settings, with the Claude account, and its Code tab reads Claude Code's. A plugin's agent is refused an item its `agent.library` names no place for, and the refusal names the key its plugin would set. - Removing RTK never uses `rtk init --uninstall`. That command deletes Gemini's `GEMINI.md` whole and removes Claude Code, OpenCode and Cursor together. +- A hook is recorded entry by entry, as written (`Applied.Hooks`, compared as canonical JSON). magpie takes out only an entry still exactly as it wrote it; one the user edited is theirs from then on, and the user's own hooks beside it stay. A hooks file that doesn't parse is a problem and is never written. Codex keeps each hook's trust in config.toml as `[hooks.state.":::"]`, keyed by position, so when magpie takes a group out `codexRekey` moves the user's trust for the groups after it to their new place. +- A carried library (backup, WebDAV, S3, profile bundles) doesn't carry hooks yet. - CC Switch's own skills folder is only ever read. - Reading the page never waits on reading skills through (#541). `Read` compares an agent's own skill with the same name in another agent (`sameTree`) and hashes each library skill given as a copy (`hashFiles`, for `behind`). Both are kept against a stamp of the folders (each file's and link's path, type, size and mtime, `stamper` in [`treememo.go`](../../internal/library/treememo.go)), taken by the same walk that compares or hashes them, before a file is opened; a later read walks the folder without opening a file, and while the stamps match reuses the answer. Only an answer from a whole read of folders untouched for `settleFor` (3s) is kept: a folder that couldn't be walked or read, or was written a moment ago, is read again next time, never taken as unchanged. A rewrite that keeps a file's size and mtime isn't seen. `Glance` (`GET /api/library?glance=1`) is the page without those two, marked `partial`; the page draws it first, then the whole read, which runs `behind` and `foundSkills` after the library's lock is let go, so a change doesn't wait on them either. - Skills installed together (`InstallSkills`, `InstallMarketSkill`, `AddNewSkills`, through `installFrom` and `installChange`) install each on its own. One the library lists from the same source, or a folder in the library's own skills folder holding exactly that skill's files (left by an install that stopped before the library was saved), is had already and goes in `Result.Had`. Its files are never written, so the user's edits stay. Another skill by that name, listed or only in the folder, or a folder that can't be read, is left as it is and goes in `Result.Skipped` with why. The rest are installed and named in `Result.Installed`. Only when nothing was installed or had does the change fail, with the first reason. @@ -63,9 +67,9 @@ agents RTK, a CLI that cuts shell output down before the model reads it. ## Verification ```sh -go test -tags nogui ./internal/library -run 'TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionSets|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList' +go test -tags nogui ./internal/library -run 'TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionSets|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks' go test -tags nogui ./internal/library -node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs +node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs ``` The package's `TestMain` runs in a home of its own (`testenv`), never the diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a25f2a1c4..2286e2c1c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3920,6 +3920,58 @@ const I18N = { "{n} servers are on for all {m} agents": "已为全部 {m} 个 Agent 启用 {n} 个服务器", "{n} servers are off for all {m} agents": "已从全部 {m} 个 Agent 中关闭 {n} 个服务器", "Take all {n} servers out of the library": "从资源库中删除全部 {n} 个服务器", + "+ Add a hook": "+ 添加 Hook", + "+ Add hook": "+ 添加 Hook", + "{agent} can run none of these hooks": "{agent} 运行不了其中任何一个 Hook", + "{agent} has {n} of these hooks — click to give it the rest": "{agent} 已有其中 {n} 个 Hook — 点击启用其余的", + "{agent} has all of these hooks — click to take them away": "{agent} 已有这些 Hook — 点击全部停用", + "{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} 在自己的设置里关闭了 Hook:在那里重新打开之前,它一个也不会运行。", + "{agent} has no hooks magpie can write": "magpie 还不能给 {agent} 写入 Hook", + "{agent}'s own event": "{agent} 自己的事件", + "{event} is {agent}'s own event: only it can run this hook": "{event} 是 {agent} 自己的事件:只有它能运行这个 Hook", + "{n} hooks are off for {agents}": "已为 {agents} 停用 {n} 个 Hook", + "{n} hooks are on for {agents}": "已为 {agents} 启用 {n} 个 Hook", + "{n} hooks removed": "已删除 {n} 个 Hook", + "A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "Hook 是 Agent 在一轮对话的某个时刻运行的命令——结束时发个通知,改完文件后跑一下格式化。只需添加一次,magpie 会按每个 Agent 自己读取的格式,写进你选中的 Agent。", + "Add one, and pick the agents that run it.": "添加一个,再选要运行它的 Agent。", + "After a tool runs": "工具运行之后", + "Any tool": "任何工具", + "Before a tool runs": "工具运行之前", + "Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "新加或改过的 Hook,Codex 要等你信任后才会运行:请在 Codex 的 /hooks 里审阅。", + "Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor 也会运行 Claude Code 的 Hook:同时给两者启用的 Hook,在 Cursor 里会运行两次。", + "e.g. notify": "例如 notify", + "Each agent's own names for them": "按每个 Agent 自己对它们的叫法", + "Every agent has all of these hooks — click to take them from every one": "每个 Agent 都已有这些 Hook — 点击从全部 Agent 停用", + "every tool": "全部工具", + "File edits": "编辑文件", + "For which tools": "对哪些工具", + "Give {agent} all of these hooks": "给 {agent} 启用这些 Hook", + "Give all of these hooks to every agent": "为每个 Agent 启用这些 Hook", + "Hook {name}": "Hook {name}", + "Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Agent 自己的、不在资源库中的 Hook 保持不变,你在 Agent 文件里改过的也一样。", + "Hooks": "Hooks", + "Letters, digits, - and _": "字母、数字、- 和 _", + "magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie 还不能给 {agents} 写入 Hook:它们的图标是灰的,悬停可看原因。", + "magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只给这台电脑上的 Agent 写入 Hook,还不支持 WSL 里的 {agent}", + "Matcher": "匹配规则", + "New hook": "新 Hook", + "No hooks in the library yet": "资源库里还没有 Hook", + "Pick hooks to turn them on or off together": "选中 Hook,一起开启或关闭", + "Pick some hooks and turn them on or off together": "选中多个 Hook,一起开启或关闭", + "Remove all {n} hooks?": "删除全部 {n} 个 Hook?", + "Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "由 Agent 的 shell 在会话的文件夹里运行;Agent 会把发生了什么以 JSON 传到它的标准输入", + "Shell commands": "Shell 命令", + "Stop picking hooks": "结束选择 Hook", + "Take all {n} hooks out of the library": "从资源库中删除全部 {n} 个 Hook", + "The agent's own matcher, as its hooks file has it; empty for all": "Agent 自己的匹配规则,照它的 Hook 文件里的写法;留空表示全部", + "the agent's own": "沿用 Agent 自己的", + "Timeout (seconds)": "超时(秒)", + "When a prompt is sent": "发送提示词时", + "When a session starts": "会话开始时", + "When a turn ends": "一轮结束时", + "When it runs": "何时运行", + "Find an event": "查找事件", + "every agent, in its own name for it": "所有 Agent,各用自己的事件名", "Remove all {n} servers?": "删除全部 {n} 个服务器?", "The servers magpie placed in {n} projects are taken away too.": "magpie 放进 {n} 个项目的这些服务器也会一并移除。", "magpie's sign-in to {n} of them is forgotten too.": "magpie 对其中 {n} 个服务器的登录也会一并清除。", @@ -8280,6 +8332,58 @@ const I18N = { "{n} servers are on for all {m} agents": "已為全部 {m} 個 Agent 啟用 {n} 個伺服器", "{n} servers are off for all {m} agents": "已從全部 {m} 個 Agent 中關閉 {n} 個伺服器", "Take all {n} servers out of the library": "從資源庫中刪除全部 {n} 個伺服器", + "+ Add a hook": "+ 新增 Hook", + "+ Add hook": "+ 新增 Hook", + "{agent} can run none of these hooks": "{agent} 執行不了其中任何一個 Hook", + "{agent} has {n} of these hooks — click to give it the rest": "{agent} 已有其中 {n} 個 Hook — 點擊啟用其餘的", + "{agent} has all of these hooks — click to take them away": "{agent} 已有這些 Hook — 點擊全部停用", + "{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} 在自己的設定裡關閉了 Hook:在那裡重新開啟之前,它一個也不會執行。", + "{agent} has no hooks magpie can write": "magpie 還不能給 {agent} 寫入 Hook", + "{agent}'s own event": "{agent} 自己的事件", + "{event} is {agent}'s own event: only it can run this hook": "{event} 是 {agent} 自己的事件:只有它能執行這個 Hook", + "{n} hooks are off for {agents}": "已為 {agents} 停用 {n} 個 Hook", + "{n} hooks are on for {agents}": "已為 {agents} 啟用 {n} 個 Hook", + "{n} hooks removed": "已刪除 {n} 個 Hook", + "A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "Hook 是 Agent 在一輪對話的某個時刻執行的命令——結束時發個通知,改完檔案後跑一下格式化。只需新增一次,magpie 會按每個 Agent 自己讀取的格式,寫進你選中的 Agent。", + "Add one, and pick the agents that run it.": "新增一個,再選要執行它的 Agent。", + "After a tool runs": "工具執行之後", + "Any tool": "任何工具", + "Before a tool runs": "工具執行之前", + "Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "新增或改過的 Hook,Codex 要等你信任後才會執行:請在 Codex 的 /hooks 裡審閱。", + "Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor 也會執行 Claude Code 的 Hook:同時給兩者啟用的 Hook,在 Cursor 裡會執行兩次。", + "e.g. notify": "例如 notify", + "Each agent's own names for them": "按每個 Agent 自己對它們的叫法", + "Every agent has all of these hooks — click to take them from every one": "每個 Agent 都已有這些 Hook — 點擊從全部 Agent 停用", + "every tool": "全部工具", + "File edits": "編輯檔案", + "For which tools": "對哪些工具", + "Give {agent} all of these hooks": "給 {agent} 啟用這些 Hook", + "Give all of these hooks to every agent": "為每個 Agent 啟用這些 Hook", + "Hook {name}": "Hook {name}", + "Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Agent 自己的、不在資源庫中的 Hook 保持不變,你在 Agent 檔案裡改過的也一樣。", + "Hooks": "Hooks", + "Letters, digits, - and _": "字母、數字、- 和 _", + "magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie 還不能給 {agents} 寫入 Hook:它們的圖示是灰的,懸停可看原因。", + "magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只給這台電腦上的 Agent 寫入 Hook,還不支援 WSL 裡的 {agent}", + "Matcher": "匹配規則", + "New hook": "新 Hook", + "No hooks in the library yet": "資源庫裡還沒有 Hook", + "Pick hooks to turn them on or off together": "選中 Hook,一起開啟或關閉", + "Pick some hooks and turn them on or off together": "選中多個 Hook,一起開啟或關閉", + "Remove all {n} hooks?": "刪除全部 {n} 個 Hook?", + "Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "由 Agent 的 shell 在工作階段的資料夾裡執行;Agent 會把發生了什麼以 JSON 傳到它的標準輸入", + "Shell commands": "Shell 命令", + "Stop picking hooks": "結束選擇 Hook", + "Take all {n} hooks out of the library": "從資源庫中刪除全部 {n} 個 Hook", + "The agent's own matcher, as its hooks file has it; empty for all": "Agent 自己的匹配規則,照它的 Hook 檔案裡的寫法;留空表示全部", + "the agent's own": "沿用 Agent 自己的", + "Timeout (seconds)": "逾時(秒)", + "When a prompt is sent": "送出提示詞時", + "When a session starts": "工作階段開始時", + "When a turn ends": "一輪結束時", + "When it runs": "何時執行", + "Find an event": "搜尋事件", + "every agent, in its own name for it": "所有 Agent,各用自己的事件名", "Remove all {n} servers?": "刪除全部 {n} 個伺服器?", "The servers magpie placed in {n} projects are taken away too.": "magpie 放進 {n} 個專案的這些伺服器也會一併移除。", "magpie's sign-in to {n} of them is forgotten too.": "magpie 對其中 {n} 個伺服器的登入也會一併清除。", @@ -12661,6 +12765,58 @@ const I18N = { "{n} servers are on for all {m} agents": "{m} 個のエージェントすべてで {n} 個のサーバーをオンにしました", "{n} servers are off for all {m} agents": "{m} 個のエージェントすべてで {n} 個のサーバーをオフにしました", "Take all {n} servers out of the library": "{n} 個のサーバーをすべてライブラリから削除", + "+ Add a hook": "+ フックを追加", + "+ Add hook": "+ フックを追加", + "{agent} can run none of these hooks": "{agent} はこれらのフックをどれも実行できません", + "{agent} has {n} of these hooks — click to give it the rest": "{agent} にはこのうち {n} 個のフックがあります — クリックで残りも渡す", + "{agent} has all of these hooks — click to take them away": "{agent} にはこれらのフックがすべてあります — クリックで外す", + "{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} は設定でフックをオフにしています。そこでオンにするまで、どのフックも実行しません。", + "{agent} has no hooks magpie can write": "magpie は {agent} にフックを書き込めません", + "{agent}'s own event": "{agent} 独自のイベント", + "{event} is {agent}'s own event: only it can run this hook": "{event} は {agent} 独自のイベントです。このフックを実行できるのは {agent} だけです", + "{n} hooks are off for {agents}": "{agents} で {n} 個のフックをオフにしました", + "{n} hooks are on for {agents}": "{agents} で {n} 個のフックをオンにしました", + "{n} hooks removed": "{n} 個のフックを削除しました", + "A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "フックは、エージェントがターンの特定の時点で実行するコマンドです。終わったときに通知する、ファイルを編集した後にフォーマッターを走らせる、など。一度追加すれば、magpie が選んだ各エージェントに、そのエージェントが読む形式で書き込みます。", + "Add one, and pick the agents that run it.": "追加して、実行するエージェントを選んでください。", + "After a tool runs": "ツールの実行後", + "Any tool": "すべてのツール", + "Before a tool runs": "ツールの実行前", + "Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "Codex は新しいフックや変更されたフックを、信頼するまで実行しません。Codex の /hooks で確認してください。", + "Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor は Claude Code のフックも実行します。両方に渡したフックは Cursor で 2 回実行されます。", + "e.g. notify": "例: notify", + "Each agent's own names for them": "各エージェントでの呼び名で書き込みます", + "Every agent has all of these hooks — click to take them from every one": "すべてのエージェントにこれらのフックがあります — クリックですべてから外す", + "every tool": "すべてのツール", + "File edits": "ファイル編集", + "For which tools": "対象のツール", + "Give {agent} all of these hooks": "{agent} にこれらのフックをすべて渡す", + "Give all of these hooks to every agent": "すべてのエージェントにこれらのフックをすべて渡す", + "Hook {name}": "フック {name}", + "Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "エージェント自身の、ライブラリにないフックはそのまま残ります。エージェントのファイルで変更したものも同じです。", + "Hooks": "フック", + "Letters, digits, - and _": "英字・数字・- と _", + "magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie はまだ {agents} にフックを渡せません。チップはグレーになっていて、理由を表示します。", + "magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie がフックを渡せるのはこのコンピューター上のエージェントだけで、WSL の {agent} にはまだ渡せません", + "Matcher": "マッチャー", + "New hook": "新しいフック", + "No hooks in the library yet": "ライブラリにはまだフックがありません", + "Pick hooks to turn them on or off together": "フックを選んでまとめてオン・オフする", + "Pick some hooks and turn them on or off together": "複数のフックを選んでまとめてオン・オフする", + "Remove all {n} hooks?": "{n} 個のフックをすべて削除しますか?", + "Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "エージェントのシェルがセッションのフォルダーで実行します。何が起きたかは JSON で標準入力に渡されます", + "Shell commands": "シェルコマンド", + "Stop picking hooks": "フックの選択を終える", + "Take all {n} hooks out of the library": "{n} 個のフックをすべてライブラリから削除", + "The agent's own matcher, as its hooks file has it; empty for all": "エージェント独自のマッチャー。フックファイルでの書き方のまま。空ならすべて", + "the agent's own": "エージェントの既定", + "Timeout (seconds)": "タイムアウト(秒)", + "When a prompt is sent": "プロンプトの送信時", + "When a session starts": "セッションの開始時", + "When a turn ends": "ターンの終了時", + "When it runs": "実行するタイミング", + "Find an event": "イベントを検索", + "every agent, in its own name for it": "すべてのエージェント、それぞれの呼び名で", "Remove all {n} servers?": "{n} 個のサーバーをすべて削除しますか?", "The servers magpie placed in {n} projects are taken away too.": "magpie が {n} 個のプロジェクトに置いたこれらのサーバーも外されます。", "magpie's sign-in to {n} of them is forgotten too.": "そのうち {n} 個のサーバーへの magpie のサインインも消去されます。", @@ -17044,6 +17200,58 @@ const I18N = { "{n} servers are on for all {m} agents": "{n} Server sind für alle {m} Agenten an", "{n} servers are off for all {m} agents": "{n} Server sind für alle {m} Agenten aus", "Take all {n} servers out of the library": "Alle {n} Server aus der Bibliothek entfernen", + "+ Add a hook": "+ Hook hinzufügen", + "+ Add hook": "+ Hook hinzufügen", + "{agent} can run none of these hooks": "{agent} kann keinen dieser Hooks ausführen", + "{agent} has {n} of these hooks — click to give it the rest": "{agent} hat {n} dieser Hooks — klicken, um ihm den Rest zu geben", + "{agent} has all of these hooks — click to take them away": "{agent} hat alle diese Hooks — klicken, um sie zu entfernen", + "{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.": "{agent} hat Hooks in seinen Einstellungen ausgeschaltet: Es führt keinen davon aus, bis sie dort wieder eingeschaltet sind.", + "{agent} has no hooks magpie can write": "magpie kann für {agent} keine Hooks schreiben", + "{agent}'s own event": "Eigenes Ereignis von {agent}", + "{event} is {agent}'s own event: only it can run this hook": "{event} ist ein eigenes Ereignis von {agent}: Nur es kann diesen Hook ausführen", + "{n} hooks are off for {agents}": "{n} Hooks sind für {agents} aus", + "{n} hooks are on for {agents}": "{n} Hooks sind für {agents} an", + "{n} hooks removed": "{n} Hooks entfernt", + "A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads.": "Ein Hook ist ein Befehl, den ein Agent an einem Punkt seines Durchgangs ausführt — eine Benachrichtigung, wenn er endet, ein Formatierer, nachdem er eine Datei bearbeitet hat. Einmal hinzugefügt, schreibt magpie ihn in jeden gewählten Agenten, in der Form, die dieser liest.", + "Add one, and pick the agents that run it.": "Fügen Sie einen hinzu und wählen Sie die Agenten, die ihn ausführen.", + "After a tool runs": "Nachdem ein Tool läuft", + "Any tool": "Jedes Tool", + "Before a tool runs": "Bevor ein Tool läuft", + "Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.": "Codex führt einen neuen oder geänderten Hook erst aus, wenn Sie ihm vertrauen: Prüfen Sie ihn in Codex unter /hooks.", + "Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.": "Cursor führt auch die Hooks von Claude Code aus: Ein Hook, der beiden gegeben wird, läuft in Cursor zweimal.", + "e.g. notify": "z. B. notify", + "Each agent's own names for them": "Unter den eigenen Namen jedes Agenten", + "Every agent has all of these hooks — click to take them from every one": "Jeder Agent hat alle diese Hooks — klicken, um sie allen zu entfernen", + "every tool": "jedes Tool", + "File edits": "Dateiänderungen", + "For which tools": "Für welche Tools", + "Give {agent} all of these hooks": "{agent} alle diese Hooks geben", + "Give all of these hooks to every agent": "Allen Agenten alle diese Hooks geben", + "Hook {name}": "Hook {name}", + "Hooks your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Hooks Ihrer Agenten, die nicht in der Bibliothek sind, bleiben unverändert, ebenso einer, den Sie in der Datei eines Agenten geändert haben.", + "Hooks": "Hooks", + "Letters, digits, - and _": "Buchstaben, Ziffern, - und _", + "magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie kann {agents} noch keine Hooks geben: Ihre Chips sind ausgegraut und sagen, warum.", + "magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Hooks nur Agenten auf diesem Computer, noch nicht {agent} in WSL", + "Matcher": "Matcher", + "New hook": "Neuer Hook", + "No hooks in the library yet": "Noch keine Hooks in der Bibliothek", + "Pick hooks to turn them on or off together": "Hooks auswählen, um sie gemeinsam ein- oder auszuschalten", + "Pick some hooks and turn them on or off together": "Mehrere Hooks auswählen und gemeinsam ein- oder ausschalten", + "Remove all {n} hooks?": "Alle {n} Hooks entfernen?", + "Run by the agent's shell, in the session's folder; the agent passes what happened as JSON on its input": "Von der Shell des Agenten im Ordner der Sitzung ausgeführt; der Agent übergibt, was geschah, als JSON auf der Eingabe", + "Shell commands": "Shell-Befehle", + "Stop picking hooks": "Auswahl der Hooks beenden", + "Take all {n} hooks out of the library": "Alle {n} Hooks aus der Bibliothek entfernen", + "The agent's own matcher, as its hooks file has it; empty for all": "Der eigene Matcher des Agenten, wie in seiner Hook-Datei; leer für alle", + "the agent's own": "der des Agenten", + "Timeout (seconds)": "Zeitlimit (Sekunden)", + "When a prompt is sent": "Wenn ein Prompt gesendet wird", + "When a session starts": "Wenn eine Sitzung beginnt", + "When a turn ends": "Wenn ein Durchgang endet", + "When it runs": "Wann er läuft", + "Find an event": "Ereignis suchen", + "every agent, in its own name for it": "jeder Agent, unter seinem eigenen Namen dafür", "Remove all {n} servers?": "Alle {n} Server entfernen?", "The servers magpie placed in {n} projects are taken away too.": "Die Server, die magpie in {n} Projekte gelegt hat, werden ebenfalls entfernt.", "magpie's sign-in to {n} of them is forgotten too.": "magpies Anmeldung bei {n} von ihnen wird ebenfalls vergessen.", diff --git a/internal/gui/assets/library.css b/internal/gui/assets/library.css index 0fb867807..78f3a5ab8 100644 --- a/internal/gui/assets/library.css +++ b/internal/gui/assets/library.css @@ -580,3 +580,8 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-row.click:hover > .lib-agents:hover .lib-ag:not(:focus) { outline-color: transparent; } .lib-grouphead > .lib-agents .lib-ag:not(:focus) { outline-color: var(--card-2); } } + +/* Hooks (#1790): the event and the tools it is for are app menus, as wide + as the dialog lets them be */ +.lib-hookedit .lib-menu { max-width: 100%; height: 28px; color: var(--fg); } +.lib-hookedit .lib-hooktimeout { max-width: 140px; } diff --git a/internal/gui/assets/library.js b/internal/gui/assets/library.js index 0a3e2a1fa..842522f86 100644 --- a/internal/gui/assets/library.js +++ b/internal/gui/assets/library.js @@ -40,6 +40,7 @@ key: "M10 2.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 0 0 0-6.4z M7.8 8.2 3 13 M4.5 11.5 6 13", person: "M8 3a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z M3.5 13.5c.6-2.4 2.3-3.6 4.5-3.6s3.9 1.2 4.5 3.6", back: "m9.5 4.5-3 3.5 3 3.5", + hook: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9", }; const tilde = (p) => (lib?.home && p?.startsWith(lib.home) ? "~" + p.slice(lib.home.length) : p || ""); @@ -372,7 +373,7 @@ // What All did, said of the item: on for how many of the agents it went // to, and which of them couldn't be given it, and why. function reportAll(v, me) { - const what = (me.list === "servers" ? "mcp:" : "skill:") + me.name; + const what = ({ servers: "mcp:", hooks: "hook:" }[me.list] || "skill:") + me.name; const shown = [...me.box.children].filter((x) => x.dataset.agent && !cannot(x)).map((x) => x.dataset.agent); const n = shown.filter((id) => me.want.includes(id)).length; const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent)); @@ -578,6 +579,7 @@ if (kind === "instructions") return t("Instructions"); if (kind === "mcp") return name ? t("MCP server {name}", { name }) : t("MCP servers"); if (kind === "skill") return t("Skill {name}", { name }); + if (kind === "hook") return t("Hook {name}", { name }); if (kind === "project") return name ? t("Skill {name}", { name }) : t("The project"); return what; } @@ -658,6 +660,7 @@ ["instructions", t("Instructions")], ["mcp", t("MCP servers") + n("mcp")], ["skills", t("Skills") + n("skills")], + ["hooks", t("Hooks") + n("hooks")], ["rtk", "RTK"], ], tab, (id) => { tab = id; @@ -706,7 +709,7 @@ const caret = focus ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null; page.replaceChildren(); fits = []; - const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length }); + const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length }); page.append(head); head.classList.toggle("stuck", top > 0); if (!lib.agents.length) { @@ -722,6 +725,7 @@ if (tab === "instructions") renderInstructions(body); else if (tab === "mcp") renderServers(body); else if (tab === "rtk") renderRTK(body); + else if (tab === "hooks") renderHooks(body); else renderSkills(body); page.append(body); for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent; @@ -1976,6 +1980,206 @@ openLib(ed); } + // ---------- hooks ---------- + + // A hook (#1790, AllenReder) is a command an agent runs at a point of + // its turn: a phone notification when it ends, a formatter after it + // edits a file. It is kept once and written into each agent picked, in + // that agent's own file and shape (hooks.go). An event is one every + // agent has, under its own name, or one agent's own, for it alone. + const HOOK_EVENTS = () => [ + ["turn-end", t("When a turn ends")], + ["after-tool", t("After a tool runs")], + ["before-tool", t("Before a tool runs")], + ["prompt", t("When a prompt is sent")], + ["session-start", t("When a session starts")], + ]; + const HOOK_TOOLS = () => [["", t("Any tool")], ["shell", t("Shell commands")], ["edit", t("File edits")]]; + const toolEvent = (ev) => ev === "after-tool" || ev === "before-tool"; + const hookAgentOf = (id) => (lib.hookAgents || []).find((x) => x.id === id); + // the agents the tab shows a chip for: every one shown, those magpie + // can't give a hook greyed, saying why + const hookAgents = () => shownAgents().filter((a) => hookAgentOf(a.id)); + // why a can't be given h, or "" + const hookBlocked = (h) => (a) => { + const ha = hookAgentOf(a.id); + if (!ha || ha.no) return ha?.wsl ? t("magpie gives hooks only to agents on this computer, not yet to {agent} in WSL", { agent: a.name }) : t("{agent} has no hooks magpie can write", { agent: a.name }); + const own = h.event?.includes(":") && h.event.split(":")[0]; + if (own && own !== a.id) return t("{event} is {agent}'s own event: only it can run this hook", { event: h.event.slice(own.length + 1), agent: nameOf(own) }); + return ""; + }; + function hookEventLabel(h) { + const i = h.event.indexOf(":"); + if (i > 0) return nameOf(h.event.slice(0, i)) + " · " + h.event.slice(i + 1); + return HOOK_EVENTS().find(([v]) => v === h.event)?.[1] || h.event; + } + function hookLine(h) { + let s = hookEventLabel(h); + if (h.matcher) s += " · " + (h.event.includes(":") ? h.matcher : HOOK_TOOLS().find(([v]) => v === h.matcher)?.[1] || h.matcher); + return s; + } + + function renderHooks(body) { + body.append(intro(t("A hook is a command an agent runs at a point of its turn — a notification when it ends, a formatter after it edits a file. Add it once and magpie writes it into each agent you pick, in the shape that agent reads."))); + const all = hookAgents(); + const hooks = lib.hooks || []; + pickingFor("hooks", hooks); + if (!hooks.length) { + body.append(empty(t("No hooks in the library yet"), t("Add one, and pick the agents that run it."), button(t("+ Add a hook"), "action", () => editHook(null)))); + } else { + if (hooks.length > 1) { + const rh = el("div", "row-head lib-hookhead"); + rh.append(el("span", "label", t("In the library")), el("span", "grow")); + if (all.length) rh.append(pickButton("hooks")); + rh.append(removeEveryButton("hooks")); + body.append(rh); + } + const list = el("div", "list lib-list"); + list.append(...[...hooks].sort((a, b) => a.name.localeCompare(b.name)).map((h) => hookRow(h, all))); + body.append(list); + if (picking) body.append(pickBar(all)); + const after = el("div", "after-list"); + after.append(button(t("+ Add hook"), "", () => editHook(null))); + body.append(after); + } + const given = (id) => hooks.some((h) => h.agents?.includes(id)); + for (const a of all) { + const ha = hookAgentOf(a.id); + if (ha.off && given(a.id)) body.append(el("p", "lib-aside lib-hooks-off", t("{agent} has hooks turned off in its settings: it runs none of them until they're turned on there.", { agent: a.name }))); + } + // Codex runs a hook only once it is trusted there, again after it + // changes (codex-rs/hooks: trusted_hash) + if (given("codex")) body.append(el("p", "lib-aside lib-hooks-codex", t("Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks."))); + // Cursor runs Claude Code's hooks as well as its own + if (hooks.some((h) => h.agents?.includes("cursor") && h.agents?.includes("claude"))) body.append(el("p", "lib-aside lib-hooks-twice", t("Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor."))); + // the agents greyed: Claude Code, Codex, Gemini CLI and Cursor are the + // ones whose hooks files magpie knows + const skip = all.filter((a) => hookAgentOf(a.id).no); + if (skip.length) body.append(el("p", "lib-aside lib-hooks-no", t("magpie can't give hooks to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") }))); + } + + function hookRow(h, all) { + const row = el("div", "row lib-row click lib-hook"); + const who = el("div", "who"); + who.append(el("div", "name mono", h.name), el("div", "sub lib-hookev", hookLine(h))); + const cmd = el("div", "sub mono lib-hookcmd", h.command); + cmd.title = h.command; + who.append(cmd); + row.append(glyph(GLYPH.hook), who, + agentChips(all, h.agents, chipsChange("hooks/agents", h.name, "hooks", (x) => hookRow(x, all)), { problems: h.problems, blocked: hookBlocked(h), all: true })); + if (picking) return pickRow(row, h.name); + row.onclick = () => editHook(h); + row.title = t("Edit {name}", { name: h.name }); + return row; + } + + function editHook(h) { + const all = hookAgents(); + const d = h ? { name: h.name, event: h.event, matcher: h.matcher || "", command: h.command, timeout: h.timeout || 0, agents: [...(h.agents || [])] } + : { name: "", event: "turn-end", matcher: "", command: "", timeout: 0, agents: [] }; + if (!h) d.agents = all.filter((a) => !hookBlocked(d)(a)).map((a) => a.id); + const ed = el("div", "editor lib-editor lib-hookedit"); + const head = el("div", "ehead"); + head.append(glyph(GLYPH.hook), el("b", "", h ? h.name : t("New hook"))); + ed.append(head); + const err = el("div", "editor-error"); + const name = field2(d.name, t("e.g. notify"), (v) => { d.name = v.trim(); }); + ed.append(...field(t("Name"), name, t("Letters, digits, - and _"))); + + // the event and the tools it is narrowed to: menus, never a ), an agent's own event (Claude +// Code · Notification) leaves only that agent's chip, and Save posts +// hooks/save with what was picked. Select and the bar's chips post +// hooks/agents-some; Remove all asks first and posts hooks/remove-all. +// At 440px wide in en, zh, zh-TW, ja and de: no sideways scroll, and what +// each click pressed stays where it was on the screen. +// No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/allen"; +const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more }); +const hk = (name, event, matcher, command, agents) => ({ name, event, matcher, command, agents }); +const HOOK_AGENTS = [ + { id: "claude", file: `${HOME}/.claude/settings.json`, events: ["PreToolUse", "PostToolUse", "Notification", "Stop"] }, + { id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["PreToolUse", "PostToolUse", "Stop"] }, + { id: "cursor", file: `${HOME}/.cursor/hooks.json`, events: ["afterFileEdit", "stop"] }, + { id: "gemini", file: `${HOME}/.gemini/settings.json`, events: ["AfterTool", "AfterAgent"] }, + { id: "opencode", no: "OpenCode has no hooks magpie can write" }, +]; +const lib = (hooks) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("cursor", "Cursor"), agent("gemini", "Gemini CLI"), agent("opencode", "OpenCode")], + instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [], + hooks, hookAgents: HOOK_AGENTS, +}); + +let I18N; +async function loadI18N() { + const src = await fs.readFile(path.join(assets, "i18n.js"), "utf8"); + I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")(); +} +// the words the page says in lang; a string missing from a language fails +function tr(lang, key, vars = {}) { + let s = key; + if (lang !== "en") { + assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`); + s = I18N[lang][key]; + } + return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)); +} + +function server(lang, state, posts) { + const can = (h, a) => a !== "opencode" && (!h.event.includes(":") || h.event.startsWith(a + ":")); + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/library") return json(lib(state.hooks)); + if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) { + const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", ""); + posts.push({ what, body }); + const put = (x, agents, on) => ({ ...x, agents: on ? [...new Set([...x.agents, ...agents.filter((a) => can(x, a))])].sort() : x.agents.filter((a) => !agents.includes(a)) }); + if (what === "hooks/agents") state.hooks = state.hooks.map((x) => (x.name === body.name ? { ...x, agents: body.agents.filter((a) => can(x, a)) } : x)); + if (what === "hooks/agents-some") state.hooks = state.hooks.map((x) => (body.names.includes(x.name) ? put(x, body.agents, body.on) : x)); + if (what === "hooks/save") state.hooks = [...state.hooks.filter((x) => x.name !== body.old), body.hook]; + if (what === "hooks/remove-all") state.hooks = state.hooks.filter((x) => !body.names.includes(x.name)); + return json({ ...lib(state.hooks), result: { changed: ["claude"] } }); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } }); + if (url.pathname.startsWith("/api/")) return json({}); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +// a click where the button is, as the reader's, and what was clicked stays +// where it was on the screen while the click redraws around it +const press = async (page, loc) => { + await page.waitForFunction(() => !document.querySelector("#view-library").getAnimations({ subtree: true }).some((a) => a.effect?.getComputedTiming().endTime !== Infinity)); + const b = await loc.boundingBox(); + const sel = String(loc); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); + await page.waitForTimeout(250); + if (!(await loc.count())) return; + const a = await loc.boundingBox(); + if (a && a.width) assert(Math.abs(a.y - b.y) <= 1, `${sel} moved on the screen from ${Math.round(b.y)} to ${Math.round(a.y)}`); +}; +const settled = (page) => page.waitForFunction(() => !document.querySelector("#modal").getAnimations({ subtree: true }).length); +// nothing wider than the window: the page, the Library, its rows, bar and dialog +const sideways = (page) => page.evaluate(() => { + const over = []; + const w = document.documentElement.clientWidth; + if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth); + const v = document.querySelector("#view-library"); + if (v.scrollWidth > v.clientWidth + 1) over.push("library " + v.scrollWidth + ">" + v.clientWidth); + for (const e of document.querySelectorAll("#view-library .lib-hookhead > *, #view-library .lib-hook, #view-library .lib-pickbar, #view-library .lib-tabs, #modal .lib-hookedit *")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right)); + } + return over; +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Library's Hooks tab", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + await loadI18N(); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + await t.test(lang, async () => { + const w = (key, vars) => tr(lang, key, vars); + const state = { hooks: [hk("bark", "turn-end", "", "curl -s https://api.day.app/KEY/done", ["codex"]), hk("fmt", "after-tool", "edit", "prettier -w .", ["claude", "cursor"])] }; + const posts = [], errors = []; + const ctx = await browser.newContext({ viewport: { width: 440, height: 1000 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "hooks"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); }); + await page.route("**/*", server(lang, state, posts)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + await v.locator(".lib-hook").first().waitFor(); + const row = (name) => v.locator(".lib-hook").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) }); + const agentsOf = (name) => state.hooks.find((s) => s.name === name)?.agents; + + // the tab, with its count, between Skills and RTK + const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim()); + assert.deepEqual(tabs.slice(2, 5), [w("Skills"), w("Hooks") + " · 2", "RTK"]); + // each hook says when it runs, in words, and what it runs + assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits")); + assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends")); + assert.equal((await row("bark").locator(".lib-hookcmd").textContent()).trim(), "curl -s https://api.day.app/KEY/done"); + // what an agent does with one given to it + await v.locator(".lib-hooks-codex").filter({ hasText: w("Codex runs a new or changed hook only once you trust it: review it in Codex's /hooks.") }).waitFor(); + await v.locator(".lib-hooks-twice").filter({ hasText: w("Cursor runs Claude Code's hooks too: a hook given to both runs twice in Cursor.") }).waitFor(); + await v.locator(".lib-hooks-no").filter({ hasText: w("magpie can't give hooks to {agents} yet: their chips are greyed, and say why.", { agents: "OpenCode" }) }).waitFor(); + assert.equal(await v.locator(".lib-hooks-off").count(), 0, "Gemini CLI, given none, said to have hooks off"); + assert.deepEqual(await sideways(page), [], "sideways scroll with the list"); + + // OpenCode's chip is greyed, says why, and a click posts nothing + const oc = row("bark").locator('.lib-ag[data-agent="opencode"]'); + assert.equal(await oc.getAttribute("aria-disabled"), "true"); + assert.equal(await oc.getAttribute("title"), w("{agent} has no hooks magpie can write", { agent: "OpenCode" })); + await press(page, oc); + await page.waitForTimeout(150); + assert.deepEqual(posts, [], "a greyed chip posted"); + + // a row's chip gives the hook to Gemini CLI + await press(page, row("bark").locator('.lib-ag[data-agent="gemini"]')); + await page.waitForFunction(() => document.querySelector('#view-library .lib-hook .lib-ag[data-agent="gemini"][aria-pressed="true"]')); + await page.waitForTimeout(200); + assert.deepEqual(posts.shift(), { what: "hooks/agents", body: { name: "bark", agents: ["codex", "gemini"] } }); + assert.deepEqual(agentsOf("bark"), ["codex", "gemini"]); + + // Add: the editor, its event and tools from app menus + await press(page, v.locator(".after-list button")); + const ed = page.locator("#modal .lib-hookedit"); + await ed.waitFor(); + await settled(page); + assert.equal(await page.locator("#modal select").count(), 0, "a native