import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import test, { type TestContext } from "node:test"; import { createEventBus, ProjectTrustStore, SessionManager } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { Check } from "typebox/value"; import workspaces from "../index.ts"; const Request = Type.Object({ root: Type.String(), path: Type.String(), revision: Type.Optional(Type.String()), }); const BusyRequest = Type.Object({ busy: Type.Array(Type.String()) }); interface Params { action: string; name?: string; } interface Context { cwd: string; } interface Tool { execute( id: string, params: Params, signal: undefined, onUpdate: undefined, ctx: Context, ): Promise<{ content: Array<{ text: string }> }>; } interface Command { handler(args: string, ctx: Context): Promise; getArgumentCompletions(prefix: string): Array<{ value: string }> | null; } interface Next { sendMessage(message: { content: string }, options: { triggerTurn: boolean }): Promise; ui: { notify(message: string): void }; } function setup( t: TestContext, options: { cwd?: (main: string) => string; /** The launch directory, when it differs from the session's directory. */ launch?: (main: string) => string; trusted: boolean; saved: boolean; memory?: boolean; busy?: string; confirm?: boolean; /** A script that fails with this output. */ failing?: string; }, ) { const dir = mkdtempSync(join(tmpdir(), "pi-workspaces-")); const agentDir = join(dir, "agent"); const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = agentDir; t.after(() => { rmSync(dir, { recursive: true, force: true }); if (previousAgentDir === undefined) { delete process.env.PI_CODING_AGENT_DIR; } else { process.env.PI_CODING_AGENT_DIR = previousAgentDir; } }); const main = join(dir, "main"); mkdirSync(main); const cwd = options.cwd?.(main) ?? main; const log: string[] = []; const events = createEventBus(); events.on("workspaces:resolve", (request) => { Object.assign(request ?? {}, { root: main }); }); for (const action of ["create", "remove"]) { events.on(`workspaces:${action}`, (request) => { assert.ok(Check(Request, request)); log.push(`${action} ${request.path} ${request.revision ?? ""}`.trim()); if (action === "create") { mkdirSync(request.path, { recursive: true }); } Object.assign(request, { result: Promise.resolve() }); }); } events.on("workspaces:busy", (request) => { if (options.busy && Check(BusyRequest, request)) { request.busy.push(options.busy); } }); let tool: Tool | undefined; let command: Command | undefined; const handlers = new Map void>(); const pi = { events, registerTool: (definition: Tool) => (tool = definition), registerCommand: (_name: string, definition: Command) => (command = definition), on: (name: string, handler: (event: { reason: string }, ctx: Context) => void) => handlers.set(name, handler), sendUserMessage: (text: string) => log.push(`prompt ${text}`), sendMessage: (message: { content: string }) => log.push(`message ${message.content}`), exec: async (file: string, args: string[], { cwd }: { cwd: string }) => { log.push(`exec ${file} ${args.join(" ")} in ${cwd}`); return options.failing === file ? { code: 1, killed: false, stdout: "", stderr: "broken" } : { code: 0, killed: false, stdout: "", stderr: "" }; }, }; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The fixture implements the API members the extension uses. workspaces(pi as never); const sessionManager = options.memory ? SessionManager.inMemory(cwd) : SessionManager.create(cwd, join(dir, "sessions")); if (options.saved) { sessionManager.appendMessage({ role: "user", content: "Start", timestamp: 1 }); sessionManager.appendMessage({ role: "assistant", content: [{ type: "text", text: "Done" }], api: "fixture", provider: "fixture", model: "fixture", usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, }, stopReason: "stop", timestamp: 2, }); } const next: Next = { sendMessage: async (message, { triggerTurn }) => { log.push(`message ${message.content} ${triggerTurn}`); }, ui: { notify: (message) => log.push(`notify ${message}`) }, }; const ctx = { cwd: options.launch?.(main) ?? cwd, hasUI: true, ui: { confirm: async (_title: string, message: string) => { log.push(`confirm ${message}`); return options.confirm ?? false; }, }, isProjectTrusted: () => options.trusted, sessionManager, switchSession: async ( file: string, { withSession }: { withSession: (ctx: Next) => Promise }, ) => { const session = SessionManager.open(file); log.push(`switch ${session.getCwd()} ${session.getEntries().length}`); ctx.sessionManager = session; ctx.cwd = session.getCwd(); await withSession(next); }, }; return { main, agentDir, log, ctx, call: async (params: Params) => { assert.ok(tool); return (await tool.execute("call", params, undefined, undefined, ctx)).content[0]?.text; }, settle: async () => { handlers.get("agent_settled")?.({ reason: "" }, ctx); assert.ok(command); await command.handler("", ctx); }, command: async (args: string) => { assert.ok(command); await command.handler(args, ctx); }, start: (reason: string) => handlers.get("session_start")?.({ reason }, ctx), complete: (prefix: string) => { handlers.get("session_start")?.({ reason: "resume" }, ctx); return command?.getArgumentCompletions(prefix)?.map((item) => item.value); }, }; } test("a workspace runs its setup after creation and its teardown before removal", async (t) => { const options: Parameters[1] = { trusted: true, saved: true }; const fixture = setup(t, options); const config = join(fixture.main, ".pi", "extensions", "workspaces"); const teardown = join(fixture.main, "bin/teardown"); mkdirSync(config, { recursive: true }); writeFileSync( join(config, "config.json"), JSON.stringify({ root: "../workspaces", revision: "trunk()", setup: "bin/setup", teardown: "bin/teardown", }), ); new ProjectTrustStore(fixture.agentDir).set(fixture.main, true); const target = resolve(fixture.main, "../workspaces/feat"); assert.match( (await fixture.call({ action: "create", name: "feat" })) ?? "", /moves there after this response/, ); await fixture.settle(); options.failing = teardown; await fixture.call({ action: "remove", name: "feat" }); await assert.rejects( fixture.settle(), /^Error: Did not remove .+: its teardown failed:\nbroken$/, ); options.failing = undefined; await fixture.call({ action: "remove", name: "feat" }); await fixture.settle(); assert.deepEqual(fixture.log, [ `create ${target} trunk()`, `exec ${join(fixture.main, "bin/setup")} ${fixture.main} in ${target}`, "prompt /workspace", `switch ${target} 2`, `message The session moved to ${target}. Continue the task. true`, "prompt /workspace", `exec ${teardown} ${fixture.main} in ${target}`, "prompt /workspace", `exec ${teardown} ${fixture.main} in ${target}`, `remove ${target}`, `switch ${fixture.main} 2`, `notify Removed ${target}`, ]); }); test("another checkout uses the main checkout's config only when the main checkout is trusted", async (t) => { const fixture = setup(t, { cwd: (main) => join(main, ".workspaces", "current"), trusted: true, saved: true, }); const config = join(fixture.main, ".pi", "extensions", "workspaces"); mkdirSync(config, { recursive: true }); writeFileSync(join(config, "config.json"), JSON.stringify({ setup: "bin/setup" })); await fixture.call({ action: "create", name: "untrusted" }); new ProjectTrustStore(fixture.agentDir).set(fixture.main, true); await fixture.call({ action: "create", name: "trusted" }); const target = join(fixture.main, ".workspaces", "trusted"); assert.deepEqual(fixture.log, [ `create ${join(fixture.main, ".workspaces", "untrusted")}`, `create ${target}`, `exec ${join(fixture.main, "bin/setup")} ${fixture.main} in ${target}`, ]); }); test("commands use workspace names, and removing the current workspace moves to the main checkout first", async (t) => { const fixture = setup(t, { trusted: false, saved: false, cwd: (main) => join(main, ".workspaces", "feat"), }); const workspace = join(fixture.main, ".workspaces", "feat"); mkdirSync(workspace, { recursive: true }); assert.deepEqual(fixture.complete("s"), ["switch"]); assert.deepEqual(fixture.complete("switch "), ["switch default", "switch feat"]); assert.deepEqual(fixture.complete("remove "), ["remove feat"]); await assert.rejects(fixture.command("feat"), /Usage/); await fixture.command("switch default"); await fixture.command("switch new"); await fixture.call({ action: "remove", name: "new" }); await fixture.settle(); const added = join(fixture.main, ".workspaces", "new"); assert.deepEqual(fixture.log, [ `switch ${fixture.main} 0`, `create ${added}`, `switch ${added} 0`, "prompt /workspace", `remove ${added}`, `switch ${fixture.main} 0`, `notify Removed ${added}`, ]); }); test("a workspace session returns its conversation to the parent session", async (t) => { const fixture = setup(t, { trusted: false, saved: true }); const { ctx } = fixture; ctx.sessionManager.appendSessionInfo("Plan"); const parent = ctx.sessionManager.getSessionFile(); assert.ok(parent); const say = (text: string) => ctx.sessionManager.appendMessage({ role: "user", content: text, timestamp: 3 }); await fixture.call({ action: "create", name: "feat" }); await fixture.settle(); assert.equal(ctx.sessionManager.getSessionName(), "Plan [feat]"); say("In feat"); await fixture.call({ action: "switch", name: "default" }); await fixture.settle(); assert.equal(ctx.sessionManager.getSessionFile(), parent); assert.equal(ctx.sessionManager.getSessionName(), "Plan"); await fixture.call({ action: "switch", name: "feat" }); await fixture.settle(); say("Again in feat"); await fixture.call({ action: "remove", name: "feat" }); await fixture.settle(); assert.equal(ctx.sessionManager.getSessionFile(), parent); assert.deepEqual( ctx.sessionManager .getBranch() .flatMap((entry) => entry.type === "message" && entry.message.role === "user" ? [entry.message.content] : [], ), ["Start", "In feat", "Again in feat"], ); await fixture.command("switch a"); const outer = ctx.sessionManager.getSessionFile(); await fixture.command("switch b"); await fixture.call({ action: "remove", name: "b" }); await fixture.settle(); assert.equal(ctx.sessionManager.getSessionFile(), outer); assert.equal(ctx.sessionManager.getSessionName(), "Plan [a]"); await fixture.command("switch default"); await fixture.command("switch feat"); say("Elsewhere"); SessionManager.open(parent).appendSessionInfo("Changed"); await fixture.command("switch default"); assert.notEqual(ctx.sessionManager.getSessionFile(), parent); assert.equal(ctx.sessionManager.getSessionName(), "Plan"); }); test("running work blocks agent moves, and the user can cancel the work to move", async (t) => { const options = { trusted: false, saved: true, busy: "1 subagent", confirm: true }; const fixture = setup(t, options); await assert.rejects( fixture.call({ action: "create", name: "feat" }), /Cannot create workspace feat while work runs: 1 subagent\./, ); assert.deepEqual(fixture.log, []); const workspace = join(fixture.main, ".workspaces", "feat"); await fixture.command("switch feat"); assert.deepEqual(fixture.log, [ "confirm The session move cancels 1 subagent.", `create ${workspace}`, `switch ${workspace} 2`, ]); fixture.log.length = 0; options.busy = ""; await fixture.call({ action: "remove", name: "feat" }); options.busy = "1 subagent"; await fixture.settle(); assert.deepEqual(fixture.log, [ "prompt /workspace", "message Cannot remove workspace feat while work runs: 1 subagent. Wait for the work to finish or stop it, then retry.", ]); fixture.log.length = 0; options.busy = ""; await fixture.call({ action: "create", name: "next" }); options.busy = "1 subagent"; await fixture.settle(); const next = join(fixture.main, ".workspaces", "next"); assert.deepEqual(fixture.log, [ `create ${next}`, "prompt /workspace", `remove ${next}`, "message Cannot create workspace next while work runs: 1 subagent. Wait for the work to finish or stop it, then retry.", ]); }); test("a session without a file does not create a workspace", async (t) => { const fixture = setup(t, { trusted: false, saved: true, memory: true }); await assert.rejects(fixture.call({ action: "create", name: "feat" }), /not saved/); assert.deepEqual(fixture.log, []); }); test("a session continued from another directory reopens in its recorded workspace", async (t) => { const fixture = setup(t, { trusted: false, saved: true, cwd: (main) => join(main, ".workspaces", "feat"), launch: (main) => main, }); const workspace = join(fixture.main, ".workspaces", "feat"); mkdirSync(workspace, { recursive: true }); fixture.start("resume"); assert.deepEqual(fixture.log, []); fixture.start("startup"); await fixture.command(""); assert.deepEqual(fixture.log, ["prompt /workspace", `switch ${workspace} 2`]); });