diff --git a/README.md b/README.md index 66f1a90..08f24f5 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,8 @@ Hierarchical, session-local task tracking for [Pi](https://pi.dev), with atomic - Cumulative active-time tracking that pauses outside `in-progress` and survives session restore - Session-branch persistence across reload, resume, fork, tree navigation, and context compaction - A concise first-action workflow prompt plus a one-shot post-compaction recovery reminder -- Compact Pi widget with hierarchy, status colors, and an adaptive progress bar +- Compact, theme-aware Pi Todo header and task tree with hierarchy, status colors, timers, and an adaptive progress bar +- Optional responsive Todo + Subagents panels when the interactive-subagents extension is present - Optional Herdr metadata showing the current task in the agent sidebar ## Requirements @@ -98,17 +99,18 @@ A task starts timing the first time it enters `in-progress`. Leaving that state ## Pi Widget -The widget appears above Pi's editor while todos exist. Run `/todo` to hide or show it for the current Pi runtime. Ten seconds after every task is completed, the task tree is automatically deleted and task IDs reset to `1`; adding or reopening unfinished work during that delay cancels the clear. Its header is the virtual task-tree root, with connectors extending from it through every top-level task so the display always remains a tree. Content at the deepest leaf level is indented one additional tree step in both the widget and expanded list output so shallower numbered items remain aligned. The outline uses only the labels needed by the deepest task: one-level trees render every task as an unlabeled leaf, two-level trees use numbered parents and unlabeled leaves, and three-level trees use Roman-numeral categories, numbered items, and unlabeled leaves. Internal task IDs remain unchanged and visible in tool output. In-progress circles rotate through `◐ ◓ ◑ ◒` twice per second; other status symbols remain still. The widget shows at most 12 task rows plus a compact count of hidden tasks, so larger plans do not crowd the editor out of an 80×24 terminal. +The widget appears above Pi's editor while todos exist. Run `/todo` to hide or show it for the current Pi runtime. Ten seconds after every task is completed, the task tree is automatically deleted and task IDs reset to `1`; adding or reopening unfinished work during that delay cancels the clear. Its compact, unboxed header retains the themed `Todos` title, done/total count, blocked-work count when present, and an adaptive progress bar; the bar drops away first at narrow widths. Body rows retain the task tree's virtual-root connectors, hierarchy, statuses, and timers. The outline uses only the labels needed by the deepest task: one-level trees render every task as an unlabeled leaf, two-level trees use numbered parents and unlabeled leaves, and three-level trees use Roman-numeral categories, numbered items, and unlabeled leaves. Internal task IDs remain unchanged and visible in tool output. In-progress circles rotate through `◐ ◓ ◑ ◒` twice per second; other status symbols remain still. The standalone widget shows at most 12 task rows plus a compact count of hidden tasks. ```text - Todos 2/6 · !1 ━━━━━──────── +Todos 2/6 · !1 ━━━━──── ├─ I. ◐ Build auth · 12:08 │ ├─ 1. ! Resolve token issue · 03:41 - │ │ └─ ○ Inspect provider response - │ └─ 2. ○ Add middleware + │ └─ ○ Inspect provider response └─ II. ✓ Define schema · 04:31 ``` +When the optional interactive-subagents extension exposes its `statusWidget` integration, Todo claims the Subagents panel only while both extensions have content. The duck-typed widget must provide `hasContent()`, `getBodyRowCount()`, `render(width, maxBodyRows?, theme?)`, `claim(onChange)`, and `isClaimed(onChange)`. The optional `theme` is the current Pi theme object with the structural `fg(color, text)` formatter; Todo passes that exact object unchanged, while older providers may ignore the third argument. `isClaimed` must return true only for the exact callback supplied by the current runtime claim; this lets Todo recover safely after a provider reload or invalidation. Above 120 columns they render side by side with a one-cell gap and up to ten body rows per panel; the shorter panel is padded with plain spaces. At 120 columns or fewer, Todo renders first and Subagents below it with one blank line between sections. Stacked panels share ten body rows, preserving one row for each panel and reporting overflow honestly. If the extension is absent or exposes an older API, Todo falls back to its full-width Todo widget. + Tool calls remain compact in the conversation. Expand a tool result with Pi's normal tool-output shortcut to inspect affected tasks or full descriptions. ## Herdr Integration diff --git a/docs/adr/0001-compose-todo-and-subagent-widgets.md b/docs/adr/0001-compose-todo-and-subagent-widgets.md new file mode 100644 index 0000000..f533c7b --- /dev/null +++ b/docs/adr/0001-compose-todo-and-subagent-widgets.md @@ -0,0 +1,5 @@ +# Compose Todo and Subagent widgets through an optional lease + +Todo owns the combined Pi widget and discovers the Subagents panel through a structural, process-local interface. Subagents retains its standalone widget until Todo claims a callback-identified lease, and Todo verifies that lease before every combined render with `isClaimed(onChange)`. `isClaimed` recognizes only the exact callback for the current runtime claim, so a provider reload or invalidation causes Todo to release and reacquire instead of trusting a stale local handle. This avoids a package dependency across the two extensions, preserves either extension's standalone behavior, and lets reload invalidate stale UI callbacks without losing running subagents. + +The optional render seam is `render(width, maxBodyRows?, theme?)`. When composing, Todo passes the exact current Pi theme object as `theme`; the only structural requirement is `fg(color, text): string`, and providers may ignore the third argument for compatibility with older implementations. Todo renders a compact unboxed header and task body. Above 120 columns the panels share a row with a one-cell gap and plain-space padding for a shorter panel; at 120 columns and below they stack with one blank line between sections. Combined layouts cap body rows at a shared ten-line budget. diff --git a/index.ts b/index.ts index 37072c6..71a7409 100644 --- a/index.ts +++ b/index.ts @@ -51,6 +51,7 @@ export default function piTodoHerdr(pi: ExtensionAPI): void { pi.on("session_tree", async (_event, ctx) => restore(ctx)); pi.on("session_shutdown", async (event) => { autoClear.cancel(); + if (activeContext !== undefined) clearTaskWidget(activeContext); activeContext = undefined; if (event.reason === "quit") await clearCurrentTask(); }); diff --git a/src/ui.ts b/src/ui.ts index 7b1808c..7375c1d 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -231,10 +231,17 @@ export function renderWidgetTree( width: number, padding = " ", inProgressFrame?: number, + maxBodyRows?: number, ): string[] { const rows = buildTreeRows(tasks, true, true); const maximumDepth = maximumTaskDepth(tasks); - const visibleRows = rows.slice(0, MAX_WIDGET_TASK_ROWS); + const outputLimit = + maxBodyRows === undefined ? MAX_WIDGET_TASK_ROWS : Math.max(1, Math.floor(Number.isFinite(maxBodyRows) ? maxBodyRows : 1)); + const hasOverflow = rows.length > outputLimit; + // The legacy, standalone widget allows twelve task rows plus one summary. + // A combined panel treats maxBodyRows as a strict total body-line budget. + const taskRowLimit = maxBodyRows === undefined ? outputLimit : hasOverflow ? Math.max(0, outputLimit - 1) : outputLimit; + const visibleRows = rows.slice(0, taskRowLimit); const lines = visibleRows.map(({ task, prefix, depth, siblingIndex, collapsed }) => { const summary = collapsed === undefined ? undefined : `${collapsed.done}/${collapsed.total} done`; const identifier = widgetOutlineLabel(depth, siblingIndex, maximumDepth); @@ -249,9 +256,9 @@ export function renderWidgetTree( inProgressFrame, ); }); - if (rows.length <= MAX_WIDGET_TASK_ROWS) return lines; + if (!hasOverflow) return lines; - const hiddenTasks = rows.slice(MAX_WIDGET_TASK_ROWS).reduce( + const hiddenTasks = rows.slice(taskRowLimit).reduce( (count, row) => count + 1 + (row.collapsed?.total ?? 0), 0, ); @@ -277,6 +284,35 @@ export function renderProgressHeader(stats: TaskStats, theme: Theme, width: numb return truncateToWidth(`${theme.fg("accent", label)} ${bar}`, Math.max(1, width)); } +function compactProgressBar(stats: TaskStats, theme: Theme): string { + const width = 8; + const filled = stats.total === 0 ? 0 : Math.round((stats.done / stats.total) * width); + const filledColor = stats.done === stats.total ? "success" : "accent"; + return ( + theme.fg(filledColor, theme.bold("━".repeat(filled))) + + theme.fg("borderMuted", "─".repeat(width - filled)) + ); +} + +/** Render the compact, unboxed Todo header and task rows. */ +export function renderTodoPanel( + tasks: Task[], + theme: Theme, + width: number, + inProgressFrame?: number, + maxBodyRows?: number, +): string[] { + if (!Number.isFinite(width) || width <= 0) return []; + const safeWidth = Math.max(1, Math.floor(width)); + const stats = snapshotStats(tasks); + const title = theme.fg("accent", "Todos"); + const count = theme.fg("muted", `${stats.done}/${stats.total}${stats.blocked > 0 ? ` · !${stats.blocked}` : ""}`); + const fullHeader = `${title} ${count} ${compactProgressBar(stats, theme)}`; + const compactHeader = `${title} ${count}`; + const header = visibleWidth(fullHeader) <= safeWidth ? fullHeader : truncateToWidth(compactHeader, safeWidth); + return [header, ...renderWidgetTree(tasks, theme, safeWidth, " ", inProgressFrame, maxBodyRows)]; +} + class TaskResultComponent implements Component { private readonly build: (width: number) => string[]; diff --git a/src/widget.ts b/src/widget.ts index 48c9f1a..6d20421 100644 --- a/src/widget.ts +++ b/src/widget.ts @@ -1,11 +1,398 @@ -import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; +import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; import type { TaskState } from "./state.ts"; -import { renderProgressHeader, renderWidgetTree } from "./ui.ts"; +import { renderTodoPanel } from "./ui.ts"; const WIDGET_ID = "pi-todo-herdr"; +const COMBINED_WIDGET_BREAKPOINT = 120; +const COMBINED_BODY_ROWS = 10; export const TODO_ANIMATION_INTERVAL_MS = 500; +interface StatusWidgetTheme { + fg(color: string, text: string): string; +} + +interface StatusWidget { + readonly source: object; + readonly hasContent: () => boolean; + readonly getBodyRowCount: () => number; + readonly render: (width: number, maxBodyRows?: number, theme?: StatusWidgetTheme) => string[]; + readonly claim: (onChange: () => void) => () => void; + readonly isClaimed: (onChange: () => void) => boolean; +} + +interface InteractiveSubagentsGlobal { + statusWidget?: unknown; +} + +class OptionalIntegrationError extends Error { + constructor(message: string, cause?: unknown) { + super(message, { cause }); + this.name = "OptionalIntegrationError"; + } +} + +class TuiRenderFailure extends Error { + readonly original: unknown; + + constructor(original: unknown) { + super("TUI render failed", { cause: original }); + this.name = "TuiRenderFailure"; + this.original = original; + } +} + +function optionalIntegrationFailure(message: string, cause?: unknown): OptionalIntegrationError { + return new OptionalIntegrationError(message, cause); +} + +function callOptionalIntegration(message: string, operation: () => T): T { + try { + return operation(); + } catch (error) { + if (error instanceof TuiRenderFailure) throw error.original; + if (error instanceof OptionalIntegrationError) throw error; + throw optionalIntegrationFailure(message, error); + } +} + +interface ActiveClaim { + owner: object; + source: object; + onChange: () => void; + release: () => void; + generation: number; +} + +// Symbols make the claim and generation survive extension reloads. A newly +// loaded module can invalidate a stale component before installing its own. +const ACTIVE_CLAIM_KEY = Symbol.for("pi-todo-herdr/active-subagents-claim"); +const WIDGET_GENERATION_KEY = Symbol.for("pi-todo-herdr/widget-generation"); +const ACTIVE_RUNTIME_KEY = Symbol.for("pi-todo-herdr/active-runtime"); +const RUNTIME_TOKEN = Symbol("pi-todo-herdr-runtime"); +const previousClaim = Reflect.get(globalThis, ACTIVE_CLAIM_KEY); +Reflect.set(globalThis, ACTIVE_RUNTIME_KEY, RUNTIME_TOKEN); +if (previousClaim !== null && typeof previousClaim === "object") { + const release = (previousClaim as { release?: unknown }).release; + Reflect.deleteProperty(globalThis, ACTIVE_CLAIM_KEY); + if (typeof release === "function") { + try { + release.call(previousClaim); + } catch { + // A stale claim must not prevent the new extension runtime loading. + } + } +} + +function isCurrentRuntime(): boolean { + return Reflect.get(globalThis, ACTIVE_RUNTIME_KEY) === RUNTIME_TOKEN; +} + +function getActiveClaim(): ActiveClaim | undefined { + const claim = Reflect.get(globalThis, ACTIVE_CLAIM_KEY); + return claim !== null && typeof claim === "object" ? (claim as ActiveClaim) : undefined; +} + +function setActiveClaim(claim: ActiveClaim | undefined): void { + if (claim === undefined) Reflect.deleteProperty(globalThis, ACTIVE_CLAIM_KEY); + else Reflect.set(globalThis, ACTIVE_CLAIM_KEY, claim); +} + +function claimBelongsTo(claim: ActiveClaim | undefined, owner: object, generation: number): claim is ActiveClaim { + return claim?.owner === owner && claim.generation === generation; +} + +function nextWidgetGeneration(): number { + const current = Reflect.get(globalThis, WIDGET_GENERATION_KEY); + const generation = typeof current === "number" && Number.isSafeInteger(current) ? current + 1 : 1; + Reflect.set(globalThis, WIDGET_GENERATION_KEY, generation); + return generation; +} + +function currentWidgetGeneration(): number { + const generation = Reflect.get(globalThis, WIDGET_GENERATION_KEY); + return typeof generation === "number" && Number.isSafeInteger(generation) ? generation : 0; +} + +function releaseActiveClaim(owner?: object, generation?: number): void { + const activeClaim = getActiveClaim(); + if ( + (owner !== undefined && activeClaim?.owner !== owner) || + (generation !== undefined && activeClaim?.generation !== generation) + ) return; + setActiveClaim(undefined); + if (activeClaim === undefined) return; + try { + activeClaim.release(); + } catch { + // A broken optional integration must never prevent the Todo widget clearing. + } +} + +function getStatusWidget(): StatusWidget | undefined { + try { + const globals = globalThis as typeof globalThis & { + __pi_interactive_subagents?: unknown; + }; + const integration = globals.__pi_interactive_subagents; + if (integration === null || typeof integration !== "object") return undefined; + const statusWidget = (integration as InteractiveSubagentsGlobal).statusWidget; + if (statusWidget === null || typeof statusWidget !== "object") return undefined; + + const candidate = statusWidget as Record; + if ( + typeof candidate.hasContent !== "function" || + typeof candidate.getBodyRowCount !== "function" || + typeof candidate.render !== "function" || + typeof candidate.claim !== "function" || + typeof candidate.isClaimed !== "function" + ) { + return undefined; + } + + const source = statusWidget; + const call = (methodName: string, args: unknown[] = []): T => + callOptionalIntegration(`Subagents ${methodName} failed`, () => { + const method = candidate[methodName]; + if (typeof method !== "function") { + throw optionalIntegrationFailure(`invalid Subagents ${methodName} method`); + } + return method.call(source, ...args) as T; + }); + + return { + source, + hasContent: () => { + const content = call("hasContent"); + if (typeof content !== "boolean") throw optionalIntegrationFailure("invalid Subagents content state"); + return content; + }, + getBodyRowCount: () => { + const count = call("getBodyRowCount"); + if (typeof count !== "number" || !Number.isFinite(count)) { + throw optionalIntegrationFailure("invalid Subagents body row count"); + } + return count; + }, + render: (width, maxBodyRows, theme) => { + const lines = call("render", [width, maxBodyRows, theme]); + const hasAllEntries = + Array.isArray(lines) && + lines.length > 0 && + Array.from({ length: lines.length }, (_, index) => { + return Object.prototype.hasOwnProperty.call(lines, index) && typeof lines[index] === "string"; + }).every(Boolean); + if (!hasAllEntries) throw optionalIntegrationFailure("invalid Subagents render output"); + const validLines = lines as string[]; + if (maxBodyRows !== undefined) { + const isBordered = validLines[0]?.includes("╭") && validLines.at(-1)?.includes("╰"); + // Body rows exclude the provider's header. Legacy bordered output has + // top and bottom chrome; the current unboxed output has one header. + const headerAndChromeRows = isBordered ? 2 : 1; + const maxLines = maxBodyRows + headerAndChromeRows; + if (validLines.length > maxLines) { + throw optionalIntegrationFailure("Subagents render output exceeded its body limit"); + } + } + return validLines; + }, + claim: (onChange) => { + const release = call("claim", [onChange]); + if (typeof release !== "function") throw optionalIntegrationFailure("invalid Subagents claim release"); + return release as () => void; + }, + isClaimed: (onChange) => { + const claimed = call("isClaimed", [onChange]); + if (typeof claimed !== "boolean") throw optionalIntegrationFailure("invalid Subagents claim state"); + return claimed; + }, + }; + } catch { + return undefined; + } +} + +function claimStatusWidget( + statusWidget: StatusWidget, + owner: object, + generation: number, + tui: { requestRender(): void }, +): boolean { + const activeClaim = getActiveClaim(); + if (activeClaim?.owner !== undefined && activeClaim.owner !== owner) return false; + if (claimBelongsTo(activeClaim, owner, generation) && activeClaim.source === statusWidget.source) { + try { + if (statusWidget.isClaimed(activeClaim.onChange)) return true; + } catch (error) { + releaseActiveClaim(owner, generation); + if (error instanceof OptionalIntegrationError) return false; + throw error; + } + // The provider may have been reset by a reload or another lifecycle event. + // Drop the stale local handle before asking it for a fresh claim. + } + releaseActiveClaim(owner, generation); + + try { + const onChange = () => { + if (!isCurrentRuntime()) { + releaseActiveClaim(owner, generation); + return; + } + const currentClaim = getActiveClaim(); + if (!claimBelongsTo(currentClaim, owner, generation) || currentClaim.onChange !== onChange) return; + try { + tui.requestRender(); + } catch (error) { + // Let the provider restore its standalone widget when the TUI is gone. + releaseActiveClaim(owner, generation); + throw new TuiRenderFailure(error); + } + }; + const release = statusWidget.claim(onChange); + setActiveClaim({ owner, source: statusWidget.source, onChange, release, generation }); + return true; + } catch (error) { + if (error instanceof OptionalIntegrationError) return false; + throw error; + } +} + +function normalizeWidth(width: number): number { + return Math.max(1, Math.floor(Number.isFinite(width) ? width : 1)); +} + +function fitLine(line: string, width: number): string { + const fittedWidth = normalizeWidth(width); + const fitted = truncateToWidth(line, fittedWidth); + return `${fitted}${" ".repeat(Math.max(0, fittedWidth - visibleWidth(fitted)))}`; +} + +function renderStatusPanel( + statusWidget: StatusWidget, + width: number, + maxBodyRows: number, + theme: StatusWidgetTheme, +): string[] { + return statusWidget.render(width, maxBodyRows, theme).map((line) => fitLine(line, width)); +} + +function normalizePanelHeight(lines: string[], height: number, blankLine: string): string[] { + if (lines.length >= height) return lines; + const blanks = Array.from({ length: height - lines.length }, () => blankLine); + const bottom = lines.at(-1); + if (bottom?.includes("╰")) return [...lines.slice(0, -1), ...blanks, bottom]; + return [...lines, ...blanks]; +} + +function renderSideBySide( + tasks: ReturnType, + theme: Theme, + width: number, + inProgressFrame: number, + statusWidget: StatusWidget, +): string[] { + const leftWidth = Math.floor((width - 1) / 2); + const rightWidth = width - 1 - leftWidth; + const todo = renderTodoPanel(tasks, theme, leftWidth, inProgressFrame, COMBINED_BODY_ROWS); + const subagents = renderStatusPanel(statusWidget, rightWidth, COMBINED_BODY_ROWS, theme); + const height = Math.max(todo.length, subagents.length); + const left = normalizePanelHeight(todo, height, " ".repeat(leftWidth)).map((line) => fitLine(line, leftWidth)); + const right = normalizePanelHeight(subagents, height, " ".repeat(rightWidth)); + return left.map((line, index) => `${line} ${right[index]}`); +} + +function bodyRowsForTodo( + tasks: ReturnType, + theme: Theme, + width: number, + inProgressFrame: number, +): number { + return Math.max(1, renderTodoPanel(tasks, theme, width, inProgressFrame, COMBINED_BODY_ROWS).length - 1); +} + +function bodyRowsForSubagents(statusWidget: StatusWidget): number { + return Math.max(1, Math.min(COMBINED_BODY_ROWS, Math.floor(statusWidget.getBodyRowCount()))); +} + +function distributeBodyRows(todoNeed: number, subagentsNeed: number): { todo: number; subagents: number } { + let todo = Math.min(todoNeed, Math.floor(COMBINED_BODY_ROWS / 2)); + let subagents = Math.min(subagentsNeed, Math.floor(COMBINED_BODY_ROWS / 2)); + let remaining = COMBINED_BODY_ROWS - todo - subagents; + + const todoUnused = Math.max(0, todoNeed - todo); + const todoExtra = Math.min(remaining, todoUnused); + todo += todoExtra; + remaining -= todoExtra; + + const subagentsUnused = Math.max(0, subagentsNeed - subagents); + subagents += Math.min(remaining, subagentsUnused); + return { todo: Math.max(1, todo), subagents: Math.max(1, subagents) }; +} + +function renderStacked( + tasks: ReturnType, + theme: Theme, + width: number, + inProgressFrame: number, + statusWidget: StatusWidget, + subagentsNeed: number, +): string[] { + const todoNeed = bodyRowsForTodo(tasks, theme, width, inProgressFrame); + const rows = distributeBodyRows(todoNeed, subagentsNeed); + return [ + ...renderTodoPanel(tasks, theme, width, inProgressFrame, rows.todo), + "", + ...renderStatusPanel(statusWidget, width, rows.subagents, theme), + ]; +} + +function renderCombinedWidget( + tasks: ReturnType, + theme: Theme, + width: number, + inProgressFrame: number, + tui: { requestRender(): void }, + owner: object, + generation: number, + composeSubagents: boolean, +): string[] { + if (!Number.isFinite(width) || width <= 0 || tasks.length === 0) { + releaseActiveClaim(owner, generation); + return []; + } + + const fittedWidth = normalizeWidth(width); + const renderTodoFallback = (): string[] => { + releaseActiveClaim(owner, generation); + return renderTodoPanel(tasks, theme, fittedWidth, inProgressFrame); + }; + if (!composeSubagents) return renderTodoFallback(); + + const statusWidget = getStatusWidget(); + if (statusWidget === undefined) return renderTodoFallback(); + + try { + if (!statusWidget.hasContent()) return renderTodoFallback(); + if (!claimStatusWidget(statusWidget, owner, generation, tui)) return renderTodoFallback(); + + const subagentsNeed = bodyRowsForSubagents(statusWidget); + return fittedWidth > COMBINED_WIDGET_BREAKPOINT + ? renderSideBySide(tasks, theme, fittedWidth, inProgressFrame, statusWidget) + : renderStacked(tasks, theme, fittedWidth, inProgressFrame, statusWidget, subagentsNeed); + } catch (error) { + if (!(error instanceof OptionalIntegrationError)) { + releaseActiveClaim(owner, generation); + throw error; + } + return renderTodoFallback(); + } +} + export function clearTaskWidget(ctx: ExtensionContext): void { + if (!isCurrentRuntime()) return; + nextWidgetGeneration(); + releaseActiveClaim(); ctx.ui.setWidget(WIDGET_ID, undefined); } @@ -15,33 +402,66 @@ export function updateTaskWidget( visible: boolean, refreshMs = TODO_ANIMATION_INTERVAL_MS, ): void { + if (!isCurrentRuntime()) return; const tasks = state.list(); if (!visible || tasks.length === 0) { clearTaskWidget(ctx); return; } + const generation = nextWidgetGeneration(); + // Subagents owns a native widget outside this extension. Only compose it + // while Pi is rendering the terminal UI, never in RPC/print modes. + const composeSubagents = ctx.mode === "tui"; + + // Replacing a widget can happen before Pi calls its old dispose hook. Release + // the optional Subagents claim eagerly so it cannot hide a standalone widget. + releaseActiveClaim(); const hasActiveTimer = tasks.some((task) => task.status === "in-progress" && task.startedAt !== undefined); ctx.ui.setWidget(WIDGET_ID, (tui, theme) => { let inProgressFrame = 0; - const timer = hasActiveTimer - ? setInterval(() => { - inProgressFrame += 1; + let disposed = false; + const owner = {}; + const isActive = (): boolean => + !disposed && isCurrentRuntime() && currentWidgetGeneration() === generation; + let timer: ReturnType | undefined; + if (hasActiveTimer) { + timer = setInterval(() => { + if (!isActive()) { + clearInterval(timer); + return; + } + inProgressFrame += 1; + try { tui.requestRender(); - }, Math.max(1, refreshMs)) - : undefined; + } catch { + disposed = true; + clearInterval(timer); + releaseActiveClaim(owner, generation); + } + }, Math.max(1, refreshMs)); + } timer?.unref(); return { render(width: number): string[] { + if (!isActive()) return []; const currentTasks = state.list(); - return [ - renderProgressHeader(state.stats(), theme, width), - ...renderWidgetTree(currentTasks, theme, width, " ", inProgressFrame), - ]; + return renderCombinedWidget( + currentTasks, + theme, + width, + inProgressFrame, + tui, + owner, + generation, + composeSubagents, + ); }, invalidate(): void {}, dispose(): void { + disposed = true; + releaseActiveClaim(owner, generation); if (timer !== undefined) clearInterval(timer); }, }; diff --git a/tests/ui.test.ts b/tests/ui.test.ts index 63f9660..340acd6 100644 --- a/tests/ui.test.ts +++ b/tests/ui.test.ts @@ -8,11 +8,12 @@ import { renderProgressHeader, renderTaskLine, renderToolResult, + renderTodoPanel, renderTree, renderWidgetTree, snapshotStats, } from "../src/ui.ts"; -import { TODO_ANIMATION_INTERVAL_MS, updateTaskWidget } from "../src/widget.ts"; +import { clearTaskWidget, TODO_ANIMATION_INTERVAL_MS, updateTaskWidget } from "../src/widget.ts"; const plainTheme = { fg: (_color: string, text: string) => text, @@ -20,6 +21,30 @@ const plainTheme = { strikethrough: (text: string) => `~${text}~`, }; +type TestTui = { requestRender(): void }; +type TestWidget = { render(width: number): string[]; dispose(): void }; + +function mountWidget(widget: unknown, tui: TestTui = { requestRender() {} }, theme: unknown = plainTheme): TestWidget { + return (widget as (tui: TestTui, theme: unknown) => TestWidget)(tui, theme); +} + +function setSubagentsIntegration(integration: unknown): void { + const globals = globalThis as typeof globalThis & { __pi_interactive_subagents?: unknown }; + if (integration === undefined) delete globals.__pi_interactive_subagents; + else globals.__pi_interactive_subagents = integration; +} + +function withSubagentsIntegration(integration: unknown, callback: () => T): T { + const globals = globalThis as typeof globalThis & { __pi_interactive_subagents?: unknown }; + const previous = globals.__pi_interactive_subagents; + setSubagentsIntegration(integration); + try { + return callback(); + } finally { + setSubagentsIntegration(previous); + } +} + function stripAnsi(text: string): string { return text.replace(/\x1b\[[0-9;]*m/g, ""); } @@ -367,15 +392,433 @@ test("hides an empty widget and renders a populated one", () => { state.add([{ name: "Task", description: "Task" }]); updateTaskWidget(state, ctx as never, true); assert.equal(typeof widget, "function"); - const component = (widget as unknown as (tui: unknown, theme: unknown) => { render(width: number): string[] })( - {}, - plainTheme, - ); - const lines = component.render(30); + const component = mountWidget(widget); + const lines = component.render(30).map(stripAnsi); assert.equal(lines.length, 2); + assert.match(lines[0] ?? "", /^Todos.*0\/1/); + assert.doesNotMatch(lines.join("\n"), /[╭╮╰╯]/); assert.ok(lines.every((line) => visibleWidth(line) <= 30)); }); +test("renders compact unboxed solo panels at narrow widths without overflowing", () => { + const state = new TaskState(() => 0); + state.add([{ name: "A long task name", status: "blocked" }]); + + for (const width of [80, 60]) { + const lines = renderTodoPanel(state.list(), plainTheme as never, width).map(stripAnsi); + assert.ok(lines.every((line) => visibleWidth(line) <= width)); + assert.match(lines[0] ?? "", /^Todos.*0\/1.*!1/); + assert.match(lines[0] ?? "", /━|─/); + assert.doesNotMatch(lines.join("\n"), /[╭╮╰╯]/); + } + + const narrow = renderTodoPanel(state.list(), plainTheme as never, 20).map(stripAnsi); + assert.ok(narrow.every((line) => visibleWidth(line) <= 20)); + assert.doesNotMatch(narrow.join("\n"), /[╭╮╰╯]/); + assert.match(narrow[0] ?? "", /0\/1/); + + const boundary = new TaskState(() => 0); + boundary.add(Array.from({ length: 13 }, (_, index) => ({ name: `Boundary ${index + 1}` }))); + const boundaryLines = renderTodoPanel(boundary.list(), plainTheme as never, 80).map(stripAnsi); + assert.equal(boundaryLines.length, 14); + assert.match(boundaryLines[12] ?? "", /Boundary 12/); + assert.match(boundaryLines[13] ?? "", /… 1 more task/); + assert.ok(boundaryLines.every((line) => !line.includes("Boundary 13"))); +}); + +test("passes the current Pi theme unchanged to composed Subagents rendering", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + const theme = { + fg: (_color: string, text: string) => text, + bold: (text: string) => text, + strikethrough: (text: string) => text, + }; + let receivedTheme: unknown; + const statusWidget = { + hasContent: () => true, + getBodyRowCount: () => 1, + isClaimed: () => true, + render: (_width: number, _maxBodyRows?: number, providerTheme?: unknown) => { + receivedTheme = providerTheme; + return ["subagents"]; + }, + claim: () => () => {}, + }; + withSubagentsIntegration({ statusWidget }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget, { requestRender() {} }, theme); + component.render(80); + assert.equal(receivedTheme, theme); + component.dispose(); + }); +}); + +test("keeps an unboxed Subagents header plus capped body rows composed at 120 columns", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + let receivedMaxBodyRows: number | undefined; + const statusWidget = { + hasContent: () => true, + getBodyRowCount: () => 2, + isClaimed: () => true, + render: (_width: number, maxBodyRows?: number) => { + receivedMaxBodyRows = maxBodyRows; + return ["Subagents", "agent one", "agent two"]; + }, + claim: () => () => {}, + }; + withSubagentsIntegration({ statusWidget }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget); + const lines = component.render(120).map(stripAnsi); + assert.equal(receivedMaxBodyRows, 2); + assert.ok(lines.some((line) => line.includes("Subagents"))); + assert.ok(lines.some((line) => line.includes("agent two"))); + assert.equal(lines[2], ""); + assert.ok(lines.every((line) => visibleWidth(line) <= 120)); + assert.doesNotMatch(lines.join("\n"), /[╭╮╰╯]/); + component.dispose(); + }); +}); + +test("switches from side-by-side to stacked panels at the 120-column breakpoint", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + let claimCount = 0; + let releaseCount = 0; + const renderCalls: Array<[number, number | undefined]> = []; + const statusWidget = { + hasContent: () => true, + getBodyRowCount: () => 2, + isClaimed: () => true, + render: (width: number, maxBodyRows?: number) => { + renderCalls.push([width, maxBodyRows]); + return ["Subagents"]; + }, + claim: (_onChange: () => void) => { + claimCount += 1; + return () => { + releaseCount += 1; + }; + }, + }; + withSubagentsIntegration({ statusWidget }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + const tui = { requestRender() {} }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget, tui); + const side = component.render(121).map(stripAnsi); + assert.match(side[0] ?? "", /Todos.*Subagents/); + assert.ok(side.every((line) => visibleWidth(line) === 121)); + assert.equal(side[1]?.slice(61), " ".repeat(60)); + assert.doesNotMatch(side.join("\n"), /[╭╮╰╯]/); + + state.add(Array.from({ length: 20 }, (_, index) => ({ name: `Extra ${index + 1}` }))); + const unequal = component.render(121).map(stripAnsi); + const rightPanel = unequal.map((line) => line.slice(61)); + assert.equal(rightPanel.at(-1), " ".repeat(60)); + assert.doesNotMatch(unequal.join("\n"), /[╭╮╰╯]/); + + const stacked = component.render(120); + assert.match(stripAnsi(stacked[0] ?? ""), /Todos/); + const stackedSubagentsIndex = stacked.findIndex((line) => stripAnsi(line).includes("Subagents")); + assert.ok(stackedSubagentsIndex > 0); + assert.ok(stackedSubagentsIndex < stacked.length); + assert.ok(stacked.every((line) => visibleWidth(line) <= 120)); + assert.equal(stacked[stackedSubagentsIndex - 1], ""); + assert.doesNotMatch(stacked.map(stripAnsi).join("\n"), /[╭╮╰╯]/); + assert.deepEqual(renderCalls.map(([, maxRows]) => maxRows), [10, 10, 2]); + assert.equal(claimCount, 1); + + component.dispose(); + assert.equal(releaseCount, 1); + }); +}); + +test("falls back to a full-width Todo panel for absent and old Subagents APIs", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + const tui = { requestRender() {} }; + const empty = { + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + render: () => [], + claim: () => () => {}, + isClaimed: () => true, + }, + }; + const malformed = { + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + render: () => new Array(1), + claim: () => () => {}, + isClaimed: () => true, + }, + }; + for (const integration of [undefined, { statusWidget: { render: () => [] } }, empty, malformed]) { + withSubagentsIntegration(integration, () => { + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget, tui); + const lines = component.render(80).map(stripAnsi); + assert.equal(lines.length, 2); + assert.match(lines[0] ?? "", /Todos/); + assert.doesNotMatch(lines.join("\n"), /[╭╮╰╯]/); + component.dispose(); + }); + } +}); + +test("reacquires a claim after the provider invalidates its callback", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + let claims = 0; + let releases = 0; + let providerCallback: (() => void) | undefined; + let providerClaimed = false; + withSubagentsIntegration({ + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + render: () => ["subagents"], + isClaimed: (onChange: () => void) => providerClaimed && providerCallback === onChange, + claim: (onChange: () => void) => { + claims += 1; + providerCallback = onChange; + providerClaimed = true; + return () => { + releases += 1; + if (providerCallback === onChange) { + providerCallback = undefined; + providerClaimed = false; + } + }; + }, + }, + }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget); + component.render(80); + assert.equal(claims, 1); + component.render(80); + assert.equal(claims, 1); + + providerClaimed = false; + providerCallback = undefined; + component.render(80); + assert.equal(claims, 2); + assert.equal(releases, 1); + component.dispose(); + assert.equal(releases, 2); + }); +}); + +test("does not mask Todo rendering failures as optional integration failures", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + withSubagentsIntegration({ + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + render: () => ["subagents"], + isClaimed: () => true, + claim: () => () => {}, + }, + }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + const failure = new Error("Todo renderer failed"); + const badTheme = { + fg: () => { + throw failure; + }, + bold: (text: string) => text, + strikethrough: (text: string) => text, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget, { requestRender() {} }, badTheme); + assert.throws(() => component.render(80), (error) => error === failure); + component.dispose(); + }); +}); + +test("does not compose or claim Subagents outside the TUI mode", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + let claims = 0; + withSubagentsIntegration({ + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + render: () => ["Subagents"], + claim: () => { + claims += 1; + return () => {}; + }, + }, + }, () => { + let widget: unknown; + const ctx = { + mode: "rpc" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget); + const lines = component.render(80).map(stripAnsi); + assert.equal(claims, 0); + assert.ok(lines.every((line) => !line.includes("Subagents"))); + component.dispose(); + }); +}); + +test("shares ten stacked body rows and keeps Todo overflow honest", () => { + const state = new TaskState(() => 0); + state.add(Array.from({ length: 20 }, (_, index) => ({ name: `Task ${index + 1}` }))); + const calls: Array<[number, number | undefined]> = []; + const statusWidget = { + hasContent: () => true, + getBodyRowCount: () => 3, + isClaimed: () => true, + render: (width: number, maxBodyRows?: number) => { + calls.push([width, maxBodyRows]); + return ["one", "two", "three"]; + }, + claim: () => () => {}, + }; + withSubagentsIntegration({ statusWidget }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget); + const lines = component.render(120).map(stripAnsi); + assert.deepEqual(calls, [[120, 3]]); + assert.ok(lines.some((line) => line.includes("… 14 more tasks"))); + assert.ok(lines.every((line) => visibleWidth(line) <= 120)); + component.dispose(); + }); +}); + +test("releases a Subagents claim when Todos hide or clear", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + let releases = 0; + withSubagentsIntegration({ + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + isClaimed: () => true, + render: () => ["subagents"], + claim: () => () => { + releases += 1; + }, + }, + }, () => { + let widget: unknown; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => (widget = content) }, + }; + updateTaskWidget(state, ctx as never, true); + const component = mountWidget(widget); + component.render(80); + updateTaskWidget(state, ctx as never, false); + assert.equal(releases, 1); + + updateTaskWidget(state, ctx as never, true); + const second = mountWidget(widget); + second.render(80); + state.remove([1]); + updateTaskWidget(state, ctx as never, true); + assert.equal(releases, 2); + second.dispose(); + }); +}); + +test("handles zero and one-column panel widths cleanly", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo" }]); + assert.deepEqual(renderTodoPanel(state.list(), plainTheme as never, 0), []); + const oneColumn = renderTodoPanel(state.list(), plainTheme as never, 1); + assert.ok(oneColumn.length > 0); + assert.ok(oneColumn.every((line) => visibleWidth(line) <= 1)); +}); + +test("ignores stale widget generations when Pi replaces the widget", () => { + const state = new TaskState(() => 0); + state.add([{ name: "Todo", status: "in-progress" }]); + let claims = 0; + let releases = 0; + withSubagentsIntegration({ + statusWidget: { + hasContent: () => true, + getBodyRowCount: () => 1, + isClaimed: () => true, + render: () => ["subagents"], + claim: () => { + claims += 1; + return () => { + releases += 1; + }; + }, + }, + }, () => { + const widgets: unknown[] = []; + const ctx = { + mode: "tui" as const, + ui: { setWidget: (_id: string, content: unknown) => widgets.push(content) }, + }; + const tui = { requestRender() {} }; + updateTaskWidget(state, ctx as never, true, 5); + const first = mountWidget(widgets[0], tui); + first.render(80); + + updateTaskWidget(state, ctx as never, true, 5); + const second = mountWidget(widgets[1], tui); + second.render(80); + assert.equal(claims, 2); + assert.equal(releases, 1); + assert.deepEqual(first.render(80), []); + + first.dispose(); + assert.equal(releases, 1); + clearTaskWidget(ctx as never); + assert.equal(releases, 2); + second.dispose(); + }); +}); + test("animates active todos twice per second", () => { assert.equal(TODO_ANIMATION_INTERVAL_MS, 500); }); @@ -397,32 +840,24 @@ test("live widgets request rerenders and dispose their interval", async () => { let renderRequests = 0; const observedFrames = new Set(); - let component: { render(width: number): string[]; dispose?(): void }; - component = ( - widget as unknown as ( - tui: { requestRender(): void }, - theme: unknown, - ) => { render(width: number): string[]; dispose?(): void } - )( - { - requestRender() { - renderRequests += 1; - const frame = stripAnsi(component.render(40)[1] ?? "").match(/[◐◓◑◒]/)?.[0]; - if (frame !== undefined) observedFrames.add(frame); - }, + let component: TestWidget; + component = mountWidget(widget, { + requestRender() { + renderRequests += 1; + const frame = stripAnsi(component.render(40)[1] ?? "").match(/[◐◓◑◒]/)?.[0]; + if (frame !== undefined) observedFrames.add(frame); }, - plainTheme, - ); + }); try { - assert.match(stripAnsi(component.render(40)[1] ?? ""), /◐.* · 00:00$/); + assert.match(stripAnsi(component.render(40)[1] ?? ""), /◐.* · 00:00/); now = 65_000; await new Promise((resolve) => setTimeout(resolve, 20)); assert.ok(renderRequests > 0); assert.ok(observedFrames.size > 0); - assert.match(stripAnsi(component.render(40)[1] ?? ""), /[◐◓◑◒].* · 01:05$/); + assert.match(stripAnsi(component.render(40)[1] ?? ""), /[◐◓◑◒].* · 01:05/); } finally { - component.dispose?.(); + component.dispose(); } const requestsAfterDispose = renderRequests;