@esso0428/pi-subagents 0.17.12 → 0.17.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,9 +5,9 @@
5
5
  * Uses the callback form of setWidget for themed rendering.
6
6
  */
7
7
 
8
- import { Editor, isKeyRelease, Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
8
+ import { Editor, isKeyRelease, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
9
9
  import { renderAgentName } from "../agent-color.js";
10
- import { type AgentManager, isTopLevelAgent } from "../agent-manager.js";
10
+ import type { AgentManager } from "../agent-manager.js";
11
11
  import { getConfig } from "../agent-types.js";
12
12
  import type { AgentInvocation, AgentRecord, SubagentType, WidgetMode } from "../types.js";
13
13
  import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type LifetimeUsage, type SessionLike } from "../usage.js";
@@ -16,19 +16,17 @@ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type Lifet
16
16
 
17
17
  /** Maximum number of rendered lines before overflow collapse kicks in. */
18
18
  export const MAX_WIDGET_LINES = 12;
19
+ /** Keep a small editor/input area visible below the above-editor widget. */
20
+ const MIN_EDITOR_LINES = 4;
19
21
 
20
- /** Number of lines available above an editor, retaining room for the prompt. */
21
- export function getWidgetLineBudget(terminalRows: number): number {
22
- if (!Number.isFinite(terminalRows)) return MAX_WIDGET_LINES;
23
- return Math.min(MAX_WIDGET_LINES, Math.max(0, Math.floor(terminalRows) - 4));
24
- }
25
-
26
- export type AgentWidgetOpenMode = "live" | "history";
27
-
28
- export interface AgentWidgetOptions {
29
- canOpenHistory?: (record: import("../types.js").AgentRecord) => boolean;
30
- onOpen?: (record: import("../types.js").AgentRecord, mode: AgentWidgetOpenMode) => void;
31
- showCost?: () => boolean;
22
+ /**
23
+ * Derive the widget ceiling from the terminal height while retaining the
24
+ * historical MAX_WIDGET_LINES ceiling. Very short terminals may have no room
25
+ * for the widget; that is preferable to consuming the editor/input area.
26
+ */
27
+ export function getWidgetLineBudget(rows: number): number {
28
+ if (!Number.isFinite(rows)) return MAX_WIDGET_LINES;
29
+ return Math.min(MAX_WIDGET_LINES, Math.max(0, Math.floor(rows) - MIN_EDITOR_LINES));
32
30
  }
33
31
 
34
32
  /** Braille spinner frames for animated running indicator. */
@@ -55,6 +53,20 @@ export type Theme = {
55
53
  bold(text: string): string;
56
54
  };
57
55
 
56
+ export type AgentWidgetOpenMode = "live" | "history";
57
+ export type AgentWidgetOpenCallback = (record: AgentRecord, mode: AgentWidgetOpenMode) => void | Promise<void>;
58
+ export interface AgentWidgetOptions {
59
+ canOpenHistory?: (record: AgentRecord) => boolean;
60
+ onOpen?: AgentWidgetOpenCallback;
61
+ showCost?: () => boolean;
62
+ }
63
+ /** @deprecated Use AgentWidgetOpenMode. */
64
+ export type AgentOpenMode = AgentWidgetOpenMode;
65
+ /** @deprecated Use AgentWidgetOpenCallback. */
66
+ export type AgentOpenCallback = AgentWidgetOpenCallback;
67
+ /** @deprecated Use AgentWidgetOptions.canOpenHistory. */
68
+ export type AgentHistoryCapability = AgentWidgetOptions["canOpenHistory"];
69
+
58
70
  export type UICtx = {
59
71
  setStatus(key: string, text: string | undefined): void;
60
72
  setWidget(
@@ -76,7 +88,7 @@ export interface AgentActivity {
76
88
  turnCount: number;
77
89
  /** Effective max turns for this agent (undefined = unlimited). */
78
90
  maxTurns?: number;
79
- /** Lifetime token usage, including partial runs. */
91
+ /** Lifetime usage breakdown — see LifetimeUsage docs. */
80
92
  lifetimeUsage: LifetimeUsage;
81
93
  }
82
94
 
@@ -93,7 +105,7 @@ export interface AgentDetails {
93
105
  activity?: string;
94
106
  /** Current spinner frame index (for animated running indicator). */
95
107
  spinnerFrame?: number;
96
- /** Short label for the model the run used, e.g. "haiku 4.5". */
108
+ /** Short model name if different from parent (e.g. "haiku", "sonnet"). */
97
109
  modelName?: string;
98
110
  /** Notable config tags (e.g. ["thinking: high", "isolated"]). */
99
111
  tags?: string[];
@@ -123,31 +135,6 @@ export function formatTokens(count: number): string {
123
135
  return `${count} token`;
124
136
  }
125
137
 
126
- /**
127
- * Format a cost as `~$0.0042`, or "" when there is nothing to show.
128
- *
129
- * The tilde is load-bearing: this is pi's own estimate from the model's listed
130
- * rates, not a billed figure, and the surfaces that print it sit next to token
131
- * counts that ARE exact.
132
- *
133
- * Nothing is printed for zero, which is also what a model with no pricing data
134
- * reports: `$0.00` beside a local model's tokens would claim its cost was
135
- * measured and found to be nothing, rather than never measured at all. For the
136
- * same reason a real cost too small for four decimals reads `<$0.0001` — it was
137
- * measured, and rounding it to `~$0.0000` would say the opposite.
138
- */
139
- export function formatCost(cost: number): string {
140
- if (!(cost > 0)) return ""; // also catches NaN
141
- if (cost < 0.0001) return "<$0.0001";
142
- if (cost >= 1) return `~$${cost.toFixed(2)}`;
143
- // Under a dollar: cents at minimum, four decimals at most, nothing trailing.
144
- // Most single runs land between a tenth of a cent and a dime, where rounding
145
- // to cents would collapse a 4x difference in spend into the same figure.
146
- const rounded = Number(cost.toFixed(4));
147
- const decimals = (String(rounded).split(".")[1] ?? "").length;
148
- return `~$${rounded.toFixed(Math.max(2, decimals))}`;
149
- }
150
-
151
138
  /**
152
139
  * Token count with optional context-fill % and compaction-count annotations.
153
140
  * Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
@@ -193,6 +180,16 @@ export function formatDuration(startedAt: number, completedAt?: number): string
193
180
  return `${formatMs(Date.now() - startedAt)} (running)`;
194
181
  }
195
182
 
183
+ /** Format an estimated model cost without implying billing precision. */
184
+ export function formatCost(cost: number): string {
185
+ if (!(cost > 0)) return "";
186
+ if (cost < 0.0001) return "<$0.0001";
187
+ if (cost >= 1) return `~$${cost.toFixed(2)}`;
188
+ const rounded = Number(cost.toFixed(4));
189
+ const decimals = (String(rounded).split(".")[1] ?? "").length;
190
+ return `~$${rounded.toFixed(Math.max(2, decimals))}`;
191
+ }
192
+
196
193
  /** Get display name for any agent type (built-in or custom). */
197
194
  export function getDisplayName(type: SubagentType): string {
198
195
  return getConfig(type).displayName;
@@ -204,13 +201,7 @@ export function getPromptModeLabel(type: SubagentType): string | undefined {
204
201
  return config.promptMode === "append" ? "twin" : undefined;
205
202
  }
206
203
 
207
- /**
208
- * Mode label is not included — callers add it where they want it.
209
- *
210
- * Both model forms come back so each surface can pick by width; the
211
- * "(asked X)" annotation is applied here rather than by callers, so a value the
212
- * spawn did not honor cannot be rendered as though it had been (#182).
213
- */
204
+ /** Mode label is not included — callers add it where they want it. */
214
205
  export function buildInvocationTags(
215
206
  invocation: AgentInvocation | undefined,
216
207
  ): { modelName?: string; modelId?: string; tags: string[] } {
@@ -232,9 +223,9 @@ export function buildInvocationTags(
232
223
  };
233
224
  }
234
225
 
235
- /** Truncate text to a single line, max `len` chars. */
226
+ /** Normalize and truncate text so it can never add physical widget rows. */
236
227
  function truncateLine(text: string, len = 60): string {
237
- const line = text.split("\n").find(l => l.trim())?.trim() ?? "";
228
+ const line = text.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
238
229
  if (line.length <= len) return line;
239
230
  return line.slice(0, len) + "…";
240
231
  }
@@ -273,10 +264,23 @@ export class AgentWidget {
273
264
  private uiCtx: UICtx | undefined;
274
265
  private widgetFrame = 0;
275
266
  private widgetInterval: ReturnType<typeof setInterval> | undefined;
276
- /** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */
277
- private finishedTurnAge = new Map<string, number>();
278
- /** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */
279
- private static readonly ERROR_LINGER_TURNS = 2;
267
+ private inputUnsub: (() => void) | undefined;
268
+ /** Whether arrow keys currently navigate the agent roster. */
269
+ private navigationActive = false;
270
+ /** Stable identity of the selected row, so roster changes do not jump selection. */
271
+ private selectedAgentId: string | undefined;
272
+ /** Last logical roster index of the selected row, used when it disappears. */
273
+ private selectedRosterIndex = 0;
274
+ /** First logical row currently represented by the bounded viewport. */
275
+ private viewportStart = 0;
276
+
277
+ /** Cached records and roster. Rebuilt by update(), never by an arrow press. */
278
+ private cachedAgents: AgentRecord[] = [];
279
+ private cachedRoster: AgentRecord[] = [];
280
+ private rosterCacheKey: string | undefined;
281
+ private rosterCacheInitialized = false;
282
+ /** Terminal history capability is a potentially filesystem-backed lookup. */
283
+ private historyOpenabilityCache = new Map<string, { key: string; value: boolean }>();
280
284
 
281
285
  /** Whether the widget callback is currently registered with the TUI. */
282
286
  private widgetRegistered = false;
@@ -284,38 +288,17 @@ export class AgentWidget {
284
288
  private tui: any | undefined;
285
289
  /** Last status bar text, used to avoid redundant setStatus calls. */
286
290
  private lastStatusText: string | undefined;
287
- private lastSnapshot = "";
288
- private inputCleanup: (() => void) | undefined;
289
- private navigationSuspended = false;
290
- private navigationActive = false;
291
- private selectedAgentId: string | undefined;
292
- private viewportStart = 0;
293
- private selectedRosterIndex = 0;
294
- private openOptions: AgentWidgetOptions;
295
- private showCost: () => boolean;
296
- private showModel: () => boolean;
291
+ /** Snapshot of the state used for the last widget registration/render request. */
292
+ private lastRenderKey: string | undefined;
293
+ private readonly openOptions: AgentWidgetOptions;
294
+ private readonly showCost: () => boolean;
295
+ private readonly showModel: () => boolean;
297
296
 
298
297
  constructor(
299
298
  private manager: AgentManager,
300
299
  private agentActivity: Map<string, AgentActivity>,
301
- /**
302
- * Read live at render time. Selects which agents the widget shows — see
303
- * `WidgetMode`. Defaults to `"all"` when a caller supplies no policy; the
304
- * extension supplies one defaulting to `"background"`.
305
- */
300
+ /** Read live at render time. Selects which agents the widget shows. */
306
301
  private mode: () => WidgetMode = () => "all",
307
- /**
308
- * Read live at render time, like `mode`. Whether running agents show an
309
- * estimated cost beside their token count. Defaults to off — the extension
310
- * supplies the user's `showCost` setting.
311
- */
312
- /**
313
- * Read live at render time, like `mode`. Whether running agents name the
314
- * model driving them and the thinking level it is running at. Defaults to
315
- * off — the extension supplies the user's `showModel` setting — because the
316
- * row is already dense and the same pair is on the tool result and in the
317
- * conversation viewer unconditionally.
318
- */
319
302
  showCostOrOptions: (() => boolean) | AgentWidgetOptions = () => false,
320
303
  showModel: () => boolean = () => false,
321
304
  ) {
@@ -340,8 +323,8 @@ export class AgentWidget {
340
323
  * only proven-foreground runs drop out — nothing else silently vanishes.
341
324
  * - `all`: every agent.
342
325
  */
343
- private widgetAgents() {
344
- const all = this.manager.listAgents().filter(isTopLevelAgent);
326
+ private widgetAgentsFromManager(): AgentRecord[] {
327
+ const all = this.manager.listAgents();
345
328
  switch (this.mode()) {
346
329
  case "off": return [];
347
330
  case "background": return all.filter(a => a.isBackground !== false);
@@ -349,130 +332,245 @@ export class AgentWidget {
349
332
  }
350
333
  }
351
334
 
352
- /** Temporarily stop global navigation from consuming input handled by another UI surface. */
353
- suspendNavigation(): void {
354
- this.navigationSuspended = true;
335
+ /** Records currently visible to the widget; safe for render and input paths. */
336
+ private widgetAgents(): AgentRecord[] {
337
+ return this.rosterCacheInitialized ? this.cachedAgents : this.widgetAgentsFromManager();
355
338
  }
356
339
 
357
- /** Resume global navigation after another UI surface has closed. */
358
- resumeNavigation(): void {
359
- this.navigationSuspended = false;
340
+ private canOpenHistory(record: AgentRecord): boolean {
341
+ return this.openOptions.canOpenHistory?.(record) ?? true;
342
+ }
343
+
344
+ private historyOpenabilityKey(record: AgentRecord): string {
345
+ return JSON.stringify([
346
+ record.status,
347
+ record.completedAt ?? null,
348
+ record.transcriptPath ?? null,
349
+ record.session !== undefined,
350
+ ]);
351
+ }
352
+
353
+ /**
354
+ * Cache terminal history capability by the record state that can affect it.
355
+ * The supplied predicate may call `existsSync`, so it must not run from a
356
+ * timer refresh, render-key calculation, or arrow-navigation path more than
357
+ * once for the same terminal record state.
358
+ */
359
+ private cachedCanOpenHistory(record: AgentRecord): boolean {
360
+ if (record.status === "running" || record.status === "queued") return true;
361
+
362
+ const key = this.historyOpenabilityKey(record);
363
+ const cached = this.historyOpenabilityCache.get(record.id);
364
+ if (cached?.key === key) return cached.value;
365
+
366
+ const value = this.canOpenHistory(record);
367
+ this.historyOpenabilityCache.set(record.id, { key, value });
368
+ return value;
369
+ }
370
+
371
+ /** Refresh the manager snapshot and openability cache at lifecycle/update time. */
372
+ private refreshRoster(): AgentRecord[] {
373
+ const agents = this.widgetAgentsFromManager();
374
+ const key = JSON.stringify({
375
+ mode: this.mode(),
376
+ agents: agents.map(record => [
377
+ record.id,
378
+ record.type,
379
+ record.description,
380
+ record.status,
381
+ record.completedAt ?? null,
382
+ record.startedAt,
383
+ record.toolUses,
384
+ record.error ?? null,
385
+ record.transcriptPath ?? null,
386
+ record.session !== undefined,
387
+ record.isBackground,
388
+ record.status !== "running" && record.status !== "queued"
389
+ ? this.cachedCanOpenHistory(record)
390
+ : undefined,
391
+ ]),
392
+ });
393
+ if (this.rosterCacheInitialized && key === this.rosterCacheKey) return this.cachedRoster;
394
+
395
+ const finished = agents.filter(record =>
396
+ record.status !== "running" && record.status !== "queued"
397
+ && record.completedAt !== undefined
398
+ && this.cachedCanOpenHistory(record),
399
+ );
400
+ const running = agents.filter(record => record.status === "running");
401
+ const queued = agents.filter(record => record.status === "queued");
402
+ this.cachedAgents = agents;
403
+ this.cachedRoster = [...running, ...queued, ...finished];
404
+ this.rosterCacheKey = key;
405
+ this.rosterCacheInitialized = true;
406
+ return this.cachedRoster;
360
407
  }
361
408
 
362
409
  /** Set the UI context (grabbed from first tool execution). */
363
410
  setUICtx(ctx: UICtx): boolean {
364
411
  if (ctx === this.uiCtx) return false;
365
- this.inputCleanup?.();
366
- this.inputCleanup = undefined;
412
+
413
+ // UICtx changed — the widget and input handler registered on the old
414
+ // context are gone. Re-register both on the next update().
415
+ this.inputUnsub?.();
416
+ this.inputUnsub = undefined;
367
417
  this.uiCtx = ctx;
368
418
  this.widgetRegistered = false;
369
419
  this.tui = undefined;
370
420
  this.lastStatusText = undefined;
371
- this.navigationSuspended = false;
421
+ this.lastRenderKey = undefined;
372
422
  this.navigationActive = false;
373
423
  this.selectedAgentId = undefined;
424
+ this.selectedRosterIndex = 0;
374
425
  this.viewportStart = 0;
375
- if (ctx.onTerminalInput) this.inputCleanup = ctx.onTerminalInput(data => this.handleInput(data));
426
+ this.cachedAgents = [];
427
+ this.cachedRoster = [];
428
+ this.rosterCacheKey = undefined;
429
+ this.rosterCacheInitialized = false;
430
+ this.historyOpenabilityCache.clear();
431
+ // Print/RPC tests and lightweight embedders may provide only the widget
432
+ // surface; real interactive contexts always implement this hook.
433
+ if (typeof ctx.onTerminalInput === "function") {
434
+ this.inputUnsub = ctx.onTerminalInput(data => this.handleKey(data));
435
+ }
376
436
  return true;
377
437
  }
378
438
 
379
- /**
380
- * Called on each new turn (tool_execution_start).
381
- * Ages finished agents and clears those that have lingered long enough.
382
- */
439
+ /** Request a render on the currently registered TUI without touching input. */
440
+ requestUiRefresh(force = true): boolean {
441
+ if (!this.tui || typeof this.tui.requestRender !== "function") return false;
442
+ this.tui.requestRender(force);
443
+ return true;
444
+ }
445
+
446
+ /** Called on each new turn (tool_execution_start). */
383
447
  onTurnStart() {
384
- // Age all finished agents
385
- for (const [id, age] of this.finishedTurnAge) {
386
- this.finishedTurnAge.set(id, age + 1);
387
- }
388
- // Trigger a widget refresh (will filter out expired agents)
389
448
  this.update();
390
449
  }
391
450
 
392
- /** Ensure the widget update timer is running. */
451
+ /** Keep the spinner/elapsed-time timer alive only while a visible agent runs. */
393
452
  ensureTimer() {
453
+ if (!this.uiCtx) return;
454
+ const roster = this.rosterCacheInitialized ? this.cachedRoster : this.refreshRoster();
455
+ if (!roster.some(a => a.status === "running")) return;
394
456
  if (!this.widgetInterval) {
395
457
  this.widgetInterval = setInterval(() => this.update(true), 250);
396
458
  }
397
459
  }
398
460
 
399
- /** Check if a finished agent should still be shown in the widget. */
400
- private shouldShowFinished(agentId: string, status: string, durable = false): boolean {
401
- // A persisted transcript is a durable history row, not a transient
402
- // completion notification. Keep it navigable after the one-turn visual
403
- // linger expires; runtime GC must not make `/agents` history disappear.
404
- if (durable) return true;
405
- const age = this.finishedTurnAge.get(agentId) ?? 0;
406
- const maxAge = ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_TURNS : 1;
407
- return age < maxAge;
408
- }
409
-
410
- /** Record an agent as finished (call when agent completes). */
411
- markFinished(agentId: string) {
412
- if (!this.finishedTurnAge.has(agentId)) {
413
- this.finishedTurnAge.set(agentId, 0);
461
+ private syncTimer(shouldRun: boolean): void {
462
+ if (shouldRun) {
463
+ this.ensureTimer();
464
+ } else if (this.widgetInterval) {
465
+ clearInterval(this.widgetInterval);
466
+ this.widgetInterval = undefined;
414
467
  }
415
468
  }
416
469
 
417
470
  /**
418
- * Drop an agent's finished-age (call when a settled agent starts running
419
- * again, i.e. a background resume). markFinished only seeds an age it has not
420
- * seen before, so a resumed agent would otherwise keep the age from its
421
- * previous run — already past the linger limit, hiding the new run's
422
- * completion line entirely.
471
+ * Retained for the lifecycle call sites. Terminal visibility is determined
472
+ * by the manager record and the history capability, not a one-turn timer.
423
473
  */
424
- markRunning(agentId: string) {
425
- this.finishedTurnAge.delete(agentId);
426
- }
474
+ markFinished(_agentId: string) {}
427
475
 
428
- private navigationAgents(): AgentRecord[] {
429
- const agents = this.widgetAgents().filter(agent =>
430
- agent.status === "running" || agent.status === "queued" || (agent.completedAt !== undefined && this.shouldShowFinished(agent.id, agent.status, agent.transcriptPath !== undefined)),
431
- );
432
- return agents.filter(agent =>
433
- agent.status === "running" || agent.status === "queued" || (this.openOptions.canOpenHistory?.(agent) ?? true),
434
- ).sort((a, b) => {
435
- const activeA = a.status === "running" || a.status === "queued" ? 0 : 1;
436
- const activeB = b.status === "running" || b.status === "queued" ? 0 : 1;
437
- return activeA - activeB;
438
- });
439
- }
476
+ /** Retained for lifecycle call sites; terminal rows are record-driven now. */
477
+ markRunning(_agentId: string) {}
440
478
 
441
- private updateViewport(roster: AgentRecord[]): void {
442
- const budget = getWidgetLineBudget(this.tui?.terminal?.rows ?? 24);
443
- const visibleRows = Math.max(1, budget - 1);
444
- if (this.selectedRosterIndex < this.viewportStart) this.viewportStart = this.selectedRosterIndex;
445
- if (this.selectedRosterIndex >= this.viewportStart + visibleRows) this.viewportStart = this.selectedRosterIndex - visibleRows + 1;
446
- this.viewportStart = Math.max(0, Math.min(this.viewportStart, Math.max(0, roster.length - visibleRows)));
479
+ /**
480
+ * Records represented by selectable rows in the above-editor widget.
481
+ *
482
+ * Keep this order as the single source of truth for both rendering and key
483
+ * navigation. `listAgents()` is newest-first; active rows come first so the
484
+ * panel exposes currently useful work before terminal history.
485
+ */
486
+ private roster(): AgentRecord[] {
487
+ return this.rosterCacheInitialized ? this.cachedRoster : this.refreshRoster();
447
488
  }
448
489
 
490
+ /** True when pi's prompt editor owns the keyboard. */
449
491
  private editorHasFocus(): boolean {
450
492
  const focused = (this.tui as { focusedComponent?: unknown } | undefined)?.focusedComponent;
451
493
  return focused == null || focused instanceof Editor;
452
494
  }
453
495
 
496
+ private selectedIndexOf(records: readonly AgentRecord[]): number {
497
+ if (!this.selectedAgentId) return -1;
498
+ return records.findIndex(record => record.id === this.selectedAgentId);
499
+ }
500
+
454
501
  private deactivate(): void {
502
+ // Keep the selected row and viewport so re-entering navigation can resume
503
+ // where the user left off. Lifecycle resets (context, dispose, empty
504
+ // roster) clear this state explicitly instead of treating every exit as a
505
+ // reset.
455
506
  this.navigationActive = false;
456
507
  this.requestUiRefresh();
457
508
  }
458
509
 
459
- private handleInput(data: string): { consume?: boolean; data?: string } | undefined {
510
+ /** Resume navigation from the retained row, or select the first row. */
511
+ private activate(records: readonly AgentRecord[]): void {
512
+ this.navigationActive = true;
513
+ const selectedIndex = this.selectedIndexOf(records);
514
+ if (selectedIndex >= 0) {
515
+ this.selectedRosterIndex = selectedIndex;
516
+ } else {
517
+ // The previously selected row may have been cleaned up while navigation
518
+ // was inactive. Resume at its old logical position, clamped to the new
519
+ // roster, rather than jumping back to the first row.
520
+ const fallbackIndex = Math.max(0, Math.min(this.selectedRosterIndex, records.length - 1));
521
+ this.selectedAgentId = records[fallbackIndex].id;
522
+ this.selectedRosterIndex = fallbackIndex;
523
+ this.viewportStart = Math.min(this.viewportStart, Math.max(0, records.length - 1));
524
+ }
525
+ this.requestUiRefresh();
526
+ }
527
+
528
+ /** Move the selected row, activating only from an empty focused editor. */
529
+ private moveSelection(direction: -1 | 1): boolean {
530
+ const records = this.roster();
531
+ const ui = this.uiCtx;
532
+ if (records.length === 0 || !ui) return false;
533
+
534
+ if (!this.navigationActive) {
535
+ if (direction !== 1 || !this.editorHasFocus() || (ui.getEditorText?.() ?? "") !== "") return false;
536
+ this.activate(records);
537
+ return true;
538
+ }
539
+
540
+ const currentIndex = Math.max(0, this.selectedIndexOf(records));
541
+ if (direction === -1 && currentIndex === 0) {
542
+ this.deactivate();
543
+ return true;
544
+ }
545
+ const nextIndex = Math.max(0, Math.min(records.length - 1, currentIndex + direction));
546
+ this.selectedAgentId = records[nextIndex].id;
547
+ this.selectedRosterIndex = nextIndex;
548
+ this.requestUiRefresh();
549
+ return true;
550
+ }
551
+
552
+ private openSelected(): void {
553
+ const record = this.roster().find(candidate => candidate.id === this.selectedAgentId);
554
+ this.deactivate();
555
+ if (!record) return;
556
+ const mode: AgentWidgetOpenMode = record.status === "running" || record.status === "queued" ? "live" : "history";
557
+ void this.openOptions.onOpen?.(record, mode);
558
+ }
559
+
560
+ /** Handle terminal input before it reaches the focused prompt editor. */
561
+ handleKey(data: string): { consume?: boolean; data?: string } | undefined {
460
562
  if (!this.uiCtx || isKeyRelease(data)) return undefined;
461
- if (this.navigationSuspended) return undefined;
462
563
  if (!this.editorHasFocus()) {
463
564
  if (this.navigationActive) this.deactivate();
464
565
  return undefined;
465
566
  }
466
567
 
467
568
  if (!this.navigationActive) {
468
- const roster = this.navigationAgents();
469
- if (!matchesKey(data, "down") || (this.uiCtx.getEditorText?.() ?? "") !== "" || roster.length === 0) return undefined;
470
- this.navigationActive = true;
471
- const index = this.selectedAgentId ? roster.findIndex(agent => agent.id === this.selectedAgentId) : -1;
472
- this.selectedRosterIndex = index >= 0 ? index : 0;
473
- this.selectedAgentId = roster[this.selectedRosterIndex]?.id;
474
- this.updateViewport(roster);
475
- this.requestUiRefresh();
569
+ const records = this.roster();
570
+ if (!matchesKey(data, "down") || (this.uiCtx.getEditorText?.() ?? "") !== "" || records.length === 0) {
571
+ return undefined;
572
+ }
573
+ this.activate(records);
476
574
  return { consume: true };
477
575
  }
478
576
 
@@ -480,47 +578,19 @@ export class AgentWidget {
480
578
  this.deactivate();
481
579
  return { consume: true };
482
580
  }
483
- if (matchesKey(data, "up") || matchesKey(data, "down")) {
484
- const roster = this.navigationAgents();
485
- if (roster.length === 0) return { consume: true };
486
- if (matchesKey(data, "up") && this.selectedRosterIndex === 0) {
487
- this.deactivate();
488
- } else {
489
- this.selectedRosterIndex = Math.max(0, Math.min(roster.length - 1, this.selectedRosterIndex + (matchesKey(data, "down") ? 1 : -1)));
490
- this.selectedAgentId = roster[this.selectedRosterIndex]?.id;
491
- this.updateViewport(roster);
492
- this.requestUiRefresh();
493
- }
494
- return { consume: true };
495
- }
581
+ if (matchesKey(data, "up")) return this.moveSelection(-1) ? { consume: true } : undefined;
582
+ if (matchesKey(data, "down")) return this.moveSelection(1) ? { consume: true } : undefined;
496
583
  if (matchesKey(data, Key.enter)) {
497
- const record = this.navigationAgents()[this.selectedRosterIndex];
498
- if (record) {
499
- const terminal = record.status !== "running" && record.status !== "queued";
500
- if (!terminal || (this.openOptions.canOpenHistory?.(record) ?? true)) {
501
- this.openOptions.onOpen?.(record, terminal ? "history" : "live");
502
- }
503
- }
584
+ this.openSelected();
504
585
  return { consume: true };
505
586
  }
506
587
 
507
- // Only arrow keys navigate. Other keys flow to the editor and leave navigation mode.
588
+ // Only ↑/↓ navigate. Other keys, including j/k/←/→, flow to the editor
589
+ // and leave navigation mode.
508
590
  this.deactivate();
509
591
  return undefined;
510
592
  }
511
593
 
512
- private requestUiRefresh(force = true): boolean {
513
- if (!this.tui || typeof this.tui.requestRender !== "function") return false;
514
- this.tui.requestRender(force);
515
- return true;
516
- }
517
-
518
- private selectionBullet(agentId: string, theme: Theme): string {
519
- return this.navigationActive && this.selectedAgentId === agentId
520
- ? theme.fg("accent", "●")
521
- : theme.fg("dim", "○");
522
- }
523
-
524
594
  /** Render a finished agent line. */
525
595
  private renderFinishedLine(a: { id: string; type: SubagentType; status: string; description: string; toolUses: number; startedAt: number; completedAt?: number; error?: string; lifetimeUsage?: LifetimeUsage }, theme: Theme): string {
526
596
  const modeLabel = getPromptModeLabel(a.type);
@@ -539,7 +609,7 @@ export class AgentWidget {
539
609
  statusText = theme.fg("dim", " stopped");
540
610
  } else if (a.status === "error") {
541
611
  icon = theme.fg("error", "✗");
542
- const errMsg = a.error ? `: ${a.error.slice(0, 60)}` : "";
612
+ const errMsg = a.error ? `: ${truncateLine(a.error)}` : "";
543
613
  statusText = theme.fg("error", ` error${errMsg}`);
544
614
  } else {
545
615
  // aborted
@@ -551,15 +621,12 @@ export class AgentWidget {
551
621
  const activity = this.agentActivity.get(a.id);
552
622
  if (activity) parts.push(formatTurns(activity.turnCount, activity.maxTurns));
553
623
  if (a.toolUses > 0) parts.push(`${a.toolUses} tool use${a.toolUses === 1 ? "" : "s"}`);
554
- // From the record, not the activity tracker: that entry is deleted the
555
- // moment an agent finishes, and "what did it cost" is a question asked
556
- // about finished agents.
557
- const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
624
+ const costText = this.showCost() && a.lifetimeUsage ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
558
625
  if (costText) parts.push(costText);
559
626
  parts.push(duration);
560
627
 
561
628
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
562
- const description = a.description.replace(/[\r\n]+/g, " ");
629
+ const description = truncateLine(a.description);
563
630
  return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", description)} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
564
631
  }
565
632
 
@@ -568,14 +635,12 @@ export class AgentWidget {
568
635
  * reading live state each time instead of capturing it in a closure.
569
636
  */
570
637
  private renderWidget(tui: any, theme: Theme): string[] {
571
- const allAgents = this.widgetAgents();
572
- const running = allAgents.filter(a => a.status === "running");
573
- const queued = allAgents.filter(a => a.status === "queued");
574
- const finished = allAgents.filter(a =>
575
- a.status !== "running" && a.status !== "queued" && a.completedAt
576
- && this.shouldShowFinished(a.id, a.status, a.transcriptPath !== undefined),
577
- );
638
+ const roster = this.roster();
639
+ const running = roster.filter(a => a.status === "running");
640
+ const queued = roster.filter(a => a.status === "queued");
641
+ const finished = roster.filter(a => a.status !== "running" && a.status !== "queued");
578
642
 
643
+ const selectedId = this.navigationActive ? this.selectedAgentId : undefined;
579
644
  const hasActive = running.length > 0 || queued.length > 0;
580
645
  const hasFinished = finished.length > 0;
581
646
 
@@ -583,9 +648,9 @@ export class AgentWidget {
583
648
  if (!hasActive && !hasFinished) return [];
584
649
 
585
650
  const w = tui.terminal.columns;
586
- const budget = getWidgetLineBudget(tui.terminal.rows ?? 24);
587
- if (budget === 0) return [];
588
- const truncate = (line: string) => truncateToWidth(line.replace(/[\r\n]+/g, " "), w);
651
+ const maxLines = getWidgetLineBudget(tui.terminal.rows);
652
+ if (maxLines === 0) return [];
653
+ const truncate = (line: string, width = w) => truncateToWidth(line, Math.max(0, width));
589
654
  const headingColor = hasActive ? "accent" : "dim";
590
655
  const headingIcon = hasActive ? "●" : "○";
591
656
  const frame = SPINNER[this.widgetFrame % SPINNER.length];
@@ -593,12 +658,18 @@ export class AgentWidget {
593
658
  // Build sections separately for overflow-aware assembly.
594
659
  // Each running agent = 2 lines (header + activity), finished = 1 line, queued = 1 line.
595
660
 
596
- const finishedLines: string[] = [];
661
+ type WidgetRow = { record: AgentRecord; lines: string[]; recordCount?: number };
662
+
663
+ const finishedLines: WidgetRow[] = [];
597
664
  for (const a of finished) {
598
- finishedLines.push(truncate(theme.fg("dim", "├─") + ` ${this.selectionBullet(a.id, theme)} ` + this.renderFinishedLine(a, theme)));
665
+ const marker = a.id === selectedId ? theme.fg("accent", "●") : theme.fg("dim", "○");
666
+ finishedLines.push({
667
+ record: a,
668
+ lines: [truncate(theme.fg("dim", "├─") + ` ${marker} ` + this.renderFinishedLine(a, theme))],
669
+ });
599
670
  }
600
671
 
601
- const runningLines: string[][] = []; // each entry is [header, activity]
672
+ const runningLines: WidgetRow[] = []; // each entry is [header, activity]
602
673
  for (const a of running) {
603
674
  const modeLabel = getPromptModeLabel(a.type);
604
675
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
@@ -607,9 +678,7 @@ export class AgentWidget {
607
678
  const bg = this.agentActivity.get(a.id);
608
679
  const toolUses = bg?.toolUses ?? a.toolUses;
609
680
  // Spend comes from the record, never from the activity tracker: the record
610
- // is the one that survives the agent finishing, and the one nested-tools
611
- // folds a hidden child's spend into. Reading the tracker while an agent
612
- // runs and the record once it stops made the figure jump at completion.
681
+ // survives the agent finishing and includes nested-child usage.
613
682
  const tokens = getLifetimeTotal(a.lifetimeUsage);
614
683
  const contextPercent = getSessionContextPercent(bg?.session);
615
684
  const tokenText = tokens > 0 ? formatSessionTokens(tokens, contextPercent, theme, a.compactionCount) : "";
@@ -617,9 +686,6 @@ export class AgentWidget {
617
686
 
618
687
  const parts: string[] = [];
619
688
  if (this.showModel()) {
620
- // Leading, and paired: a thinking level means nothing without the model
621
- // it applies to. The tag is taken from buildInvocationTags rather than
622
- // rebuilt so the "(asked X)" annotation survives.
623
689
  const { modelName, tags } = buildInvocationTags(a.invocation);
624
690
  if (modelName) parts.push(modelName);
625
691
  const thinkingTag = tags.find(tag => tag.startsWith("thinking: "));
@@ -632,159 +698,305 @@ export class AgentWidget {
632
698
  parts.push(elapsed);
633
699
  const statsText = parts.join(" · ");
634
700
 
635
- const activity = (bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…").replace(/[\r\n]+/g, " ");
701
+ const activity = bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…";
636
702
 
637
- runningLines.push([
638
- truncate(theme.fg("dim", "├─") + ` ${this.selectionBullet(a.id, theme)} ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", a.description)} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
639
- truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${activity}`)),
640
- ]);
703
+ const marker = a.id === selectedId ? theme.fg("accent", "●") : theme.fg("dim", "○");
704
+ runningLines.push({
705
+ record: a,
706
+ lines: [
707
+ truncate(theme.fg("dim", "├─") + ` ${marker} ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", truncateLine(a.description))} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
708
+ truncate(theme.fg("dim", "│ ") + ` ${theme.fg("dim", `⎿ ${truncateLine(activity)}`)}`),
709
+ ],
710
+ });
641
711
  }
642
712
 
643
- const selectedQueued = this.navigationActive && this.selectedAgentId !== undefined && queued.some(agent => agent.id === this.selectedAgentId);
644
- const queuedLine = queued.length > 0
645
- ? truncate(theme.fg("dim", "├─") + ` ${selectedQueued ? theme.fg("accent", "●") : theme.fg("dim", "○")} ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)
646
- : undefined;
647
-
648
- // Assemble with overflow cap (heading + overflow indicator = 2 reserved lines).
649
- const maxBody = Math.max(1, budget - 1); // heading takes 1 line
650
- const totalBody = finishedLines.length + runningLines.length * 2 + (queuedLine ? 1 : 0);
713
+ const queuedLines: WidgetRow[] = queued.map(a => {
714
+ const marker = a.id === selectedId ? theme.fg("accent", "●") : theme.fg("dim", "○");
715
+ return {
716
+ record: a,
717
+ lines: [truncate(theme.fg("dim", "├─") + ` ${marker} ${theme.fg("muted", "◦")} ${theme.fg("dim", `${getDisplayName(a.type)} ${truncateLine(a.description)} · queued`)}`)],
718
+ };
719
+ });
651
720
 
652
- const hint = "↑↓ select · enter view · esc back";
653
- const lines: string[] = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents") + " " + theme.fg("dim", hint))];
721
+ // Keep the idle widget compact: a queue is one logical status line until
722
+ // navigation starts. While navigating, expand it back to the same per-agent
723
+ // roster used by key handling so every selected queued record can render.
724
+ const queuedSummary: WidgetRow[] = queued.length > 0 && !this.navigationActive
725
+ ? [{
726
+ record: queued[0],
727
+ recordCount: queued.length,
728
+ lines: [truncate(theme.fg("dim", "├─") + ` ${theme.fg("dim", "○")} ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)],
729
+ }]
730
+ : [];
731
+
732
+ // Assemble with a responsive cap (heading + overflow indicator = 2
733
+ // reserved lines when content exceeds the available body budget).
734
+ const maxBody = maxLines - 1; // heading takes 1 line
735
+ const rows: WidgetRow[] = [
736
+ ...runningLines,
737
+ ...(this.navigationActive ? queuedLines : queuedSummary),
738
+ ...finishedLines,
739
+ ];
740
+ const totalBody = rows.reduce((total, row) => total + row.lines.length, 0);
741
+
742
+ const heading = "Agents ↑↓ select · enter view · esc back";
743
+ const lines: string[] = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, heading))];
744
+
745
+ if (maxLines === 1) {
746
+ // There is room only for the heading; do not consume the editor/input row.
747
+ return lines;
748
+ }
654
749
 
655
750
  if (totalBody <= maxBody) {
656
- // Everything fits — add all lines and fix up connectors for the last item.
657
- lines.push(...finishedLines);
658
- for (const pair of runningLines) lines.push(...pair);
659
- if (queuedLine) lines.push(queuedLine);
660
-
661
- // Fix last connector: swap ├─ → └─ and │ → space for activity lines.
662
- if (lines.length > 1) {
663
- const last = lines.length - 1;
664
- lines[last] = lines[last].replace("├─", "└─");
665
- // If last item is a running agent activity line, fix indent of that line
666
- // and fix the header line above it.
667
- if (runningLines.length > 0 && !queuedLine) {
668
- // The last two lines are the last running agent's header + activity.
669
- if (last >= 2) {
670
- lines[last - 1] = lines[last - 1].replace("├─", "└─");
671
- lines[last] = lines[last].replace("│ ", " ");
672
- }
751
+ this.viewportStart = 0;
752
+ for (const row of rows) lines.push(...row.lines);
753
+ if (rows.length > 0) {
754
+ const lastRow = rows[rows.length - 1];
755
+ const lastStart = lines.length - lastRow.lines.length;
756
+ // Keep the selected row's bullet adjacent to the normal branch marker.
757
+ // This makes the active row unambiguous even when it is the last row.
758
+ const lastRowSelected = this.navigationActive && lastRow.record.id === selectedId;
759
+ if (!lastRowSelected) lines[lastStart] = lines[lastStart].replace("├─", "└─");
760
+ if (lastRow.lines.length === 2) {
761
+ lines[lastStart + 1] = lines[lastStart + 1].replace("│ ", " ");
673
762
  }
674
763
  }
675
- } else {
676
- // Overflow — prioritize: running > queued > finished.
677
- // Reserve 1 line for overflow indicator.
678
- let budget = maxBody - 1;
679
- let hiddenRunning = 0;
680
- let hiddenFinished = 0;
681
-
682
- // Reserve the queued line's row up front. It is a single summary of N
683
- // waiting agents, so it cannot be folded into the "+N more" count (which
684
- // is denominated in agents) without either under-reporting it as 1 or
685
- // inflating the total with agents that were never getting their own rows.
686
- // Reserving costs at most one running agent — which IS counted below —
687
- // and makes the drop unreachable. It matters most exactly when it used to
688
- // vanish: the pool is saturated and the queue is what the user needs to see.
689
- const queuedReserve = queuedLine ? 1 : 0;
690
- budget -= queuedReserve;
691
-
692
- // 1. Running agents (2 lines each)
693
- for (const pair of runningLines) {
694
- if (budget >= 2) {
695
- lines.push(...pair);
696
- budget -= 2;
764
+ } else if (!this.navigationActive && queuedSummary.length > 0) {
765
+ // In the idle view the queue is deliberately one summary row. Preserve
766
+ // that row before spending space on terminal history, and account for
767
+ // the real number of queued records if the summary itself cannot fit.
768
+ // Navigation expands the queue into per-record rows and uses the full
769
+ // contiguous viewport below.
770
+ const visibleRows: WidgetRow[] = [];
771
+ const hiddenRows: WidgetRow[] = [];
772
+ let bodyBudget = Math.max(0, maxBody - 1); // reserve the footer
773
+ let runningBudget = Math.max(0, bodyBudget - 1); // reserve queued summary
774
+
775
+ for (const row of runningLines) {
776
+ const height = row.lines.length;
777
+ if (height <= runningBudget) {
778
+ visibleRows.push(row);
779
+ runningBudget -= height;
780
+ bodyBudget -= height;
697
781
  } else {
698
- hiddenRunning++;
782
+ hiddenRows.push(row);
699
783
  }
700
784
  }
701
785
 
702
- // 2. Queued line (always fits — its row was reserved above)
703
- if (queuedLine) {
704
- budget += queuedReserve;
705
- lines.push(queuedLine);
706
- budget--;
786
+ const summaryRow = queuedSummary[0];
787
+ if (bodyBudget > 0) {
788
+ visibleRows.push(summaryRow);
789
+ bodyBudget -= summaryRow.lines.length;
790
+ } else {
791
+ hiddenRows.push(summaryRow);
707
792
  }
708
793
 
709
- // 3. Finished agents
710
- for (const fl of finishedLines) {
711
- if (budget >= 1) {
712
- lines.push(fl);
713
- budget--;
794
+ for (const row of finishedLines) {
795
+ const height = row.lines.length;
796
+ if (height <= bodyBudget) {
797
+ visibleRows.push(row);
798
+ bodyBudget -= height;
714
799
  } else {
715
- hiddenFinished++;
800
+ hiddenRows.push(row);
716
801
  }
717
802
  }
718
803
 
719
- // Overflow summary
720
- // On extremely short terminals the queued summary itself consumes the
721
- // last useful row; keep its count in the compact footer. At the normal
722
- // 12-line ceiling the summary is a single visible row and must not be
723
- // counted as hidden agents.
724
- const hiddenQueued = queuedLine && (tui.terminal.rows ?? 24) < 10 ? queued.length : 0;
725
- const overflowParts: string[] = [];
726
- if (hiddenRunning > 0) overflowParts.push(`${hiddenRunning} running`);
727
- if (hiddenFinished > 0) overflowParts.push(`${hiddenFinished} finished`);
728
- if (hiddenQueued > 0) overflowParts.push(`${hiddenQueued} queued`);
729
- const hiddenTotal = hiddenRunning + hiddenFinished + hiddenQueued;
730
- const overflowText = overflowParts.join(", ");
731
- lines.push(truncate(theme.fg("dim", "└─") + ` ${theme.fg("dim", `+${hiddenTotal} more (${overflowText})`)}`)
732
- );
733
- }
804
+ for (const row of visibleRows) lines.push(...row.lines);
805
+ if (visibleRows.length > 0) {
806
+ const lastRow = visibleRows[visibleRows.length - 1];
807
+ const lastStart = lines.length - lastRow.lines.length;
808
+ lines[lastStart] = lines[lastStart].replace("├─", "└─");
809
+ if (lastRow.lines.length === 2) {
810
+ lines[lastStart + 1] = lines[lastStart + 1].replace("│ ", " ");
811
+ }
812
+ }
734
813
 
735
- if (this.navigationActive) {
736
- const roster = this.navigationAgents();
737
- const selected = roster[this.selectedRosterIndex];
738
- const hasSelected = selected ? lines.some(line => line.includes(selected.description.replace(/[\r\n]+/g, " "))) : true;
739
- if (selected && !hasSelected) {
740
- const selectedLine = truncate(theme.fg("dim", "└─") + ` ${this.selectionBullet(selected.id, theme)} ${selected.status === "queued" ? "◦" : "⠋"} ${theme.fg("muted", selected.description.replace(/[\r\n]+/g, " "))}`);
741
- if (lines.length >= budget) lines[lines.length - 1] = selectedLine;
742
- else lines.push(selectedLine);
814
+ const hiddenCount = (rows: readonly WidgetRow[]): number =>
815
+ rows.reduce((total, row) => total + (row.recordCount ?? 1), 0);
816
+ const categoryCount = (status: string): number => hiddenRows
817
+ .filter(row => row.record.status === status)
818
+ .reduce((total, row) => total + (row.recordCount ?? 1), 0);
819
+ const finishedCount = hiddenRows
820
+ .filter(row => row.record.status !== "running" && row.record.status !== "queued")
821
+ .reduce((total, row) => total + (row.recordCount ?? 1), 0);
822
+ const categoryCounts: string[] = [
823
+ ["running", categoryCount("running")] as [string, number],
824
+ ["queued", categoryCount("queued")] as [string, number],
825
+ ["finished", finishedCount] as [string, number],
826
+ ].filter(([, count]) => count > 0).map(([label, count]) => `${count} ${label}`);
827
+ const hidden = hiddenCount(hiddenRows);
828
+ lines.push(truncate(theme.fg("dim", "└─") + ` ${theme.fg("dim", `+${hidden} more (${categoryCounts.join(", ")})`)}`));
829
+ } else {
830
+ // Reserve one line for a directional overflow summary. The viewport is
831
+ // a contiguous slice in roster order, so the same slice is navigable and
832
+ // renderable even when the selected row is currently hidden.
833
+ const baseContentBudget = Math.max(0, maxBody - 1);
834
+ const heightAt = (index: number) => rows[index]?.lines.length ?? 0;
835
+ const endFor = (start: number, budget: number): number => {
836
+ let used = 0;
837
+ let end = start;
838
+ while (end < rows.length && used + heightAt(end) <= budget) {
839
+ used += heightAt(end++);
840
+ }
841
+ return end;
842
+ };
843
+
844
+ let start = Math.max(0, Math.min(this.viewportStart, Math.max(0, rows.length - 1)));
845
+ const selectedIndex = this.navigationActive && selectedId
846
+ ? rows.findIndex(row => row.record.id === selectedId)
847
+ : -1;
848
+ if (selectedIndex >= 0) {
849
+ if (selectedIndex < start) start = selectedIndex;
850
+ if (selectedIndex >= endFor(start, baseContentBudget)) start = selectedIndex;
851
+ }
852
+
853
+ // Keep both directional affordances in the viewport chrome: the top
854
+ // count sits below the heading and the bottom count sits below the
855
+ // bounded roster. Each consumes one row when that direction is hidden.
856
+ let showTopMore = start > 0;
857
+ let contentBudget = Math.max(0, maxBody - (showTopMore ? 2 : 1));
858
+ if (selectedIndex >= 0 && selectedIndex >= endFor(start, contentBudget)) {
859
+ start = selectedIndex;
860
+ showTopMore = start > 0;
861
+ contentBudget = Math.max(0, maxBody - (showTopMore ? 2 : 1));
743
862
  }
744
- if (this.viewportStart > 0) {
745
- if (lines.length >= budget) lines.splice(1, 1, truncate(theme.fg("dim", "↑ more")));
746
- else lines.splice(1, 0, truncate(theme.fg("dim", "↑ more")));
863
+ this.viewportStart = start;
864
+
865
+ let used = 0;
866
+ let end = start;
867
+ const visibleBody: string[] = [];
868
+ while (end < rows.length && used + heightAt(end) <= contentBudget) {
869
+ visibleBody.push(...rows[end].lines);
870
+ used += heightAt(end);
871
+ end++;
747
872
  }
748
- const railStart = this.viewportStart > 0 ? 2 : 1;
749
- for (let index = railStart; index < lines.length; index++) {
750
- const plain = lines[index] ?? "";
751
- lines[index] = truncate(plain + (selected && plain.includes(selected.description.replace(/[\r\n]+/g, " ")) ? "┃" : "│"));
873
+ // A selected two-line row must remain addressable even if only one body
874
+ // line is available. Showing its header is preferable to hiding it.
875
+ if (end === start && rows[start] && contentBudget > 0) {
876
+ visibleBody.push(rows[start].lines[0]);
877
+ end = start + 1;
878
+ }
879
+
880
+ const countRows = (selectedRows: readonly WidgetRow[]): number =>
881
+ selectedRows.reduce((total, row) => total + (row.recordCount ?? 1), 0);
882
+ const hiddenBefore = countRows(rows.slice(0, start));
883
+ const hiddenAfter = countRows(rows.slice(end));
884
+ const hidden = hiddenBefore + hiddenAfter;
885
+ const hiddenRows = rows.filter((_row, index) => index < start || index >= end);
886
+ const categoryCount = (status: string): number => hiddenRows
887
+ .filter(row => row.record.status === status)
888
+ .reduce((total, row) => total + (row.recordCount ?? 1), 0);
889
+ const categoryCounts: string[] = [
890
+ ["running", categoryCount("running")] as [string, number],
891
+ ["queued", categoryCount("queued")] as [string, number],
892
+ ["finished", hiddenRows
893
+ .filter(row => row.record.status !== "running" && row.record.status !== "queued")
894
+ .reduce((total, row) => total + (row.recordCount ?? 1), 0)] as [string, number],
895
+ ].filter(([, count]) => count > 0).map(([label, count]) => `${count} ${label}`);
896
+ const direction = [
897
+ ...(hiddenBefore > 0 ? [`↑ ${hiddenBefore} more`] : []),
898
+ ...(hiddenAfter > 0 ? [`↓ ${hiddenAfter} more`] : []),
899
+ ].join(" · ");
900
+ const summary = `+${hidden} more (${direction}${categoryCounts.length > 0 ? `; ${categoryCounts.join(", ")}` : ""})`;
901
+
902
+ if (showTopMore) lines.push(truncate(theme.fg("dim", `↑ ${hiddenBefore} more`)));
903
+
904
+ // Fill the bounded viewport so the scrollbar track has a stable height.
905
+ while (visibleBody.length < contentBudget) visibleBody.push("");
906
+ const totalBody = rows.reduce((total, row) => total + row.lines.length, 0);
907
+ const startOffset = rows.slice(0, start).reduce((total, row) => total + row.lines.length, 0);
908
+ const trackHeight = Math.max(0, contentBudget);
909
+ const minThumbHeight = Math.min(2, trackHeight);
910
+ const thumbHeight = Math.max(
911
+ minThumbHeight,
912
+ Math.min(trackHeight, Math.round((trackHeight * trackHeight) / totalBody)),
913
+ );
914
+ const maxScrollTop = Math.max(0, totalBody - trackHeight);
915
+ const maxThumbTop = Math.max(0, trackHeight - thumbHeight);
916
+ const thumbOffset = maxScrollTop === 0
917
+ ? 0
918
+ : Math.round((startOffset / maxScrollTop) * maxThumbTop);
919
+ const contentWidth = Math.max(0, w - 1);
920
+ for (let index = 0; index < visibleBody.length; index++) {
921
+ const isThumb = index >= thumbOffset && index < thumbOffset + thumbHeight;
922
+ const scrollbar = isThumb
923
+ ? theme.fg("scrollbarThumb", this.navigationActive ? "█" : "┃")
924
+ : theme.fg("scrollbarTrack", "│");
925
+ const bodyLine = truncate(visibleBody[index] ?? "", contentWidth);
926
+ lines.push(bodyLine + " ".repeat(Math.max(0, contentWidth - visibleWidth(bodyLine))) + scrollbar);
927
+ }
928
+
929
+ // The directional count is outside the viewport, like ScrollView's
930
+ // surrounding chrome, and therefore does not consume scrollbar track.
931
+ if (hiddenAfter > 0) {
932
+ lines.push(truncate(theme.fg("dim", `↓ ${hiddenAfter} more · +${hidden} more (${categoryCounts.length > 0 ? categoryCounts.join(", ") : ""})`)));
933
+ } else if (!showTopMore) {
934
+ lines.push(truncate(theme.fg("dim", "└─") + ` ${theme.fg("dim", summary)}`));
935
+ } else {
936
+ // Keep a stable footer row when the selected viewport reaches the end.
937
+ lines.push(truncate(theme.fg("dim", "└─")));
752
938
  }
753
- if (lines.length > budget) lines.length = budget;
754
939
  }
940
+
755
941
  return lines;
756
942
  }
757
943
 
758
- /** Force an immediate widget update. */
944
+ /** Build a render-relevant snapshot without capturing mutable records. */
945
+ private renderKey(allAgents: ReturnType<AgentManager["listAgents"]>): string {
946
+ const activities = allAgents.map(a => {
947
+ const activity = this.agentActivity.get(a.id);
948
+ return activity ? {
949
+ id: a.id,
950
+ activeTools: [...activity.activeTools.entries()],
951
+ toolUses: activity.toolUses,
952
+ responseText: activity.responseText,
953
+ turnCount: activity.turnCount,
954
+ maxTurns: activity.maxTurns,
955
+ lifetimeUsage: activity.lifetimeUsage,
956
+ contextPercent: getSessionContextPercent(activity.session),
957
+ } : undefined;
958
+ });
959
+ return JSON.stringify({
960
+ frame: this.widgetFrame,
961
+ agents: allAgents.map(a => ({
962
+ id: a.id,
963
+ type: a.type,
964
+ description: a.description,
965
+ status: a.status,
966
+ toolUses: a.toolUses,
967
+ startedAt: a.startedAt,
968
+ completedAt: a.completedAt,
969
+ error: a.error,
970
+ lifetimeUsage: a.lifetimeUsage,
971
+ compactionCount: a.compactionCount,
972
+ isBackground: a.isBackground,
973
+ hasSession: a.session !== undefined,
974
+ transcriptPath: a.transcriptPath,
975
+ openableHistory: this.cachedCanOpenHistory(a),
976
+ })),
977
+ activities,
978
+ navigationActive: this.navigationActive,
979
+ selectedAgentId: this.selectedAgentId,
980
+ viewportStart: this.viewportStart,
981
+ });
982
+ }
983
+
984
+ /** Force an immediate widget update. `advanceSpinner` is reserved for the timer. */
759
985
  update(advanceSpinner = false) {
760
986
  if (!this.uiCtx) return;
987
+ // Refresh the manager snapshot once per lifecycle update. Arrow handling
988
+ // only changes selection and requests a render; it never scans the manager.
989
+ const roster = this.refreshRoster();
761
990
  const allAgents = this.widgetAgents();
762
- if (this.navigationActive || this.selectedAgentId) {
763
- const roster = this.navigationAgents();
764
- const selectedIndex = this.selectedAgentId ? roster.findIndex(agent => agent.id === this.selectedAgentId) : -1;
765
- if (selectedIndex >= 0) {
766
- this.selectedRosterIndex = selectedIndex;
767
- } else if (roster.length > 0 && this.selectedAgentId) {
768
- this.selectedRosterIndex = Math.min(this.selectedRosterIndex, roster.length - 1);
769
- this.selectedAgentId = roster[this.selectedRosterIndex]?.id;
770
- } else if (roster.length === 0) {
771
- this.navigationActive = false;
772
- this.selectedAgentId = undefined;
773
- this.selectedRosterIndex = 0;
774
- this.viewportStart = 0;
775
- }
776
- this.updateViewport(roster);
777
- }
778
991
 
779
992
  // Lightweight existence checks — full categorization happens in renderWidget()
780
993
  let runningCount = 0;
781
994
  let queuedCount = 0;
782
- let hasFinished = false;
783
- for (const a of allAgents) {
784
- if (a.status === "running") { runningCount++; }
785
- else if (a.status === "queued") { queuedCount++; }
786
- else if (a.completedAt && this.shouldShowFinished(a.id, a.status, a.transcriptPath !== undefined)) { hasFinished = true; }
995
+ for (const a of roster) {
996
+ if (a.status === "running") runningCount++;
997
+ else if (a.status === "queued") queuedCount++;
787
998
  }
999
+ const hasFinished = roster.some(a => a.status !== "running" && a.status !== "queued");
788
1000
  const hasActive = runningCount > 0 || queuedCount > 0;
789
1001
 
790
1002
  // Nothing to show — clear widget
@@ -798,11 +1010,12 @@ export class AgentWidget {
798
1010
  this.uiCtx.setStatus("subagents", undefined);
799
1011
  this.lastStatusText = undefined;
800
1012
  }
801
- if (this.widgetInterval) { clearInterval(this.widgetInterval); this.widgetInterval = undefined; }
802
- // Clean up stale entries
803
- for (const [id] of this.finishedTurnAge) {
804
- if (!allAgents.some(a => a.id === id)) this.finishedTurnAge.delete(id);
805
- }
1013
+ this.lastRenderKey = undefined;
1014
+ this.navigationActive = false;
1015
+ this.selectedAgentId = undefined;
1016
+ this.selectedRosterIndex = 0;
1017
+ this.viewportStart = 0;
1018
+ this.syncTimer(false);
806
1019
  return;
807
1020
  }
808
1021
 
@@ -820,26 +1033,30 @@ export class AgentWidget {
820
1033
  this.lastStatusText = newStatusText;
821
1034
  }
822
1035
 
1036
+ // Spinner animation is driven only by the timer while a visible running
1037
+ // agent exists. Event-driven updates refresh changed stats without making
1038
+ // an otherwise idle widget advance.
823
1039
  if (advanceSpinner && runningCount > 0) this.widgetFrame++;
824
-
825
- const snapshot = allAgents.map(agent => {
826
- const activity = this.agentActivity.get(agent.id);
827
- return [
828
- agent.id,
829
- agent.status,
830
- agent.description,
831
- agent.toolUses,
832
- agent.completedAt ?? "",
833
- this.finishedTurnAge.get(agent.id) ?? "",
834
- getLifetimeTotal(agent.lifetimeUsage),
835
- activity?.toolUses ?? "",
836
- activity?.responseText ?? "",
837
- Math.floor((Date.now() - agent.startedAt) / 1000),
838
- ].join("\u0000");
839
- }).join("\u0001");
840
- if (this.widgetRegistered && snapshot === this.lastSnapshot && !advanceSpinner) return;
841
- this.lastSnapshot = snapshot;
842
- if (!advanceSpinner) this.widgetFrame++;
1040
+ this.syncTimer(runningCount > 0);
1041
+ const selectedIndex = this.selectedIndexOf(roster);
1042
+ if (selectedIndex >= 0) {
1043
+ this.selectedRosterIndex = selectedIndex;
1044
+ } else if (this.navigationActive) {
1045
+ if (roster.length === 0) {
1046
+ this.navigationActive = false;
1047
+ this.selectedAgentId = undefined;
1048
+ this.selectedRosterIndex = 0;
1049
+ this.viewportStart = 0;
1050
+ } else {
1051
+ // Keep the selection near the row that disappeared. Both the saved
1052
+ // logical index and viewport are clamped as the roster shrinks.
1053
+ const fallbackIndex = Math.max(0, Math.min(this.selectedRosterIndex, roster.length - 1));
1054
+ this.selectedAgentId = roster[fallbackIndex].id;
1055
+ this.selectedRosterIndex = fallbackIndex;
1056
+ this.viewportStart = Math.min(this.viewportStart, roster.length - 1);
1057
+ }
1058
+ }
1059
+ const renderKey = this.renderKey(allAgents);
843
1060
 
844
1061
  // Register widget callback once; subsequent updates use requestRender()
845
1062
  // which re-invokes render() without replacing the component (avoids layout thrashing).
@@ -852,23 +1069,20 @@ export class AgentWidget {
852
1069
  // Theme changed — force re-registration so factory captures fresh theme.
853
1070
  this.widgetRegistered = false;
854
1071
  this.tui = undefined;
1072
+ this.lastRenderKey = undefined;
855
1073
  },
856
1074
  };
857
1075
  }, { placement: "aboveEditor" });
858
1076
  this.widgetRegistered = true;
859
- } else {
860
- // Widget already registered — just request a re-render of existing components.
1077
+ } else if (renderKey !== this.lastRenderKey) {
1078
+ // Widget already registered — request a re-render only when visible state
1079
+ // changed (or the spinner timer advanced).
861
1080
  this.tui?.requestRender();
862
1081
  }
1082
+ this.lastRenderKey = renderKey;
863
1083
  }
864
1084
 
865
1085
  dispose() {
866
- this.inputCleanup?.();
867
- this.inputCleanup = undefined;
868
- this.navigationActive = false;
869
- this.selectedAgentId = undefined;
870
- this.viewportStart = 0;
871
- this.selectedRosterIndex = 0;
872
1086
  if (this.widgetInterval) {
873
1087
  clearInterval(this.widgetInterval);
874
1088
  this.widgetInterval = undefined;
@@ -877,9 +1091,21 @@ export class AgentWidget {
877
1091
  this.uiCtx.setWidget("agents", undefined);
878
1092
  this.uiCtx.setStatus("subagents", undefined);
879
1093
  }
1094
+ this.inputUnsub?.();
1095
+ this.inputUnsub = undefined;
880
1096
  this.widgetRegistered = false;
881
1097
  this.tui = undefined;
882
1098
  this.lastStatusText = undefined;
883
- this.lastSnapshot = "";
1099
+ this.lastRenderKey = undefined;
1100
+ this.navigationActive = false;
1101
+ this.selectedAgentId = undefined;
1102
+ this.selectedRosterIndex = 0;
1103
+ this.viewportStart = 0;
1104
+ this.cachedAgents = [];
1105
+ this.cachedRoster = [];
1106
+ this.rosterCacheKey = undefined;
1107
+ this.rosterCacheInitialized = false;
1108
+ this.historyOpenabilityCache.clear();
1109
+ this.uiCtx = undefined;
884
1110
  }
885
1111
  }