library: the hooks an agent runs that magpie didn't give it are listed, brought in and removed (InkCoalW on X)
InkCoalW asked on X for magpie to read and manage the hooks an agent already uses (~/.claude/settings.json, Codex's hooks.json and the like), covering both managing and cleaning them up. The Library's Hooks tab now lists them under "In your agents", the way found skills and servers are: each one shows its event and matcher, its command, its agent and its file. - Bring in (hooks/import) makes it a library hook, or joins a library hook with the same event, matcher, command and timeout, and records the entry in the file as magpie's. The file is left byte for byte as it was. - An entry the library can't keep as written has Bring in greyed out and a title that says why: several commands, a prompt or other non-command handler, or a shape such as async. It can still be removed. - Remove (hooks/remove-found) asks first. It copies the file to magpie's backups, then takes out only that entry through the same hookWrite path magpie's own hooks use: Codex's trust keys are re-keyed, Grok's TOML block is cut, and the rest of the file, its comments included, stays. - A key gone stale since the list was drawn is refused. One of two identical entries removes only one. - RTK's own hooks belong to the RTK tab and aren't listed. The page sends only a key the server derived. The file paths join revealable() so the row's path link opens. Run, on mote via mote-run, at this head rebased oneb1da1572: - go test -tags nogui -run 'TestFoundHooks|TestHooks' ./internal/library: ok - go test -tags nogui -timeout 45m ./internal/library ./internal/gui: library ok. gui has three reds: - TestEveryRouteIsNamedForTheCLI is the next commit's route, fixed there. - TestBuiltinsTranslated (#7257) and TestSettingsSaveKeepsWhatItDoesNotSend (#7240) fail the same on a fresh origin/maineb1da1572copy. - go vet with GOOS=darwin, linux and windows on ./internal/library and ./internal/gui: ok. gofmt -l: empty. - GUI: library-found-hooks.test.cjs is 12/12 in Chromium and WebKit, in en, zh, zh-TW, ja and de, at 440px. Also run: library-hooks, library-rtk-nohook, project-hooks, found-fold, found-skill-pick-remove, library-all, library-loading, plugin-github-hooks, i18n-keys, i18n-en-no-cjk, gui-de, gui-ja, gui-zh-tw, with agent-open-terminal and agent-menu-label: 171 of 183 pass. The 12 reds fail the same on a fresh origin/maineb1da1572copy: - gui-ja "{agents}" twice (#7144) - found-skill-pick-remove (#5013) - agent-menu-label in the WebKit panel (#6371) Broken by hand, each one red: - no backup: TestFoundHooksRemoved - no Codex re-key: TestFoundHooksRemoved - applied records not claimed: Listed and BroughtIn - no RTK owner: Listed - no shape check: Listed - the old client.js: the GUI test is 0/12 - RTK filter removed: the GUI test is 0/12 Not tried: real agents' files outside a sandbox HOME, Windows and Linux GUI runs, the whole GUI suite (both test machines were running other sessions' GUI suites).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -4843,6 +4843,14 @@ magpie.plugin("library", (ctx) => {
|
||||
after.append(button(t("+ Add hook"), "", () => editHook(null)));
|
||||
body.append(after);
|
||||
}
|
||||
// the hooks the agents run that magpie didn't give them, as the user or
|
||||
// another tool wrote them (@InkCoalW on X); RTK's are the RTK tab's
|
||||
const found = agentless() ? [] : (lib.foundHooks || []).filter((f) => !f.own);
|
||||
if (found.length) {
|
||||
const rh = el("div", "row-head lib-foundhookhead");
|
||||
rh.append(el("span", "label", t("In your agents")), el("span", "grow"), el("span", "note", t("not in the library — bring one in to manage it here")));
|
||||
body.append(rh, foldedFound("hooks", found.map(foundHookRow)));
|
||||
}
|
||||
const given = (id) => hooks.some((h) => h.agents?.includes(id));
|
||||
for (const a of all) {
|
||||
const ha = hookAgentOf(a.id);
|
||||
@@ -4879,6 +4887,60 @@ magpie.plugin("library", (ctx) => {
|
||||
return row;
|
||||
}
|
||||
|
||||
// One hook of an agent's own file: when it runs, what it runs, and where
|
||||
// it is written.
|
||||
function foundHookLabel(f) { return f.matcher ? f.event + " · " + f.matcher : f.event; }
|
||||
|
||||
function foundHookRow(f) {
|
||||
const row = el("div", "row lib-row lib-found lib-foundhook");
|
||||
const who = el("div", "who");
|
||||
who.append(el("div", "name mono", foundHookLabel(f)));
|
||||
const line = f.commands.join(" ; ");
|
||||
const cmd = el("div", "sub mono lib-hookcmd", line);
|
||||
cmd.title = line;
|
||||
who.append(cmd);
|
||||
const src = el("div", "lib-src");
|
||||
src.append(pathLink(f.file));
|
||||
who.append(src);
|
||||
const have = el("div", "lib-have");
|
||||
const a = agentOf(f.agent);
|
||||
if (a) { const i = agentIcon(a.icon); i.title = a.name; have.append(i); }
|
||||
row.append(glyph(GLYPH.hook), who, have);
|
||||
const b = button(t("Bring in"), "action", () => change("hooks/import", { names: [f.key] }, t("{name} is in the library now", { name: f.hook.name })));
|
||||
if (f.hook) {
|
||||
b.title = f.joins ? t("It is {name} of the library: {agent} is ticked for it", { name: f.joins, agent: a?.name || f.agent })
|
||||
: t("Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others", { name: f.hook.name, agent: a?.name || f.agent });
|
||||
} else {
|
||||
// a group of several, a prompt or an agent hook, or a key the
|
||||
// library has no field for: magpie would change it on its next write
|
||||
b.disabled = true;
|
||||
b.title = f.why === "several" ? t("It runs several commands: the library keeps a hook as one command")
|
||||
: f.why === "type" ? t("It isn't a command: the library keeps command hooks")
|
||||
: t("It has settings the library doesn't keep: bringing it in would change it");
|
||||
}
|
||||
const rm = button("", "lib-icon danger", () => confirmRemoveFoundHook(f));
|
||||
rm.append(svg(GLYPH.trash, 13, 1.4));
|
||||
rm.title = t("Remove");
|
||||
row.append(b, rm);
|
||||
return row;
|
||||
}
|
||||
|
||||
function confirmRemoveFoundHook(f) {
|
||||
const ed = el("div", "editor lib-editor");
|
||||
const head = el("div", "ehead");
|
||||
head.append(glyph(GLYPH.trash), el("b", "", t("Remove this {event} hook?", { event: foundHookLabel(f) })));
|
||||
ed.append(head);
|
||||
const cmd = el("p", "lib-confirm mono", f.commands.join(" ; "));
|
||||
ed.append(cmd);
|
||||
ed.append(el("p", "lib-confirm", t("It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.", { file: tilde(f.file) })));
|
||||
const bar = el("div", "bar");
|
||||
const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("hooks/remove-found", { names: [f.key] }, t("Hook removed"))) closeLibModal(true); });
|
||||
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go);
|
||||
ed.append(bar);
|
||||
modal = { save: () => go.click() };
|
||||
openLib(ed);
|
||||
}
|
||||
|
||||
function editHook(h) {
|
||||
const all = hookAgents();
|
||||
const d = h ? { name: h.name, description: h.description || "", event: h.event, matcher: h.matcher || "", command: h.command, timeout: h.timeout || 0, agents: [...(h.agents || [])] }
|
||||
|
||||
@@ -1166,6 +1166,14 @@ magpie.strings({
|
||||
"What only this project needs — its stack, how to run its tests, what not to touch…": "只有这个项目需要的 — 技术栈、怎么跑测试、哪些不要动…",
|
||||
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "写在每个智能体在项目里读取的文件的两行标记之间 — 文件其余部分仍归你。magpie 新建的文件不会进入 git,.gitignore 不会被改动。",
|
||||
"{agents} reads no project instructions file magpie knows of.": "{agents} 没有 magpie 已知的项目指令文件。",
|
||||
"It is {name} of the library: {agent} is ticked for it": "它就是资源库里的 {name}:已为 {agent} 勾选",
|
||||
"Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "以 {name} 留在资源库中:{agent} 照常运行它,你也可以把它给其他 Agent",
|
||||
"It runs several commands: the library keeps a hook as one command": "它运行多条命令:资源库里的钩子只保存一条命令",
|
||||
"It isn't a command: the library keeps command hooks": "它不是命令:资源库只保存命令钩子",
|
||||
"It has settings the library doesn't keep: bringing it in would change it": "它有资源库不保存的设置:导入会改动它",
|
||||
"Remove this {event} hook?": "删除这个 {event} 钩子?",
|
||||
"It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "它会从 {file} 中移除,文件其余部分保持不变。改动前文件会先复制到 magpie 的备份中,可以从那里恢复。",
|
||||
"Hook removed": "钩子已删除",
|
||||
},
|
||||
"zh-TW": {
|
||||
"project scope": "專案範圍",
|
||||
@@ -2332,6 +2340,14 @@ magpie.strings({
|
||||
"What only this project needs — its stack, how to run its tests, what not to touch…": "只有這個專案需要的 — 技術棧、怎麼跑測試、哪些不要動…",
|
||||
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "寫在每個智能體在專案裡讀取的檔案的兩行標記之間 — 檔案其餘部分仍歸你。magpie 新建的檔案不會進入 git,.gitignore 不會被改動。",
|
||||
"{agents} reads no project instructions file magpie knows of.": "{agents} 沒有 magpie 已知的專案指令檔案。",
|
||||
"It is {name} of the library: {agent} is ticked for it": "它就是資源庫裡的 {name}:已為 {agent} 勾選",
|
||||
"Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "以 {name} 留在資源庫中:{agent} 照常執行它,你也可以把它給其他 Agent",
|
||||
"It runs several commands: the library keeps a hook as one command": "它執行多條命令:資源庫裡的鉤子只保存一條命令",
|
||||
"It isn't a command: the library keeps command hooks": "它不是命令:資源庫只保存命令鉤子",
|
||||
"It has settings the library doesn't keep: bringing it in would change it": "它有資源庫不保存的設定:匯入會改動它",
|
||||
"Remove this {event} hook?": "刪除這個 {event} 鉤子?",
|
||||
"It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "它會從 {file} 中移除,檔案其餘部分保持不變。改動前檔案會先複製到 magpie 的備份中,可以從那裡還原。",
|
||||
"Hook removed": "鉤子已刪除",
|
||||
},
|
||||
ja: {
|
||||
"project scope": "プロジェクトの範囲",
|
||||
@@ -3498,6 +3514,14 @@ magpie.strings({
|
||||
"What only this project needs — its stack, how to run its tests, what not to touch…": "このプロジェクトだけに必要なこと — 技術スタック、テストの実行方法、触れてはいけないもの…",
|
||||
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "各エージェントがプロジェクトで読むファイルの 2 行のマーカーの間に書き込みます — ファイルの他の部分はあなたのものです。magpie が作ったファイルは git から除外され、.gitignore は変更しません。",
|
||||
"{agents} reads no project instructions file magpie knows of.": "{agents} は magpie が把握しているプロジェクトの指示ファイルを読みません。",
|
||||
"It is {name} of the library: {agent} is ticked for it": "ライブラリの {name} と同じです:{agent} にチェックが入ります",
|
||||
"Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "{name} としてライブラリに残します:{agent} は引き続き実行し、他のエージェントにも渡せます",
|
||||
"It runs several commands: the library keeps a hook as one command": "複数のコマンドを実行します:ライブラリのフックはコマンド 1 つだけを保持します",
|
||||
"It isn't a command: the library keeps command hooks": "コマンドではありません:ライブラリはコマンドのフックを保持します",
|
||||
"It has settings the library doesn't keep: bringing it in would change it": "ライブラリが保持しない設定があります:取り込むと変わってしまいます",
|
||||
"Remove this {event} hook?": "この {event} フックを削除しますか?",
|
||||
"It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "{file} から取り除かれ、ファイルの他の部分はそのままです。変更前にファイルは magpie のバックアップにコピーされ、そこから元に戻せます。",
|
||||
"Hook removed": "フックを削除しました",
|
||||
},
|
||||
de: {
|
||||
"project scope": "Projektbereich",
|
||||
@@ -4664,5 +4688,13 @@ magpie.strings({
|
||||
"What only this project needs — its stack, how to run its tests, what not to touch…": "Was nur dieses Projekt braucht — sein Stack, wie seine Tests laufen, was nicht angefasst wird…",
|
||||
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "Zwischen zwei Markierungszeilen in die Datei geschrieben, die jeder Agent im Projekt liest — der Rest der Datei bleibt deiner. Eine Datei, die magpie anlegt, bleibt aus git heraus, ihre .gitignore unberührt.",
|
||||
"{agents} reads no project instructions file magpie knows of.": "{agents} liest keine Projekt-Anweisungsdatei, die magpie kennt.",
|
||||
"It is {name} of the library: {agent} is ticked for it": "Er ist {name} aus der Bibliothek: {agent} wird dafür angehakt",
|
||||
"Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "Behält ihn als {name} in der Bibliothek: {agent} führt ihn weiter aus, und du kannst ihn den anderen geben",
|
||||
"It runs several commands: the library keeps a hook as one command": "Er führt mehrere Befehle aus: die Bibliothek hält einen Hook als einen Befehl",
|
||||
"It isn't a command: the library keeps command hooks": "Er ist kein Befehl: die Bibliothek hält Befehls-Hooks",
|
||||
"It has settings the library doesn't keep: bringing it in would change it": "Er hat Einstellungen, die die Bibliothek nicht hält: Übernehmen würde ihn ändern",
|
||||
"Remove this {event} hook?": "Diesen {event}-Hook entfernen?",
|
||||
"It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "Er wird aus {file} entfernt, der Rest der Datei bleibt, wie er ist. Die Datei wird vorher in magpies Sicherungen kopiert, von wo sie sich zurückholen lässt.",
|
||||
"Hook removed": "Hook entfernt",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -164,6 +164,9 @@ func revealable(v *library.View) []string {
|
||||
for _, s := range v.FoundSkills {
|
||||
out = append(out, s.Link, s.Shared)
|
||||
}
|
||||
for _, h := range v.FoundHooks {
|
||||
out = append(out, h.File)
|
||||
}
|
||||
for _, s := range v.Subagents {
|
||||
// the file it is kept in, to edit it in
|
||||
if s.Path != "" {
|
||||
@@ -833,6 +836,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
res, err = library.RemoveHooks([]string{in.Name})
|
||||
case "hooks/remove-all":
|
||||
res, err = library.RemoveHooks(in.Names)
|
||||
case "hooks/import":
|
||||
// hooks the agents run that magpie didn't give them, by
|
||||
// their keys (@InkCoalW on X)
|
||||
res, err = library.ImportHooks(in.Names)
|
||||
case "hooks/remove-found":
|
||||
// out of the agents' own files, each copied to the backups first
|
||||
res, err = library.RemoveFoundHooks(in.Names)
|
||||
case "plugins/install":
|
||||
res, err = library.InstallPlugins(in.Source, in.Names, in.Agents)
|
||||
case "plugins/agents":
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// @InkCoalW on X: read and manage the hooks an agent already runs, and
|
||||
// clean them up. The Hooks tab lists them "In your agents", under the
|
||||
// library's own: each with its event and matcher, its command, its agent
|
||||
// and the file it is in. Bring in posts hooks/import with its key; one
|
||||
// the library can't keep as written (two commands, a prompt hook) has
|
||||
// Bring in greyed, saying why, and can still be removed. Remove asks
|
||||
// first, says the file is copied to the backups, and posts
|
||||
// hooks/remove-found. RTK's own hooks are the RTK tab's and aren't listed.
|
||||
// With no hooks in the library the list is still there, under the empty
|
||||
// state. In en, zh, zh-TW, ja and de, at 440px wide: no sideways scroll.
|
||||
// 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 { strings } = require("./strings.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const HOME = "/Users/ink";
|
||||
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
|
||||
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"] },
|
||||
];
|
||||
const FOUND = () => [
|
||||
{ key: "k-say", agent: "claude", event: "Stop", commands: ["say done"], file: `${HOME}/.claude/settings.json`, hook: { name: "say", event: "turn-end", command: "say done", agents: ["claude"] } },
|
||||
{ key: "k-two", agent: "codex", event: "PostToolUse", matcher: "Bash", commands: ["lint-a", "lint-b"], file: `${HOME}/.codex/hooks.json`, why: "several" },
|
||||
{ key: "k-rtk", agent: "claude", event: "PreToolUse", matcher: "Bash", commands: ["rtk hook claude"], file: `${HOME}/.claude/settings.json`, own: "rtk" },
|
||||
];
|
||||
const lib = (state) => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [agent("claude", "Claude Code"), agent("codex", "Codex")],
|
||||
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [],
|
||||
hooks: state.hooks, hookAgents: HOOK_AGENTS, foundHooks: state.found,
|
||||
});
|
||||
|
||||
let I18N;
|
||||
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) {
|
||||
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));
|
||||
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 });
|
||||
if (what === "hooks/import") {
|
||||
const f = state.found.find((x) => body.names.includes(x.key));
|
||||
state.hooks = [...state.hooks, f.hook];
|
||||
state.found = state.found.filter((x) => !body.names.includes(x.key));
|
||||
}
|
||||
if (what === "hooks/remove-found") state.found = state.found.filter((x) => !body.names.includes(x.key));
|
||||
return json({ ...lib(state), 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: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
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-foundhookhead > *, #view-library .lib-foundhook, #view-library .lib-foundhook *, #modal .lib-editor *")) {
|
||||
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 hooks the agents run that magpie didn't give them", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
I18N = strings().I18N;
|
||||
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: [], found: FOUND() };
|
||||
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.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, state, posts));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const rows = page.locator("#view-library .lib-foundhook");
|
||||
await rows.first().waitFor();
|
||||
|
||||
// the library has none: the found ones are listed under the empty state
|
||||
assert.equal(await page.locator("#view-library .lib-foundhookhead .label").textContent(), w("In your agents"));
|
||||
assert.equal(await rows.count(), 2, "RTK's own hook isn't listed");
|
||||
const say = rows.filter({ hasText: "say done" });
|
||||
assert.equal((await say.locator(".name").textContent()).trim(), "Stop");
|
||||
assert.equal((await say.locator(".lib-path").textContent()).trim(), "~/.claude/settings.json");
|
||||
assert.equal(await say.locator(".lib-have [title]").getAttribute("title"), "Claude Code");
|
||||
const two = rows.filter({ hasText: "lint-a ; lint-b" });
|
||||
assert.equal((await two.locator(".name").textContent()).trim(), "PostToolUse · Bash");
|
||||
const twoIn = two.getByRole("button", { name: w("Bring in"), exact: true });
|
||||
assert(await twoIn.isDisabled(), "one the library can't keep as written can't be brought in");
|
||||
assert.equal(await twoIn.getAttribute("title"), w("It runs several commands: the library keeps a hook as one command"));
|
||||
assert.deepEqual(await sideways(page), [], "nothing sideways at 440");
|
||||
|
||||
// removing asks first, says where the backup goes, and posts the key
|
||||
await two.locator("button.lib-icon.danger").click();
|
||||
const modal = page.locator("#modal");
|
||||
await modal.locator(".ehead b").waitFor();
|
||||
assert.equal(await modal.locator(".ehead b").textContent(), w("Remove this {event} hook?", { event: "PostToolUse · Bash" }));
|
||||
assert(await modal.getByText(w("It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.", { file: "~/.codex/hooks.json" })).isVisible());
|
||||
assert.deepEqual(await sideways(page), [], "the dialog fits at 440");
|
||||
assert.equal(posts.length, 0, "nothing posted before the confirm");
|
||||
await modal.getByRole("button", { name: w("Remove"), exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-foundhook").length === 1);
|
||||
assert.deepEqual(posts.at(-1), { what: "hooks/remove-found", body: { names: ["k-two"] } });
|
||||
|
||||
// bringing one in posts its key, and it is the library's after
|
||||
await say.getByRole("button", { name: w("Bring in"), exact: true }).click();
|
||||
await page.waitForFunction(() => !document.querySelector("#view-library .lib-foundhook"));
|
||||
assert.deepEqual(posts.at(-1), { what: "hooks/import", body: { names: ["k-say"] } });
|
||||
assert.equal(await page.locator("#view-library .lib-hook .name").first().textContent(), "say");
|
||||
assert.equal(await page.locator("#view-library .lib-foundhookhead").count(), 0, "with none found, no heading");
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// Hooks the agents run that magpie didn't give them (@InkCoalW on X: read
|
||||
// and manage the hooks an agent already uses, and clean them up): an entry
|
||||
// in an agent's own hooks file that no record of magpie's claims, as the
|
||||
// user or another tool wrote it. The Hooks tab lists them under "In your
|
||||
// agents", as the MCP and Skills tabs list the servers and skills the
|
||||
// agents have of their own. One can be brought into the library, from then
|
||||
// on magpie's like any hook it wrote (unticked, edited, given to the other
|
||||
// agents), or taken out of the agent's file, the file copied to the backups
|
||||
// first, so Backups puts it back.
|
||||
|
||||
// FoundHook is one entry of an agent's hooks file that magpie didn't write.
|
||||
type FoundHook struct {
|
||||
// Key names the entry for ImportHooks and RemoveFoundHooks: the agent,
|
||||
// its event, the entry's text and which of the same entries it is
|
||||
Key string `json:"key"`
|
||||
Agent string `json:"agent"`
|
||||
// Event is the agent's own name for it ("PostToolUse")
|
||||
Event string `json:"event"`
|
||||
Matcher string `json:"matcher,omitempty"`
|
||||
// Commands are what it runs: a group can hold several, and a handler
|
||||
// that isn't a command is named by its type, "(prompt)"
|
||||
Commands []string `json:"commands"`
|
||||
// Timeout in seconds, when the entry sets one
|
||||
Timeout int `json:"timeout,omitempty"`
|
||||
File string `json:"file"`
|
||||
// Hook is what bringing it in makes it; nil when the library can't
|
||||
// keep it as it is written (Why: "several", "type" or "shape"), and
|
||||
// then it can only be removed
|
||||
Hook *Hook `json:"hook,omitempty"`
|
||||
Why string `json:"why,omitempty"`
|
||||
// Joins is the library hook it is the same as, for another agent:
|
||||
// bringing it in ticks this agent for that hook
|
||||
Joins string `json:"joins,omitempty"`
|
||||
// Own: written by a tool magpie runs from another tab ("rtk", RTK's
|
||||
// installer), which takes it out there; the page doesn't list it
|
||||
Own string `json:"own,omitempty"`
|
||||
|
||||
entry json.RawMessage
|
||||
canon string // the entry written one way, as the records compare it
|
||||
}
|
||||
|
||||
// foundOwner is the tool of magpie's another tab that writes a hook with
|
||||
// this command: RTK's installer writes "rtk hook <agent>" (rtk.go), Gemini's
|
||||
// as rtk-hook-gemini.
|
||||
func foundOwner(cmds []string) string {
|
||||
for _, c := range cmds {
|
||||
if strings.Contains(c, "rtk hook ") || strings.Contains(c, "rtk-hook-") {
|
||||
return "rtk"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// foundHooksOf lists the hooks of these agents that no record of magpie's
|
||||
// claims. A file that can't be read is left out: what it holds is unknown,
|
||||
// and it is said on the library's hooks where it matters.
|
||||
func foundHooksOf(l *Library, targets []*Target) []FoundHook {
|
||||
out := []FoundHook{}
|
||||
for _, t := range targets {
|
||||
if t.Gone || t.Agent.ID == "dsh" {
|
||||
// dsh's magpie-hooks.json is magpie's own file, every entry of it
|
||||
continue
|
||||
}
|
||||
sp, _ := hookSpecOf(t)
|
||||
if sp == nil {
|
||||
continue
|
||||
}
|
||||
evs, lists, err := hookLists(sp)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
claimed := map[string]map[int]bool{}
|
||||
for _, rec := range l.applied(t.Agent.ID).Hooks {
|
||||
c := canonical(rec.Entry)
|
||||
for i, e := range lists[rec.Event] {
|
||||
if !claimed[rec.Event][i] && canonical(e) == c {
|
||||
if claimed[rec.Event] == nil {
|
||||
claimed[rec.Event] = map[int]bool{}
|
||||
}
|
||||
claimed[rec.Event][i] = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, ev := range evs {
|
||||
seen := map[string]int{}
|
||||
for i, e := range lists[ev] {
|
||||
if claimed[ev][i] {
|
||||
continue
|
||||
}
|
||||
c := canonical(e)
|
||||
n := seen[c]
|
||||
seen[c]++
|
||||
f := foundHook(l, t.Agent.ID, sp, ev, e)
|
||||
f.Key, f.canon = foundKey(t.Agent.ID, ev, c, n), c
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func foundKey(agent, ev, canon string, n int) string {
|
||||
s := sha256.Sum256([]byte(agent + "\x00" + ev + "\x00" + canon + "\x00" + strconv.Itoa(n)))
|
||||
return hex.EncodeToString(s[:8])
|
||||
}
|
||||
|
||||
// hookLists is every event's list in the agent's hooks file, the events in
|
||||
// the file's order.
|
||||
func hookLists(sp *hookSpec) ([]string, map[string][]json.RawMessage, error) {
|
||||
lists := map[string][]json.RawMessage{}
|
||||
var evs []string
|
||||
if sp.toml {
|
||||
for _, ev := range sp.native {
|
||||
x, err := grokHookBlocks(sp.path, ev)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(x) > 0 {
|
||||
evs = append(evs, ev)
|
||||
lists[ev] = x
|
||||
}
|
||||
}
|
||||
return evs, lists, nil
|
||||
}
|
||||
doc, err := readHooksFile(sp.path)
|
||||
if err != nil || doc == nil {
|
||||
return nil, lists, err
|
||||
}
|
||||
var failed error
|
||||
gjson.GetBytes(doc, "hooks").ForEach(func(k, v gjson.Result) bool {
|
||||
if !v.IsArray() {
|
||||
return true // not a list of hooks: nothing the agent runs, left as it is
|
||||
}
|
||||
var list []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(v.Raw), &list); err != nil {
|
||||
failed = err
|
||||
return false
|
||||
}
|
||||
evs = append(evs, k.String())
|
||||
lists[k.String()] = list
|
||||
return true
|
||||
})
|
||||
return evs, lists, failed
|
||||
}
|
||||
|
||||
// foundHook reads one entry: what it runs, and the library hook it would
|
||||
// be, checked by writing that hook back the way magpie writes it: only an
|
||||
// entry that comes out the same is brought in, so nothing of the user's
|
||||
// (a second command, async, a status message) is lost on the next write.
|
||||
func foundHook(l *Library, id string, sp *hookSpec, ev string, e json.RawMessage) FoundHook {
|
||||
f := FoundHook{Agent: id, Event: ev, File: sp.path, Commands: []string{}, entry: e}
|
||||
var group map[string]any
|
||||
if sp.toml {
|
||||
blk, _ := grokBlockText(e)
|
||||
var doc map[string]any
|
||||
if toml.Unmarshal([]byte(blk), &doc) == nil {
|
||||
hs, _ := doc["hooks"].(map[string]any)
|
||||
list, _ := hs[ev].([]any)
|
||||
if len(list) == 1 {
|
||||
group, _ = list[0].(map[string]any)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_ = json.Unmarshal(e, &group)
|
||||
}
|
||||
var handlers []map[string]any
|
||||
if sp.flat {
|
||||
if group != nil {
|
||||
handlers = []map[string]any{group}
|
||||
}
|
||||
} else if group != nil {
|
||||
hs, _ := group["hooks"].([]any)
|
||||
for _, h := range hs {
|
||||
if m, ok := h.(map[string]any); ok {
|
||||
handlers = append(handlers, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
if group != nil {
|
||||
f.Matcher, _ = group["matcher"].(string)
|
||||
}
|
||||
why := ""
|
||||
for _, h := range handlers {
|
||||
typ, _ := h["type"].(string)
|
||||
cmd, _ := h["command"].(string)
|
||||
if (typ == "" || typ == "command") && cmd != "" {
|
||||
f.Commands = append(f.Commands, cmd)
|
||||
} else {
|
||||
if typ == "" {
|
||||
typ = "?"
|
||||
}
|
||||
f.Commands = append(f.Commands, "("+typ+")")
|
||||
why = "type"
|
||||
}
|
||||
}
|
||||
if len(handlers) == 1 {
|
||||
f.Timeout = numberOf(handlers[0]["timeout"])
|
||||
if sp.ms {
|
||||
f.Timeout /= 1000
|
||||
}
|
||||
}
|
||||
f.Own = foundOwner(f.Commands)
|
||||
switch {
|
||||
case why != "":
|
||||
case len(handlers) != 1:
|
||||
why = "several"
|
||||
default:
|
||||
if h := adoptable(id, sp, ev, e, f.Matcher, f.Commands[0], numberOf(handlers[0]["timeout"])); h != nil {
|
||||
f.Hook = h
|
||||
for _, x := range l.Hooks {
|
||||
if x.Event == h.Event && x.Matcher == h.Matcher && x.Command == h.Command && x.Timeout == h.Timeout && hookTakes(x, id) {
|
||||
f.Joins = x.Name
|
||||
h.Name = x.Name
|
||||
break
|
||||
}
|
||||
}
|
||||
if f.Joins == "" {
|
||||
h.Name = freeHookName(l, h.Command)
|
||||
}
|
||||
} else {
|
||||
why = "shape"
|
||||
}
|
||||
}
|
||||
f.Why = why
|
||||
return f
|
||||
}
|
||||
|
||||
func numberOf(v any) int {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return int(n)
|
||||
case int64:
|
||||
return int(n)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// adoptable is the library hook entry e is, under event ev of the agent, or
|
||||
// nil when no hook magpie writes comes out as e: a portable one when its
|
||||
// event and matcher are the portable one's, else the agent's own event as
|
||||
// written.
|
||||
func adoptable(id string, sp *hookSpec, ev string, e json.RawMessage, matcher, cmd string, timeout int) *Hook {
|
||||
if sp.ms {
|
||||
if timeout%1000 != 0 {
|
||||
return nil
|
||||
}
|
||||
timeout /= 1000
|
||||
}
|
||||
var tries []Hook
|
||||
for _, p := range HookEvents {
|
||||
if sp.events[p] != ev {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case matcher == "":
|
||||
tries = append(tries, Hook{Event: p})
|
||||
case slices.Contains(toolEvents, p):
|
||||
for _, k := range HookTools {
|
||||
if sp.tools[k] == matcher {
|
||||
tries = append(tries, Hook{Event: p, Matcher: k})
|
||||
}
|
||||
}
|
||||
case p == "session-start":
|
||||
tries = append(tries, Hook{Event: p, Matcher: matcher})
|
||||
if g := grokStarts[matcher]; g != nil {
|
||||
tries = append(tries, Hook{Event: p, Matcher: strings.Join(g, "|")})
|
||||
}
|
||||
}
|
||||
}
|
||||
if slices.Contains(sp.native, ev) {
|
||||
tries = append(tries, Hook{Event: id + ":" + ev, Matcher: matcher})
|
||||
}
|
||||
want := canonical(e)
|
||||
for _, h := range tries {
|
||||
h.Name, h.Command, h.Timeout, h.Agents = "found", cmd, timeout, []string{id}
|
||||
if h.check() != nil || !hookTakes(&h, id) {
|
||||
continue
|
||||
}
|
||||
if canonical(sp.entry(&h, ev)) == want {
|
||||
return &h
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// freeHookName is a name for a hook running cmd that the library doesn't
|
||||
// have yet: the program it runs, "say" for "say done".
|
||||
func freeHookName(l *Library, cmd string) string {
|
||||
base := "hook"
|
||||
for _, w := range strings.Fields(cmd) {
|
||||
if strings.Contains(w, "=") && !strings.ContainsAny(w, "/\\") {
|
||||
continue // FOO=1 before the program
|
||||
}
|
||||
w = strings.Trim(w, `"'`)
|
||||
w = filepath.Base(strings.ReplaceAll(w, `\`, "/"))
|
||||
w = strings.TrimSuffix(w, filepath.Ext(w))
|
||||
var b strings.Builder
|
||||
for _, r := range strings.ToLower(w) {
|
||||
if r < 128 && (r == '-' || r == '_' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9') {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if s := strings.Trim(b.String(), "-_"); s != "" {
|
||||
base = s
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(base) > 40 {
|
||||
base = base[:40]
|
||||
}
|
||||
name := base
|
||||
for n := 2; l.hook(name) != nil; n++ {
|
||||
name = base + "-" + strconv.Itoa(n)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func pickFound(found []FoundHook, keys []string) ([]FoundHook, error) {
|
||||
if len(keys) == 0 {
|
||||
return nil, errors.New("no hooks named")
|
||||
}
|
||||
var out []FoundHook
|
||||
for _, k := range slices.Compact(slices.Sorted(slices.Values(keys))) {
|
||||
i := slices.IndexFunc(found, func(f FoundHook) bool { return f.Key == k })
|
||||
if i < 0 {
|
||||
return nil, errors.New("that hook is no longer in the agent's file: it changed since the page was drawn")
|
||||
}
|
||||
out = append(out, found[i])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ImportHooks brings the hooks named into the library: each is the
|
||||
// library's from then on, given to the agent it was found in, the entry
|
||||
// there left exactly as it is. One the same as a library hook given to
|
||||
// other agents ticks this agent for that hook.
|
||||
func ImportHooks(keys []string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
found, err := pickFound(foundHooksOf(l, Targets()), keys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range found {
|
||||
if f.Hook == nil {
|
||||
return fmt.Errorf("magpie can't keep %s's %s hook as it is written: it can only be removed", f.Agent, f.Event)
|
||||
}
|
||||
// the same hook in the library, one brought in a moment ago
|
||||
// from another agent too, takes this agent as well
|
||||
var h *Hook
|
||||
for _, x := range l.Hooks {
|
||||
if x.Event == f.Hook.Event && x.Matcher == f.Hook.Matcher && x.Command == f.Hook.Command && x.Timeout == f.Hook.Timeout && hookTakes(x, f.Agent) {
|
||||
h = x
|
||||
break
|
||||
}
|
||||
}
|
||||
if h == nil {
|
||||
c := *f.Hook
|
||||
c.Name = freeHookName(l, c.Command)
|
||||
h = &c
|
||||
l.Hooks = append(l.Hooks, h)
|
||||
}
|
||||
h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(append(slices.Clone(h.Agents), f.Agent)))))
|
||||
a := l.applied(f.Agent)
|
||||
a.Hooks = append(a.Hooks, HookEntry{Name: h.Name, Event: f.Event, Entry: f.entry})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// foundSentinel names the record of a found hook being taken out, which
|
||||
// no library hook can be called.
|
||||
const foundSentinel = "\x00found"
|
||||
|
||||
// RemoveFoundHooks takes the hooks named out of their agents' files, each
|
||||
// file copied to the backups first: Backups puts one back. The rest of
|
||||
// each file stays as it is, and Codex's trust of the hooks after one moves
|
||||
// with them.
|
||||
func RemoveFoundHooks(keys []string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
all := foundHooksOf(l, Targets())
|
||||
found, err := pickFound(all, keys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b := l.kept
|
||||
if b == nil {
|
||||
b = newBackups()
|
||||
l.kept = b
|
||||
}
|
||||
byAgent := map[string][]FoundHook{}
|
||||
for _, f := range found {
|
||||
byAgent[f.Agent] = append(byAgent[f.Agent], f)
|
||||
}
|
||||
for _, id := range slices.Sorted(func(yield func(string) bool) {
|
||||
for k := range byAgent {
|
||||
if !yield(k) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}) {
|
||||
t := targetByID(id)
|
||||
if t == nil {
|
||||
return fmt.Errorf("%s isn't here", id)
|
||||
}
|
||||
sp, why := hookSpecOf(t)
|
||||
if sp == nil {
|
||||
return errors.New(why)
|
||||
}
|
||||
a := l.applied(id)
|
||||
var want []*Hook
|
||||
for _, h := range l.Hooks {
|
||||
if slices.Contains(h.Agents, id) {
|
||||
want = append(want, h)
|
||||
}
|
||||
}
|
||||
recs := slices.Clone(a.Hooks)
|
||||
for _, f := range byAgent[id] {
|
||||
recs = append(recs, HookEntry{Name: foundSentinel, Event: f.Event, Entry: f.entry})
|
||||
}
|
||||
// a failure of the found entries' own, or of the whole file,
|
||||
// stops it; a library hook's own (an event the agent lacks) is
|
||||
// the sync's to say
|
||||
var failed, first error
|
||||
w := &hookWrite{id: id, sp: sp, want: want, recs: recs, gone: t.Gone,
|
||||
keep: func(path string) error { return b.keep(id, path) },
|
||||
fail: func(what string, err error) {
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
if failed == nil && (what == "hooks" || what == "hook:"+foundSentinel) {
|
||||
failed = err
|
||||
}
|
||||
}}
|
||||
if id == "codex" {
|
||||
w.rekeyCfg = filepath.Join(codexDir(), "config.toml")
|
||||
}
|
||||
got, _, ok := w.run()
|
||||
if !ok {
|
||||
if failed == nil {
|
||||
failed = first
|
||||
}
|
||||
if failed == nil {
|
||||
failed = fmt.Errorf("%s couldn't be written", sp.path)
|
||||
}
|
||||
return fmt.Errorf("%s: %w", t.Agent.Name, failed)
|
||||
}
|
||||
if failed != nil {
|
||||
return fmt.Errorf("%s: %w", t.Agent.Name, failed)
|
||||
}
|
||||
a.Hooks = slices.DeleteFunc(got, func(r HookEntry) bool { return r.Name == foundSentinel })
|
||||
}
|
||||
// read back: as many of each entry as there were, less those taken
|
||||
// out, or the one left is said, not reported gone
|
||||
count := func(fs []FoundHook) map[string]int {
|
||||
m := map[string]int{}
|
||||
for _, f := range fs {
|
||||
m[f.Agent+"\x00"+f.Event+"\x00"+f.canon]++
|
||||
}
|
||||
return m
|
||||
}
|
||||
before, after, gone := count(all), count(foundHooksOf(l, Targets())), count(found)
|
||||
for _, f := range found {
|
||||
k := f.Agent + "\x00" + f.Event + "\x00" + f.canon
|
||||
if after[k] > before[k]-gone[k] {
|
||||
return fmt.Errorf("the %s hook is still in %s", f.Event, f.File)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func foundHooks(t *testing.T) []FoundHook {
|
||||
t.Helper()
|
||||
v, err := Read(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v.FoundHooks
|
||||
}
|
||||
|
||||
func foundBy(fs []FoundHook, agent, cmd string) *FoundHook {
|
||||
for i := range fs {
|
||||
if fs[i].Agent == agent && strings.Join(fs[i].Commands, "\n") == cmd {
|
||||
return &fs[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keptCopies is the copies of a file named base in magpie's backups.
|
||||
func keptCopies(t *testing.T, base string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
filepath.WalkDir(BackupDir(), func(p string, d fs.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() && filepath.Base(p) == base {
|
||||
b, _ := os.ReadFile(p)
|
||||
out = append(out, string(b))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// The hooks an agent already runs that magpie didn't give it are listed
|
||||
// (@InkCoalW on X), each as what it runs and where; the ones magpie wrote
|
||||
// aren't, nor are RTK's (the RTK tab's), and one the library can't keep as
|
||||
// written is said so, to be removed only.
|
||||
func TestFoundHooksListed(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
write(t, settings, `{
|
||||
// the user's own
|
||||
"model": "opus",
|
||||
"hooks": {
|
||||
"Stop": [
|
||||
{"hooks": [{"type": "command", "command": "say done", "timeout": 5}]},
|
||||
{"hooks": [{"type": "command", "command": "bg-job", "async": true}]}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{"matcher": "Edit|Write|MultiEdit", "hooks": [{"type": "command", "command": "prettier --write ."}]},
|
||||
{"matcher": "Bash", "hooks": [{"type": "command", "command": "a"}, {"type": "command", "command": "b"}]}
|
||||
],
|
||||
"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "rtk hook claude"}]}],
|
||||
"Notification": [{"hooks": [{"type": "prompt", "prompt": "is it done?"}]}]
|
||||
}
|
||||
}
|
||||
`)
|
||||
write(t, filepath.Join(h, ".codex/hooks.json"), `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"/usr/local/bin/notify-me.sh --loud"}]}]}}`)
|
||||
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"claude"}}))
|
||||
|
||||
fs := foundHooks(t)
|
||||
if f := foundBy(fs, "claude", "bark"); f != nil {
|
||||
t.Errorf("the hook magpie wrote is listed as found: %+v", f)
|
||||
}
|
||||
say := foundBy(fs, "claude", "say done")
|
||||
if say == nil || say.Event != "Stop" || say.Timeout != 5 || say.File != settings || say.Hook == nil ||
|
||||
say.Hook.Event != "turn-end" || say.Hook.Name != "say" || say.Hook.Timeout != 5 {
|
||||
t.Fatalf("say done: %+v (%+v)", say, fs)
|
||||
}
|
||||
if f := foundBy(fs, "claude", "prettier --write ."); f == nil || f.Hook == nil || f.Hook.Event != "after-tool" || f.Hook.Matcher != "edit" {
|
||||
t.Errorf("prettier, a portable after-tool on edit: %+v", f)
|
||||
}
|
||||
if f := foundBy(fs, "claude", "a\nb"); f == nil || f.Hook != nil || f.Why != "several" || f.Matcher != "Bash" {
|
||||
t.Errorf("a group of two commands: %+v", f)
|
||||
}
|
||||
// async isn't a thing a library hook has: brought in, the next write
|
||||
// would drop it
|
||||
if f := foundBy(fs, "claude", "bg-job"); f == nil || f.Hook != nil || f.Why != "shape" {
|
||||
t.Errorf("an async hook: %+v", f)
|
||||
}
|
||||
if f := foundBy(fs, "claude", "(prompt)"); f == nil || f.Hook != nil || f.Why != "type" {
|
||||
t.Errorf("a prompt hook: %+v", f)
|
||||
}
|
||||
if f := foundBy(fs, "claude", "rtk hook claude"); f == nil || f.Own != "rtk" {
|
||||
t.Errorf("RTK's hook: %+v", f)
|
||||
}
|
||||
if f := foundBy(fs, "codex", "/usr/local/bin/notify-me.sh --loud"); f == nil || f.Hook == nil || f.Hook.Name != "notify-me" {
|
||||
t.Errorf("codex's: %+v", f)
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for _, f := range fs {
|
||||
if keys[f.Key] || f.Key == "" {
|
||||
t.Errorf("key %q twice or empty", f.Key)
|
||||
}
|
||||
keys[f.Key] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Brought into the library, a found hook is magpie's like one it wrote:
|
||||
// the entry stays as it is, given to the other agents it lands in their
|
||||
// files, and unticked it comes out of the file it was found in, the user's
|
||||
// other hooks left. One the same as a library hook joins it.
|
||||
func TestFoundHooksBroughtIn(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
mine := `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"say done"}]}],"Notification":[{"hooks":[{"type":"command","command":"keep-me"}]}]}}`
|
||||
write(t, settings, mine)
|
||||
codexHooks := filepath.Join(h, ".codex/hooks.json")
|
||||
write(t, codexHooks, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"say done"}]}]}}`)
|
||||
|
||||
fs := foundHooks(t)
|
||||
cl, cx := foundBy(fs, "claude", "say done"), foundBy(fs, "codex", "say done")
|
||||
if cl == nil || cx == nil {
|
||||
t.Fatalf("found: %+v", fs)
|
||||
}
|
||||
ok(t)(ImportHooks([]string{cl.Key, cx.Key}))
|
||||
if got := read(t, settings); got != mine {
|
||||
t.Errorf("bringing it in changed the file:\n%s", got)
|
||||
}
|
||||
v, _ := Read(nil)
|
||||
if len(v.Hooks) != 1 || v.Hooks[0].Name != "say" || v.Hooks[0].Event != "turn-end" || strings.Join(v.Hooks[0].Agents, ",") != "claude,codex" {
|
||||
t.Fatalf("library hooks: %+v", v.Hooks)
|
||||
}
|
||||
if f := foundBy(v.FoundHooks, "claude", "say done"); f != nil {
|
||||
t.Errorf("still found after it was brought in: %+v", f)
|
||||
}
|
||||
if f := foundBy(v.FoundHooks, "claude", "keep-me"); f == nil {
|
||||
t.Errorf("the one not brought in is no longer found")
|
||||
}
|
||||
// given to Gemini too, it lands there
|
||||
ok(t)(HookAgents("say", []string{"claude", "codex", "gemini"}))
|
||||
if got := hooksOf(t, filepath.Join(h, ".gemini/settings.json"), "AfterAgent"); len(got) != 1 || !strings.Contains(got[0], "say done") {
|
||||
t.Errorf("gemini AfterAgent: %v", got)
|
||||
}
|
||||
// unticked for Claude, it comes out of the file it was found in alone
|
||||
ok(t)(HookAgents("say", []string{"codex", "gemini"}))
|
||||
if got := hooksOf(t, settings, "Stop"); len(got) != 0 {
|
||||
t.Errorf("claude Stop after unticking: %v", got)
|
||||
}
|
||||
if got := hooksOf(t, settings, "Notification"); len(got) != 1 {
|
||||
t.Errorf("the user's other hook went: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Removed, a found hook comes out of its agent's file and nothing else
|
||||
// does: the user's other hooks, their comments and settings stay, the
|
||||
// file is copied to the backups first, and Codex's trust of the hooks
|
||||
// after it moves with them.
|
||||
func TestFoundHooksRemoved(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
before := `{
|
||||
// the user's own
|
||||
"model": "opus",
|
||||
"hooks": {
|
||||
"Stop": [
|
||||
{"hooks": [{"type": "command", "command": "old-thing"}]},
|
||||
{"hooks": [{"type": "command", "command": "say done"}]}
|
||||
]
|
||||
}
|
||||
}
|
||||
`
|
||||
write(t, settings, before)
|
||||
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"claude", "codex"}}))
|
||||
codexHooks := filepath.Join(h, ".codex/hooks.json")
|
||||
cfg := filepath.Join(h, ".codex/config.toml")
|
||||
// the user's two of their own, the first to go, after magpie's: the
|
||||
// second's trust moves to the first's place
|
||||
write(t, codexHooks, `{"hooks":{"Stop":[{"hooks":[{"command":"bark","type":"command"}]},{"hooks":[{"type":"command","command":"gone-soon"}]},{"hooks":[{"type":"command","command":"mine"}]}]}}`)
|
||||
key := func(g int) string { return codexKey(codexHooks + ":stop:" + string(rune('0'+g)) + ":0") }
|
||||
write(t, cfg, "model = \"gpt-5\"\n\n[hooks.state]\n\n[hooks.state."+key(1)+"]\ntrusted_hash = \"sha256:aaa\"\n\n[hooks.state."+key(2)+"]\ntrusted_hash = \"sha256:bbb\"\n")
|
||||
|
||||
fs := foundHooks(t)
|
||||
old, gone := foundBy(fs, "claude", "old-thing"), foundBy(fs, "codex", "gone-soon")
|
||||
if old == nil || gone == nil {
|
||||
t.Fatalf("found: %+v", fs)
|
||||
}
|
||||
ok(t)(RemoveFoundHooks([]string{old.Key, gone.Key}))
|
||||
|
||||
got := read(t, settings)
|
||||
if !strings.Contains(got, "// the user's own") || !strings.Contains(got, `"model": "opus"`) || strings.Contains(got, "old-thing") || !strings.Contains(got, "say done") {
|
||||
t.Errorf("claude's settings after:\n%s", got)
|
||||
}
|
||||
if s := hooksOf(t, settings, "Stop"); len(s) != 2 || !strings.Contains(s[1], `"bark"`) {
|
||||
t.Errorf("claude Stop after (say done, then magpie's bark): %v", s)
|
||||
}
|
||||
if b := keptCopies(t, "settings.json"); len(b) == 0 || !strings.Contains(strings.Join(b, ""), "old-thing") {
|
||||
t.Errorf("claude's settings weren't backed up first: %q", b)
|
||||
}
|
||||
if s := hooksOf(t, codexHooks, "Stop"); len(s) != 2 || !strings.Contains(s[0], "bark") || !strings.Contains(s[1], "mine") {
|
||||
t.Errorf("codex Stop after: %v", s)
|
||||
}
|
||||
if b := keptCopies(t, "hooks.json"); len(b) == 0 || !strings.Contains(strings.Join(b, ""), "gone-soon") {
|
||||
t.Errorf("codex's hooks weren't backed up first: %q", b)
|
||||
}
|
||||
if c, want := read(t, cfg), "model = \"gpt-5\"\n\n[hooks.state]\n\n[hooks.state."+key(1)+"]\ntrusted_hash = \"sha256:bbb\"\n"; c != want {
|
||||
t.Errorf("codex config.toml after:\n%s\nwant:\n%s", c, want)
|
||||
}
|
||||
// magpie's own hook is magpie's still: unticking it takes it out
|
||||
ok(t)(RemoveHooks([]string{"bark"}))
|
||||
if s := hooksOf(t, settings, "Stop"); len(s) != 1 || !strings.Contains(s[0], "say done") {
|
||||
t.Errorf("claude Stop after bark went: %v", s)
|
||||
}
|
||||
// a key the file no longer has is said, not taken as done
|
||||
if _, err := RemoveFoundHooks([]string{old.Key}); err == nil {
|
||||
t.Errorf("a found hook gone already was removed again without a word")
|
||||
}
|
||||
}
|
||||
|
||||
// Of two entries the same, removing one leaves the other; a Grok block
|
||||
// comes out of its config.toml alone.
|
||||
func TestFoundHooksTwinsAndGrok(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
write(t, settings, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"twin"}]},{"hooks":[{"type":"command","command":"twin"}]}]}}`)
|
||||
build := filepath.Join(h, ".grok/config.toml")
|
||||
write(t, build, "model = \"grok-4.7\"\n\n[[hooks.Stop]]\n [[hooks.Stop.hooks]]\n type = \"command\"\n command = \"say grok done\"\n\n[[hooks.Stop]]\n [[hooks.Stop.hooks]]\n type = \"command\"\n command = \"stays\"\n")
|
||||
|
||||
fs := foundHooks(t)
|
||||
var twins []FoundHook
|
||||
for _, f := range fs {
|
||||
if f.Agent == "claude" {
|
||||
twins = append(twins, f)
|
||||
}
|
||||
}
|
||||
if len(twins) != 2 || twins[0].Key == twins[1].Key {
|
||||
t.Fatalf("twins: %+v", twins)
|
||||
}
|
||||
g := foundBy(fs, "grok", "say grok done")
|
||||
if g == nil || g.Hook == nil || g.Hook.Event != "turn-end" {
|
||||
t.Fatalf("grok: %+v", fs)
|
||||
}
|
||||
ok(t)(RemoveFoundHooks([]string{twins[1].Key, g.Key}))
|
||||
if s := hooksOf(t, settings, "Stop"); len(s) != 1 {
|
||||
t.Errorf("claude Stop after one twin went: %v", s)
|
||||
}
|
||||
if b := grokBlocks(t, build, "Stop"); len(b) != 1 || !strings.Contains(b[0], "stays") {
|
||||
t.Errorf("grok Stop after: %q", b)
|
||||
}
|
||||
if s := read(t, build); !strings.HasPrefix(s, "model = \"grok-4.7\"\n") {
|
||||
t.Errorf("grok config after:\n%s", s)
|
||||
}
|
||||
}
|
||||
@@ -558,6 +558,9 @@ type View struct {
|
||||
Rules []RuleView `json:"rules"`
|
||||
RuleAgents []RuleAgentView `json:"ruleAgents"`
|
||||
FoundServers []Found `json:"foundServers"`
|
||||
// FoundHooks are the hooks the agents run that magpie didn't give
|
||||
// them (hooks_found.go)
|
||||
FoundHooks []FoundHook `json:"foundHooks"`
|
||||
// Plugins are the plugins kept as one item each (plugin.go)
|
||||
Plugins []PluginView `json:"plugins"`
|
||||
Skills []SkillView `json:"skills"`
|
||||
@@ -869,6 +872,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
|
||||
for i := range v.FoundServers {
|
||||
v.FoundServers[i].Icon = serverIcon(l, v.FoundServers[i].Server)
|
||||
}
|
||||
v.FoundHooks = foundHooksOf(l, targets)
|
||||
v.NewSkills = newSkills(l)
|
||||
v.CheckFolders = l.addedFromFolders()
|
||||
v.Projects = projectViews(l, problems)
|
||||
|
||||
Reference in New Issue
Block a user