@aoshizuku/pi-bettertui 0.1.1 → 0.1.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.
package/src/timeline.ts CHANGED
@@ -1,881 +1,881 @@
1
- import { isFailed, isInterrupted, isManagedTool, isMergeableTool, isShellTool, skillReadName, targetKey } from "./tool-summary.js";
2
- import type { ToolContentBlock, ToolResultSnapshot } from "./types.js";
3
- import { argsOf, str } from "./format.js";
4
- import { classifyBlock, FOLD_OFF, type FoldPolicy, type FoldStats, thinkingAnchor, thinkingRuns } from "./segment.js";
5
-
6
- export interface ToolRow {
7
- id: string;
8
- name: string;
9
- args: Record<string, unknown>;
10
- group?: ToolGroup;
11
- standalone: boolean;
12
- expanded: boolean;
13
- startedAt: number;
14
- /** When the call started running, as opposed to when its arguments started streaming. */
15
- execStartedAt?: number;
16
- endedAt?: number;
17
- result?: ToolResultSnapshot;
18
- partialText: string;
19
- invalidate?: () => void;
20
- lastInvalidateAt: number;
21
- version: number;
22
- }
23
-
24
- export interface ToolGroup {
25
- id: string;
26
- members: ToolRow[];
27
- expanded: boolean;
28
- closed: boolean;
29
- startedAt: number;
30
- endedAt?: number;
31
- }
32
-
33
- /** A thinking run inside a segment; its text is refreshed on every update of its message. */
34
- export interface SegThinkingItem {
35
- kind: "thinking";
36
- anchor: string;
37
- msgTs: number;
38
- run: number;
39
- text: string;
40
- streaming: boolean;
41
- /**
42
- * Measured live only (fold-more.md §5.5): when the run was first seen (its message's timestamp
43
- * when the run opens the message), and when it stopped growing — the next block of its message
44
- * appeared, or the message ended. A seed has no clock to read and leaves both unset.
45
- */
46
- startedAt?: number;
47
- endedAt?: number;
48
- /** Runs with text in the message so far, and the message's `durationMs`; the fallback when nothing was measured. */
49
- messageRuns: number;
50
- messageDurationMs?: number;
51
- }
52
-
53
- /**
54
- * How long a finished thinking run took, for its line in the list: what was measured live, else
55
- * its message's `durationMs` when the message holds only this run. A message with several runs
56
- * cannot split its duration among them, so those get none (`Thought`).
57
- */
58
- export function thoughtDuration(item: SegThinkingItem): number | undefined {
59
- if (item.startedAt !== undefined && item.endedAt !== undefined) return Math.max(0, item.endedAt - item.startedAt);
60
- return item.messageRuns === 1 ? item.messageDurationMs : undefined;
61
- }
62
-
63
- export interface SegToolItem {
64
- kind: "tool";
65
- /** The tool call id. */
66
- anchor: string;
67
- name: string;
68
- }
69
-
70
- export type SegItem = SegThinkingItem | SegToolItem;
71
-
72
- /**
73
- * A run of thinking and non-changing tool calls between two boundaries (fold-more.md §5.1).
74
- * Items keep the model's real output order across assistant messages.
75
- */
76
- export interface Segment {
77
- id: string;
78
- items: SegItem[];
79
- /** The first anchor; it draws the whole segment and never changes. */
80
- host: string;
81
- /** No more items join: a boundary came. The segment still draws as a list until it collapses. */
82
- closed: boolean;
83
- /**
84
- * Drawn as one summary line instead of the list: set for every segment of a run once the run
85
- * settles, never in the middle of one (fold-more.md §4.10).
86
- */
87
- collapsed: boolean;
88
- /** A collapsed segment opened again into its list. */
89
- expanded: boolean;
90
- /** Items whose details are open in the list. */
91
- expandedItems: Set<string>;
92
- /** Messages that put thinking into this segment: timestamp → duration, counted once each. */
93
- thinkingMsgs: Map<number, { durationMs?: number; streaming: boolean }>;
94
- }
95
-
96
- export type FoldRole =
97
- | { kind: "single"; segment?: Segment }
98
- | { kind: "host"; segment: Segment }
99
- | { kind: "hidden"; segment: Segment };
100
-
101
- /** Session entry types that end a segment besides messages; extension state entries do not. */
102
- const SEGMENT_CLOSING_ENTRIES = new Set(["compaction", "branch_summary", "custom_message"]);
103
-
104
- interface MessageLike {
105
- role?: string;
106
- content?: unknown;
107
- stopReason?: string;
108
- timestamp?: number;
109
- toolCallId?: string;
110
- toolName?: string;
111
- isError?: boolean;
112
- details?: unknown;
113
- durationMs?: number;
114
- }
115
-
116
- function asMessage(value: unknown): MessageLike | undefined {
117
- return typeof value === "object" && value !== null ? (value as MessageLike) : undefined;
118
- }
119
-
120
- export function hasVisibleText(message: MessageLike | undefined): boolean {
121
- if (!message) return false;
122
- if (typeof message.content === "string") return message.content.trim().length > 0;
123
- if (!Array.isArray(message.content)) return false;
124
- return message.content.some((item) => {
125
- if (!item || typeof item !== "object") return false;
126
- const block = item as { type?: unknown; text?: unknown };
127
- return block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0;
128
- });
129
- }
130
-
131
- function snapshot(value: unknown): ToolResultSnapshot | undefined {
132
- if (!value || typeof value !== "object") return undefined;
133
- const message = value as {
134
- content?: unknown;
135
- details?: unknown;
136
- isError?: unknown;
137
- durationMs?: unknown;
138
- };
139
- const content: ToolContentBlock[] = [];
140
- if (Array.isArray(message.content)) {
141
- for (const block of message.content) {
142
- if (!block || typeof block !== "object") continue;
143
- const item = block as { type?: unknown; text?: unknown; data?: unknown; mimeType?: unknown };
144
- if (item.type === "text" && typeof item.text === "string") {
145
- content.push({ type: "text", text: item.text });
146
- } else if (item.type === "image" && typeof item.data === "string" && typeof item.mimeType === "string") {
147
- content.push({ type: "image", data: item.data, mimeType: item.mimeType });
148
- }
149
- }
150
- }
151
- return {
152
- content,
153
- details: message.details,
154
- isError: message.isError === true,
155
- durationMs: typeof message.durationMs === "number" ? message.durationMs : undefined,
156
- };
157
- }
158
-
159
- /**
160
- * Timeline of compact transcript rows. It owns grouping and boundaries only;
161
- * rendering lives in tool-row.ts. This keeps resume and live rendering
162
- * deterministic from the same model.
163
- */
164
- export class ActivityTimeline {
165
- private rows = new Map<string, ToolRow>();
166
- private groups = new Map<string, ToolGroup>();
167
- private current?: ToolGroup;
168
- private sequence = 0;
169
- epoch = 0;
170
-
171
- // Fold (fold-more.md §5.9). Off by default, so read-only groups work as before.
172
- private fold: FoldPolicy = FOLD_OFF;
173
- private segments = new Map<string, Segment>();
174
- private anchorOf = new Map<string, Segment>();
175
- private currentSegment?: Segment;
176
- /** Units already placed: an item, or a boundary that has already closed its segment. */
177
- private seenUnits = new Map<string, "item" | "boundary">();
178
- private ingested = new Set<number>();
179
- private latestMessage = Number.NEGATIVE_INFINITY;
180
- private seeding = false;
181
- /** pi's Ctrl+O state, recorded by tool rows so thinking hosts can follow it too. */
182
- globalExpanded = false;
183
- /** pi's Ctrl+T state ("show thinking details"), recorded by the thinking patch. */
184
- thinkingDetails = false;
185
- /** Called when a segment hosted by a thinking run changes; there is no tool row to invalidate. */
186
- onFoldChange?: () => void;
187
-
188
- reset(): void {
189
- this.rows.clear();
190
- this.groups.clear();
191
- this.current = undefined;
192
- this.sequence = 0;
193
- this.segments.clear();
194
- this.anchorOf.clear();
195
- this.currentSegment = undefined;
196
- this.seenUnits.clear();
197
- this.ingested.clear();
198
- this.latestMessage = Number.NEGATIVE_INFINITY;
199
- this.epoch++;
200
- }
201
-
202
- /** Takes effect for what is ingested next; callers reseed after changing it. */
203
- setFoldPolicy(policy: FoldPolicy): void {
204
- this.fold = policy;
205
- }
206
-
207
- get foldEnabled(): boolean {
208
- return this.fold.enabled;
209
- }
210
-
211
- get foldPolicy(): FoldPolicy {
212
- return this.fold;
213
- }
214
-
215
- /** Invalidate callbacks of every row, so a reseed can make pi rebuild their components. */
216
- rowInvalidators(): Array<() => void> {
217
- return [...this.rows.values()].flatMap((row) => (row.invalidate ? [row.invalidate] : []));
218
- }
219
-
220
- bumpEpoch(): void {
221
- this.epoch++;
222
- }
223
-
224
- begin(id: string, name: string, args: unknown, at = Date.now(), merge = true): ToolRow {
225
- const existing = this.rows.get(id);
226
- if (existing) return existing;
227
-
228
- const row: ToolRow = {
229
- id,
230
- name,
231
- args: argsOf(args),
232
- standalone: true,
233
- expanded: false,
234
- startedAt: at,
235
- partialText: "",
236
- lastInvalidateAt: 0,
237
- version: 0,
238
- };
239
- this.rows.set(id, row);
240
-
241
- // Fold replaces read-only groups; ingestAssistant builds segments instead.
242
- if (this.fold.enabled) return row;
243
- if (!merge || !isMergeableTool(name) || !isManagedTool(name) || skillReadName(name, row.args)) {
244
- this.closeCurrent();
245
- return row;
246
- }
247
-
248
- if (!this.current || this.current.closed) {
249
- const group: ToolGroup = {
250
- id: `g:${id}`,
251
- members: [row],
252
- expanded: false,
253
- closed: false,
254
- startedAt: at,
255
- };
256
- this.current = group;
257
- this.groups.set(group.id, group);
258
- row.group = group;
259
- row.standalone = false;
260
- } else {
261
- const group = this.current;
262
- group.members.push(row);
263
- group.endedAt = undefined;
264
- row.group = group;
265
- row.standalone = false;
266
- }
267
- return row;
268
- }
269
-
270
- /**
271
- * A call's arguments stream in after its row exists, so a read can join a group
272
- * before its path shows it loads a skill. Move such a row out to stand alone, and
273
- * close the group so later reads do not merge into a row drawn above it.
274
- */
275
- detachSkillRead(id: string): boolean {
276
- const row = this.rows.get(id);
277
- const group = row?.group;
278
- if (!row || !group || !skillReadName(row.name, row.args)) return false;
279
- const index = group.members.indexOf(row);
280
- if (index >= 0) group.members.splice(index, 1);
281
- row.group = undefined;
282
- row.standalone = true;
283
- if (group.members.length === 0) {
284
- this.groups.delete(group.id);
285
- if (this.current === group) this.current = undefined;
286
- } else {
287
- if (this.current === group) this.closeCurrent(false);
288
- this.touchGroup(group);
289
- }
290
- row.invalidate?.();
291
- return true;
292
- }
293
-
294
- end(id: string, result: unknown, at = Date.now()): ToolRow | undefined {
295
- const row = this.rows.get(id);
296
- if (!row) return undefined;
297
- row.endedAt = at;
298
- row.result = snapshot(result);
299
- row.partialText = "";
300
- row.version++;
301
- if (row.group) {
302
- row.group.endedAt = Math.max(row.group.endedAt ?? 0, at);
303
- }
304
- this.touch(row);
305
- return row;
306
- }
307
-
308
- setResult(id: string, result: unknown, at = Date.now()): ToolRow | undefined {
309
- const row = this.rows.get(id);
310
- if (!row) return undefined;
311
- row.endedAt = at;
312
- row.result = snapshot(result);
313
- row.partialText = "";
314
- row.version++;
315
- if (row.group) row.group.endedAt = Math.max(row.group.endedAt ?? 0, at);
316
- return row;
317
- }
318
-
319
- update(id: string, partialResult: unknown, now = Date.now()): void {
320
- const row = this.rows.get(id);
321
- if (!row || row.endedAt !== undefined) return;
322
- const text = partialText(partialResult);
323
- if (text === undefined) return;
324
- row.partialText = text;
325
- row.version++;
326
- if (now - row.lastInvalidateAt < 100) return;
327
- row.lastInvalidateAt = now;
328
- this.touch(row);
329
- }
330
-
331
- /**
332
- * A call starts running. Under fold its elapsed time counts from here, not from when its
333
- * arguments started streaming, which matters once parallel commands sit side by side; the
334
- * preview block's one-second delay counts from here in both modes (fold-more.md §5.8).
335
- */
336
- startExecution(id: string, at = Date.now()): ToolRow | undefined {
337
- const row = this.rows.get(id);
338
- if (!row || row.endedAt !== undefined) return row;
339
- if (this.fold.enabled) row.startedAt = at;
340
- row.execStartedAt ??= at;
341
- return row;
342
- }
343
-
344
- refresh(id: string): void {
345
- const row = this.rows.get(id);
346
- if (row) this.touch(row);
347
- }
348
-
349
- /**
350
- * Redraw the host of the fold segment `id` belongs to, unless `id` is the host itself. Never
351
- * invalidates `id`'s own row, so it is safe to call from that row's renderer.
352
- */
353
- refreshHost(id: string): void {
354
- const segment = this.fold.enabled ? this.anchorOf.get(id) : undefined;
355
- if (segment && segment.host !== id) this.touchSegment(segment);
356
- }
357
-
358
- attach(id: string, invalidate: () => void): ToolRow | undefined {
359
- const row = this.rows.get(id);
360
- if (!row) return undefined;
361
- row.invalidate = invalidate;
362
- return row;
363
- }
364
-
365
- row(id: string): ToolRow | undefined {
366
- return this.rows.get(id);
367
- }
368
-
369
- group(id: string): ToolGroup | undefined {
370
- return this.groups.get(id);
371
- }
372
-
373
- groupsList(): ToolGroup[] {
374
- return [...this.groups.values()];
375
- }
376
-
377
- onMessage(message: unknown): void {
378
- const value = asMessage(message);
379
- if (!value) return;
380
- if (value.role === "user") {
381
- this.closeCurrent();
382
- this.closeSegment();
383
- return;
384
- }
385
- if (value.role === "toolResult") return;
386
- if (value.role !== "assistant") {
387
- // Custom and user-shell messages sit between segments like a user message does.
388
- this.closeSegment();
389
- return;
390
- }
391
- if (hasVisibleText(value) || value.stopReason === "error" || value.stopReason === "aborted") {
392
- this.closeCurrent();
393
- }
394
- }
395
-
396
- closeCurrent(settled = true): void {
397
- if (!this.current) return;
398
- const group = this.current;
399
- group.closed = true;
400
- if (settled) group.endedAt ??= Date.now();
401
- this.current = undefined;
402
- this.touchGroup(group);
403
- }
404
-
405
- toggleGroup(group: ToolGroup): void {
406
- group.expanded = !group.expanded;
407
- this.touchGroup(group);
408
- }
409
-
410
- toggleRow(row: ToolRow): void {
411
- row.expanded = !row.expanded;
412
- row.invalidate?.();
413
- }
414
-
415
- private touch(row: ToolRow): void {
416
- const segment = this.fold.enabled ? this.anchorOf.get(row.id) : undefined;
417
- if (segment) {
418
- this.touchSegment(segment);
419
- if (segment.host !== row.id) row.invalidate?.();
420
- return;
421
- }
422
- if (row.group) {
423
- this.touchGroup(row.group);
424
- return;
425
- }
426
- row.invalidate?.();
427
- }
428
-
429
- private touchGroup(group: ToolGroup): void {
430
- const owner = group.members[0];
431
- owner?.invalidate?.();
432
- }
433
-
434
- private touchSegment(segment: Segment): void {
435
- const host = this.rows.get(segment.host);
436
- if (host?.invalidate) host.invalidate();
437
- else this.onFoldChange?.();
438
- }
439
-
440
- /**
441
- * Rebuild groups from persisted entries. A rendered transcript is not
442
- * guaranteed to emit live tool events, so resume must be deterministic.
443
- */
444
- seed(entries: readonly unknown[], merge = true, manage: (name: string) => boolean = isManagedTool): void {
445
- this.reset();
446
- this.seeding = true;
447
- try {
448
- this.seedEntries(entries, merge, manage);
449
- } finally {
450
- this.seeding = false;
451
- }
452
- }
453
-
454
- private seedEntries(entries: readonly unknown[], merge: boolean, manage: (name: string) => boolean): void {
455
- for (const entry of entries) {
456
- if (!entry || typeof entry !== "object") continue;
457
- const record = entry as { type?: unknown; message?: unknown };
458
- if (record.type !== "message") {
459
- this.closeCurrent();
460
- if (typeof record.type === "string" && SEGMENT_CLOSING_ENTRIES.has(record.type)) this.closeSegment();
461
- continue;
462
- }
463
- const message = asMessage(record.message);
464
- if (!message) continue;
465
- const timestamp = typeof message.timestamp === "number" ? message.timestamp : Date.now();
466
-
467
- if (message.role === "user") {
468
- this.closeCurrent();
469
- this.closeSegment();
470
- continue;
471
- }
472
-
473
- if (message.role === "assistant") {
474
- if (hasVisibleText(message)) this.closeCurrent();
475
- if (!Array.isArray(message.content)) continue;
476
- for (const item of message.content) {
477
- if (!item || typeof item !== "object") continue;
478
- const block = item as { type?: unknown; id?: unknown; name?: unknown; arguments?: unknown };
479
- if (block.type !== "toolCall" || typeof block.id !== "string" || typeof block.name !== "string") {
480
- continue;
481
- }
482
- if (!manage(block.name)) {
483
- this.closeCurrent();
484
- continue;
485
- }
486
- this.begin(block.id, block.name, block.arguments, timestamp, merge);
487
- }
488
- // The same entry point as streaming, so a resumed session folds the same way.
489
- this.ingestAssistant(message, false, timestamp);
490
- continue;
491
- }
492
-
493
- if (message.role === "toolResult" && typeof message.toolCallId === "string") {
494
- this.end(message.toolCallId, message, timestamp);
495
- } else if (message.role !== "toolResult") {
496
- this.closeSegment();
497
- }
498
- }
499
- this.closeCurrent();
500
- // A seed only runs while no run is going on (session start, tree navigation, a config
501
- // change after the run settled), so every run in the history has ended by now: collapse
502
- // all of it, as agent_settled did live. A run cut off by a crash collapses too.
503
- this.settle();
504
- }
505
-
506
- // -----------------------------------------------------------------------
507
- // Fold segments
508
- // -----------------------------------------------------------------------
509
-
510
- /**
511
- * Place the blocks of an assistant message into segments (fold-more.md §5.1). Called with
512
- * every streaming snapshot and once more at the end; idempotent: blocks seen before only
513
- * refresh (thinking text, streaming state), new blocks are appended in content order.
514
- *
515
- * The one change to an earlier decision: a shell command or read joins while its arguments
516
- * stream; once they are complete and show a change or a skill load, it leaves its segment
517
- * again and closes it. It is always the newest item then, so no other item moves.
518
- */
519
- ingestAssistant(message: unknown, streaming: boolean, at = Date.now()): void {
520
- if (!this.fold.enabled) return;
521
- const value = asMessage(message);
522
- if (!value || value.role !== "assistant" || typeof value.timestamp !== "number") return;
523
- const ts = value.timestamp;
524
- const known = this.ingested.has(ts);
525
- // Outside a seed, a message older than the newest one seen only refreshes what is already
526
- // placed: history belongs to the seed, and appending would put old blocks after newer ones.
527
- // The seed walks entries in session order, whatever their timestamps say.
528
- if (!known && ts < this.latestMessage && !this.seeding) return;
529
- if (!known) {
530
- this.ingested.add(ts);
531
- this.latestMessage = Math.max(this.latestMessage, ts);
532
- }
533
- const grow = this.seeding || ts >= this.latestMessage;
534
- const content: unknown[] = Array.isArray(value.content) ? value.content : [];
535
- const last = content.length - 1;
536
- const runs = new Map(thinkingRuns(content).map((run) => [run.firstBlock, run]));
537
- const durationMs = typeof value.durationMs === "number" ? value.durationMs : undefined;
538
- // Thinking runs time themselves only while they stream in front of us.
539
- const measure = streaming && !this.seeding;
540
-
541
- for (let index = 0; index < content.length; index++) {
542
- const block = content[index];
543
- if (!block || typeof block !== "object") continue;
544
- const type = (block as { type?: unknown }).type;
545
- if (type === "thinking") {
546
- const run = runs.get(index);
547
- if (!run) continue;
548
- index = run.lastBlock;
549
- const anchor = thinkingAnchor(ts, run.runIndex);
550
- if (classifyBlock({ type: "thinking", thinking: run.text }, this.fold) !== "fold") {
551
- this.placeBoundary(anchor, grow);
552
- continue;
553
- }
554
- const segment = this.placeItem(anchor, grow, () => ({
555
- kind: "thinking",
556
- anchor,
557
- msgTs: ts,
558
- run: run.runIndex,
559
- text: run.text,
560
- streaming: false,
561
- // The first run of a message counts from the message's start, like its durationMs.
562
- startedAt: measure ? (run.firstBlock === 0 ? Math.min(ts, at) : at) : undefined,
563
- messageRuns: runs.size,
564
- }));
565
- const item = segment?.items.find((entry) => entry.anchor === anchor);
566
- if (segment && item?.kind === "thinking") {
567
- item.text = run.text;
568
- item.streaming = streaming && run.lastBlock === last;
569
- if (item.startedAt !== undefined && item.endedAt === undefined && !item.streaming) {
570
- item.endedAt = Math.max(item.startedAt, at);
571
- }
572
- item.messageRuns = runs.size;
573
- item.messageDurationMs = durationMs;
574
- segment.thinkingMsgs.set(ts, { durationMs, streaming });
575
- }
576
- continue;
577
- }
578
- if (type === "toolCall") {
579
- const call = block as { id?: unknown; name?: unknown; arguments?: unknown };
580
- const id = call.id;
581
- if (typeof id !== "string") continue;
582
- const name = typeof call.name === "string" ? call.name : "";
583
- if (name && this.fold.manage(name)) {
584
- const row = this.begin(id, name, call.arguments, at, false);
585
- row.args = argsOf(call.arguments);
586
- }
587
- const kind = classifyBlock(block, this.fold, !streaming || index < last);
588
- if (kind === "fold") this.placeItem(id, grow, () => ({ kind: "tool", anchor: id, name }));
589
- else this.placeBoundary(id, grow);
590
- continue;
591
- }
592
- if (classifyBlock(block, this.fold) === "text") this.placeBoundary(`msg:${ts}!${index}`, grow);
593
- }
594
-
595
- if (!streaming && (value.stopReason === "error" || value.stopReason === "aborted")) {
596
- this.placeBoundary(`msg:${ts}!stop`, grow);
597
- }
598
- }
599
-
600
- private placeItem(anchor: string, grow: boolean, create: () => SegItem): Segment | undefined {
601
- const seen = this.seenUnits.get(anchor);
602
- if (seen === "item") return this.anchorOf.get(anchor);
603
- if (seen === "boundary" || !grow) return undefined;
604
- let segment = this.currentSegment;
605
- if (!segment) {
606
- segment = {
607
- id: `seg:${anchor}`,
608
- items: [],
609
- host: anchor,
610
- closed: false,
611
- collapsed: false,
612
- expanded: false,
613
- expandedItems: new Set(),
614
- thinkingMsgs: new Map(),
615
- };
616
- this.segments.set(segment.id, segment);
617
- this.currentSegment = segment;
618
- }
619
- segment.items.push(create());
620
- this.anchorOf.set(anchor, segment);
621
- this.seenUnits.set(anchor, "item");
622
- this.touchSegment(segment);
623
- return segment;
624
- }
625
-
626
- private placeBoundary(key: string, grow: boolean): void {
627
- const seen = this.seenUnits.get(key);
628
- if (seen === "boundary") return;
629
- if (seen === "item") {
630
- this.detach(key);
631
- return;
632
- }
633
- if (!grow) return;
634
- this.seenUnits.set(key, "boundary");
635
- this.closeSegment();
636
- }
637
-
638
- /** Take a provisional item back out of its segment and close the segment (§5.2). */
639
- private detach(anchor: string): void {
640
- this.seenUnits.set(anchor, "boundary");
641
- const segment = this.anchorOf.get(anchor);
642
- this.anchorOf.delete(anchor);
643
- if (!segment) return;
644
- segment.items = segment.items.filter((item) => item.anchor !== anchor);
645
- segment.expandedItems.delete(anchor);
646
- if (segment.items.length === 0) {
647
- this.segments.delete(segment.id);
648
- if (this.currentSegment === segment) this.currentSegment = undefined;
649
- } else if (this.currentSegment === segment) {
650
- this.closeSegment();
651
- } else {
652
- this.touchSegment(segment);
653
- }
654
- this.rows.get(anchor)?.invalidate?.();
655
- }
656
-
657
- /**
658
- * End the open segment: text, a change, a user message, compaction, or the run settling.
659
- * A closed segment keeps drawing as a list; only `settle` collapses it.
660
- */
661
- closeSegment(): void {
662
- const segment = this.currentSegment;
663
- if (!segment) return;
664
- segment.closed = true;
665
- this.currentSegment = undefined;
666
- this.touchSegment(segment);
667
- }
668
-
669
- /**
670
- * The run settled (agent_settled live, the end of a seed): close the open segment and
671
- * collapse every segment still drawn as a list into its summary line (fold-more.md §4.10).
672
- * Segments the user opened during the run collapse too, and their item details close.
673
- */
674
- settle(): void {
675
- this.closeSegment();
676
- for (const segment of this.segments.values()) {
677
- if (segment.collapsed) continue;
678
- segment.collapsed = true;
679
- segment.expanded = false;
680
- segment.expandedItems.clear();
681
- this.touchSegment(segment);
682
- }
683
- }
684
-
685
- segment(anchor: string): Segment | undefined {
686
- return this.anchorOf.get(anchor);
687
- }
688
-
689
- segmentsList(): Segment[] {
690
- return [...this.segments.values()];
691
- }
692
-
693
- /**
694
- * What the slot of `anchor` draws (fold-more.md §5.6): itself when its segment is below the
695
- * threshold, everything when it is the host, nothing otherwise. Derived on every render.
696
- */
697
- foldRole(anchor: string): FoldRole {
698
- const segment = this.fold.enabled ? this.anchorOf.get(anchor) : undefined;
699
- if (!segment || segment.items.length < this.fold.minItems) return { kind: "single", segment };
700
- return segment.host === anchor ? { kind: "host", segment } : { kind: "hidden", segment };
701
- }
702
-
703
- toggleSegment(segment: Segment): void {
704
- segment.expanded = !segment.expanded;
705
- this.touchSegment(segment);
706
- }
707
-
708
- toggleSegmentItem(segment: Segment, anchor: string): void {
709
- if (segment.expandedItems.has(anchor)) segment.expandedItems.delete(anchor);
710
- else segment.expandedItems.add(anchor);
711
- this.touchSegment(segment);
712
- }
713
-
714
- /** Counts and tenses for the summary line (fold-more.md §5.4). */
715
- segmentStats(segment: Segment, now = Date.now()): FoldStats {
716
- let thinkingCount = 0;
717
- let thinkingActive = false;
718
- let commands = 0;
719
- let commandsActive = false;
720
- const readTargets = new Set<string>();
721
- let readCalls = 0;
722
- let searches = 0;
723
- let lists = 0;
724
- let exploreActive = false;
725
- let tools = 0;
726
- let failed = 0;
727
- let interrupted = 0;
728
- for (const item of segment.items) {
729
- if (item.kind === "thinking") {
730
- thinkingCount++;
731
- if (item.streaming) thinkingActive = true;
732
- continue;
733
- }
734
- tools++;
735
- const row = this.rows.get(item.anchor);
736
- const name = row?.name ?? item.name;
737
- const active = !row || row.endedAt === undefined;
738
- if (isFailed(row?.result)) failed++;
739
- else if (isInterrupted(row?.result)) interrupted++;
740
- if (isShellTool(name)) {
741
- commands++;
742
- if (active) commandsActive = true;
743
- continue;
744
- }
745
- if (active) exploreActive = true;
746
- if (name === "read") {
747
- readCalls++;
748
- readTargets.add(targetKey(name, row?.args ?? {}, item.anchor));
749
- } else if (name === "grep" || name === "find") {
750
- searches++;
751
- } else if (name === "ls") {
752
- lists++;
753
- }
754
- }
755
- let ms: number | undefined;
756
- for (const [ts, entry] of segment.thinkingMsgs) {
757
- const value = entry.durationMs ?? (entry.streaming ? Math.max(0, now - ts) : undefined);
758
- if (value !== undefined) ms = (ms ?? 0) + value;
759
- }
760
- return {
761
- thinking: { count: thinkingCount, ms, active: thinkingActive },
762
- commands: { count: commands, active: commandsActive },
763
- reads: readTargets.size || readCalls,
764
- searches,
765
- lists,
766
- exploreActive,
767
- tools,
768
- failed,
769
- interrupted,
770
- };
771
- }
772
-
773
- /** Partition of anchors into segments, for tests and debugging. */
774
- foldSnapshot(): Array<{ host: string; items: string[]; closed: boolean; collapsed: boolean }> {
775
- return this.segmentsList().map((segment) => ({
776
- host: segment.host,
777
- items: segment.items.map((item) => item.anchor),
778
- closed: segment.closed,
779
- collapsed: segment.collapsed,
780
- }));
781
- }
782
- }
783
-
784
- export interface GroupCounts {
785
- calls: number;
786
- reads: number;
787
- searches: number;
788
- lists: number;
789
- }
790
-
791
- export function groupCounts(group: ToolGroup): GroupCounts {
792
- const readTargets = new Set<string>();
793
- let readCalls = 0;
794
- let searches = 0;
795
- let lists = 0;
796
- for (const member of group.members) {
797
- if (member.name === "read") {
798
- readCalls++;
799
- readTargets.add(targetKey(member.name, member.args, member.id));
800
- } else if (member.name === "grep" || member.name === "find") {
801
- searches++;
802
- } else if (member.name === "ls") {
803
- lists++;
804
- }
805
- }
806
- return {
807
- calls: group.members.length,
808
- reads: readTargets.size || readCalls,
809
- searches,
810
- lists,
811
- };
812
- }
813
-
814
- export function groupActive(group: ToolGroup): boolean {
815
- return group.members.some((member) => member.endedAt === undefined);
816
- }
817
-
818
- /** Members that failed; an interrupted call is not a failure (DESIGN.md §9). */
819
- export function groupFailed(group: ToolGroup): number {
820
- return group.members.filter((member) => isFailed(member.result)).length;
821
- }
822
-
823
- /** Members cut short by an interrupt. */
824
- export function groupInterrupted(group: ToolGroup): number {
825
- return group.members.filter((member) => isInterrupted(member.result)).length;
826
- }
827
-
828
- export function groupEndedAt(group: ToolGroup): number {
829
- return group.endedAt ?? Math.max(...group.members.map((member) => member.endedAt ?? member.startedAt));
830
- }
831
-
832
- export function groupKind(group: ToolGroup): "reads" | "searches" | "lists" | "mixed" {
833
- const counts = groupCounts(group);
834
- const kinds = Number(counts.reads > 0) + Number(counts.searches > 0) + Number(counts.lists > 0);
835
- if (kinds > 1) return "mixed";
836
- if (counts.searches > 0) return "searches";
837
- if (counts.lists > 0) return "lists";
838
- return "reads";
839
- }
840
-
841
- export function groupAction(group: ToolGroup): string {
842
- const active = groupActive(group);
843
- switch (groupKind(group)) {
844
- case "mixed":
845
- return active ? "Exploring" : "Explored";
846
- case "searches":
847
- return active ? "Searching" : "Searched";
848
- case "lists":
849
- return active ? "Listing" : "Listed";
850
- default:
851
- return active ? "Reading" : "Read";
852
- }
853
- }
854
-
855
- export function groupSummary(group: ToolGroup): string {
856
- const counts = groupCounts(group);
857
- const parts: string[] = [];
858
- if (counts.reads > 0) parts.push(`${counts.reads} file${counts.reads === 1 ? "" : "s"}`);
859
- if (counts.searches > 0) parts.push(`${counts.searches} search${counts.searches === 1 ? "" : "es"}`);
860
- if (counts.lists > 0) parts.push(`${counts.lists} dir${counts.lists === 1 ? "" : "s"}`);
861
- return parts.join(", ");
862
- }
863
-
864
- export function groupDuration(group: ToolGroup, now = Date.now()): number {
865
- const end = groupActive(group) ? now : groupEndedAt(group);
866
- return Math.max(0, end - group.startedAt);
867
- }
868
-
869
- function partialText(value: unknown): string | undefined {
870
- if (!value || typeof value !== "object") return undefined;
871
- const content = (value as { content?: unknown }).content;
872
- if (!Array.isArray(content)) return undefined;
873
- const text = content
874
- .flatMap((block) => {
875
- if (!block || typeof block !== "object") return [];
876
- const item = block as { type?: unknown; text?: unknown };
877
- return item.type === "text" && typeof item.text === "string" ? [item.text] : [];
878
- })
879
- .join("\n");
880
- return str(text);
881
- }
1
+ import { isFailed, isInterrupted, isManagedTool, isMergeableTool, isShellTool, skillReadName, targetKey } from "./tool-summary.js";
2
+ import type { ToolContentBlock, ToolResultSnapshot } from "./types.js";
3
+ import { argsOf, str } from "./format.js";
4
+ import { classifyBlock, FOLD_OFF, type FoldPolicy, type FoldStats, thinkingAnchor, thinkingRuns } from "./segment.js";
5
+
6
+ export interface ToolRow {
7
+ id: string;
8
+ name: string;
9
+ args: Record<string, unknown>;
10
+ group?: ToolGroup;
11
+ standalone: boolean;
12
+ expanded: boolean;
13
+ startedAt: number;
14
+ /** When the call started running, as opposed to when its arguments started streaming. */
15
+ execStartedAt?: number;
16
+ endedAt?: number;
17
+ result?: ToolResultSnapshot;
18
+ partialText: string;
19
+ invalidate?: () => void;
20
+ lastInvalidateAt: number;
21
+ version: number;
22
+ }
23
+
24
+ export interface ToolGroup {
25
+ id: string;
26
+ members: ToolRow[];
27
+ expanded: boolean;
28
+ closed: boolean;
29
+ startedAt: number;
30
+ endedAt?: number;
31
+ }
32
+
33
+ /** A thinking run inside a segment; its text is refreshed on every update of its message. */
34
+ export interface SegThinkingItem {
35
+ kind: "thinking";
36
+ anchor: string;
37
+ msgTs: number;
38
+ run: number;
39
+ text: string;
40
+ streaming: boolean;
41
+ /**
42
+ * Measured live only (fold-more.md §5.5): when the run was first seen (its message's timestamp
43
+ * when the run opens the message), and when it stopped growing — the next block of its message
44
+ * appeared, or the message ended. A seed has no clock to read and leaves both unset.
45
+ */
46
+ startedAt?: number;
47
+ endedAt?: number;
48
+ /** Runs with text in the message so far, and the message's `durationMs`; the fallback when nothing was measured. */
49
+ messageRuns: number;
50
+ messageDurationMs?: number;
51
+ }
52
+
53
+ /**
54
+ * How long a finished thinking run took, for its line in the list: what was measured live, else
55
+ * its message's `durationMs` when the message holds only this run. A message with several runs
56
+ * cannot split its duration among them, so those get none (`Thought`).
57
+ */
58
+ export function thoughtDuration(item: SegThinkingItem): number | undefined {
59
+ if (item.startedAt !== undefined && item.endedAt !== undefined) return Math.max(0, item.endedAt - item.startedAt);
60
+ return item.messageRuns === 1 ? item.messageDurationMs : undefined;
61
+ }
62
+
63
+ export interface SegToolItem {
64
+ kind: "tool";
65
+ /** The tool call id. */
66
+ anchor: string;
67
+ name: string;
68
+ }
69
+
70
+ export type SegItem = SegThinkingItem | SegToolItem;
71
+
72
+ /**
73
+ * A run of thinking and non-changing tool calls between two boundaries (fold-more.md §5.1).
74
+ * Items keep the model's real output order across assistant messages.
75
+ */
76
+ export interface Segment {
77
+ id: string;
78
+ items: SegItem[];
79
+ /** The first anchor; it draws the whole segment and never changes. */
80
+ host: string;
81
+ /** No more items join: a boundary came. The segment still draws as a list until it collapses. */
82
+ closed: boolean;
83
+ /**
84
+ * Drawn as one summary line instead of the list: set for every segment of a run once the run
85
+ * settles, never in the middle of one (fold-more.md §4.10).
86
+ */
87
+ collapsed: boolean;
88
+ /** A collapsed segment opened again into its list. */
89
+ expanded: boolean;
90
+ /** Items whose details are open in the list. */
91
+ expandedItems: Set<string>;
92
+ /** Messages that put thinking into this segment: timestamp → duration, counted once each. */
93
+ thinkingMsgs: Map<number, { durationMs?: number; streaming: boolean }>;
94
+ }
95
+
96
+ export type FoldRole =
97
+ | { kind: "single"; segment?: Segment }
98
+ | { kind: "host"; segment: Segment }
99
+ | { kind: "hidden"; segment: Segment };
100
+
101
+ /** Session entry types that end a segment besides messages; extension state entries do not. */
102
+ const SEGMENT_CLOSING_ENTRIES = new Set(["compaction", "branch_summary", "custom_message"]);
103
+
104
+ interface MessageLike {
105
+ role?: string;
106
+ content?: unknown;
107
+ stopReason?: string;
108
+ timestamp?: number;
109
+ toolCallId?: string;
110
+ toolName?: string;
111
+ isError?: boolean;
112
+ details?: unknown;
113
+ durationMs?: number;
114
+ }
115
+
116
+ function asMessage(value: unknown): MessageLike | undefined {
117
+ return typeof value === "object" && value !== null ? (value as MessageLike) : undefined;
118
+ }
119
+
120
+ export function hasVisibleText(message: MessageLike | undefined): boolean {
121
+ if (!message) return false;
122
+ if (typeof message.content === "string") return message.content.trim().length > 0;
123
+ if (!Array.isArray(message.content)) return false;
124
+ return message.content.some((item) => {
125
+ if (!item || typeof item !== "object") return false;
126
+ const block = item as { type?: unknown; text?: unknown };
127
+ return block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0;
128
+ });
129
+ }
130
+
131
+ function snapshot(value: unknown): ToolResultSnapshot | undefined {
132
+ if (!value || typeof value !== "object") return undefined;
133
+ const message = value as {
134
+ content?: unknown;
135
+ details?: unknown;
136
+ isError?: unknown;
137
+ durationMs?: unknown;
138
+ };
139
+ const content: ToolContentBlock[] = [];
140
+ if (Array.isArray(message.content)) {
141
+ for (const block of message.content) {
142
+ if (!block || typeof block !== "object") continue;
143
+ const item = block as { type?: unknown; text?: unknown; data?: unknown; mimeType?: unknown };
144
+ if (item.type === "text" && typeof item.text === "string") {
145
+ content.push({ type: "text", text: item.text });
146
+ } else if (item.type === "image" && typeof item.data === "string" && typeof item.mimeType === "string") {
147
+ content.push({ type: "image", data: item.data, mimeType: item.mimeType });
148
+ }
149
+ }
150
+ }
151
+ return {
152
+ content,
153
+ details: message.details,
154
+ isError: message.isError === true,
155
+ durationMs: typeof message.durationMs === "number" ? message.durationMs : undefined,
156
+ };
157
+ }
158
+
159
+ /**
160
+ * Timeline of compact transcript rows. It owns grouping and boundaries only;
161
+ * rendering lives in tool-row.ts. This keeps resume and live rendering
162
+ * deterministic from the same model.
163
+ */
164
+ export class ActivityTimeline {
165
+ private rows = new Map<string, ToolRow>();
166
+ private groups = new Map<string, ToolGroup>();
167
+ private current?: ToolGroup;
168
+ private sequence = 0;
169
+ epoch = 0;
170
+
171
+ // Fold (fold-more.md §5.9). Off by default, so read-only groups work as before.
172
+ private fold: FoldPolicy = FOLD_OFF;
173
+ private segments = new Map<string, Segment>();
174
+ private anchorOf = new Map<string, Segment>();
175
+ private currentSegment?: Segment;
176
+ /** Units already placed: an item, or a boundary that has already closed its segment. */
177
+ private seenUnits = new Map<string, "item" | "boundary">();
178
+ private ingested = new Set<number>();
179
+ private latestMessage = Number.NEGATIVE_INFINITY;
180
+ private seeding = false;
181
+ /** pi's Ctrl+O state, recorded by tool rows so thinking hosts can follow it too. */
182
+ globalExpanded = false;
183
+ /** pi's Ctrl+T state ("show thinking details"), recorded by the thinking patch. */
184
+ thinkingDetails = false;
185
+ /** Called when a segment hosted by a thinking run changes; there is no tool row to invalidate. */
186
+ onFoldChange?: () => void;
187
+
188
+ reset(): void {
189
+ this.rows.clear();
190
+ this.groups.clear();
191
+ this.current = undefined;
192
+ this.sequence = 0;
193
+ this.segments.clear();
194
+ this.anchorOf.clear();
195
+ this.currentSegment = undefined;
196
+ this.seenUnits.clear();
197
+ this.ingested.clear();
198
+ this.latestMessage = Number.NEGATIVE_INFINITY;
199
+ this.epoch++;
200
+ }
201
+
202
+ /** Takes effect for what is ingested next; callers reseed after changing it. */
203
+ setFoldPolicy(policy: FoldPolicy): void {
204
+ this.fold = policy;
205
+ }
206
+
207
+ get foldEnabled(): boolean {
208
+ return this.fold.enabled;
209
+ }
210
+
211
+ get foldPolicy(): FoldPolicy {
212
+ return this.fold;
213
+ }
214
+
215
+ /** Invalidate callbacks of every row, so a reseed can make pi rebuild their components. */
216
+ rowInvalidators(): Array<() => void> {
217
+ return [...this.rows.values()].flatMap((row) => (row.invalidate ? [row.invalidate] : []));
218
+ }
219
+
220
+ bumpEpoch(): void {
221
+ this.epoch++;
222
+ }
223
+
224
+ begin(id: string, name: string, args: unknown, at = Date.now(), merge = true): ToolRow {
225
+ const existing = this.rows.get(id);
226
+ if (existing) return existing;
227
+
228
+ const row: ToolRow = {
229
+ id,
230
+ name,
231
+ args: argsOf(args),
232
+ standalone: true,
233
+ expanded: false,
234
+ startedAt: at,
235
+ partialText: "",
236
+ lastInvalidateAt: 0,
237
+ version: 0,
238
+ };
239
+ this.rows.set(id, row);
240
+
241
+ // Fold replaces read-only groups; ingestAssistant builds segments instead.
242
+ if (this.fold.enabled) return row;
243
+ if (!merge || !isMergeableTool(name) || !isManagedTool(name) || skillReadName(name, row.args)) {
244
+ this.closeCurrent();
245
+ return row;
246
+ }
247
+
248
+ if (!this.current || this.current.closed) {
249
+ const group: ToolGroup = {
250
+ id: `g:${id}`,
251
+ members: [row],
252
+ expanded: false,
253
+ closed: false,
254
+ startedAt: at,
255
+ };
256
+ this.current = group;
257
+ this.groups.set(group.id, group);
258
+ row.group = group;
259
+ row.standalone = false;
260
+ } else {
261
+ const group = this.current;
262
+ group.members.push(row);
263
+ group.endedAt = undefined;
264
+ row.group = group;
265
+ row.standalone = false;
266
+ }
267
+ return row;
268
+ }
269
+
270
+ /**
271
+ * A call's arguments stream in after its row exists, so a read can join a group
272
+ * before its path shows it loads a skill. Move such a row out to stand alone, and
273
+ * close the group so later reads do not merge into a row drawn above it.
274
+ */
275
+ detachSkillRead(id: string): boolean {
276
+ const row = this.rows.get(id);
277
+ const group = row?.group;
278
+ if (!row || !group || !skillReadName(row.name, row.args)) return false;
279
+ const index = group.members.indexOf(row);
280
+ if (index >= 0) group.members.splice(index, 1);
281
+ row.group = undefined;
282
+ row.standalone = true;
283
+ if (group.members.length === 0) {
284
+ this.groups.delete(group.id);
285
+ if (this.current === group) this.current = undefined;
286
+ } else {
287
+ if (this.current === group) this.closeCurrent(false);
288
+ this.touchGroup(group);
289
+ }
290
+ row.invalidate?.();
291
+ return true;
292
+ }
293
+
294
+ end(id: string, result: unknown, at = Date.now()): ToolRow | undefined {
295
+ const row = this.rows.get(id);
296
+ if (!row) return undefined;
297
+ row.endedAt = at;
298
+ row.result = snapshot(result);
299
+ row.partialText = "";
300
+ row.version++;
301
+ if (row.group) {
302
+ row.group.endedAt = Math.max(row.group.endedAt ?? 0, at);
303
+ }
304
+ this.touch(row);
305
+ return row;
306
+ }
307
+
308
+ setResult(id: string, result: unknown, at = Date.now()): ToolRow | undefined {
309
+ const row = this.rows.get(id);
310
+ if (!row) return undefined;
311
+ row.endedAt = at;
312
+ row.result = snapshot(result);
313
+ row.partialText = "";
314
+ row.version++;
315
+ if (row.group) row.group.endedAt = Math.max(row.group.endedAt ?? 0, at);
316
+ return row;
317
+ }
318
+
319
+ update(id: string, partialResult: unknown, now = Date.now()): void {
320
+ const row = this.rows.get(id);
321
+ if (!row || row.endedAt !== undefined) return;
322
+ const text = partialText(partialResult);
323
+ if (text === undefined) return;
324
+ row.partialText = text;
325
+ row.version++;
326
+ if (now - row.lastInvalidateAt < 100) return;
327
+ row.lastInvalidateAt = now;
328
+ this.touch(row);
329
+ }
330
+
331
+ /**
332
+ * A call starts running. Under fold its elapsed time counts from here, not from when its
333
+ * arguments started streaming, which matters once parallel commands sit side by side; the
334
+ * preview block's one-second delay counts from here in both modes (fold-more.md §5.8).
335
+ */
336
+ startExecution(id: string, at = Date.now()): ToolRow | undefined {
337
+ const row = this.rows.get(id);
338
+ if (!row || row.endedAt !== undefined) return row;
339
+ if (this.fold.enabled) row.startedAt = at;
340
+ row.execStartedAt ??= at;
341
+ return row;
342
+ }
343
+
344
+ refresh(id: string): void {
345
+ const row = this.rows.get(id);
346
+ if (row) this.touch(row);
347
+ }
348
+
349
+ /**
350
+ * Redraw the host of the fold segment `id` belongs to, unless `id` is the host itself. Never
351
+ * invalidates `id`'s own row, so it is safe to call from that row's renderer.
352
+ */
353
+ refreshHost(id: string): void {
354
+ const segment = this.fold.enabled ? this.anchorOf.get(id) : undefined;
355
+ if (segment && segment.host !== id) this.touchSegment(segment);
356
+ }
357
+
358
+ attach(id: string, invalidate: () => void): ToolRow | undefined {
359
+ const row = this.rows.get(id);
360
+ if (!row) return undefined;
361
+ row.invalidate = invalidate;
362
+ return row;
363
+ }
364
+
365
+ row(id: string): ToolRow | undefined {
366
+ return this.rows.get(id);
367
+ }
368
+
369
+ group(id: string): ToolGroup | undefined {
370
+ return this.groups.get(id);
371
+ }
372
+
373
+ groupsList(): ToolGroup[] {
374
+ return [...this.groups.values()];
375
+ }
376
+
377
+ onMessage(message: unknown): void {
378
+ const value = asMessage(message);
379
+ if (!value) return;
380
+ if (value.role === "user") {
381
+ this.closeCurrent();
382
+ this.closeSegment();
383
+ return;
384
+ }
385
+ if (value.role === "toolResult") return;
386
+ if (value.role !== "assistant") {
387
+ // Custom and user-shell messages sit between segments like a user message does.
388
+ this.closeSegment();
389
+ return;
390
+ }
391
+ if (hasVisibleText(value) || value.stopReason === "error" || value.stopReason === "aborted") {
392
+ this.closeCurrent();
393
+ }
394
+ }
395
+
396
+ closeCurrent(settled = true): void {
397
+ if (!this.current) return;
398
+ const group = this.current;
399
+ group.closed = true;
400
+ if (settled) group.endedAt ??= Date.now();
401
+ this.current = undefined;
402
+ this.touchGroup(group);
403
+ }
404
+
405
+ toggleGroup(group: ToolGroup): void {
406
+ group.expanded = !group.expanded;
407
+ this.touchGroup(group);
408
+ }
409
+
410
+ toggleRow(row: ToolRow): void {
411
+ row.expanded = !row.expanded;
412
+ row.invalidate?.();
413
+ }
414
+
415
+ private touch(row: ToolRow): void {
416
+ const segment = this.fold.enabled ? this.anchorOf.get(row.id) : undefined;
417
+ if (segment) {
418
+ this.touchSegment(segment);
419
+ if (segment.host !== row.id) row.invalidate?.();
420
+ return;
421
+ }
422
+ if (row.group) {
423
+ this.touchGroup(row.group);
424
+ return;
425
+ }
426
+ row.invalidate?.();
427
+ }
428
+
429
+ private touchGroup(group: ToolGroup): void {
430
+ const owner = group.members[0];
431
+ owner?.invalidate?.();
432
+ }
433
+
434
+ private touchSegment(segment: Segment): void {
435
+ const host = this.rows.get(segment.host);
436
+ if (host?.invalidate) host.invalidate();
437
+ else this.onFoldChange?.();
438
+ }
439
+
440
+ /**
441
+ * Rebuild groups from persisted entries. A rendered transcript is not
442
+ * guaranteed to emit live tool events, so resume must be deterministic.
443
+ */
444
+ seed(entries: readonly unknown[], merge = true, manage: (name: string) => boolean = isManagedTool): void {
445
+ this.reset();
446
+ this.seeding = true;
447
+ try {
448
+ this.seedEntries(entries, merge, manage);
449
+ } finally {
450
+ this.seeding = false;
451
+ }
452
+ }
453
+
454
+ private seedEntries(entries: readonly unknown[], merge: boolean, manage: (name: string) => boolean): void {
455
+ for (const entry of entries) {
456
+ if (!entry || typeof entry !== "object") continue;
457
+ const record = entry as { type?: unknown; message?: unknown };
458
+ if (record.type !== "message") {
459
+ this.closeCurrent();
460
+ if (typeof record.type === "string" && SEGMENT_CLOSING_ENTRIES.has(record.type)) this.closeSegment();
461
+ continue;
462
+ }
463
+ const message = asMessage(record.message);
464
+ if (!message) continue;
465
+ const timestamp = typeof message.timestamp === "number" ? message.timestamp : Date.now();
466
+
467
+ if (message.role === "user") {
468
+ this.closeCurrent();
469
+ this.closeSegment();
470
+ continue;
471
+ }
472
+
473
+ if (message.role === "assistant") {
474
+ if (hasVisibleText(message)) this.closeCurrent();
475
+ if (!Array.isArray(message.content)) continue;
476
+ for (const item of message.content) {
477
+ if (!item || typeof item !== "object") continue;
478
+ const block = item as { type?: unknown; id?: unknown; name?: unknown; arguments?: unknown };
479
+ if (block.type !== "toolCall" || typeof block.id !== "string" || typeof block.name !== "string") {
480
+ continue;
481
+ }
482
+ if (!manage(block.name)) {
483
+ this.closeCurrent();
484
+ continue;
485
+ }
486
+ this.begin(block.id, block.name, block.arguments, timestamp, merge);
487
+ }
488
+ // The same entry point as streaming, so a resumed session folds the same way.
489
+ this.ingestAssistant(message, false, timestamp);
490
+ continue;
491
+ }
492
+
493
+ if (message.role === "toolResult" && typeof message.toolCallId === "string") {
494
+ this.end(message.toolCallId, message, timestamp);
495
+ } else if (message.role !== "toolResult") {
496
+ this.closeSegment();
497
+ }
498
+ }
499
+ this.closeCurrent();
500
+ // A seed only runs while no run is going on (session start, tree navigation, a config
501
+ // change after the run settled), so every run in the history has ended by now: collapse
502
+ // all of it, as agent_settled did live. A run cut off by a crash collapses too.
503
+ this.settle();
504
+ }
505
+
506
+ // -----------------------------------------------------------------------
507
+ // Fold segments
508
+ // -----------------------------------------------------------------------
509
+
510
+ /**
511
+ * Place the blocks of an assistant message into segments (fold-more.md §5.1). Called with
512
+ * every streaming snapshot and once more at the end; idempotent: blocks seen before only
513
+ * refresh (thinking text, streaming state), new blocks are appended in content order.
514
+ *
515
+ * The one change to an earlier decision: a shell command or read joins while its arguments
516
+ * stream; once they are complete and show a change or a skill load, it leaves its segment
517
+ * again and closes it. It is always the newest item then, so no other item moves.
518
+ */
519
+ ingestAssistant(message: unknown, streaming: boolean, at = Date.now()): void {
520
+ if (!this.fold.enabled) return;
521
+ const value = asMessage(message);
522
+ if (!value || value.role !== "assistant" || typeof value.timestamp !== "number") return;
523
+ const ts = value.timestamp;
524
+ const known = this.ingested.has(ts);
525
+ // Outside a seed, a message older than the newest one seen only refreshes what is already
526
+ // placed: history belongs to the seed, and appending would put old blocks after newer ones.
527
+ // The seed walks entries in session order, whatever their timestamps say.
528
+ if (!known && ts < this.latestMessage && !this.seeding) return;
529
+ if (!known) {
530
+ this.ingested.add(ts);
531
+ this.latestMessage = Math.max(this.latestMessage, ts);
532
+ }
533
+ const grow = this.seeding || ts >= this.latestMessage;
534
+ const content: unknown[] = Array.isArray(value.content) ? value.content : [];
535
+ const last = content.length - 1;
536
+ const runs = new Map(thinkingRuns(content).map((run) => [run.firstBlock, run]));
537
+ const durationMs = typeof value.durationMs === "number" ? value.durationMs : undefined;
538
+ // Thinking runs time themselves only while they stream in front of us.
539
+ const measure = streaming && !this.seeding;
540
+
541
+ for (let index = 0; index < content.length; index++) {
542
+ const block = content[index];
543
+ if (!block || typeof block !== "object") continue;
544
+ const type = (block as { type?: unknown }).type;
545
+ if (type === "thinking") {
546
+ const run = runs.get(index);
547
+ if (!run) continue;
548
+ index = run.lastBlock;
549
+ const anchor = thinkingAnchor(ts, run.runIndex);
550
+ if (classifyBlock({ type: "thinking", thinking: run.text }, this.fold) !== "fold") {
551
+ this.placeBoundary(anchor, grow);
552
+ continue;
553
+ }
554
+ const segment = this.placeItem(anchor, grow, () => ({
555
+ kind: "thinking",
556
+ anchor,
557
+ msgTs: ts,
558
+ run: run.runIndex,
559
+ text: run.text,
560
+ streaming: false,
561
+ // The first run of a message counts from the message's start, like its durationMs.
562
+ startedAt: measure ? (run.firstBlock === 0 ? Math.min(ts, at) : at) : undefined,
563
+ messageRuns: runs.size,
564
+ }));
565
+ const item = segment?.items.find((entry) => entry.anchor === anchor);
566
+ if (segment && item?.kind === "thinking") {
567
+ item.text = run.text;
568
+ item.streaming = streaming && run.lastBlock === last;
569
+ if (item.startedAt !== undefined && item.endedAt === undefined && !item.streaming) {
570
+ item.endedAt = Math.max(item.startedAt, at);
571
+ }
572
+ item.messageRuns = runs.size;
573
+ item.messageDurationMs = durationMs;
574
+ segment.thinkingMsgs.set(ts, { durationMs, streaming });
575
+ }
576
+ continue;
577
+ }
578
+ if (type === "toolCall") {
579
+ const call = block as { id?: unknown; name?: unknown; arguments?: unknown };
580
+ const id = call.id;
581
+ if (typeof id !== "string") continue;
582
+ const name = typeof call.name === "string" ? call.name : "";
583
+ if (name && this.fold.manage(name)) {
584
+ const row = this.begin(id, name, call.arguments, at, false);
585
+ row.args = argsOf(call.arguments);
586
+ }
587
+ const kind = classifyBlock(block, this.fold, !streaming || index < last);
588
+ if (kind === "fold") this.placeItem(id, grow, () => ({ kind: "tool", anchor: id, name }));
589
+ else this.placeBoundary(id, grow);
590
+ continue;
591
+ }
592
+ if (classifyBlock(block, this.fold) === "text") this.placeBoundary(`msg:${ts}!${index}`, grow);
593
+ }
594
+
595
+ if (!streaming && (value.stopReason === "error" || value.stopReason === "aborted")) {
596
+ this.placeBoundary(`msg:${ts}!stop`, grow);
597
+ }
598
+ }
599
+
600
+ private placeItem(anchor: string, grow: boolean, create: () => SegItem): Segment | undefined {
601
+ const seen = this.seenUnits.get(anchor);
602
+ if (seen === "item") return this.anchorOf.get(anchor);
603
+ if (seen === "boundary" || !grow) return undefined;
604
+ let segment = this.currentSegment;
605
+ if (!segment) {
606
+ segment = {
607
+ id: `seg:${anchor}`,
608
+ items: [],
609
+ host: anchor,
610
+ closed: false,
611
+ collapsed: false,
612
+ expanded: false,
613
+ expandedItems: new Set(),
614
+ thinkingMsgs: new Map(),
615
+ };
616
+ this.segments.set(segment.id, segment);
617
+ this.currentSegment = segment;
618
+ }
619
+ segment.items.push(create());
620
+ this.anchorOf.set(anchor, segment);
621
+ this.seenUnits.set(anchor, "item");
622
+ this.touchSegment(segment);
623
+ return segment;
624
+ }
625
+
626
+ private placeBoundary(key: string, grow: boolean): void {
627
+ const seen = this.seenUnits.get(key);
628
+ if (seen === "boundary") return;
629
+ if (seen === "item") {
630
+ this.detach(key);
631
+ return;
632
+ }
633
+ if (!grow) return;
634
+ this.seenUnits.set(key, "boundary");
635
+ this.closeSegment();
636
+ }
637
+
638
+ /** Take a provisional item back out of its segment and close the segment (§5.2). */
639
+ private detach(anchor: string): void {
640
+ this.seenUnits.set(anchor, "boundary");
641
+ const segment = this.anchorOf.get(anchor);
642
+ this.anchorOf.delete(anchor);
643
+ if (!segment) return;
644
+ segment.items = segment.items.filter((item) => item.anchor !== anchor);
645
+ segment.expandedItems.delete(anchor);
646
+ if (segment.items.length === 0) {
647
+ this.segments.delete(segment.id);
648
+ if (this.currentSegment === segment) this.currentSegment = undefined;
649
+ } else if (this.currentSegment === segment) {
650
+ this.closeSegment();
651
+ } else {
652
+ this.touchSegment(segment);
653
+ }
654
+ this.rows.get(anchor)?.invalidate?.();
655
+ }
656
+
657
+ /**
658
+ * End the open segment: text, a change, a user message, compaction, or the run settling.
659
+ * A closed segment keeps drawing as a list; only `settle` collapses it.
660
+ */
661
+ closeSegment(): void {
662
+ const segment = this.currentSegment;
663
+ if (!segment) return;
664
+ segment.closed = true;
665
+ this.currentSegment = undefined;
666
+ this.touchSegment(segment);
667
+ }
668
+
669
+ /**
670
+ * The run settled (agent_settled live, the end of a seed): close the open segment and
671
+ * collapse every segment still drawn as a list into its summary line (fold-more.md §4.10).
672
+ * Segments the user opened during the run collapse too, and their item details close.
673
+ */
674
+ settle(): void {
675
+ this.closeSegment();
676
+ for (const segment of this.segments.values()) {
677
+ if (segment.collapsed) continue;
678
+ segment.collapsed = true;
679
+ segment.expanded = false;
680
+ segment.expandedItems.clear();
681
+ this.touchSegment(segment);
682
+ }
683
+ }
684
+
685
+ segment(anchor: string): Segment | undefined {
686
+ return this.anchorOf.get(anchor);
687
+ }
688
+
689
+ segmentsList(): Segment[] {
690
+ return [...this.segments.values()];
691
+ }
692
+
693
+ /**
694
+ * What the slot of `anchor` draws (fold-more.md §5.6): itself when its segment is below the
695
+ * threshold, everything when it is the host, nothing otherwise. Derived on every render.
696
+ */
697
+ foldRole(anchor: string): FoldRole {
698
+ const segment = this.fold.enabled ? this.anchorOf.get(anchor) : undefined;
699
+ if (!segment || segment.items.length < this.fold.minItems) return { kind: "single", segment };
700
+ return segment.host === anchor ? { kind: "host", segment } : { kind: "hidden", segment };
701
+ }
702
+
703
+ toggleSegment(segment: Segment): void {
704
+ segment.expanded = !segment.expanded;
705
+ this.touchSegment(segment);
706
+ }
707
+
708
+ toggleSegmentItem(segment: Segment, anchor: string): void {
709
+ if (segment.expandedItems.has(anchor)) segment.expandedItems.delete(anchor);
710
+ else segment.expandedItems.add(anchor);
711
+ this.touchSegment(segment);
712
+ }
713
+
714
+ /** Counts and tenses for the summary line (fold-more.md §5.4). */
715
+ segmentStats(segment: Segment, now = Date.now()): FoldStats {
716
+ let thinkingCount = 0;
717
+ let thinkingActive = false;
718
+ let commands = 0;
719
+ let commandsActive = false;
720
+ const readTargets = new Set<string>();
721
+ let readCalls = 0;
722
+ let searches = 0;
723
+ let lists = 0;
724
+ let exploreActive = false;
725
+ let tools = 0;
726
+ let failed = 0;
727
+ let interrupted = 0;
728
+ for (const item of segment.items) {
729
+ if (item.kind === "thinking") {
730
+ thinkingCount++;
731
+ if (item.streaming) thinkingActive = true;
732
+ continue;
733
+ }
734
+ tools++;
735
+ const row = this.rows.get(item.anchor);
736
+ const name = row?.name ?? item.name;
737
+ const active = !row || row.endedAt === undefined;
738
+ if (isFailed(row?.result)) failed++;
739
+ else if (isInterrupted(row?.result)) interrupted++;
740
+ if (isShellTool(name)) {
741
+ commands++;
742
+ if (active) commandsActive = true;
743
+ continue;
744
+ }
745
+ if (active) exploreActive = true;
746
+ if (name === "read") {
747
+ readCalls++;
748
+ readTargets.add(targetKey(name, row?.args ?? {}, item.anchor));
749
+ } else if (name === "grep" || name === "find") {
750
+ searches++;
751
+ } else if (name === "ls") {
752
+ lists++;
753
+ }
754
+ }
755
+ let ms: number | undefined;
756
+ for (const [ts, entry] of segment.thinkingMsgs) {
757
+ const value = entry.durationMs ?? (entry.streaming ? Math.max(0, now - ts) : undefined);
758
+ if (value !== undefined) ms = (ms ?? 0) + value;
759
+ }
760
+ return {
761
+ thinking: { count: thinkingCount, ms, active: thinkingActive },
762
+ commands: { count: commands, active: commandsActive },
763
+ reads: readTargets.size || readCalls,
764
+ searches,
765
+ lists,
766
+ exploreActive,
767
+ tools,
768
+ failed,
769
+ interrupted,
770
+ };
771
+ }
772
+
773
+ /** Partition of anchors into segments, for tests and debugging. */
774
+ foldSnapshot(): Array<{ host: string; items: string[]; closed: boolean; collapsed: boolean }> {
775
+ return this.segmentsList().map((segment) => ({
776
+ host: segment.host,
777
+ items: segment.items.map((item) => item.anchor),
778
+ closed: segment.closed,
779
+ collapsed: segment.collapsed,
780
+ }));
781
+ }
782
+ }
783
+
784
+ export interface GroupCounts {
785
+ calls: number;
786
+ reads: number;
787
+ searches: number;
788
+ lists: number;
789
+ }
790
+
791
+ export function groupCounts(group: ToolGroup): GroupCounts {
792
+ const readTargets = new Set<string>();
793
+ let readCalls = 0;
794
+ let searches = 0;
795
+ let lists = 0;
796
+ for (const member of group.members) {
797
+ if (member.name === "read") {
798
+ readCalls++;
799
+ readTargets.add(targetKey(member.name, member.args, member.id));
800
+ } else if (member.name === "grep" || member.name === "find") {
801
+ searches++;
802
+ } else if (member.name === "ls") {
803
+ lists++;
804
+ }
805
+ }
806
+ return {
807
+ calls: group.members.length,
808
+ reads: readTargets.size || readCalls,
809
+ searches,
810
+ lists,
811
+ };
812
+ }
813
+
814
+ export function groupActive(group: ToolGroup): boolean {
815
+ return group.members.some((member) => member.endedAt === undefined);
816
+ }
817
+
818
+ /** Members that failed; an interrupted call is not a failure (DESIGN.md §9). */
819
+ export function groupFailed(group: ToolGroup): number {
820
+ return group.members.filter((member) => isFailed(member.result)).length;
821
+ }
822
+
823
+ /** Members cut short by an interrupt. */
824
+ export function groupInterrupted(group: ToolGroup): number {
825
+ return group.members.filter((member) => isInterrupted(member.result)).length;
826
+ }
827
+
828
+ export function groupEndedAt(group: ToolGroup): number {
829
+ return group.endedAt ?? Math.max(...group.members.map((member) => member.endedAt ?? member.startedAt));
830
+ }
831
+
832
+ export function groupKind(group: ToolGroup): "reads" | "searches" | "lists" | "mixed" {
833
+ const counts = groupCounts(group);
834
+ const kinds = Number(counts.reads > 0) + Number(counts.searches > 0) + Number(counts.lists > 0);
835
+ if (kinds > 1) return "mixed";
836
+ if (counts.searches > 0) return "searches";
837
+ if (counts.lists > 0) return "lists";
838
+ return "reads";
839
+ }
840
+
841
+ export function groupAction(group: ToolGroup): string {
842
+ const active = groupActive(group);
843
+ switch (groupKind(group)) {
844
+ case "mixed":
845
+ return active ? "Exploring" : "Explored";
846
+ case "searches":
847
+ return active ? "Searching" : "Searched";
848
+ case "lists":
849
+ return active ? "Listing" : "Listed";
850
+ default:
851
+ return active ? "Reading" : "Read";
852
+ }
853
+ }
854
+
855
+ export function groupSummary(group: ToolGroup): string {
856
+ const counts = groupCounts(group);
857
+ const parts: string[] = [];
858
+ if (counts.reads > 0) parts.push(`${counts.reads} file${counts.reads === 1 ? "" : "s"}`);
859
+ if (counts.searches > 0) parts.push(`${counts.searches} search${counts.searches === 1 ? "" : "es"}`);
860
+ if (counts.lists > 0) parts.push(`${counts.lists} dir${counts.lists === 1 ? "" : "s"}`);
861
+ return parts.join(", ");
862
+ }
863
+
864
+ export function groupDuration(group: ToolGroup, now = Date.now()): number {
865
+ const end = groupActive(group) ? now : groupEndedAt(group);
866
+ return Math.max(0, end - group.startedAt);
867
+ }
868
+
869
+ function partialText(value: unknown): string | undefined {
870
+ if (!value || typeof value !== "object") return undefined;
871
+ const content = (value as { content?: unknown }).content;
872
+ if (!Array.isArray(content)) return undefined;
873
+ const text = content
874
+ .flatMap((block) => {
875
+ if (!block || typeof block !== "object") return [];
876
+ const item = block as { type?: unknown; text?: unknown };
877
+ return item.type === "text" && typeof item.text === "string" ? [item.text] : [];
878
+ })
879
+ .join("\n");
880
+ return str(text);
881
+ }