@oh-my-pi/pi-tui 18.11.0 → 18.11.2

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +52 -146
  2. package/dist/types/apps/git/git-tui.d.ts +16 -2
  3. package/dist/types/autocomplete.d.ts +2 -0
  4. package/dist/types/charts/chart-svg.d.ts +7 -13
  5. package/dist/types/chat/table-chart.d.ts +11 -15
  6. package/dist/types/chrome/transcript-container.d.ts +2 -0
  7. package/dist/types/components/image.d.ts +2 -0
  8. package/dist/types/components/markdown.d.ts +37 -0
  9. package/dist/types/native/blobs.d.ts +11 -11
  10. package/dist/types/overlays/agent-hub-projection.d.ts +10 -5
  11. package/dist/types/overlays/job-tree.d.ts +50 -0
  12. package/dist/types/overlays/jobs-panel.d.ts +24 -11
  13. package/dist/types/prompt/composer.d.ts +20 -0
  14. package/dist/types/prompt/custom-editor.d.ts +2 -0
  15. package/dist/types/prompt/image-references.d.ts +22 -0
  16. package/dist/types/prompt/macos-spelling.d.ts +2 -1
  17. package/dist/types/prompt/prose-gate.d.ts +3 -0
  18. package/dist/types/prompt/queued-messages.d.ts +1 -1
  19. package/dist/types/prompt/typing-word.d.ts +25 -0
  20. package/dist/types/render/hyperlink.d.ts +2 -0
  21. package/dist/types/render/utils.d.ts +1 -1
  22. package/dist/types/status-line/context-usage.d.ts +3 -0
  23. package/dist/types/status-line/host.d.ts +6 -4
  24. package/dist/types/status-line/startup.d.ts +6 -6
  25. package/dist/types/stdin-buffer.d.ts +7 -0
  26. package/dist/types/terminal.d.ts +8 -4
  27. package/dist/types/tools/eval.d.ts +5 -0
  28. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  29. package/dist/types/tools/read.d.ts +5 -4
  30. package/dist/types/tui.d.ts +10 -0
  31. package/package.json +9 -9
  32. package/src/apps/git/git-tui.ts +27 -10
  33. package/src/apps/git/sidebar.ts +5 -1
  34. package/src/autocomplete.ts +21 -19
  35. package/src/bracketed-paste.ts +9 -2
  36. package/src/charts/chart-svg.ts +19 -22
  37. package/src/chat/assistant-message.ts +37 -12
  38. package/src/chat/bash-execution.ts +7 -2
  39. package/src/chat/image-loading.ts +4 -6
  40. package/src/chat/read-tool-group.ts +1 -0
  41. package/src/chat/table-chart.ts +24 -57
  42. package/src/chat/tool-execution.ts +11 -4
  43. package/src/chat/user-message.ts +22 -15
  44. package/src/chrome/transcript-container.ts +10 -0
  45. package/src/components/editor.ts +12 -12
  46. package/src/components/image.ts +23 -6
  47. package/src/components/markdown.ts +375 -6
  48. package/src/components/settings-list.ts +2 -4
  49. package/src/native/blobs.ts +22 -6
  50. package/src/native/reconcile.ts +19 -15
  51. package/src/overlays/agent-hub-projection.ts +63 -12
  52. package/src/overlays/btw-history-panel.ts +30 -23
  53. package/src/overlays/extensions/extension-list.ts +4 -6
  54. package/src/overlays/job-tree.ts +177 -0
  55. package/src/overlays/jobs-panel.ts +107 -49
  56. package/src/overlays/settings-selector.ts +3 -0
  57. package/src/prompt/composer.ts +180 -23
  58. package/src/prompt/custom-editor.ts +19 -1
  59. package/src/prompt/image-references.ts +79 -2
  60. package/src/prompt/macos-spelling.ts +28 -5
  61. package/src/prompt/prose-gate.ts +3 -0
  62. package/src/prompt/queued-messages.ts +9 -2
  63. package/src/prompt/typing-word.ts +59 -0
  64. package/src/render/code-cell.ts +8 -1
  65. package/src/render/hyperlink.ts +5 -0
  66. package/src/render/utils.ts +1 -1
  67. package/src/render/width-aware-text.ts +6 -5
  68. package/src/status-line/component.ts +22 -10
  69. package/src/status-line/context-usage.ts +22 -16
  70. package/src/status-line/footer.ts +18 -35
  71. package/src/status-line/host.ts +6 -1
  72. package/src/status-line/startup.ts +6 -6
  73. package/src/stdin-buffer.ts +11 -1
  74. package/src/terminal.ts +136 -42
  75. package/src/tools/ast-grep.ts +2 -2
  76. package/src/tools/edit.ts +16 -1
  77. package/src/tools/eval.ts +51 -11
  78. package/src/tools/grouped-file-output.ts +6 -1
  79. package/src/tools/read.ts +6 -5
  80. package/src/tools/write.ts +1 -1
  81. package/src/tui.ts +61 -30
  82. package/src/utils.ts +5 -3
@@ -7,10 +7,12 @@
7
7
  * cache), else uploads it with verb `b` before the frame that first
8
8
  * references it.
9
9
  */
10
+ import * as url from "node:url";
10
11
  import type { TspProps } from "@oh-my-pi/pi-wire";
11
12
  import { resolveImageOptions } from "../render/render-utils";
12
13
  import { getImageDimensions } from "../terminal-capabilities";
13
14
  import { node } from "./describe";
15
+ import { imageLinksEnabled, transcriptImageLink } from "../prompt/image-references";
14
16
  import type { NativeChild, NativeNode } from "./node";
15
17
 
16
18
  export interface NativeBlob {
@@ -92,15 +94,29 @@ export function base64ImageNode(
92
94
  );
93
95
  }
94
96
 
95
- /** `image` nodes for base64 payloads, one per slot key, rebuilt only when the slot's payload changes. */
97
+ /**
98
+ * Props that make an `image` node open the file at `filePath` (as a `file://` URL, the TSP
99
+ * open-target form): a click zooms the image in the terminal, and the file opens from its
100
+ * context menu. Empty without a file.
101
+ */
102
+ export function openableImageProps(filePath: string | undefined): Pick<TspProps<"image">, "href" | "actions"> {
103
+ return filePath ? { href: url.pathToFileURL(filePath).href, actions: { menu: ["open"] } } : {};
104
+ }
105
+
106
+ /**
107
+ * `image` nodes for base64 payloads, one per slot key, rebuilt only when the slot's payload
108
+ * or the link policy changes. Each opens its file (`sourcePath`, else a blob copy).
109
+ */
96
110
  export class NativeImageCache {
97
- #entries = new Map<string, { data: string; node: NativeNode }>();
111
+ #entries = new Map<string, { data: string; linked: boolean; node: NativeNode }>();
98
112
 
99
- get(key: string, data: string, mimeType: string): NativeNode {
113
+ get(key: string, data: string, mimeType: string, sourcePath?: string): NativeNode {
114
+ const linked = imageLinksEnabled();
100
115
  const cached = this.#entries.get(key);
101
- if (cached?.data === data) return cached.node;
102
- const image = base64ImageNode(data, mimeType, { alt: mimeType }, key);
103
- this.#entries.set(key, { data, node: image });
116
+ if (cached?.data === data && cached.linked === linked) return cached.node;
117
+ const open = openableImageProps(transcriptImageLink({ data, mimeType }, sourcePath));
118
+ const image = base64ImageNode(data, mimeType, { alt: mimeType, ...open }, key);
119
+ this.#entries.set(key, { data, linked, node: image });
104
120
  return image;
105
121
  }
106
122
  }
@@ -700,24 +700,28 @@ export class Reconciler {
700
700
  this.#ops.push(["text", id, "append", newText.slice(oldText.length)]);
701
701
  return;
702
702
  }
703
- if ((kind === "editor" || kind === "input") && oldText.length > 0) {
703
+ // A streaming `md` node rewrites only its tail (the speculatively closed span it ends in), so an
704
+ // edit past a shared head splices too instead of resending the whole text.
705
+ if ((kind === "editor" || kind === "input" || kind === "md") && oldText.length > 0) {
704
706
  const limit = Math.min(oldText.length, newText.length);
705
707
  let prefix = 0;
706
708
  while (prefix < limit && oldText.charCodeAt(prefix) === newText.charCodeAt(prefix)) prefix++;
707
- let suffix = 0;
708
- while (
709
- suffix < limit - prefix &&
710
- oldText.charCodeAt(oldText.length - 1 - suffix) === newText.charCodeAt(newText.length - 1 - suffix)
711
- )
712
- suffix++;
713
- this.#ops.push([
714
- "splice",
715
- id,
716
- prefix,
717
- oldText.length - prefix - suffix,
718
- newText.slice(prefix, newText.length - suffix),
719
- ]);
720
- return;
709
+ if (kind !== "md" || prefix > 0) {
710
+ let suffix = 0;
711
+ while (
712
+ suffix < limit - prefix &&
713
+ oldText.charCodeAt(oldText.length - 1 - suffix) === newText.charCodeAt(newText.length - 1 - suffix)
714
+ )
715
+ suffix++;
716
+ this.#ops.push([
717
+ "splice",
718
+ id,
719
+ prefix,
720
+ oldText.length - prefix - suffix,
721
+ newText.slice(prefix, newText.length - suffix),
722
+ ]);
723
+ return;
724
+ }
721
725
  }
722
726
  this.#ops.push(["text", id, "replace", newText]);
723
727
  }
@@ -4,6 +4,10 @@ import type { ObservableSession } from "./session-observer-registry";
4
4
 
5
5
  export type AgentMetrics = AgentMetricsSummary;
6
6
 
7
+ export interface AgentCostSnapshot {
8
+ cost: number | undefined;
9
+ }
10
+
7
11
  export interface AggregateMetrics extends AgentMetrics {
8
12
  reportedAgents: number;
9
13
  /** Rows whose duration is an observer-measured active runtime. */
@@ -203,15 +207,28 @@ export function hubFallbackStatsSession<TRecord extends AgentRecordLike>(
203
207
  return session && typeof session.getSessionStats === "function" ? session : undefined;
204
208
  }
205
209
 
206
- function withDirectCost(metrics: AgentMetrics | undefined, cost: number | undefined): AgentMetrics | undefined {
210
+ /**
211
+ * Shared row policy for the Agent Hub and the status-line cost total.
212
+ * Non-cost metrics come from live progress, then persisted history, then the retained
213
+ * snapshot (parked rows only), then the live session. Cost always overlays the cumulative
214
+ * direct-session bill: live, then `history.directCost` (written at park), then retained.
215
+ * Persisted `history.metrics.cost` is a leaf-scoped snapshot, so it never wins.
216
+ */
217
+ function projectRowMetrics<TMetrics extends AgentCostSnapshot>(
218
+ ref: AgentRecordLike,
219
+ observed: ObservableSession | undefined,
220
+ live: TMetrics | undefined,
221
+ retained: TMetrics | undefined,
222
+ hasLiveSession: boolean,
223
+ ): TMetrics | AgentMetrics | undefined {
224
+ const cost = live?.cost ?? ref.history?.directCost ?? retained?.cost;
225
+ const metrics = observed?.progress
226
+ ? progressMetrics(observed)
227
+ : (ref.history?.metrics ?? (!hasLiveSession ? retained : undefined) ?? live);
207
228
  return metrics && cost !== undefined ? { ...metrics, cost } : metrics;
208
229
  }
209
230
 
210
- /**
211
- * Preserve progress/history for non-cost metrics, overlaying cumulative direct-session cost.
212
- * Persisted `history.metrics.cost` is a leaf-scoped snapshot, so it never overrides live
213
- * progress; only the cumulative direct-cost sources do.
214
- */
231
+ /** Full Agent Hub row metrics; see {@link projectRowMetrics} for source precedence. */
215
232
  export function hubRowMetrics<TRecord extends AgentRecordLike>(
216
233
  ref: TRecord,
217
234
  observed: ObservableSession | undefined,
@@ -220,12 +237,46 @@ export function hubRowMetrics<TRecord extends AgentRecordLike>(
220
237
  const session = hubFallbackStatsSession(ref, observed);
221
238
  const liveEntry = session ? sessionMetrics.get(session) : undefined;
222
239
  const retainedEntry = sessionMetrics.get(ref);
223
- const historyMetrics = ref.history?.metrics;
224
- const cost = liveEntry?.metrics?.cost ?? ref.history?.directCost ?? retainedEntry?.metrics?.cost;
225
- if (observed?.progress) return withDirectCost(progressMetrics(observed), cost);
226
- if (historyMetrics) return withDirectCost(historyMetrics, cost);
227
- if (!session && retainedEntry?.metrics) return withDirectCost(retainedEntry.metrics, cost);
228
- return withDirectCost(liveEntry?.metrics, cost);
240
+ return projectRowMetrics(ref, observed, liveEntry?.metrics, retainedEntry?.metrics, session !== undefined);
241
+ }
242
+
243
+ /** Cost-only projection for frequent status updates; full roster metrics keep their own cache. */
244
+ export function aggregateCost<TRecord extends AgentRecordLike>(args: {
245
+ rows: readonly TRecord[];
246
+ observedById: ReadonlyMap<string, ObservableSession>;
247
+ sessionCosts: WeakMap<object, AgentCostSnapshot>;
248
+ }): number {
249
+ let total = 0;
250
+ const countedSessions = new Set<NonNullable<AgentRecordLike["session"]>>();
251
+ for (const ref of args.rows) {
252
+ const observed = args.observedById.get(ref.id);
253
+ const session = hubFallbackStatsSession(ref, observed);
254
+ let cached = session ? args.sessionCosts.get(session) : undefined;
255
+ if (session) {
256
+ const directCost = readSessionDirectCost(session);
257
+ if (directCost !== undefined) {
258
+ cached = { cost: directCost };
259
+ args.sessionCosts.set(session, cached);
260
+ } else if (!cached || !fallbackReadCurrent(cached, session)) {
261
+ const stamp = fallbackReadStamp(session);
262
+ cached = { cost: readSessionMetrics(session, undefined)?.cost };
263
+ if (stamp) fallbackReadStamps.set(cached, stamp);
264
+ args.sessionCosts.set(session, cached);
265
+ }
266
+ if (cached?.cost !== undefined) args.sessionCosts.set(ref, cached);
267
+ }
268
+ const cost = projectRowMetrics(
269
+ ref,
270
+ observed,
271
+ cached?.cost !== undefined ? cached : undefined,
272
+ args.sessionCosts.get(ref),
273
+ session !== undefined,
274
+ )?.cost;
275
+ if (cost === undefined || (session && countedSessions.has(session))) continue;
276
+ if (session) countedSessions.add(session);
277
+ total += finiteMetric(cost);
278
+ }
279
+ return total;
229
280
  }
230
281
 
231
282
  export function aggregateMetrics<TRecord extends AgentRecordLike>(args: {
@@ -369,8 +369,9 @@ export class BtwHistoryPanel implements Component, Focusable {
369
369
  }
370
370
  handleInput(data: string): void {
371
371
  if (this.#composer) {
372
- // The input owns every key, including panel shortcuts and pasted text.
373
- this.#composer.input.handleInput(data);
372
+ // The input owns every key it handles, including panel shortcuts and
373
+ // pasted text; the line keys it ignores still scroll the answer above.
374
+ if (!this.#composer.input.handleInput(data)) this.#scrollDetail(data);
374
375
  this.#options.requestRender();
375
376
  return;
376
377
  }
@@ -417,31 +418,37 @@ export class BtwHistoryPanel implements Component, Focusable {
417
418
  else if (matchesKey(data, "home")) this.#select(0);
418
419
  else if (matchesKey(data, "end")) this.#select(this.#records.length - 1);
419
420
  else return;
420
- } else {
421
- const by: TspScrollBy | undefined = matchesSelectUp(data)
422
- ? "line-up"
423
- : matchesSelectDown(data)
424
- ? "line-down"
425
- : matchesSelectPageUp(data)
426
- ? "page-up"
427
- : matchesSelectPageDown(data)
428
- ? "page-down"
429
- : matchesKey(data, "home")
430
- ? "start"
431
- : matchesKey(data, "end")
432
- ? "end"
433
- : undefined;
434
- if (by === "line-up") this.#detail.scroll(-1);
435
- else if (by === "line-down") this.#detail.scroll(1);
436
- else if (by === "page-up") this.#detail.page(-1);
437
- else if (by === "page-down") this.#detail.page(1);
438
- else if (!this.#detail.handleScrollKey(data)) return;
439
- if (by) this.#scroll = { by, n: (this.#scroll?.n ?? 0) + 1 };
440
- this.#followLatest = matchesKey(data, "end");
421
+ } else if (!this.#scrollDetail(data)) {
422
+ return;
441
423
  }
442
424
  this.#options.requestRender();
443
425
  }
444
426
 
427
+ /** Apply an answer-pane scroll key; a scroll stops following the newest row unless it is End. */
428
+ #scrollDetail(data: string): boolean {
429
+ const by: TspScrollBy | undefined = matchesSelectUp(data)
430
+ ? "line-up"
431
+ : matchesSelectDown(data)
432
+ ? "line-down"
433
+ : matchesSelectPageUp(data)
434
+ ? "page-up"
435
+ : matchesSelectPageDown(data)
436
+ ? "page-down"
437
+ : matchesKey(data, "home")
438
+ ? "start"
439
+ : matchesKey(data, "end")
440
+ ? "end"
441
+ : undefined;
442
+ if (by === "line-up") this.#detail.scroll(-1);
443
+ else if (by === "line-down") this.#detail.scroll(1);
444
+ else if (by === "page-up") this.#detail.page(-1);
445
+ else if (by === "page-down") this.#detail.page(1);
446
+ else if (!this.#detail.handleScrollKey(data)) return false;
447
+ if (by) this.#scroll = { by, n: (this.#scroll?.n ?? 0) + 1 };
448
+ this.#followLatest = matchesKey(data, "end");
449
+ return true;
450
+ }
451
+
445
452
  /** A large glass sheet (the list beside the reader), palette-sized while there is nothing to list. */
446
453
  get nativeOverlay(): NonNullable<Component["nativeOverlay"]> {
447
454
  return this.#records.length > 0 ? SHEET : EMPTY_SHEET;
@@ -7,7 +7,6 @@
7
7
  */
8
8
  import type { TspPickerGroup, TspPickerItem, TspProps, TspSpan, TspTone } from "@oh-my-pi/pi-wire";
9
9
  import type { Component } from "../../tui";
10
- import { formatKeyHint } from "../../app-keybindings";
11
10
  import { node, span, stableKey } from "../../native/describe";
12
11
  import type { NativeNode } from "../../native/node";
13
12
  import { pickerFuzzyHits, pickerQuery } from "../../native/picker";
@@ -499,11 +498,10 @@ export class ExtensionList implements Component {
499
498
  ]
500
499
  : undefined,
501
500
  facts: { kind: this.#getKindLabel(ext.kind) },
502
- disabled: effectivelyDisabled
503
- ? masterDisabled
504
- ? "Provider disabled"
505
- : `Disabled · ${formatKeyHint("space")} to enable`
506
- : undefined,
501
+ // Only a disabled provider makes the row inert. An extension switched
502
+ // off by its own toggle must stay activatable, or the click/dblclick
503
+ // that turned it off could never turn it back on.
504
+ disabled: masterDisabled ? "Provider disabled" : undefined,
507
505
  };
508
506
  }
509
507
 
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The jobs of an agent and its subagents as a tree, shared by the jobs sheet
3
+ * and the `/jobs` report. The viewing agent's own jobs sit at the top level;
4
+ * a subagent's jobs nest under the task job that runs it, or under a header
5
+ * naming the subagent when that job is no longer listed (a foreground task, or
6
+ * one evicted from the recent list). Siblings sort branchiest first: the more
7
+ * rows a subtree holds the higher it sits, so leaf jobs settle to the bottom of
8
+ * their level; ties keep running before settled, then oldest first.
9
+ */
10
+ import { buildTreePrefix, getTreeBranch } from "../render/utils";
11
+ import type { Theme } from "../theme/theme";
12
+
13
+ /** What the tree reads off a job. */
14
+ export interface JobTreeJob {
15
+ readonly id: string;
16
+ readonly status: "running" | "completed" | "failed" | "cancelled";
17
+ readonly startTime: number;
18
+ /** Registry id of the agent that owns the job; absent or the root id: a top-level job. */
19
+ readonly ownerId?: string;
20
+ /** Registry id of the subagent a task job runs: the job heads that agent's subtree. */
21
+ readonly agentId?: string;
22
+ }
23
+
24
+ /** A subagent in the tree, by registry id: an owner of listed jobs, or an ancestor linking one to the root. */
25
+ export interface JobTreeAgent {
26
+ readonly id: string;
27
+ readonly parentId?: string;
28
+ }
29
+
30
+ /** Where a row sits: its depth and the rails drawn left of it. */
31
+ export interface JobTreePlace {
32
+ /** 0 for the top level. */
33
+ readonly depth: number;
34
+ /** Per enclosing level below the top, whether that level's rail continues past this row. */
35
+ readonly rails: readonly boolean[];
36
+ /** Whether this row is the last of its siblings. */
37
+ readonly last: boolean;
38
+ /** Whether rows nest under this one. */
39
+ readonly parent: boolean;
40
+ }
41
+
42
+ /** One tree row: a job (a task job also heads its subagent), or a header for a subagent with no listed task job. */
43
+ export type JobTreeRow<J extends JobTreeJob> =
44
+ | (JobTreePlace & { readonly kind: "job"; readonly job: J; readonly agent?: JobTreeAgent })
45
+ | (JobTreePlace & { readonly kind: "agent"; readonly agent: JobTreeAgent });
46
+
47
+ interface TreeNode<J> {
48
+ job?: J;
49
+ agent?: JobTreeAgent;
50
+ readonly children: TreeNode<J>[];
51
+ /** Rows nested under this node. */
52
+ size: number;
53
+ running: boolean;
54
+ startTime: number;
55
+ }
56
+
57
+ /**
58
+ * `jobs` as tree rows in display order. `rootId` is the viewing agent: its
59
+ * jobs, ownerless jobs and jobs of owners outside `agents` sit at the top
60
+ * level, as do agents whose parent is the root or unknown.
61
+ */
62
+ export function buildJobTree<J extends JobTreeJob>(
63
+ jobs: readonly J[],
64
+ agents: readonly JobTreeAgent[],
65
+ rootId: string | undefined,
66
+ ): JobTreeRow<J>[] {
67
+ const top: TreeNode<J>[] = [];
68
+ const agentNodes = new Map<string, TreeNode<J>>();
69
+ for (const agent of agents) {
70
+ if (agent.id === rootId) continue;
71
+ agentNodes.set(agent.id, { agent, children: [], size: 0, running: false, startTime: Infinity });
72
+ }
73
+ // A task job heads its subagent; with several, the running then newest one.
74
+ for (const job of jobs) {
75
+ const node = job.agentId === undefined ? undefined : agentNodes.get(job.agentId);
76
+ if (!node) continue;
77
+ const held = node.job;
78
+ if (!held || (held.status !== "running" && (job.status === "running" || job.startTime > held.startTime))) {
79
+ node.job = job;
80
+ }
81
+ }
82
+ for (const node of agentNodes.values()) {
83
+ (parentNode(agentNodes, node.agent!)?.children ?? top).push(node);
84
+ }
85
+ for (const job of jobs) {
86
+ if (job.agentId !== undefined && agentNodes.get(job.agentId)?.job === job) continue;
87
+ const owner = job.ownerId === undefined || job.ownerId === rootId ? undefined : agentNodes.get(job.ownerId);
88
+ (owner?.children ?? top).push({ job, children: [], size: 0, running: false, startTime: Infinity });
89
+ }
90
+ settle(top);
91
+ return flatten(top);
92
+ }
93
+
94
+ /** `agent`'s parent node, or undefined for the top level: the root, an unknown agent, or a link that would close a cycle. */
95
+ function parentNode<J>(agentNodes: ReadonlyMap<string, TreeNode<J>>, agent: JobTreeAgent): TreeNode<J> | undefined {
96
+ const parent = agent.parentId === undefined ? undefined : agentNodes.get(agent.parentId);
97
+ if (!parent) return undefined;
98
+ const seen = new Set<string>();
99
+ for (let cursor = agent.parentId; cursor !== undefined && !seen.has(cursor);) {
100
+ if (cursor === agent.id) return undefined;
101
+ seen.add(cursor);
102
+ cursor = agentNodes.get(cursor)?.agent?.parentId;
103
+ }
104
+ return parent;
105
+ }
106
+
107
+ /** Size, liveness and start time of each subtree, then siblings branchiest first; drops subagents with nothing listed. */
108
+ function settle<J extends JobTreeJob>(top: TreeNode<J>[]): void {
109
+ // Post-order without recursion: lineage depth is not ours to bound.
110
+ const order: TreeNode<J>[] = [];
111
+ const stack = [...top];
112
+ while (stack.length > 0) {
113
+ const node = stack.pop()!;
114
+ order.push(node);
115
+ stack.push(...node.children);
116
+ }
117
+ const prune = (nodes: TreeNode<J>[]): void => {
118
+ const kept = nodes.filter(node => node.job !== undefined || node.children.length > 0);
119
+ nodes.splice(0, nodes.length, ...kept);
120
+ nodes.sort(compareNodes);
121
+ };
122
+ for (let i = order.length - 1; i >= 0; i--) {
123
+ const node = order[i];
124
+ prune(node.children);
125
+ node.size = 0;
126
+ node.running = node.job?.status === "running";
127
+ node.startTime = node.job?.startTime ?? Infinity;
128
+ for (const child of node.children) {
129
+ node.size += 1 + child.size;
130
+ node.running ||= child.running;
131
+ node.startTime = Math.min(node.startTime, child.startTime);
132
+ }
133
+ }
134
+ prune(top);
135
+ }
136
+
137
+ /** Branchiest first: the larger subtree, then running before settled, then the older. */
138
+ function compareNodes<J>(a: TreeNode<J>, b: TreeNode<J>): number {
139
+ return b.size - a.size || Number(!a.running) - Number(!b.running) || a.startTime - b.startTime;
140
+ }
141
+
142
+ /** Depth-first rows of `top`, iteratively so lineage depth stays unbounded. */
143
+ function flatten<J extends JobTreeJob>(top: readonly TreeNode<J>[]): JobTreeRow<J>[] {
144
+ const out: JobTreeRow<J>[] = [];
145
+ const stack: { node: TreeNode<J>; depth: number; rails: readonly boolean[]; last: boolean }[] = [];
146
+ const push = (level: readonly TreeNode<J>[], depth: number, rails: readonly boolean[]): void => {
147
+ for (let i = level.length - 1; i >= 0; i--) {
148
+ stack.push({ node: level[i], depth, rails, last: i === level.length - 1 });
149
+ }
150
+ };
151
+ push(top, 0, []);
152
+ while (stack.length > 0) {
153
+ const { node, depth, rails, last } = stack.pop()!;
154
+ const place = { depth, rails, last, parent: node.children.length > 0 };
155
+ if (node.job) out.push({ ...place, kind: "job", job: node.job, agent: node.agent });
156
+ else if (node.agent) out.push({ ...place, kind: "agent", agent: node.agent });
157
+ // The top level draws no rail, so its children's rails start empty.
158
+ push(node.children, depth + 1, depth === 0 ? [] : [...rails, !last]);
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /** The connector drawn before a row's head: nothing at the top level, else rails then a branch. */
164
+ export function jobTreeGuide(row: JobTreePlace, theme: Theme): string {
165
+ if (row.depth === 0) return "";
166
+ return `${buildTreePrefix(row.rails, theme)}${getTreeBranch(row.last, theme)} `;
167
+ }
168
+
169
+ /**
170
+ * The prefix of lines under a row's head (its label, a wrapped command): the
171
+ * rails that continue past it, then the rail down to its children or blank,
172
+ * two columns wide so a top-level leaf's lines indent by two.
173
+ */
174
+ export function jobTreeIndent(row: JobTreePlace, theme: Theme): string {
175
+ const rails = row.depth === 0 ? "" : buildTreePrefix([...row.rails, !row.last], theme);
176
+ return `${rails}${row.parent ? `${theme.tree.vertical} ` : " "}`;
177
+ }