@abelxiaoxing/cadence 2.0.24 → 2.0.26

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.
@@ -14,8 +14,12 @@ export const SUBAGENT_EVENTS = {
14
14
  /** Panel → producers: the agent whose transcript is shown (`id: null` when
15
15
  * none), so a producer can load messages for that one agent only. */
16
16
  export const SUBAGENT_VIEW = "subagent:view";
17
+ /** Session entry holding one finished batch's card; display only, never part
18
+ * of the model's context. */
19
+ export const CARD_ENTRY = "cadence-agent-batch";
17
20
 
18
21
  export type SubagentStatus = "running" | "done" | "error" | "cancelled";
22
+ type Ended = Exclude<SubagentStatus, "running">;
19
23
 
20
24
  export interface SubagentState {
21
25
  id: string;
@@ -45,6 +49,11 @@ export interface SubagentState {
45
49
 
46
50
  /** Retained messages per agent; older ones are counted, not kept. */
47
51
  export const MAX_MESSAGES = 2000;
52
+ /** Ended agents kept for review outside the open batch; older ones are
53
+ * dropped with their messages once a batch collapses into its card. */
54
+ export const MAX_ENDED = 24;
55
+ /** Agents written into one card; more are counted, not listed. */
56
+ export const MAX_CARD_AGENTS = 64;
48
57
  const ENDED = new Set(["done", "error", "cancelled"]);
49
58
 
50
59
  const record = (v: unknown): Record<string, unknown> | undefined =>
@@ -64,10 +73,18 @@ const count = (v: unknown) =>
64
73
  : undefined;
65
74
 
66
75
  /** Map<id, SubagentState> fed only by bus events. Malformed, unknown-agent,
67
- * duplicate-start and post-end activity events are ignored. */
76
+ * duplicate-start and post-end activity events are ignored.
77
+ *
78
+ * Agents whose start was observed also form batches: the first such start
79
+ * while no batch is open opens one, later starts join it, and it stays open
80
+ * until the panel closes it after every member ended. An agent first seen
81
+ * with `startedAt: null` ran before anyone looked: it joins no batch, so it
82
+ * neither reopens the live view nor repeats a card already shown. */
68
83
  export class SubagentStore {
69
84
  private readonly agents = new Map<string, SubagentState>();
70
85
  private readonly listeners = new Set<() => void>();
86
+ private batchIds: string[] = [];
87
+ private batchOpen = false;
71
88
  constructor(private readonly now: () => number = Date.now) {}
72
89
 
73
90
  get size(): number {
@@ -85,6 +102,37 @@ export class SubagentStore {
85
102
  for (const a of this.agents.values()) if (a.status === "running") n++;
86
103
  return n;
87
104
  }
105
+ /** The open batch's agents in start order; empty when none is open. */
106
+ batch(): SubagentState[] {
107
+ if (!this.batchOpen) return [];
108
+ return this.batchIds.flatMap((id) => this.agents.get(id) ?? []);
109
+ }
110
+ /** The open batch has agents and none of them still runs. */
111
+ settled(): boolean {
112
+ const batch = this.batch();
113
+ return batch.length > 0 && batch.every((a) => a.status !== "running");
114
+ }
115
+ /** Close the open batch and return its agents; the next observed start
116
+ * opens a new one. */
117
+ closeBatch(): SubagentState[] {
118
+ const batch = this.batch();
119
+ this.batchOpen = false;
120
+ this.batchIds = [];
121
+ return batch;
122
+ }
123
+ /** Drop ended agents outside the open batch, oldest first, until at most
124
+ * `keep` remain; `retain` ids stay. Returns the dropped ids. Listeners are
125
+ * not called: the caller is the panel, which redraws itself. */
126
+ prune(keep: number, retain: (string | undefined)[] = []): string[] {
127
+ const open = new Set(this.batchOpen ? this.batchIds : []);
128
+ const ended = [...this.agents.values()].filter(
129
+ (a) =>
130
+ a.status !== "running" && !open.has(a.id) && !retain.includes(a.id),
131
+ );
132
+ const drop = ended.slice(0, Math.max(0, ended.length - keep));
133
+ for (const a of drop) this.agents.delete(a.id);
134
+ return drop.map((a) => a.id);
135
+ }
88
136
  subscribe(listener: () => void): () => void {
89
137
  this.listeners.add(listener);
90
138
  return () => this.listeners.delete(listener);
@@ -116,6 +164,13 @@ export class SubagentStore {
116
164
  revision: 0,
117
165
  activeAt: now,
118
166
  });
167
+ if (o.startedAt !== null) {
168
+ if (!this.batchOpen) {
169
+ this.batchOpen = true;
170
+ this.batchIds = [];
171
+ }
172
+ this.batchIds.push(id);
173
+ }
119
174
  return true;
120
175
  }
121
176
  const agent = this.agents.get(id);
@@ -207,16 +262,13 @@ export type PaintRole =
207
262
  export type Paint = (role: PaintRole, text: string) => string;
208
263
 
209
264
  export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
210
- const SYMBOL: Record<
211
- Exclude<SubagentStatus, "running">,
212
- [string, PaintRole]
213
- > = {
265
+ const SYMBOL: Record<Ended, [string, PaintRole]> = {
214
266
  done: ["✔", "success"],
215
267
  error: ["✘", "error"],
216
268
  cancelled: ["○", "muted"],
217
269
  };
218
270
  export function statusSymbol(
219
- agent: SubagentState,
271
+ agent: Pick<SubagentState, "status">,
220
272
  frame: number,
221
273
  ): [string, PaintRole] {
222
274
  return agent.status === "running"
@@ -236,6 +288,18 @@ export function factsText(agent: SubagentState, now: number): string {
236
288
  const used = usage(agent);
237
289
  return `${elapsedText(agent, now)}${used ? ` · ${used}` : ""}`;
238
290
  }
291
+ /** A row's text: the error of a failed agent, otherwise its activity, led by
292
+ * the label unless the producer already led with it (`label · …`). */
293
+ export function described(
294
+ agent: Pick<SubagentState, "label" | "activity" | "status" | "error">,
295
+ ): string {
296
+ const text =
297
+ agent.status === "error" && agent.error ? agent.error : agent.activity;
298
+ if (!text) return agent.label;
299
+ return text === agent.label || text.startsWith(`${agent.label} `)
300
+ ? text
301
+ : `${agent.label} · ${text}`;
302
+ }
239
303
 
240
304
  /** The `max` most recently active agents plus any pinned ones, shown in
241
305
  * stable start order, and how many others are hidden. */
@@ -259,18 +323,6 @@ export function visibleAgents(
259
323
  return { rows, hidden: agents.length - rows.length };
260
324
  }
261
325
 
262
- export interface PanelFrame {
263
- agents: SubagentState[];
264
- focus: "input" | "panel";
265
- /** Selected row: an agent id, or undefined for main. */
266
- selected: string | undefined;
267
- /** Agent shown in place of the main view, if any. */
268
- view: string | undefined;
269
- now: number;
270
- frame: number;
271
- maxRows: number;
272
- showEmpty: boolean;
273
- }
274
326
  const s = (n: number) => (n === 1 ? "" : "s");
275
327
  const cut = (text: string, width: number) =>
276
328
  truncateToWidth(text, Math.max(0, width), "…");
@@ -279,117 +331,289 @@ const cut = (text: string, width: number) =>
279
331
  const clip = (plain: string, width: number) =>
280
332
  cut(plain, width).replaceAll("\x1b[0m", "");
281
333
 
282
- /** Z3: `● main`, an optional `+K more`, then one row per visible agent:
283
- * `<status> <kind> <activity…> <elapsed> [· ↓in [↑out]]`. */
284
- export function panelLines(
285
- f: PanelFrame,
334
+ /** One row: `<lead><status> [<kind> ]<text…> <facts>`, never wider than
335
+ * `width`. A selected row is reverse video across the whole width. */
336
+ interface Row {
337
+ symbol: [string, PaintRole];
338
+ kind: string;
339
+ text: string;
340
+ failed: boolean;
341
+ facts: string;
342
+ }
343
+ function rowLine(
344
+ row: Row,
345
+ lead: string,
346
+ kindWidth: number,
286
347
  width: number,
287
348
  paint: Paint,
288
- ): string[] {
289
- if (f.agents.length === 0 && !f.showEmpty) return [];
290
- const marked = f.focus === "panel";
291
- const marker = (selected: boolean) => (!marked ? "" : selected ? "▶" : " ");
292
- const row = (selected: boolean, plain: string, painted: string) => {
293
- if (!selected) return cut(painted, width);
294
- const cell = clip(plain, width);
349
+ selected = false,
350
+ ): string {
351
+ const [symbol, role] = row.symbol;
352
+ const kind = kindWidth ? clip(row.kind, kindWidth) : "";
353
+ const kindCell = kindWidth
354
+ ? `${kind}${" ".repeat(kindWidth - visibleWidth(kind))} `
355
+ : "";
356
+ const head = `${lead}${symbol} ${kindCell}`;
357
+ const room = width - visibleWidth(head) - visibleWidth(row.facts) - 2;
358
+ const text = room < 4 ? "" : clip(row.text, room);
359
+ const gap = " ".repeat(room < 4 ? 1 : room - visibleWidth(text) + 2);
360
+ if (selected) {
361
+ const cell = clip(head + text + gap + row.facts, width);
295
362
  return paint("selected", cell + " ".repeat(width - visibleWidth(cell)));
363
+ }
364
+ return cut(
365
+ `${paint("dim", lead)}${paint(role, symbol)} ${kindCell}${
366
+ row.failed ? paint("error", text) : text
367
+ }${gap}${paint("dim", row.facts)}`,
368
+ width,
369
+ );
370
+ }
371
+ const liveRow = (a: SubagentState, now: number, frame: number): Row => {
372
+ const used = usage(a);
373
+ return {
374
+ symbol: statusSymbol(a, frame),
375
+ kind: a.kind,
376
+ text: described(a),
377
+ failed: a.status === "error",
378
+ facts: `${elapsedText(a, now).padStart(8)}${used ? ` · ${used}` : ""}`,
296
379
  };
297
- const onMain = f.selected === undefined;
380
+ };
381
+ const kindColumn = (kinds: string[]) =>
382
+ Math.min(12, Math.max(7, ...kinds.map((k) => visibleWidth(k))));
383
+ /** The kind every agent shares, if any; it then names the batch instead of
384
+ * repeating on each row. A producer's default `agent` names nothing. */
385
+ const sharedKind = (agents: { kind: string }[]) => {
386
+ const kinds = new Set(agents.map((a) => a.kind));
387
+ const [kind] = kinds;
388
+ return kinds.size === 1 && kind !== "agent" ? kind : undefined;
389
+ };
390
+ /** `text` and a dim `hint` when both fit; otherwise the text alone. */
391
+ const hinted = (text: string, hint: string, width: number, paint: Paint) =>
392
+ visibleWidth(text) + visibleWidth(hint) <= width
393
+ ? text + paint("dim", hint)
394
+ : cut(text, width);
395
+ const noun = (kind: string | undefined, n: number) =>
396
+ `${kind ? `${kind} ` : ""}agent${s(n)}`;
397
+ /** Tree leads for `n` rows; the last closes the tree unless `+K more` follows. */
398
+ const tree = (n: number, more: number) =>
399
+ Array.from({ length: n }, (_, i) => (i === n - 1 && !more ? " └ " : " ├ "));
400
+
401
+ /** One finished batch as written into the session: display text only. */
402
+ export interface CardAgent {
403
+ kind: string;
404
+ /** The row text ({@link described}) when the batch closed. */
405
+ text: string;
406
+ status: Ended;
407
+ /** Milliseconds, or null when the start was never observed. */
408
+ elapsed: number | null;
409
+ }
410
+ export interface AgentCard {
411
+ agents: CardAgent[];
412
+ /** Members beyond {@link MAX_CARD_AGENTS}, counted, not listed. */
413
+ omitted: number;
414
+ /** First observed start to last end, or null when none was timed. */
415
+ elapsed: number | null;
416
+ }
417
+ export function cardOf(agents: SubagentState[]): AgentCard {
418
+ const ended = agents.filter(
419
+ (a): a is SubagentState & { status: Ended } => a.status !== "running",
420
+ );
421
+ const timed = ended.filter((a) => !a.untimed);
422
+ const first = Math.min(...timed.map((a) => a.startedAt));
423
+ const last = Math.max(...timed.map((a) => a.endedAt ?? a.startedAt));
424
+ return {
425
+ agents: ended.slice(0, MAX_CARD_AGENTS).map((a) => ({
426
+ kind: a.kind,
427
+ text: described(a),
428
+ status: a.status,
429
+ elapsed: a.untimed ? null : elapsedOf(a, a.startedAt),
430
+ })),
431
+ omitted: Math.max(0, ended.length - MAX_CARD_AGENTS),
432
+ elapsed: timed.length ? Math.max(0, last - first) : null,
433
+ };
434
+ }
435
+ /** A card read back from a session file, which anyone may have edited:
436
+ * anything malformed renders nothing rather than guessed text. */
437
+ export function decodeCard(data: unknown): AgentCard | undefined {
438
+ const o = record(data);
439
+ if (!o || !Array.isArray(o.agents) || o.agents.length > MAX_CARD_AGENTS)
440
+ return undefined;
441
+ const ms = (v: unknown) => (v === null ? null : count(v));
442
+ const agents: CardAgent[] = [];
443
+ for (const value of o.agents) {
444
+ const a = record(value);
445
+ const kind = a && line(a.kind, 32);
446
+ const text = a && line(a.text, 1024);
447
+ const elapsed = a && ms(a.elapsed);
448
+ if (
449
+ !a ||
450
+ !kind ||
451
+ text === undefined ||
452
+ elapsed === undefined ||
453
+ !ENDED.has(a.status as string)
454
+ )
455
+ return undefined;
456
+ agents.push({ kind, text, status: a.status as Ended, elapsed });
457
+ }
458
+ const omitted = count(o.omitted);
459
+ const elapsed = ms(o.elapsed);
460
+ if (omitted === undefined || elapsed === undefined) return undefined;
461
+ if (agents.length + omitted === 0) return undefined;
462
+ return { agents, omitted, elapsed };
463
+ }
464
+
465
+ /** A finished batch: `✔ 3 Research agents finished · 2m 14s`, with outcome
466
+ * counts when any failed or was cancelled. Collapsed, it lists only those;
467
+ * expanded, every member with its final text and elapsed time. */
468
+ export function cardLines(
469
+ card: AgentCard,
470
+ expanded: boolean,
471
+ width: number,
472
+ paint: Paint,
473
+ hint = true,
474
+ ): string[] {
475
+ const n = card.agents.length + card.omitted;
476
+ const tally = (status: Ended) =>
477
+ card.agents.filter((a) => a.status === status).length;
478
+ const failed = tally("error"),
479
+ cancelled = tally("cancelled");
480
+ const [symbol, role] =
481
+ SYMBOL[failed ? "error" : cancelled ? "cancelled" : "done"];
482
+ const kind = sharedKind(card.agents);
483
+ const outcome =
484
+ failed || cancelled
485
+ ? ` · ${tally("done")} done${failed ? ` · ${failed} failed` : ""}${
486
+ cancelled ? ` · ${cancelled} cancelled` : ""
487
+ }`
488
+ : "";
489
+ const took = card.elapsed === null ? "" : ` · ${formatElapsed(card.elapsed)}`;
490
+ const shown = expanded
491
+ ? card.agents
492
+ : card.agents.filter((a) => a.status !== "done");
493
+ const more = expanded ? card.omitted : 0;
494
+ const header = hinted(
495
+ `${paint(role, symbol)} ${n} ${noun(kind, n)} finished${outcome}${took}`,
496
+ hint && !expanded ? " (ctrl+o to expand)" : "",
497
+ width,
498
+ paint,
499
+ );
500
+ const kindWidth = kind ? 0 : kindColumn(shown.map((a) => a.kind));
501
+ const rows = shown.map((a) => ({
502
+ symbol: SYMBOL[a.status],
503
+ kind: a.kind,
504
+ text: a.text,
505
+ failed: a.status === "error",
506
+ facts: (a.elapsed === null ? "—" : formatElapsed(a.elapsed)).padStart(8),
507
+ }));
508
+ const leads = tree(rows.length, more);
298
509
  const lines = [
299
- row(
300
- marked && onMain,
301
- `${marker(onMain)}● main`,
302
- `${marker(onMain)}${paint(f.view === undefined ? "accent" : "dim", "●")} main`,
510
+ header,
511
+ ...rows.map((r, i) => rowLine(r, leads[i], kindWidth, width, paint)),
512
+ ];
513
+ if (more) lines.push(cut(`${paint("dim", " └ ")}… +${more} more`, width));
514
+ return lines;
515
+ }
516
+
517
+ export interface LiveFrame {
518
+ /** The open batch, or a kept one (`CADENCE_AGENT_PANEL=always`). */
519
+ agents: SubagentState[];
520
+ now: number;
521
+ frame: number;
522
+ maxRows: number;
523
+ /** Show the `↓ to manage` hint: the input box has focus. */
524
+ hint: boolean;
525
+ }
526
+ /** Above the input while a batch is open. Running: a spinner header with the
527
+ * batch's outcome counts, then its running and failed/cancelled members; a
528
+ * member that finished cleanly is only counted. Settled: the card it is about
529
+ * to become, so the collapse into the transcript does not change the text. */
530
+ export function liveLines(f: LiveFrame, width: number, paint: Paint): string[] {
531
+ const { agents } = f;
532
+ if (agents.length === 0) return [];
533
+ const running = agents.filter((a) => a.status === "running");
534
+ if (running.length === 0)
535
+ return cardLines(cardOf(agents), false, width, paint, false);
536
+ const kind = sharedKind(agents);
537
+ const tally = (status: SubagentStatus) =>
538
+ agents.filter((a) => a.status === status).length;
539
+ const done = tally("done"),
540
+ failed = tally("error"),
541
+ cancelled = tally("cancelled");
542
+ const counts = `${done ? ` · ${done} done` : ""}${
543
+ failed ? ` · ${failed} failed` : ""
544
+ }${cancelled ? ` · ${cancelled} cancelled` : ""}`;
545
+ const [spin, role] = statusSymbol(running[0], f.frame);
546
+ const header = hinted(
547
+ `${paint(role, spin)} ${running.length} ${noun(kind, running.length)} running${counts}`,
548
+ f.hint ? " (↓ to manage)" : "",
549
+ width,
550
+ paint,
551
+ );
552
+ const listed = [
553
+ ...running,
554
+ ...agents.filter((a) => a.status === "error" || a.status === "cancelled"),
555
+ ];
556
+ const rows = listed.slice(0, f.maxRows);
557
+ const more = listed.length - rows.length;
558
+ const kindWidth = kind ? 0 : kindColumn(rows.map((a) => a.kind));
559
+ const leads = tree(rows.length, more);
560
+ const lines = [
561
+ header,
562
+ ...rows.map((a, i) =>
563
+ rowLine(liveRow(a, f.now, f.frame), leads[i], kindWidth, width, paint),
303
564
  ),
304
565
  ];
566
+ if (more) lines.push(cut(`${paint("dim", " └ ")}… +${more} more`, width));
567
+ return lines;
568
+ }
569
+
570
+ export interface PanelFrame {
571
+ agents: SubagentState[];
572
+ focus: "input" | "panel";
573
+ /** Selected row: an agent id, or undefined while the input has focus. */
574
+ selected: string | undefined;
575
+ /** Agent shown in place of the main view, if any. */
576
+ view: string | undefined;
577
+ now: number;
578
+ frame: number;
579
+ maxRows: number;
580
+ }
581
+ /** Below the input only while it is being used (focus moved down to it, or
582
+ * an agent view is open): this Pi session's agents, at most `maxRows` of the
583
+ * most recently active plus the selection, `+K more`, and a key hint. */
584
+ export function panelLines(
585
+ f: PanelFrame,
586
+ width: number,
587
+ paint: Paint,
588
+ ): string[] {
589
+ if (f.agents.length === 0 || (f.focus !== "panel" && f.view === undefined))
590
+ return [];
305
591
  const { rows, hidden } = visibleAgents(f.agents, f.maxRows, [
306
592
  f.selected,
307
593
  f.view,
308
594
  ]);
309
- if (hidden > 0)
310
- lines.push(
311
- cut(`${marker(false)}${paint("dim", ` +${hidden} more`)}`, width),
312
- );
313
- const kindWidth = Math.min(
314
- 12,
315
- Math.max(7, ...rows.map((a) => visibleWidth(a.kind))),
316
- );
595
+ const lines = hidden ? [cut(paint("dim", ` +${hidden} more`), width)] : [];
596
+ const kindWidth = kindColumn(rows.map((a) => a.kind));
317
597
  for (const a of rows) {
318
- const selected = marked && f.selected === a.id;
319
- const [symbol, role] = statusSymbol(a, f.frame);
320
- const kind = clip(a.kind, kindWidth);
321
- const kindCell = kind + " ".repeat(kindWidth - visibleWidth(kind));
322
- const used = usage(a);
323
- const right = `${elapsedText(a, f.now).padStart(8)}${used ? ` · ${used}` : ""}`;
324
- const head = `${marker(selected)}${symbol} ${kindCell} `;
325
- const room = width - visibleWidth(head) - visibleWidth(right) - 2;
326
- const failed = a.status === "error" && a.error;
327
- const activity = room < 4 ? "" : clip(failed || a.activity, room);
328
- const gap = " ".repeat(room < 4 ? 1 : room - visibleWidth(activity) + 2);
598
+ const selected = f.focus === "panel" && f.selected === a.id;
329
599
  lines.push(
330
- row(
600
+ rowLine(
601
+ liveRow(a, f.now, f.frame),
602
+ selected ? "▶" : " ",
603
+ kindWidth,
604
+ width,
605
+ paint,
331
606
  selected,
332
- head + activity + gap + right,
333
- `${marker(selected)}${paint(role, symbol)} ${kindCell} ${
334
- failed ? paint("error", activity) : activity
335
- }${gap}${paint("dim", right)}`,
336
607
  ),
337
608
  );
338
609
  }
610
+ if (f.view === undefined)
611
+ lines.push(
612
+ cut(paint("dim", " ↑↓ select · Enter open · Esc back to input"), width),
613
+ );
339
614
  return lines;
340
615
  }
341
616
 
342
- /** Bottom of Z1: launched/waiting block while any agent runs, then one
343
- * finished line with the outcome counts. */
344
- export function summaryLines(
345
- agents: SubagentState[],
346
- width: number,
347
- paint: Paint,
348
- maxLabels: number,
349
- ): string[] {
350
- if (agents.length === 0) return [];
351
- const n = agents.length;
352
- const running = agents.filter((a) => a.status === "running").length;
353
- if (running === 0) {
354
- const count = (status: SubagentStatus) =>
355
- agents.filter((a) => a.status === status).length;
356
- const cancelled = count("cancelled");
357
- const outcome = `ok=${count("done")}, failed=${count("error")}${
358
- cancelled ? `, cancelled=${cancelled}` : ""
359
- }`;
360
- return [
361
- cut(
362
- `${paint("success", "✔")} ${n} background agent${s(n)} finished (${outcome}) — select a row below and press Enter to review`,
363
- width,
364
- ),
365
- ];
366
- }
367
- // Running agents first, so a new one is never hidden behind finished ones.
368
- const shown = [
369
- ...agents.filter((a) => a.status === "running"),
370
- ...agents.filter((a) => a.status !== "running"),
371
- ].slice(0, maxLabels);
372
- const more = n - shown.length;
373
- const tree = shown.map((a, i) =>
374
- cut(
375
- ` ${paint("dim", i === shown.length - 1 && !more ? "└" : "├")} ${a.label}`,
376
- width,
377
- ),
378
- );
379
- if (more) tree.push(cut(` ${paint("dim", "└")} … +${more} more`, width));
380
- return [
381
- cut(
382
- `${paint("accent", "●")} ${n} background agent${s(n)} launched (↓ to manage)`,
383
- width,
384
- ),
385
- ...tree,
386
- cut(
387
- `${paint("dim", "*")} Waiting for ${running} background agent${s(running)} to finish`,
388
- width,
389
- ),
390
- ];
391
- }
392
-
393
617
  export type PanelKey =
394
618
  | "down"
395
619
  | "up"
@@ -414,8 +638,9 @@ export interface Scroll {
414
638
  }
415
639
 
416
640
  /** Focus model. F_input (default) passes every key except ↓ on an idle, empty
417
- * editor; F_panel moves the Z3 selection; an agent view keeps F_panel and
418
- * replaces the main view until Esc, Ctrl+C or Enter on main. */
641
+ * editor, which moves focus down to the agent list; F_panel moves its
642
+ * selection, and ↑ past the first row or Esc returns to the input. An agent
643
+ * view keeps F_panel and replaces the main view until Esc or Ctrl+C. */
419
644
  export class PanelFocus {
420
645
  focus: "input" | "panel" = "input";
421
646
  selected: string | undefined;
@@ -423,22 +648,29 @@ export class PanelFocus {
423
648
  /** Rows of the last rendered agent view, for paging. */
424
649
  page = 10;
425
650
  private readonly scrolls = new Map<string, Scroll>();
426
- constructor(private readonly store: SubagentStore) {}
651
+ constructor(
652
+ private readonly store: SubagentStore,
653
+ private readonly maxRows = 6,
654
+ ) {}
427
655
 
428
656
  key(key: PanelKey, editorIdle: boolean): PanelAction {
429
657
  if (this.focus === "input" && this.view === undefined) {
430
658
  if (key !== "down" || !editorIdle || this.store.size === 0) return "pass";
431
659
  this.focus = "panel";
432
- this.selected = this.store.ordered()[0].id;
660
+ this.selected = visibleAgents(
661
+ this.store.ordered(),
662
+ this.maxRows,
663
+ ).rows[0]?.id;
433
664
  return "consume";
434
665
  }
435
- const rows = [undefined, ...this.store.ordered().map((a) => a.id)];
436
- const at = Math.max(0, rows.indexOf(this.selected));
666
+ const rows = this.store.ordered().map((a) => a.id);
667
+ // A selection the store dropped falls back to the first row.
668
+ const at = Math.max(0, rows.indexOf(this.selected ?? ""));
437
669
  switch (key) {
438
670
  case "up":
439
671
  case "previous":
440
- // ↑ past main returns to the input, the inverse of ↓.
441
- if (at === 0 && this.view === undefined) this.focus = "input";
672
+ // ↑ past the first row returns to the input, the inverse of ↓.
673
+ if (at === 0 && this.view === undefined) this.toInput();
442
674
  else this.selected = rows[Math.max(0, at - 1)];
443
675
  return "consume";
444
676
  case "down":
@@ -446,9 +678,9 @@ export class PanelFocus {
446
678
  this.selected = rows[Math.min(rows.length - 1, at + 1)];
447
679
  return "consume";
448
680
  case "enter":
681
+ this.selected = rows[at];
449
682
  if (this.selected === undefined) {
450
- if (this.view !== undefined) return this.leave();
451
- this.focus = "input";
683
+ this.toInput();
452
684
  return "consume";
453
685
  }
454
686
  if (this.view === undefined) {
@@ -460,7 +692,7 @@ export class PanelFocus {
460
692
  case "escape":
461
693
  case "interrupt":
462
694
  if (this.view !== undefined) return this.leave();
463
- this.focus = "input";
695
+ this.toInput();
464
696
  // Ctrl+C keeps Pi's own clear/interrupt/exit meaning.
465
697
  return key === "escape" ? "consume" : "pass";
466
698
  case "pageUp":
@@ -477,14 +709,14 @@ export class PanelFocus {
477
709
  return key === "halfUp" || key === "halfDown" ? "consume" : "pass";
478
710
  default:
479
711
  if (this.view !== undefined) return "consume";
480
- this.focus = "input";
712
+ this.toInput();
481
713
  return "pass";
482
714
  }
483
715
  }
484
716
  /** Pi replaced the agent view (another dialog took the editor slot). */
485
717
  abandon(): void {
486
718
  this.view = undefined;
487
- this.focus = "input";
719
+ this.toInput();
488
720
  }
489
721
  /** Top line for this view, remembered per agent across switches. */
490
722
  settle(id: string, total: number, height: number): number {
@@ -498,6 +730,14 @@ export class PanelFocus {
498
730
  scrollOf(id: string): Scroll | undefined {
499
731
  return this.scrolls.get(id);
500
732
  }
733
+ /** The store dropped these agents: forget their scroll positions. */
734
+ forget(ids: string[]): void {
735
+ for (const id of ids) this.scrolls.delete(id);
736
+ }
737
+ private toInput(): void {
738
+ this.focus = "input";
739
+ this.selected = undefined;
740
+ }
501
741
  private leave(): PanelAction {
502
742
  this.view = undefined;
503
743
  return "close";