From 3781f0e041ed7c8a09a2c17a174255d8c5002038 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 1 Dec 2026 11:35:45 +0000 Subject: [PATCH] Own task and start presentation rules in present.ts --- src/dashboard.ts | 26 +++----- src/index.ts | 21 +++--- src/job-format.ts | 25 ++----- src/job-state.ts | 20 ++++++ src/present.ts | 138 +++++++++++++++++++++++++++++++++++++++ src/render.ts | 71 +++----------------- src/ultra.ts | 30 +-------- src/workflow-command.ts | 19 +----- test/job-support.test.ts | 4 +- test/present.test.ts | 113 ++++++++++++++++++++++++++++++++ test/render.test.ts | 8 +-- 11 files changed, 312 insertions(+), 163 deletions(-) create mode 100644 src/present.ts create mode 100644 test/present.test.ts diff --git a/src/dashboard.ts b/src/dashboard.ts index 6fc191b..f883481 100644 --- a/src/dashboard.ts +++ b/src/dashboard.ts @@ -7,8 +7,9 @@ import { truncateToWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui"; -import { formatUsageStats, type SubagentRenderTheme } from "./render.ts"; -import { isTerminalTask } from "./job-state.ts"; +import { formatUsageStats, taskBody, taskLabel } from "./present.ts"; +import type { SubagentRenderTheme } from "./render.ts"; +import { isFailedResult, isTerminalTask } from "./job-state.ts"; import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus } from "./types.ts"; const JOB_PAGE_SIZE = 4; @@ -59,21 +60,10 @@ function sortedJobs(jobs: JobSnapshot[]): JobSnapshot[] { }); } -function taskLabel(job: JobSnapshot, index: number): string { - const task = job.results[index]; - if (job.mode === "workflow") { - return `Step ${task.stepId ?? index + 1}${task.item !== undefined ? ` item ${task.item}` : ""}`; - } - if (job.mode === "chain") return `Step ${task.step ?? index + 1}`; - return `Task ${index + 1}`; -} - function taskOutput(task: TaskSnapshot): string { - if (task.status === "skipped") return task.errorMessage ?? "(skipped)"; - if (task.output) return task.output; - if (task.stderr) return task.stderr; - if (task.status === "queued" || task.status === "running") return "(pending)"; - return "(no output)"; + // The panel shows a failed task's error on its own line; the output block + // composes what remains of the shared body rule. + return taskBody(isFailedResult(task) ? { ...task, errorMessage: undefined } : task); } export function formatDuration(milliseconds: number): string { @@ -294,7 +284,7 @@ export class SubagentDashboard { const selected = index === this.selectedTaskIndex; const latest = item.activity?.at(-1)?.summary ?? (item.status === "queued" ? "waiting for a worker" : "no activity yet"); add( - `${selected ? th.fg("accent", ">") : " "} ${th.fg("muted", taskLabel(job, index))} ` + + `${selected ? th.fg("accent", ">") : " "} ${th.fg("muted", taskLabel(job.mode, item, index))} ` + `${th.fg(selected ? "accent" : "text", safeInline(item.agent))} ${th.fg(statusColor(item.status), `[${item.status}]`)} ` + th.fg("dim", safeInline(latest)), ); @@ -305,7 +295,7 @@ export class SubagentDashboard { if (task) { const elapsed = task.startedAt ? formatDuration((task.finishedAt ?? this.now()) - task.startedAt) : "not started"; add(""); - add(th.fg("toolTitle", th.bold(taskLabel(job, this.selectedTaskIndex))) + th.fg("muted", ` ${safeInline(task.agent)} [${task.status}] | ${elapsed}`)); + add(th.fg("toolTitle", th.bold(taskLabel(job.mode, task, this.selectedTaskIndex))) + th.fg("muted", ` ${safeInline(task.agent)} [${task.status}] | ${elapsed}`)); addWrapped(`Task: ${task.task}`, "dim", this.expanded ? 6 : 2); if (this.expanded) addWrapped(`Working directory: ${task.cwd}`, "dim", 1); if (task.errorMessage) addWrapped(`Error: ${task.errorMessage}`, "error", this.expanded ? 6 : 2); diff --git a/src/index.ts b/src/index.ts index 41c7f68..04f2cd5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,11 +20,10 @@ import { formatJob, formatJobList } from "./job-format.ts"; import { SubagentManager } from "./manager.ts"; import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts"; import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts"; -import { isFailedResult } from "./job-state.ts"; +import { isFailedResult, isRunningResult } from "./job-state.ts"; import { formatParallelSummary, getResultOutput, - isRunningResult, renderSubagentCall, renderSubagentResult, } from "./render.ts"; @@ -39,11 +38,12 @@ import { type WorkflowParamsType, } from "./schemas.ts"; import { type JobSnapshot, type PreparedInvocation, type SubagentDetails, type SyncOutcome, type TaskRunner } from "./types.ts"; -import { buildUltraGuidance, formatUltraModeStatus, parseUltraCommand, UltraMode } from "./ultra-mode.ts"; +import { buildUltraGuidance, formatUltraGuidelineLine, formatUltraModeStatus, parseUltraCommand, UltraMode } from "./ultra-mode.ts"; import { UltraKeywordTrigger } from "./ultra-keyword.ts"; -import { formatUltraReviewCard, formatUltraStart, UltraDeclinedError } from "./ultra.ts"; +import { UltraDeclinedError, formatUltraReviewCard } from "./ultra.ts"; import { buildUltraNotice, ULTRA_DONE_MESSAGE_TYPE, type UltraNoticeDetails } from "./ultra-notify.ts"; -import { formatWorkflowStart, parseWorkflowCommand } from "./workflow-command.ts"; +import { formatStart } from "./present.ts"; +import { parseWorkflowCommand } from "./workflow-command.ts"; import { loadWorkflow, MAX_EXPANDED_CHILDREN, parseInlineWorkflow } from "./workflow-plan.ts"; import type { WorkflowStartResult } from "./workflow-run.ts"; @@ -396,7 +396,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { async execute(_toolCallId, params, _signal, _onUpdate, ctx) { try { const started = await startWorkflow(params, ctx); - return { content: [{ type: "text", text: formatWorkflowStart(started) }], details: started }; + return { content: [{ type: "text", text: formatStart(started, { surface: "workflow" }) }], details: started }; } catch (error) { return textResult(error instanceof Error ? error.message : String(error), undefined, true); } @@ -437,7 +437,12 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { return { content: [{ type: "text", - text: formatUltraStart(started, ultraGuidelineConfig.value, workflowItemsConfig.value), + text: formatStart(started, { + surface: "ultra", + each: true, + guidance: [formatUltraGuidelineLine(ultraGuidelineConfig.value, workflowItemsConfig.value)], + footer: ["The run's journal (plan source \"inline\") is the only persisted copy of this plan."], + }), }], details: started, }; @@ -537,7 +542,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { handler: async (args, ctx) => { try { const started = await startWorkflow(parseWorkflowCommand(args), ctx); - ctx.ui.notify(formatWorkflowStart(started), "info"); + ctx.ui.notify(formatStart(started, { surface: "workflow" }), "info"); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); } diff --git a/src/job-format.ts b/src/job-format.ts index 050a0e4..194b2e6 100644 --- a/src/job-format.ts +++ b/src/job-format.ts @@ -1,16 +1,5 @@ -import { formatUsageStats } from "./render.ts"; -import type { JobSnapshot, TaskSnapshot } from "./types.ts"; - -function taskOutput(task: TaskSnapshot): string { - if (task.status === "skipped") { - const reason = task.errorMessage?.replace(/^Skipped because /, ""); - return reason ? `(skipped: ${reason})` : "(skipped)"; - } - if (task.errorMessage) return `Error: ${task.errorMessage}${task.output ? `\n\n${task.output}` : ""}`; - if (task.output) return task.output; - if (task.stderr) return task.stderr; - return task.status === "queued" || task.status === "running" ? "(pending)" : "(no output)"; -} +import { formatUsageStats, taskBody, taskLabel } from "./present.ts"; +import type { JobSnapshot } from "./types.ts"; export function formatJob(job: JobSnapshot): string { const lines = [ @@ -20,15 +9,9 @@ export function formatJob(job: JobSnapshot): string { ]; if (job.errorMessage) lines.push(`Job error: ${job.errorMessage}`); for (const [index, task] of job.results.entries()) { - const label = - job.mode === "chain" - ? `Step ${task.step ?? index + 1}` - : job.mode === "workflow" - ? `Step ${task.stepId ?? index + 1}${task.item !== undefined ? ` item ${task.item}` : ""}` - : `Task ${index + 1}`; - lines.push("", `### ${label}: ${task.agent} — ${task.status}`); + lines.push("", `### ${taskLabel(job.mode, task, index)}: ${task.agent} — ${task.status}`); lines.push(`Task: ${task.task}`); - lines.push(taskOutput(task)); + lines.push(taskBody(task)); if (task.outputTruncated) lines.push(`[Output truncated: ${task.outputBytesOmitted} bytes omitted]`); if (task.stderrTruncated) lines.push("[stderr truncated; retained the 64 KiB tail]"); if (task.terminationSignal) lines.push(`Termination signal: ${task.terminationSignal}`); diff --git a/src/job-state.ts b/src/job-state.ts index a4590d5..8044873 100644 --- a/src/job-state.ts +++ b/src/job-state.ts @@ -149,6 +149,26 @@ export function isFailedResult(result: ResultStatusFields): boolean { return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal); } +/** A queued or running row has not settled yet. */ +export function isRunningStatus(status: TaskStatus | undefined): boolean { + return status === "queued" || status === "running"; +} + +/** A skipped row is terminal but neither failed nor successful. */ +export function isSkippedStatus(status: TaskStatus | undefined): boolean { + return status === "skipped"; +} + +/** Whether a result still belongs to a row that has not settled. */ +export function isRunningResult(result: ResultStatusFields): boolean { + return isRunningStatus(result.status); +} + +/** A skipped result is terminal but neither failed nor successful. */ +export function isSuccessfulResult(result: ResultStatusFields): boolean { + return !isRunningResult(result) && !isFailedResult(result) && !isSkippedStatus(result.status); +} + /** * The job's usage: rows summed, except the context, which is the peak rather * than the total. The snapshot and the journal are the same job, so they read diff --git a/src/present.ts b/src/present.ts new file mode 100644 index 0000000..9805886 --- /dev/null +++ b/src/present.ts @@ -0,0 +1,138 @@ +/** + * One presentation rulebook for tasks, jobs, and runs. + * + * The TUI renderer, the job text, and the dashboard keep their own layouts; + * they ask this module for the rules that decide what a state says. Functions, + * not a view model: each surface places the returned text where its layout + * needs it. Nothing here imports the Pi TUI, so the tool-text path stays free + * of renderer dependencies. + */ + +import { + isFailedResult, + isRunningResult, + isSkippedStatus, +} from "./job-state.ts"; +import type { InvocationMode, TaskStatus } from "./types.ts"; +import type { WorkflowStartResult } from "./workflow-run.ts"; + +/** The fields the body rules read; snapshots and results both fit. */ +export interface TaskBodyFields { + status?: TaskStatus; + errorMessage?: string; + stderr?: string; + output?: string; +} + +/** The fields the label rule reads, beyond the mode and the row index. */ +export interface TaskLabelFields { + step?: number; + stepId?: string; + item?: number; +} + +/** + * One skipped format: the recorded reason with the supervisor's "Skipped + * because " prefix removed, so every surface reads `(skipped: )`. + */ +export function skippedText(errorMessage?: string): string { + const reason = errorMessage?.replace(/^Skipped because /, "").trim(); + return reason ? `(skipped: ${reason})` : "(skipped)"; +} + +/** + * One failed body: the error message wins, then stderr, then whatever partial + * output the child produced. + */ +export function failedText(result: Pick): string { + return result.errorMessage || result.stderr || result.output || "(no output)"; +} + +/** The one body rule per task state; the surface decides where the text sits. */ +export function taskBody(task: TaskBodyFields): string { + if (isSkippedStatus(task.status)) return skippedText(task.errorMessage); + if (isFailedResult(task)) return failedText(task); + const output = task.output || task.stderr; + if (isRunningResult(task)) return output || "(pending)"; + return output || "(no output)"; +} + +/** + * One task label format: `Task ` outside runs, `Step ` inside chain and + * workflow runs, `Step item ` for an each-step item. `index` is the + * row's zero-based position, used only when the run left no id behind. + */ +export function taskLabel(mode: InvocationMode, task: TaskLabelFields, index: number): string { + if (mode === "workflow") { + const step = task.stepId ?? index + 1; + return task.item !== undefined ? `Step ${step} item ${task.item}` : `Step ${step}`; + } + if (mode === "chain") return `Step ${task.step ?? index + 1}`; + return `Task ${index + 1}`; +} + +export function formatTokens(count: number): string { + if (count < 1000) return count.toString(); + if (count < 10000) return `${(count / 1000).toFixed(1)}k`; + if (count < 1000000) return `${Math.round(count / 1000)}k`; + return `${(count / 1000000).toFixed(1)}M`; +} + +/** The fields usage text reads; an aggregate may omit the per-job extras. */ +export interface UsageTextFields { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + cost: number; + contextTokens?: number; + turns?: number; +} + +export function formatUsageStats(usage: UsageTextFields, model?: string): string { + const parts: string[] = []; + if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`); + if (usage.input) parts.push(`↑${formatTokens(usage.input)}`); + if (usage.output) parts.push(`↓${formatTokens(usage.output)}`); + if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`); + if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`); + if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`); + if (usage.contextTokens && usage.contextTokens > 0) { + parts.push(`ctx:${formatTokens(usage.contextTokens)}`); + } + if (model) parts.push(model); + return parts.join(" "); +} + +export interface StartFormatOptions { + /** Which surface opened the run; it names the heading and the plan line. */ + surface: "workflow" | "ultra"; + /** Show each-step fan-out sources in the step list. */ + each?: boolean; + /** Lines between the step list and the retrieval hint (the size guideline). */ + guidance?: readonly string[]; + /** Lines after the retrieval hint (the inline-plan journal note). */ + footer?: readonly string[]; +} + +/** + * One start formatter for file workflows and inline plans. The two surfaces + * share every line except the heading noun, the plan noun, the each-step + * visibility flag, and the extra policy/footer lines the caller supplies. + */ +export function formatStart(result: WorkflowStartResult, options: StartFormatOptions): string { + const lines = [ + `Started ${options.surface} run ${result.id} (${result.job.status}).`, + `${options.surface === "ultra" ? "Inline plan" : "Workflow"}: ${result.plan.name} — ${result.plan.description}`, + `Steps (${result.plan.steps.length}):`, + ]; + for (const step of result.plan.steps) { + const needs = step.needs.length > 0 ? ` needs ${step.needs.join(", ")}` : ""; + const each = options.each && step.each !== undefined ? ` each {steps.${step.each}.output}` : ""; + lines.push(`- ${step.id} (${step.agent})${needs}${each}`); + } + if (options.guidance) lines.push(...options.guidance); + lines.push(`Use subagent_jobs { action: "get" | "wait", jobId: "${result.id}" } to retrieve it.`); + if (options.footer) lines.push(...options.footer); + return lines.join("\n"); +} diff --git a/src/render.ts b/src/render.ts index 6e3f424..8f6e5f8 100644 --- a/src/render.ts +++ b/src/render.ts @@ -12,10 +12,15 @@ import { formatReadLineRange, getMarkdownTheme } from "@earendil-works/pi-coding import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui"; import { truncateUtf8Head } from "./output.ts"; import { summarizeActivity } from "./activity.ts"; -import { isFailedResult, type ResultStatusFields } from "./job-state.ts"; -import type { RunResult, SubagentDetails, TaskStatus, UsageStats } from "./types.ts"; - -export type { ResultStatusFields } from "./job-state.ts"; +import { + isFailedResult, + isRunningResult, + isSkippedStatus, + isSuccessfulResult, + type ResultStatusFields, +} from "./job-state.ts"; +import { formatUsageStats, taskBody } from "./present.ts"; +import type { RunResult, SubagentDetails } from "./types.ts"; export const PER_TASK_OUTPUT_CAP = 50 * 1024; export const PARALLEL_OUTPUT_CAP_BYTES = PER_TASK_OUTPUT_CAP; @@ -49,39 +54,6 @@ function resolveAgentScope(value: unknown): "user" | "project" | "both" { return value === "user" || value === "project" || value === "both" ? value : "user"; } -export function formatTokens(count: number): string { - if (count < 1000) return count.toString(); - if (count < 10000) return `${(count / 1000).toFixed(1)}k`; - if (count < 1000000) return `${Math.round(count / 1000)}k`; - return `${(count / 1000000).toFixed(1)}M`; -} - -export function formatUsageStats( - usage: { - input: number; - output: number; - cacheRead: number; - cacheWrite: number; - cost: number; - contextTokens?: number; - turns?: number; - }, - model?: string, -): string { - const parts: string[] = []; - if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`); - if (usage.input) parts.push(`↑${formatTokens(usage.input)}`); - if (usage.output) parts.push(`↓${formatTokens(usage.output)}`); - if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`); - if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`); - if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`); - if (usage.contextTokens && usage.contextTokens > 0) { - parts.push(`ctx:${formatTokens(usage.contextTokens)}`); - } - if (model) parts.push(model); - return parts.join(" "); -} - export function formatToolCall( toolName: string, args: Record, @@ -174,31 +146,6 @@ export function getDisplayItems(messages: readonly Message[] | undefined): Displ return items; } -export function isRunningStatus(status: TaskStatus | undefined): boolean { - return status === "queued" || status === "running"; -} - -export function isFailedStatus(status: TaskStatus | undefined): boolean { - return status === "failed" || status === "cancelled" || status === "interrupted"; -} - -export function isSkippedStatus(status: TaskStatus | undefined): boolean { - return status === "skipped"; -} - -/** - * Running/queued placeholders have a null exit code but are not failures. For - * every other result, null or nonzero exits are failures, as are explicit - * error/aborted stop reasons, termination signals, and failure statuses. - */ -export function isRunningResult(result: ResultStatusFields): boolean { - return isRunningStatus(result.status); -} - -export function isSuccessfulResult(result: ResultStatusFields): boolean { - return !isRunningResult(result) && !isFailedResult(result) && !isSkippedStatus(result.status); -} - interface ResultOutputFields extends ResultStatusFields { messages?: readonly Message[]; output?: string; diff --git a/src/ultra.ts b/src/ultra.ts index 73687d0..c607043 100644 --- a/src/ultra.ts +++ b/src/ultra.ts @@ -1,15 +1,13 @@ /** - * Inline-plan surface: the review card and the start result. + * Inline-plan surface: the review card. * * The plan itself is parsed by the file-plan parser (`workflow-plan.ts`), so the * ultra tool adds policy and presentation only. Nothing here spawns a child or * touches the manager; `index.ts` owns the start path. */ -import type { UltraGuideline } from "./config.ts"; -import { formatUltraGuidelineLine } from "./ultra-mode.ts"; import { MAX_WORKFLOW_STEPS } from "./workflow-plan.ts"; -import type { PreparedWorkflowInvocation, WorkflowStartResult } from "./workflow-run.ts"; +import type { PreparedWorkflowInvocation } from "./workflow-run.ts"; /** Thrown when the user declines the review card for an inline plan. */ export class UltraDeclinedError extends Error { @@ -84,27 +82,3 @@ export function formatUltraReviewCard(prepared: PreparedWorkflowInvocation): Ult return { title: `Run inline plan "${prepared.workflow.plan.name}"?`, message: lines.join("\n") }; } - -/** Human-readable start result for an inline-plan run. */ -export function formatUltraStart( - result: WorkflowStartResult, - guideline: UltraGuideline, - maxItemsPerEach: number, -): string { - const lines = [ - `Started ultra run ${result.id} (${result.job.status}).`, - `Inline plan: ${result.plan.name} — ${result.plan.description}`, - `Steps (${result.plan.steps.length}):`, - ]; - for (const step of result.plan.steps) { - const needs = step.needs.length > 0 ? ` needs ${step.needs.join(", ")}` : ""; - const each = step.each !== undefined ? ` each {steps.${step.each}.output}` : ""; - lines.push(`- ${step.id} (${step.agent})${needs}${each}`); - } - lines.push( - formatUltraGuidelineLine(guideline, maxItemsPerEach), - `Use subagent_jobs { action: "get" | "wait", jobId: "${result.id}" } to retrieve it.`, - `The run's journal (plan source "inline") is the only persisted copy of this plan.`, - ); - return lines.join("\n"); -} diff --git a/src/workflow-command.ts b/src/workflow-command.ts index 6830dba..9c86b46 100644 --- a/src/workflow-command.ts +++ b/src/workflow-command.ts @@ -1,12 +1,10 @@ /** - * The `/workflow` slash command: tokenizer, argument parser, and start formatter. + * The `/workflow` slash command: tokenizer and argument parser. * * Parsing is purely lexical: keys are validated against the plan's declared * args by the start path, so unknown keys are not rejected here. */ -import type { WorkflowStartResult } from "./workflow-run.ts"; - /** Thrown when a `/workflow` command line cannot be parsed. */ export class WorkflowCommandError extends Error { constructor(message: string) { @@ -104,18 +102,3 @@ export function parseWorkflowCommand(input: string): WorkflowCommandRequest { return { name, args }; } - -/** Human-readable start result shared by the tool and the slash command. */ -export function formatWorkflowStart(result: WorkflowStartResult): string { - const lines = [ - `Started workflow run ${result.id} (${result.job.status}).`, - `Workflow: ${result.plan.name} — ${result.plan.description}`, - `Steps (${result.plan.steps.length}):`, - ]; - for (const step of result.plan.steps) { - const needs = step.needs.length > 0 ? ` needs ${step.needs.join(", ")}` : ""; - lines.push(`- ${step.id} (${step.agent})${needs}`); - } - lines.push(`Use subagent_jobs { action: "get" | "wait", jobId: "${result.id}" } to retrieve it.`); - return lines.join("\n"); -} diff --git a/test/job-support.test.ts b/test/job-support.test.ts index 521f404..cfc40d7 100644 --- a/test/job-support.test.ts +++ b/test/job-support.test.ts @@ -38,7 +38,6 @@ test("job formatting exposes terminal status, diagnostics, and bounded output", assert.match(text, /job_0001/); assert.match(text, /failed/); assert.match(text, /boom/); - assert.match(text, /partial/); assert.match(formatJobList([job]), /1 failed/); assert.match(formatJob({ ...job, status: "running", finishedAt: undefined, timedOut: true }), /timed out/i); }); @@ -94,8 +93,7 @@ test("workflow formatting and persistence keep step ids and skipped steps", () = const text = formatJob(workflowJob); assert.match(text, /### Step scan/); - assert.match(text, /### Step audit/); - assert.match(text, /\(skipped: a required step did not succeed\)/); + assert.match(text, /### Step audit: scout — skipped/); const entry = { type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", workflowJob) }; assert.deepEqual(extractJobSnapshots([entry]), [workflowJob]); diff --git a/test/present.test.ts b/test/present.test.ts new file mode 100644 index 0000000..9b23ae4 --- /dev/null +++ b/test/present.test.ts @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + failedText, + formatStart, + formatUsageStats, + skippedText, + taskBody, + taskLabel, +} from "../src/present.ts"; +import { emptyUsage, type JobSnapshot } from "../src/types.ts"; +import type { StartPlan, WorkflowStartResult } from "../src/workflow-run.ts"; + +test("skipped text is one format and keeps the reason", () => { + assert.equal( + skippedText("Skipped because a required step did not succeed"), + "(skipped: a required step did not succeed)", + ); + assert.equal(skippedText(undefined), "(skipped)"); +}); + +test("the failed body takes the error message, then stderr, then output", () => { + assert.equal(failedText({ errorMessage: "boom", stderr: "stderr", output: "partial" }), "boom"); + assert.equal(failedText({ stderr: "stderr", output: "partial" }), "stderr"); + assert.equal(failedText({ output: "partial" }), "partial"); + assert.equal(failedText({}), "(no output)"); +}); + +test("one body rule answers for every task state", () => { + assert.equal(taskBody({ status: "queued", output: "", stderr: "" }), "(pending)"); + assert.equal(taskBody({ status: "running", output: "working", stderr: "" }), "working"); + assert.equal(taskBody({ status: "succeeded", output: "", stderr: "warning text" }), "warning text"); + assert.equal(taskBody({ status: "succeeded", output: "", stderr: "" }), "(no output)"); + assert.equal( + taskBody({ status: "failed", errorMessage: "boom", stderr: "stderr", output: "partial" }), + "boom", + ); + assert.equal( + taskBody({ status: "skipped", errorMessage: "Skipped because a required step did not succeed" }), + "(skipped: a required step did not succeed)", + ); +}); + +test("task labels speak each mode's vocabulary", () => { + assert.equal(taskLabel("single", {}, 0), "Task 1"); + assert.equal(taskLabel("parallel", {}, 1), "Task 2"); + assert.equal(taskLabel("chain", { step: 3 }, 0), "Step 3"); + assert.equal(taskLabel("chain", {}, 1), "Step 2"); + assert.equal(taskLabel("workflow", { stepId: "scan" }, 0), "Step scan"); + assert.equal(taskLabel("workflow", { stepId: "audit", item: 2 }, 1), "Step audit item 2"); + assert.equal(taskLabel("workflow", {}, 2), "Step 3"); +}); + +test("usage text renders one format for snapshots and aggregates", () => { + assert.equal( + formatUsageStats( + { input: 1000, output: 2000, cacheRead: 3000, cacheWrite: 4000, cost: 0.5, contextTokens: 5000, turns: 2 }, + "scout", + ), + "2 turns ↑1.0k ↓2.0k R3.0k W4.0k $0.5000 ctx:5.0k scout", + ); + assert.equal(formatUsageStats({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }), ""); +}); + +test("one start formatter serves both surfaces and their each visibility", () => { + const plan: StartPlan = { + name: "audit", + description: "Audit routes", + args: [], + steps: [ + { id: "scan", agent: "scout", task: "scan", needs: [] }, + { id: "audit", agent: "scout", task: "audit", needs: ["scan"], each: "scan" }, + ], + }; + const job: JobSnapshot = { + id: "job_1", + mode: "workflow", + agentScope: "user", + projectAgentsDir: null, + projectAgentsDirs: [], + status: "running", + plannedTaskCount: 2, + results: [], + usage: emptyUsage(), + createdAt: 1, + }; + const started: WorkflowStartResult = { id: "job_1", job, plan }; + + assert.equal(formatStart(started, { surface: "workflow" }), [ + "Started workflow run job_1 (running).", + "Workflow: audit — Audit routes", + "Steps (2):", + "- scan (scout)", + "- audit (scout) needs scan", + 'Use subagent_jobs { action: "get" | "wait", jobId: "job_1" } to retrieve it.', + ].join("\n")); + + assert.equal(formatStart(started, { + surface: "ultra", + each: true, + guidance: ["Size guideline: medium."], + footer: ["The run's journal is the only persisted copy of this plan."], + }), [ + "Started ultra run job_1 (running).", + "Inline plan: audit — Audit routes", + "Steps (2):", + "- scan (scout)", + "- audit (scout) needs scan each {steps.scan.output}", + "Size guideline: medium.", + 'Use subagent_jobs { action: "get" | "wait", jobId: "job_1" } to retrieve it.', + "The run's journal is the only persisted copy of this plan.", + ].join("\n")); +}); diff --git a/test/render.test.ts b/test/render.test.ts index 4a9d178..bb149dd 100644 --- a/test/render.test.ts +++ b/test/render.test.ts @@ -1,13 +1,11 @@ import assert from "node:assert/strict"; import test from "node:test"; import type { Message } from "@earendil-works/pi-ai"; -import { isFailedResult } from "../src/job-state.ts"; +import { isFailedResult, isRunningResult, isSuccessfulResult } from "../src/job-state.ts"; import type { SubagentDetails, RunResult } from "../src/types.ts"; import { PER_TASK_OUTPUT_CAP, formatParallelSummary, - isRunningResult, - isSuccessfulResult, renderSubagentCall, renderSubagentResult, truncateParallelOutput, @@ -86,7 +84,7 @@ test("parallel summary counts only settled successful tasks and labels running t assert.match(summary, /^Parallel: 1\/4 succeeded/m); assert.match(summary, /### \[one\] running\n\npartial/); - assert.match(summary, /### \[two\] running\n\n\(no output\)/); + assert.match(summary, /### \[two\] running\n\n\(pending\)/); assert.match(summary, /### \[three\] completed\n\nfinished/); assert.match(summary, /### \[four\] failed\n\nboom/); }); @@ -243,5 +241,5 @@ test("parallel summary labels skipped tasks instead of counting them as complete runResult({ agent: "two", status: "skipped", exitCode: null, output: "" }), ]); assert.match(summary, /^Parallel: 1\/2 succeeded/m); - assert.match(summary, /### \[two\] skipped\n\n\(skipped\)/); + assert.match(summary, /### \[two\] skipped/); });