Add completion notices for ultra runs

This commit is contained in:
alex committed 2026-11-30 17:21:35 +00:00
1 parent a867d9460a
commit d7f345ac04
8 files changed
+610 -4

No files matched your search

@@ -0,0 +1,3 @@
# Ultra completion notices push the consolidated answer; every other surface stays pull-based
A run started by the `ultra` tool is inline-sourced, and when it reaches a terminal state the extension sends a custom message — `pi.sendMessage({ customType: "pi-subagent-ultra-done", content, display: true, details }, { triggerTurn: true })` — carrying the run's status plus the journal's already-bounded output of the last succeeded step. A run with no succeeded step sends its status and error instead of partial output. This is a scoped amendment of the pull-based doctrine: `subagent_async` and `workflow` starts still never start an automatic model turn, and `PI_SUBAGENT_ULTRA_NOTIFY=off` restores pure pull for ultra runs too; `PI_SUBAGENT_ULTRA=off` removes the notice with the rest of the layer. Without this exception ultra mode is a polling chore, and the point of a plan is that the parent's context receives only the consolidated answer rather than every intermediate result. The notice is delivery, not a new record: the run's journal remains the audit record, and the payload reuses the journal's bounded outputs as-is, never re-expanding a child's output. Decided 2026-11-30 in the ultra-layer spec (issue #14).
+15
View File
@@ -47,3 +47,18 @@ export function readUltraEnabled(value: string | undefined): { value: boolean; w
if (value === "off") return { value: false };
return { value: true, warning: `Invalid PI_SUBAGENT_ULTRA="${value}"; using on.` };
}
/**
* Whether a terminal ultra run sends a completion notice.
*
* `PI_SUBAGENT_ULTRA_NOTIFY=off` restores pure pull-based retrieval; the
* default is on, and an unrecognized value keeps the default with a warning.
* Like the ultra switch itself, this is an extension-level setting, never a
* tool parameter the model controls.
*/
export function readUltraNotify(value: string | undefined): { value: boolean; warning?: string } {
if (value === undefined || value === "") return { value: true };
if (value === "on") return { value: true };
if (value === "off") return { value: false };
return { value: true, warning: `Invalid PI_SUBAGENT_ULTRA_NOTIFY="${value}"; using on.` };
}
+25 -3
View File
@@ -14,7 +14,7 @@ import {
getAgentDir,
} from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import { readMaxWorkers, readMaxWorkflowItems, readUltraEnabled } from "./config.ts";
import { readMaxWorkers, readMaxWorkflowItems, readUltraEnabled, readUltraNotify } from "./config.ts";
import { SubagentDashboard } from "./dashboard.ts";
import { formatJob, formatJobList } from "./job-format.ts";
import { SubagentManager } from "./manager.ts";
@@ -40,6 +40,7 @@ import {
} from "./schemas.ts";
import { type JobSnapshot, type PreparedInvocation, type SubagentDetails, type SyncOutcome, type TaskRunner } from "./types.ts";
import { formatUltraReviewCard, formatUltraStart, UltraDeclinedError } from "./ultra.ts";
import { buildUltraNotice, ULTRA_DONE_MESSAGE_TYPE, type UltraNoticeDetails } from "./ultra-notify.ts";
import { formatWorkflowStart, parseWorkflowCommand, type WorkflowStartResult } from "./workflow.ts";
import { loadWorkflow, parseInlineWorkflow } from "./workflows.ts";
@@ -114,9 +115,10 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
const workerConfig = readMaxWorkers(process.env.PI_SUBAGENT_MAX_WORKERS);
const workflowItemsConfig = readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS);
const ultraConfig = readUltraEnabled(process.env.PI_SUBAGENT_ULTRA);
const ultraNotifyConfig = readUltraNotify(process.env.PI_SUBAGENT_ULTRA_NOTIFY);
let currentContext: ExtensionContext | undefined;
let activeDashboard: SubagentDashboard | undefined;
let configurationWarnings = [workerConfig.warning, workflowItemsConfig.warning, ultraConfig.warning].filter(
let configurationWarnings = [workerConfig.warning, workflowItemsConfig.warning, ultraConfig.warning, ultraNotifyConfig.warning].filter(
(warning): warning is string => warning !== undefined,
);
@@ -146,6 +148,16 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
} catch {
// The journal is an audit record; losing it never changes a run.
}
const notice = buildUltraNotice(journal, {
ultraEnabled: ultraConfig.value,
notifyEnabled: ultraNotifyConfig.value,
});
if (!notice) return;
try {
pi.sendMessage(notice, { triggerTurn: true });
} catch {
// A completion notice is best-effort; a delivery failure never changes a run.
}
},
});
@@ -372,6 +384,16 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
});
if (ultraConfig.value) {
pi.registerMessageRenderer(ULTRA_DONE_MESSAGE_TYPE, (message, _options, theme) => {
const details = message.details as UltraNoticeDetails | undefined;
if (!details) return undefined;
return new Text(
theme.fg("muted", "Ultra ") + theme.fg("accent", details.jobId) + theme.fg("muted", ` ${details.status}`),
0,
0,
);
});
pi.registerTool({
name: "ultra",
label: "Ultra (inline plan)",
@@ -382,7 +404,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
"Shapes the engine expresses well: fan-out then fan-in (each-step, then a step that needs it), adversarial verification (a verifier step that needs the producer), generate-and-filter (parallel producers, then a filter step), and a pre-expanded tournament bracket. Classify-and-act and loop-until-done are not expressible in one plan; run per-class or per-iteration plans from the parent. For a large run, start with a small slice first.",
"Validation is identical to file plans and happens before anything starts: structure, step-output references, declared arguments, the 64-step cap, the 256-children-per-run cap, and every step agent and cwd. Project-local agents referenced by an inline plan still hit the existing project-agent confirmation.",
"With a UI, one review card per start follows validation and precedes the run: it shows the plan, every step with its needs and fan-out source, the child-count estimate against the caps, and every named agent with its user or project source. Declining spawns nothing. No-UI (print/json) sessions never prompt and start directly. Review policy is the extension's, never a tool parameter.",
"Returns the run id and expanded plan; the run is an ordinary async job. Retrieve it with subagent_jobs { action: \"get\" | \"wait\", jobId }. Results are pull-based: completion never starts an automatic model turn. Children of an ultra run cannot dispatch further agents or runs. The run's journal records the plan with source \"inline\" and is its only persisted copy.",
"Returns the run id and expanded plan; the run is an ordinary async job. Retrieve it with subagent_jobs { action: \"get\" | \"wait\", jobId }. When this run finishes, its status and consolidated answer are delivered back as a message that may start a turn; subagent_async and workflow runs stay pull-based, and PI_SUBAGENT_ULTRA_NOTIFY=off restores pure pull for ultra too. Children of an ultra run cannot dispatch further agents or runs. The run's journal records the plan with source \"inline\" and is its only persisted copy.",
].join(" "),
parameters: UltraParams,
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
+86
View File
@@ -0,0 +1,86 @@
/**
* Completion notices for ultra runs — the scoped exception to pull-based results.
*
* A workflow run emits one journal at its terminal transition. For a run
* started by the `ultra` tool — the only inline-sourced plan — `index.ts` turns
* that journal into a custom message with `triggerTurn: true`, so the
* consolidated answer reaches the parent without polling (ADR 0006). Payloads
* reuse the journal's already-bounded step outputs; nothing here re-expands a
* child's output or reads a task snapshot again.
*/
import type { WorkflowJournal, WorkflowJournalStep } from "./journal.ts";
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
import type { JobStatus } from "./types.ts";
export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done";
export interface UltraNotifyOptions {
/** The PI_SUBAGENT_ULTRA kill switch; off disables the whole layer, notices included. */
ultraEnabled: boolean;
/** PI_SUBAGENT_ULTRA_NOTIFY; off restores pure pull-based retrieval. */
notifyEnabled: boolean;
}
/** Small, renderable details; the answer itself stays in the message content. */
export interface UltraNoticeDetails {
jobId: string;
status: JobStatus;
planName: string;
stepId?: string;
}
export interface UltraNotice {
customType: string;
content: string;
display: true;
details: UltraNoticeDetails;
}
/** The last step that succeeded, in journal (plan) order. */
function lastSucceededStep(steps: readonly WorkflowJournalStep[]): WorkflowJournalStep | undefined {
for (let index = steps.length - 1; index >= 0; index--) {
if (steps[index].status === "succeeded") return steps[index];
}
return undefined;
}
/**
* Error messages are normally short, but the notice carries no unbounded
* text by contract, so bound them with the same budget as step outputs.
*/
function boundedReason(message: string): string {
const bounded = truncateUtf8Head(message, MAX_TASK_OUTPUT_BYTES);
return bounded.truncated ? `${bounded.text}\n\n[Error truncated: ${bounded.bytesOmitted} bytes omitted]` : bounded.text;
}
/**
* The notice for one terminal run, or undefined when notices are off or the
* run came from a workflow file.
*
* A run with no succeeded step reports its status and error only: there is no
* partial output to present as the consolidated answer. Runs started through
* `subagent_async` or a workflow file are not inline-sourced and stay
* pull-based.
*/
export function buildUltraNotice(journal: WorkflowJournal, options: UltraNotifyOptions): UltraNotice | undefined {
if (!options.ultraEnabled || !options.notifyEnabled) return undefined;
if (journal.plan.source !== "inline") return undefined;
const step = lastSucceededStep(journal.steps);
const lines = [`Ultra run ${journal.jobId} ${journal.status} — plan "${journal.plan.name}".`];
if (step) {
lines.push(`Last succeeded step: ${step.id}.`, step.output || "(no output)");
} else {
lines.push("No step succeeded.");
if (journal.errorMessage) lines.push(`Error: ${boundedReason(journal.errorMessage)}`);
}
const details: UltraNoticeDetails = {
jobId: journal.jobId,
status: journal.status,
planName: journal.plan.name,
};
if (step) details.stepId = step.id;
return { customType: ULTRA_DONE_MESSAGE_TYPE, content: lines.join("\n"), display: true, details };
}
+13 -1
View File
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readMaxWorkflowItems, readMaxWorkers, readUltraEnabled } from "../src/config.ts";
import { readMaxWorkflowItems, readMaxWorkers, readUltraEnabled, readUltraNotify } from "../src/config.ts";
test("worker configuration defaults to 16 and accepts only integers from 1 through 32", () => {
assert.deepEqual(readMaxWorkers(undefined), { value: 16 });
@@ -37,3 +37,15 @@ test("ultra defaults on, disables only on an explicit off, and warns on invalid
assert.match(result.warning ?? "", /PI_SUBAGENT_ULTRA/);
}
});
test("ultra notices default on, disable only on an explicit off, and warn on invalid values", () => {
assert.deepEqual(readUltraNotify(undefined), { value: true });
assert.deepEqual(readUltraNotify(""), { value: true });
assert.deepEqual(readUltraNotify("on"), { value: true });
assert.deepEqual(readUltraNotify("off"), { value: false });
for (const invalid of ["0", "false", "OFF", " maybe", "disabled"]) {
const result = readUltraNotify(invalid);
assert.equal(result.value, true);
assert.match(result.warning ?? "", /PI_SUBAGENT_ULTRA_NOTIFY/);
}
});
+1
View File
@@ -49,6 +49,7 @@ async function harness(initialEntries: unknown[] = [], options: HarnessOptions =
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 }); },
};
+466
View File
@@ -0,0 +1,466 @@
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/journal.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.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,
);
return (waited.details as any).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(`Ultra 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("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(`Ultra 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(`Ultra 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, /Ultra 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: "Ultra 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 });
}
});
+1
View File
@@ -68,6 +68,7 @@ async function harness(options: HarnessOptions = {}) {
},
registerCommand() {},
registerEntryRenderer() {},
registerMessageRenderer() {},
on(name: string, handler: (event: any, ctx: ExtensionToolContext) => unknown) {
events.set(name, handler);
},