541 lines
19 KiB
TypeScript
541 lines
19 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, { after } from "node:test";
|
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
import registerExtension from "../src/index.ts";
|
|
import type { WorkflowJournal, WorkflowJournalStep } from "../src/types.ts";
|
|
import { MAX_TASK_OUTPUT_BYTES } from "../src/output.ts";
|
|
import { extractWorkflowJournals } from "../src/persistence.ts";
|
|
import { emptyUsage, type JobStatus, type TaskStatus } from "../src/types.ts";
|
|
import { buildUltraNotice, ULTRA_DONE_MESSAGE_TYPE, type UltraNoticeDetails } from "../src/ultra-notify.ts";
|
|
import type { WorkflowStartResult } from "../src/workflow-run.ts";
|
|
import { FakeRunner } from "./helpers.ts";
|
|
|
|
const tempRoots: string[] = [];
|
|
|
|
after(() => {
|
|
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
|
|
});
|
|
|
|
type Execute = (
|
|
id: string,
|
|
params: any,
|
|
signal?: AbortSignal,
|
|
onUpdate?: unknown,
|
|
ctx?: ExtensionToolContext,
|
|
) => Promise<AgentToolResult<any>>;
|
|
|
|
interface SentMessage {
|
|
message: { customType: string; content: string; display: boolean; details?: UltraNoticeDetails };
|
|
options?: { triggerTurn?: boolean; deliverAs?: string };
|
|
}
|
|
|
|
type MessageRenderer = (message: any, options: any, theme: any) => { render(width: number): readonly string[] } | undefined;
|
|
|
|
async function harness(options: { sendMessageThrows?: boolean } = {}) {
|
|
const cwd = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-ultra-notify-"));
|
|
tempRoots.push(cwd);
|
|
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 project agent\n---\nTest prompt\n",
|
|
);
|
|
|
|
const runner = new FakeRunner();
|
|
const tools = new Map<string, { name: string; description?: string; execute: Execute }>();
|
|
const events = new Map<string, (event: any, ctx: ExtensionToolContext) => unknown>();
|
|
const entries: unknown[] = [];
|
|
const messages: SentMessage[] = [];
|
|
const renderers = new Map<string, MessageRenderer>();
|
|
const notifications: string[] = [];
|
|
|
|
const pi = {
|
|
registerTool(definition: { name: string; description?: string; execute: Execute }) {
|
|
tools.set(definition.name, definition);
|
|
},
|
|
registerCommand() {},
|
|
registerEntryRenderer() {},
|
|
registerMessageRenderer(type: string, renderer: MessageRenderer) {
|
|
renderers.set(type, renderer);
|
|
},
|
|
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 });
|
|
},
|
|
sendMessage(message: SentMessage["message"], sendOptions?: SentMessage["options"]) {
|
|
if (options.sendMessageThrows) throw new Error("session unavailable");
|
|
messages.push({ message, options: sendOptions });
|
|
},
|
|
};
|
|
registerExtension(pi as unknown as ExtensionAPI, runner);
|
|
|
|
const ctx = {
|
|
cwd,
|
|
mode: "tui",
|
|
hasUI: true,
|
|
model: undefined,
|
|
thinkingLevel: undefined,
|
|
isProjectTrusted: () => true,
|
|
ui: {
|
|
confirm: async () => true,
|
|
notify: (text: string) => {
|
|
notifications.push(text);
|
|
},
|
|
setStatus: () => {},
|
|
},
|
|
sessionManager: {
|
|
getBranch: () => [],
|
|
getSessionId: () => "test-session",
|
|
},
|
|
} as unknown as ExtensionToolContext;
|
|
|
|
return { cwd, runner, tools, events, entries, messages, renderers, notifications, ctx };
|
|
}
|
|
|
|
async function startSession(h: Awaited<ReturnType<typeof harness>>): Promise<void> {
|
|
await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx);
|
|
}
|
|
|
|
function inlinePlan(steps: Array<Record<string, unknown>>, name = "notice-plan"): string {
|
|
const frontmatter = { name, description: "Notice test plan", args: [], steps };
|
|
return `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\nNotes.\n`;
|
|
}
|
|
|
|
async function startUltra(
|
|
h: Awaited<ReturnType<typeof harness>>,
|
|
steps: Array<Record<string, unknown>>,
|
|
): Promise<WorkflowStartResult> {
|
|
const result = await h.tools.get("ultra")!.execute("ultra", { plan: inlinePlan(steps) }, undefined, undefined, h.ctx);
|
|
assert.notEqual(result.isError, true);
|
|
return result.details as WorkflowStartResult;
|
|
}
|
|
|
|
function tick(): Promise<void> {
|
|
return new Promise((resolve) => setImmediate(resolve));
|
|
}
|
|
|
|
async function waitFor(h: Awaited<ReturnType<typeof harness>>, jobId: string) {
|
|
const waited = await h.tools.get("subagent_jobs")!.execute(
|
|
"wait",
|
|
{ action: "wait", jobId, timeoutSeconds: 1 },
|
|
undefined,
|
|
undefined,
|
|
h.ctx,
|
|
);
|
|
const details = waited.details as any;
|
|
return details.run ?? details.job;
|
|
}
|
|
|
|
async function withEnv(name: string, value: string, run: () => Promise<void>): Promise<void> {
|
|
const previous = process.env[name];
|
|
process.env[name] = value;
|
|
try {
|
|
await run();
|
|
} finally {
|
|
if (previous === undefined) delete process.env[name];
|
|
else process.env[name] = previous;
|
|
}
|
|
}
|
|
|
|
function journalStep(id: string, status: TaskStatus, output = ""): WorkflowJournalStep {
|
|
return {
|
|
id,
|
|
inputHash: `sha256:${"0".repeat(64)}`,
|
|
status,
|
|
attempts: status === "queued" ? 0 : 1,
|
|
output,
|
|
outputTruncated: false,
|
|
outputBytesOmitted: 0,
|
|
items: [],
|
|
};
|
|
}
|
|
|
|
function journal(overrides: Partial<WorkflowJournal> = {}): WorkflowJournal {
|
|
return {
|
|
jobId: "job_0001",
|
|
status: "succeeded" as JobStatus,
|
|
plan: {
|
|
name: "inline-plan",
|
|
description: "Test inline plan",
|
|
args: [],
|
|
steps: [],
|
|
source: "inline",
|
|
filePath: "ultra:inline",
|
|
},
|
|
args: {},
|
|
steps: [],
|
|
usage: emptyUsage(),
|
|
createdAt: 1,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
test("an inline run sends one notice at terminal state with the consolidated answer", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
const started = await startUltra(h, [
|
|
{ id: "scan", agent: "scout", task: "scan sources" },
|
|
{ id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"] },
|
|
]);
|
|
assert.equal(h.messages.length, 0);
|
|
|
|
h.runner.complete("scan sources", "src/a.ts");
|
|
await tick();
|
|
assert.equal(h.messages.length, 0, "a running run sends no notice");
|
|
|
|
h.runner.complete("merge src/a.ts", "the consolidated answer");
|
|
await tick();
|
|
const job = await waitFor(h, started.id);
|
|
assert.equal(job.status, "succeeded");
|
|
|
|
assert.equal(h.messages.length, 1);
|
|
const { message, options } = h.messages[0];
|
|
assert.equal(message.customType, ULTRA_DONE_MESSAGE_TYPE);
|
|
assert.equal(message.display, true);
|
|
assert.equal(typeof message.content, "string");
|
|
assert.deepEqual(options, { triggerTurn: true });
|
|
assert.deepEqual(message.details, {
|
|
jobId: started.id,
|
|
status: "succeeded",
|
|
planName: "notice-plan",
|
|
stepId: "merge",
|
|
});
|
|
assert.match(message.content, new RegExp(`Run ${started.id} succeeded`));
|
|
assert.match(message.content, /Last succeeded step: merge\./);
|
|
assert.match(message.content, /the consolidated answer/);
|
|
assert.doesNotMatch(message.content, /src\/a\.ts/);
|
|
|
|
await h.tools.get("subagent_jobs")!.execute("get", { action: "get", jobId: started.id }, undefined, undefined, h.ctx);
|
|
await tick();
|
|
assert.equal(h.messages.length, 1, "exactly one notice per run");
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("the push notice and wait carry identical bytes for the same run", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
const started = await startUltra(h, [
|
|
{ id: "scan", agent: "scout", task: "scan sources" },
|
|
{ id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"] },
|
|
]);
|
|
|
|
h.runner.complete("scan sources", "src/a.ts");
|
|
await tick();
|
|
h.runner.complete("merge src/a.ts", "the consolidated answer");
|
|
await tick();
|
|
|
|
const waited = await h.tools.get("subagent_jobs")!.execute(
|
|
"wait",
|
|
{ action: "wait", jobId: started.id, timeoutSeconds: 1 },
|
|
undefined,
|
|
undefined,
|
|
h.ctx,
|
|
);
|
|
const waitText = waited.content[0]?.type === "text" ? waited.content[0].text : "";
|
|
assert.equal(h.messages.length, 1);
|
|
assert.equal(waitText, h.messages[0].message.content, "pull and push carry the same bytes");
|
|
assert.equal(Buffer.byteLength(waitText, "utf8"), Buffer.byteLength(h.messages[0].message.content, "utf8"));
|
|
assert.match(waitText, /Steps: scan succeeded · merge succeeded/);
|
|
assert.match(waitText, /Last succeeded step: merge\./);
|
|
assert.match(waitText, /the consolidated answer/);
|
|
assert.doesNotMatch(waitText, /src\/a\.ts/, "wait never returns an intermediate step output");
|
|
|
|
const run = (waited.details as any).run;
|
|
assert.equal(run.status, "succeeded");
|
|
assert.equal(run.answer.stepId, "merge");
|
|
assert.deepEqual(run.steps.map((step: any) => [step.id, step.status]), [
|
|
["scan", "succeeded"],
|
|
["merge", "succeeded"],
|
|
]);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("a timed-out wait on a run carries status and step lines, never an intermediate output", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
const started = await startUltra(h, [
|
|
{ id: "scan", agent: "scout", task: "scan sources" },
|
|
{ id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"] },
|
|
]);
|
|
|
|
h.runner.complete("scan sources", "intermediate secret");
|
|
await tick();
|
|
const waited = await h.tools.get("subagent_jobs")!.execute(
|
|
"wait",
|
|
{ action: "wait", jobId: started.id, timeoutSeconds: 0.01 },
|
|
undefined,
|
|
undefined,
|
|
h.ctx,
|
|
);
|
|
const text = waited.content[0]?.type === "text" ? waited.content[0].text : "";
|
|
assert.match(text, /(wait timed out; run is unchanged)/);
|
|
assert.match(text, /Steps: scan succeeded · merge running/);
|
|
assert.doesNotMatch(text, /intermediate secret/);
|
|
assert.doesNotMatch(text, /Last succeeded step/);
|
|
|
|
h.runner.complete("merge intermediate secret", "final");
|
|
await tick();
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("file-sourced workflow runs never notify", async () => {
|
|
const h = await harness();
|
|
try {
|
|
const workflowsDir = path.join(h.cwd, ".pi", "workflows");
|
|
fs.mkdirSync(workflowsDir, { recursive: true });
|
|
fs.writeFileSync(
|
|
path.join(workflowsDir, "file-plan.md"),
|
|
inlinePlan([{ id: "scan", agent: "scout", task: "scan a file plan" }], "file-plan"),
|
|
"utf-8",
|
|
);
|
|
await startSession(h);
|
|
const result = await h.tools.get("workflow")!.execute(
|
|
"workflow",
|
|
{ name: "file-plan" },
|
|
undefined,
|
|
undefined,
|
|
h.ctx,
|
|
);
|
|
assert.notEqual(result.isError, true);
|
|
const started = result.details as WorkflowStartResult;
|
|
|
|
h.runner.complete("scan a file plan", "file answer");
|
|
await tick();
|
|
const job = await waitFor(h, started.id);
|
|
assert.equal(job.status, "succeeded");
|
|
assert.equal(extractWorkflowJournals(h.entries).length, 1, "the journal is still persisted");
|
|
assert.equal(h.messages.length, 0);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("a run with no succeeded step notifies with status only, never partial output", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
const failed = await startUltra(h, [
|
|
{ id: "scan", agent: "scout", task: "scan fails" },
|
|
{ id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"] },
|
|
]);
|
|
h.runner.complete("scan fails", "partial findings", { exitCode: 1, errorMessage: "scan exploded" });
|
|
await tick();
|
|
const failedJob = await waitFor(h, failed.id);
|
|
assert.equal(failedJob.status, "failed");
|
|
|
|
assert.equal(h.messages.length, 1);
|
|
assert.match(h.messages[0].message.content, new RegExp(`Run ${failed.id} failed`));
|
|
assert.match(h.messages[0].message.content, /No step succeeded\./);
|
|
assert.doesNotMatch(h.messages[0].message.content, /partial findings/);
|
|
assert.equal(h.messages[0].message.details?.stepId, undefined);
|
|
|
|
const cancelled = await startUltra(h, [{ id: "solo", agent: "scout", task: "cancel me" }]);
|
|
await h.tools.get("subagent_jobs")!.execute(
|
|
"cancel",
|
|
{ action: "cancel", jobId: cancelled.id },
|
|
undefined,
|
|
undefined,
|
|
h.ctx,
|
|
);
|
|
await tick();
|
|
const cancelledJob = await waitFor(h, cancelled.id);
|
|
assert.equal(cancelledJob.status, "cancelled");
|
|
|
|
assert.equal(h.messages.length, 2);
|
|
assert.match(h.messages[1].message.content, new RegExp(`Run ${cancelled.id} cancelled`));
|
|
assert.match(h.messages[1].message.content, /No step succeeded\./);
|
|
assert.equal(h.messages[1].message.details?.stepId, undefined);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("the payload is the journal's bounded last-succeeded output, not re-expanded", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
const started = await startUltra(h, [{ id: "merge", agent: "scout", task: "merge everything" }]);
|
|
const answer = `${"A".repeat(MAX_TASK_OUTPUT_BYTES)}TAIL-MARKER`;
|
|
h.runner.complete("merge everything", answer);
|
|
await tick();
|
|
const job = await waitFor(h, started.id);
|
|
assert.equal(job.status, "succeeded");
|
|
|
|
const [runJournal] = extractWorkflowJournals(h.entries);
|
|
const bounded = runJournal.steps[0].output;
|
|
assert.equal(runJournal.steps[0].outputTruncated, true);
|
|
assert.match(bounded, /\[Output truncated: \d+ bytes omitted\]$/);
|
|
|
|
assert.equal(h.messages.length, 1);
|
|
const content = h.messages[0].message.content;
|
|
assert.ok(content.endsWith(bounded), "the notice uses the bounded journal output as-is");
|
|
assert.doesNotMatch(content, /TAIL-MARKER/);
|
|
assert.ok(
|
|
Buffer.byteLength(content, "utf8") < MAX_TASK_OUTPUT_BYTES + 512,
|
|
`notice stayed bounded (${Buffer.byteLength(content, "utf8")} bytes)`,
|
|
);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("buildUltraNotice carries the last succeeded step in journal order and the error when none succeeded", () => {
|
|
const noticed = buildUltraNotice(
|
|
journal({
|
|
status: "failed",
|
|
steps: [
|
|
journalStep("scan", "succeeded", "scan output"),
|
|
journalStep("audit", "succeeded", "audit output"),
|
|
journalStep("merge", "failed", "partial merge"),
|
|
],
|
|
}),
|
|
{ ultraEnabled: true, notifyEnabled: true },
|
|
);
|
|
assert.ok(noticed);
|
|
assert.equal(noticed.details.stepId, "audit");
|
|
assert.match(noticed.content, /Run job_0001 failed/);
|
|
assert.match(noticed.content, /audit output/);
|
|
assert.doesNotMatch(noticed.content, /partial merge/);
|
|
assert.doesNotMatch(noticed.content, /scan output/);
|
|
|
|
const failedEarly = buildUltraNotice(
|
|
journal({ status: "failed", steps: [journalStep("scan", "failed", "partial")], errorMessage: "spawn failed" }),
|
|
{ ultraEnabled: true, notifyEnabled: true },
|
|
);
|
|
assert.ok(failedEarly);
|
|
assert.match(failedEarly.content, /No step succeeded\./);
|
|
assert.match(failedEarly.content, /Error: spawn failed/);
|
|
assert.doesNotMatch(failedEarly.content, /partial/);
|
|
assert.equal(failedEarly.details.stepId, undefined);
|
|
});
|
|
|
|
test("buildUltraNotice is gated by source and both switches", () => {
|
|
const inline = journal({ steps: [journalStep("scan", "succeeded", "done")] });
|
|
assert.ok(buildUltraNotice(inline, { ultraEnabled: true, notifyEnabled: true }));
|
|
assert.equal(buildUltraNotice(inline, { ultraEnabled: true, notifyEnabled: false }), undefined);
|
|
assert.equal(buildUltraNotice(inline, { ultraEnabled: false, notifyEnabled: true }), undefined);
|
|
assert.equal(
|
|
buildUltraNotice(journal({ plan: { ...inline.plan, source: "project" } }), {
|
|
ultraEnabled: true,
|
|
notifyEnabled: true,
|
|
}),
|
|
undefined,
|
|
);
|
|
});
|
|
|
|
test("PI_SUBAGENT_ULTRA_NOTIFY=off suppresses notices while the run still finishes", async () => {
|
|
await withEnv("PI_SUBAGENT_ULTRA_NOTIFY", "off", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
const started = await startUltra(h, [{ id: "scan", agent: "scout", task: "scan quietly" }]);
|
|
h.runner.complete("scan quietly", "done");
|
|
await tick();
|
|
const job = await waitFor(h, started.id);
|
|
assert.equal(job.status, "succeeded");
|
|
assert.equal(extractWorkflowJournals(h.entries).length, 1);
|
|
assert.equal(h.messages.length, 0);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
test("an invalid PI_SUBAGENT_ULTRA_NOTIFY warns and keeps notices on", async () => {
|
|
await withEnv("PI_SUBAGENT_ULTRA_NOTIFY", "sometimes", async () => {
|
|
const h = await harness();
|
|
try {
|
|
await startSession(h);
|
|
assert.equal(h.notifications.length, 1);
|
|
assert.match(h.notifications[0], /PI_SUBAGENT_ULTRA_NOTIFY="sometimes"/);
|
|
assert.match(h.notifications[0], /using on/);
|
|
|
|
const started = await startUltra(h, [{ id: "scan", agent: "scout", task: "scan loudly" }]);
|
|
h.runner.complete("scan loudly", "done");
|
|
await tick();
|
|
await waitFor(h, started.id);
|
|
assert.equal(h.messages.length, 1);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
test("PI_SUBAGENT_ULTRA=off removes the ultra tool, notice renderer, and notices", async () => {
|
|
await withEnv("PI_SUBAGENT_ULTRA", "off", async () => {
|
|
const h = await harness();
|
|
try {
|
|
assert.equal(h.tools.has("ultra"), false);
|
|
assert.equal(h.renderers.has(ULTRA_DONE_MESSAGE_TYPE), false);
|
|
await startSession(h);
|
|
assert.equal(h.messages.length, 0);
|
|
assert.equal(
|
|
buildUltraNotice(journal({ steps: [journalStep("scan", "succeeded", "done")] }), {
|
|
ultraEnabled: false,
|
|
notifyEnabled: true,
|
|
}),
|
|
undefined,
|
|
);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
test("a failed notice send never breaks the run or its journal", async () => {
|
|
const h = await harness({ sendMessageThrows: true });
|
|
try {
|
|
await startSession(h);
|
|
const started = await startUltra(h, [{ id: "scan", agent: "scout", task: "scan despite no notice" }]);
|
|
h.runner.complete("scan despite no notice", "done");
|
|
await tick();
|
|
const job = await waitFor(h, started.id);
|
|
assert.equal(job.status, "succeeded");
|
|
assert.equal(extractWorkflowJournals(h.entries).length, 1);
|
|
assert.equal(h.messages.length, 0);
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("the notice renderer is registered and draws one line with the job id and status", async () => {
|
|
const h = await harness();
|
|
try {
|
|
const renderer = h.renderers.get(ULTRA_DONE_MESSAGE_TYPE);
|
|
assert.ok(renderer);
|
|
const component = renderer(
|
|
{
|
|
role: "custom",
|
|
customType: ULTRA_DONE_MESSAGE_TYPE,
|
|
content: "Run job_0042 succeeded — plan \"audit\".",
|
|
display: true,
|
|
details: { jobId: "job_0042", status: "succeeded", planName: "audit" },
|
|
timestamp: 0,
|
|
},
|
|
{ expanded: false, outputPad: 0, keyHint: (_key: string, hint: string) => hint },
|
|
{ fg: (_color: string, text: string) => text },
|
|
);
|
|
assert.ok(component);
|
|
const lines = component.render(120);
|
|
assert.equal(lines.length, 1);
|
|
assert.equal(lines[0].trimEnd(), "Ultra job_0042 succeeded");
|
|
} finally {
|
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
|
}
|
|
});
|