/** * worktree 接线层(index.ts)的单测:**不 mock pi**,用 pi 自己的扩展加载器 * (`discoverAndLoadExtensions`)真加载 `index.ts`,再用 `bindCommandContext` 注入 * 命令上下文(`switchSession` / `waitForIdle` 等),从外面驱动注册的命令、工具与钩子。 * * 为什么不 mock:`index.ts` 会 import pi 的 typebox 与真实 SessionManager,mock 掉就测不到 * 「命令真的建出了 worktree」这类行为。真加载器也让 `PI_WORKTREE` 这类加载期开关有真实语义。 * * 切换本身(cwd 真的变过去)由 worktree.e2e.test.ts 用真 pi 验证;这里注入的 * `switchSession` 只记录入参并执行 `withSession`,不重建 runtime。 * * 找不到本机 pi 库入口就整体 skip(不假装通过)。 * * node --test clients/pi/extensions/worktree/index.test.ts */ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath, pathToFileURL } from "node:url"; import { clearPending, getPending, setPending } from "./state.ts"; const EXTENSION_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), "index.ts"); // ============================================================================= // 找到本机 pi 的库入口(与 background-tasks/index.test.ts 同源) // ============================================================================= async function findPiLibraryEntry(): Promise { const candidates: string[] = []; if (process.env.PI_TEST_PI_ENTRY) candidates.push(process.env.PI_TEST_PI_ENTRY); for (const dir of (process.env.PATH ?? "").split(path.delimiter)) { if (!dir) continue; const shimPath = path.join(dir, "pi"); try { const real = fs.realpathSync(shimPath); if (real !== shimPath) candidates.push(path.join(path.dirname(real), "index.js")); } catch { // 不是符号链接 / 不存在 } try { const match = /^# cmd-shim-target=(.+)$/m.exec(fs.readFileSync(shimPath, "utf8")); if (match?.[1]) candidates.push(path.join(path.dirname(match[1].trim()), "index.js")); } catch { // 读不到这个 shim } } const packageDir = path.join(os.homedir(), ".pi/agent/npm/node_modules/@earendil-works/pi-coding-agent"); candidates.push(path.join(packageDir, "dist/bundle/index.js"), path.join(packageDir, "dist/index.js")); for (const candidate of candidates) { if (!fs.existsSync(candidate)) continue; try { await import(pathToFileURL(candidate).href); return candidate; } catch { // 空壳副本:换下一个 } } return undefined; } const piEntry = await findPiLibraryEntry(); const skip = piEntry === undefined ? "找不到本机 pi 的库入口(装过 pi 才有)" : false; // ============================================================================= // fixture // ============================================================================= const cleanup: Array<() => void> = []; test.after(() => { for (const fn of cleanup) fn(); clearPending(); }); function makeRepo(): { repo: string; worktrees: () => string[] } { const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-idx-"))); const repo = path.join(root, "repo"); fs.mkdirSync(repo); const git = (...args: string[]) => { const r = spawnSync("git", args, { cwd: repo, encoding: "utf8" }); assert.equal(r.status, 0, `git ${args.join(" ")}: ${r.stderr}`); }; git("init", "-q"); git("config", "user.email", "t@example.com"); git("config", "user.name", "t"); git("config", "commit.gpgsign", "false"); fs.writeFileSync(path.join(repo, "a.txt"), "a\n"); git("add", "."); git("commit", "-qm", "init"); cleanup.push(() => fs.rmSync(root, { recursive: true, force: true })); return { repo, worktrees: () => spawnSync("git", ["worktree", "list", "--porcelain"], { cwd: repo, encoding: "utf8" }) .stdout.split("\n") .filter((l) => l.startsWith("worktree ")) .map((l) => l.slice("worktree ".length).trim()), }; } type Fn = (...args: any[]) => any; interface Harness { /** 载入的扩展对象(handlers / tools / commands)。 */ extension: any; notifies: Array<{ text: string; level?: string }>; statuses: Map; sent: Array<{ message: any; options?: any }>; switches: Array<{ sessionPath: string; options: any }>; /** withSession 的新 ctx 收到过的用户消息(续句)。 */ continuation: string[]; /** 命令上下文;改 `cwd` 就相当于"会话现在在别的目录"。 */ ctx: any; command(args: string): Promise; tool(name: string, params: unknown): Promise<{ text: string; details: any; terminate?: boolean }>; settled(): Promise; sessionStart(): Promise; setConfirm(value: boolean): void; setSessionFile(value: string | null): void; } /** * 载入扩展并接好命令上下文。 * * 开关(`PI_WORKTREE` / `PI_WORKTREE_CONTINUE`)由调用方在**调用本函数之前**设置: * 前者是加载期读的,后者是执行期读的。 */ async function loadHarness(o: { cwd: string; sessionFile?: string | null }): Promise { const pi = (await import(pathToFileURL(piEntry!).href)) as any; const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-load-")); const agentDir = path.join(root, "agent"); fs.mkdirSync(agentDir, { recursive: true }); cleanup.push(() => fs.rmSync(root, { recursive: true, force: true })); const loaded = await pi.discoverAndLoadExtensions([EXTENSION_PATH], o.cwd, agentDir, pi.createEventBus()); assert.deepEqual(loaded.errors, [], "pi 的扩展加载器不应该报错"); const extension = loaded.extensions[0]; assert.ok(extension, "应该加载到 worktree 扩展"); let confirmAnswer = true; let sessionFile: string | null = o.sessionFile === undefined ? "/tmp/fake-source.jsonl" : o.sessionFile; const notifies: Harness["notifies"] = []; const statuses = new Map(); const sent: Harness["sent"] = []; const switches: Harness["switches"] = []; const continuation: string[] = []; // pi 的 runtime 上 sendUserMessage 在裸加载时是抛错桩;这里换成记录器 loaded.runtime.sendUserMessage = (content: any, options: any) => void sent.push({ message: content, options }); const ctx: any = { mode: "tui", hasUI: true, cwd: o.cwd, isIdle: () => true, ui: { confirm: async () => confirmAnswer, notify: (text: string, level?: string) => notifies.push({ text, level }), setStatus: (key: string, text: string | undefined) => { if (text === undefined) statuses.delete(key); else statuses.set(key, text); }, }, sessionManager: { getSessionFile: () => (sessionFile === null ? undefined : sessionFile), getCwd: () => ctx.cwd, getSessionId: () => "test-session", getBranch: () => [], buildContextEntries: () => [], }, // 命令用的 switchSession:记录入参并真的执行 withSession(后者拿到新 ctx) switchSession: async (sessionPath: string, options: any) => { switches.push({ sessionPath, options }); if (options?.withSession) { const next = { ...ctx, cwd: options.cwdOverride ?? ctx.cwd, sendUserMessage: async (content: string) => void continuation.push(content), }; await options.withSession(next); } return { cancelled: false }; }, }; extension.runner?.setUIContext?.(ctx.ui, "tui"); const harness: Harness = { extension, notifies, statuses, sent, switches, continuation, ctx, setConfirm: (value) => { confirmAnswer = value; }, setSessionFile: (value) => { sessionFile = value; }, command: async (args) => { const command = extension.commands.get("worktree"); assert.ok(command, "必须注册 /worktree 命令"); // 命令直接拿这个 ctx;真实 runner 的 createCommandContext() 只是给它加 stale 守卫, // 我们已在 ctx 上挂好了 switchSession await command.handler(args, ctx); }, tool: async (name, params) => { const definition = extension.tools.get(name)?.definition; assert.ok(definition, `必须注册 ${name} 工具`); const result = await definition.execute("call-1", params, undefined, undefined, ctx); const text = (result.content ?? []).map((part: any) => part.text ?? "").join("\n"); return { text, details: result.details, terminate: result.terminate }; }, settled: async () => { for (const handler of extension.handlers.get("agent_settled") ?? []) { await handler({ type: "agent_settled", aborted: false }, ctx); } }, sessionStart: async () => { for (const handler of extension.handlers.get("session_start") ?? []) { await handler({ type: "session_start", reason: "startup" }, ctx); } }, }; return harness; } /** 设置/还原一个环境变量,返回还原函数。 */ function withEnv(key: string, value: string | undefined): () => void { const previous = process.env[key]; if (value === undefined) delete process.env[key]; else process.env[key] = value; return () => { if (previous === undefined) delete process.env[key]; else process.env[key] = previous; }; } // ============================================================================= // 测试 // ============================================================================= test("注册命令 worktree、工具 worktree、以及 agent_settled / session_start 处理器", { skip }, async () => { const { repo } = makeRepo(); const h = await loadHarness({ cwd: repo }); assert.ok(h.extension.commands.has("worktree")); assert.ok(h.extension.tools.has("worktree")); assert.ok((h.extension.handlers.get("agent_settled") ?? []).length >= 1); assert.ok((h.extension.handlers.get("session_start") ?? []).length >= 1); }); test("PI_WORKTREE=off 时什么都不注册", { skip }, async () => { const restore = withEnv("PI_WORKTREE", "off"); try { const { repo } = makeRepo(); const pi = (await import(pathToFileURL(piEntry!).href)) as any; const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-off-")); cleanup.push(() => fs.rmSync(root, { recursive: true, force: true })); fs.mkdirSync(path.join(root, "agent"), { recursive: true }); const loaded = await pi.discoverAndLoadExtensions( [EXTENSION_PATH], repo, path.join(root, "agent"), pi.createEventBus(), ); assert.deepEqual(loaded.errors, []); const extension = loaded.extensions[0]; assert.equal(extension.commands.size, 0); assert.equal(extension.tools.size, 0); assert.equal(extension.handlers.size, 0); } finally { restore(); } }); test("/worktree new <名>:不问 confirm,直接切;withSession 的 cwd 是目标路径", { skip }, async () => { const { repo } = makeRepo(); const h = await loadHarness({ cwd: repo }); h.setConfirm(false); // 命令若问了,就会走"拒绝"分支 await h.command("new feat/one"); const target = path.join(repo, ".worktrees", "feat", "one"); assert.equal(h.switches.length, 1, "命令必须直接切(不问 confirm)"); assert.equal(h.switches[0].options.cwdOverride, target); assert.ok(fs.existsSync(target), "目录要建出来"); assert.ok(fs.existsSync(path.join(repo, ".worktrees", "feat", "one", "a.txt")), "worktree 里要有仓库内容"); const branch = spawnSync("git", ["branch", "--show-current"], { cwd: target, encoding: "utf8" }).stdout.trim(); assert.equal(branch, "feat/one"); }); test("模型工具:confirm 拒绝则不建不切;同意则建树 + setPending,且本轮不切(但本轮会被它结束)", { skip }, async () => { const { repo, worktrees } = makeRepo(); clearPending(); const h = await loadHarness({ cwd: repo }); h.setConfirm(false); const denied = await h.tool("worktree", { name: "declined-one" }); assert.equal(h.switches.length, 0); assert.match(denied.text, /declined/i); assert.equal(denied.terminate, undefined, "拒绝不能结束本轮"); assert.equal(getPending(), undefined); assert.equal(fs.existsSync(path.join(repo, ".worktrees", "declined-one")), false, "拒绝时不能建目录"); h.setConfirm(true); const accepted = await h.tool("worktree", { name: "ok-one" }); assert.equal(h.switches.length, 0, "工具执行期不能替换 runtime"); assert.ok(worktrees().some((p) => p.endsWith(".worktrees/ok-one")), "目录要建出来"); assert.equal(getPending()?.branch, "ok-one"); assert.match(accepted.text, /ok-one/); // 承重断言:没有 terminate,pi 会继续跑这一轮,切换被拖到整段活干完(2026-10-30 真实事故) assert.equal(accepted.terminate, true, "工具结果必须带 terminate,否则切换会被拖到本轮结束"); clearPending(); }); test("模型工具:create:false 且树不存在 → 报错、不建目录、不落 pending、不 terminate", { skip }, async () => { const { repo } = makeRepo(); clearPending(); const h = await loadHarness({ cwd: repo }); h.setConfirm(true); const missing = await h.tool("worktree", { name: "never-created", create: false }); assert.match(missing.text, /没有名为/); assert.equal(missing.terminate, undefined, "失败不能结束本轮"); assert.equal(getPending(), undefined); assert.equal(fs.existsSync(path.join(repo, ".worktrees", "never-created")), false, "create:false 绝不能偷偷建"); }); test("模型工具:create:false 且树已存在 → 复用同一目录,不重新创建", { skip }, async () => { const { repo } = makeRepo(); clearPending(); const setup = await loadHarness({ cwd: repo }); await setup.command("new reused-one"); const target = path.join(repo, ".worktrees", "reused-one"); assert.ok(fs.existsSync(target)); // 在树里留一个文件:若被重新创建(git worktree add 到已存在的目录)它就会消失或报错 fs.writeFileSync(path.join(target, "marker.txt"), "keep\n"); const h = await loadHarness({ cwd: repo }); h.setConfirm(true); const reused = await h.tool("worktree", { name: "reused-one", create: false }); assert.equal(reused.details?.path, target, "要复用已有目录"); assert.equal(reused.terminate, true); assert.equal(fs.readFileSync(path.join(target, "marker.txt"), "utf8"), "keep\n", "不能把已有树重建掉"); assert.equal(getPending()?.path, target); clearPending(); }); test("agent_settled:有待办才派发内部命令(只派发一次),真正清空发生在 __enter 命令", { skip }, async () => { const { repo } = makeRepo(); clearPending(); const h = await loadHarness({ cwd: repo }); h.sent.length = 0; await h.settled(); assert.equal(h.sent.length, 0, "没待办不该派发"); h.setConfirm(true); await h.tool("worktree", { name: "settled-one" }); assert.ok(getPending()); h.sent.length = 0; await h.settled(); assert.equal(h.sent.length, 1, "待办存在时要派发"); assert.match(String(h.sent[0].message), /^\/worktree/); assert.equal(h.sent[0].options?.expandPromptTemplates, true); assert.ok(getPending()?.dispatchedAt, "派发后要打标记"); // 同一条待办不再重复派发(settled 每次运行结束都会触发) h.sent.length = 0; await h.settled(); assert.equal(h.sent.length, 0, "已派发的不再派发"); // 真正的清空发生在命令里:它拿着待办完成切换 await h.command("__enter"); assert.equal(h.switches.length, 1, "__enter 要真的切过去"); assert.match(h.switches[0].options.cwdOverride, /\.worktrees\/settled-one$/); assert.equal(getPending(), undefined, "命令消费后待办要清掉"); }); test("续句:默认在 withSession 里发一条,PI_WORKTREE_CONTINUE=off 时不发", { skip }, async () => { const { repo } = makeRepo(); const on = await loadHarness({ cwd: repo }); await on.command("new cont-on"); assert.equal(on.continuation.length, 1, "默认要发续句"); assert.match(on.continuation[0], /\.worktrees\/cont-on/); assert.match(on.continuation[0], /cont-on/); const restore = withEnv("PI_WORKTREE_CONTINUE", "off"); try { const off = await loadHarness({ cwd: repo }); await off.command("new cont-off"); assert.equal(off.switches.length, 1); assert.equal(off.continuation.length, 0, "关掉之后一个字都不发"); } finally { restore(); } }); test("空会话(没有 session 文件)也必须切过去", { skip }, async () => { const { repo } = makeRepo(); const h = await loadHarness({ cwd: repo, sessionFile: null }); await h.command("new empty-session"); const target = path.join(repo, ".worktrees", "empty-session"); assert.equal(h.switches.length, 1, "空会话不能卡在 forkFrom 的报错上"); assert.equal(h.switches[0].options.cwdOverride, target); assert.ok(fs.existsSync(target)); }); test("/worktree(无参数)报状态;非 git 目录里 new 失败且不切", { skip }, async () => { const { repo } = makeRepo(); const h = await loadHarness({ cwd: repo }); await h.command(""); assert.ok(h.notifies.length >= 1, "要打印状态"); const nogit = fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-nogit-idx-")); cleanup.push(() => fs.rmSync(nogit, { recursive: true, force: true })); const bad = await loadHarness({ cwd: nogit }); await bad.command("new whatever"); assert.equal(bad.switches.length, 0, "非 git 目录不能切"); assert.equal(bad.notifies.at(-1)?.level, "error"); }); test("/worktree exit 从 linked worktree 切回主仓根", { skip }, async () => { const { repo } = makeRepo(); const setup = await loadHarness({ cwd: repo }); await setup.command("new to-exit"); const wtPath = path.join(repo, ".worktrees", "to-exit"); const h = await loadHarness({ cwd: wtPath }); await h.command("exit"); assert.equal(h.switches.length, 1); assert.equal(h.switches[0].options.cwdOverride, repo, "要切回主仓根"); }); test("/worktree exit 在 worktree 已被删除后仍能切回主仓根", { skip }, async () => { const { repo } = makeRepo(); const setup = await loadHarness({ cwd: repo }); await setup.command("new merged-away"); const wtPath = path.join(repo, ".worktrees", "merged-away"); assert.ok(fs.existsSync(wtPath)); // 模拟真实事故:活干完、合并进主干、树被删,而会话 cwd 还钉在原地 const h = await loadHarness({ cwd: wtPath }); spawnSync("git", ["worktree", "remove", wtPath], { cwd: repo, encoding: "utf8" }); assert.equal(fs.existsSync(wtPath), false, "前置:目录要真的没了"); await h.command("exit"); assert.equal(h.switches.length, 1, "cwd 消失不能把用户困在死目录里"); assert.equal(h.switches[0].options.cwdOverride, repo, "要切回主仓根"); assert.equal(h.notifies.filter((n) => n.level === "error").length, 0, "不该报错"); }); test("/worktree rm:干净树能删,脏树报错并保留", { skip }, async () => { const { repo, worktrees } = makeRepo(); const h = await loadHarness({ cwd: repo }); await h.command("new removable"); const target = path.join(repo, ".worktrees", "removable"); await h.command("rm removable"); assert.equal(fs.existsSync(target), false, "干净树要删掉"); await h.command("new dirty-one"); fs.writeFileSync(path.join(repo, ".worktrees", "dirty-one", "junk.txt"), "x\n"); await h.command("rm dirty-one"); assert.equal(fs.existsSync(path.join(repo, ".worktrees", "dirty-one")), true, "脏树必须保留"); assert.equal(h.notifies.at(-1)?.level, "error"); assert.ok(worktrees().some((p) => p.endsWith(".worktrees/dirty-one"))); }); test("session_start 在 linked worktree 里挂 🌳 status,在主仓里清掉", { skip }, async () => { const { repo } = makeRepo(); const setup = await loadHarness({ cwd: repo }); await setup.command("new status-one"); const wtPath = path.join(repo, ".worktrees", "status-one"); const inWt = await loadHarness({ cwd: wtPath }); await inWt.sessionStart(); assert.match(String(inWt.statuses.get("worktree")), /🌳 status-one/); const inMain = await loadHarness({ cwd: repo }); await inMain.sessionStart(); assert.equal(inMain.statuses.get("worktree"), undefined, "主仓里不该有 🌳 徽标"); }); test("/worktree exit 的续句报出主仓路径与主仓分支(不出现空分支)", { skip }, async () => { const { repo } = makeRepo(); const setup = await loadHarness({ cwd: repo }); await setup.command("new exit-msg"); const wtPath = path.join(repo, ".worktrees", "exit-msg"); const h = await loadHarness({ cwd: wtPath }); await h.command("exit"); assert.equal(h.continuation.length, 1); assert.match(h.continuation[0], new RegExp(repo.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))); assert.match(h.continuation[0], /main/, "主仓分支是 main,续句应当带上"); assert.doesNotMatch(h.continuation[0], /branch \./, "不能留下空分支残句"); }); test("/worktree(无参数)在 cwd 已消失时点明并指路 exit", { skip }, async () => { const { repo } = makeRepo(); const setup = await loadHarness({ cwd: repo }); await setup.command("new status-gone"); const wtPath = path.join(repo, ".worktrees", "status-gone"); const h = await loadHarness({ cwd: wtPath }); spawnSync("git", ["worktree", "remove", wtPath], { cwd: repo, encoding: "utf8" }); assert.equal(fs.existsSync(wtPath), false); await h.command(""); const last = String(h.notifies.at(-1)?.text); assert.match(last, /已不存在/, "要点明 cwd 没了"); assert.match(last, /exit/, "要指路 exit"); }); test("/worktree new 拒绝非法名字(不建目录、不切)", { skip }, async () => { const { repo } = makeRepo(); const h = await loadHarness({ cwd: repo }); await h.command("new ../escape"); assert.equal(h.switches.length, 0); assert.equal(h.notifies.at(-1)?.level, "error"); assert.match(String(h.notifies.at(-1)?.text), /\.\.|非法/); assert.equal(fs.existsSync(path.join(repo, "..", "escape")), false); });