Files
pi-subagent/test/extension.test.ts
T

568 lines
23 KiB
TypeScript

import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import test from "node:test";
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
import type { Message } from "@earendil-works/pi-ai";
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
import { Value } from "typebox/value";
import registerExtension from "../src/index.ts";
import { extractJobSnapshots } from "../src/persistence.ts";
import { WorkflowParams } from "../src/schemas.ts";
import type { WorkflowStartResult } from "../src/workflow-run.ts";
import { FakeRunner, result as makeResult } from "./helpers.ts";
type Execute = (id: string, params: any, signal?: AbortSignal, onUpdate?: unknown, ctx?: ExtensionToolContext) => Promise<AgentToolResult<any>>;
interface HarnessOptions {
trusted?: boolean;
confirmResult?: boolean | boolean[];
}
interface Confirmation {
title: string;
message: string;
}
async function harness(initialEntries: unknown[] = [], options: HarnessOptions = {}) {
let branch = initialEntries;
const cwd = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-extension-"));
const agentsDir = path.join(cwd, ".pi", "agents");
await fs.promises.mkdir(agentsDir, { recursive: true });
await fs.promises.writeFile(path.join(agentsDir, "scout.md"), "---\nname: scout\ndescription: Test agent\n---\nTest prompt\n");
const runner = new FakeRunner();
const tools = new Map<string, { name: string; description?: string; execute: Execute }>();
const commands = new Map<string, (args: string, ctx: ExtensionToolContext) => Promise<void>>();
const events = new Map<string, (event: any, ctx: ExtensionToolContext) => unknown>();
const entries: unknown[] = [];
const notifications: string[] = [];
const customComponents: any[] = [];
const customClosers: Array<() => void> = [];
let customRenders = 0;
const statuses = new Map<string, string | undefined>();
const confirmations: Confirmation[] = [];
const confirmAnswers = Array.isArray(options.confirmResult) ? [...options.confirmResult] : undefined;
const confirmFallback = typeof options.confirmResult === "boolean" ? options.confirmResult : true;
const pi = {
registerTool(definition: { name: string; description?: string; execute: Execute }) { tools.set(definition.name, definition); },
registerCommand(name: string, definition: { handler: (args: string, ctx: ExtensionToolContext) => Promise<void> }) { commands.set(name, definition.handler); },
registerEntryRenderer() {},
registerMessageRenderer() {},
on(name: string, handler: (event: any, ctx: ExtensionToolContext) => unknown) { events.set(name, handler); },
appendEntry(_type: string, data: unknown) { entries.push({ type: "custom", customType: _type, data }); },
};
registerExtension(pi as unknown as ExtensionAPI, runner);
const ctx = {
cwd,
mode: "tui",
hasUI: true,
model: undefined,
thinkingLevel: undefined,
isProjectTrusted: () => options.trusted ?? true,
ui: {
confirm: async (title: string, message: string) => {
confirmations.push({ title, message });
return confirmAnswers && confirmAnswers.length > 0 ? confirmAnswers.shift()! : confirmFallback;
},
notify: (text: string) => { notifications.push(text); },
setStatus: (key: string, text: string | undefined) => { statuses.set(key, text); },
custom: (factory: (tui: any, theme: any, keybindings: any, done: () => void) => any) => {
return new Promise<void>((resolve) => {
const component = factory(
{ requestRender: () => { customRenders++; } },
{ fg: (_color: string, text: string) => text, bold: (text: string) => text },
{ matches: (data: string, keybinding: string) => data === keybinding },
() => resolve(),
);
customComponents.push(component);
customClosers.push(() => resolve());
});
},
},
sessionManager: {
getBranch: () => branch,
getSessionId: () => "test-session",
},
} as unknown as ExtensionToolContext;
return {
cwd, runner, tools, commands, events, entries, notifications, statuses, confirmations, ctx,
customComponents,
getCustomRenders: () => customRenders,
closeCustom: () => customClosers.pop()?.(),
setBranch: (entries: unknown[]) => { branch = entries; },
};
}
function textOf(result: AgentToolResult<any>): string {
return result.content[0]?.type === "text" ? result.content[0].text : "";
}
function writeWorkflowFile(
directory: string,
name: string,
options: { args?: string[]; steps: Array<Record<string, unknown>> },
): string {
fs.mkdirSync(directory, { recursive: true });
const filePath = path.join(directory, `${name}.md`);
const frontmatter = JSON.stringify(
{ name, description: `${name} workflow`, args: options.args ?? [], steps: options.steps },
null,
2,
);
fs.writeFileSync(filePath, `---\n${frontmatter}\n---\n\nNotes.\n`, "utf-8");
return filePath;
}
function writeProjectWorkflow(
cwd: string,
name: string,
options: { args?: string[]; steps: Array<Record<string, unknown>> },
): string {
return writeWorkflowFile(path.join(cwd, ".pi", "workflows"), name, options);
}
const params = { agent: "scout", task: "test task", agentScope: "project", confirmProjectAgents: false };
test("Pi adapters preserve sync results and expose async failure/cancel/interruption without management errors", async () => {
const h = await harness();
try {
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
const syncPromise = h.tools.get("subagent")!.execute("sync", params, undefined, undefined, h.ctx);
await new Promise((resolve) => setImmediate(resolve));
h.runner.complete("test task", "sync output");
const sync = await syncPromise;
assert.equal(sync.content[0].type, "text");
assert.equal(sync.content[0].type === "text" ? sync.content[0].text : "", "sync output");
assert.notEqual(sync.isError, true);
const started = await h.tools.get("subagent_async")!.execute("async-1", params, undefined, undefined, h.ctx);
const jobId = (started.details as any).job.id as string;
h.runner.complete("test task", "partial", { exitCode: 1, errorMessage: "boom" });
const failed = await h.tools.get("subagent_jobs")!.execute("wait-1", { action: "wait", jobId, timeoutSeconds: 1 }, undefined, undefined, h.ctx);
assert.equal((failed.details as any).job.status, "failed");
assert.notEqual(failed.isError, true);
assert.match(extractJobSnapshots(h.entries).at(-1)?.status ?? "", /failed/);
const listing = h.commands.get("subagents")!("", h.ctx);
await new Promise((resolve) => setImmediate(resolve));
assert.equal(h.customComponents.length, 1);
assert.match(h.customComponents[0].render(120).join("\n"), new RegExp(jobId));
h.closeCustom();
await listing;
const second = await h.tools.get("subagent_async")!.execute("async-2", params, undefined, undefined, h.ctx);
const secondId = (second.details as any).job.id as string;
const cancelling = await h.tools.get("subagent_jobs")!.execute("cancel", { action: "cancel", jobId: secondId }, undefined, undefined, h.ctx);
assert.equal((cancelling.details as any).job.status, "cancelling");
assert.notEqual(cancelling.isError, true);
const cancelled = await h.tools.get("subagent_jobs")!.execute("wait-2", { action: "wait", jobId: secondId, timeoutSeconds: 1 }, undefined, undefined, h.ctx);
assert.equal((cancelled.details as any).job.status, "cancelled");
assert.notEqual(cancelled.isError, true);
const third = await h.tools.get("subagent_async")!.execute("async-3", params, undefined, undefined, h.ctx);
const thirdId = (third.details as any).job.id as string;
await h.events.get("session_shutdown")?.({ type: "session_shutdown", reason: "reload" }, h.ctx);
const interrupted = await h.tools.get("subagent_jobs")!.execute("get-3", { action: "get", jobId: thirdId }, undefined, undefined, h.ctx);
assert.equal((interrupted.details as any).job.status, "interrupted");
assert.notEqual(interrupted.isError, true);
const unknown = await h.tools.get("subagent_jobs")!.execute("unknown", { action: "get", jobId: "job_missing" }, undefined, undefined, h.ctx);
assert.equal(unknown.isError, true);
assert.equal(h.runner.aborted.includes("test task"), true);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("subagents opens a selected job in the TUI and keeps text output in RPC", async () => {
const h = await harness();
try {
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
const started = await h.tools.get("subagent_async")!.execute("async", params, undefined, undefined, h.ctx);
const jobId = (started.details as any).job.id as string;
const opening = h.commands.get("subagents")!(jobId, h.ctx);
await new Promise((resolve) => setImmediate(resolve));
const component = h.customComponents[0];
assert.match(component.render(120).join("\n"), new RegExp(`> ${jobId}`));
const rendersBeforeProgress = h.getCustomRenders();
const pending = h.runner.calls[0];
const message = {
role: "assistant",
content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }],
timestamp: 100,
} as unknown as Message;
pending.options.onUpdate?.({
result: {
...makeResult(pending.task, "live output"),
status: "running",
exitCode: null,
messages: [message],
},
message,
});
assert.ok(h.getCustomRenders() > rendersBeforeProgress);
assert.match(component.render(120).join("\n"), /\$ npm test/);
h.closeCustom();
await opening;
const rpc = { ...h.ctx, mode: "rpc" } as ExtensionToolContext;
await h.commands.get("subagents")!(jobId, rpc);
assert.match(h.notifications.at(-1) ?? "", new RegExp(jobId));
await h.commands.get("subagents")!("", rpc);
assert.match(h.notifications.at(-1) ?? "", /Subagent jobs/);
assert.equal(h.customComponents.length, 1);
h.runner.complete("test task");
} finally {
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("async dispatch rejects print/JSON before admission", async () => {
const h = await harness();
try {
for (const mode of ["print", "json"]) {
const ctx = { ...h.ctx, mode } as ExtensionToolContext;
const result = await h.tools.get("subagent_async")!.execute("async", params, undefined, undefined, ctx);
assert.equal(result.isError, true);
assert.match(result.content[0].type === "text" ? result.content[0].text : "", /synchronous subagent/);
}
assert.equal(h.runner.calls.length, 0);
assert.equal(h.entries.length, 0);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("session restart restores persisted interrupted history without starting a child", async () => {
const first = await harness();
let second: Awaited<ReturnType<typeof harness>> | undefined;
try {
await first.events.get("session_start")?.({ type: "session_start", reason: "startup" }, first.ctx);
const started = await first.tools.get("subagent_async")!.execute("async", params, undefined, undefined, first.ctx);
const jobId = (started.details as any).job.id as string;
await first.events.get("session_shutdown")?.({ type: "session_shutdown", reason: "reload" }, first.ctx);
second = await harness(first.entries);
await second.events.get("session_start")?.({ type: "session_start", reason: "reload" }, second.ctx);
const restored = await second.tools.get("subagent_jobs")!.execute("get", { action: "get", jobId }, undefined, undefined, second.ctx);
assert.equal((restored.details as any).job.status, "interrupted");
assert.notEqual(restored.isError, true);
assert.equal(second.runner.calls.length, 0);
} finally {
await fs.promises.rm(first.cwd, { recursive: true, force: true });
if (second) await fs.promises.rm(second.cwd, { recursive: true, force: true });
}
});
test("invalid workflow item configuration is surfaced as a warning at session start", async () => {
const previous = process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS;
try {
for (const [value, warning] of [["0", true], ["257", true], ["1", false], ["256", false]] as const) {
process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = value;
const h = await harness();
try {
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
if (warning) {
assert.equal(h.notifications.length, 1, value);
assert.match(h.notifications[0], /PI_SUBAGENT_WORKFLOW_MAX_ITEMS/);
assert.match(h.notifications[0], /using 32/);
} else {
assert.equal(h.notifications.length, 0, value);
}
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
}
} finally {
if (previous === undefined) delete process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS;
else process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = previous;
}
});
test("session_tree replaces history from the active branch", async () => {
const h = await harness();
try {
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
const started = await h.tools.get("subagent_async")!.execute("async", params, undefined, undefined, h.ctx);
const jobId = (started.details as any).job.id as string;
h.runner.complete("test task");
await h.tools.get("subagent_jobs")!.execute("wait", { action: "wait", jobId, timeoutSeconds: 1 }, undefined, undefined, h.ctx);
h.setBranch([]);
await h.events.get("session_tree")?.({ type: "session_tree" }, h.ctx);
const missing = await h.tools.get("subagent_jobs")!.execute("get", { action: "get", jobId }, undefined, undefined, h.ctx);
assert.equal(missing.isError, true);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("workflow tool starts a run and returns its id and start plan", async () => {
const h = await harness([], { trusted: true });
try {
writeProjectWorkflow(h.cwd, "audit", {
args: ["glob"],
steps: [
{ id: "scan", agent: "scout", task: "scan {args.glob}" },
{ id: "report", agent: "scout", task: "report {steps.scan.output}", needs: ["scan"] },
],
});
const result = await h.tools.get("workflow")!.execute(
"wf",
{ action: "start", name: "audit", args: { glob: "src/**" } },
undefined,
undefined,
h.ctx,
);
assert.notEqual(result.isError, true);
const started = result.details as WorkflowStartResult;
assert.match(started.id, /^job_\d+$/);
assert.equal(started.job.id, started.id);
assert.equal(started.plan.name, "audit");
assert.deepEqual(started.plan.steps.map((step) => step.id), ["scan", "report"]);
assert.deepEqual(started.plan.steps[1].needs, ["scan"]);
assert.match(textOf(result), new RegExp(started.id));
assert.match(textOf(result), /scan/);
assert.equal(h.runner.calls.length, 1);
assert.equal(h.runner.calls[0].task.task, "scan src/**");
const listed = await h.tools.get("subagent_jobs")!.execute("list", { action: "list" }, undefined, undefined, h.ctx);
assert.match(textOf(listed), new RegExp(started.id));
h.runner.complete("scan src/**", "src/a.ts");
await new Promise((resolve) => setImmediate(resolve));
assert.equal(h.runner.calls[1].task.task, "report src/a.ts");
h.runner.complete("report src/a.ts", "ranked findings");
const waited = await h.tools.get("subagent_jobs")!.execute(
"wait",
{ action: "wait", jobId: started.id, timeoutSeconds: 1 },
undefined,
undefined,
h.ctx,
);
assert.equal((waited.details as any).run.status, "succeeded");
} finally {
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("workflow start surfaces every validation failure before any child spawns", async () => {
const h = await harness([], { trusted: true });
try {
writeProjectWorkflow(h.cwd, "args-flow", {
args: ["glob"],
steps: [{ id: "scan", agent: "scout", task: "scan {args.glob}" }],
});
writeProjectWorkflow(h.cwd, "cycle-flow", {
steps: [
{ id: "a", agent: "scout", task: "a", needs: ["b"] },
{ id: "b", agent: "scout", task: "b", needs: ["a"] },
],
});
writeProjectWorkflow(h.cwd, "too-many-flow", {
steps: Array.from({ length: 65 }, (_, index) => ({ id: `s${index}`, agent: "scout", task: `task ${index}` })),
});
const cases: Array<[Record<string, unknown>, RegExp]> = [
[{ action: "start", name: "missing-flow" }, /Unknown workflow: "missing-flow"/],
[{ action: "start", name: "args-flow", args: { other: "x" } }, /unknown argument "other"/],
[{ action: "start", name: "args-flow", args: { glob: "src/**", other: "x" } }, /unknown argument "other"/],
[{ action: "start", name: "cycle-flow" }, /needs form a cycle/],
[{ action: "start", name: "too-many-flow" }, /too many steps \(65\)/],
];
for (const [request, expected] of cases) {
const result = await h.tools.get("workflow")!.execute("wf", request, undefined, undefined, h.ctx);
assert.equal(result.isError, true);
assert.match(textOf(result), expected);
}
assert.equal(h.runner.calls.length, 0);
assert.equal(h.entries.length, 0);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("project workflows prompt once per directory while user workflows are trusted", async () => {
const h = await harness([], { trusted: false });
const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
try {
const userDir = path.join(h.cwd, "user-agent-dir");
fs.mkdirSync(path.join(userDir, "agents"), { recursive: true });
fs.writeFileSync(
path.join(userDir, "agents", "global.md"),
"---\nname: global\ndescription: Global agent\n---\nYou are global.\n",
"utf-8",
);
writeWorkflowFile(path.join(userDir, "workflows"), "user-flow", {
steps: [{ id: "run", agent: "global", task: "user run" }],
});
process.env.PI_CODING_AGENT_DIR = userDir;
const projectFile = writeProjectWorkflow(h.cwd, "project-flow", {
steps: [{ id: "run", agent: "global", task: "project run" }],
});
const first = await h.tools.get("workflow")!.execute(
"wf-1",
{ action: "start", name: "project-flow" },
undefined,
undefined,
h.ctx,
);
assert.notEqual(first.isError, true);
const second = await h.tools.get("workflow")!.execute(
"wf-2",
{ action: "start", name: "project-flow" },
undefined,
undefined,
h.ctx,
);
assert.notEqual(second.isError, true);
const user = await h.tools.get("workflow")!.execute(
"wf-3",
{ action: "start", name: "user-flow" },
undefined,
undefined,
h.ctx,
);
assert.notEqual(user.isError, true);
assert.equal(h.confirmations.length, 1);
assert.match(h.confirmations[0].title, /project/i);
assert.ok(h.confirmations[0].message.includes(path.dirname(projectFile)));
assert.ok(h.confirmations[0].message.includes("project-flow"));
assert.match(h.confirmations[0].message, /repo-controlled/);
assert.equal(h.runner.calls.length, 3);
} finally {
if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("one workflow start confirms every untrusted project directory only once", async () => {
const h = await harness([], { trusted: false });
try {
const projectFile = writeProjectWorkflow(h.cwd, "project-flow", {
steps: [{ id: "run", agent: "scout", task: "project run" }],
});
const first = await h.tools.get("workflow")!.execute(
"wf-1",
{ action: "start", name: "project-flow" },
undefined,
undefined,
h.ctx,
);
assert.notEqual(first.isError, true);
const workflowDir = path.dirname(projectFile);
const agentsDir = path.join(h.cwd, ".pi", "agents");
assert.equal(h.confirmations.length, 1);
assert.ok(h.confirmations[0].message.includes(workflowDir));
assert.ok(h.confirmations[0].message.includes(agentsDir));
assert.match(h.confirmations[0].message, /repo-controlled/);
const second = await h.tools.get("workflow")!.execute(
"wf-2",
{ action: "start", name: "project-flow" },
undefined,
undefined,
h.ctx,
);
assert.notEqual(second.isError, true);
assert.equal(h.confirmations.length, 1);
assert.equal(h.runner.calls.length, 2);
} finally {
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("declining project workflow trust aborts before any child spawns", async () => {
const h = await harness([], { trusted: false, confirmResult: false });
try {
writeProjectWorkflow(h.cwd, "project-flow", {
steps: [{ id: "run", agent: "scout", task: "project run" }],
});
const result = await h.tools.get("workflow")!.execute(
"wf",
{ action: "start", name: "project-flow" },
undefined,
undefined,
h.ctx,
);
assert.equal(result.isError, true);
assert.match(textOf(result), /not approved/);
assert.equal(h.confirmations.length, 1);
assert.equal(h.runner.calls.length, 0);
assert.equal(h.entries.length, 0);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("the /workflow command parses quoted key=value arguments and validates keys", async () => {
const h = await harness([], { trusted: true });
try {
writeProjectWorkflow(h.cwd, "parse-flow", {
args: ["channel", "glob"],
steps: [{ id: "notify", agent: "scout", task: "notify {args.channel} about {args.glob}" }],
});
await h.commands.get("workflow")!('parse-flow channel="#ops team" glob=\'src/**\'', h.ctx);
assert.equal(h.runner.calls.length, 1);
assert.equal(h.runner.calls[0].task.task, "notify #ops team about src/**");
assert.match(h.notifications.at(-1) ?? "", /job_\d+/);
await h.commands.get("workflow")!("parse-flow channel", h.ctx);
assert.match(h.notifications.at(-1) ?? "", /expected key=value/i);
assert.equal(h.runner.calls.length, 1);
await h.commands.get("workflow")!('parse-flow channel="#ops" glob="src/**" bogus=x', h.ctx);
assert.match(h.notifications.at(-1) ?? "", /unknown argument "bogus"/);
assert.equal(h.runner.calls.length, 1);
await h.commands.get("workflow")!('parse-flow channel="#ops"', h.ctx);
assert.match(h.notifications.at(-1) ?? "", /missing required argument "glob"/);
assert.equal(h.runner.calls.length, 1);
await h.commands.get("workflow")!("", h.ctx);
assert.match(h.notifications.at(-1) ?? "", /Usage: \/workflow/);
assert.equal(h.runner.calls.length, 1);
h.runner.complete("notify #ops team about src/**", "sent");
} finally {
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});
test("the workflow tool exposes one start action and a compact description", async () => {
const h = await harness();
try {
const tool = h.tools.get("workflow");
assert.ok(tool);
assert.ok((tool.description?.length ?? Number.POSITIVE_INFINITY) < 4000);
assert.equal(Value.Check(WorkflowParams, { action: "start", name: "audit" }), true);
assert.equal(Value.Check(WorkflowParams, { action: "start", name: "audit", args: { glob: "src/**" } }), true);
assert.equal(Value.Check(WorkflowParams, { action: "stop", name: "audit" }), false);
assert.equal(Value.Check(WorkflowParams, { action: "start" }), false);
} finally {
await fs.promises.rm(h.cwd, { recursive: true, force: true });
}
});