Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion docs/USAGE_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
5 changes: 5 additions & 0 deletions src/ui/orchestration-presentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
Expand Down Expand Up @@ -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;
}

Expand Down
51 changes: 50 additions & 1 deletion src/ui/progress-panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<LoopEntry["orchestration"]>["work"][number];

// What still needs watching comes first; finished work is the first to scroll out of the bounded rows.
const ITEM_ORDER: Record<WorkItem["status"], number> = { active: 0, failed: 1, uncertain: 1, pending: 2, completed: 3, cancelled: 4 };
const REPORTED_STATE: Partial<Record<WorkItem["dispatches"][number]["status"], string>> = { 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".
Expand All @@ -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")]);
}
Expand Down
2 changes: 2 additions & 0 deletions src/ui/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
11 changes: 9 additions & 2 deletions test/helpers/progress-panel-fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<PanelWorkItem> = () => ({}),
): LoopEntry {
return {
id,
prompt: "Fan out",
Expand All @@ -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,
Expand Down
Loading
Loading