diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c9b72d..59777ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Unreleased] + +- Increase the default global worker limit from 4 to 16; `PI_SUBAGENT_MAX_WORKERS` overrides and the 1 to 32 validation range are unchanged. +- Replace TUI `/subagents` notifications with a live, keyboard-driven dashboard for job navigation, per-task activity, output, usage, filtering, expansion, and confirmed cancellation. RPC retains text output. +- Surface bounded live activity for async tasks without persisting every message, and make synchronous subagent output compact by default with full details available through expansion. + ## [0.2.0] - 2026-11-26 Declarative workflow layer (spec #4, feature #3). diff --git a/README.md b/README.md index 4b8e655..36a1e06 100644 --- a/README.md +++ b/README.md @@ -116,17 +116,27 @@ Workflow authoring is documented in the `workflow-authoring` skill at `.agents/s /subagents cancel job_0001 ``` -The footer shows the number of active jobs. `/subagents` lists active and retained terminal jobs; the detailed view includes tasks, diagnostics, output, timing, and usage. +The footer shows the number of active jobs. In the TUI, `/subagents` opens a live dashboard with active jobs first. `/subagents job_0001` selects that job directly; `/subagents cancel job_0001` remains a noninteractive cancellation shortcut. Outside the TUI, list and detail commands retain their text output. + +Dashboard controls: + +- `up`/`down` or `j`/`k`: select a job; `left`/`right` or `h`/`l`: select a task or workflow step. +- `Enter`: expand or collapse the selected task's brief, activity, and output. +- `f`: switch between all jobs and active jobs only. +- `c`, then `y`: confirm cancellation of an active job; `n` or `Esc` abandons the confirmation. +- `Esc`: close the dashboard. + +The selected task shows its status, elapsed time, recent tool and assistant activity, bounded output, errors, model, and usage. The default synchronous `subagent` view is also compact: each agent reports its current status and latest activity, with full task and output details available through tool expansion (`Ctrl+O`). ## Scheduling and admission -Synchronous and asynchronous work share one FIFO scheduler. At most four child processes run globally by default. +Synchronous and asynchronous work share one FIFO scheduler. At most sixteen child processes run globally by default. ```bash export PI_SUBAGENT_MAX_WORKERS=8 ``` -Valid worker values are integers from 1 through 32. Invalid values fall back to four with a warning. A session accepts at most 64 nonterminal async jobs; excess admission fails atomically without spawning work. Cancelling or finishing jobs frees admission capacity. +Valid worker values are integers from 1 through 32. Invalid values fall back to sixteen with a warning. A session accepts at most 64 nonterminal async jobs; excess admission fails atomically without spawning work. Cancelling or finishing jobs frees admission capacity. Before admission, the extension validates all agents and directories. Relative `cwd` values resolve against the caller’s `ctx.cwd`. Agent discovery is performed separately at each task’s resolved directory, so project-local agents follow the task rather than the parent process’s incidental directory. @@ -155,7 +165,7 @@ There is no per-task execution timeout. Work runs until completion, explicit can ## Results, history, and usage -Async snapshots retain per-task final output up to 50 KiB and a valid-UTF-8 stderr tail up to 64 KiB, with explicit truncation metadata. Raw message/tool transcripts are retained for synchronous rendering but not for async history. +Async snapshots retain per-task final output up to 50 KiB and a valid-UTF-8 stderr tail up to 64 KiB, with explicit truncation metadata. Each task also retains its 20 most recent display-safe activity summaries, capped at 512 bytes each. Live message updates refresh an open dashboard without appending a session entry per message; the latest bounded activity is persisted at job and task transitions. Raw message/tool transcripts are retained for synchronous rendering but not for async history. Pi custom entries persist bounded job snapshots outside model context. Reload/resume restores them for inspection; restored unfinished jobs become `interrupted`, never runnable. `/new` starts empty. `/tree` navigation replaces terminal history from the active branch without disturbing live jobs. Active jobs plus the 50 most recent terminal jobs are retained; oldest terminal history evicts first. diff --git a/src/activity.ts b/src/activity.ts new file mode 100644 index 0000000..acadea3 --- /dev/null +++ b/src/activity.ts @@ -0,0 +1,69 @@ +import type { Message } from "@earendil-works/pi-ai"; +import { replaceControlCharacters, stripTerminalSequences } from "@earendil-works/pi-tui"; +import { truncateUtf8Head } from "./output.ts"; +import type { TaskActivity } from "./types.ts"; + +export const MAX_TASK_ACTIVITY = 20; +export const MAX_TASK_ACTIVITY_BYTES = 512; + +function clean(value: string): string { + return replaceControlCharacters(stripTerminalSequences(value)).replace(/\s+/g, " ").trim(); +} + +function bounded(value: string): string { + const normalized = clean(value); + const truncated = truncateUtf8Head(normalized, MAX_TASK_ACTIVITY_BYTES - 3); + return truncated.truncated ? `${truncated.text}...` : truncated.text; +} + +function argument(args: Record, ...names: string[]): string { + for (const name of names) { + if (typeof args[name] === "string") return args[name]; + } + return ""; +} + +function toolCallSummary(name: string, args: Record): string { + if (name === "bash") return bounded(`$ ${argument(args, "command") || "..."}`); + if (["read", "write", "edit"].includes(name)) { + return bounded(`${name} ${argument(args, "path", "file_path") || "..."}`); + } + let serialized = ""; + try { + serialized = JSON.stringify(args); + } catch { + serialized = ""; + } + return bounded(`${name}${serialized ? ` ${serialized}` : ""}`); +} + +function resultText(content: readonly { type: string; text?: string }[]): string { + const text = content.filter((part) => part.type === "text" && typeof part.text === "string"); + return text.length > 0 ? text.map((part) => part.text).join(" ") : "(no text output)"; +} + +/** Recompute a bounded tail from the runner's accumulated messages, avoiding duplicate entries on each update. */ +export function summarizeActivity(messages: readonly Message[], now: number): TaskActivity[] { + const activity: TaskActivity[] = []; + for (const message of messages) { + const timestamp = Number.isFinite(message.timestamp) ? message.timestamp : now; + if (message.role === "assistant") { + for (const part of message.content) { + if (part.type === "text") { + const summary = bounded(part.text); + if (summary) activity.push({ kind: "text", summary, timestamp }); + } else if (part.type === "toolCall") { + activity.push({ kind: "toolCall", summary: toolCallSummary(part.name, part.arguments), timestamp }); + } + } + } else if (message.role === "toolResult") { + activity.push({ + kind: "toolResult", + summary: bounded(`${message.toolName}: ${resultText(message.content)}`), + timestamp, + isError: message.isError, + }); + } + } + return activity.slice(-MAX_TASK_ACTIVITY); +} diff --git a/src/config.ts b/src/config.ts index 98f30e2..a522cf9 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,4 +1,4 @@ -export const DEFAULT_MAX_WORKERS = 4; +export const DEFAULT_MAX_WORKERS = 16; export const MAX_WORKERS_LIMIT = 32; export function readMaxWorkers(value: string | undefined): { value: number; warning?: string } { diff --git a/src/dashboard.ts b/src/dashboard.ts new file mode 100644 index 0000000..a72fa45 --- /dev/null +++ b/src/dashboard.ts @@ -0,0 +1,344 @@ +import type { KeybindingsManager } from "@earendil-works/pi-tui"; +import { + Key, + matchesKey, + replaceControlCharacters, + stripTerminalSequences, + truncateToWidth, + wrapTextWithAnsi, +} from "@earendil-works/pi-tui"; +import { formatUsageStats, type SubagentRenderTheme } from "./render.ts"; +import { isTerminalTask, type JobSnapshot, type JobStatus, type TaskSnapshot, type TaskStatus } from "./types.ts"; + +const JOB_PAGE_SIZE = 4; +const TASK_PAGE_SIZE = 4; + +type DashboardKeybindings = Pick; + +export interface SubagentDashboardOptions { + getJobs: () => JobSnapshot[]; + cancelJob: (id: string) => JobSnapshot; + initialJobId?: string; + theme: SubagentRenderTheme; + keybindings: DashboardKeybindings; + requestRender: () => void; + done: () => void; + now?: () => number; +} + +function isActive(status: JobStatus): boolean { + return status === "queued" || status === "running" || status === "cancelling"; +} + +function statusColor(status: JobStatus | TaskStatus): string { + if (status === "running") return "accent"; + if (status === "queued") return "muted"; + if (status === "cancelling") return "warning"; + if (status === "succeeded") return "success"; + if (status === "failed") return "error"; + if (status === "skipped") return "muted"; + return "warning"; +} + +function safeText(value: string): string { + return stripTerminalSequences(value) + .split("\n") + .map((line) => replaceControlCharacters(line)) + .join("\n"); +} + +function safeInline(value: string): string { + return replaceControlCharacters(stripTerminalSequences(value)).trim(); +} + +function sortedJobs(jobs: JobSnapshot[]): JobSnapshot[] { + return [...jobs].sort((a, b) => { + const activeDifference = Number(isActive(b.status)) - Number(isActive(a.status)); + return activeDifference || b.createdAt - a.createdAt || a.id.localeCompare(b.id); + }); +} + +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)"; +} + +export function formatDuration(milliseconds: number): string { + const seconds = Math.max(0, Math.floor(milliseconds / 1000)); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`; + return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`; +} + +export class SubagentDashboard { + private readonly options: SubagentDashboardOptions; + private readonly now: () => number; + private allJobs: JobSnapshot[] = []; + private jobs: JobSnapshot[] = []; + private selectedJobId?: string; + private selectedTaskIndex = 0; + private activeOnly = false; + private expanded = false; + private confirmingCancel = false; + private notice: string | undefined; + private cachedWidth: number | undefined; + private cachedLines: string[] | undefined; + private disposed = false; + + constructor(options: SubagentDashboardOptions) { + this.options = options; + this.now = options.now ?? Date.now; + this.selectedJobId = options.initialJobId; + this.loadJobs(); + } + + refresh(): void { + if (this.disposed) return; + this.loadJobs(); + this.changed(); + } + + invalidate(): void { + this.cachedWidth = undefined; + this.cachedLines = undefined; + } + + dispose(): void { + this.disposed = true; + this.invalidate(); + } + + private changed(): void { + this.invalidate(); + this.options.requestRender(); + } + + private loadJobs(): void { + const previousJobId = this.selectedJobId; + this.allJobs = sortedJobs(this.options.getJobs()); + this.jobs = this.activeOnly ? this.allJobs.filter((job) => isActive(job.status)) : this.allJobs; + if (!this.jobs.some((job) => job.id === this.selectedJobId)) this.selectedJobId = this.jobs[0]?.id; + if (previousJobId !== this.selectedJobId) { + this.selectedTaskIndex = 0; + this.expanded = false; + this.confirmingCancel = false; + } + const job = this.selectedJob(); + this.selectedTaskIndex = Math.max(0, Math.min(this.selectedTaskIndex, Math.max(0, (job?.results.length ?? 1) - 1))); + if (this.confirmingCancel && (!job || !isActive(job.status))) this.confirmingCancel = false; + } + + private selectedJob(): JobSnapshot | undefined { + return this.jobs.find((job) => job.id === this.selectedJobId); + } + + private selectedTask(): TaskSnapshot | undefined { + return this.selectedJob()?.results[this.selectedTaskIndex]; + } + + private moveJob(delta: number): void { + const current = this.jobs.findIndex((job) => job.id === this.selectedJobId); + const next = Math.max(0, Math.min(this.jobs.length - 1, Math.max(0, current) + delta)); + const selected = this.jobs[next]; + if (!selected || selected.id === this.selectedJobId) return; + this.selectedJobId = selected.id; + this.selectedTaskIndex = 0; + this.expanded = false; + this.notice = undefined; + this.changed(); + } + + private moveTask(delta: number): void { + const count = this.selectedJob()?.results.length ?? 0; + if (count === 0) return; + this.selectedTaskIndex = Math.max(0, Math.min(count - 1, this.selectedTaskIndex + delta)); + this.notice = undefined; + this.changed(); + } + + private close(): void { + if (this.disposed) return; + this.disposed = true; + this.options.done(); + } + + handleInput(data: string): void { + if (this.disposed) return; + const kb = this.options.keybindings; + const job = this.selectedJob(); + + if (this.confirmingCancel) { + if (matchesKey(data, "y") && job) { + try { + this.options.cancelJob(job.id); + this.notice = `Cancellation requested for ${job.id}`; + } catch (error) { + this.notice = error instanceof Error ? error.message : String(error); + } + this.confirmingCancel = false; + this.refresh(); + } else if (matchesKey(data, "n") || kb.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape)) { + this.confirmingCancel = false; + this.notice = "Cancellation not requested"; + this.changed(); + } + return; + } + + if (kb.matches(data, "tui.select.cancel") || matchesKey(data, Key.escape) || matchesKey(data, "ctrl+c")) { + this.close(); + return; + } + if (matchesKey(data, "f")) { + this.activeOnly = !this.activeOnly; + this.notice = undefined; + this.loadJobs(); + this.changed(); + return; + } + if (!job) return; + if (kb.matches(data, "tui.select.up") || matchesKey(data, "k")) this.moveJob(-1); + else if (kb.matches(data, "tui.select.down") || matchesKey(data, "j")) this.moveJob(1); + else if (kb.matches(data, "tui.select.pageUp")) this.moveJob(-JOB_PAGE_SIZE); + else if (kb.matches(data, "tui.select.pageDown")) this.moveJob(JOB_PAGE_SIZE); + else if (matchesKey(data, Key.left) || matchesKey(data, "h")) this.moveTask(-1); + else if (matchesKey(data, Key.right) || matchesKey(data, "l")) this.moveTask(1); + else if (kb.matches(data, "tui.select.confirm")) { + this.expanded = !this.expanded; + this.notice = undefined; + this.changed(); + } else if (matchesKey(data, "c")) { + if (isActive(job.status)) { + this.confirmingCancel = true; + this.notice = undefined; + } else { + this.notice = `${job.id} is already terminal`; + } + this.changed(); + } + } + + render(width: number): string[] { + const renderWidth = Math.max(1, width); + if (this.cachedLines && this.cachedWidth === renderWidth) return this.cachedLines; + const th = this.options.theme; + const lines: string[] = []; + const add = (line = "") => lines.push(truncateToWidth(line, renderWidth)); + const addWrapped = (value: string, color = "text", maxLines = Number.POSITIVE_INFINITY) => { + const wrapped = wrapTextWithAnsi(safeText(value), renderWidth); + for (const line of wrapped.slice(0, maxLines)) add(th.fg(color, line)); + if (wrapped.length > maxLines) add(th.fg("muted", `... ${wrapped.length - maxLines} more lines`)); + }; + + const active = this.allJobs.filter((job) => isActive(job.status)).length; + const succeeded = this.allJobs.filter((job) => job.status === "succeeded").length; + const attention = this.allJobs.filter((job) => ["failed", "cancelled", "interrupted"].includes(job.status)).length; + add(th.fg("toolTitle", th.bold("Subagents"))); + add(th.fg("muted", `${active} active | ${succeeded} succeeded | ${attention} need attention | ${this.allJobs.length} total`)); + + const job = this.selectedJob(); + if (!job) { + add(""); + add(th.fg("muted", this.allJobs.length === 0 ? "No subagent jobs." : "No active subagent jobs.")); + add(""); + add(th.fg("dim", `${this.activeOnly ? "f all jobs | " : ""}Esc close`)); + this.cachedWidth = renderWidth; + this.cachedLines = lines; + return lines; + } + + add(th.fg("dim", `${this.activeOnly ? "Active only" : "All jobs"} | ${this.jobs.length} shown`)); + const selectedJobIndex = Math.max(0, this.jobs.findIndex((item) => item.id === job.id)); + const jobStart = Math.max(0, Math.min(selectedJobIndex - Math.floor(JOB_PAGE_SIZE / 2), this.jobs.length - JOB_PAGE_SIZE)); + for (const [offset, item] of this.jobs.slice(jobStart, jobStart + JOB_PAGE_SIZE).entries()) { + const index = jobStart + offset; + const selected = index === selectedJobIndex; + const terminal = item.results.filter((task) => isTerminalTask(task.status)).length; + const elapsed = formatDuration((item.finishedAt ?? this.now()) - (item.startedAt ?? item.createdAt)); + add( + `${selected ? th.fg("accent", ">") : " "} ${th.fg(selected ? "accent" : "text", item.id)} ` + + `${th.fg(statusColor(item.status), item.status.padEnd(11))} ${item.mode.padEnd(8)} ` + + `${terminal}/${item.plannedTaskCount} done ${th.fg("dim", elapsed)}`, + ); + } + if (this.jobs.length > JOB_PAGE_SIZE) add(th.fg("dim", `${jobStart + 1}-${Math.min(jobStart + JOB_PAGE_SIZE, this.jobs.length)} of ${this.jobs.length} jobs`)); + + add(""); + add(th.fg("accent", th.bold(job.id)) + th.fg("muted", ` ${job.mode} | ${job.status} | ${job.agentScope}`)); + const started = job.startedAt ? new Date(job.startedAt).toISOString() : "not started"; + add(th.fg("dim", `Started ${started} | ${formatDuration((job.finishedAt ?? this.now()) - (job.startedAt ?? job.createdAt))}`)); + const jobUsage = formatUsageStats(job.usage); + if (jobUsage) add(th.fg("dim", `Job usage: ${jobUsage}`)); + if (job.errorMessage) addWrapped(`Job error: ${job.errorMessage}`, "error", 2); + + const taskCount = job.results.length; + this.selectedTaskIndex = Math.max(0, Math.min(this.selectedTaskIndex, Math.max(0, taskCount - 1))); + const taskStart = Math.max(0, Math.min(this.selectedTaskIndex - Math.floor(TASK_PAGE_SIZE / 2), taskCount - TASK_PAGE_SIZE)); + add(th.fg("muted", `Tasks ${taskCount}/${job.plannedTaskCount} recorded`)); + for (let index = taskStart; index < Math.min(taskStart + TASK_PAGE_SIZE, taskCount); index++) { + const item = job.results[index]; + 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))} ` + + `${th.fg(selected ? "accent" : "text", safeInline(item.agent))} ${th.fg(statusColor(item.status), `[${item.status}]`)} ` + + th.fg("dim", safeInline(latest)), + ); + } + if (taskCount > TASK_PAGE_SIZE) add(th.fg("dim", `${taskStart + 1}-${taskStart + TASK_PAGE_SIZE} of ${taskCount} tasks`)); + + const task = this.selectedTask(); + 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}`)); + 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); + const activity = task.activity ?? []; + if (activity.length > 0) { + add(th.fg("muted", "Recent activity")); + const activityLimit = this.expanded ? 8 : 3; + for (const item of activity.slice(-activityLimit)) { + const label = item.kind === "toolCall" ? "call" : item.kind === "toolResult" ? (item.isError ? "error" : "result") : "text"; + addWrapped(` ${label}: ${item.summary}`, item.isError ? "error" : "toolOutput", this.expanded ? 3 : 1); + } + if (activity.length > activityLimit) add(th.fg("dim", `${activity.length - activityLimit} earlier activities retained in history`)); + } + add(th.fg("muted", "Output")); + addWrapped(taskOutput(task), task.status === "failed" ? "error" : "toolOutput", this.expanded ? 12 : 3); + if (task.outputTruncated) add(th.fg("warning", `Output truncated: ${task.outputBytesOmitted} bytes omitted`)); + if (task.stderrTruncated) add(th.fg("warning", "stderr truncated; retained tail only")); + const usage = formatUsageStats(task.usage, task.model); + if (usage) add(th.fg("dim", usage)); + } else { + add(th.fg("muted", "No tasks started yet.")); + } + + if (this.notice) add(th.fg("warning", this.notice)); + add(""); + if (this.confirmingCancel) { + add(th.fg("warning", th.bold(`Cancel ${job.id}?`)) + th.fg("dim", " y confirm | n/Esc back")); + } else { + const cancelHint = isActive(job.status) ? " | c cancel" : ""; + add(th.fg("dim", `up/down jobs | left/right tasks | Enter ${this.expanded ? "less" : "more"} | f ${this.activeOnly ? "all" : "active"}${cancelHint} | Esc close`)); + } + + this.cachedWidth = renderWidth; + this.cachedLines = lines; + return lines; + } +} diff --git a/src/index.ts b/src/index.ts index f49ad45..f07ca9b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ import { } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; import { readMaxWorkers, readMaxWorkflowItems } from "./config.ts"; +import { SubagentDashboard } from "./dashboard.ts"; 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"; @@ -104,6 +105,7 @@ 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); let currentContext: ExtensionContext | undefined; + let activeDashboard: SubagentDashboard | undefined; let configurationWarnings = [workerConfig.warning, workflowItemsConfig.warning].filter( (warning): warning is string => warning !== undefined, ); @@ -118,6 +120,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { maxWorkers: workerConfig.value, onJobChange: (job) => { updateStatus(); + activeDashboard?.refresh(); if (!currentContext) return; try { pi.appendEntry(SUBAGENT_JOB_ENTRY, persistedJob(currentContext.sessionManager.getSessionId(), job)); @@ -125,6 +128,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { // Ephemeral sessions and persistence failures do not change job execution. } }, + onJobActivity: () => activeDashboard?.refresh(), onWorkflowJournal: (journal) => { if (!currentContext) return; try { @@ -169,6 +173,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { pi.on("session_shutdown", async () => { await manager.shutdown(); + activeDashboard = undefined; updateStatus(); currentContext = undefined; }); @@ -176,6 +181,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { pi.on("session_tree", (_event, ctx) => { currentContext = ctx; manager.replaceHistory(extractJobSnapshots(ctx.sessionManager.getBranch())); + activeDashboard?.refresh(); updateStatus(ctx); }); @@ -329,17 +335,43 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { }, }); + async function showSubagents(ctx: ExtensionContext, jobId?: string): Promise { + if (ctx.mode !== "tui") { + ctx.ui.notify(jobId ? formatJob(manager.get(jobId)) : formatJobList(manager.list()), "info"); + return; + } + if (jobId) manager.get(jobId); + let dashboard: SubagentDashboard | undefined; + try { + await ctx.ui.custom((tui, theme, keybindings, done) => { + dashboard = new SubagentDashboard({ + getJobs: () => manager.list(), + cancelJob: (id) => manager.cancel(id), + initialJobId: jobId, + theme, + keybindings, + requestRender: () => tui.requestRender(), + done: () => done(), + }); + activeDashboard = dashboard; + return dashboard; + }); + } finally { + if (activeDashboard === dashboard) activeDashboard = undefined; + } + } + pi.registerCommand("subagents", { - description: "List, inspect, or cancel async subagents: /subagents [job-id | cancel job-id]", + description: "Browse, inspect, or cancel async subagents: /subagents [job-id | cancel job-id]", handler: async (args, ctx) => { const parts = args.trim().split(/\s+/).filter(Boolean); try { if (parts.length === 0) { - ctx.ui.notify(formatJobList(manager.list()), "info"); + await showSubagents(ctx); return; } if (parts.length === 1) { - ctx.ui.notify(formatJob(manager.get(parts[0])), "info"); + await showSubagents(ctx, parts[0]); return; } if (parts.length === 2 && parts[0] === "cancel") { diff --git a/src/manager.ts b/src/manager.ts index 51d1acb..2df3131 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -1,3 +1,5 @@ +import { summarizeActivity } from "./activity.ts"; +import { DEFAULT_MAX_WORKERS } from "./config.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; import { buildWorkflowJournal, type WorkflowJournal } from "./journal.ts"; import { @@ -22,7 +24,6 @@ import { import type { PreparedWorkflowInvocation, WorkflowRunSpec, WorkflowStartResult } from "./workflow.ts"; import { WorkflowSupervisor } from "./workflow-supervisor.ts"; -const DEFAULT_MAX_WORKERS = 4; const DEFAULT_MAX_ACTIVE_JOBS = 64; const DEFAULT_HISTORY_LIMIT = 50; const DEFAULT_WAIT_SECONDS = 30; @@ -90,6 +91,7 @@ export class SubagentManager { private readonly historyLimit: number; private readonly now: () => number; private readonly onJobChange?: (snapshot: JobSnapshot) => void; + private readonly onJobActivity?: (snapshot: JobSnapshot) => void; private readonly onWorkflowJournal?: (journal: WorkflowJournal) => void; /** DAG supervision for workflow runs; the pool and lifecycle stay here. */ private readonly workflows: WorkflowSupervisor; @@ -108,6 +110,7 @@ export class SubagentManager { this.historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT; this.now = options.now ?? Date.now; this.onJobChange = options.onJobChange; + this.onJobActivity = options.onJobActivity; this.onWorkflowJournal = options.onWorkflowJournal; this.workflows = new WorkflowSupervisor( { @@ -479,20 +482,25 @@ export class SubagentManager { if (execution.status === "queued") { execution.status = "running"; execution.startedAt = this.now(); - this.emit(execution); } + this.emit(execution); this.emitSync(execution); try { const result = await this.runner.run(task.prepared, execution.request.dispatchDefaults, { signal: controller.signal, onUpdate: (partial) => { - if (execution.isAsync) return; partial.status = "running"; + if (execution.isAsync) { + this.updateSnapshotFromResult(task, partial); + this.emitActivity(execution); + return; + } task.result = partial; this.emitSync(execution); }, }); this.applyResult(execution, task, result); + this.emit(execution); this.emitSync(execution); resolve(result); } catch (error) { @@ -502,6 +510,8 @@ export class SubagentManager { errorMessage: error instanceof Error ? error.message : String(error), }; this.applyResult(execution, task, result); + this.emit(execution); + this.emitSync(execution); resolve(result); } finally { this.liveWorkers--; @@ -509,6 +519,21 @@ export class SubagentManager { } } + private updateSnapshotFromResult(task: InternalTask, result: RunResult): void { + const output = truncateUtf8Head(result.output, MAX_TASK_OUTPUT_BYTES); + task.snapshot.output = output.text; + task.snapshot.outputTruncated = output.truncated; + task.snapshot.outputBytesOmitted = output.bytesOmitted; + task.snapshot.stderr = result.stderr; + task.snapshot.stderrTruncated = result.stderrTruncated ?? false; + task.snapshot.usage = { ...result.usage }; + task.snapshot.model = result.model; + task.snapshot.stopReason = result.stopReason; + task.snapshot.errorMessage = result.errorMessage; + task.snapshot.terminationSignal = result.terminationSignal; + if (result.messages.length > 0) task.snapshot.activity = summarizeActivity(result.messages, this.now()); + } + private applyResult(execution: Execution, task: InternalTask, result: RunResult): void { const settled = execution.isAsync ? { ...result, messages: [] } : result; task.result = { ...settled, ...taskIdentityExtras(task.prepared) }; @@ -519,17 +544,7 @@ export class SubagentManager { task.snapshot.status = execution.cancelRequested ? "cancelled" : failed(result) ? "failed" : "succeeded"; task.result.status = task.snapshot.status; task.snapshot.exitCode = result.exitCode; - const output = truncateUtf8Head(result.output, MAX_TASK_OUTPUT_BYTES); - task.snapshot.output = output.text; - task.snapshot.outputTruncated = output.truncated; - task.snapshot.outputBytesOmitted = output.bytesOmitted; - task.snapshot.stderr = result.stderr; - task.snapshot.stderrTruncated = result.stderrTruncated ?? false; - task.snapshot.usage = { ...result.usage }; - task.snapshot.model = result.model; - task.snapshot.stopReason = result.stopReason; - task.snapshot.errorMessage = result.errorMessage; - task.snapshot.terminationSignal = result.terminationSignal; + this.updateSnapshotFromResult(task, result); task.snapshot.finishedAt = this.now(); } @@ -594,6 +609,15 @@ export class SubagentManager { }); } + private emitActivity(execution: Execution): void { + if (!execution.isAsync) return; + try { + this.onJobActivity?.(this.snapshot(execution)); + } catch { + // Transient UI observers cannot interrupt scheduling. + } + } + private emit(execution: Execution): void { if (!execution.isAsync) return; try { diff --git a/src/persistence.ts b/src/persistence.ts index 101bc8d..e9d7b2c 100644 --- a/src/persistence.ts +++ b/src/persistence.ts @@ -37,6 +37,16 @@ function validUsage(value: unknown): boolean { return record(value) && usageKeys.every((key) => typeof value[key] === "number" && Number.isFinite(value[key])); } +function validActivity(value: unknown): boolean { + return Array.isArray(value) && value.every((item) => + record(item) + && (item.kind === "text" || item.kind === "toolCall" || item.kind === "toolResult") + && typeof item.summary === "string" + && typeof item.timestamp === "number" && Number.isFinite(item.timestamp) + && (item.isError === undefined || typeof item.isError === "boolean") + ); +} + function validTask(value: unknown): boolean { if (!record(value)) return false; return typeof value.agent === "string" @@ -53,6 +63,7 @@ function validTask(value: unknown): boolean { && typeof value.outputBytesOmitted === "number" && typeof value.stderr === "string" && typeof value.stderrTruncated === "boolean" + && (value.activity === undefined || validActivity(value.activity)) && validUsage(value.usage); } diff --git a/src/render.ts b/src/render.ts index 5a2c85a..59e4728 100644 --- a/src/render.ts +++ b/src/render.ts @@ -11,13 +11,12 @@ import type { Message } from "@earendil-works/pi-ai"; import { formatReadLineRange, getMarkdownTheme } from "@earendil-works/pi-coding-agent"; import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui"; import { truncateUtf8Head } from "./output.ts"; +import { summarizeActivity } from "./activity.ts"; import type { RunResult, SubagentDetails, TaskStatus, UsageStats } from "./types.ts"; export const PER_TASK_OUTPUT_CAP = 50 * 1024; export const PARALLEL_OUTPUT_CAP_BYTES = PER_TASK_OUTPUT_CAP; -const COLLAPSED_ITEM_COUNT = 10; - export interface SubagentRenderTheme { fg(color: any, text: string): string; bold(text: string): string; @@ -334,6 +333,20 @@ function resultStatusIcon(result: RunResult, theme: SubagentRenderTheme): string : theme.fg("success", "✓"); } +function collapsedStatus(result: RunResult, running: boolean): string { + if (running) return result.status === "queued" ? "queued" : "running"; + return result.status ?? (isFailedResult(result) ? "failed" : "succeeded"); +} + +function collapsedActivity(result: RunResult, running: boolean, theme: SubagentRenderTheme): string { + if (!running && isFailedResult(result) && result.errorMessage) return theme.fg("error", `Error: ${result.errorMessage}`); + const latest = summarizeActivity(result.messages ?? [], 0).at(-1); + if (latest) return theme.fg(latest.isError ? "error" : "toolOutput", latest.summary); + const output = resultOutput(result); + if (output) return theme.fg("toolOutput", output.split("\n").find((line) => line.trim()) ?? output); + return theme.fg("muted", running ? "(waiting for activity)" : "(no output)"); +} + export function renderSubagentResult( result: SubagentResultLike, options: SubagentRenderOptions, @@ -353,33 +366,18 @@ export function renderSubagentResult( const mdTheme = getMarkdownTheme(); const fg = (color: string, text: string) => theme.fg(color, text); - const renderDisplayItems = (items: DisplayItem[], limit?: number) => { - const toShow = limit ? items.slice(-limit) : items; - const skipped = limit && items.length > limit ? items.length - limit : 0; - let text = ""; - if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`); - for (const item of toShow) { - if (item.type === "text") { - const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n"); - text += `${theme.fg("toolOutput", preview)}\n`; - } else { - text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, fg)}\n`; - } - } - return text.trimEnd(); - }; - if (mode === "single" && results.length === 1) { const r = results[0]; const running = resultIsRunning(r, overallActive); const isError = !running && isFailedResult(r); - const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓"); + const icon = running ? theme.fg("warning", "…") : isError ? theme.fg("error", "✗") : theme.fg("success", "✓"); + const statusSuffix = running ? theme.fg("warning", ` [${collapsedStatus(r, true)}]`) : ""; const displayItems = getDisplayItems(r.messages); const finalOutput = resultOutput(r); if (expanded) { const container = new Container(); - let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`; + let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}${statusSuffix}`; if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`; container.addChild(new Text(header, 0, 0)); if (isError && r.errorMessage) container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0)); @@ -410,28 +408,22 @@ export function renderSubagentResult( return container; } - let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`; + let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}${statusSuffix}`; if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`; - if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`; - else if (displayItems.length === 0) { - if (finalOutput) { - const preview = finalOutput.split("\n").slice(0, 3).join("\n"); - text += `\n${theme.fg("toolOutput", preview)}`; - } else { - text += `\n${theme.fg("muted", "(no output)")}`; - } - } else { - text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`; - if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`; - } + text += `\n${collapsedActivity(r, running, theme)}`; + text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`; const usageStr = formatUsageStats(r.usage, r.model); if (usageStr) text += `\n${theme.fg("dim", usageStr)}`; return new Text(text, 0, 0); } if (mode === "chain") { - const successCount = results.filter((r) => !isFailedResult(r)).length; - const icon = successCount === results.length ? theme.fg("success", "✓") : theme.fg("error", "✗"); + const successCount = results.filter(isSuccessfulResult).length; + const icon = overallActive + ? theme.fg("warning", "…") + : successCount === results.length + ? theme.fg("success", "✓") + : theme.fg("error", "✗"); if (expanded) { const container = new Container(); @@ -447,13 +439,19 @@ export function renderSubagentResult( ); for (const r of results) { - const rIcon = resultStatusIcon(r, theme); + const rRunning = resultIsRunning(r, overallActive); + const rIcon = rRunning ? theme.fg("warning", "…") : resultStatusIcon(r, theme); const displayItems = getDisplayItems(r.messages); const finalOutput = resultOutput(r); container.addChild(new Spacer(1)); container.addChild( - new Text(`${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0), + new Text( + `${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}` + + (rRunning ? theme.fg("warning", ` [${collapsedStatus(r, true)}]`) : ""), + 0, + 0, + ), ); container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0)); @@ -485,19 +483,11 @@ export function renderSubagentResult( let text = icon + " " + theme.fg("toolTitle", theme.bold("chain ")) + theme.fg("accent", `${successCount}/${results.length} steps`); for (const r of results) { - const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓"); - const displayItems = getDisplayItems(r.messages); - const finalOutput = resultOutput(r); - text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`; - if (displayItems.length === 0) { - if (finalOutput) { - text += `\n${theme.fg("toolOutput", finalOutput.split("\n").slice(0, 3).join("\n"))}`; - } else { - text += `\n${theme.fg("muted", "(no output)")}`; - } - } else { - text += `\n${renderDisplayItems(displayItems, 5)}`; - } + const rRunning = resultIsRunning(r, overallActive); + const rIcon = rRunning ? theme.fg("warning", "…") : resultStatusIcon(r, theme); + text += `\n${rIcon} ${theme.fg("muted", `Step ${r.step}: `)}${theme.fg("accent", r.agent)}`; + text += ` ${theme.fg(rRunning ? "warning" : "muted", `[${collapsedStatus(r, rRunning)}]`)}`; + text += `\n ${collapsedActivity(r, rRunning, theme)}`; } const usageStr = formatUsageStats(aggregateUsage(results)); if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`; @@ -506,33 +496,47 @@ export function renderSubagentResult( } if (mode === "parallel" || mode === "workflow") { - const running = results.filter((r) => resultIsRunning(r, overallActive)).length; + const running = results.filter((r) => resultIsRunning(r, overallActive) && r.status !== "queued").length; + const queued = results.filter((r) => r.status === "queued").length; + const active = running + queued; + const settled = results.filter((r) => !resultIsRunning(r, overallActive)).length; const successCount = results.filter((r) => !resultIsRunning(r, overallActive) && isSuccessfulResult(r)).length; const failCount = results.filter((r) => !resultIsRunning(r, overallActive) && isFailedResult(r)).length; - const isRunning = running > 0; - const icon = isRunning - ? theme.fg("warning", "⏳") + const icon = active > 0 + ? theme.fg("warning", "…") : failCount > 0 ? theme.fg("warning", "◐") : theme.fg("success", "✓"); const unit = mode === "workflow" ? "steps" : "tasks"; - const status = isRunning - ? `${successCount + failCount}/${results.length} done, ${running} running` - : `${successCount}/${results.length} ${unit}`; + const status = active > 0 + ? [ + `${settled}/${results.length} done`, + running > 0 ? `${running} running` : "", + queued > 0 ? `${queued} queued` : "", + ].filter(Boolean).join(", ") + : `${successCount}/${results.length} ${unit}${failCount > 0 ? `, ${failCount} failed` : ""}`; - if (expanded && !isRunning) { + if (expanded) { const container = new Container(); container.addChild( new Text(`${icon} ${theme.fg("toolTitle", theme.bold(`${mode} `))}${theme.fg("accent", status)}`, 0, 0), ); for (const r of results) { - const rIcon = resultStatusIcon(r, theme); + const rRunning = resultIsRunning(r, overallActive); + const rIcon = rRunning ? theme.fg("warning", "…") : resultStatusIcon(r, theme); const displayItems = getDisplayItems(r.messages); const finalOutput = resultOutput(r); container.addChild(new Spacer(1)); - container.addChild(new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0)); + container.addChild( + new Text( + `${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}` + + (rRunning ? theme.fg("warning", ` [${collapsedStatus(r, true)}]`) : ""), + 0, + 0, + ), + ); container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0)); for (const item of displayItems) { @@ -561,23 +565,15 @@ export function renderSubagentResult( } let text = `${icon} ${theme.fg("toolTitle", theme.bold(`${mode} `))}${theme.fg("accent", status)}`; - for (const r of results) { + for (const [index, r] of results.entries()) { const rRunning = resultIsRunning(r, overallActive); - const rIcon = rRunning ? theme.fg("warning", "⏳") : resultStatusIcon(r, theme); - const displayItems = getDisplayItems(r.messages); - const finalOutput = resultOutput(r); - text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`; - if (displayItems.length === 0) { - if (finalOutput) { - text += `\n${theme.fg("toolOutput", finalOutput.split("\n").slice(0, 3).join("\n"))}`; - } else { - text += `\n${theme.fg("muted", rRunning ? "(running...)" : "(no output)")}`; - } - } else { - text += `\n${renderDisplayItems(displayItems, 5)}`; - } + const rIcon = rRunning ? theme.fg("warning", "…") : resultStatusIcon(r, theme); + const workflowLabel = r.stepId ? `${r.stepId}${r.item !== undefined ? ` item ${r.item}` : ""}: ` : ""; + const label = mode === "workflow" ? `${workflowLabel}${r.agent}` : `${index + 1}. ${r.agent}`; + text += `\n${rIcon} ${theme.fg("accent", label)} ${theme.fg(rRunning ? "warning" : "muted", `[${collapsedStatus(r, rRunning)}]`)}`; + text += `\n ${collapsedActivity(r, rRunning, theme)}`; } - if (!isRunning) { + if (active === 0) { const usageStr = formatUsageStats(aggregateUsage(results)); if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`; } diff --git a/src/types.ts b/src/types.ts index cffecd3..786d927 100644 --- a/src/types.ts +++ b/src/types.ts @@ -76,6 +76,16 @@ export interface TaskRunner { run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise; } +export type TaskActivityKind = "text" | "toolCall" | "toolResult"; + +/** A bounded, display-safe summary of one child message or tool interaction. */ +export interface TaskActivity { + kind: TaskActivityKind; + summary: string; + timestamp: number; + isError?: boolean; +} + export interface TaskSnapshot { agent: string; agentSource: "user" | "project" | "unknown"; @@ -98,6 +108,8 @@ export interface TaskSnapshot { stopReason?: string; errorMessage?: string; terminationSignal?: string; + /** Recent display activity. Optional for snapshots persisted before activity was added. */ + activity?: TaskActivity[]; startedAt?: number; finishedAt?: number; } @@ -158,6 +170,7 @@ export function emptyTaskSnapshot(prepared: PreparedTask): TaskSnapshot { outputBytesOmitted: 0, stderr: "", stderrTruncated: false, + activity: [], usage: emptyUsage(), }; } @@ -204,6 +217,8 @@ export interface ManagerOptions { historyLimit?: number; now?: () => number; onJobChange?: (snapshot: JobSnapshot) => void; + /** Transient progress for open views. Unlike onJobChange, this is not persisted per message. */ + onJobActivity?: (snapshot: JobSnapshot) => void; /** Called once per workflow run, when it reaches a terminal state. */ onWorkflowJournal?: (journal: WorkflowJournal) => void; } diff --git a/test/activity.test.ts b/test/activity.test.ts new file mode 100644 index 0000000..da0d661 --- /dev/null +++ b/test/activity.test.ts @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { AssistantMessage, Message } from "@earendil-works/pi-ai"; +import { MAX_TASK_ACTIVITY, MAX_TASK_ACTIVITY_BYTES, summarizeActivity } from "../src/activity.ts"; + +function assistantMessage(content: AssistantMessage["content"], timestamp: number): AssistantMessage { + return { + role: "assistant", + content, + api: "fake" as AssistantMessage["api"], + provider: "fake" as AssistantMessage["provider"], + model: "fake-model", + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "stop", + timestamp, + }; +} + +test("summarizes assistant text, tool calls, and tool results in order", () => { + const messages: Message[] = [ + assistantMessage([ + { type: "text", text: " I'll inspect\nthe code. " }, + { type: "toolCall", id: "call-1", name: "read", arguments: { path: "src/index.ts" } }, + ], 100), + { + role: "toolResult", + toolCallId: "call-1", + toolName: "read", + content: [{ type: "text", text: "file contents" }], + isError: false, + timestamp: 101, + }, + ]; + + assert.deepEqual(summarizeActivity(messages, 999), [ + { kind: "text", summary: "I'll inspect the code.", timestamp: 100 }, + { kind: "toolCall", summary: "read src/index.ts", timestamp: 100 }, + { kind: "toolResult", summary: "read: file contents", timestamp: 101, isError: false }, + ]); +}); + +test("activity keeps only a bounded, display-safe UTF-8 tail", () => { + const messages = Array.from({ length: MAX_TASK_ACTIVITY + 5 }, (_, index) => + assistantMessage([{ type: "text", text: `message ${index}` }], index), + ); + const long = summarizeActivity([ + assistantMessage([{ + type: "text", + text: `\u001b[31m${"é".repeat(MAX_TASK_ACTIVITY_BYTES)}\u001b[0m`, + }], 0), + ], 999); + + const activity = summarizeActivity(messages, 999); + assert.equal(activity.length, MAX_TASK_ACTIVITY); + assert.equal(activity[0].summary, "message 5"); + assert.equal(activity.at(-1)?.summary, `message ${MAX_TASK_ACTIVITY + 4}`); + + assert.ok(Buffer.byteLength(long[0].summary, "utf8") <= MAX_TASK_ACTIVITY_BYTES); + assert.equal(long[0].summary.includes("\u001b"), false); + assert.equal(long[0].summary.includes("\uFFFD"), false); +}); \ No newline at end of file diff --git a/test/config.test.ts b/test/config.test.ts index c15992d..3ce6616 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -2,13 +2,13 @@ import assert from "node:assert/strict"; import test from "node:test"; import { readMaxWorkflowItems, readMaxWorkers } from "../src/config.ts"; -test("worker configuration accepts only integers from 1 through 32", () => { - assert.deepEqual(readMaxWorkers(undefined), { value: 4 }); +test("worker configuration defaults to 16 and accepts only integers from 1 through 32", () => { + assert.deepEqual(readMaxWorkers(undefined), { value: 16 }); assert.deepEqual(readMaxWorkers("1"), { value: 1 }); assert.deepEqual(readMaxWorkers("32"), { value: 32 }); for (const invalid of ["0", "33", "-1", "1.5", "four", " 4"]) { const result = readMaxWorkers(invalid); - assert.equal(result.value, 4); + assert.equal(result.value, 16); assert.match(result.warning ?? "", /PI_SUBAGENT_MAX_WORKERS/); } }); diff --git a/test/dashboard.test.ts b/test/dashboard.test.ts new file mode 100644 index 0000000..a71466c --- /dev/null +++ b/test/dashboard.test.ts @@ -0,0 +1,201 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { SubagentDashboard } from "../src/dashboard.ts"; +import { visibleWidth } from "@earendil-works/pi-tui"; +import { emptyUsage, type JobSnapshot, type TaskSnapshot } from "../src/types.ts"; + +const theme = { + fg: (_color: any, text: string) => text, + bold: (text: string) => text, +}; + +const keybindings = { + matches(data: string, keybinding: string) { + return data === keybinding; + }, +}; + +function task(overrides: Partial = {}): TaskSnapshot { + return { + agent: "scout", + agentSource: "user", + task: "inspect the code", + cwd: "/tmp", + status: "running", + exitCode: null, + output: "working", + outputTruncated: false, + outputBytesOmitted: 0, + stderr: "", + stderrTruncated: false, + usage: emptyUsage(), + activity: [{ kind: "toolCall", summary: "$ npm test", timestamp: 100 }], + startedAt: 1_000, + ...overrides, + }; +} + +function job(overrides: Partial = {}): JobSnapshot { + return { + id: "job_0001", + mode: "parallel", + agentScope: "user", + projectAgentsDir: null, + projectAgentsDirs: [], + status: "running", + plannedTaskCount: 1, + results: [task()], + usage: emptyUsage(), + createdAt: 1_000, + startedAt: 1_000, + ...overrides, + }; +} + +function dashboard(jobs: JobSnapshot[], overrides: Record = {}) { + return new SubagentDashboard({ + getJobs: () => jobs, + cancelJob: (id: string) => { + throw new Error(`Unexpected cancellation: ${id}`); + }, + theme, + keybindings, + requestRender: () => {}, + done: () => {}, + now: () => 12_000, + ...overrides, + }); +} + +test("dashboard leads with active work and shows the selected task's latest activity", () => { + const view = dashboard([ + job({ + id: "job_0002", + status: "failed", + results: [task({ status: "failed", output: "boom", activity: [] })], + createdAt: 2_000, + }), + job(), + ]); + + const text = view.render(120).join("\n"); + assert.match(text, /Subagents/); + assert.match(text, /1 active/); + assert.ok(text.indexOf("job_0001") < text.indexOf("job_0002")); + assert.match(text, /\$ npm test/); + assert.match(text, /working/); +}); + +test("cancellation requires confirmation and terminal jobs cannot be cancelled", () => { + let jobs = [job()]; + const cancelled: string[] = []; + let closed = 0; + const view = dashboard(jobs, { + getJobs: () => jobs, + cancelJob: (id: string) => { + cancelled.push(id); + jobs = [{ ...jobs[0], status: "cancelling" }]; + return jobs[0]; + }, + done: () => { closed++; }, + }); + + view.handleInput("c"); + assert.match(view.render(100).join("\n"), /Cancel job_0001\?/); + assert.deepEqual(cancelled, []); + view.handleInput("n"); + assert.match(view.render(100).join("\n"), /not requested/); + + view.handleInput("c"); + view.handleInput("y"); + assert.deepEqual(cancelled, ["job_0001"]); + assert.match(view.render(100).join("\n"), /Cancellation requested/); + assert.match(view.render(100).join("\n"), /cancelling/); + + const terminal = dashboard([job({ status: "succeeded" })], { + cancelJob: (id: string) => { throw new Error(`Unexpected ${id}`); }, + }); + terminal.handleInput("c"); + assert.match(terminal.render(100).join("\n"), /already terminal/); + terminal.handleInput("tui.select.cancel"); + view.handleInput("tui.select.cancel"); + assert.equal(closed, 1); +}); + +test("navigation, expansion, filtering, and refresh preserve a coherent selection", () => { + let jobs = [ + job({ results: [task(), task({ agent: "reviewer", output: "second output", activity: [] })] , plannedTaskCount: 2 }), + job({ id: "job_0002", status: "failed", createdAt: 2_000, results: [task({ status: "failed", output: "boom", activity: [] })] }), + ]; + let renders = 0; + const view = dashboard(jobs, { getJobs: () => jobs, requestRender: () => { renders++; } }); + + view.handleInput("\x1b[C"); + assert.match(view.render(100).join("\n"), /second output/); + view.handleInput("tui.select.down"); + assert.match(view.render(100).join("\n"), /> job_0002/); + assert.match(view.render(100).join("\n"), /boom/); + view.handleInput("tui.select.confirm"); + assert.match(view.render(100).join("\n"), /Enter less/); + + jobs = [job({ id: "job_0003", createdAt: 3_000 }), ...jobs]; + view.refresh(); + assert.match(view.render(100).join("\n"), /> job_0002/); + assert.ok(renders > 0); + + view.handleInput("f"); + assert.doesNotMatch(view.render(100).join("\n"), /job_0002/); + jobs = jobs.map((item) => isActiveForTest(item) ? { ...item, status: "succeeded", finishedAt: 12_000 } : item); + view.refresh(); + assert.match(view.render(100).join("\n"), /No active subagent jobs/); + view.handleInput("f"); + assert.match(view.render(100).join("\n"), /job_0002/); +}); + +test("dashboard fits narrow widths and strips terminal controls from child output", () => { + const view = dashboard([job({ + results: [task({ + task: "审查 the implementation", + output: "\u001b[31mwide 中文 output\u001b[0m\nsecond line", + activity: [{ kind: "text", summary: "\u001b[31m reading 中文日本語 \u001b[0m", timestamp: 100 }], + })], + })]); + + for (const width of [20, 32, 80]) { + const lines = view.render(width); + for (const line of lines) { + assert.ok(visibleWidth(line) <= width, `width ${width}: ${line}`); + assert.equal(line.includes("\u001b[31m"), false, JSON.stringify(line)); + } + } +}); + +function isActiveForTest(item: JobSnapshot): boolean { + return item.status === "queued" || item.status === "running" || item.status === "cancelling"; +} + +test("empty and restored job states remain inspectable", () => { + const empty = dashboard([]); + assert.match(empty.render(60).join("\n"), /No subagent jobs/); + empty.handleInput("f"); + assert.match(empty.render(60).join("\n"), /No subagent jobs/); + + const restored = dashboard([ + job({ + id: "job_restored", + mode: "workflow", + status: "interrupted", + results: [task({ + stepId: "scan", + item: 2, + status: "interrupted", + output: "partial result", + errorMessage: "Interrupted by session restart", + })], + }), + ]); + const text = restored.render(100).join("\n"); + assert.match(text, /Step scan item 2/); + assert.match(text, /Interrupted by session restart/); + assert.match(text, /partial result/); +}); diff --git a/test/extension.test.ts b/test/extension.test.ts index f7986e8..2635e4c 100644 --- a/test/extension.test.ts +++ b/test/extension.test.ts @@ -4,13 +4,14 @@ import * as os from "node:os"; import * as path from "node:path"; import test from "node:test"; import type { AgentToolResult } from "@earendil-works/pi-agent-core"; +import type { Message } from "@earendil-works/pi-ai"; import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent"; import { Value } from "typebox/value"; import registerExtension from "../src/index.ts"; import { extractJobSnapshots } from "../src/persistence.ts"; import { WorkflowParams } from "../src/schemas.ts"; import type { WorkflowStartResult } from "../src/workflow.ts"; -import { FakeRunner } from "./helpers.ts"; +import { FakeRunner, result as makeResult } from "./helpers.ts"; type Execute = (id: string, params: any, signal?: AbortSignal, onUpdate?: unknown, ctx?: ExtensionToolContext) => Promise>; @@ -37,6 +38,9 @@ async function harness(initialEntries: unknown[] = [], options: HarnessOptions = const events = new Map unknown>(); const entries: unknown[] = []; const notifications: string[] = []; + const customComponents: any[] = []; + const customClosers: Array<() => void> = []; + let customRenders = 0; const statuses = new Map(); const confirmations: Confirmation[] = []; const confirmAnswers = Array.isArray(options.confirmResult) ? [...options.confirmResult] : undefined; @@ -64,6 +68,18 @@ async function harness(initialEntries: unknown[] = [], options: HarnessOptions = }, notify: (text: string) => { notifications.push(text); }, setStatus: (key: string, text: string | undefined) => { statuses.set(key, text); }, + custom: (factory: (tui: any, theme: any, keybindings: any, done: () => void) => any) => { + return new Promise((resolve) => { + const component = factory( + { requestRender: () => { customRenders++; } }, + { fg: (_color: string, text: string) => text, bold: (text: string) => text }, + { matches: (data: string, keybinding: string) => data === keybinding }, + () => resolve(), + ); + customComponents.push(component); + customClosers.push(() => resolve()); + }); + }, }, sessionManager: { getBranch: () => branch, @@ -73,6 +89,9 @@ async function harness(initialEntries: unknown[] = [], options: HarnessOptions = return { cwd, runner, tools, commands, events, entries, notifications, statuses, confirmations, ctx, + customComponents, + getCustomRenders: () => customRenders, + closeCustom: () => customClosers.pop()?.(), setBranch: (entries: unknown[]) => { branch = entries; }, }; } @@ -128,8 +147,12 @@ test("Pi adapters preserve sync results and expose async failure/cancel/interrup assert.notEqual(failed.isError, true); assert.match(extractJobSnapshots(h.entries).at(-1)?.status ?? "", /failed/); - await h.commands.get("subagents")!("", h.ctx); - assert.match(h.notifications.at(-1) ?? "", new RegExp(jobId)); + const listing = h.commands.get("subagents")!("", h.ctx); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(h.customComponents.length, 1); + assert.match(h.customComponents[0].render(120).join("\n"), new RegExp(jobId)); + h.closeCustom(); + await listing; const second = await h.tools.get("subagent_async")!.execute("async-2", params, undefined, undefined, h.ctx); const secondId = (second.details as any).job.id as string; @@ -155,6 +178,47 @@ test("Pi adapters preserve sync results and expose async failure/cancel/interrup } }); +test("subagents opens a selected job in the TUI and keeps text output in RPC", async () => { + const h = await harness(); + try { + await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx); + const started = await h.tools.get("subagent_async")!.execute("async", params, undefined, undefined, h.ctx); + const jobId = (started.details as any).job.id as string; + + const opening = h.commands.get("subagents")!(jobId, h.ctx); + await new Promise((resolve) => setImmediate(resolve)); + const component = h.customComponents[0]; + assert.match(component.render(120).join("\n"), new RegExp(`> ${jobId}`)); + const rendersBeforeProgress = h.getCustomRenders(); + const pending = h.runner.calls[0]; + pending.options.onUpdate?.({ + ...makeResult(pending.task, "live output"), + status: "running", + exitCode: null, + messages: [{ + role: "assistant", + content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }], + timestamp: 100, + }] as unknown as Message[], + }); + assert.ok(h.getCustomRenders() > rendersBeforeProgress); + assert.match(component.render(120).join("\n"), /\$ npm test/); + h.closeCustom(); + await opening; + + const rpc = { ...h.ctx, mode: "rpc" } as ExtensionToolContext; + await h.commands.get("subagents")!(jobId, rpc); + assert.match(h.notifications.at(-1) ?? "", new RegExp(jobId)); + await h.commands.get("subagents")!("", rpc); + assert.match(h.notifications.at(-1) ?? "", /Subagent jobs/); + assert.equal(h.customComponents.length, 1); + h.runner.complete("test task"); + } finally { + await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx); + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + test("async dispatch rejects print/JSON before admission", async () => { const h = await harness(); try { diff --git a/test/job-support.test.ts b/test/job-support.test.ts index 264ffd7..521f404 100644 --- a/test/job-support.test.ts +++ b/test/job-support.test.ts @@ -54,6 +54,25 @@ test("persistence wraps snapshots and ignores foreign or malformed entries", () assert.deepEqual(restored, [job]); }); +test("persistence validates activity summaries and accepts legacy snapshots without them", () => { + const withActivity: JobSnapshot = { + ...job, + results: [{ + ...job.results[0], + activity: [ + { kind: "toolCall", summary: "read src/index.ts", timestamp: 20 }, + { kind: "toolResult", summary: "read: contents", timestamp: 21, isError: false }, + ], + }], + }; + const entry = { type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", withActivity) }; + assert.deepEqual(extractJobSnapshots([entry]), [withActivity]); + + const broken = structuredClone(entry); + broken.data.job.results[0].activity![0].timestamp = "yesterday" as unknown as number; + assert.deepEqual(extractJobSnapshots([broken]), []); +}); + test("workflow formatting and persistence keep step ids and skipped steps", () => { const workflowJob: JobSnapshot = { ...job, diff --git a/test/manager.test.ts b/test/manager.test.ts index cb795e1..68234cc 100644 --- a/test/manager.test.ts +++ b/test/manager.test.ts @@ -1,7 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; +import type { Message } from "@earendil-works/pi-ai"; import { SubagentManager } from "../src/manager.ts"; -import { FakeRunner, invocation } from "./helpers.ts"; +import type { JobSnapshot } from "../src/types.ts"; +import { FakeRunner, invocation, result as makeResult } from "./helpers.ts"; test("async single returns an ID before completion and later exposes its result", async () => { const runner = new FakeRunner(); @@ -20,6 +22,44 @@ test("async single returns an ID before completion and later exposes its result" assert.equal(terminal.results[0].status, "succeeded"); }); +test("async progress exposes bounded activity without persisting every message", async () => { + const persisted: JobSnapshot[] = []; + const progress: JobSnapshot[] = []; + const runner = new FakeRunner(); + const manager = new SubagentManager(runner, { + onJobChange: (job) => persisted.push(job), + onJobActivity: (job) => progress.push(job), + }); + const job = manager.startAsync(invocation()); + const persistedBeforeProgress = persisted.length; + const pending = runner.calls[0]; + const messages = [{ + role: "assistant", + content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }], + timestamp: 100, + }] as unknown as Message[]; + + pending.options.onUpdate?.({ + ...makeResult(pending.task, "working"), + status: "running", + exitCode: null, + messages, + }); + + const current = manager.get(job.id); + assert.equal(current.results[0].output, "working"); + assert.deepEqual(current.results[0].activity, [ + { kind: "toolCall", summary: "$ npm test", timestamp: 100 }, + ]); + assert.equal(progress.length, 1); + assert.equal(persisted.length, persistedBeforeProgress); + + runner.complete("task 1", "finished"); + const terminal = await manager.wait(job.id, 1); + assert.equal(terminal.results[0].activity?.[0].summary, "$ npm test"); + assert.equal(persisted.at(-1)?.results[0].activity?.[0].summary, "$ npm test"); +}); + test("parallel preserves partial results and does not finish while another task can run", async () => { const runner = new FakeRunner(); const manager = new SubagentManager(runner, { maxWorkers: 1 }); @@ -78,6 +118,23 @@ test("cancel drains queued tasks, aborts running tasks, and is idempotent", asyn assert.equal(manager.cancel(job.id).status, "cancelled"); }); +test("the manager defaults to sixteen shared workers", async () => { + const runner = new FakeRunner(); + const manager = new SubagentManager(runner); + const request = invocation("parallel"); + request.tasks = Array.from({ length: 17 }, (_, index) => ({ ...request.tasks[0], task: `task ${index + 1}` })); + + const job = manager.startAsync(request); + assert.equal(runner.calls.length, 16); + assert.equal(manager.get(job.id).results.filter((task) => task.status === "queued").length, 1); + + for (const pending of [...runner.calls]) runner.complete(pending.task.task); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runner.calls.length, 17); + runner.complete("task 17"); + assert.equal((await manager.wait(job.id, 1)).status, "succeeded"); +}); + test("synchronous and async work share the global worker limit", async () => { const runner = new FakeRunner(); const manager = new SubagentManager(runner, { maxWorkers: 1 }); diff --git a/test/render.test.ts b/test/render.test.ts index 6be12de..9913d18 100644 --- a/test/render.test.ts +++ b/test/render.test.ts @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; +import type { Message } from "@earendil-works/pi-ai"; import type { SubagentDetails, RunResult } from "../src/types.ts"; import { PER_TASK_OUTPUT_CAP, @@ -127,6 +128,64 @@ test("parallel rendering shows running tasks without counting them as failures", assert.doesNotMatch(text, /✗/); }); +test("collapsed rendering shows only the latest activity for each running agent", () => { + const messages = [ + { + role: "assistant", + content: [ + { type: "text", text: "earlier reasoning" }, + { type: "toolCall", id: "old", name: "bash", arguments: { command: "old-command" } }, + ], + }, + { + role: "assistant", + content: [ + { type: "text", text: "latest reasoning" }, + { type: "toolCall", id: "new", name: "read", arguments: { path: "src/latest.ts" } }, + ], + }, + ] as unknown as Message[]; + const result = { + content: [{ type: "text" as const, text: "partial" }], + details: details([ + runResult({ status: "running", exitCode: null, messages, output: "working" }), + ]), + }; + + const text = renderedText(renderSubagentResult(result, { expanded: false }, theme)); + assert.match(text, /src\/latest\.ts/); + assert.match(text, /\[running\]/); + assert.doesNotMatch(text, /earlier reasoning|latest reasoning|old-command/); +}); + +test("expanded parallel rendering keeps live task status and tool details", () => { + const messages = [{ + role: "assistant", + content: [{ type: "toolCall", id: "call", name: "bash", arguments: { command: "npm test" } }], + }] as unknown as Message[]; + const result = { + content: [{ type: "text" as const, text: "partial" }], + details: details([runResult({ status: "running", exitCode: null, messages, output: "working" })]), + }; + + const text = renderedText(renderSubagentResult(result, { expanded: true }, theme)); + assert.match(text, /\[running\]/); + assert.match(text, /npm test/); + assert.match(text, /working/); +}); + +test("workflow progress counts skipped steps as settled", () => { + const result = { + content: [{ type: "text" as const, text: "partial" }], + details: details([ + runResult({ stepId: "skipped-step", status: "skipped", exitCode: null, output: "" }), + runResult({ stepId: "running-step", status: "running", exitCode: null }), + ], { mode: "workflow", status: "running" }), + }; + + assert.match(renderedText(renderSubagentResult(result, { expanded: false }, theme)), /1\/2 done/); +}); + test("expanded parallel rendering uses RunResult.output for final text", () => { const result = { content: [{ type: "text" as const, text: "ignored" }],