library: a project gets a single hook, for the agents that read a project's hooks file (#7253)

A project had hooks only through the plugins it took. Now the Hooks tab
lists the projects, and a hook can be given to one on its own, per agent
(Claude Code and Codex; Pi, Goose and the rest read no project hooks
file). Project.Hooks feeds projectHooks, so the write and the HookRecs
ownership records are the ones plugins' hooks already use: withdrawing
removes only what magpie wrote, never the user's own entries. Worktrees
follow through syncTrees; renaming or deleting a hook in the library moves
or drops its project entry. CLI: magpie library project hook.

Also fixes the CLI's problem keys (they lacked the kind prefix for mcp and
subagent) and the empty-project count in syncTrees, which now counts
Hooks and ClaudePlugins.

Run on mote: gofmt; go vet library, cli, gui; go test of the TestProject*,
TestHook* and TestLibraryProject* tests in internal/library and
internal/cli; GUI project-hooks (new, chromium and webkit, en and zh),
project-plugins, project-claude-plugins, i18n-keys. 14 other library GUI
files were red on this base with "nativeView is not iterable"; origin/main
has 03ae057b8 for that, rerun after the rebase.
Not tried: a real Codex or Claude session reading the written files.
This commit is contained in:
yetone
2026-11-20 04:36:59 +08:00
parent 81dc4fc67d
commit 1e174f8f9f
13 changed files with 410 additions and 16 deletions
File diff suppressed because one or more lines are too long
+7
View File
@@ -31,6 +31,11 @@ const libraryProjectUsage = `magpie library project [--json] the projects (
magpie library project subagent add <dir> <subagent…> [agents=a,b…] the same for library subagents
magpie library project subagent rm <dir> <subagent…> take subagents out of it
magpie library project subagent agents <dir> <subagent> <a,b…|none> the agents it has the subagent for
magpie library project hook [list] <dir> [--json] its own hooks and the agents each is for
magpie library project hook add <dir> <hook…> [agents=a,b…] give it library hooks, one at a time, written into
.claude/settings.local.json and .codex/hooks.json beside what's there
magpie library project hook rm <dir> <hook…> take them out, only the entries magpie wrote
magpie library project hook agents <dir> <hook> <a,b…|none> the agents it has the hook for
magpie library project instructions <dir> [--json] its own instructions, the agents they're for and the files
magpie library project instructions <dir> text <text…>|--file <f>|- set them ("" takes them out); written, between
magpie's two marker lines, into the project file each agent reads: by default for
@@ -141,6 +146,8 @@ func libraryProjectCmd(args []string) error {
return projectKindCmd(projectServers, rest, usage)
case "subagent":
return projectKindCmd(projectSubagents, rest, usage)
case "hook":
return projectKindCmd(projectHooks, rest, usage)
case "instructions", "instr":
return projectInstrCmd(rest, usage)
}
+10 -3
View File
@@ -25,7 +25,7 @@ type projectKind struct {
}
var projectServers = projectKind{
word: "server", plural: "servers", reads: "MCP servers", takes: "mcp",
word: "server", plural: "servers", reads: "MCP servers", takes: "mcp", problem: "mcp:",
folder: func(a library.AgentView) string { return a.ProjectMCP },
of: func(p *library.ProjectView) map[string][]string { return p.Servers },
set: func(dir string, names, agents []string) (*library.Result, error) {
@@ -42,12 +42,19 @@ var projectServers = projectKind{
}
var projectSubagents = projectKind{
word: "subagent", plural: "subagents", reads: "subagents", takes: "mcp",
word: "subagent", plural: "subagents", reads: "subagents", takes: "mcp", problem: "subagent:",
folder: func(a library.AgentView) string { return a.ProjectSubagents },
of: func(p *library.ProjectView) map[string][]string { return p.Subagents },
set: library.ProjectSubagents,
}
var projectHooks = projectKind{
word: "hook", plural: "hooks", reads: "hooks", problem: "hook:",
folder: func(a library.AgentView) string { return a.ProjectHooks },
of: func(p *library.ProjectView) map[string][]string { return p.Hooks },
set: library.ProjectHooks,
}
// agentsOf is a comma list of agents, none for no agent, each refused when
// magpie knows of no place it reads this kind from in a project.
func (k projectKind) agentsOf(v *library.View, s string) ([]string, error) {
@@ -194,7 +201,7 @@ func projectKindCmd(k projectKind, rest []string, usage func() error) error {
}
var bad []string
for _, n := range names {
key := k.word + ":" + n
key := k.problem + n
if why := p.Problems[key]; why != "" {
bad = append(bad, n)
fmt.Println(amber.Render("!"), n, muted.Render("not placed:"), why)
+52
View File
@@ -361,3 +361,55 @@ func TestLibraryProjectServerAndSubagentCmd(t *testing.T) {
}
refused("subagent", "rm", ".", "reviewer")
}
// #7253: one hook added to a project and taken out again through the CLI,
// beside the user's own entry, for the agents named.
func TestLibraryProjectHookCmd(t *testing.T) {
proj := projectSandbox(t)
if _, err := library.SaveHook("", library.Hook{Name: "bark", Event: "turn-end", Command: "say bark", Agents: []string{}}); err != nil {
t.Fatal(err)
}
own := `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo mine"}]}]}}`
if err := os.MkdirAll(filepath.Join(proj, ".claude"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(proj, ".claude", "settings.local.json"), []byte(own), 0o644); err != nil {
t.Fatal(err)
}
must := func(args ...string) string {
t.Helper()
out, err := projectOut(t, args...)
if err != nil {
t.Fatalf("library project %v: %v\n%s", args, err, out)
}
return out
}
read := func(rel string) string {
b, _ := os.ReadFile(filepath.Join(proj, rel))
return string(b)
}
must("add", ".")
for _, bad := range [][]string{{"hook", "add", ".", "nope"}, {"hook", "add", ".", "bark", "agents=zz"}, {"hook", "add", ".", "bark", "--yes"}, {"hook", "rm", ".", "bark"}} {
if out, err := projectOut(t, bad...); err == nil {
t.Errorf("library project %v was taken:\n%s", bad, out)
}
}
must("hook", "add", ".", "bark", "agents=claude,codex")
if got := read(".claude/settings.local.json"); !strings.Contains(got, "say bark") || !strings.Contains(got, "echo mine") {
t.Errorf("claude:\n%s", got)
}
if got := read(".codex/hooks.json"); !strings.Contains(got, "say bark") {
t.Errorf("codex:\n%s", got)
}
if out := must("hook", "."); !strings.Contains(out, "bark") || !strings.Contains(out, "codex") {
t.Errorf("list:\n%s", out)
}
must("hook", "agents", ".", "bark", "codex")
if got := read(".claude/settings.local.json"); strings.Contains(got, "say bark") || !strings.Contains(got, "echo mine") {
t.Errorf("claude after agents:\n%s", got)
}
must("hook", "rm", ".", "bark")
if _, err := os.Stat(filepath.Join(proj, ".codex", "hooks.json")); err == nil {
t.Error("the file magpie made stayed")
}
}
+37 -6
View File
@@ -4820,6 +4820,7 @@ magpie.plugin("library", (ctx) => {
// 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(", ") })));
if (!agentless() && (hooks.length || lib.projects.length)) renderProjects(body, "hooks");
body.append(...nativeSection("hook"));
}
@@ -7053,7 +7054,7 @@ magpie.plugin("library", (ctx) => {
function renderProjects(body, kind) {
const rh = el("div", "row-head");
rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : kind === "plugins" ? t("Project plugins") : kind === "instructions" ? t("Project instructions") : t("Project servers")), el("span", "grow"));
rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : kind === "plugins" ? t("Project plugins") : kind === "hooks" ? t("Project hooks") : kind === "instructions" ? t("Project instructions") : t("Project servers")), el("span", "grow"));
if (!addingProject) rh.append(button(t("Add a project"), "action lib-updall", () => { addingProject = { dir: "" }; render(); }));
body.append(rh);
if (addingProject) body.append(addProjectCard(kind));
@@ -7062,6 +7063,8 @@ magpie.plugin("library", (ctx) => {
? t("Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.")
: kind === "subagents"
? t("Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.")
: kind === "hooks"
? t("Give a project's agents some of these hooks as the project's own: magpie writes each into the project's .claude/settings.local.json or .codex/hooks.json, beside what's already there.")
: kind === "plugins"
? t("Give a project a whole plugin: magpie writes each part where its agents read the project's own, and taking the plugin out takes out only what it wrote.")
: kind === "mcp"
@@ -7122,19 +7125,19 @@ magpie.plugin("library", (ctx) => {
}
function projectCard(p, kind) {
const mcp = kind === "mcp", sub = kind === "subagents", ins = kind === "instructions", plg = kind === "plugins";
const mcp = kind === "mcp", sub = kind === "subagents", ins = kind === "instructions", plg = kind === "plugins", hk = kind === "hooks";
const card = el("div", "list lib-card lib-project" + (p.missing ? " missing" : ""));
const isOpen = openProjects.has(p.dir);
const head = el("div", "row lib-row click lib-projhead" + (isOpen ? " open" : ""));
const who = el("div", "who");
const nm = el("div", "name", p.name);
if (p.missing) nm.append(tag(t("Folder is gone"), "warn"));
else if (p.copy && !mcp && !sub && !ins && !plg) nm.append(tag(t("Copies"), ""));
else if (p.copy && !mcp && !sub && !ins && !plg && !hk) nm.append(tag(t("Copies"), ""));
who.append(nm);
const src = el("div", "lib-src");
src.append(pathLink(p.dir));
who.append(src);
const names = Object.keys((plg ? p.plugins : sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort();
const names = Object.keys((hk ? p.hooks : plg ? p.plugins : sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort();
const pills = el("div", "lib-tags");
if (!isOpen && ins) {
const first = (projTexts[p.dir] ?? p.instr ?? "").split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "") || "";
@@ -7147,7 +7150,7 @@ magpie.plugin("library", (ctx) => {
} else if (!isOpen) {
for (const n of names.slice(0, 4)) pills.append(tag(n, "lib-dot"));
if (names.length > 4) pills.append(tag("+" + (names.length - 4), ""));
if (!names.length) pills.append(tag(plg ? t("No Claude plugins yet") : sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked"));
if (!names.length) pills.append(tag(hk ? t("No hooks yet") : plg ? t("No Claude plugins yet") : sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked"));
}
const acts = el("div", "lib-rowacts");
const rm = button("", "lib-icon danger", () => confirmRemoveProject(p));
@@ -7158,13 +7161,14 @@ magpie.plugin("library", (ctx) => {
chev.append(svg(CHEV_R, 11, 1.7));
head.append(glyph(GLYPH.folder), who, pills, acts, chev);
head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); projectShown.delete(p.dir); render(); };
head.title = ins ? (isOpen ? t("Hide its instructions") : t("Write its instructions")) : plg ? (isOpen ? t("Hide its plugins") : t("Pick the plugins it gets")) : sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets");
head.title = hk ? (isOpen ? t("Hide its hooks") : t("Pick the hooks it gets")) : ins ? (isOpen ? t("Hide its instructions") : t("Write its instructions")) : plg ? (isOpen ? t("Hide its plugins") : t("Pick the plugins it gets")) : sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets");
card.append(head);
if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""]));
if (!isOpen) return card;
if (mcp) return projectServers(p, card);
if (sub) return projectSubagents(p, card);
if (plg) return projectPlugins(p, card);
if (hk) return projectHooks(p, card);
if (ins) return projectInstructions(p, card);
const opts = el("div", "lib-projopts");
@@ -7391,6 +7395,33 @@ magpie.plugin("library", (ctx) => {
return card;
}
// The project's card, open on the Hooks tab: each library hook with the
// chips of the agents that read hooks from a project's own file (#7253).
function projectHooks(p, card) {
const all = shownAgents().filter((a) => a.projectHooks);
for (const h of [...(lib.hooks || [])].sort((a, b) => a.name.localeCompare(b.name))) {
const row = el("div", "row lib-row lib-projskill lib-projhook");
const w = el("div", "who");
const n = el("div", "name mono", h.name);
const problem = p.problems?.["hook:" + h.name];
if (problem) n.append(tag(t("Not written"), "warn", problem));
w.append(n);
const sub = el("div", "sub", problem || hookLine(h));
sub.title = problem || h.command;
w.append(sub);
const on = (p.hooks?.[h.name] || []).filter((id) => all.some((a) => a.id === id));
const say = (next) => next.length
? t("{item} is in {name} for {agents}", { item: h.name, name: p.name, agents: next.map(nameOf).join(", ") })
: t("{item} is out of {name}", { item: h.name, name: p.name });
row.append(glyph(GLYPH.hook), w, agentChips(all, on, projectChange("projects/hooks", p.dir, h.name, say), { blocked: hookBlocked(h) }));
card.append(row);
}
if (!(lib.hooks || []).length) card.append(el("p", "lib-aside lib-projfoot", t("No hooks in the library yet")));
card.append(el("p", "lib-aside lib-projfoot", t("Written into the project's own hooks file for each agent, one entry per hook; a file magpie makes is kept out of git, its .gitignore untouched. An entry there that isn't magpie's is left as it is.")));
if (all.some((a) => a.id === "codex")) card.append(el("p", "lib-aside lib-projfoot lib-projhooks-codex", t("Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.")));
return card;
}
// The project's card, open on the Claude plugins tab: each library
// plugin with the chips of the agents that take some part of it in a
// project. A chip gives the agent every part it can take there; none
@@ -797,6 +797,12 @@ magpie.strings({
"Pick the plugins it gets": "选择它要用的插件",
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、服务器和子代理放在项目自己的那些位置,hooks 写进 .claude/settings.local.json 和 .codex/hooks.json。那里不是 magpie 写的文件、你改过的条目,都保持原样。",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。",
"Project hooks": "项目 Hooks",
"No hooks yet": "还没有 Hook",
"Hide its hooks": "收起它的 Hook",
"Pick the hooks it gets": "选择它用的 Hook",
"Give a project's agents some of these hooks as the project's own: magpie writes each into the project's .claude/settings.local.json or .codex/hooks.json, beside what's already there.": "把这些 Hook 作为项目自己的交给项目的 Agent:magpie 会把每个写进项目的 .claude/settings.local.json 或 .codex/hooks.json,原有内容保持不动。",
"Written into the project's own hooks file for each agent, one entry per hook; a file magpie makes is kept out of git, its .gitignore untouched. An entry there that isn't magpie's is left as it is.": "写进项目里每个 Agent 自己的 hooks 文件,一个 Hook 一条;magpie 新建的文件不会进 git,.gitignore 不动。文件里不是 magpie 写的条目保持原样。",
"The plugins above are Claude Code's own, turned on for this project in .claude/settings.local.json. They stay installed through Claude Code.": "上面的插件是 Claude Code 自带的,在 .claude/settings.local.json 里只为这个项目启用,仍由 Claude Code 安装。",
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把这些子代理作为项目自己的给项目里的 Agent:magpie 写进它的 .claude/agents 等文件夹,并让它们不进 git。",
"{name} added — pick the subagents it gets": "已添加 {name},选择它要用的子代理",
@@ -1946,6 +1952,12 @@ magpie.strings({
"Pick the plugins it gets": "選擇它要用的外掛",
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、伺服器和子代理放在專案自己的那些位置,hooks 寫進 .claude/settings.local.json 和 .codex/hooks.json。那裡不是 magpie 寫的檔案、你改過的條目,都保持原樣。",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的專案裡執行專案的 hooks,並且要先在 /hooks 中審閱。",
"Project hooks": "專案 Hooks",
"No hooks yet": "還沒有 Hook",
"Hide its hooks": "收起它的 Hook",
"Pick the hooks it gets": "選擇它用的 Hook",
"Give a project's agents some of these hooks as the project's own: magpie writes each into the project's .claude/settings.local.json or .codex/hooks.json, beside what's already there.": "把這些 Hook 作為專案自己的交給專案的 Agent:magpie 會把每個寫進專案的 .claude/settings.local.json 或 .codex/hooks.json,原有內容保持不動。",
"Written into the project's own hooks file for each agent, one entry per hook; a file magpie makes is kept out of git, its .gitignore untouched. An entry there that isn't magpie's is left as it is.": "寫進專案裡每個 Agent 自己的 hooks 檔案,一個 Hook 一條;magpie 新建的檔案不會進 git,.gitignore 不動。檔案裡不是 magpie 寫的項目保持原樣。",
"The plugins above are Claude Code's own, turned on for this project in .claude/settings.local.json. They stay installed through Claude Code.": "上面的外掛是 Claude Code 自帶的,在 .claude/settings.local.json 裡只為這個專案啟用,仍由 Claude Code 安裝。",
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把這些子代理作為專案自己的給專案裡的 Agent:magpie 寫進它的 .claude/agents 等資料夾,並讓它們不進 git。",
"{name} added — pick the subagents it gets": "已新增 {name},選擇它要用的子代理",
@@ -3086,6 +3098,12 @@ magpie.strings({
"Pick the plugins it gets": "渡すプラグインを選ぶ",
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "スキル、サーバー、サブエージェントはプロジェクト自身のものと同じ場所に、フックは .claude/settings.local.json と .codex/hooks.json に書き込まれます。magpie のものではないファイルや、あなたが変更した項目はそのまま残ります。",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex は信頼したプロジェクトでのみ、/hooks で確認した後にプロジェクトのフックを実行します。",
"Project hooks": "プロジェクトのフック",
"No hooks yet": "フックはまだありません",
"Hide its hooks": "フックを閉じる",
"Pick the hooks it gets": "渡すフックを選ぶ",
"Give a project's agents some of these hooks as the project's own: magpie writes each into the project's .claude/settings.local.json or .codex/hooks.json, beside what's already there.": "これらのフックをプロジェクト自身のものとしてエージェントに渡します。magpie は各フックをプロジェクトの .claude/settings.local.json または .codex/hooks.json に、既にある内容はそのままに書き込みます。",
"Written into the project's own hooks file for each agent, one entry per hook; a file magpie makes is kept out of git, its .gitignore untouched. An entry there that isn't magpie's is left as it is.": "各エージェントのプロジェクトの hooks ファイルにフックごとに 1 件書き込みます。magpie が作ったファイルは git の対象外になり、.gitignore には触れません。magpie が書いたものでない項目はそのまま残ります。",
"The plugins above are Claude Code's own, turned on for this project in .claude/settings.local.json. They stay installed through Claude Code.": "上のプラグインは Claude Code 自身のもので、このプロジェクトに限り .claude/settings.local.json で有効にします。インストールは引き続き Claude Code が行います。",
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "これらのサブエージェントをプロジェクト専用として渡します。magpie が .claude/agents などに書き込み、git には入れません。",
"{name} added — pick the subagents it gets": "{name} を追加しました。渡すサブエージェントを選んでください",
@@ -4231,6 +4249,12 @@ magpie.strings({
"Pick the plugins it gets": "Wähle die Plugins, die es bekommt",
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "Skills, Server und Subagenten kommen dorthin, wo die eigenen des Projekts liegen, Hooks in .claude/settings.local.json und .codex/hooks.json. Eine Datei dort, die nicht von magpie ist, oder ein Eintrag, den du geändert hast, bleibt, wie er ist.",
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex führt die Hooks eines Projekts nur in einem Projekt aus, dem du vertraust, und erst, nachdem du sie in /hooks geprüft hast.",
"Project hooks": "Projekt-Hooks",
"No hooks yet": "Noch keine Hooks",
"Hide its hooks": "Hooks ausblenden",
"Pick the hooks it gets": "Hooks auswählen",
"Give a project's agents some of these hooks as the project's own: magpie writes each into the project's .claude/settings.local.json or .codex/hooks.json, beside what's already there.": "Gib den Agenten eines Projekts einige dieser Hooks als projekteigene: magpie schreibt jeden in die .claude/settings.local.json oder .codex/hooks.json des Projekts, neben das, was dort schon steht.",
"Written into the project's own hooks file for each agent, one entry per hook; a file magpie makes is kept out of git, its .gitignore untouched. An entry there that isn't magpie's is left as it is.": "In die projekteigene Hooks-Datei jedes Agenten geschrieben, ein Eintrag pro Hook; eine von magpie angelegte Datei bleibt aus git heraus, die .gitignore unberührt. Ein Eintrag dort, der nicht von magpie stammt, bleibt wie er ist.",
"The plugins above are Claude Code's own, turned on for this project in .claude/settings.local.json. They stay installed through Claude Code.": "Die Plugins darüber sind die von Claude Code selbst und gelten nur für dieses Projekt, aktiviert in .claude/settings.local.json. Installiert bleiben sie über Claude Code.",
"Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "Gib den Agenten eines Projekts einige dieser Subagenten als eigene: magpie schreibt sie in dessen .claude/agents und Ähnliches und hält sie aus git heraus.",
"{name} added — pick the subagents it gets": "{name} hinzugefügt – wähle die Subagenten dafür",
+3
View File
@@ -952,6 +952,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.ProjectServer(in.Dir, in.Name, in.Agents)
case "projects/plugin":
res, err = library.ProjectPlugin(in.Dir, in.Name, in.Agents)
case "projects/hooks":
// some library hooks in this project, for these agents
res, err = library.ProjectHooks(in.Dir, oneOrMore(in.Name, in.Names), in.Agents)
case "projects/claude-plugin":
// a plugin Claude Code has installed, on for this project alone
// (agents ["claude"]) or taken out of its settings ([])
+132
View File
@@ -0,0 +1,132 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// (#7253, jinpwng on X) A project's Hooks tab lists the library's hooks, each
// with chips for the agents that read a project's hooks file, and a chip posts to
// projects/hooks; no chip left takes it out. In English and Chinese.
// 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/emo";
const DIR = HOME + "/code/app";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, ...more });
const plugin = (name, more) => ({ name, version: "1.0.0", description: "", agents: [], skills: [], mcp: [], hooks: [], subagents: [], ...more });
const lib = (given) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [
agent("claude", "Claude Code", { projectSkills: ".claude/skills", projectMCP: ".mcp.json", projectSubagents: ".claude/agents", projectHooks: ".claude/settings.local.json" }),
agent("codex", "Codex", { projectMCP: ".codex/config.toml", projectSubagents: ".codex/agents", projectHooks: ".codex/hooks.json" }),
agent("pi", "Pi", { projectSkills: ".agents/skills", projectMCP: ".pi/mcp.json" }),
agent("goose", "Goose"),
],
instructions: { agents: [] }, servers: [], subagents: [], skills: [], foundServers: [], foundSkills: [],
hooks: [{ name: "bark", event: "turn-end", command: "say bark", agents: [] }], hookAgents: [{ id: "claude", file: `${HOME}/.claude/settings.json`, events: ["Stop"] }, { id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["Stop"] }], plugins: [], claudeInstalled: [{ id: "fmt@acme", on: false }, { id: "lint@acme", on: true }],
projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: {}, plugins: {}, hooks: given, wrote: {} }],
});
function server(lang, posts) {
let given = {};
return async (route) => {
const req = route.request(), url = new URL(req.url());
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 route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib(given) });
if (url.pathname === "/api/library/projects/hooks") {
const b = req.postDataJSON();
posts.push(b);
if (posts.hold) await posts.hold;
given = { ...given, [b.name]: b.agents };
if (!b.agents.length) delete given[b.name];
return route.fulfill({ json: { ...lib(given), result: { changed: [], problems: [] } } });
}
if (url.pathname === "/api/library/native") return route.fulfill({ json: [] });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const scrolled = (page) => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop || e.scrollLeft).map((e) => `${e.className}:${e.scrollTop},${e.scrollLeft}`)].join(" "));
// a click where the element is, as the reader's: Playwright's own click
// first scrolls it into view
const press = async (page, loc) => {
const b = await loc.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
// a chip: the chips fan out under the pointer first, as a reader's hand
// does, and the chip is pressed where it is then
// (a render after the last write may replace it under the pointer, so it
// is found again until it stays)
const box = async (loc) => {
for (;;) {
await loc.waitFor({ state: "visible" });
const b = await loc.boundingBox();
if (b) return b;
}
};
const chip = async (page, loc) => {
const a = await box(loc);
await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
await page.waitForTimeout(350);
const b = await box(loc);
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
const words = {
en: { codex: "Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.", one: "bark is in app for Claude Code", two: "bark is in app for Claude Code, Codex", out: "bark is out of app" },
zh: { codex: "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。", one: "bark 已在 app 中对 Claude Code 开启", two: "bark 已在 app 中对 Claude Code, Codex 开启", out: "bark 已从 app 中移除" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a project turns on a plugin Claude Code has installed", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => {
if (errors.length) console.log(errors);
await browser.close();
});
for (const lang of ["en", "zh"]) {
await t.test(lang, async () => {
const w = words[lang], posts = [];
const ctx = await browser.newContext({ viewport: { width: 860, height: 700 } });
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, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const card = page.locator("#view-library .lib-project");
await card.waitFor();
await press(page, card.locator(".lib-projhead"));
const row = card.locator(".lib-projhook").filter({ hasText: "bark" });
await row.waitFor();
assert.deepEqual(await row.locator(".lib-ag").evaluateAll((cs) => cs.map((c) => c.dataset.agent)), ["claude", "codex"], "Pi and Goose read no project hooks file");
assert.equal((await card.locator(".lib-projhooks-codex").textContent()).trim(), w.codex);
const on = (n) => page.waitForFunction((k) => document.querySelectorAll("#view-library .lib-projhook .lib-ag.on").length === k, n);
const said = (m) => page.waitForFunction((x) => document.querySelector("#status").textContent.trim() === x, m);
await chip(page, row.locator('.lib-ag[data-agent="claude"]'));
await on(1); await said(w.one);
await chip(page, row.locator('.lib-ag[data-agent="codex"]'));
await on(2); await said(w.two);
await chip(page, row.locator('.lib-ag[data-agent="claude"]'));
await on(1);
await chip(page, row.locator('.lib-ag[data-agent="codex"]'));
await on(0); await said(w.out);
assert.deepEqual(posts.map((b) => [b.dir, b.name, b.agents]), [[DIR, "bark", ["claude"]], [DIR, "bark", ["claude", "codex"]], [DIR, "bark", ["codex"]], [DIR, "bark", []]]);
await ctx.close();
});
}
});
}
+9
View File
@@ -1187,6 +1187,14 @@ func SaveHook(old string, h Hook) (*Result, error) {
return fmt.Errorf("no hook called %s", old)
}
l.Hooks = slices.Delete(l.Hooks, i, i+1)
if old != h.Name {
for _, p := range l.Projects {
if a, ok := p.Hooks[old]; ok {
delete(p.Hooks, old)
p.Hooks[h.Name] = a
}
}
}
}
h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(h.Agents))))
l.Hooks = append(l.Hooks, &h)
@@ -1277,6 +1285,7 @@ func RemoveHooks(names []string) (*Result, error) {
return errors.New(failed[0].Error)
}
l.Hooks = slices.DeleteFunc(l.Hooks, func(h *Hook) bool { return slices.Contains(names, h.Name) })
l.dropProjectHooks(names)
return nil
})
if res != nil {
+65
View File
@@ -3,6 +3,7 @@ package library
import (
"errors"
"fmt"
"maps"
"path/filepath"
"slices"
"sort"
@@ -107,6 +108,17 @@ func (l *Library) withPlugins(p *Project) (skills, servers, subagents map[string
// projectHooks are, by agent, the hooks the project's plugins give it.
func (l *Library) projectHooks(p *Project) map[string][]*Hook {
out := map[string][]*Hook{}
for _, name := range slices.Sorted(maps.Keys(p.Hooks)) {
h := l.hook(name)
if h == nil {
continue
}
for _, a := range p.Hooks[name] {
if ProjectHooksFile(a) != "" && hookTakes(h, a) && !slices.Contains(out[a], h) {
out[a] = append(out[a], h)
}
}
}
for _, name := range slices.Sorted(func(yield func(string) bool) {
for k := range p.Plugins {
if !yield(k) {
@@ -250,6 +262,59 @@ func ProjectPlugin(dir, name string, agents []string) (*Result, error) {
})
}
// ProjectHooks sets which agents get each of some library hooks in a
// project, one at a time, not as part of a plugin (#7253); none takes them
// out, and with them only the entries magpie wrote.
func ProjectHooks(dir string, names, agents []string) (*Result, error) {
return change(func(l *Library) error {
p := l.project(dir)
if p == nil {
return fmt.Errorf("no project %s", dir)
}
if len(names) == 0 {
return errors.New("no hooks given")
}
for _, n := range names {
if l.hook(n) == nil {
return fmt.Errorf("no hook called %s", n)
}
}
var ids []string
for _, id := range agents {
if ProjectHooksFile(id) == "" {
return fmt.Errorf("magpie knows of no file %s reads a project's hooks from", id)
}
ids = set(ids, id, true)
}
for _, n := range names {
if len(ids) == 0 {
delete(p.Hooks, n)
continue
}
if p.Hooks == nil {
p.Hooks = map[string][]string{}
}
p.Hooks[n] = slices.Clone(ids)
}
if len(p.Hooks) == 0 {
p.Hooks = nil
}
return nil
})
}
// dropProjectHooks takes hooks leaving the library out of every project.
func (l *Library) dropProjectHooks(names []string) {
for _, p := range l.Projects {
for _, n := range names {
delete(p.Hooks, n)
}
if len(p.Hooks) == 0 {
p.Hooks = nil
}
}
}
// dropProjectPlugin takes a plugin out of every project, and their
// worktrees: it is leaving the library.
func (l *Library) dropProjectPlugin(name string) {
+53
View File
@@ -205,3 +205,56 @@ func loadT(t *testing.T) *Library {
}
return l
}
// One hook given to a project on its own (#7253): written into each
// chosen agent's project hooks file, beside what the user has there, and
// taken out again with only magpie's entry; a hook leaving the library
// leaves its projects, and a worktree follows.
func TestProjectOneHookPerAgent(t *testing.T) {
_, a, b := pluginProjects(t)
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "say bark", Agents: []string{}}))
ok(t)(SaveHook("", Hook{Name: "tick", Event: "turn-end", Command: "say tick", Agents: []string{}}))
f := filepath.Join(a, ".claude/settings.local.json")
write(t, f, `{
// mine
"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo mine"}]}]}
}
`)
if _, err := ProjectHooks(a, []string{"bark"}, []string{"gemini"}); err == nil {
t.Error("an agent with no project hooks file was taken")
}
if _, err := ProjectHooks(a, []string{"nope"}, []string{"claude"}); err == nil {
t.Error("a hook the library hasn't was taken")
}
res := ok(t)(ProjectHooks(a, []string{"bark"}, []string{"claude", "codex"}))
ok(t)(ProjectHooks(a, []string{"tick"}, []string{"codex"}))
if len(res.Problems) > 0 {
t.Fatalf("problems: %+v", res.Problems)
}
claude, codex := read(t, f), read(t, filepath.Join(a, ".codex/hooks.json"))
if !strings.Contains(claude, "say bark") || !strings.Contains(claude, "echo mine") || !strings.Contains(claude, "// mine") || strings.Contains(claude, "say tick") {
t.Errorf("claude:\n%s", claude)
}
if !strings.Contains(codex, "say bark") || !strings.Contains(codex, "say tick") {
t.Errorf("codex:\n%s", codex)
}
gone(t, filepath.Join(b, ".codex"))
if v := View0(t); len(v.Projects[0].Hooks["bark"]) != 2 {
t.Errorf("view: %+v", v.Projects[0].Hooks)
}
ok(t)(ProjectHooks(a, []string{"bark"}, []string{"claude", "codex"})) // again: once
if n := strings.Count(read(t, f), "say bark"); n != 1 {
t.Errorf("%d entries:\n%s", n, read(t, f))
}
ok(t)(ProjectHooks(a, []string{"bark"}, nil))
if got := read(t, f); strings.Contains(got, "say bark") || !strings.Contains(got, "echo mine") || !strings.Contains(got, "// mine") {
t.Errorf("after withdrawing:\n%s", got)
}
// a hook leaving the library leaves the project
ok(t)(RemoveHooks([]string{"tick"}))
gone(t, filepath.Join(a, ".codex/hooks.json"))
if v := View0(t); len(v.Projects[0].Hooks) != 0 {
t.Errorf("view after removal: %+v", v.Projects[0].Hooks)
}
}
+3 -3
View File
@@ -461,7 +461,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
t = &Project{Dir: d}
}
t.Copy, t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = p.Copy, p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins = p.Instr, p.InstrAgents, p.Plugins, p.ClaudePlugins
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins, t.Hooks = p.Instr, p.InstrAgents, p.Plugins, p.ClaudePlugins, p.Hooks
l.syncFolder(t, res, hubs)
trees = append(trees, t)
}
@@ -475,7 +475,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
// no longer one of the repository's worktrees, or no longer the
// project's: what magpie put there comes out
t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = nil, nil, nil, nil, nil
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins = "", nil, nil, nil
t.Instr, t.InstrAgents, t.Plugins, t.ClaudePlugins, t.Hooks = "", nil, nil, nil, nil
l.syncFolder(t, res, nil)
if t.holds() {
trees = append(trees, t)
@@ -533,7 +533,7 @@ func (l *Library) treesChanged() bool {
}
}
}
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents)+len(p.Plugins) == 0 && len(p.Trees) == 0 {
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents)+len(p.Plugins)+len(p.Hooks)+len(p.ClaudePlugins) == 0 && len(p.Trees) == 0 {
continue
}
dirs := p.treeDirs()
+14 -3
View File
@@ -65,6 +65,10 @@ type Project struct {
// (project_subagents.go)
Subagents map[string][]string `json:"subagents,omitempty"`
AgentFiles []SubagentFile `json:"agentFiles,omitempty"`
// Hooks are the library's hooks the project has on their own, and for
// which agents, written into each agent's project hooks file like
// those of its plugins (HookRecs; project_plugins.go)
Hooks map[string][]string `json:"hooks,omitempty"`
// Instr is the project's own instructions, InstrAgents the agents
// whose project file they're written into, InstrFiles the files
// magpie wrote them in (project_instructions.go)
@@ -157,7 +161,7 @@ func (l *Library) syncProjects(res *Result) {
func (l *Library) syncProject(p *Project, res *Result) {
if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() {
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.Plugins) > 0 || len(p.ClaudePlugins) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() {
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.Plugins) > 0 || len(p.Hooks) > 0 || len(p.ClaudePlugins) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() {
res.Problems = append(res.Problems, Problem{Agent: p.Dir, What: "project:", Error: "the folder is gone"})
}
return
@@ -552,7 +556,7 @@ func RemoveProject(dir string, keep bool) (*Result, error) {
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
return nil
}
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents, p.Plugins, p.ClaudePlugins = nil, nil, nil, nil, nil, nil, nil, nil
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents, p.Plugins, p.ClaudePlugins, p.Hooks = nil, nil, nil, nil, nil, nil, nil, nil, nil
l.syncProject(p, &Result{})
if !p.holds() && p.Claude == nil && !slices.ContainsFunc(p.Trees, (*Project).holds) {
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
@@ -652,7 +656,10 @@ type ProjectView struct {
// ClaudePlugins are the plugins Claude Code has installed that the
// project turns on for itself
ClaudePlugins []string `json:"claudePlugins"`
Missing bool `json:"missing,omitempty"` // the folder is gone
// Hooks are the library's hooks the project has on their own, for
// the agents given
Hooks map[string][]string `json:"hooks"`
Missing bool `json:"missing,omitempty"` // the folder is gone
// Problems are, by skill ("" for the project's own), what couldn't be done
Problems map[string]string `json:"problems,omitempty"`
}
@@ -695,6 +702,10 @@ func projectViews(l *Library, problems []Problem) []ProjectView {
v.Plugins[k] = append([]string{}, a...)
}
v.ClaudePlugins = append([]string{}, p.ClaudePlugins...)
v.Hooks = map[string][]string{}
for k, a := range p.Hooks {
v.Hooks[k] = append([]string{}, a...)
}
for _, t := range p.Trees {
v.Trees = append(v.Trees, t.Dir)
}