/** * worktree 端到端:**真 pi(RPC 模式)+ 真 git 仓库**,验证 `/worktree new <名>` 之后 * 会话 cwd 真的变成 `/.worktrees/<名>`,而不是靠 `cd` 假装;以及反方向的 * `/worktree exit`(命令)与 `worktree{action:"exit"}`(**模型工具**)真的把 cwd 送回主仓根。 * * 为什么必须用真 pi:这件事的全部意义在于「runtime 整体重建」。假 ctx 只能验证 * `switchSession` 的入参,验证不了新会话的 `ctx.cwd`、内置工具基准目录与 statusline 读 git 的目录。 * 模型工具那条尤其要真跑:它靠 `terminate` + `agent_settled` 派发内部命令,两环都是 pi 自己的行为。 * * 隔离:`PI_CODING_AGENT_DIR` 指向临时目录,`-ne -ns -np --no-themes -nc --no-mcp --offline -na` * 关掉发现与网络;只有 `-e` 显式给的扩展会加载。不碰用户真实的 `~/.pi/agent`。 * 用 `--tools bash,worktree` 而不是 `--no-tools`,因为断言要跑 `pwd` / `git branch`,而模型工具 * 不在白名单里时 pi 会直接回 `Tool worktree not found`(实测)。 * * 找不到本机 pi 就整体 skip(不假装通过)。 * * node --test clients/pi/extensions/worktree/worktree.e2e.test.ts */ import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import http from "node:http"; import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; import { describe, test } from "node:test"; import { fileURLToPath } from "node:url"; const EXT = path.join(path.dirname(fileURLToPath(import.meta.url)), "index.ts"); const skip = spawnSync("pi", ["--version"], { encoding: "utf8" }).status === 0 ? false : "找不到本机 pi(PATH 上没有 pi),端到端整体跳过"; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); interface RunResult { /** 切换后 `pwd` 的输出(realpath 后的形式可能带 /private 前缀)。 */ pwd: string; /** `pwd` 的 realpath(在临时目录还在时算好,否则断言时已 ENOENT)。 */ pwdReal: string; /** 切换后 `git branch --show-current` 的输出。 */ branch: string; /** 主仓 `git status --porcelain`(应当为空:exclude 生效)。 */ mainPorcelain: string; /** 每个 session_start 的 (reason, cwd),cwd 已 realpath。 */ starts: Array<{ reason: string; cwd: string }>; /** stderr 摘要,失败时打印。 */ stderr: string; /** 主仓根的 realpath(断言退出真的回到了这里)。 */ repoReal: string; } async function runScenario(options: { command: string; then?: string; viaModelTool?: boolean }): Promise { const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-e2e-"))); const agentDir = path.join(root, "agent"); const repo = path.join(root, "repo"); fs.mkdirSync(agentDir); 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"); // 探针扩展:把每次 session_start 的 reason 与 cwd 写进文件(模型不会告诉你这些) const probe = path.join(root, "probe.ts"); const probeLog = path.join(root, "probe.log"); fs.writeFileSync( probe, [ 'import { appendFileSync } from "node:fs";', `export default function (pi) {`, ` pi.on("session_start", (event, ctx) => appendFileSync(${JSON.stringify(probeLog)}, event.reason + "\\t" + ctx.cwd + "\\n"));`, `}`, "", ].join("\n"), ); // 模型工具那条要一个假 LLM:它得真的发出 worktree{action:"exit"} 这个工具调用, // 才能验到 terminate → agent_settled → __exit 整条链(那两环都是 pi 自己的行为)。 const llm = options.viaModelTool ? await startFakeWorktreeLlm() : undefined; if (llm) { fs.writeFileSync( path.join(agentDir, "models.json"), JSON.stringify({ providers: { fake: { baseUrl: llm.baseUrl, api: "anthropic-messages", apiKey: "x", models: [{ id: "fake-1", name: "fake-1", reasoning: false, input: ["text"], contextWindow: 100000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, }], }, }, }), ); } // 真 pi 跑 RPC:命令那两条不请求模型;工具那条靠上面的假 LLM(续句一律关掉,见下) const real = spawn( "pi", [ "--mode", "rpc", "-ne", "-ns", "-np", "--no-themes", "-nc", "--no-mcp", "--offline", "-na", // worktree 不在白名单里时 pi 直接回 `Tool worktree not found`(实测),所以必须点名 "--tools", options.viaModelTool ? "bash,worktree" : "bash", ...(llm ? ["--provider", "fake", "--model", "fake-1"] : []), "-e", EXT, "-e", probe, ], { cwd: repo, env: { ...process.env, PI_CODING_AGENT_DIR: agentDir, PI_SKIP_VERSION_CHECK: "1", PI_OFFLINE: "1", // 续句会给模型发一条消息,这里没配 LLM;它的行为由 index.test.ts 覆盖 PI_WORKTREE_CONTINUE: "off", }, stdio: ["pipe", "pipe", "pipe"], }, ); const events: any[] = []; let stderr = ""; let buffer = ""; real.stderr.setEncoding("utf8"); real.stderr.on("data", (d: string) => { stderr += d; }); real.stdout.setEncoding("utf8"); real.stdout.on("data", (d: string) => { buffer += d; for (let i = buffer.indexOf("\n"); i >= 0; i = buffer.indexOf("\n")) { const line = buffer.slice(0, i).replace(/\r$/, ""); buffer = buffer.slice(i + 1); if (!line.trim()) continue; try { events.push(JSON.parse(line)); } catch { // 非 JSON 行直接忽略 } } }); const send = (command: object) => real.stdin.write(`${JSON.stringify(command)}\n`); const until = async (get: () => T | undefined | false, ms: number, label: string): Promise => { const deadline = Date.now() + ms; for (;;) { const value = get(); if (value) return value; if (Date.now() > deadline) throw new Error(`等待超时:${label}\n[pi stderr] ${stderr.slice(0, 800)}`); await sleep(25); } }; const response = (id: string) => events.find((e) => e.type === "response" && e.id === id); try { send({ id: "ready", type: "get_state" }); await until(() => response("ready"), 30_000, "get_state 应答(pi 就绪)"); // 命令要真的建出 worktree 并切过去;RPC 的 prompt 会展开扩展命令。 // 注意:`session_start` 是**扩展事件**,RPC 协议不会把它发到 stdout(只有扩展自己的 // setStatus / notify 会变成 extension_ui_request),所以切换的证据只有两处: // ① 探针扩展写进文件的那一行 ② 切换后 bash 报出的 pwd。 send({ id: "enter", type: "prompt", message: options.command }); const promptResp = await until(() => response("enter"), 40_000, "prompt 应答"); assert.equal(promptResp.data?.disposition, "handled", "扩展命令要真的被执行(而不是当成普通消息)"); await until( () => fs.existsSync(probeLog) && fs.readFileSync(probeLog, "utf8").includes("resume"), 40_000, "探针记到一次 resume 的 session_start", ); await sleep(300); // 第二站(例如 exit):要等第二次 resume 才算切完,否则 pwd 读到的还是上一站。 // viaModelTool 时它是一句普通话,由假 LLM 翻成 worktree{action:"exit"} 工具调用 —— // 这时 disposition 不是 "handled"(它真的起了一轮模型),所以只对命令形态断言它。 if (options.then) { const before = fs.readFileSync(probeLog, "utf8").split("\n").filter((l) => l.startsWith("resume")).length; send({ id: "then", type: "prompt", message: options.then }); const thenResp = await until(() => response("then"), 40_000, "第二条 prompt 应答"); if (!options.viaModelTool) { assert.equal(thenResp.data?.disposition, "handled", "第二条扩展命令也要真的执行"); } await until( () => fs.readFileSync(probeLog, "utf8").split("\n").filter((l) => l.startsWith("resume")).length > before, 40_000, "探针记到第二次 resume 的 session_start", ); await sleep(300); } // 切换之后,让 bash 报出它看到的目录与分支(这是会话 cwd 的真相) send({ id: "probe", type: "bash", command: "pwd; git branch --show-current" }); const bashResp = await until(() => response("probe"), 20_000, "bash 应答"); const output: string = bashResp.data?.output ?? ""; const [pwd, branch] = output.trim().split("\n"); const starts = fs .existsSync(probeLog) ? fs .readFileSync(probeLog, "utf8") .split("\n") .filter(Boolean) .map((line) => { const [reason, cwd] = line.split("\t"); return { reason, cwd: realpathOrSelf(cwd ?? "") }; }) : []; const mainPorcelain = spawnSync("git", ["status", "--porcelain"], { cwd: repo, encoding: "utf8" }).stdout.trim(); return { pwd: pwd ?? "", pwdReal: realpathOrSelf(pwd ?? ""), branch: branch ?? "", mainPorcelain, starts, repoReal: realpathOrSelf(repo), stderr, }; } finally { real.kill("SIGTERM"); if (llm) await llm.close(); fs.rmSync(root, { recursive: true, force: true }); } } describe("worktree 端到端(真 pi RPC + 真 git)", () => { test("/worktree new <名> 之后会话 cwd 与分支都真的变了", { skip, timeout: 90_000 }, async () => { const r = await runScenario({ command: "/worktree new feat/e2e" }); // 断言前先看切换真的发生过(探针记的是 pi 自己报的 cwd,不是我们推的) const switched = r.starts.find((s) => s.reason === "resume"); assert.ok(switched, `要出现一次 resume 的 session_start(实际:${JSON.stringify(r.starts)})`); assert.match(switched!.cwd, /\.worktrees\/feat\/e2e$/); // bash 看到的目录必须与之一致 assert.match(r.pwd, /\.worktrees\/feat\/e2e$/); assert.equal(r.pwdReal, switched!.cwd); // 分支跟着变 assert.equal(r.branch, "feat/e2e"); // exclude 生效:主仓依然干净(否则整棵 worktree 会被算成未跟踪) assert.equal(r.mainPorcelain, ""); }); test("/worktree new → /worktree exit:会话 cwd 真的回到主仓根", { skip, timeout: 120_000 }, async () => { // 这是 2026-11-15 事故的反向验证:只有真 pi 能证明会话 cwd 回来了, // 而 cwd 没回来就删树 = bash 在 spawn 阶段彻底不可用。 const r = await runScenario({ command: "/worktree new feat/e2e-roundtrip", then: "/worktree exit" }); const resumes = r.starts.filter((s) => s.reason === "resume"); assert.equal(resumes.length, 2, `进与出各一次切换(实际:${JSON.stringify(r.starts)})`); assert.match(resumes[0]!.cwd, /\.worktrees\/feat\/e2e-roundtrip$/, "第一站是 worktree"); assert.equal(resumes[1]!.cwd, r.repoReal, "第二站必须是主仓根"); // bash 看到的目录跟着回来了(承重:删树安全性就建立在这一条上) assert.equal(r.pwdReal, r.repoReal, "bash 必须从主仓根 spawn"); assert.equal(r.branch, "main", "主仓分支也要跟着回来"); assert.equal(r.mainPorcelain, ""); }); test("模型工具 worktree{action:exit}:terminate → agent_settled → __exit 整条链真的把 cwd 送回主仓", { skip, timeout: 120_000 }, async () => { // 2026-11-15 事故的正主:模型当时根本调不到退出(只有 /worktree exit 命令)。 // 这条用假 LLM 真的发出那个工具调用,验证 terminate 与 agent_settled 派发都真的生效 —— // 那两环是 pi 自己的行为,假 ctx 的单测只能验到我们登记了待办。 const r = await runScenario({ command: "/worktree new feat/e2e-tool-exit", then: "Leave the worktree now with the worktree tool.", viaModelTool: true, }); const resumes = r.starts.filter((s) => s.reason === "resume"); assert.equal(resumes.length, 2, `进与出各一次切换(实际:${JSON.stringify(r.starts)})`); assert.match(resumes[0]!.cwd, /\.worktrees\/feat\/e2e-tool-exit$/); assert.equal(resumes[1]!.cwd, r.repoReal, "模型工具的 exit 必须真的把会话切回主仓根"); assert.equal(r.pwdReal, r.repoReal, "bash 必须从主仓根 spawn"); assert.equal(r.branch, "main"); }); }); /** * 一个只会做一件事的假 LLM(anthropic 线格式):最后一条带文本的 user 消息含 * "Leave the worktree" 时发一次 `worktree{action:"exit"}` 工具调用,其余情况回一句普通文本。 * * 不复用 interrupt-marker/fake-llm.ts:那份的行为围绕 bash/ESSAY/SLEEP,这里需要的是 * 另一个工具名与参数,改那份会把两个扩展的用例耦在一起。 */ async function startFakeWorktreeLlm(): Promise<{ baseUrl: string; close(): Promise }> { const server = http.createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); const body = JSON.parse(Buffer.concat(chunks).toString("utf8")); const messages: any[] = body?.messages ?? []; let lastText = ""; for (let i = messages.length - 1; i >= 0; i--) { const m = messages[i]; if (m?.role !== "user") continue; const text = typeof m.content === "string" ? m.content : (m.content ?? []).filter((p: any) => p?.type === "text").map((p: any) => p.text).join(""); if (text.trim() !== "") { lastText = text; break; } } res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); const event = (type: string, data: object) => res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`); event("message_start", { message: { id: "msg_fake", type: "message", role: "assistant", model: "fake-1", content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 } }, }); if (lastText.includes("Leave the worktree")) { event("content_block_start", { index: 0, content_block: { type: "tool_use", id: "tu_exit", name: "worktree", input: {} } }); event("content_block_delta", { index: 0, delta: { type: "input_json_delta", partial_json: JSON.stringify({ action: "exit" }) } }); event("content_block_stop", { index: 0 }); event("message_delta", { delta: { stop_reason: "tool_use", stop_sequence: null }, usage: { output_tokens: 5 } }); } else { event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }); event("content_block_delta", { index: 0, delta: { type: "text_delta", text: "ok." } }); event("content_block_stop", { index: 0 }); event("message_delta", { delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 2 } }); } event("message_stop", {}); res.end(); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const port = (server.address() as AddressInfo).port; return { baseUrl: `http://127.0.0.1:${port}`, close: () => new Promise((resolve) => { server.closeAllConnections(); server.close(() => resolve()); }), }; } /** 路径存在则 realpath,否则原样(断言失败时要能打出原始值,而不是再抛一次)。 */ function realpathOrSelf(target: string): string { try { return fs.realpathSync(target); } catch { return target; } }