/** * worktree 端到端:**真 pi(RPC 模式)+ 真 git 仓库**,验证 `/worktree new <名>` 之后 * 会话 cwd 真的变成 `/.worktrees/<名>`,而不是靠 `cd` 假装。 * * 为什么必须用真 pi:这件事的全部意义在于「runtime 整体重建」。假 ctx 只能验证 * `switchSession` 的入参,验证不了新会话的 `ctx.cwd`、内置工具基准目录与 statusline 读 git 的目录。 * * 隔离:`PI_CODING_AGENT_DIR` 指向临时目录,`-ne -ns -np --no-themes -nc --no-mcp --offline -na` * 关掉发现与网络;只有 `-e` 显式给的扩展会加载。不碰用户真实的 `~/.pi/agent`。 * 用 `--tools bash` 而不是 `--no-tools`,因为断言要跑 `pwd` / `git branch`。 * * 找不到本机 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 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; } async function runScenario(options: { command: string }): 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"), ); // 真 pi 跑 RPC:只发扩展命令与 bash,不请求模型(续句关掉,见下) const real = spawn( "pi", [ "--mode", "rpc", "-ne", "-ns", "-np", "--no-themes", "-nc", "--no-mcp", "--offline", "-na", "--tools", "bash", "-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); // 切换之后,让 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, stderr, }; } finally { real.kill("SIGTERM"); 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, ""); }); }); /** 路径存在则 realpath,否则原样(断言失败时要能打出原始值,而不是再抛一次)。 */ function realpathOrSelf(target: string): string { try { return fs.realpathSync(target); } catch { return target; } }