pi-subagent-manager 0.14.0 → 0.16.0

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,6 +14,9 @@ import {
14
14
  import type { ThreadService, TranscriptSnapshot } from "../types.ts";
15
15
  import { dialogText, type DialogHost } from "./dialog.ts";
16
16
  import { AGENT_PROGRESS_INTERVAL, agentProgressIcon, agentTypeLabel } from "./ui.ts";
17
+ import type { LoaderStyle } from "../prefs/settings.ts";
18
+
19
+ type ThemeBg = Parameters<Theme["bg"]>[0];
17
20
 
18
21
  /** Transcript detail level cycled by the t key: full → preview → compact. */
19
22
  export type TranscriptDetail = "full" | "preview" | "compact";
@@ -65,7 +68,10 @@ export class LiveAgentView {
65
68
  private unsubscribe: (() => void) | undefined;
66
69
  private renderTimer: ReturnType<typeof setTimeout> | undefined;
67
70
  private progressTimer: ReturnType<typeof setInterval> | undefined;
68
- private cache = new WeakMap<object, { width: number; detail: TranscriptDetail; lines: string[] }>();
71
+ private cache = new WeakMap<
72
+ object,
73
+ { width: number; detail: TranscriptDetail; lines: string[] }
74
+ >();
69
75
  private scroll: ScrollView;
70
76
  private content: string[] = [];
71
77
  private restoreViewport = true;
@@ -86,6 +92,7 @@ export class LiveAgentView {
86
92
  private viewport: AgentViewportState,
87
93
  private done: (result: "back" | "main") => void,
88
94
  private nerdFontIcons = false,
95
+ private loaderStyle: LoaderStyle = "circle",
89
96
  ) {
90
97
  this.scroll = new ScrollView(
91
98
  { render: () => this.content, invalidate() {} },
@@ -187,7 +194,10 @@ export class LiveAgentView {
187
194
 
188
195
  private syncProgress(): void {
189
196
  const state = this.snapshot?.thread?.state;
190
- const active = this.nerdFontIcons && !this.disposed && !this.error &&
197
+ const active =
198
+ this.nerdFontIcons &&
199
+ !this.disposed &&
200
+ !this.error &&
191
201
  (state === "starting" || state === "running");
192
202
  if (!active) {
193
203
  if (this.progressTimer !== undefined) clearInterval(this.progressTimer);
@@ -275,6 +285,23 @@ export class LiveAgentView {
275
285
  return this.viewport.detail ?? "preview";
276
286
  }
277
287
 
288
+ /** One column of horizontal padding on each side of the transcript. */
289
+ private pad(lines: string[]): string[] {
290
+ return lines.map((line) => ` ${line}`);
291
+ }
292
+
293
+ /** Full-width themed band with one column of padding, like pi's tool boxes. */
294
+ private band(lines: string[], token: ThemeBg, width: number): string[] {
295
+ const inner = Math.max(1, width - 2);
296
+ return lines.map((line) => {
297
+ const clipped = truncateToWidth(line, inner, "", true);
298
+ return this.theme.bg(
299
+ token,
300
+ ` ${clipped}${" ".repeat(Math.max(0, inner - visibleWidth(clipped)))} `,
301
+ );
302
+ });
303
+ }
304
+
278
305
  private wrap(value: string, width: number): string[] {
279
306
  return text(value)
280
307
  .split("\n")
@@ -320,28 +347,39 @@ export class LiveAgentView {
320
347
  return lines;
321
348
  }
322
349
 
350
+ /** Renders padded rows: `width` is the full transcript width. Tool calls get a themed band. */
323
351
  private blocks(content: unknown, width: number): string[] {
324
- if (typeof content === "string") return this.markdown(content, width);
325
- if (!Array.isArray(content)) return this.wrap(json(content), width);
352
+ const inner = Math.max(1, width - 2);
353
+ if (!Array.isArray(content)) return this.pad(this.blockLines(content, inner));
326
354
  return content.flatMap((value) => {
327
355
  const block = object(value);
328
- if (!block) return this.wrap(json(value), width);
329
- if (block.type === "text") return this.markdown(String(block.text ?? ""), width);
330
- if (block.type === "image") return ["[Image — text-only observer]"];
331
- if (block.type === "thinking") {
332
- if (this.detail === "compact")
333
- return [this.theme.fg("dim", "[Thinking hidden · t cycles view]")];
334
- // Thinking is model-authored Markdown; preview truncates the rendered lines, not the source.
335
- const rendered = this.markdown(String(block.thinking ?? "[redacted thinking]"), width, true);
336
- if (this.detail === "full" || rendered.length <= 3) return rendered;
337
- return [...rendered.slice(0, 3), this.theme.fg("dim", "...")];
338
- }
339
- if (block.type === "toolCall")
340
- return this.toolCall(String(block.name), block.arguments, width);
341
- return this.preview(json(block), width);
356
+ if (block?.type === "toolCall")
357
+ return this.band(
358
+ this.toolCall(String(block.name), block.arguments, inner),
359
+ "toolSuccessBg",
360
+ width,
361
+ );
362
+ return this.pad(this.blockLines(value, inner));
342
363
  });
343
364
  }
344
365
 
366
+ private blockLines(value: unknown, width: number): string[] {
367
+ if (typeof value === "string") return this.markdown(value, width);
368
+ const block = object(value);
369
+ if (!block) return this.wrap(json(value), width);
370
+ if (block.type === "text") return this.markdown(String(block.text ?? ""), width);
371
+ if (block.type === "image") return ["[Image — text-only observer]"];
372
+ if (block.type === "thinking") {
373
+ if (this.detail === "compact")
374
+ return [this.theme.fg("dim", "[Thinking hidden · t cycles view]")];
375
+ // Thinking is model-authored Markdown; preview truncates the rendered lines, not the source.
376
+ const rendered = this.markdown(String(block.thinking ?? "[redacted thinking]"), width, true);
377
+ if (this.detail === "full" || rendered.length <= 3) return rendered;
378
+ return [...rendered.slice(0, 3), this.theme.fg("dim", "...")];
379
+ }
380
+ return this.preview(json(block), width);
381
+ }
382
+
345
383
  private message(message: AgentMessage, width: number): string[] {
346
384
  const cached = this.cache.get(message);
347
385
  if (cached && cached.width === width && cached.detail === this.detail) return cached.lines;
@@ -352,17 +390,30 @@ export class LiveAgentView {
352
390
  : message.role;
353
391
  const collapsed = !["user", "assistant", "custom"].includes(message.role);
354
392
  const content = data.content ?? data.summary ?? data.output ?? data;
355
- const lines = [
356
- this.theme.fg(data.isError ? "error" : "accent", dialogText(label)),
357
- ...(collapsed ? this.preview(content, width) : this.blocks(content, width)),
358
- ...(data.errorMessage
359
- ? (collapsed
360
- ? this.preview(String(data.errorMessage), width)
361
- : this.wrap(String(data.errorMessage), width)
362
- ).map((line) => this.theme.fg("error", line))
363
- : []),
364
- "",
365
- ];
393
+ const inner = Math.max(1, width - 2);
394
+ const heading = this.theme.fg(data.isError ? "error" : "accent", dialogText(label));
395
+ const errors = data.errorMessage
396
+ ? (collapsed
397
+ ? this.preview(String(data.errorMessage), inner)
398
+ : this.wrap(String(data.errorMessage), inner)
399
+ ).map((line) => this.theme.fg("error", line))
400
+ : [];
401
+ const lines =
402
+ message.role === "toolResult"
403
+ ? [
404
+ ...this.band(
405
+ [heading, ...this.preview(content, inner), ...errors],
406
+ data.isError ? "toolErrorBg" : "customMessageBg",
407
+ width,
408
+ ),
409
+ "",
410
+ ]
411
+ : [
412
+ ...this.pad([heading]),
413
+ ...(collapsed ? this.pad(this.preview(content, inner)) : this.blocks(content, width)),
414
+ ...this.pad(errors),
415
+ "",
416
+ ];
366
417
  this.cache.set(message, { width, detail: this.detail, lines });
367
418
  return lines;
368
419
  }
@@ -448,7 +499,9 @@ export class LiveAgentView {
448
499
  }
449
500
  case "ls": {
450
501
  const limit = num("limit");
451
- lines = [`${title("ls")} ${path ?? "."}${limit != null ? detail(` (limit ${limit})`) : ""}`];
502
+ lines = [
503
+ `${title("ls")} ${path ?? "."}${limit != null ? detail(` (limit ${limit})`) : ""}`,
504
+ ];
452
505
  break;
453
506
  }
454
507
  default:
@@ -474,34 +527,36 @@ export class LiveAgentView {
474
527
  const columns = Math.max(1, width);
475
528
  const snapshot = this.snapshot;
476
529
  const thread = snapshot?.thread;
530
+ const inner = Math.max(1, columns - 2);
477
531
  const header = this.theme.fg(
478
532
  "accent",
479
533
  dialogText(
480
- `${this.path} · ${agentTypeLabel(thread?.type ?? "agent", thread ? agentProgressIcon(thread, this.nerdFontIcons) : undefined, this.nerdFontIcons)} · ${thread?.state ?? "attaching"} — Watching — main continues`,
534
+ `${this.path} · ${agentTypeLabel(thread?.type ?? "agent", thread?.icon, this.nerdFontIcons, thread ? agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle) : undefined)} · ${thread?.state ?? "attaching"} — Watching — main continues`,
481
535
  ),
482
536
  );
483
537
  const body: string[] = [];
484
538
  if (this.error)
485
539
  body.push(
486
- this.theme.fg("error", dialogText(`Attachment error: ${this.error}`)),
487
- "Ctrl+R Retry · Esc Back · Ctrl+Q Back to main",
540
+ ` ${this.theme.fg("error", dialogText(`Attachment error: ${this.error}`))}`,
541
+ " Ctrl+R Retry · Esc Back · Ctrl+Q Back to main",
488
542
  );
489
543
  if (!snapshot) {
490
- if (!this.error) body.push("Attaching to retained live session…");
544
+ if (!this.error) body.push(" Attaching to retained live session…");
491
545
  } else {
492
546
  if (snapshot.inheritedCount)
493
547
  body.push(
494
- this.theme.fg(
495
- "dim",
496
- `${snapshot.inheritedCount} inherited messages ${this.viewport.showInherited ? "shown" : "collapsed"} · c toggle`,
497
- ),
548
+ " " +
549
+ this.theme.fg(
550
+ "dim",
551
+ `${snapshot.inheritedCount} inherited messages ${this.viewport.showInherited ? "shown" : "collapsed"} · c toggle`,
552
+ ),
498
553
  );
499
554
  const start = this.viewport.showInherited ? 0 : snapshot.inheritedCount;
500
555
  for (const message of snapshot.messages.slice(start))
501
556
  body.push(...this.message(message, columns));
502
557
  if (snapshot.assistant)
503
558
  body.push(
504
- this.theme.fg("warning", "Assistant streaming…"),
559
+ ` ${this.theme.fg("warning", "Assistant streaming…")}`,
505
560
  ...this.message(snapshot.assistant, columns),
506
561
  );
507
562
  const committedResults = new Set(
@@ -511,23 +566,29 @@ export class LiveAgentView {
511
566
  );
512
567
  for (const tool of snapshot.tools) {
513
568
  if (committedResults.has(tool.toolCallId)) continue;
514
- const call = this.toolCall(tool.toolName, tool.args, columns);
569
+ const call = this.toolCall(tool.toolName, tool.args, inner);
515
570
  call[0] = `${call[0]} ${this.theme.fg(
516
571
  tool.isError ? "error" : "warning",
517
572
  dialogText(
518
573
  `— ${tool.state}${tool.isError ? " (error)" : ""}${tool.parentToolCallId ? " (nested)" : ""}`,
519
574
  ),
520
575
  )}`;
521
- body.push(...call);
576
+ body.push(...this.band(call, "toolSuccessBg", columns));
522
577
  if (tool.result !== undefined && this.detail !== "compact")
523
- body.push(...this.preview(object(tool.result)?.content ?? tool.result, columns));
578
+ body.push(
579
+ ...this.band(
580
+ this.preview(object(tool.result)?.content ?? tool.result, inner),
581
+ tool.isError ? "toolErrorBg" : "customMessageBg",
582
+ columns,
583
+ ),
584
+ );
524
585
  body.push("");
525
586
  }
526
587
  if (!body.length)
527
588
  body.push(
528
589
  thread?.state === "starting"
529
- ? "Starting — waiting for transcript attachment…"
530
- : "No retained messages yet.",
590
+ ? " Starting — waiting for transcript attachment…"
591
+ : " No retained messages yet.",
531
592
  );
532
593
  }
533
594
  this.content = body;
@@ -546,7 +607,7 @@ export class LiveAgentView {
546
607
  const footer = this.error
547
608
  ? "Ctrl+R Retry · Tab input/transcript · Esc tree · Ctrl+Q main"
548
609
  : `${this.editing ? "Enter steer · Tab browse" : `Tab steer · Home/End scroll · c context · t view:${this.detail}`} · Esc tree · Ctrl+Q main · ↑↓/PgUp/PgDn scroll · ${this.viewport.follow ? "following" : "scrolled"}`;
549
- const input = this.input.render(columns)[0]!;
610
+ const input = ` ${this.input.render(inner)[0]!}`;
550
611
  const status = this.theme.fg(
551
612
  this.steerStatus ? (this.steerFailed ? "error" : "muted") : this.error ? "error" : "muted",
552
613
  dialogText(
@@ -558,14 +619,22 @@ export class LiveAgentView {
558
619
  : "Live transcript · Enter to steer"),
559
620
  ),
560
621
  );
622
+ // Chrome rows share the transcript's one-column side padding; `visible` is already padded.
623
+ const chrome = (line: string) => ` ${truncateToWidth(line, inner, "")}`;
561
624
  const lines =
562
625
  height === 1
563
626
  ? [input]
564
627
  : height === 2
565
- ? [header, input]
628
+ ? [chrome(header), input]
566
629
  : height === 3
567
- ? [header, this.theme.fg("dim", footer), input]
568
- : [header, status, ...visible, this.theme.fg("dim", footer), input];
630
+ ? [chrome(header), chrome(this.theme.fg("dim", footer)), input]
631
+ : [
632
+ chrome(header),
633
+ chrome(status),
634
+ ...visible,
635
+ chrome(this.theme.fg("dim", footer)),
636
+ input,
637
+ ];
569
638
  return fillViewport(lines, width, height);
570
639
  }
571
640
  }
@@ -8,6 +8,8 @@ import {
8
8
  } from "./dialog.ts";
9
9
  import {
10
10
  DEFAULT_MANAGER_SETTINGS,
11
+ LOADER_STYLES,
12
+ type LoaderStyle,
11
13
  loadManagerSaveScope,
12
14
  saveManagerSaveScope,
13
15
  saveManagerSettings,
@@ -18,6 +20,18 @@ import {
18
20
  type WidgetMode,
19
21
  } from "../prefs/settings.ts";
20
22
  import { editAgentTypes } from "./ui.ts";
23
+ import type { ToolEditorOptions } from "./tool-picker.ts";
24
+ import { AGENT_LOADERS } from "./agent-loader.ts";
25
+
26
+ const LOADER_OPTIONS = LOADER_STYLES.map((id) => {
27
+ const loader = AGENT_LOADERS[id];
28
+ return {
29
+ id,
30
+ label: loader.label,
31
+ value: `${loader.frames.join(" ")} · ${Object.values(loader.states).join(" ")}`,
32
+ help: `Each row: all starting/running frames · completed, paused, failed, stopped.\nStarting/running: ${loader.frames.join(" ")}\nCompleted: ${loader.states.completed} · Paused: ${loader.states.paused}\nFailed: ${loader.states.failed} · Stopped: ${loader.states.stopped}\nRequires [labs] Nerd Font icons On. The loader appears before the unchanged role icon.`,
33
+ };
34
+ });
21
35
 
22
36
  const FIELDS = [
23
37
  {
@@ -133,6 +147,7 @@ export async function configureAgents(
133
147
  store: ConfigStore;
134
148
  settings: ManagerSettings;
135
149
  agentDir: string;
150
+ getAllTools?: ToolEditorOptions["getAllTools"];
136
151
  apply(): void;
137
152
  },
138
153
  ): Promise<void> {
@@ -148,6 +163,7 @@ async function configureAgentsDialog(
148
163
  store: ConfigStore;
149
164
  settings: ManagerSettings;
150
165
  agentDir: string;
166
+ getAllTools?: ToolEditorOptions["getAllTools"];
151
167
  apply(): void;
152
168
  },
153
169
  ): Promise<void> {
@@ -195,7 +211,13 @@ async function configureAgentsDialog(
195
211
  id: "nerdFontIcons",
196
212
  label: "[labs] Nerd Font icons",
197
213
  value: draft.nerdFontIcons ? "On" : "Off",
198
- help: "Experimental: display each agent type’s optional icon.\nRequires a Nerd Font configured in your terminal; otherwise glyphs may appear as boxes.\nOff by default. Save and apply to update the widget immediately.",
214
+ help: "Experimental: display each agent type’s optional icon, preceded by its loader/state indicator.\nRequires a Nerd Font configured in your terminal; otherwise glyphs may appear as boxes.\nOff by default. Save and apply to update the widget immediately.",
215
+ },
216
+ {
217
+ id: "loaderStyle",
218
+ label: "[labs] Loader style",
219
+ value: AGENT_LOADERS[draft.loaderStyle].label,
220
+ help: "Choose Circle, Braille or Hourglass. Preview every animation frame and settled state for all families.\nRequires [labs] Nerd Font icons On. Circle is the default.\nSave and apply to update the widget immediately.",
199
221
  },
200
222
  {
201
223
  id: "finalRecap",
@@ -286,6 +308,11 @@ async function configureAgentsDialog(
286
308
  draft.widgetMode = mode as WidgetMode;
287
309
  } else if (action === "nerdFontIcons") {
288
310
  draft.nerdFontIcons = !draft.nerdFontIcons;
311
+ } else if (action === "loaderStyle") {
312
+ const style = await dialogMenu(ctx, "[labs] Loader style", LOADER_OPTIONS, {
313
+ selectedId: draft.loaderStyle,
314
+ });
315
+ if (LOADER_STYLES.includes(style as LoaderStyle)) draft.loaderStyle = style as LoaderStyle;
289
316
  } else if (action === "finalRecap") {
290
317
  draft.finalRecap = !draft.finalRecap;
291
318
  } else if (action === "scope") {
@@ -301,7 +328,10 @@ async function configureAgentsDialog(
301
328
  }
302
329
  } else if (action === "defaults") draft = { ...DEFAULT_MANAGER_SETTINGS };
303
330
  else if (action === "types") {
304
- await editAgentTypes(ctx, options.store, draft.nerdFontIcons);
331
+ await editAgentTypes(ctx, options.store, draft.nerdFontIcons, {
332
+ getAllTools: options.getAllTools ?? (() => []),
333
+ toolFiltering: draft.toolFiltering,
334
+ });
305
335
  options.store.reload();
306
336
  } else if (action === "save") {
307
337
  const file = saveManagerSettings({
@@ -24,6 +24,7 @@ import {
24
24
  frameDialog,
25
25
  } from "./dialog.ts";
26
26
  import type { ThreadService } from "../types.ts";
27
+ import type { LoaderStyle } from "../prefs/settings.ts";
27
28
  import { buildStatusTree, type StatusRow } from "./thread-tree.ts";
28
29
  import {
29
30
  AGENT_PROGRESS_INTERVAL, agentProgressIcon, agentTypeBadge, agentTypeLabel, showThreads, threadMetrics,
@@ -109,6 +110,7 @@ export class StatusDialog {
109
110
  fullscreen?: boolean;
110
111
  },
111
112
  private nerdFontIcons = false,
113
+ private loaderStyle: LoaderStyle = "circle",
112
114
  ) {
113
115
  this.state = navigation?.state ?? { selectedPath: selected || ROOT, collapsed: new Set() };
114
116
  }
@@ -260,7 +262,7 @@ export class StatusDialog {
260
262
  const status = dialogText(thread.status);
261
263
  return [
262
264
  this.theme.fg(selected ? "accent" : base, head),
263
- this.theme.fg(base, `${agentTypeLabel(thread.type, thread.icon, this.nerdFontIcons)} ${path} `),
265
+ this.theme.fg(base, `${agentTypeLabel(thread.type, thread.icon, this.nerdFontIcons, agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle))} ${path} `),
264
266
  this.theme.fg(hint, state),
265
267
  this.theme.fg(base, ` ${status}`),
266
268
  ].join("");
@@ -268,8 +270,8 @@ export class StatusDialog {
268
270
  const rest = [thread.path, thread.state, thread.status]
269
271
  .map((part) => dialogText(part))
270
272
  .join(" ");
271
- const badge = agentTypeBadge(thread.type, thread.color, this.theme,
272
- agentProgressIcon(thread, this.nerdFontIcons), this.nerdFontIcons);
273
+ const badge = agentTypeBadge(thread.type, thread.color, this.theme, thread.icon, this.nerdFontIcons,
274
+ agentProgressIcon(thread, this.nerdFontIcons, Date.now(), true, this.loaderStyle));
273
275
  if (selected)
274
276
  return `${this.theme.fg("accent", head)}${badge} ${this.theme.fg("accent", rest)}`;
275
277
  return `${head}${badge} ${rest}`;
@@ -337,6 +339,7 @@ async function showAgentDialog(
337
339
  selected?: string;
338
340
  inspect?: (path: string) => Promise<void>;
339
341
  nerdFontIcons?: boolean;
342
+ loaderStyle?: LoaderStyle;
340
343
  } = {},
341
344
  ): Promise<void> {
342
345
  const open = options.inspect ?? ((path: string) => showThreads(ctx, service, path));
@@ -347,7 +350,7 @@ async function showAgentDialog(
347
350
  let dialog: StatusDialog | undefined;
348
351
  try {
349
352
  const chosen = await ctx.ui.custom<string | undefined>((host, theme, _keys, done) => {
350
- dialog = new StatusDialog(host, theme, service, done, selected, options.title, undefined, options.nerdFontIcons);
353
+ dialog = new StatusDialog(host, theme, service, done, selected, options.title, undefined, options.nerdFontIcons, options.loaderStyle);
351
354
  dialog.startRefresh();
352
355
  return dialog;
353
356
  }, DIALOG_OPTIONS);
@@ -367,9 +370,10 @@ export async function showAgentStatus(
367
370
  service: ThreadService,
368
371
  inspect?: (path: string) => Promise<void>,
369
372
  nerdFontIcons = false,
373
+ loaderStyle: LoaderStyle = "circle",
370
374
  ): Promise<void> {
371
375
  if (!canOpenDialog(ctx)) return;
372
- await showAgentDialog(ctx, service, { inspect, nerdFontIcons });
376
+ await showAgentDialog(ctx, service, { inspect, nerdFontIcons, loaderStyle });
373
377
  }
374
378
 
375
379
  /** Root-owned navigation state. Opening and closing never changes the executing session. */
@@ -390,7 +394,7 @@ export class AgentNavigationController {
390
394
  this.session = undefined;
391
395
  }
392
396
 
393
- open(ctx: ExtensionContext, service: ThreadService, selectedPath?: string, nerdFontIcons = false): Promise<void> {
397
+ open(ctx: ExtensionContext, service: ThreadService, selectedPath?: string, nerdFontIcons = false, loaderStyle: LoaderStyle = "circle"): Promise<void> {
394
398
  if (this.opening) return this.opening;
395
399
  if (!canOpenDialog(ctx)) return Promise.resolve();
396
400
  if (selectedPath) this.tree.selectedPath = selectedPath;
@@ -471,6 +475,7 @@ export class AgentNavigationController {
471
475
  actions: (path) => finish({ kind: "actions", path }),
472
476
  },
473
477
  nerdFontIcons,
478
+ loaderStyle,
474
479
  );
475
480
  treeDialog.startRefresh();
476
481
  return treeDialog;
@@ -488,7 +493,7 @@ export class AgentNavigationController {
488
493
  }
489
494
  const result = await session.mount<"back" | "main">(
490
495
  (tui, activeTheme, _keys, finish) =>
491
- new LiveAgentView(tui, activeTheme, service, chosen.path, viewport!, finish, nerdFontIcons),
496
+ new LiveAgentView(tui, activeTheme, service, chosen.path, viewport!, finish, nerdFontIcons, loaderStyle),
492
497
  );
493
498
  if (result !== "back") break;
494
499
  }
@@ -534,11 +539,12 @@ export async function showAgentTree(
534
539
  service: ThreadService,
535
540
  selectedPath?: string,
536
541
  nerdFontIcons = false,
542
+ loaderStyle: LoaderStyle = "circle",
537
543
  ): Promise<void> {
538
544
  let navigation = navigationByService.get(service);
539
545
  if (!navigation) {
540
546
  navigation = new AgentNavigationController();
541
547
  navigationByService.set(service, navigation);
542
548
  }
543
- await navigation.open(ctx, service, selectedPath, nerdFontIcons);
549
+ await navigation.open(ctx, service, selectedPath, nerdFontIcons, loaderStyle);
544
550
  }
@@ -24,11 +24,7 @@ function comparePath(a: string, b: string): number {
24
24
  return a < b ? -1 : a > b ? 1 : 0;
25
25
  }
26
26
 
27
- function chainHas(
28
- parentOf: Map<string, string | null>,
29
- start: string,
30
- target: string,
31
- ): boolean {
27
+ function chainHas(parentOf: Map<string, string | null>, start: string, target: string): boolean {
32
28
  const seen = new Set<string>();
33
29
  let current: string | null = start;
34
30
  while (current) {
@@ -39,18 +35,49 @@ function chainHas(
39
35
  return false;
40
36
  }
41
37
 
38
+ /** When an agent last (re)started; older saves fall back to creation time. */
39
+ export function lastStarted(thread: ThreadView | undefined): number {
40
+ const value = thread?.lastStartedAt ?? thread?.createdAt;
41
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
42
+ }
43
+
44
+ /** Newest branch first: a branch ranks by its most recently started agent. Cycles are guarded. */
45
+ export function recencyComparator(threads: ThreadView[]): (a: string, b: string) => number {
46
+ const byPath = new Map<string, ThreadView>();
47
+ for (const thread of threads) {
48
+ if (thread?.path && !byPath.has(thread.path)) byPath.set(thread.path, thread);
49
+ }
50
+ const latest = new Map<string, number>();
51
+ for (const thread of byPath.values()) {
52
+ const time = lastStarted(thread);
53
+ const seen = new Set<string>();
54
+ let current: string | null = thread.path;
55
+ while (current && !seen.has(current)) {
56
+ seen.add(current);
57
+ latest.set(current, Math.max(latest.get(current) ?? 0, time));
58
+ const view = byPath.get(current);
59
+ current = view
60
+ ? view.parent && view.parent !== current
61
+ ? view.parent
62
+ : null
63
+ : lexicalParent(current);
64
+ }
65
+ }
66
+ return (a, b) => (latest.get(b) ?? 0) - (latest.get(a) ?? 0) || comparePath(a, b);
67
+ }
68
+
42
69
  /** Flatten retained agents. Parent links win over path shape; /root is always present.
43
- * `comparePaths` orders siblings and roots only. Cycle repair stays lexical.
70
+ * `comparePaths` orders siblings and roots only (default: most recently started branch first).
71
+ * Cycle repair stays lexical.
44
72
  */
45
73
  export function buildStatusTree(
46
74
  threads: ThreadView[],
47
75
  collapsed: Set<string>,
48
- comparePaths: (a: string, b: string) => number = comparePath,
76
+ comparePaths: (a: string, b: string) => number = recencyComparator(threads),
49
77
  ): StatusRow[] {
50
78
  const threadsByPath = new Map<string, ThreadView>();
51
79
  for (const thread of threads) {
52
- if (thread?.path && !threadsByPath.has(thread.path))
53
- threadsByPath.set(thread.path, thread);
80
+ if (thread?.path && !threadsByPath.has(thread.path)) threadsByPath.set(thread.path, thread);
54
81
  }
55
82
  const nodes = new Map<string, StatusNode>();
56
83
  const parentOf = new Map<string, string | null>();
@@ -65,8 +92,7 @@ export function buildStatusTree(
65
92
  const declaredParent = (path: string): string | null => {
66
93
  if (path === ROOT) return null;
67
94
  const thread = threadsByPath.get(path);
68
- if (thread)
69
- return thread.parent && thread.parent !== path ? thread.parent : null;
95
+ if (thread) return thread.parent && thread.parent !== path ? thread.parent : null;
70
96
  return lexicalParent(path);
71
97
  };
72
98
  const ensure = (path: string, seen = new Set<string>()): void => {