diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index bf87c0f..fb0d023 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -133,7 +133,7 @@ Uncertain dispatches do not change the window; they already block all dispatch. Lifecycle callbacks CAS loop revision, owner runtime/generation, work ID, dispatch ID, attempt, and agent ID. Normal terminal evidence is bounded and persisted with `provider_owned` completion status; pi-loop does not call `subagents:rpc:consume`, so the provider retains its native completion surface. Protocol-v2 stop replies and `stopped`/`aborted` lifecycle statuses acknowledge cancellation, not quiescence. They become non-retryable, non-consumable `uncertain` dispatches before stop RPCs run. A late spawn reply may attach its exact cleanup identity without restoring execution. Proved failures retry only within `maxAttempts`; a spawn timeout is ambiguous without upstream status/list or idempotent dispatch keys, so it becomes `uncertain` and is never retried automatically. -Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; name `WorkflowCreate` and `TaskCreate` for other shapes; and explain `verify`. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface. +Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; name `WorkflowCreate` and `TaskCreate` for other shapes; and explain `verify`. A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total; a field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface. Session shutdown/switch invalidates lifecycle callbacks, persists unresolved work as uncertain, and best-effort requests cancellation before store rebinding. Any unresolved dispatch history prevents controller deletion under the Store lock; cancelled batches stay paused and inspectable. Late completion events do not clear this safety latch. Protocol v2 provides no safe automatic clearance or deletion route. Legacy `stopped`/`interrupted` records normalize to non-consumable uncertainty; previously launched retries or consumed evidence cannot be undone, and missing historical stop provenance cannot be reconstructed. A new runtime cannot adopt an unexpired foreign owner lease; after expiry it marks active dispatches uncertain rather than risking duplicates. Project scope, dynamic work addition, dependency graphs, cross-session election, and exact-once dispatch are not implemented. diff --git a/docs/USAGE_GUIDE.md b/docs/USAGE_GUIDE.md index d843e78..29ba3ba 100644 --- a/docs/USAGE_GUIDE.md +++ b/docs/USAGE_GUIDE.md @@ -362,6 +362,6 @@ The TUI status line summarizes ordinary loops, workflows, orchestrations, runnin Workflow tool cards, `LoopList`, and `TaskList` stay at two lines while collapsed: the summary, then one dense preview such as `✓plan ▸ [implement] ▸ review ▸ done │ CLAIMED 4m │ try 1/3 │ » pass|retry`. It shows the state trail (visited states marked, the current state bracketed), derived activity using the same status word as the summary, attempt, and available outcomes; idle work without a live lease is flagged `(unclaimed)`. Several workflows or tasks share a one-line roster. The preview is display metadata only and never changes model-facing tool text. Colors come from the active pi theme, so custom themes apply. The default glyphs are box-drawing, basic shapes, and Latin-1 characters that effectively every monospace font draws. A terminal cannot report its font and a missing icon renders blank, so Nerd Font icons are opt-in (`PI_LOOP_GLYPHS=nerd` or `NERD_FONT=1`) and are accents only: brackets and separators stay portable. A non-UTF-8 locale or `TERM=linux|dumb` selects ASCII. `/loop glyphs [nerd|unicode|ascii]` switches the set and prints a sample; it applies to cards created afterwards. -On terminals at least 110 columns wide, a narrow progress panel docks at the top-right while a workflow, orchestration, running monitor, or native task is in progress. It never takes keyboard focus and disappears when nothing is in progress. Each workflow is a vertical state trail (`✓` visited, `▶` current with derived activity and attempt, `○` not yet entered) followed by its available outcomes; workflows that are paused or unclaimed are listed first. Running monitors (at most three, oldest first) show id, elapsed time, description or command, and their last output line, with a `quiet` flag after five minutes without output; monitor state is process-local, so nothing is shown for monitors from a previous pi process. Native tasks show `done/total`, in-progress work first, and flag a claim whose lease has expired. The panel is presentation only: it reads the same LoopStore and TaskStore snapshots as the status line and never claims work, resumes a controller, or schedules a wake. Task rows come only from standalone tasks, monitor rows only from this process's MonitorManager, and workflow rows only from LoopStore. Monitor output is untrusted and stripped of control bytes before display. Durations refresh on state changes and the existing 30-second heartbeat, and every minute while a monitor runs. Because it overlays the transcript's right edge, hide it with `/loop panel off` (or `/loop panel` to toggle), or start pi with `PI_LOOP_PANEL=off`. +On terminals at least 110 columns wide, a narrow progress panel docks at the top-right while a workflow, orchestration, running monitor, or native task is in progress. It never takes keyboard focus and disappears when nothing is in progress. Each workflow is a vertical state trail (`✓` visited, `▶` current with derived activity and attempt, `○` not yet entered) followed by its available outcomes; workflows that are paused or unclaimed are listed first. Each orchestration (at most two) is a header with its progress and in-flight count, followed by up to five work items named by `label` or prompt: `●` in flight with its last reported dispatch state, elapsed time and attempt; `✗` failed; `?` uncertain; `○` pending; `✓` complete with duration and token count when the provider reported them; `–` cancelled. In-flight items are listed first and finished ones last, and a final `… N more` line counts the items not shown. The reported state is the last one received, not proof a worker is running. Running monitors (at most three, oldest first) show id, elapsed time, description or command, and their last output line, with a `quiet` flag after five minutes without output; monitor state is process-local, so nothing is shown for monitors from a previous pi process. Native tasks show `done/total`, in-progress work first, and flag a claim whose lease has expired. The panel is presentation only: it reads the same LoopStore and TaskStore snapshots as the status line and never claims work, resumes a controller, or schedules a wake. Task rows come only from standalone tasks, monitor rows only from this process's MonitorManager, and workflow rows only from LoopStore. Monitor output is untrusted and stripped of control bytes before display. Durations refresh on state changes and the existing 30-second heartbeat, and every minute while a monitor runs. Because it overlays the transcript's right edge, hide it with `/loop panel off` (or `/loop panel` to toggle), or start pi with `PI_LOOP_PANEL=off`. The runtime allows at most 25 active loops and 25 running monitors. Each orchestration batch allows up to 32 work items, 8 local workers under fixed pacing (under `aimd`, the batch size when every item declares `verify`, otherwise 8), and 3 attempts per item, plus up to 3 overload re-sends per item that do not count as attempts. diff --git a/src/ui/orchestration-presentation.ts b/src/ui/orchestration-presentation.ts index 4e0aa95..91f8173 100644 --- a/src/ui/orchestration-presentation.ts +++ b/src/ui/orchestration-presentation.ts @@ -10,6 +10,7 @@ import type { OrchestrationWorkItem, OrchestrationWorkStatus, } from "../types.js"; +import { formatCompactWorkflowDuration } from "./workflow-presentation.js"; export function orchestrationCancellationMessage(id: string, result: OrchestrationCancellation): string { if (result === "deleted") return `Orchestration #${id} cancelled and deleted`; @@ -98,6 +99,10 @@ export function orchestrationWorkSummary(item: OrchestrationWorkItem): string { let line = `#${item.id} [${orchestrationWorkStatusLabel(item.status)}] ${label} · ${item.label ?? compactPrompt(item.prompt)}`; if (dispatch?.agentId) line += ` · agent=${dispatch.agentId}`; if (item.attemptCount > 0) line += ` · attempts=${item.attemptCount}`; + // Evidence the batch holds for the item; a field is absent when nothing was reported. + if (dispatch?.verify) line += dispatch.verify.passed ? " · verify ok" : ` · verify failed (exit ${dispatch.verify.exitCode ?? "none"})`; + if (dispatch?.usage?.durationMs !== undefined) line += ` · ${formatCompactWorkflowDuration(dispatch.usage.durationMs)}`; + if (dispatch?.usage?.tokens) line += ` · ${dispatch.usage.tokens.total} tokens`; return line; } diff --git a/src/ui/progress-panel.ts b/src/ui/progress-panel.ts index fea70ce..78e894e 100644 --- a/src/ui/progress-panel.ts +++ b/src/ui/progress-panel.ts @@ -39,6 +39,7 @@ const MAX_DETAILED_WORKFLOWS = 2; const MAX_STATE_ROWS = 6; const MAX_TASK_ROWS = 5; const MAX_ORCHESTRATION_ROWS = 2; +const MAX_ORCHESTRATION_ITEM_ROWS = 5; const MAX_MONITOR_ROWS = 3; /** Silence longer than this is flagged; a long build with no output is worth a glance. */ const MONITOR_QUIET_MS = 5 * 60_000; @@ -237,6 +238,54 @@ function taskLines(tasks: readonly TaskEntry[], now: number): PanelLine[] { return lines; } +/** Compact token count: the panel has room for magnitude, not digits. */ +function compactTokens(total: number): string { + if (total < 1_000) return String(total); + if (total < 999_500) return `${Math.round(total / 1_000)}k`; + return `${(total / 1_000_000).toFixed(1)}M`; +} + +type WorkItem = NonNullable["work"][number]; + +// What still needs watching comes first; finished work is the first to scroll out of the bounded rows. +const ITEM_ORDER: Record = { active: 0, failed: 1, uncertain: 1, pending: 2, completed: 3, cancelled: 4 }; +const REPORTED_STATE: Partial> = { spawning: "starting", queued: "queued", running: "running", verifying: "verifying" }; + +function orchestrationItemLine(item: WorkItem, now: number): PanelLine { + const name = seg(plainPanelText(item.label ?? item.prompt), item.status === "active" ? "text" : "muted"); + const dispatch = item.dispatches.at(-1); + if (item.status === "active") { + // Last reported state and time since it was asked for: evidence of dispatch, not of a live worker. + const reported = dispatch ? REPORTED_STATE[dispatch.status] : undefined; + const detail = dispatch && reported + ? `${reported} ${formatCompactWorkflowDuration(now - (dispatch.startedAt ?? dispatch.requestedAt))}${dispatch.attempt > 1 ? ` · try ${dispatch.attempt}` : ""} ` + : ""; + return [seg(" ● ", "accent"), seg(detail, "dim"), name]; + } + if (item.status === "completed") { + const duration = dispatch?.usage?.durationMs; + const tokens = dispatch?.usage?.tokens?.total; + const detail = [ + ...(duration !== undefined ? [formatCompactWorkflowDuration(duration)] : []), + ...(tokens !== undefined ? [`${compactTokens(tokens)} tok`] : []), + ].join(" · "); + return [seg(" ✓ ", "success"), seg(detail ? `${detail} ` : "", "dim"), name]; + } + if (item.status === "failed") return [seg(" ✗ ", "warning"), seg("failed ", "warning"), name]; + if (item.status === "uncertain") return [seg(" ? ", "warning"), seg("uncertain ", "warning"), name]; + if (item.status === "cancelled") return [seg(" – ", "dim"), name]; + return [seg(" ○ ", "dim"), name]; +} + +function orchestrationLines(entry: LoopEntry, now: number): PanelLine[] { + const work = entry.orchestration?.work ?? []; + // Array.prototype.sort is stable, so items keep batch order within a rank. + const ordered = [...work].sort((a, b) => ITEM_ORDER[a.status] - ITEM_ORDER[b.status]); + const lines = [orchestrationLine(entry), ...ordered.slice(0, MAX_ORCHESTRATION_ITEM_ROWS).map((item) => orchestrationItemLine(item, now))]; + if (ordered.length > MAX_ORCHESTRATION_ITEM_ROWS) lines.push([seg(` … ${ordered.length - MAX_ORCHESTRATION_ITEM_ROWS} more`, "dim")]); + return lines; +} + /** * Lays out the panel body. Every returned line fits `width` visible columns and * at most `maxRows` lines are returned; an empty result means "hide the panel". @@ -260,7 +309,7 @@ export function layoutProgressPanel(input: ProgressPanelInput, width: number, ma } const orchestrations = input.loops.filter(isPanelOrchestration); - for (const entry of orchestrations.slice(0, MAX_ORCHESTRATION_ROWS)) lines.push(orchestrationLine(entry)); + for (const entry of orchestrations.slice(0, MAX_ORCHESTRATION_ROWS)) lines.push(...orchestrationLines(entry, now)); if (orchestrations.length > MAX_ORCHESTRATION_ROWS) { lines.push([seg(`◇ … ${orchestrations.length - MAX_ORCHESTRATION_ROWS} more`, "dim")]); } diff --git a/src/ui/widget.ts b/src/ui/widget.ts index 49a2b32..7ef2949 100644 --- a/src/ui/widget.ts +++ b/src/ui/widget.ts @@ -133,6 +133,8 @@ export class LoopWidget { }; for (const entry of entries) { if (entry.workflow && isStatusVisibleLoop(entry)) consider(entry.workflow.activeExecution?.lease?.expiresAt); + // In-flight item rows show elapsed time at minute resolution, like monitor rows. + if (isOrchestrationInProgress(entry) && entry.orchestration?.work.some((item) => item.status === "active")) consider(now + MONITOR_REFRESH_MS); } for (const task of tasks) { if (task.status === "in_progress") consider(task.claim?.leaseExpiresAt); diff --git a/test/helpers/progress-panel-fixtures.ts b/test/helpers/progress-panel-fixtures.ts index 89a7b60..8a081fc 100644 --- a/test/helpers/progress-panel-fixtures.ts +++ b/test/helpers/progress-panel-fixtures.ts @@ -88,7 +88,14 @@ export function panelWorkflow(options: PanelWorkflowOptions = {}): LoopEntry { }; } -export function panelOrchestration(id: string, statuses: OrchestrationState["work"][number]["status"][], status: OrchestrationState["status"] = "active"): LoopEntry { +type PanelWorkItem = OrchestrationState["work"][number]; + +export function panelOrchestration( + id: string, + statuses: PanelWorkItem["status"][], + status: OrchestrationState["status"] = "active", + decorate: (index: number) => Partial = () => ({}), +): LoopEntry { return { id, prompt: "Fan out", @@ -106,7 +113,7 @@ export function panelOrchestration(id: string, statuses: OrchestrationState["wor concurrency: 2, maxAttempts: 2, owner: { sessionId: "s", runtimeId: "r", generation: 0 }, - work: statuses.map((workStatus, index) => ({ id: String(index + 1), prompt: "p", status: workStatus, attemptCount: 0, dispatches: [] })), + work: statuses.map((workStatus, index) => ({ id: String(index + 1), prompt: "p", status: workStatus, attemptCount: 0, dispatches: [], ...decorate(index) })), nextWakeSequence: 1, createdAt: PANEL_NOW - 60_000, updatedAt: PANEL_NOW, diff --git a/test/orchestration-presentation.test.ts b/test/orchestration-presentation.test.ts index 4a16d9c..4eb129f 100644 --- a/test/orchestration-presentation.test.ts +++ b/test/orchestration-presentation.test.ts @@ -57,6 +57,29 @@ describe("orchestration presentation", () => { expect(orchestrationTone(state)).toBe("warning"); }); + it("E1: a listing row ends with the evidence held for the item: verify result, time and tokens", () => { + const entry = createEntry(); + const [first, second] = entry.orchestration!.work; + first!.status = "completed"; + first!.attemptCount = 1; + first!.dispatches.push({ + dispatchId: "d", attempt: 1, ownerRuntimeId: "runtime", ownerGeneration: 1, status: "completed", requestedAt: 1, agentId: "a1", consumeStatus: "provider_owned", consumeAttempts: 0, + usage: { durationMs: 421_000, tokens: { input: 160_000, output: 1_800, total: 161_800 } }, + verify: { passed: true, exitCode: 0, durationMs: 12 }, + }); + second!.status = "failed"; + second!.attemptCount = 1; + second!.dispatches.push({ dispatchId: "e", attempt: 1, ownerRuntimeId: "runtime", ownerGeneration: 1, status: "failed", requestedAt: 1, consumeStatus: "none", consumeAttempts: 0, verify: { passed: false, exitCode: 1, durationMs: 9 } }); + const before = structuredClone(entry); + const rows = orchestrationControllerText(entry).split("\n"); + // Existing fields keep their order; evidence is appended. + expect(rows.at(-2)).toBe("#1 [complete] Explore · Inspect API compatibility · agent=a1 · attempts=1 · verify ok · 7m · 161800 tokens"); + expect(rows.at(-1)).toBe("#2 [failed] Plan · Review rollout risks · attempts=1 · verify failed (exit 1)"); + expect(entry).toEqual(before); + // Control: an item with no evidence gets no evidence fields. + expect(orchestrationControllerText(createEntry()).split("\n").at(-1)).toBe("#2 [pending] Plan · Review rollout risks"); + }); + it.each(["spawning", "queued", "running"] as const)("separates reservations from %s observations", (status) => { const entry = createEntry(); const state = entry.orchestration!; diff --git a/test/progress-panel.test.ts b/test/progress-panel.test.ts index 05b9a46..e5677ed 100644 --- a/test/progress-panel.test.ts +++ b/test/progress-panel.test.ts @@ -146,14 +146,68 @@ describe("progress panel layout", () => { it("lists only orchestrations still running or needing attention, so a running batch is never crowded out", () => { const loops = [panelOrchestration("1", ["completed"], "completed"), panelOrchestration("2", ["cancelled"], "cancelled"), panelOrchestration("3", ["active"]), panelOrchestration("4", ["failed"], "needs_attention")]; - expect(text({ loops, tasks: [], now })).toEqual(["◇ #3 0/1 · 1/2 in flight", "◇ #4 0/1 needs attention"]); + expect(text({ loops, tasks: [], now }).filter((line) => line.startsWith("◇"))).toEqual(["◇ #3 0/1 · 1/2 in flight", "◇ #4 0/1 needs attention"]); expect(text({ loops: loops.slice(0, 2), tasks: [], now })).toEqual([]); }); it("summarizes orchestration progress without claiming observed execution", () => { const lines = text({ loops: [panelOrchestration("7", ["completed", "active", "pending"])], tasks: [], now }); - expect(lines).toEqual(["◇ #7 1/3 · 1/2 in flight"]); - expect(text({ loops: [panelOrchestration("8", ["failed"], "needs_attention")], tasks: [], now })).toEqual(["◇ #8 0/1 needs attention"]); + expect(lines[0]).toBe("◇ #7 1/3 · 1/2 in flight"); + expect(text({ loops: [panelOrchestration("8", ["failed"], "needs_attention")], tasks: [], now })[0]).toBe("◇ #8 0/1 needs attention"); + }); + + describe("orchestration item rows", () => { + const dispatch = (fields: Record) => ({ dispatchId: "d", attempt: 1, ownerRuntimeId: "r", ownerGeneration: 0, status: "running", requestedAt: now - 600_000, consumeStatus: "provider_owned", consumeAttempts: 0, ...fields }); + const rows = (entry: ReturnType, width = 60, max = 40) => text({ loops: [entry], tasks: [], now }, width, max); + + it("R1: lists each item under its batch, in flight first, then problems, pending and done", () => { + const entry = panelOrchestration("7", ["completed", "active", "pending", "failed"], "active", (index) => [ + { label: "seatbelt", dispatches: [dispatch({ status: "completed", startedAt: now - 600_000, settledAt: now - 180_000, usage: { durationMs: 421_000, tokens: { input: 160_000, output: 1_800, total: 161_800 } } })] }, + { label: "native-pi", attemptCount: 2, dispatches: [dispatch({ status: "failed" }), dispatch({ attempt: 2, startedAt: now - 180_000 })] }, + {}, + { label: "tls", attemptCount: 1, dispatches: [dispatch({ status: "failed" })] }, + ][index] as never); + expect(rows(entry)).toEqual([ + "◇ #7 1/4 · 1/2 in flight", + " ● running 3m · try 2 native-pi", + " ✗ failed tls", + " ○ p", + " ✓ 7m · 162k tok seatbelt", + ]); + }); + + it("R2: shows the last reported dispatch state and elapsed time, never more than was reported", () => { + const entry = panelOrchestration("7", ["active", "active", "active", "uncertain"], "active", (index) => [ + { label: "a", dispatches: [dispatch({ status: "spawning", requestedAt: now - 5_000 })] }, + { label: "b", dispatches: [dispatch({ status: "queued", requestedAt: now - 120_000 })] }, + { label: "c", dispatches: [dispatch({ status: "verifying", startedAt: now - 3_600_000 })] }, + { label: "d", dispatches: [dispatch({ status: "uncertain" })] }, + ][index] as never); + expect(rows(entry).slice(1)).toEqual([" ● starting 5s a", " ● queued 2m b", " ● verifying 1h c", " ? uncertain d"]); + }); + + it("R3: a finished item without usage evidence shows no token or duration figures", () => { + const entry = panelOrchestration("7", ["completed", "completed", "active"], "active", (index) => [ + { label: "bare", dispatches: [dispatch({ status: "completed" })] }, + { label: "timed", dispatches: [dispatch({ status: "completed", usage: { durationMs: 61_000 } })] }, + { label: "run" }, + ][index] as never); + expect(rows(entry).slice(1)).toEqual([" ● run", " ✓ bare", " ✓ 1m timed"]); + }); + + it("R4: bounds the rows of one batch and says how many are not shown", () => { + const entry = panelOrchestration("7", Array.from({ length: 9 }, () => "pending" as const)); + const lines = rows(entry); + expect(lines).toHaveLength(7); + expect(lines.at(-1)).toBe(" … 4 more"); + // A cancelled item is listed last and dimmed out, not dropped. + expect(rows(panelOrchestration("8", ["cancelled", "active"])).slice(1)).toEqual([" ● p", " – p"]); + }); + + it("R5: names an item by its label, else its prompt, with control bytes removed", () => { + const entry = panelOrchestration("7", ["pending", "pending"], "active", (index) => [{ label: "ok\u001b[31m" }, { prompt: "line one\nline\ttwo" }][index] as never); + expect(rows(entry).slice(1)).toEqual([" ○ ok [31m", " ○ line one line two"]); + }); }); it("bounds rows and width, and strips control and escape bytes", () => { diff --git a/test/property/progress-panel.property.test.ts b/test/property/progress-panel.property.test.ts index 26ce517..c132b42 100644 --- a/test/property/progress-panel.property.test.ts +++ b/test/property/progress-panel.property.test.ts @@ -52,7 +52,18 @@ const orchestration: fc.Arbitrary = fc.record({ id: fc.integer({ min: 1, max: 999 }).map(String), work: fc.array(fc.constantFrom("pending", "active", "completed", "failed", "uncertain", "cancelled"), { maxLength: 32 }), status: fc.constantFrom("active", "needs_attention", "completed", "cancelled"), -}).map(({ id, work, status }) => panelOrchestration(id, work as never, status as never)); + labels: fc.array(fc.option(hostileText, { nil: undefined }), { maxLength: 32 }), + startedAgo: fc.array(fc.option(fc.integer({ min: -86_400_000, max: 30 * 86_400_000 }), { nil: undefined }), { maxLength: 32 }), + tokens: fc.option(fc.nat(), { nil: undefined }), +}).map(({ id, work, status, labels, startedAgo, tokens }) => panelOrchestration(id, work as never, status as never, (index) => ({ + ...(labels[index] !== undefined ? { label: labels[index] } : {}), + ...(startedAgo[index] !== undefined ? { + dispatches: [{ + dispatchId: "d", attempt: 1, ownerRuntimeId: "r", ownerGeneration: 0, status: "running", requestedAt: PANEL_NOW - startedAgo[index]!, + consumeStatus: "provider_owned", consumeAttempts: 0, ...(tokens !== undefined ? { usage: { tokens: { input: tokens, output: 0, total: tokens } } } : {}), + }] as never, + } : {}), +}))); const monitor: fc.Arbitrary = fc.record({ id: fc.oneof(fc.integer({ min: 1, max: 999 }).map(String), hostileText), @@ -108,6 +119,31 @@ describe("progress panel properties", () => { ); }); + it("accounts for every work item of a shown orchestration: rows listed plus rows withheld", () => { + fc.assert( + fc.property(fc.uniqueArray(orchestration, { maxLength: 4, selector: (entry) => entry.id }), timestamp, (loops, now) => { + const lines = layoutProgressPanel({ loops, tasks: [], now }, 80, 1_000).map(panelLineText); + const shown = loops.filter((entry) => ["active", "needs_attention"].includes(entry.orchestration!.status)).slice(0, 2); + const blocks: string[][] = []; + for (const line of lines) { + if (/^◇ #\d+ /.test(line)) blocks.push([]); + else if (!line.startsWith("◇")) blocks.at(-1)!.push(line); + } + expect(blocks).toHaveLength(shown.length); + shown.forEach((entry, index) => { + const block = blocks[index]!; + const withheld = Number(block.at(-1)?.match(/^ {4}… (\d+) more$/)?.[1] ?? 0); + const listed = block.length - (withheld > 0 ? 1 : 0); + expect(listed).toBeLessThanOrEqual(5); + expect(listed + withheld).toBe(entry.orchestration!.work.length); + // No item row may read as a workflow's current state or a top-level controller row. + for (const line of block) expect(line).toMatch(/^ {2}(?:[●✗?○✓–] | {2}… )/); + }); + }), + propertyOptions(300), + ); + }); + it("keeps task, monitor, and controller rows on their own authority", () => { fc.assert( fc.property(input, (snapshot) => { diff --git a/test/widget.test.ts b/test/widget.test.ts index bddcb43..0d83e2c 100644 --- a/test/widget.test.ts +++ b/test/widget.test.ts @@ -325,6 +325,30 @@ describe("LoopWidget status rendering", () => { expect(latestStatusCall()?.[1]).toContain("◇ 1 orchestration | #1 needs attention"); }); + it("W5: repaints each minute while a batch has work in flight, and not otherwise", () => { + vi.useFakeTimers(); + try { + const entry = start(); + const list = vi.spyOn(store, "list"); + widget.update(); + // Control: pending work shows no elapsed time, so nothing needs a repaint. + expect(vi.getTimerCount()).toBe(0); + entry.orchestration!.work[0]!.status = "active"; + widget.update(); + const before = list.mock.calls.length; + vi.advanceTimersByTime(59_999); + expect(list.mock.calls.length).toBe(before); + vi.advanceTimersByTime(1); + expect(list.mock.calls.length).toBe(before + 1); + // Finished: the repaint stops with the work. + settle(entry, "completed"); + widget.update(); + expect(vi.getTimerCount()).toBe(0); + } finally { + vi.useRealTimers(); + } + }); + it("W4: finished batches do not inflate the count of later ones", () => { for (let index = 0; index < 5; index++) settle(start(), "completed"); start();