dsh-trajectory-traceview-plus 0.0.0-stage → 0.11.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.
@@ -0,0 +1,2627 @@
1
+ //#region pure helpers: snapshot -> timeline tree
2
+ /** Nested programmatic tool calls deeper than this are dropped (cycle guard). */
3
+ const SUB_CALL_MAX_DEPTH = 8;
4
+ /**
5
+ * Total materialised sub-call budget per tool cell. The depth cap alone does not
6
+ * bound work: a wide tree hits breadth^depth, and 5 siblings x 9 levels produced
7
+ * 2.4 million copied nodes (12.7 s) from a payload that was already in memory.
8
+ * Once the budget is spent the remaining children are dropped rather than paying
9
+ * an unbounded copy cost.
10
+ */
11
+ const SUB_CALL_MAX_TOTAL = 2000;
12
+ /**
13
+ * `title` tooltips must not carry a whole argument payload. The visible text was
14
+ * already clipped to 64 chars, but the title held the FULL string, so a session
15
+ * with 480 long-payload calls pushed 14.6 MB of markup (207 KB of it title text).
16
+ */
17
+ const TITLE_PREVIEW_CHARS = 200;
18
+ /**
19
+ * Upper bound for a believable single tool duration. Long-running commands exist,
20
+ * but once a reading crosses a day it is a timestamp artefact (reload gap, missing
21
+ * `callTime`), not a real measurement, and it must not enter any total.
22
+ */
23
+ const TOOL_DUR_CEILING_MS = 6 * 60 * 60 * 1000;
24
+ /** First non-empty line of a possibly-Markdown string. */
25
+ function firstLine(value) {
26
+ if (typeof value !== "string") return "";
27
+ for (const raw of value.split(/\r?\n/)) {
28
+ const line = raw.trim();
29
+ if (line !== "") return line;
30
+ }
31
+ return "";
32
+ }
33
+
34
+ /**
35
+ * Coerce a projected field to a string at the SOURCE, not at every render site.
36
+ *
37
+ * The host contracts type these fields as `string` (`TurnErrorNode.message`,
38
+ * `CommandNode.args`, compaction summary), so a non-string is already a contract
39
+ * violation — but "already a violation" is not the same as "cannot happen", and
40
+ * this plugin's rule is that one bad field degrades ITS OWN record, never the
41
+ * panel. React throws `Objects are not valid as a React child` for an object, so a
42
+ * single drifted field blanked the whole card (and, outside the boundary, the
43
+ * whole view) instead of printing something.
44
+ *
45
+ * Objects fall back to their JSON so the reader can still see what arrived; that
46
+ * is strictly more useful than "[object Object]" and it never throws.
47
+ */
48
+ function asText(value) {
49
+ if (typeof value === "string") return value;
50
+ if (value === null || value === void 0) return "";
51
+ // A non-finite number is not a value the log provided; `String(NaN)` would put
52
+ // the literal token "NaN" into the panel and the export.
53
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "";
54
+ if (typeof value === "boolean") return String(value);
55
+ try { return safeJsonPreview(value, 2000); } catch (e) { return ""; }
56
+ }
57
+ /**
58
+ * Normalise a prompt's tool catalog for rendering.
59
+ *
60
+ * `prompt.tools` reaches the request tab straight from the host and is only
61
+ * checked for being an array (the fold replaces a non-array with `[]`); the
62
+ * ENTRIES were trusted. One `null` entry threw
63
+ * `Cannot read properties of null (reading 'name')` during render and blanked
64
+ * the whole request tab — every other tool in the catalog disappeared because
65
+ * of one hole in the list. Drop holes, coerce the three fields we print, and
66
+ * keep the order so the catalog still reads like the real one.
67
+ */
68
+ function safeToolList(tools) {
69
+ if (!Array.isArray(tools)) return [];
70
+ const out = [];
71
+ for (const raw of tools) {
72
+ if (raw === null || typeof raw !== "object") continue;
73
+ out.push({
74
+ name: asText(raw.name),
75
+ description: asText(raw.description),
76
+ parameters: raw.parameters
77
+ });
78
+ }
79
+ return out;
80
+ }
81
+ /** First text block of a ContentBlock list (full text). */
82
+ function textOfContent(content, t) {
83
+ // `for…of` on a non-array throws, and a host payload with a wrong-shaped
84
+ // `content` (e.g. an object) crashed the whole view. `blocksText` already
85
+ // guards this way; the two helpers must agree on tolerating bad input.
86
+ if (!Array.isArray(content)) return "";
87
+ // ContentBlock is merge-extensible and the host ships seven types. Returning
88
+ // only the first text block dropped every other kind, so a user message that
89
+ // was a file or an image rendered as empty. Join all readable parts and label
90
+ // the ones that have no text, mirroring blocksText.
91
+ const parts = [];
92
+ for (const b of content) {
93
+ if (b == null || typeof b !== "object") continue;
94
+ if (b.type === "text" && typeof b.text === "string" && b.text !== "") { parts.push(b.text); continue; }
95
+ if (b.type === "image") { parts.push(typeof t === "function" ? t("block.image") : "image"); continue; }
96
+ if (b.type === "file") {
97
+ const name = typeof b.attachment?.name === "string" && b.attachment.name !== "" ? b.attachment.name : null;
98
+ const label = typeof t === "function" ? t("block.file") : "file";
99
+ parts.push(name !== null ? `${label}: ${name}` : label);
100
+ continue;
101
+ }
102
+ // Tool-set changes are a defined ContentBlock type, not unknown payload:
103
+ // rendering them as "other content · tool-addition" threw away the tool
104
+ // NAME, which is the only thing the notice is about. The official layout
105
+ // spells it out the same way.
106
+ if (b.type === "tool-addition" || b.type === "tool-removal") {
107
+ const name = typeof b.toolName === "string" && b.toolName !== "" ? b.toolName : null;
108
+ // A nameless entry still has to say SOMETHING: dropping it made a
109
+ // tool-set change render as an empty row. Degrade to the generic tag.
110
+ if (name !== null) {
111
+ const key = b.type === "tool-addition" ? "block.toolAdded" : "block.toolRemoved";
112
+ const fallback = b.type === "tool-addition" ? "[tool added] " : "[tool removed] ";
113
+ parts.push(typeof t === "function" ? t(key).replace("{name}", name) : fallback + name);
114
+ } else {
115
+ const label = typeof t === "function" ? t("block.other") : "other";
116
+ parts.push(`${label} · ${b.type}`);
117
+ }
118
+ continue;
119
+ }
120
+ // Unknown/plugin-added blocks degrade to their type tag instead of vanishing.
121
+ if (typeof b.type === "string" && b.type !== "") {
122
+ const label = typeof t === "function" ? t("block.other") : "other";
123
+ parts.push(`${label} · ${b.type}`);
124
+ }
125
+ }
126
+ return parts.join("\n");
127
+ }
128
+ /** Join every text block; images become a visible placeholder. */
129
+ function blocksText(content, t) {
130
+ if (!Array.isArray(content)) return "";
131
+ const parts = [];
132
+ for (const b of content) {
133
+ if (b == null) continue;
134
+ if (b.type === "text" && typeof b.text === "string") { if (b.text !== "") parts.push(b.text); }
135
+ // The image placeholder is user-visible: hardcoding Chinese leaked it into
136
+ // the English UI. Fall back to English only when no translator is passed, so
137
+ // pure-function callers stay valid.
138
+ else if (b.type === "image") parts.push(typeof t === "function" ? t("block.image") : "image");
139
+ else if (b.type === "reasoning" && typeof b.text === "string" && b.text !== "") parts.push(b.text);
140
+ // A tool that attaches a file (a reader, an exporter) produced an EMPTY
141
+ // result cell: `file` was not handled here at all, so the card showed
142
+ // nothing for a result that plainly existed. The attachment name is the
143
+ // only usable identifier, so show it when present.
144
+ else if (b.type === "file") {
145
+ const fname = typeof b.attachment?.name === "string" && b.attachment.name !== "" ? b.attachment.name : null;
146
+ const flabel = typeof t === "function" ? t("block.file") : "file";
147
+ parts.push(fname !== null ? `${flabel}: ${fname}` : flabel);
148
+ }
149
+ }
150
+ return parts.join("\n");
151
+ }
152
+ /** Display name for one sub-call entry (settled or running shape). */
153
+ function subName(sub) {
154
+ if (sub == null) return "?";
155
+ const fromCall = sub.call?.name;
156
+ if (typeof fromCall === "string" && fromCall !== "") return fromCall;
157
+ if (typeof sub.name === "string" && sub.name !== "") return sub.name;
158
+ return typeof sub.callId === "string" ? sub.callId : "?";
159
+ }
160
+ /** Millisecond duration label, e.g. `1,500 ms`. */
161
+ function fmtMs(ms) {
162
+ if (ms == null || !Number.isFinite(ms)) return "";
163
+ return `${String(Math.round(ms)).replace(/\B(?=(\d{3})+(?!\d))/g, ",")} ms`;
164
+ }
165
+ /**
166
+ * Human duration for KPI tiles. A long session's total tool time runs into
167
+ * minutes/hours, and "3600.0 s" is unreadable, so scale the unit with the value.
168
+ */
169
+ function fmtDur(ms) {
170
+ if (ms == null || !Number.isFinite(ms) || ms <= 0) return "—";
171
+ if (ms < 1000) return `${String(Math.round(ms))} ms`;
172
+ // Round first, then choose the unit: otherwise 59,960 ms formats as "60.0 s"
173
+ // (a value that reads as one minute but carries a seconds label), and 3,599,999
174
+ // ms as "60 min" instead of "1.0 h".
175
+ const s = Math.round(ms / 100) / 10;
176
+ if (s < 60) return `${s.toFixed(1)} s`;
177
+ const m = Math.round(ms / 6000) / 10;
178
+ if (m < 60) return `${m.toFixed(m < 10 ? 1 : 0)} min`;
179
+ return `${(Math.round(ms / 36000) / 100).toFixed(1)} h`;
180
+ }
181
+ /** Compact integer with thousands separators. */
182
+ function fmtInt(n) {
183
+ if (n == null || !Number.isFinite(n)) return "0";
184
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
185
+ }
186
+ /** Compact token count: `1.2k` / `34.5k` / `1.2M`. */
187
+ function fmtTokens(n) {
188
+ if (n == null || !Number.isFinite(n) || n <= 0) return "—";
189
+ if (n < 1000) return String(Math.round(n));
190
+ // Same rule as the M tier below: round to the target precision FIRST, then pick
191
+ // the unit. `999,999` rounds to 1000, and printing "1000k" is a four-digit
192
+ // mantissa that should have carried into "1.0M".
193
+ if (n < 999.5e3) {
194
+ const k = n / 1000;
195
+ return `${n < 9950 ? k.toFixed(1) : String(Math.round(k))}k`;
196
+ }
197
+ if (n < 1e6) return `${(n / 1e6).toFixed(1)}M`;
198
+ // Round to one decimal BEFORE choosing the unit, so 999,999,999 becomes
199
+ // "1.0B" rather than "1000.0M" (a four-digit mantissa that reads as an error).
200
+ if (n < 999.95e6) return `${(n / 1e6).toFixed(1)}M`;
201
+ // Long sessions really do cross a billion cumulative input tokens (a 4-turn
202
+ // run here measured 16.3e9). Without the B step that printed "16300.0M",
203
+ // which is both wrong-looking and 5 characters wider than the KPI allows.
204
+ return `${(n / 1e9).toFixed(1)}B`;
205
+ }
206
+ /** Pretty-print raw tool arguments: JSON when parseable, else trimmed source. */
207
+ function prettyArgs(raw) {
208
+ if (typeof raw !== "string" || raw.trim() === "") return "";
209
+ try {
210
+ const obj = JSON.parse(raw);
211
+ if (obj && typeof obj === "object") return JSON.stringify(obj, null, 2);
212
+ } catch { /* not JSON — fall through */ }
213
+ return raw.length > 1200 ? `${raw.slice(0, 1200)}…` : raw;
214
+ }
215
+ /** Pretty-print an arbitrary object as JSON. */
216
+ function prettyJson(obj) {
217
+ try { return JSON.stringify(obj, null, 2); } catch { return String(obj); }
218
+ }
219
+ /** Normalize a TokenUsage payload to a flat record (null-safe). */
220
+ function normalizeUsage(u) {
221
+ if (u == null || typeof u !== "object") return null;
222
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.round(v) : 0);
223
+ return {
224
+ input: num(u.inputTokens) + num(u.cacheReadTokens) + num(u.cacheWriteTokens),
225
+ output: num(u.outputTokens) + num(u.reasoningTokens),
226
+ raw: num(u.inputTokens),
227
+ cacheRead: num(u.cacheReadTokens),
228
+ cacheWrite: num(u.cacheWriteTokens),
229
+ think: num(u.reasoningTokens)
230
+ };
231
+ }
232
+ /**
233
+ * Highest turn number among the folded turns (0 when nothing has been folded).
234
+ *
235
+ * A loop, never `Math.max(...turns.map(...))`: spreading one argument per turn
236
+ * throws "Maximum call stack size exceeded" once a session is large enough
237
+ * (measured at ~125k turns — and the fold dies with it, taking the whole view
238
+ * down). A malformed or merged log can reach that size even though no real
239
+ * interactive session does.
240
+ */
241
+ function maxTurnOf(turns) {
242
+ let max = 0;
243
+ if (!Array.isArray(turns)) return max;
244
+ for (const e of turns) {
245
+ if (e == null) continue;
246
+ const n = e.turn;
247
+ if (typeof n === "number" && Number.isFinite(n) && n > max) max = n;
248
+ }
249
+ return max;
250
+ }
251
+ /** Fresh mutable per-step accumulator used while folding assistant nodes. */
252
+ function newStepState(seq) {
253
+ return {
254
+ seq, time: null, cells: [], live: false, request: null,
255
+ // T5: distinguishes "no timing object at all" from "timing recorded, but
256
+ // the edge fell outside the loaded window". Collapsing both into a bare
257
+ // null makes "no duration" ambiguous; official keeps `timingRecorded`
258
+ // for exactly this reason (trajectory-record.d.ts:10).
259
+ timingRecorded: false,
260
+ // Anchor identity, written ONLY at the durable patch site below.
261
+ // Never derived from `seq` (which is min-reduced and also carries
262
+ // epoch-ms / +0.5 synthetic values). null => not deep-linkable.
263
+ anchorSeq: null,
264
+ ttftMs: null, startMs: null, endMs: null, firstTokMs: null, toolMs: 0, toolCount: 0,
265
+ hasError: false, interrupted: false, usage: null, modelHint: null
266
+ };
267
+ }
268
+ /**
269
+ * Map a LIST of sub-calls with ONE shared budget. Calling `subDetailOf(x, 0)` per
270
+ * root created a fresh budget for each, so five roots copied 7,775 nodes even
271
+ * though the cap was 2,000. The cap is per tool cell, not per root.
272
+ */
273
+ function mapSubCalls(list, tr) {
274
+ if (!Array.isArray(list)) return [];
275
+ const budget = { used: 0 };
276
+ const out = [];
277
+ for (const sub of list) {
278
+ if (budget.used >= SUB_CALL_MAX_TOTAL) break;
279
+ out.push(subDetailOf(sub, 0, budget, tr));
280
+ }
281
+ return out;
282
+ }
283
+ /** Map one sub-call entry (settled ToolResultNode or running shape) to full detail. */
284
+ function subDetailOf(sub, depth, budget, tr) {
285
+ const level = Number.isSafeInteger(depth) ? depth : 0;
286
+ // Shared budget across the whole tree, not per level. `budget` is threaded
287
+ // explicitly so a call can never reset the counter by recursing.
288
+ const spent = budget ?? { used: 0 };
289
+ spent.used += 1;
290
+ if (sub == null) return { name: "?", callId: null, argsRaw: "", resultText: "", isError: false, errorName: undefined, running: false, durationMs: null, subCalls: [] };
291
+ const settled = sub.kind === "tool-result";
292
+ const argsRaw = typeof sub.argsRaw === "string" ? sub.argsRaw : (typeof sub.call?.argsRaw === "string" ? sub.call.argsRaw : "");
293
+ const durationMs = settled && Number.isFinite(sub.callTime) && Number.isFinite(sub.time) ? Math.max(0, sub.time - sub.callTime) : null;
294
+ return {
295
+ name: subName(sub),
296
+ callId: typeof sub.callId === "string" ? sub.callId : null,
297
+ argsRaw,
298
+ resultText: settled ? blocksText(sub.content, tr) : "",
299
+ isError: settled && sub.isError === true,
300
+ errorName: settled ? sub.error?.name : undefined,
301
+ running: !settled,
302
+ durationMs,
303
+ // Programmatic tool calling nests: a sub call can itself make sub calls.
304
+ // Flattening only one level dropped every deeper call, so the detail panel
305
+ // and the Markdown export lost evidence that exists in the log. The depth
306
+ // cap keeps a malformed/cyclic payload from recursing forever.
307
+ subCalls: (level < SUB_CALL_MAX_DEPTH && spent.used < SUB_CALL_MAX_TOTAL && Array.isArray(sub.subCalls))
308
+ ? sub.subCalls.map((x) => (spent.used < SUB_CALL_MAX_TOTAL ? subDetailOf(x, level + 1, spent, tr) : null)).filter((x) => x !== null)
309
+ : []
310
+ };
311
+ }
312
+ /** Compact prompt-change summary: tool names added/removed + system char delta. */
313
+ function promptDiffOf(change, curPrompt) {
314
+ if (change == null) return null;
315
+ const kind = typeof change.kind === "string" ? change.kind : "system-and-tools";
316
+ const prev = change.previous ?? null;
317
+ const curTools = Array.isArray(curPrompt?.tools) ? curPrompt.tools : [];
318
+ const curNames = new Set(curTools.map((tool) => tool?.name).filter((n) => typeof n === "string"));
319
+ const prevNames = new Set((Array.isArray(prev?.tools) ? prev.tools : []).map((tool) => tool?.name).filter((n) => typeof n === "string"));
320
+ const toolsAdded = [...curNames].filter((n) => !prevNames.has(n));
321
+ const toolsRemoved = [...prevNames].filter((n) => !curNames.has(n));
322
+ const curSystemChars = typeof curPrompt?.system === "string" ? curPrompt.system.length : 0;
323
+ const prevSystemChars = typeof prev?.system === "string" ? prev.system.length : 0;
324
+ // Q2-1: name-level add/remove is not enough — a rewritten tool description or
325
+ // schema changes model behaviour without changing the catalog names.
326
+ const toolsChanged = prev === null ? [] : changedTools(prev?.tools, curPrompt?.tools);
327
+ const textDiff = prev === null ? null : promptTextDiff(prev?.system, curPrompt?.system, PROMPT_DIFF_LINES);
328
+ return {
329
+ kind, toolsAdded, toolsRemoved, toolsChanged,
330
+ prevSystemChars, curSystemChars, systemDelta: curSystemChars - prevSystemChars,
331
+ textDiff, isInitial: prev === null
332
+ };
333
+ }
334
+ /** Cap for one tool result inside a single-step review pack. */
335
+ const STEP_RESULT_LIMIT = 4000;
336
+ /** Cap for the recorded payload of one `unknown` surface node. */
337
+ const UNKNOWN_PAYLOAD_LIMIT = 2000;
338
+ /**
339
+ * Minimum gap between projection rebuilds while a step is streaming.
340
+ * The trajectory snapshot changes on every streamed token, and folding the
341
+ * whole session costs ~40 ms at 3,200 stations (~90 ms at 6,400). Rebuilding
342
+ * per token therefore stalls the main thread continuously for no visible
343
+ * gain: 120 ms of staleness is imperceptible, while 8 rebuilds/second instead
344
+ * of ~30 leaves the frame budget intact. Idle sessions never rebuild at all.
345
+ */
346
+ const STREAM_REBUILD_MS = 120;
347
+ /**
348
+ * Best-effort JSON preview of an opaque payload. Values reaching here are
349
+ * documented as `session.data` (plain JSON), but a truncated or exotic event
350
+ * could still carry a cycle or a BigInt, and a review view must not throw on
351
+ * the one node whose whole purpose is "the reader should see this".
352
+ * @param value - whatever the event carried.
353
+ * @param limit - maximum characters to keep.
354
+ * @returns a printable string, never throwing.
355
+ */
356
+ /**
357
+ * Render a log-supplied integer for display.
358
+ *
359
+ * `String(n.turn)` on a NaN/Infinity/object field printed "轮次 NaN" and
360
+ * "[object Object]" straight into the panel and the export. A number the log does
361
+ * not actually provide must read as unknown, not as a bogus value.
362
+ */
363
+ function numOr(v, fallback) {
364
+ return Number.isSafeInteger(v) ? String(v) : (fallback === void 0 ? "?" : fallback);
365
+ }
366
+ /** A readable stand-in for a value JSON refuses to serialise. */
367
+ function describeUnrepresentable(value) {
368
+ if (value === void 0) return "";
369
+ if (typeof value === "symbol") { try { return String(value); } catch { return "[symbol]"; } }
370
+ if (typeof value === "function") return "[function]";
371
+ return `[${typeof value}]`;
372
+ }
373
+ /**
374
+ * A tool callId rendered as text.
375
+ *
376
+ * `callId` is typed as a string by the contract, but a damaged/merged log can carry
377
+ * a number, BigInt or Symbol. A template literal THROWS on a Symbol, so the orphan
378
+ * card must not interpolate it raw. BigInt/numbers are shown as their digits; truly
379
+ * unprintable values fall back to `describeUnrepresentable`.
380
+ */
381
+ /**
382
+ * Tool arguments as text.
383
+ *
384
+ * The contract types `argsRaw` as a string, but a merged/hand-edited log can carry the
385
+ * already-parsed object. `typeof === "string"` then silently produced an EMPTY args
386
+ * field — the card looked like the tool was called with no arguments. Render whatever
387
+ * was recorded instead.
388
+ */
389
+ function argsText(argsRaw) {
390
+ if (typeof argsRaw === "string") return argsRaw;
391
+ if (argsRaw == null) return "";
392
+ const preview = safeJsonPreview(argsRaw,2000);
393
+ return preview;
394
+ }
395
+
396
+ function displayCallId(callId) {
397
+ if (typeof callId === "string") return callId;
398
+ if (typeof callId === "number" || typeof callId === "bigint" || typeof callId === "boolean") return String(callId);
399
+ return describeUnrepresentable(callId);
400
+ }
401
+ function safeJsonPreview(value, limit, indent) {
402
+ let text = "";
403
+ // "Nothing recorded" must render as nothing. `JSON.stringify(null)` is the string
404
+ // "null", so an unknown event with no payload showed the literal word "null" in
405
+ // the panel — the same confusion the "undefined" case had. Callers already test
406
+ // for `""`, so returning "" keeps the empty branch working.
407
+ if (value === null || value === void 0) return "";
408
+ // `JSON.stringify(NaN)` and of `Infinity` are both the string "null", so a
409
+ // non-finite number payload rendered the literal word "null" too.
410
+ if (typeof value === "number" && !Number.isFinite(value)) return "";
411
+ if (typeof value === "string") text = value;
412
+ else {
413
+ // `indent` is only for the request tab, which shows the payload pretty-printed.
414
+ const pad = Number.isSafeInteger(indent) && indent > 0 ? indent : void 0;
415
+ // Fast path FIRST. The guarded replacer below keeps a global `seen` set, so it
416
+ // labels any object that appears twice — including a perfectly ordinary alias
417
+ // (`[x, x]`, or one schema object reused by two tools) — as "[Circular]".
418
+ // Plain stringify handles aliases correctly and only fails on a real cycle or
419
+ // a BigInt, so trying it first means the marked-up output is reserved for the
420
+ // cases that actually need it.
421
+ try {
422
+ text = JSON.stringify(value, null, pad);
423
+ // JSON.stringify returns `undefined` (not a string) for a value it cannot
424
+ // represent — a bare Symbol, a function, or `undefined` itself. The old
425
+ // `String(text)` then made the panel print the literal word "undefined",
426
+ // which reads like a bug in the viewer rather than "this payload is not
427
+ // representable". Say what it actually is.
428
+ if (typeof text !== "string") text = describeUnrepresentable(value);
429
+ } catch (plain) {
430
+ try {
431
+ // ANCESTRY, not "seen anywhere". A WeakSet that is never cleared marks
432
+ // any value met twice, so one BigInt or one real cycle anywhere in the
433
+ // payload turned every ordinary alias (`{a: shared, b: shared}`, two
434
+ // tools sharing one schema object) into "[Circular]" — silently hiding
435
+ // content that is perfectly representable. `[Circular]` must mean "this
436
+ // object is its own ANCESTOR", so the check walks the holder chain that
437
+ // the replacer's `this` already gives us: record which object contains
438
+ // which, then ask whether the current container descends from the value.
439
+ // (A push/pop stack cannot work here: the replacer is never told when it
440
+ // leaves a value, so nothing would ever pop.)
441
+ const parents = new WeakMap();
442
+ text = JSON.stringify(value, function (k, v) {
443
+ if (typeof v === "bigint") return `${String(v)}n`;
444
+ if (v !== null && typeof v === "object") {
445
+ for (let h = this; h !== null && typeof h === "object"; h = parents.get(h)) {
446
+ if (h === v) return "[Circular]";
447
+ }
448
+ parents.set(v, this);
449
+ }
450
+ return v;
451
+ }, pad);
452
+ if (typeof text !== "string") text = describeUnrepresentable(value);
453
+ } catch (e) {
454
+ try { text = String(value); } catch (e2) { text = ""; }
455
+ }
456
+ }
457
+ }
458
+ const cap = Number.isFinite(limit) ? limit : UNKNOWN_PAYLOAD_LIMIT;
459
+ return text.length > cap ? `${text.slice(0, cap)}…` : text;
460
+ }
461
+ /** How many changed prompt lines to keep per side in the diff view. */
462
+ const PROMPT_DIFF_LINES = 40;
463
+ /**
464
+ * Q2-2: which parts of this panel are verbatim and which are inferred.
465
+ * The message list is rebuilt from the log, the prompt header is recorded, and
466
+ * anything touching unloaded history is partial. Users must not confuse the
467
+ * reconstruction for the exact payload the server saw.
468
+ */
469
+ function evidenceOf(request, messages, hasMore) {
470
+ const out = [];
471
+ if (request != null && request.prompt != null) out.push({ id: "prompt", level: "exact" });
472
+ if (Array.isArray(messages) && messages.length > 0) out.push({ id: "messages", level: "reconstructed" });
473
+ if (hasMore === true) out.push({ id: "range", level: "partial" });
474
+ return out;
475
+ }
476
+ /**
477
+ * Q2-1: the summary above only says "system prompt changed by N chars". A prompt
478
+ * author needs the actual changed lines. Pure: no DOM, no I/O.
479
+ * Returns the first `limit` changed lines per side, as {removed, added, narrows}.
480
+ */
481
+ function promptTextDiff(prevText, curText, limit) {
482
+ const cap = Number.isSafeInteger(limit) && limit > 0 ? limit : 40;
483
+ const split = (v) => (typeof v === "string" && v !== "" ? v.split(/\r?\n/) : []);
484
+ const a = split(prevText);
485
+ const b = split(curText);
486
+ if (a.length === 0 && b.length === 0) return null;
487
+ // Trim the common prefix and suffix so a one-line edit in a 3k-line prompt
488
+ // does not show up as "everything changed".
489
+ let head = 0;
490
+ while (head < a.length && head < b.length && a[head] === b[head]) head += 1;
491
+ let tail = 0;
492
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1;
493
+ const removedAll = a.slice(head, a.length - tail);
494
+ const addedAll = b.slice(head, b.length - tail);
495
+ if (removedAll.length === 0 && addedAll.length === 0) return null;
496
+ return {
497
+ removed: removedAll.slice(0, cap),
498
+ added: addedAll.slice(0, cap),
499
+ // true when the diff was truncated (more lines exist than we show)
500
+ narrows: removedAll.length > cap || addedAll.length > cap,
501
+ removedCount: removedAll.length,
502
+ addedCount: addedAll.length,
503
+ startLine: head + 1
504
+ };
505
+ }
506
+ /** Serialize one tool schema so a changed schema compares by content, not only by name. */
507
+ function toolSchemaKey(tool) {
508
+ if (tool == null || typeof tool !== "object") return "";
509
+ const name = typeof tool.name === "string" ? tool.name : "";
510
+ let body = "";
511
+ try { body = JSON.stringify(tool.inputSchema ?? tool.schema ?? tool.parameters ?? null); } catch { body = ""; }
512
+ return `${name}\u0000${typeof tool.description === "string" ? tool.description : ""}\u0000${body}`;
513
+ }
514
+ /** Tool catalogs that share a name but differ in description/schema. */
515
+ function changedTools(prevTools, curTools) {
516
+ const prev = Array.isArray(prevTools) ? prevTools : [];
517
+ const cur = Array.isArray(curTools) ? curTools : [];
518
+ const prevBy = new Map();
519
+ for (const tool of prev) { const k = toolSchemaKey(tool); const name = k.split("\u0000")[0]; if (name !== "") prevBy.set(name, k); }
520
+ const out = [];
521
+ for (const tool of cur) {
522
+ const k = toolSchemaKey(tool);
523
+ const name = k.split("\u0000")[0];
524
+ if (name === "") continue;
525
+ const was = prevBy.get(name);
526
+ if (was !== void 0 && was !== k) out.push(name);
527
+ }
528
+ return out;
529
+ }
530
+ /** Decode throughput (tokens/sec) from usage + timing; null when unknown. */
531
+ function decodeRateOf(usage, firstTokenTime, completedTime) {
532
+ if (usage == null || !(usage.output > 0)) return null;
533
+ if (!Number.isFinite(firstTokenTime) || !Number.isFinite(completedTime)) return null;
534
+ const ms = completedTime - firstTokenTime;
535
+ if (!(ms > 300)) return null; // too short to be meaningful
536
+ return usage.output / (ms / 1000);
537
+ }
538
+ /** Reconstruct the model-visible message list sent before seq `beforeSeq`. */
539
+ function reconstructMessages(nodes, beforeSeq, tr) {
540
+ const out = [];
541
+ // `seq` rides along as the message's IDENTITY. The request tab keys its rows on
542
+ // the array index, and this list is rebuilt whenever the station window grows
543
+ // backwards — paging in older history PREPENDS messages, so index 3 stops being
544
+ // the message it was. With index keys React reuses the DOM node and an expanded
545
+ // `<details>` ends up showing a different message's body, while the collapsed one
546
+ // below it silently expands.
547
+ for (const n of nodes) {
548
+ // `continue`, not `break`. This used to stop at the FIRST node whose seq was
549
+ // past the step, which silently depended on `nodes` being sorted ascending.
550
+ // The only caller passes the already-sorted `tree.nodes`, so it worked — but
551
+ // any caller handing in a raw or re-ordered log got an EMPTY list with no
552
+ // error (measured: [seq5, seq1, seq3] with beforeSeq=4 returned nothing).
553
+ // Filtering costs one extra number comparison per node and removes the
554
+ // hidden precondition.
555
+ if (beforeSeq != null && n.seq != null && n.seq >= beforeSeq) continue;
556
+ if (n.kind === "user" || n.kind === "steering" || n.kind === "context") {
557
+ out.push({ role: "user", seq: n.seq ?? null, content: n.content ?? [], text: blocksText(n.content, tr) });
558
+ } else if (n.kind === "assistant") {
559
+ // `deriveTraceTree` hardens `blocks` on its own, but the request tab rebuilds
560
+ // from the RAW node. A single `null` block made this map read `.kind` off
561
+ // null and took the whole panel down (measured: TypeError inside the render
562
+ // boundary's sibling `useMemo`, so the boundary never caught it).
563
+ const rawBlocks = Array.isArray(n.blocks) ? n.blocks : [];
564
+ const blocks = rawBlocks.filter((b) => b != null && typeof b === "object");
565
+ const content = blocks.map((b) => {
566
+ if (b.kind === "tool-call") return { type: "tool-call", id: b.callId, name: b.name, arguments: b.argsRaw };
567
+ if (b.kind === "reasoning") return { type: "reasoning", text: b.text };
568
+ if (b.kind === "text") return { type: "text", text: b.text };
569
+ if (b.kind === "image") return { type: "image", attachment: b.attachment };
570
+ return { type: "other", data: b.block };
571
+ });
572
+ const text = blocks.map((b) => (b.kind === "text" ? b.text : b.kind === "reasoning" ? b.text : "")).join("\n").trim();
573
+ out.push({ role: "assistant", seq: n.seq ?? null, content, text });
574
+ } else if (n.kind === "tool-result") {
575
+ out.push({ role: "tool", seq: n.seq ?? null, content: n.content ?? [], toolCallId: n.callId, isError: n.isError === true, text: blocksText(n.content, tr) });
576
+ } else if (n.kind === "compaction") {
577
+ const head = firstLine(n.summary ?? "");
578
+ const cpt = typeof tr === "function" ? tr : (k) => k;
579
+ // The decorative CJK brackets were hardcoded too; move them into the locale so
580
+ // the English UI gets parentheses instead.
581
+ out.push({ role: "note", seq: n.seq ?? null, content: [], text: `${cpt("note.wrapL")}${cpt("note.compaction")}${head !== "" ? head : cpt("note.compacted")}${cpt("note.wrapM")}${cpt("note.replace")} ${n.shadowedItemCount ?? "?"} ${cpt("note.items")} / ${cpt("note.about")} ${fmtTokens(n.shadowedTokenCount)} tokens${cpt("note.wrapR")}` });
582
+ }
583
+ }
584
+ return out;
585
+ }
586
+ // ── Stable anchors (G2) ──────────────────────────────────────────────
587
+ // Grammar (see docs/DESIGN.md §4.1):
588
+ // tvp1:e<seq> durable record, seq must be an integer
589
+ // tvp1:e<seq>#t3s7 same + human hint (parsing uses `e`)
590
+ // tvp1:c<callId> tool result alias, resolves to its seq
591
+ // tvp1:p<turn>s<step> synthetic step (not deep-linkable)
592
+ // tvp1:p<turn>s<step>c<callId> synthetic tool result (disambiguates)
593
+ // tvp1:t<turn>s<step> readable alias, resolved via the index
594
+ const ANCHOR_PREFIX = "tvp1:";
595
+ /** Build the canonical anchor string for a station (or null when it has none). */
596
+ function anchorOf(station) {
597
+ if (station == null) return null;
598
+ if (typeof station.anchorKey === "string" && station.anchorKey !== "") return `${ANCHOR_PREFIX}${station.anchorKey}`;
599
+ if (station.kind === "step") {
600
+ const turn = Number.isFinite(station.turn) ? station.turn : 0;
601
+ // Must match how `p<turn>s<step>` is RESOLVED, which uses `turnStep`
602
+ // (per-turn) and only falls back to the window-wide `stepNo`. Writing
603
+ // `stepNo` here made every synthetic step — the live/streaming one has no
604
+ // anchorSeq at all — hand out an anchor that could not be pasted back:
605
+ // copy on turn 2's live step produced `tvp1:p2s3`, which resolved to
606
+ // "not loaded" because turn 2's first step is `turnStep` 1, not 3.
607
+ const step = Number.isFinite(station.turnStep) ? station.turnStep : station.stepNo;
608
+ return `${ANCHOR_PREFIX}p${turn}s${step}`;
609
+ }
610
+ return null;
611
+ }
612
+ /**
613
+ * Does this station's own anchor resolve back to THIS station?
614
+ *
615
+ * `e<seq>` identifies a SEQ, and one seq can carry several stations: a `turn-error`
616
+ * is stamped with the turn's end seq, which can equal the assistant message's seq,
617
+ * and a malformed log can repeat a seq outright. The resolver deliberately prefers
618
+ * a step (that is what anchors are normally copied from), so an error card offered
619
+ * a "copy anchor" button that, pasted back, jumped to the STEP instead — the user
620
+ * copied identity A and landed on record B.
621
+ *
622
+ * Callers use this to avoid handing out an anchor that does not come back.
623
+ */
624
+ function anchorResolvesToSelf(station, stations) {
625
+ if (station == null || !Array.isArray(stations)) return false;
626
+ const a = anchorOf(station);
627
+ if (a === null) return false;
628
+ const back = resolveAnchorInStations(parseAnchor(a), stations);
629
+ return back.ok === true && back.station != null && back.station.id === station.id;
630
+ }
631
+ /**
632
+ * Parse an anchor string. Pure: returns a discriminated result, never throws.
633
+ * Forms follow the grammar above; every legal form has a branch.
634
+ */
635
+ function parseAnchor(raw) {
636
+ if (typeof raw !== "string") return { ok: false, reason: "invalid" };
637
+ let body = raw.trim();
638
+ if (body.startsWith("#")) body = body.slice(1);
639
+ const hash = body.indexOf("#");
640
+ const hint = hash >= 0 ? body.slice(hash + 1) : null;
641
+ if (hash >= 0) body = body.slice(0, hash);
642
+ if (!body.startsWith(ANCHOR_PREFIX)) return { ok: false, reason: "invalid", hint };
643
+ const tail = body.slice(ANCHOR_PREFIX.length);
644
+ // e<seq>
645
+ const e = /^e(\d+(?:\.\d+)?)$/.exec(tail);
646
+ if (e !== null) {
647
+ const n = Number(e[1]);
648
+ if (!Number.isSafeInteger(n) || n < 0) return { ok: false, reason: "synthetic", hint };
649
+ return { ok: true, form: "e", seq: n, hint };
650
+ }
651
+ // Turns and steps are 1-based everywhere in the projection, so `t0` / `s0`
652
+ // cannot name any record. Accepting them looked harmless — resolution said
653
+ // "not-loaded" — but that answer makes the view PAGE FOR OLDER HISTORY
654
+ // (up to 40 round trips) chasing a record that can never arrive, and then
655
+ // reports "只有前 40 页" instead of "this anchor is malformed". Long digit
656
+ // runs overflowed to Infinity with the same effect. `e<seq>` already guarded
657
+ // with `Number.isSafeInteger`; these two branches did not.
658
+ const posInt = (v) => {
659
+ const n = Number(v);
660
+ return Number.isSafeInteger(n) && n >= 1 ? n : null;
661
+ };
662
+ // p<turn>s<step>[c<callId>]
663
+ const p = /^p(\d+)s(\d+)(?:c(.+))?$/.exec(tail);
664
+ if (p !== null) {
665
+ const turn = posInt(p[1]);
666
+ const step = posInt(p[2]);
667
+ if (turn === null || step === null) return { ok: false, reason: "invalid", hint };
668
+ return {
669
+ ok: true, form: "p",
670
+ turn, step,
671
+ callId: p[3] === void 0 ? null : p[3],
672
+ hint
673
+ };
674
+ }
675
+ // t<turn>s<step>
676
+ const tt = /^t(\d+)s(\d+)$/.exec(tail);
677
+ if (tt !== null) {
678
+ const turn = posInt(tt[1]);
679
+ const step = posInt(tt[2]);
680
+ if (turn === null || step === null) return { ok: false, reason: "invalid", hint };
681
+ return { ok: true, form: "t", turn, step, hint };
682
+ }
683
+ // c<callId>
684
+ if (tail.startsWith("c") && tail.length > 1) return { ok: true, form: "c", callId: tail.slice(1), hint };
685
+ return { ok: false, reason: "invalid", hint };
686
+ }
687
+ /** Map a parsed anchor onto a station, or explain why it cannot be resolved. */
688
+ function resolveAnchorInStations(parsed, stations) {
689
+ if (parsed == null || parsed.ok !== true) {
690
+ return { ok: false, reason: parsed?.reason ?? "invalid" };
691
+ }
692
+ if (parsed.form === "e") {
693
+ // A seq is shared by DIFFERENT node kinds: a turn-error is stamped with the
694
+ // turn's end seq, which can equal the assistant message's seq. A plain
695
+ // `find` then returned the error node for `tvp1:e2` while the user meant the
696
+ // step. Prefer a step (the thing anchors are normally copied from); otherwise
697
+ // take the first match as before.
698
+ const hits = stations.filter((st) => st.anchorSeq === parsed.seq);
699
+ if (hits.length === 0) return { ok: false, reason: "not-loaded", seq: parsed.seq };
700
+ const preferred = hits.find((st) => st.kind === "step") ?? hits[0];
701
+ return { ok: true, station: preferred };
702
+ }
703
+ if (parsed.form === "c") {
704
+ for (const st of stations) {
705
+ if (st.kind === "step") {
706
+ for (const c of st.cells ?? []) {
707
+ if (c.kind !== "tool" || c.callId !== parsed.callId) continue;
708
+ if (Number.isSafeInteger(st.anchorSeq)) return { ok: true, station: st };
709
+ return { ok: false, reason: "synthetic-tool" };
710
+ }
711
+ continue;
712
+ }
713
+ // A tool result with no matching call becomes its own `orphan-tool`
714
+ // station, which carries the callId itself. Skipping it here made
715
+ // `tvp1:c<id>` fail on a result that was plainly loaded and visible.
716
+ if (st.kind === "orphan-tool" && st.callId === parsed.callId) {
717
+ if (Number.isSafeInteger(st.anchorSeq)) return { ok: true, station: st };
718
+ return { ok: false, reason: "synthetic-tool" };
719
+ }
720
+ }
721
+ return { ok: false, reason: "not-loaded" };
722
+ }
723
+ if (parsed.form === "p" || parsed.form === "t") {
724
+ const hit = stations.find((st) => st.kind === "step"
725
+ && Number.isFinite(st.turn) && st.turn === parsed.turn
726
+ && (st.turnStep ?? st.stepNo) === parsed.step
727
+ && (parsed.callId == null || (st.cells ?? []).some((c) => c.kind === "tool" && c.callId === parsed.callId)));
728
+ if (hit === void 0) return { ok: false, reason: "not-loaded" };
729
+ if (parsed.form === "t" && hit.anchorSeq !== null) {
730
+ return { ok: true, station: hit, upgraded: `e${hit.anchorSeq}` };
731
+ }
732
+ return { ok: true, station: hit, synthetic: hit.synthetic === true };
733
+ }
734
+ return { ok: false, reason: "invalid" };
735
+ }
736
+ /**
737
+ * G2: how far back must we page before this anchor can resolve?
738
+ * Returns the smallest seq that must be covered, or null when paging cannot help
739
+ * (synthetic / unparseable anchors never become durable by loading more history).
740
+ * `e<seq>` and `c<callId>` carry an exact seq; `p`/`t` only carry a turn/step
741
+ * coordinate, so they ask for the whole history (0) and rely on re-resolve.
742
+ */
743
+ /**
744
+ * How far back paging must go for this anchor, expressed as a seq floor.
745
+ *
746
+ * `0` means "no bound known, keep paging" — which is what `p` / `t` anchors
747
+ * used to return unconditionally. That turned the floor check in the paging
748
+ * loop into a no-op for turn/step anchors: a deep `p3s1` link on a long session
749
+ * pulled the maximum number of pages even when the oldest loaded station was
750
+ * already older than the requested turn. Turn anchors carry a turn number, and
751
+ * turns only ever grow with seq, so "have we loaded turn N" is decidable
752
+ * without knowing seqs: see `anchorTurnFloor`.
753
+ */
754
+ function anchorLoadTarget(parsed) {
755
+ if (parsed == null || parsed.ok !== true) return null;
756
+ if (parsed.form === "e") return Number.isSafeInteger(parsed.seq) && parsed.seq >= 0 ? parsed.seq : null;
757
+ if (parsed.form === "c") return 0;
758
+ if (parsed.form === "p" || parsed.form === "t") return 0;
759
+ return null;
760
+ }
761
+ /**
762
+ * Oldest TURN currently loaded, or null when no station carries one.
763
+ *
764
+ * Used to stop back-paging for `p` / `t` anchors: seql is monotonic with turns,
765
+ * so once the window reaches at or below the requested turn, further pages
766
+ * cannot reveal anything newer.
767
+ */
768
+ function anchorTurnFloor(stations) {
769
+ let floor = null;
770
+ for (const st of stations) {
771
+ if (typeof st.turn !== "number" || !Number.isFinite(st.turn)) continue;
772
+ if (floor === null || st.turn < floor) floor = st.turn;
773
+ }
774
+ return floor;
775
+ }
776
+ /**
777
+ * True when the loaded window provably extends back past the anchor's turn, so
778
+ * paging further back cannot help. Conservative: unknown → false (keep paging).
779
+ */
780
+ function anchorCoveredByWindow(parsed, stations) {
781
+ if (parsed == null || parsed.ok !== true) return false;
782
+ if (parsed.form === "p" || parsed.form === "t") {
783
+ if (!Number.isFinite(parsed.turn)) return false;
784
+ // Seeing ANY station of the target turn proves nothing: a window can hold
785
+ // only turn 2's last step, and stopping there reported "not loaded" even
786
+ // though turn 2's earlier steps were one page away.
787
+ // The turn is covered when either
788
+ // (a) a strictly EARLIER turn is loaded — paging back cannot add steps to
789
+ // turn N any more, or
790
+ // (b) this turn's first step is already present.
791
+ const floor = anchorTurnFloor(stations);
792
+ const hasTargetTurn = stations.some((st) => Number.isFinite(st.turn) && st.turn === parsed.turn);
793
+ // The target turn must actually be in the window before its first step can
794
+ // prove anything; otherwise a future turn would look "covered".
795
+ if (!hasTargetTurn) return false;
796
+ if (floor !== null && floor < parsed.turn) return true;
797
+ // Nothing here: "the target turn is the oldest turn loaded" is NOT proof
798
+ // that no earlier page holds more of it (N1 covers exactly that: turn 9's
799
+ // earlier steps can still be one page back). Paging stops on `hasMore`
800
+ // instead — see the caller, which already refuses to page past history.
801
+ // The 101 s / 3,360-station deep link was the CALLER searching all history
802
+ // for a step that never existed, which shows up as an honest "not loaded".
803
+ return stations.some((st) => st.kind === "step"
804
+ && Number.isFinite(st.turn) && st.turn === parsed.turn
805
+ && (st.turnStep ?? st.stepNo) === 1);
806
+ }
807
+ if (parsed.form === "e") {
808
+ if (!Number.isSafeInteger(parsed.seq)) return false;
809
+ const floor = anchorSeqFloor(stations);
810
+ return floor !== null && floor <= parsed.seq;
811
+ }
812
+ return false;
813
+ }
814
+ /**
815
+ * Smallest anchorSeq currently loaded — i.e. the lower edge of the window.
816
+ * Used to stop back-paging as soon as the requested seq is covered, instead of
817
+ * blindly pulling pages until the session start. Returns null when unknown.
818
+ */
819
+ function anchorSeqFloor(stations) {
820
+ let floor = null;
821
+ for (const st of stations) {
822
+ const n = st.anchorSeq;
823
+ if (!Number.isSafeInteger(n) || n < 0) continue;
824
+ if (floor === null || n < floor) floor = n;
825
+ }
826
+ return floor;
827
+ }
828
+ /**
829
+ * Run one hash-navigation step for an incoming anchor.
830
+ * Returns `changed: false` when the URL already carries this anchor — the caller
831
+ * must then skip history.replaceState, otherwise every render pushes a new entry.
832
+ * (Strings are primitives: `a === b` cannot tell "rebuilt" from "identity", so the
833
+ * decision is returned as an explicit flag instead of being inferred by the caller.)
834
+ */
835
+ /**
836
+ * Deduplicate concurrent work keyed by a string.
837
+ *
838
+ * The anchor search is started from two places (the URL/focus effect and the
839
+ * typed-Enter handler) and its driving effect also depends on `N`, which grows
840
+ * with every page it loads — so one request could spawn several concurrent
841
+ * 40-page searches. Each keeps its own page counter, which is why the progress
842
+ * text was seen moving backwards (25 -> 23 -> 11 -> 20) while one `t2s1` lookup
843
+ * ran for 133 s; the host's own network time for that run was only 8.7 s.
844
+ *
845
+ * Only an IDENTICAL key is blocked: a different anchor must be allowed to
846
+ * supersede an in-flight one, otherwise typing a new target would be silently
847
+ * ignored while the old search kept paging.
848
+ */
849
+ function createFlightGuard() {
850
+ let current = "";
851
+ return {
852
+ tryStart(key) {
853
+ const k = String(key ?? "");
854
+ if (k !== "" && current === k) return false;
855
+ current = k;
856
+ return true;
857
+ },
858
+ finish(key) {
859
+ // Keyed: a request that was superseded must not clear the newer one.
860
+ if (current === String(key ?? "")) current = "";
861
+ },
862
+ current() { return current; }
863
+ };
864
+ }
865
+ function nextHashFor(hash, anchor) {
866
+ // Normalize exactly the way `parseAnchor` does, or the URL written here is
867
+ // not the one that will be read back. `parseAnchor` trims and strips ONE
868
+ // leading `#`, so pasting `#tvp1:e2` (a form it accepts) was mirrored as
869
+ // `##tvp1:e2` — a link that resolved fine in this tab and reported "锚点格式
870
+ // 无法识别" for whoever opened it.
871
+ let body = typeof anchor === "string" ? anchor.trim() : "";
872
+ if (body.startsWith("#")) body = body.slice(1);
873
+ if (body === "") return { hash, changed: false };
874
+ const want = `#${body}`;
875
+ if (hash === want) return { hash, changed: false };
876
+ return { hash: want, changed: true };
877
+ }
878
+ /**
879
+ * Fold a TrajectorySnapshot into the timeline tree:
880
+ * root -> turns -> chronological stations (user messages / steps / special events)
881
+ * plus a flattened station list, aggregate stats, and per-step raw request info.
882
+ * @param snap - the `views.get("trajectory")` snapshot (or an empty stand-in).
883
+ * @param t - bound translate function for this plugin's namespace.
884
+ */
885
+ /**
886
+ * Coerce an untrusted collection into an array of non-null objects.
887
+ * The snapshot is produced by another plugin: a single malformed entry must
888
+ * degrade into "that entry is skipped", never into a crashed view.
889
+ */
890
+ function safeList(value) {
891
+ if (!Array.isArray(value)) return [];
892
+ const out = [];
893
+ for (const item of value) if (item != null && typeof item === "object") out.push(item);
894
+ return out;
895
+ }
896
+ /**
897
+ * Node kinds this projector consumes. Kept next to the projector, not in the
898
+ * component, so the "what is unknown" answer can never drift from "what is drawn".
899
+ * Order matters only for readability.
900
+ */
901
+ /**
902
+ * Node kinds this plugin can place on the timeline. `unknown` is here on
903
+ * purpose: it is the contract's own documented fallback surface
904
+ * (`UnknownSurfaceNode`, "known unsupported developer events throw before
905
+ * fallback selection"), so a session that contains one is a session with an
906
+ * unsupported EVENT, not a drifted CONTRACT. Counting it as drift made a
907
+ * single exotic event blank the whole view with "版本不兼容".
908
+ */
909
+ const KNOWN_NODE_KINDS = new Set([
910
+ "user", "steering", "context", "assistant", "tool-result",
911
+ "compaction", "turn-error", "model-retry", "turn-max-tokens", "command",
912
+ "unknown"
913
+ ]);
914
+ /**
915
+ * Drift guard. The snapshot comes from another plugin whose contract we do not own:
916
+ * a renamed field or kind must degrade LOUDLY, not into a plausible-looking trace.
917
+ * Returns { ok, problems[] } where `problems` are machine-readable tokens.
918
+ */
919
+ function snapshotContract(snap) {
920
+ const problems = [];
921
+ if (snap == null || typeof snap !== "object") return { ok: false, problems: ["no-snapshot"] };
922
+ if (!("eventNodes" in snap)) problems.push("missing-eventNodes");
923
+ else if (!Array.isArray(snap.eventNodes)) problems.push("eventNodes-not-array");
924
+ else {
925
+ let badShape = 0;
926
+ for (const n of snap.eventNodes) {
927
+ if (n == null || typeof n !== "object" || typeof n.kind !== "string" || n.kind === ""
928
+ || typeof n.seq !== "number" || !Number.isFinite(n.seq)) badShape += 1;
929
+ // A node whose `content` is present but not an array is malformed enough to
930
+ // matter: the trajectory helpers iterate it. Catching it here lets the view
931
+ // show its incompatibility notice instead of throwing mid-render.
932
+ else if (n.content !== void 0 && n.content !== null && !Array.isArray(n.content)) badShape += 1;
933
+ }
934
+ if (badShape > 0) problems.push("bad-node-shape");
935
+ }
936
+ return { ok: problems.length === 0, problems };
937
+ }
938
+ /**
939
+ * True when a NON-EMPTY snapshot produced no usable node at all. That is the
940
+ * signature of a contract rename (field names stay valid, kinds change), which
941
+ * must be reported as incompatibility rather than "no data yet".
942
+ */
943
+ function isEverythingUnknown(nodes, stats) {
944
+ const total = Array.isArray(nodes) ? nodes.length : 0;
945
+ if (total === 0 || stats == null) return false;
946
+ const dropped = (Number(stats.unknown) || 0) + (Number(stats.invalid) || 0);
947
+ return dropped >= total;
948
+ }
949
+ /** Count nodes we received but cannot place: unknown kind, or structurally unusable. */
950
+ function unknownNodeStats(nodes) {
951
+ let unknown = 0;
952
+ let invalid = 0;
953
+ const kinds = [];
954
+ for (const n of Array.isArray(nodes) ? nodes : []) {
955
+ if (n == null || typeof n !== "object") { invalid += 1; continue; }
956
+ const kind = n.kind;
957
+ if (typeof kind !== "string" || kind === "") { invalid += 1; continue; }
958
+ if (!KNOWN_NODE_KINDS.has(kind)) { unknown += 1; if (kinds.length < 5 && !kinds.includes(kind)) kinds.push(kind); }
959
+ }
960
+ return { unknown, invalid, kinds };
961
+ }
962
+ /**
963
+ * `seq` is the ONE field the whole projection orders by, compares and pastes
964
+ * into ids, and it arrives from a persisted log. Normally a number — but a
965
+ * truncated or hand-edited record can carry a BigInt or a Symbol, and JS THROWS
966
+ * on those: `Symbol - number`, `Symbol > number` and even a template literal all
967
+ * raise TypeError. A review tool whose entire promise is "show me what the log
968
+ * recorded" must not refuse to render a log *because* it is damaged, so pin the
969
+ * field to a number once, at the entry, and let everything downstream stay simple.
970
+ */
971
+ /**
972
+ * `Number(x)` THROWS on a Symbol, and `step` arrives from the same untrusted log
973
+ * `seq` does. Three call sites coerced it directly, so one damaged record took
974
+ * down the whole projection. Same contract as before (`|| 1`, clamped to >= 1),
975
+ * but total for every input.
976
+ */
977
+ function stepOf(v) {
978
+ const n = typeof v === "symbol" ? NaN : Number(v);
979
+ return Math.max(1, Number.isFinite(n) ? Math.trunc(n) : 1);
980
+ }
981
+ function seqOf(v) {
982
+ if (Number.isSafeInteger(v)) return v;
983
+ // BigInt is comparable and printable, so keep it when it still fits a double.
984
+ if (typeof v === "bigint") { const n = Number(v); return Number.isSafeInteger(n) ? n : null; }
985
+ return null;
986
+ }
987
+ function deriveTraceTree(snap, t) {
988
+ const rawNodes = safeList(snap?.eventNodes);
989
+ // Only pay for the copy when a node actually needs repairing: a well-formed
990
+ // snapshot (the normal case) proceeds with the objects the host handed us.
991
+ let nodes = rawNodes;
992
+ for (const n of rawNodes) {
993
+ if (n !== null && typeof n === "object" && !Number.isSafeInteger(n.seq)) {
994
+ nodes = rawNodes.map((m) => (m !== null && typeof m === "object" && !Number.isSafeInteger(m.seq)
995
+ ? { ...m, seq: seqOf(m.seq) } : m));
996
+ break;
997
+ }
998
+ }
999
+ nodes = nodes.slice().sort((a, b) => (Number.isFinite(a.seq) ? a.seq : -Infinity) - (Number.isFinite(b.seq) ? b.seq : -Infinity));
1000
+ // Drift diagnostics: computed once, surfaced by the view (never silently dropped).
1001
+ const contract = snapshotContract(snap);
1002
+ const nodeStats = unknownNodeStats(Array.isArray(snap?.eventNodes) ? snap.eventNodes : []);
1003
+ // A callId is NOT globally unique in a log that was merged, replayed or written
1004
+ // by a buggy client: the same id can appear in two different turns. A plain
1005
+ // `Map<callId, result>` kept only the LAST one, so turn 1's call displayed
1006
+ // turn 2's output (wrong data) while turn 2's call was dropped by the
1007
+ // claim-based dedupe below (lost data) — silently, which is the one outcome
1008
+ // this view promises never to produce. Keep every result per id, ordered by
1009
+ // seq, and let each call claim the next unconsumed one.
1010
+ const resultsById = new Map();
1011
+ for (const n of nodes) {
1012
+ // Index EVERY callId, not just strings. A Map keys on any value, and skipping
1013
+ // non-strings meant a Symbol/BigInt id could never be claimed: the call showed
1014
+ // an empty result AND the very same result also surfaced as an orphan — the
1015
+ // same output twice, one of the copies looking like "no output".
1016
+ if (n.kind !== "tool-result") continue;
1017
+ const list = resultsById.get(n.callId);
1018
+ if (list === void 0) resultsById.set(n.callId, [n]);
1019
+ else list.push(n);
1020
+ }
1021
+ for (const list of resultsById.values()) list.sort((a, b) => a.seq - b.seq);
1022
+ // Results already paired with a call. The orphan pass must skip these, and a
1023
+ // second call with the same id must take a DIFFERENT result.
1024
+ const consumedResults = new Set();
1025
+ const runningById = new Map();
1026
+ // Same reason as `resultsById`: key on the raw value so a non-string id still pairs.
1027
+ for (const c of safeList(snap?.runningCalls)) if (c !== null && typeof c === "object") runningById.set(c.callId, c);
1028
+ const schemasById = snap?.callSchemas instanceof Map ? snap.callSchemas : new Map();
1029
+ // Keyed by `${turn}:${callId}`, NOT by callId alone.
1030
+ //
1031
+ // A callId can repeat across turns in a merged/replayed log. Deduping on the
1032
+ // bare id dropped the SECOND call entirely: its cell was never created and its
1033
+ // result surfaced as an unrelated "orphan" in whatever turn the seq happened to
1034
+ // fall in. The cell ids below (`t${callId}`) stay call-keyed, so a per-turn
1035
+ // scope produces distinct React keys too.
1036
+ // Claims per `${turn}:${callId}`. A plain Set gave the durable loop "first wins":
1037
+ // two DISTINCT tool-call blocks sharing an id in one turn made the second vanish.
1038
+ // The same guard is still needed across the three sources (durable / running /
1039
+ // partial) so one call is not attached twice, hence a claim COUNT.
1040
+ // NESTED, not a flattened string key. Every attempt to encode `turn` + `callId`
1041
+ // into one string collided with a real id that happened to look like the encoding:
1042
+ // `String(callId)` merged two distinct `Symbol("same")`s, then a `#1` string id met
1043
+ // the ordinal `#1`, then a `~1` string id met the `~`-prefixed ordinal. A string id
1044
+ // may be ANY sequence of characters, so no prefix is safe. Outer key = turn, inner
1045
+ // key = the raw callId, where Map's SameValueZero keeps `"~1"` and any Symbol apart
1046
+ // by construction rather than by luck.
1047
+ const attachedCalls = new Map();
1048
+ const callsInTurn = (turn) => {
1049
+ const k = String(turn);
1050
+ let m = attachedCalls.get(k);
1051
+ if (m === void 0) { m = new Map(); attachedCalls.set(k, m); }
1052
+ return m;
1053
+ };
1054
+ const claimCall = (turn, callId) => {
1055
+ const m = callsInTurn(turn);
1056
+ const n = m.get(callId) ?? 0;
1057
+ m.set(callId, n + 1);
1058
+ return n;
1059
+ };
1060
+ const claimedCall = (turn, callId) => {
1061
+ const m = attachedCalls.get(String(turn));
1062
+ return m !== void 0 && (m.get(callId) ?? 0) > 0;
1063
+ };
1064
+ /**
1065
+ * Cell ids double as React keys, and `callId` comes straight from the log. A
1066
+ * template literal calls ToString, which THROWS on a Symbol — one damaged
1067
+ * tool-call id took the entire projection down (`Cannot convert a Symbol value
1068
+ * to a string`). String ids are kept VERBATIM because anchors are built from
1069
+ * them (tvp1:c<callId>); anything else gets an ordinal that is unique within the
1070
+ * station, which is all a React key needs.
1071
+ */
1072
+ // Cells double as React keys inside a step. Two DISTINCT tool-call blocks in one
1073
+ // message may legitimately share a callId (a merged/retried log), and with the
1074
+ // old helper the ordinal was dropped for string ids — so `tdup` appeared twice and
1075
+ // React warned about duplicate keys (measured: `["tdup","tdup"]`). Suffix the
1076
+ // ordinal unconditionally; it is what keeps same-id siblings apart.
1077
+ const cellId = (prefix, callId, ordinal) => `${prefix}${typeof callId === "string" ? callId : `?${String(ordinal)}`}#${String(ordinal)}`;
1078
+ /** Next unclaimed result for this call id, or undefined when none is left. */
1079
+ const takeResult = (callId) => {
1080
+ const list = resultsById.get(callId);
1081
+ if (list === void 0) return void 0;
1082
+ for (const r of list) {
1083
+ if (consumedResults.has(r)) continue;
1084
+ consumedResults.add(r);
1085
+ return r;
1086
+ }
1087
+ return void 0;
1088
+ };
1089
+
1090
+ // Requests keyed by `${turn}:${step}`, with prompt inheritance across
1091
+ // requests (a header in force covers steps until a newer one replaces it).
1092
+ // A merged/retried log can carry MORE THAN ONE request for the same turn:step.
1093
+ // A plain `Map.set` kept only the last, silently losing status/usage/prompt from
1094
+ // the earlier one. Keep every request per key in log order; a station consumes the
1095
+ // LATEST one (so a step retried after a failure still shows its final status), and
1096
+ // leftovers stay in the bucket. They are counted as unplaced ONLY when the key
1097
+ // matched no station at all — a leftover on a matched key is a retry, not a miss.
1098
+ const requestsByStep = new Map();
1099
+ // Keys that actually FOUND a station. A leftover in such a bucket is an earlier
1100
+ // attempt at a step that exists (a retry); a leftover in an unmatched bucket is a
1101
+ // request with no step at all. Only the latter belongs in `unplacedRequests`.
1102
+ const matchedRequestKeys = new Set();
1103
+ const compactionReqs = [];
1104
+ let unplaceableRequests = 0;
1105
+ // Keys that actually found a step. Anything left over is a request the log
1106
+ // recorded but this view could not place; it must be reported, not discarded.
1107
+ {
1108
+ // `startSeq` comes from the host record. Subtracting a Symbol throws
1109
+ // (`Cannot convert a Symbol value to a number`) and a BigInt throws too, so one
1110
+ // malformed request used to take the entire projection down before any station
1111
+ // existed. Sort only on finite numbers; anything else keeps its relative order
1112
+ // at the end instead of entering the comparator arithmetic.
1113
+ const seqOrder = (v) => (typeof v === "bigint" ? Number(v) : v);
1114
+ // `safeList` DROPS non-object rows (as it must: every other caller needs objects),
1115
+ // and the request list then simply omitted them. Nodes report their unusable rows
1116
+ // through `nodeStats.invalid`; requests now count theirs too, so a log carrying a
1117
+ // null/stranded row is described instead of quietly shortened.
1118
+ const rawReqs = Array.isArray(snap?.requests) ? snap.requests : [];
1119
+ const reqs = [];
1120
+ for (const raw of rawReqs) {
1121
+ if (raw == null || typeof raw !== "object") { unplaceableRequests +=1; continue; }
1122
+ reqs.push(raw);
1123
+ }
1124
+ reqs.sort((a, b) => {
1125
+ const x = seqOrder(a?.startSeq);
1126
+ const y = seqOrder(b?.startSeq);
1127
+ const xf = Number.isFinite(x);
1128
+ const yf = Number.isFinite(y);
1129
+ if (xf && yf) return x - y;
1130
+ if (xf) return -1;
1131
+ if (yf) return 1;
1132
+ return 0;
1133
+ });
1134
+ let lastPrompt = null;
1135
+ for (const r of reqs) {
1136
+ // A non-object row (null, a bare string) cannot be shown OR counted, and
1137
+ // `safeList` only guarantees the container is an array. Nodes already report
1138
+ // their unusable rows through `nodeStats.invalid`; requests must not vanish
1139
+ // just because the row is not shaped like a request.
1140
+ if (r == null || typeof r !== "object") { unplaceableRequests +=1; continue; }
1141
+ if (r?.purpose === "compaction") { compactionReqs.push(r); continue; }
1142
+ // A request we cannot even key (no `turn`, or a purpose this build does
1143
+ // not know) used to be dropped on the floor. The view promises that what
1144
+ // the log recorded is shown, including the parts it cannot interpret —
1145
+ // unknown NODE kinds already become visible "unknown" stations, so
1146
+ // requests get the same treatment (a counted, explained notice).
1147
+ if (r?.purpose !== "assistant" || typeof r.turn !== "number") { unplaceableRequests += 1; continue; }
1148
+ const prompt = r.prompt ?? lastPrompt;
1149
+ if (r.prompt != null) lastPrompt = r.prompt;
1150
+ // A request whose `step` is not a usable number cannot be keyed:
1151
+ // `${turn}:${step}` threw "Cannot convert a Symbol value to a string"
1152
+ // on a hostile record and took the whole projection down. Count it as
1153
+ // unplaceable instead — the same honest notice the other unkeyable rows get.
1154
+ const stepNo = seqOf(r.step);
1155
+ if (stepNo === null) { unplaceableRequests +=1; continue; }
1156
+ const rk = `${String(r.turn)}:${String(stepNo)}`;
1157
+ const bucket = requestsByStep.get(rk);
1158
+ const entry = { req: r, prompt };
1159
+ if (bucket === void 0) requestsByStep.set(rk, [entry]);
1160
+ else bucket.push(entry);
1161
+ }
1162
+ }
1163
+
1164
+ const turns = [];
1165
+ const turnMap = new Map();
1166
+ // Ids double as React keys and as the selection pin's identity, so they must be
1167
+ // unique AND stable across rebuilds. Shared by the user/context stations and the
1168
+ // synthetic steps: both are numbered from data that a malformed log can repeat.
1169
+ const usedStationIds = new Set();
1170
+ let pendingUser = [];
1171
+ let lastTurnEntry = null;
1172
+ const ensureTurn = (turn, seq) => {
1173
+ let e = turnMap.get(turn);
1174
+ if (e === void 0) {
1175
+ e = { turn, user: [], stations: [], seq: seq ?? Number.MAX_SAFE_INTEGER };
1176
+ turnMap.set(turn, e);
1177
+ turns.push(e);
1178
+ lastTurnEntry = e;
1179
+ }
1180
+ if (e.seq > seq) e.seq = seq;
1181
+ return e;
1182
+ };
1183
+ const flushUser = (turn, seq) => {
1184
+ if (pendingUser.length === 0) return;
1185
+ const e = ensureTurn(turn, seq);
1186
+ for (const u of pendingUser) {
1187
+ e.user.push(u);
1188
+ e.stations.push({ id: u.id, kind: "user", who: u.who, text: u.text, time: u.time, seq: u.seq });
1189
+ }
1190
+ pendingUser = [];
1191
+ };
1192
+
1193
+ for (const n of nodes) {
1194
+ if (n.kind === "user" || n.kind === "steering" || n.kind === "context") {
1195
+ // The contract puts the label at `producer.label` (ContextProducerView),
1196
+ // NOT under `provenance`. Reading the wrong path meant every context row
1197
+ // rendered a bare "上下文注入" and the producer name was never shown.
1198
+ const producerLabel = typeof n.producer?.label === "string" && n.producer.label !== "" ? n.producer.label : null;
1199
+ const who = n.kind === "context"
1200
+ ? `${t("node.context")}${producerLabel !== null ? ` · ${producerLabel}` : ""}`
1201
+ : t("node.user");
1202
+ // Ids double as React keys and as the selection pin's identity, so they must
1203
+ // be unique. Two user nodes sharing a seq (a malformed/duplicated log)
1204
+ // produced two `u7` stations; suffix the duplicate instead of colliding.
1205
+ const baseId = `u${n.seq}`;
1206
+ let entryId = baseId;
1207
+ for (let dupe = 2; usedStationIds.has(entryId); dupe += 1) entryId = `${baseId}-${String(dupe)}`;
1208
+ usedStationIds.add(entryId);
1209
+ const entry = { id: entryId, who, text: textOfContent(n.content, t), time: n.time, seq: n.seq, steering: n.kind === "steering" };
1210
+ // A user turn that has no assistant/special event yet must still be shown.
1211
+ // Start its turn here when the node declares one; otherwise park it in
1212
+ // `pendingUser` and let the next assistant message's turn adopt it.
1213
+ //
1214
+ // Do NOT fall back to `partial.turn`: a streaming partial describes the
1215
+ // turn being GENERATED right now, so borrowing its number filed every
1216
+ // historical user message under the newest turn. rc.2 UserMessageNode has
1217
+ // no `turn` field at all, so that fallback applied to almost every user
1218
+ // message — one session's turns came out as [user(t2), step(t2),
1219
+ // user(t2), step(t1)] with the old turn ordered last.
1220
+ const declared = typeof n.turn === "number" ? n.turn : null;
1221
+ if (declared !== null) {
1222
+ const e = ensureTurn(declared, n.seq);
1223
+ e.user.push(entry);
1224
+ e.stations.push({ id: entry.id, kind: "user", who: entry.who, text: entry.text, time: entry.time, seq: entry.seq });
1225
+ continue;
1226
+ }
1227
+ pendingUser.push(entry);
1228
+ continue;
1229
+ }
1230
+ if (n.kind === "assistant") {
1231
+ const turn = typeof n.turn === "number" ? n.turn : 0;
1232
+ flushUser(turn, n.seq);
1233
+ const e = ensureTurn(turn, n.seq);
1234
+ const step = stepOf(n.step);
1235
+ let st = e.steps?.get(step);
1236
+ if (st === void 0) {
1237
+ if (e.steps === void 0) e.steps = new Map();
1238
+ st = newStepState(n.seq);
1239
+ e.steps.set(step, st);
1240
+ }
1241
+ if (st.seq > n.seq) st.seq = n.seq;
1242
+ // Durable anchor: only when this node is a real persisted assistant
1243
+ // message (messageId present) AND its seq is a non-negative safe
1244
+ // integer. Synthetic interruption fallbacks carry a fractional seq
1245
+ // and no messageId, so they never qualify.
1246
+ if (typeof n.messageId === "string" && n.messageId !== "" && Number.isSafeInteger(n.seq) && n.seq >= 0) {
1247
+ if (st.anchorSeq === null || st.anchorSeq > n.seq) st.anchorSeq = n.seq;
1248
+ }
1249
+ if (Number.isFinite(n.time) && (st.time === null || st.time > n.time)) st.time = n.time;
1250
+ if (n.interrupted === true) st.interrupted = true;
1251
+ if (st.modelHint === null) {
1252
+ // The current DSH contract (records.d.ts, AssistantMessageNode) carries the
1253
+ // model on `providerMetadata`; `provenance` was a guess. Reading only the
1254
+ // wrong fields meant a node whose request had been windowed away showed
1255
+ // NO model at all, even though the log recorded one.
1256
+ const mh = n.requestConfig?.model ?? n.providerMetadata?.model ?? n.provenance?.model;
1257
+ if (typeof mh === "string" && mh !== "") st.modelHint = mh;
1258
+ }
1259
+ // `blocks` can contain nulls in a malformed payload; reading `.kind` off
1260
+ // null threw TypeError inside the fold and took the whole view down.
1261
+ for (const b of Array.isArray(n.blocks) ? n.blocks : []) {
1262
+ if (b == null || typeof b !== "object") continue;
1263
+ if (b.kind === "text" && typeof b.text === "string" && b.text !== "") {
1264
+ st.cells.push({ id: `a${n.seq}${st.cells.length}`, kind: "assistant", text: b.text, thinking: "" });
1265
+ } else if (b.kind === "reasoning" && typeof b.text === "string" && b.text !== "") {
1266
+ st.cells.push({ id: `r${n.seq}${st.cells.length}`, kind: "assistant", text: "", thinking: b.text });
1267
+ } else if (b.kind === "image" || b.kind === "other") {
1268
+ // AssistantBlock also has `image` and `other`. The adapters are
1269
+ // text-only today, but dropping these silently made a future image
1270
+ // reply look like the model produced nothing. Surface a placeholder
1271
+ // instead; it is honest and costs one cell.
1272
+ const label = b.kind === "image" ? t("block.image")
1273
+ : `${t("block.other")}${typeof b.block === "object" && b.block !== null && typeof b.block.type === "string" ? ` · ${b.block.type}` : ""}`;
1274
+ st.cells.push({ id: `o${n.seq}${st.cells.length}`, kind: "assistant", text: label, thinking: "" });
1275
+ } else if (b.kind !== "text" && b.kind !== "reasoning" && b.kind !== "tool-call") {
1276
+ // A kind this build does not know (the host adding one is exactly how
1277
+ // `image`/`other` arrived). These used to fall through the chain and
1278
+ // vanish, so a future block type would render as "the model said
1279
+ // nothing". Name it instead of guessing at its content.
1280
+ st.cells.push({ id: `u${n.seq}${st.cells.length}`, kind: "assistant", text: `${t("block.unknown")} · ${String(b.kind)}`, thinking: "" });
1281
+ } else if (b.kind === "tool-call") {
1282
+ // every durable block is a real call, even with a repeated id
1283
+ claimCall(turn, b.callId);
1284
+ const res = takeResult(b.callId);
1285
+ const isRunning = res === undefined && runningById.has(b.callId);
1286
+ if (isRunning) st.live = true;
1287
+ const schema = schemasById.get(b.callId);
1288
+ // A tool cannot plausibly run for a day. When the log is reloaded or
1289
+ // reparsed, `callTime` can be missing or belong to a different pass, and
1290
+ // `res.time - res.callTime` then spans the reload gap: one step in a real
1291
+ // session reported 78,834,620 ms (21.9 h) for a 3-second bash call, and
1292
+ // that single value dominated the "tool time" KPI. Treat anything past
1293
+ // the ceiling as "unknown" rather than "enormous" — the card shows the
1294
+ // step span either way, and a wrong number is worse than no number.
1295
+ const rawDur = res != null && Number.isFinite(res.callTime) && Number.isFinite(res.time) ? Math.max(0, res.time - res.callTime) : null;
1296
+ const dur = rawDur !== null && rawDur <= TOOL_DUR_CEILING_MS ? rawDur : null;
1297
+ st.toolMs += dur ?? 0;
1298
+ st.toolCount += 1;
1299
+ if (res?.isError === true) st.hasError = true;
1300
+ st.cells.push({
1301
+ id: cellId("t", b.callId, st.cells.length),
1302
+ kind: "tool",
1303
+ callId: b.callId,
1304
+ name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
1305
+ args: argsText(b.argsRaw),
1306
+ resultText: res !== undefined ? blocksText(res.content, t) : "",
1307
+ isError: res?.isError === true,
1308
+ errorName: res?.error?.name,
1309
+ durationMs: dur,
1310
+ running: isRunning,
1311
+ subCalls: mapSubCalls(res?.subCalls, t),
1312
+ schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1313
+ });
1314
+ }
1315
+ }
1316
+ if (n.timing != null) {
1317
+ st.timingRecorded = true;
1318
+ if (Number.isFinite(n.timing.stepStartTime) && Number.isFinite(n.timing.firstTokenTime)) {
1319
+ st.ttftMs = Math.max(0, n.timing.firstTokenTime - n.timing.stepStartTime);
1320
+ }
1321
+ if (Number.isFinite(n.timing.stepStartTime) && (st.startMs === null || st.startMs > n.timing.stepStartTime)) st.startMs = n.timing.stepStartTime;
1322
+ if (Number.isFinite(n.timing.completedTime) && (st.endMs === null || st.endMs < n.timing.completedTime)) st.endMs = n.timing.completedTime;
1323
+ if (Number.isFinite(n.timing.firstTokenTime) && st.firstTokMs === null) st.firstTokMs = n.timing.firstTokenTime;
1324
+ }
1325
+ const u = normalizeUsage(n.usage);
1326
+ if (u !== null) st.usage = u;
1327
+ }
1328
+ }
1329
+ // Any user message still pending has no owning turn yet (e.g. a snapshot whose
1330
+ // only content is a user message). Give it its own turn rather than dropping it
1331
+ // or attaching it to an unrelated earlier turn.
1332
+ if (pendingUser.length > 0) {
1333
+ // A user message still pending at EOF belongs to the turn being generated
1334
+ // when there is one — that IS its owning turn. Only without a partial do we
1335
+ // have to invent the next number, otherwise a window holding just the
1336
+ // current input filed it under turn 1 while the live step sat in turn 5.
1337
+ const lastTurnNo = maxTurnOf(turns);
1338
+ const partialTurn = typeof snap?.partial?.turn === "number" ? snap.partial.turn : null;
1339
+ const ownTurn = partialTurn !== null ? partialTurn
1340
+ : lastTurnEntry === null ? 1 : lastTurnNo + 1;
1341
+ // A steering message is not new input: it interjects into the turn that is
1342
+ // already running. The official layout keeps it in `lastAssistantTurn` when
1343
+ // no assistant follows it (`node.kind === 'steering' ? lastAssistantTurn : …`),
1344
+ // so filing it under `ownTurn` invented a whole extra turn at the tail of
1345
+ // the window. Only differs when nothing follows: with a following assistant
1346
+ // both implementations agree on that assistant's turn.
1347
+ const steeringTurn = partialTurn !== null ? partialTurn
1348
+ : lastTurnNo >= 1 ? lastTurnNo : 1;
1349
+ const steeringItems = pendingUser.filter((u) => u.steering === true);
1350
+ const inputItems = pendingUser.filter((u) => u.steering !== true);
1351
+ if (inputItems.length > 0) {
1352
+ const e = ensureTurn(ownTurn, inputItems[0].seq);
1353
+ for (const u of inputItems) { e.user.push(u); e.stations.push({ id: u.id, kind: "user", who: u.who, text: u.text, time: u.time, seq: u.seq }); }
1354
+ }
1355
+ if (steeringItems.length > 0) {
1356
+ const e = ensureTurn(steeringTurn, steeringItems[0].seq);
1357
+ for (const u of steeringItems) { e.user.push(u); e.stations.push({ id: u.id, kind: "user", who: u.who, text: u.text, time: u.time, seq: u.seq }); }
1358
+ }
1359
+ pendingUser = [];
1360
+ }
1361
+
1362
+ // In-flight tool calls not already attached via an assistant block.
1363
+ for (const c of safeList(snap?.runningCalls)) {
1364
+ // A numeric STRING turn ("1") used to fail `typeof === "number"` and the whole
1365
+ // in-flight call vanished, with no station and no warning. `seqOf` already
1366
+ // normalises the same hostile shapes for nodes; use it here too. A genuinely
1367
+ // unusable turn still falls back to 0 rather than disappearing.
1368
+ const cTurn = seqOf(c.turn) ?? 0;
1369
+ if (claimedCall(cTurn, c.callId)) continue;
1370
+ // Claim the call id here as well: the streaming partial can describe the very
1371
+ // same in-flight call, and without claiming it the tool is counted twice
1372
+ // (once from runningCalls, once from the partial block).
1373
+ claimCall(cTurn, c.callId);
1374
+ const e = ensureTurn(cTurn, c.time);
1375
+ const step = stepOf(c.step);
1376
+ if (e.steps === void 0) e.steps = new Map();
1377
+ let st = e.steps.get(step);
1378
+ if (st === void 0) {
1379
+ st = newStepState(c.time);
1380
+ st.time = Number.isFinite(c.time) ? c.time : null;
1381
+ e.steps.set(step, st);
1382
+ }
1383
+ st.live = true;
1384
+ st.toolCount += 1;
1385
+ const schema = schemasById.get(c.callId);
1386
+ st.cells.push({
1387
+ id: cellId("t", c.callId, st.cells.length), kind: "tool", callId: c.callId,
1388
+ name: typeof c.name === "string" && c.name !== "" ? c.name : t("node.tool"),
1389
+ args: argsText(c.argsRaw),
1390
+ resultText: "", isError: false, errorName: void 0, durationMs: null,
1391
+ running: true,
1392
+ subCalls: mapSubCalls(c.subCalls, t),
1393
+ schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1394
+ });
1395
+ }
1396
+
1397
+ // Streaming partial assistant (in-flight reply of the current step).
1398
+ const p = snap?.partial;
1399
+ if (p != null && Array.isArray(p.blocks) && p.blocks.length > 0) {
1400
+ const turn = typeof p.turn === "number" ? p.turn : 0;
1401
+ const seq = lastTurnEntry != null ? lastTurnEntry.seq + 0.5 : 0.5;
1402
+ flushUser(turn, seq);
1403
+ const e = ensureTurn(turn, seq);
1404
+ const step = stepOf(p.step);
1405
+ if (e.steps === void 0) e.steps = new Map();
1406
+ let st = e.steps.get(step);
1407
+ if (st === void 0) {
1408
+ st = newStepState(seq);
1409
+ e.steps.set(step, st);
1410
+ }
1411
+ st.live = true;
1412
+ // The in-flight reply carries `timing` too (rc.2 TrajectoryPartialAssistant
1413
+ // exposes it and the real builder fills it). Ignoring it made the header
1414
+ // claim "timing not recorded" for a step whose start and first token were
1415
+ // already known. There is no completedTime yet, so endMs stays null — the
1416
+ // duration is simply not known until the step finishes.
1417
+ if (p.timing != null) {
1418
+ const pt = p.timing;
1419
+ if (Number.isFinite(pt.stepStartTime)) {
1420
+ st.timingRecorded = true;
1421
+ if (st.startMs === null || st.startMs > pt.stepStartTime) st.startMs = pt.stepStartTime;
1422
+ }
1423
+ if (Number.isFinite(pt.stepStartTime) && Number.isFinite(pt.firstTokenTime)) {
1424
+ st.ttftMs = Math.max(0, pt.firstTokenTime - pt.stepStartTime);
1425
+ st.timingRecorded = true;
1426
+ }
1427
+ if (Number.isFinite(pt.firstTokenTime) && st.firstTokMs === null) st.firstTokMs = pt.firstTokenTime;
1428
+ if (Number.isFinite(pt.completedTime) && (st.endMs === null || st.endMs < pt.completedTime)) st.endMs = pt.completedTime;
1429
+ }
1430
+ // Dedupe by CONTENT, not by kind. `existingKinds.has("assistant")` meant the
1431
+ // second text block of a streaming reply was dropped entirely: the parser
1432
+ // emits one `text` block per content part, so a reply that resumed after a
1433
+ // tool call lost everything after its first part. Only an identical string
1434
+ // (the durable copy already present) is suppressed.
1435
+ // Snapshot of what the DURABLE blocks already put on this step. The partial is
1436
+ // a re-send of the in-flight reply, so repeating durable content must not
1437
+ // duplicate it — but distinct partial parts must not collapse into each other.
1438
+ const durableTexts = new Set(st.cells.filter((c) => c.kind === "assistant" && typeof c.thinking === "string" && c.thinking === "").map((c) => c.text));
1439
+ const durableThinking = new Set(st.cells.filter((c) => typeof c.thinking === "string" && c.thinking !== "").map((c) => c.thinking));
1440
+ // Same guard as the durable loop: a null/primitive block must be skipped, not
1441
+ // throw. The 0.9.26 fix hardened `blocks` in the durable path only, so a
1442
+ // malformed PARTIAL still crashed the entire view (found by fuzzing).
1443
+ for (const b of Array.isArray(p.blocks) ? p.blocks : []) {
1444
+ if (b == null || typeof b !== "object") continue;
1445
+ if (b.kind === "text" && typeof b.text === "string" && b.text !== "" && !durableTexts.has(b.text)) {
1446
+ // Dedupe ONLY against what the durable node already contributed. Two
1447
+ // separate blocks that happen to contain the same string are still two
1448
+ // parts; adding each to the dedupe set made the second vanish.
1449
+ st.cells.push({ id: `pa${st.cells.length}`, kind: "assistant", text: b.text, thinking: "" });
1450
+ } else if (b.kind === "reasoning" && typeof b.text === "string" && b.text !== ""
1451
+ // Tool cells carry no `thinking` at all, and `undefined !== ""` is true —
1452
+ // so any tool call in this step made the reasoning look already-taken
1453
+ // and it was dropped. Only cells that actually hold prose count.
1454
+ && !durableThinking.has(b.text)) {
1455
+ st.cells.push({ id: `pr${st.cells.length}`, kind: "assistant", text: "", thinking: b.text });
1456
+ } else if (b.kind === "image" || b.kind === "other") {
1457
+ // The durable loop got this placeholder in the same change; the STREAMING
1458
+ // branch was missed, so a live image reply showed an empty step until the
1459
+ // turn finalized. Both loops must agree.
1460
+ const plabel = b.kind === "image" ? t("block.image")
1461
+ : `${t("block.other")}${typeof b.block === "object" && b.block !== null && typeof b.block.type === "string" ? ` · ${b.block.type}` : ""}`;
1462
+ st.cells.push({ id: `po${st.cells.length}`, kind: "assistant", text: plabel, thinking: "" });
1463
+ } else if (b.kind !== "text" && b.kind !== "reasoning" && b.kind !== "tool-call") {
1464
+ // Same forward-compat rule as the durable loop: a kind this build does not
1465
+ // know must be NAMED, not dropped. The streaming branch was missed when the
1466
+ // durable one got the placeholder, so a live `file`/future block showed an
1467
+ // empty step (measured: cells [] for {kind:"future"} and {kind:"file"}).
1468
+ st.cells.push({ id: `pu${st.cells.length}`, kind: "assistant", text: `${t("block.unknown")} · ${String(b.kind)}`, thinking: "" });
1469
+ } else if (b.kind === "tool-call") {
1470
+ if (claimedCall(turn, b.callId)) continue;
1471
+ claimCall(turn, b.callId);
1472
+ const res = takeResult(b.callId);
1473
+ st.toolCount += 1;
1474
+ if (res?.isError === true) st.hasError = true;
1475
+ const schema = schemasById.get(b.callId);
1476
+ st.cells.push({
1477
+ id: cellId("t", b.callId, st.cells.length), kind: "tool", callId: b.callId,
1478
+ name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
1479
+ args: argsText(b.argsRaw),
1480
+ resultText: res !== undefined ? blocksText(res.content, t) : "",
1481
+ isError: res?.isError === true,
1482
+ errorName: res?.error?.name,
1483
+ durationMs: null, running: res === undefined,
1484
+ subCalls: mapSubCalls(res?.subCalls, t),
1485
+ schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1486
+ });
1487
+ }
1488
+ }
1489
+ }
1490
+
1491
+ // Special events: compaction / turn-error / retry / max-tokens / command.
1492
+ // Compaction/command nodes carry no turn number: seat them by seq range —
1493
+ // the turn whose first event seq is the greatest one not after the event.
1494
+ const turnsBySeq = [...turns].sort((a, b) => a.seq - b.seq);
1495
+ // Binary search: `turnsBySeq` is already sorted. The previous linear scan ran
1496
+ // once per compaction/special event, so a log with many of both cost
1497
+ // O(events x turns) — measured 105 ms at 1000 turns, and it grows from there.
1498
+ const turnForSeq = (s) => {
1499
+ let lo = 0;
1500
+ let hi = turnsBySeq.length - 1;
1501
+ let best = null;
1502
+ while (lo <= hi) {
1503
+ const mid = (lo + hi) >> 1;
1504
+ if (turnsBySeq[mid].seq <= s) { best = turnsBySeq[mid]; lo = mid + 1; }
1505
+ else hi = mid - 1;
1506
+ }
1507
+ return best ?? lastTurnEntry ?? ensureTurn(0, s);
1508
+ };
1509
+ const consumedCompactionReqs = new Set();
1510
+ // Index the exact-replacementSeq match instead of scanning every request per
1511
+ // compaction. Both the exact lookup and the timed fallback iterated the whole
1512
+ // request list, so N compactions x M requests was quadratic: a synthetic
1513
+ // 2000-compaction log cost 315 ms and the visit count grew from 5,050 to
1514
+ // 2,001,000. The map makes the exact hit O(1); the timed fallback still scans,
1515
+ // but only when there is no exact match.
1516
+ const compactionByReplacement = new Map();
1517
+ for (const r of compactionReqs) {
1518
+ if (Number.isSafeInteger(r.replacementSeq) && !compactionByReplacement.has(r.replacementSeq)) {
1519
+ compactionByReplacement.set(r.replacementSeq, r);
1520
+ }
1521
+ }
1522
+ for (const n of nodes) {
1523
+ if (n.kind === "compaction") {
1524
+ const e = turnForSeq(n.seq);
1525
+ // Pair with the compaction provider request: exact replacementSeq
1526
+ // match first, else the nearest unconsumed compaction request that
1527
+ // completed within a minute before this marker landed.
1528
+ let matched = compactionByReplacement.get(n.seq);
1529
+ if (matched !== void 0 && consumedCompactionReqs.has(matched)) matched = void 0;
1530
+ if (matched === void 0) {
1531
+ // A duplicate request may hold the same replacementSeq; fall back to a
1532
+ // scan only in that (rare) case.
1533
+ matched = compactionReqs.find((r) => !consumedCompactionReqs.has(r) && r.replacementSeq === n.seq);
1534
+ }
1535
+ if (matched === void 0 && Number.isFinite(n.time)) {
1536
+ let best = null;
1537
+ for (const r of compactionReqs) {
1538
+ if (consumedCompactionReqs.has(r)) continue;
1539
+ const doneAt = Number.isFinite(r.completedAt) ? r.completedAt : r.startedAt;
1540
+ if (!Number.isFinite(doneAt)) continue;
1541
+ const gap = n.time - doneAt;
1542
+ if (gap < -5000 || gap > 60000) continue;
1543
+ if (best === null || Math.abs(gap) < Math.abs(best.gap)) best = { r, gap };
1544
+ }
1545
+ if (best !== null) matched = best.r;
1546
+ }
1547
+ let crequest = null;
1548
+ if (matched !== void 0) {
1549
+ consumedCompactionReqs.add(matched);
1550
+ crequest = {
1551
+ status: matched.status,
1552
+ startedAt: Number.isFinite(matched.startedAt) ? matched.startedAt : null,
1553
+ durationMs: Number.isFinite(matched.startedAt) && Number.isFinite(matched.completedAt) ? Math.max(0, matched.completedAt - matched.startedAt) : null,
1554
+ config: matched.requestConfig ?? null,
1555
+ usage: normalizeUsage(matched.usage),
1556
+ outputText: blocksText(matched.rawOutput, t) || blocksText(matched.summary, t) || ""
1557
+ };
1558
+ }
1559
+ e.stations.push({
1560
+ id: `m${n.seq}`, kind: "compaction", time: n.time, seq: n.seq,
1561
+ summary: asText(n.summary),
1562
+ // Raw values here reached a template literal (`${station.count}`), which
1563
+ // calls ToString and THROWS on a Symbol — the step-copy Markdown took the
1564
+ // whole render down. Non-integers become null, which the callers already
1565
+ // treat as "not recorded".
1566
+ count: Number.isSafeInteger(n.shadowedItemCount) ? n.shadowedItemCount : null,
1567
+ tokens: Number.isSafeInteger(n.shadowedTokenCount) ? n.shadowedTokenCount : null,
1568
+ crequest,
1569
+ label: t("node.compaction")
1570
+ });
1571
+ } else if (n.kind === "turn-error") {
1572
+ const e = ensureTurn(typeof n.turn === "number" ? n.turn : 0, n.seq);
1573
+ e.stations.push({
1574
+ id: `e${n.seq}`, kind: "error", time: n.time, seq: n.seq,
1575
+ message: asText(n.message), code: typeof n.code === "string" ? n.code : void 0, label: t("node.error")
1576
+ });
1577
+ } else if (n.kind === "model-retry") {
1578
+ const e = ensureTurn(typeof n.turn === "number" ? n.turn : 0, n.seq);
1579
+ e.stations.push({
1580
+ id: `y${n.seq}`, kind: "retry", time: n.time, seq: n.seq,
1581
+ message: asText(n.failure?.message), code: typeof n.failure?.code === "string" ? n.failure.code : void 0,
1582
+ retry: n.retry, maxRetries: n.maxRetries, provider: asText(n.provider),
1583
+ retryState: asText(n.retryState), label: t("node.retry")
1584
+ });
1585
+ } else if (n.kind === "turn-max-tokens") {
1586
+ const e = ensureTurn(typeof n.turn === "number" ? n.turn : 0, n.seq);
1587
+ e.stations.push({ id: `x${n.seq}`, kind: "maxTokens", time: n.time, seq: n.seq, label: t("node.maxTokens") });
1588
+ } else if (n.kind === "command") {
1589
+ const e = turnForSeq(n.seq);
1590
+ e.stations.push({
1591
+ id: `c${n.seq}`, kind: "command", time: n.time, seq: n.seq,
1592
+ name: asText(n.name) !== "" ? asText(n.name) : `/${asText(n.commandId) || "?"}`, args: asText(n.args),
1593
+ outcomeKind: n.outcome?.kind ?? null, outcomeText: asText(n.outcome?.text),
1594
+ label: t("node.command")
1595
+ });
1596
+ } else if (n.kind === "unknown") {
1597
+ // The contract's own fallback surface. Rendering nothing would hide a
1598
+ // real event that exists in the session log, and the review tool's whole
1599
+ // promise is that what the log recorded is what the reader sees.
1600
+ const e = turnForSeq(n.seq);
1601
+ e.stations.push({
1602
+ id: `k${n.seq}`, kind: "unknown", time: n.time, seq: n.seq,
1603
+ eventType: typeof n.type === "string" ? n.type : "",
1604
+ payload: safeJsonPreview(n.data, UNKNOWN_PAYLOAD_LIMIT),
1605
+ label: t("node.unknown")
1606
+ });
1607
+ }
1608
+ }
1609
+
1610
+ // O1: orphan tool results. A `tool-result` whose matching `tool-call` is not in
1611
+ // the loaded window (or whose `call` is null after truncation) is never attached
1612
+ // above, so it would otherwise vanish from the timeline entirely. The official
1613
+ // view renders these too (via `resultAsText(resultPreview)`), so dropping them
1614
+ // silently would under-report work actually done.
1615
+ {
1616
+ // Station ids double as React keys AND as the selection pin's identity, so they
1617
+ // must be unique across rebuilds **and stable when older history is prepended**.
1618
+ // A running ordinal does neither: adding one earlier node renumbered every later
1619
+ // orphan (`ot1000` became `ot1001`), so the pinned selection pointed elsewhere
1620
+ // after paging. Count per seq value instead — an earlier seq cannot change the
1621
+ // counter of a later one.
1622
+ const orphanSeen = new Map();
1623
+ const orphans = nodes
1624
+ // Use the RESULT objects, not the call ids: with a duplicated id the id
1625
+ // is "attached" while the second result was never shown anywhere.
1626
+ // ANY unconsumed tool-result becomes an orphan. The old filter also required
1627
+ // a STRING callId, so a Symbol/BigInt id made the whole record vanish with
1628
+ // no station and no warning.
1629
+ .filter((n) => n.kind === "tool-result" && !consumedResults.has(n))
1630
+ .sort((a, b) => a.seq - b.seq);
1631
+ const orphanId = (seq) => {
1632
+ const seen = orphanSeen.get(seq) ?? 0;
1633
+ orphanSeen.set(seq, seen + 1);
1634
+ // `seqOf` pins an unusable seq to null, so `null` is the common malformed case;
1635
+ // a readable "x" beats describing it as "[object]".
1636
+ const base = seq == null ? "x"
1637
+ : (typeof seq === "number" && Number.isFinite(seq) ? String(seq)
1638
+ : (typeof seq === "string" && seq !== "" ? seq : displayCallId(seq)));
1639
+ return `ot${base}${seen === 0 ? "" : `_${String(seen)}`}`;
1640
+ };
1641
+ for (const n of orphans) {
1642
+ const e = turnForSeq(n.seq);
1643
+ const text = blocksText(n.content, t);
1644
+ const subCalls = mapSubCalls(n.subCalls, t);
1645
+ // Anchor issuance is centralized in the "special stations" branch below
1646
+ // (it re-checks `seq` for integer-ness and stamps anchorKey/synthetic).
1647
+ e.stations.push({
1648
+ // `id` was `ot${callId}`: two orphan results sharing an id produced the
1649
+ // SAME React key (measured `["otdup","otdup"]`), and a non-string callId
1650
+ // threw inside the template literal. Key on seq, which is stable, and
1651
+ // suffix only the duplicates of that SAME seq.
1652
+ id: orphanId(n.seq),
1653
+ kind: "orphan-tool",
1654
+ seq: n.seq,
1655
+ time: n.time,
1656
+ callId: displayCallId(n.callId),
1657
+ // `ToolResultNode.name` is always present per the contract; `call` may be
1658
+ // null when the window cut the tool-call away. Reading only `call.name`
1659
+ // mislabelled such a result as an anonymous "tool" and made it
1660
+ // unfindable by search.
1661
+ name: typeof n.name === "string" && n.name !== "" ? n.name
1662
+ : (typeof n.call?.name === "string" && n.call.name !== "" ? n.call.name : t("node.tool")),
1663
+ args: typeof n.call?.argsRaw === "string" ? n.call.argsRaw : "",
1664
+ resultText: text,
1665
+ // `blocksText` already covers text / image / reasoning blocks.
1666
+ // Official view computes its preview from `node.content` too
1667
+ // (summarizeResult); there is no `resultPreview` field on the node.
1668
+ displayText: text !== "" ? text : (n.error?.code ?? n.error?.name ?? ""),
1669
+ isError: n.isError === true,
1670
+ subCalls,
1671
+ hasError: n.isError === true
1672
+ });
1673
+ }
1674
+ }
1675
+
1676
+ // Assemble turns into ordered station lists + attach requests.
1677
+ // Sort turns by their earliest known seq first (turn 0 "system events" may
1678
+ // be created late by a stray compaction/command and would otherwise land last).
1679
+ for (const e of turns) {
1680
+ let mseq = e.seq;
1681
+ for (const st of e.stations) if (st.seq < mseq) mseq = st.seq;
1682
+ for (const st of e.steps?.values() ?? []) if (st.seq < mseq) mseq = st.seq;
1683
+ e.minSeq = mseq;
1684
+ }
1685
+ turns.sort((a, b) => a.minSeq - b.minSeq);
1686
+ let seq = 0;
1687
+ const nid = () => `n${seq++}`;
1688
+ let stepCounter = 0;
1689
+ let currentStepNo = null;
1690
+ const stations = [];
1691
+ let stats = { turns: 0, steps: 0, tools: 0, errors: 0, toolMs: 0, tokensIn: 0, tokensOut: 0, running: 0, maxToolMs: 0, lastModel: null };
1692
+
1693
+ const turnNodes = turns.map((e) => {
1694
+ const pieceList = [];
1695
+ for (const s of e.stations) {
1696
+ pieceList.push({ at: s.seq, kind: s.kind, data: s });
1697
+ if (s.kind === "orphan-tool") {
1698
+ stats.tools += 1;
1699
+ if (s.isError === true) stats.errors += 1;
1700
+ }
1701
+ }
1702
+ const stepNums = e.steps === void 0 ? [] : [...e.steps.keys()].sort((a, b) => a - b);
1703
+ for (const s of stepNums) {
1704
+ const st = e.steps.get(s);
1705
+ pieceList.push({ at: st.seq, kind: "step", data: st, stepNum: s });
1706
+ }
1707
+ pieceList.sort((a, b) => a.at - b.at);
1708
+
1709
+ let toolCount = 0;
1710
+ let stepMs = 0;
1711
+ let errCount = 0;
1712
+ for (const st of e.steps?.values() ?? []) {
1713
+ toolCount += st.toolCount;
1714
+ stepMs += st.toolMs;
1715
+ if (st.hasError) errCount += 1;
1716
+ for (const c of st.cells) if (c.kind === "tool" && c.running === true) stats.running += 1;
1717
+ if (st.toolMs > stats.maxToolMs) stats.maxToolMs = st.toolMs;
1718
+ }
1719
+ const children = [];
1720
+ for (const piece of pieceList) {
1721
+ if (piece.kind === "user") {
1722
+ const uSeq = Number.isSafeInteger(piece.data.seq) && piece.data.seq >= 0 ? piece.data.seq : null;
1723
+ const station = {
1724
+ id: piece.data.id, kind: "user", who: piece.data.who, text: piece.data.text, time: piece.data.time,
1725
+ anchorSeq: uSeq,
1726
+ anchorKey: uSeq !== null ? `e${uSeq}` : null,
1727
+ synthetic: uSeq === null,
1728
+ };
1729
+ children.push(station);
1730
+ stations.push(station);
1731
+ continue;
1732
+ }
1733
+ if (piece.kind === "step") {
1734
+ const st = piece.data;
1735
+ stepCounter += 1;
1736
+ // The LABEL must be the per-turn number, for exactly the reason the
1737
+ // station label was: `stepCounter` is a window-wide counter, so the
1738
+ // header read "current step 3" and then "current step 11" for the SAME
1739
+ // streaming reply once older history was paged in. `stepCounter` stays
1740
+ // as the internal ordinal (and `totalSteps`), the user-visible number
1741
+ // comes from `turnStep`.
1742
+ // Use `piece.stepNum`: the station object is built further below, so
1743
+ // `st` (the raw accumulator) has no `turnStep` yet — reading it here
1744
+ // silently fell through to the window-wide counter.
1745
+ if (st.live === true && currentStepNo === null) {
1746
+ currentStepNo = Number.isFinite(piece.stepNum) ? piece.stepNum : stepCounter;
1747
+ }
1748
+ // attach request info (messages are reconstructed lazily in the component)
1749
+ const key = `${e.turn}:${piece.stepNum}`;
1750
+ const bucket = requestsByStep.get(key);
1751
+ // Every request in the bucket is a real record. Consume the LATEST one:
1752
+ // the original `Map.set` kept the last attempt, so a step retried after a
1753
+ // failure showed the final (successful) status. Taking the earliest here
1754
+ // silently flipped such a step back to "error". Leftovers are retained in
1755
+ // the bucket but are NOT counted as unplaced: they are superseded retries
1756
+ // of this same step, not requests without a step.
1757
+ const found = bucket === void 0 ? void 0 : bucket.pop();
1758
+ let request = null;
1759
+ if (found !== void 0) {
1760
+ matchedRequestKeys.add(key);
1761
+ const r = found.req;
1762
+ request = {
1763
+ status: r.status,
1764
+ error: r.error,
1765
+ retry: r.retry,
1766
+ maxRetries: r.maxRetries,
1767
+ retryDelayMs: r.retryDelayMs,
1768
+ startedAt: r.startedAt,
1769
+ completedAt: r.completedAt,
1770
+ durationMs: r.startedAt != null && r.completedAt != null && Number.isFinite(r.completedAt) ? Math.max(0, r.completedAt - r.startedAt) : null,
1771
+ config: r.requestConfig ?? found.prompt?.config ?? null,
1772
+ usage: normalizeUsage(r.usage) ?? st.usage,
1773
+ prompt: found.prompt != null ? {
1774
+ system: found.prompt.system ?? "",
1775
+ tools: Array.isArray(found.prompt.tools) ? found.prompt.tools : [],
1776
+ systemChars: typeof found.prompt.system === "string" ? found.prompt.system.length : 0
1777
+ } : null,
1778
+ promptChangeKind: r.promptChange?.kind ?? null,
1779
+ promptDiff: promptDiffOf(r.promptChange, found.prompt),
1780
+ startSeq: r.startSeq ?? null
1781
+ };
1782
+ }
1783
+ // The KPI must agree with the detail panel. The detail shows
1784
+ // `normalizeUsage(r.usage) ?? st.usage`, but the overview only summed the
1785
+ // REQUEST usage — so a step whose only usage came from the assistant node
1786
+ // displayed tokens in the detail and 0 in the KPI (measured 10/7 vs 0/0).
1787
+ // Sum the SAME effective usage exactly once, so a step that carries both
1788
+ // is not double-counted.
1789
+ const effUsage = request !== null ? request.usage : st.usage;
1790
+ if (effUsage != null) { stats.tokensIn += effUsage.input; stats.tokensOut += effUsage.output; }
1791
+ const cfgModel = request?.config?.model;
1792
+ if (typeof cfgModel === "string" && cfgModel !== "") stats.lastModel = cfgModel;
1793
+ else if (st.modelHint !== null) stats.lastModel = st.modelHint;
1794
+ const stepDurMs = st.startMs !== null && st.endMs !== null ? Math.max(0, st.endMs - st.startMs) : null;
1795
+ const decodeRate = decodeRateOf(st.usage ?? request?.usage ?? null, st.firstTokMs, st.endMs);
1796
+ const meta = [];
1797
+ if (st.toolCount > 0) meta.push(`${st.toolCount}${t("meta.tools")}`);
1798
+ // Same unit as the KPI tile: on one screen "9.2 min" and "114,774 ms" force
1799
+ // the reader to convert in their head. Exact ms belongs in the detail panel.
1800
+ if (st.toolCount > 0 && st.toolMs > 0) meta.push(`${t("meta.toolDur")} ${fmtDur(st.toolMs)}`);
1801
+ // Label the measure. A bare "103,686 ms" next to a KPI called "tool time"
1802
+ // reads as if it should add up to that KPI, but this chip is the STEP
1803
+ // span (model time + tool time + gaps). Two different quantities sharing
1804
+ // one word is what made the totals look inconsistent.
1805
+ if (stepDurMs !== null) meta.push(`${t("meta.stepDur")} ${fmtDur(stepDurMs)}`);
1806
+ else if (st.ttftMs != null && Number.isFinite(st.ttftMs)) meta.push(`${t("chip.ttft")} ${fmtDur(st.ttftMs)}`);
1807
+ if (st.usage !== null && st.usage.input + st.usage.output > 0) meta.push(`${fmtTokens(st.usage.input + st.usage.output)}${t("meta.tokens")}`);
1808
+ if (st.live === true) meta.push(t("chip.running"));
1809
+ if (st.interrupted) meta.push(t("chip.interrupted"));
1810
+ if (st.hasError) meta.push(t("meta.error"));
1811
+ const anchorSeq = st.anchorSeq;
1812
+ const station = {
1813
+ // Identity must survive the window growing backwards. `stepCounter`
1814
+ // is a running count, so prepending history renumbered every step
1815
+ // and the selection pin (which keys on id) silently pointed at a
1816
+ // different record. anchorSeq is the stable, persisted identity;
1817
+ // fall back to the counter only for synthetic steps without one.
1818
+ // A synthetic step has no persisted seq, so its id used to embed
1819
+ // `stepCounter` — a WINDOW-wide running count. Prepending older
1820
+ // history then changed the id of the very step the reader had
1821
+ // selected, the pin's `findIndex` returned -1, and the panel
1822
+ // silently showed a DIFFERENT record at the same position. Turn +
1823
+ // per-turn step is stable across paging; duplicates (a malformed
1824
+ // log repeating a step number) get a suffix instead.
1825
+ id: anchorSeq !== null ? `s${anchorSeq}` : (() => {
1826
+ const base = `sx${String(e.turn)}-${String(piece.stepNum)}`;
1827
+ let cand = base;
1828
+ for (let dupe = 2; usedStationIds.has(cand); dupe += 1) cand = `${base}-${String(dupe)}`;
1829
+ usedStationIds.add(cand);
1830
+ return cand;
1831
+ })(),
1832
+ kind: "step",
1833
+ stepNo: stepCounter,
1834
+ // Per-turn step number. `stepNo` above is a WINDOW-wide running
1835
+ // counter, so turn 2's first step is 3 in a window that already
1836
+ // showed two turn-1 steps. Anchors are written per turn
1837
+ // (`tvp1:t2s1`), so they must resolve against this, not stepNo.
1838
+ turnStep: piece.stepNum,
1839
+ anchorSeq,
1840
+ anchorKey: anchorSeq !== null ? `e${anchorSeq}` : null,
1841
+ synthetic: anchorSeq === null,
1842
+ turn: e.turn,
1843
+ // Per-turn number: a window-wide counter renumbers every step
1844
+ // whenever older history is prepended.
1845
+ label: `${t("node.step")} ${piece.stepNum}`,
1846
+ detail: `${t("node.turn")} ${numOr(e.turn)} · ${t("node.step")} ${numOr(piece.stepNum)}`,
1847
+ meta,
1848
+ cells: st.cells,
1849
+ live: st.live === true,
1850
+ hasError: st.hasError,
1851
+ interrupted: st.interrupted,
1852
+ durationMs: stepDurMs,
1853
+ // G4-T1: exact step span from `timing.stepStartTime` / `completedTime`.
1854
+ // null when either side is absent (window edge, live step, no timing).
1855
+ startMs: st.startMs,
1856
+ endMs: st.endMs,
1857
+ timingRecorded: st.timingRecorded,
1858
+ ttftMs: st.ttftMs,
1859
+ decodeRate,
1860
+ modelHint: st.modelHint,
1861
+ request,
1862
+ time: st.time,
1863
+ };
1864
+ children.push(station);
1865
+ stats.steps += 1;
1866
+ stats.tools += st.toolCount;
1867
+ stats.toolMs += st.toolMs;
1868
+ if (st.hasError) stats.errors += 1;
1869
+ stations.push(station);
1870
+ continue;
1871
+ }
1872
+ // special stations
1873
+ const d = piece.data;
1874
+ let meta = [];
1875
+ if (d.kind === "compaction") {
1876
+ meta.push(t("chip.compacted"));
1877
+ if (Number.isSafeInteger(d.count)) meta.push(`${numOr(d.count)}${t("meta.steps")}`);
1878
+ if (d.tokens != null) meta.push(`${fmtTokens(d.tokens)}${t("meta.tokens")}`);
1879
+ } else if (d.kind === "error") {
1880
+ meta.push(t("meta.error"));
1881
+ stats.errors += 1;
1882
+ } else if (d.kind === "retry") {
1883
+ meta.push(t("chip.retry"));
1884
+ if (Number.isFinite(d.retry)) meta.push(`#${d.retry}`);
1885
+ } else if (d.kind === "command") {
1886
+ if (d.outcomeKind === "success") meta.push(t("status.done"));
1887
+ else if (d.outcomeKind === "error") {
1888
+ // A failed command is a failure in the session, so it belongs in the
1889
+ // error KPI — the label alone left the counter at zero.
1890
+ meta.push(t("meta.error"));
1891
+ stats.errors += 1;
1892
+ }
1893
+ }
1894
+ const specialAnchor = Number.isSafeInteger(d.seq) && d.seq >= 0 ? d.seq : null;
1895
+ const station = {
1896
+ id: d.id, kind: d.kind, label: d.label, meta, time: d.time, ...d,
1897
+ anchorSeq: specialAnchor,
1898
+ anchorKey: specialAnchor !== null ? `e${specialAnchor}` : null,
1899
+ synthetic: specialAnchor === null,
1900
+ };
1901
+ children.push(station);
1902
+ stations.push(station);
1903
+ }
1904
+ const m = [];
1905
+ if (stepNums.length > 0) m.push(`${stepNums.length}${t("meta.steps")}`);
1906
+ if (toolCount > 0) m.push(`${toolCount}${t("meta.tools")}`);
1907
+ return { id: `t${e.turn}`, kind: "turn", label: e.turn === 0 ? t("node.systemTurn") : `${t("node.turn")} ${numOr(e.turn)}`, meta: m, children };
1908
+ });
1909
+ // Attach the turn tag to the first station of each turn.
1910
+ {
1911
+ let turnIdx = 0;
1912
+ for (const turn of turnNodes) {
1913
+ const first = turn.children[0];
1914
+ if (first !== void 0 && first.tag === void 0) first.tag = turn.label;
1915
+ turnIdx += 1;
1916
+ }
1917
+ }
1918
+ const rootMeta = turns.length > 0 ? [`${turns.length}${t("meta.turns")}`] : [];
1919
+ stats.turns = turns.length;
1920
+ return {
1921
+ id: "root",
1922
+ kind: "root",
1923
+ label: t("view.root"),
1924
+ meta: rootMeta,
1925
+ children: turnNodes,
1926
+ stations,
1927
+ nodes,
1928
+ totalSteps: stepCounter,
1929
+ currentStepNo,
1930
+ stats,
1931
+ // drift diagnostics (see snapshotContract / unknownNodeStats)
1932
+ contract,
1933
+ nodeStats,
1934
+ // Requests the log carries that could not be attached to a step. Counted
1935
+ // rather than dropped, and shown in the header next to the node-drift chips.
1936
+ unplacedRequests: (() => {
1937
+ let n = unplaceableRequests;
1938
+ // A leftover entry in a MATCHED bucket is NOT an unplaced request: it is an
1939
+ // EARLIER attempt at the same turn:step (a retry). The step exists and shows
1940
+ // the latest attempt, exactly as the pre-bucket `Map.set` did — counting the
1941
+ // superseded attempt here produced a header warning on a perfectly healthy
1942
+ // retried log (measured: error+ok on one step → unplaced=1, old behavior 0).
1943
+ // A bucket that NEVER matched, however, is exactly "no matching step" and is
1944
+ // reported (that case has its own guard: EXPORTDRIFT1).
1945
+ for (const [key, bucket] of requestsByStep) if (!matchedRequestKeys.has(key)) n += bucket.length;
1946
+ // A compaction request whose marker is not in the loaded window (still
1947
+ // running, or the marker was paged out) matched no station at all. It was
1948
+ // collected into `compactionReqs` and then simply forgotten: the log
1949
+ // recorded a provider request and the view showed nothing. Count it here,
1950
+ // which is exactly what "no matching step" means for this surface.
1951
+ for (const r of compactionReqs) if (!consumedCompactionReqs.has(r)) n += 1;
1952
+ return n;
1953
+ })()
1954
+ };
1955
+ }
1956
+ /**
1957
+ * Station indices whose haystack contains the (lower-cased) query.
1958
+ *
1959
+ * The haystack is materialized here, on first search, instead of during the
1960
+ * fold. Lower-casing and joining every station's text was the single most
1961
+ * expensive part of building the tree (~109 ms of ~200 ms at 3,400 stations),
1962
+ * and it was paid on EVERY projection rebuild — including one per streaming
1963
+ * token — even though most sessions are never searched.
1964
+ */
1965
+ function matchStations(stations, query) {
1966
+ const q = String(query ?? "").trim().toLowerCase();
1967
+ if (q === "") return [];
1968
+ const out = [];
1969
+ for (let i = 0; i < stations.length; i += 1) {
1970
+ const hay = stationHay(stations[i]);
1971
+ if (hay !== "" && hay.includes(q)) out.push(i);
1972
+ }
1973
+ return out;
1974
+ }
1975
+ /**
1976
+ * One-line description for assistive tech: what this station IS, where it sits,
1977
+ * and what happened — the same three facts the visual layout conveys by shape,
1978
+ * position and colour.
1979
+ */
1980
+ /**
1981
+ * The station's own words, flattened to one line and capped.
1982
+ *
1983
+ * A station is a `role="option"`, and `aria-label` REPLACES the name that would
1984
+ * otherwise be computed from its descendants. So a label built only from the kind
1985
+ * ("用户", "错误") told a screen-reader user nothing about WHICH message it was —
1986
+ * every user turn announced identically, and an error turn never said what failed.
1987
+ * The whole point of an error station is its message.
1988
+ */
1989
+ function stationExcerpt(station) {
1990
+ if (station == null) return "";
1991
+ let raw = "";
1992
+ switch (station.kind) {
1993
+ case "user": raw = station.text; break;
1994
+ case "error":
1995
+ case "retry": raw = station.message; break;
1996
+ case "compaction": raw = station.summary; break;
1997
+ case "command": raw = [station.name, station.args].filter((x) => typeof x === "string" && x !== "").join(" "); break;
1998
+ case "unknown": raw = station.eventType; break;
1999
+ case "step": {
2000
+ // First thing the assistant actually said. `thinking` is skipped: it is
2001
+ // deliberately hidden behind a disclosure and should not be announced as
2002
+ // the name of the station.
2003
+ for (const c of Array.isArray(station.cells) ? station.cells : []) {
2004
+ if (c != null && c.kind === "assistant" && typeof c.text === "string" && c.text.trim() !== "") { raw = c.text; break; }
2005
+ }
2006
+ break;
2007
+ }
2008
+ default: break;
2009
+ }
2010
+ const flat = String(raw ?? "").replace(/\s+/g, " ").trim();
2011
+ return flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
2012
+ }
2013
+ function stationAriaLabel(station, position, total, t) {
2014
+ // Per-turn number: `stepNo` is a window-wide counter, so this label used to
2015
+ // read "步骤 1" and then "步骤 5" for the same station once older history was
2016
+ // loaded — a screen reader user would hear the record renumbered under them.
2017
+ const kind = station.kind === "step" ? `${t("node.step")} ${String(station.turnStep ?? station.stepNo)}`
2018
+ : station.kind === "user" ? t("node.user")
2019
+ : station.kind === "error" ? t("node.error")
2020
+ : station.kind === "compaction" ? t("node.compaction")
2021
+ : station.kind === "orphan-tool" ? t("node.orphanTool")
2022
+ : station.kind === "unknown" ? t("node.unknown")
2023
+ : String(station.kind);
2024
+ const parts = [`${position} / ${total}`, kind];
2025
+ if (station.kind === "step" && typeof station.turn === "number") parts.push(`${t("node.turn")} ${String(station.turn)}`);
2026
+ const meta = Array.isArray(station.meta) && station.meta.length > 0 ? station.meta.join(" · ") : "";
2027
+ if (meta !== "") parts.push(meta);
2028
+ if (station.hasError === true) parts.push(t("meta.error"));
2029
+ const excerpt = stationExcerpt(station);
2030
+ if (excerpt !== "") parts.push(excerpt);
2031
+ return parts.join(",");
2032
+ }
2033
+ /**
2034
+ * Cached lower-cased haystack for one station. Built at most once per station
2035
+ * object, and only when someone actually searches.
2036
+ * @param station - one station from the folded tree.
2037
+ * @returns the searchable text, or "" when the station carries none.
2038
+ */
2039
+ function stationHay(station) {
2040
+ if (station == null) return "";
2041
+ if (typeof station.hay === "string") return station.hay;
2042
+ // Derive from what the station already carries instead of materializing a
2043
+ // parallel array during the fold: the cells ARE the text, so copying them
2044
+ // into a second list was pure overhead paid on every projection rebuild.
2045
+ const parts = [station.label, station.who, station.text];
2046
+ if (Array.isArray(station.cells)) {
2047
+ for (const c of station.cells) {
2048
+ if (c.kind === "assistant") { parts.push(c.text, c.thinking); }
2049
+ else {
2050
+ parts.push(c.name, c.args, c.resultText, c.errorName);
2051
+ // Programmatic tool calls nest, and a search for a child's name must
2052
+ // find the step that made it. Only the top-level call was indexed.
2053
+ // Walk the whole chain: nesting is arbitrary depth, and a fixed two
2054
+ // levels left deeper calls findable in the panel but not by search.
2055
+ const collectSubs = (list, depth) => {
2056
+ if (depth > SUB_CALL_MAX_DEPTH) return;
2057
+ for (const sub of list ?? []) {
2058
+ parts.push(sub.name, sub.argsRaw, sub.resultText, sub.errorName);
2059
+ collectSubs(sub.subCalls, depth + 1);
2060
+ }
2061
+ };
2062
+ collectSubs(c.subCalls, 0);
2063
+ }
2064
+ }
2065
+ }
2066
+ parts.push(station.summary, station.message, station.name, station.args, station.outcomeText, station.displayText, station.eventType, station.payload);
2067
+ const hay = parts.filter((v) => typeof v === "string" && v !== "").join("\n").toLowerCase();
2068
+ station.hay = hay;
2069
+ return hay;
2070
+ }
2071
+ /**
2072
+ * D2: search only ever sees the loaded window, so the boundary must be visible.
2073
+ * Returns null when the whole session is already loaded (nothing to warn about).
2074
+ */
2075
+ function searchScopeNote(hasMore, loading, t) {
2076
+ if (hasMore !== true) return null;
2077
+ return loading === true ? t("search.scopeLoading") : t("search.scopePartial");
2078
+ }
2079
+ /**
2080
+ * Q2-3: build a single-step review pack. Copying the whole trace is too much when
2081
+ * a prompt author only wants "why did THIS step go wrong": merge the request config,
2082
+ * the prompt/tool diff, the tool results and the evidence levels into one block.
2083
+ */
2084
+ /**
2085
+ * One bullet per nested sub-call, recursively. Programmatic tool calling can nest
2086
+ * arbitrarily deep; printing only the first level silently dropped the rest, so
2087
+ * the export showed a call whose children — including failures — were invisible.
2088
+ */
2089
+ function pushSubLines(L, sub, level, t) {
2090
+ const indent = " ".repeat(Math.max(0, level));
2091
+ L.push(`${indent}- ↳ **${sub.name}**${sub.durationMs != null ? ` (${fmtMs(sub.durationMs)})` : ""}${sub.isError ? " ✗" : ""}${sub.argsRaw !== "" ? ` \`${String(sub.argsRaw).replace(/\s+/g, " ").slice(0, 120)}\`` : ""}`);
2092
+ if (sub.errorName != null && sub.errorName !== "") L.push(`${indent} - ✗ ${sub.errorName}`);
2093
+ // A truncated line must SAY it was truncated. The old `.slice(0,160)` produced a
2094
+ // bullet that looked complete, so a 500-char child result was silently shortened
2095
+ // in the export while the detail panel showed all of it — the export then could
2096
+ // not be used to reproduce the failure it was meant to document.
2097
+ if (sub.resultText !== "") {
2098
+ const text = String(sub.resultText);
2099
+ const first = text.split("\n")[0];
2100
+ const shown = first.slice(0, 160);
2101
+ const cut = shown.length < first.length || first.length < text.length;
2102
+ const unit = typeof t === "function" ? t("detail.chars") : "";
2103
+ L.push(`${indent} - ${shown}${cut ? ` …(${fmtInt(text.length)}${unit !== "" ? " " + unit : ""})` : ""}`);
2104
+ }
2105
+ for (const deeper of sub.subCalls ?? []) pushSubLines(L, deeper, level + 1, t);
2106
+ }
2107
+ function buildStepMarkdown(station, messages, hasMore, t) {
2108
+ const L = [];
2109
+ if (station == null) return "";
2110
+ // Same per-turn rule as everywhere else the step number is shown. `stepNo` is
2111
+ // the window-wide ordinal: exporting single steps produced "步骤 1.7" for a
2112
+ // reply that its own card calls "步骤 1", and the number changed depending on
2113
+ // how much history happened to be loaded when the export ran.
2114
+ const stepNum = Number.isFinite(station.turnStep) ? station.turnStep : station.stepNo;
2115
+ const head = station.kind === "step" ? `${t("node.step")} ${station.turn ?? "?"}.${stepNum ?? "?"}` : station.kind;
2116
+ L.push(`# ${t("export.stepTitle")} · ${head}`);
2117
+ L.push("");
2118
+ const anchor = anchorOf(station);
2119
+ if (anchor !== null) { L.push(`> ${t("anchor.copy")}: \`${anchor}\``); L.push(""); }
2120
+ const evidence = evidenceOf(station.request ?? null, messages, hasMore);
2121
+ if (evidence.length > 0) {
2122
+ L.push(`> ${evidence.map((e) => `${t(`evidence.${e.level}`)}`).join(" · ")}`);
2123
+ L.push("");
2124
+ }
2125
+ const req = station.request ?? null;
2126
+ if (req != null) {
2127
+ const cfg = req.config ?? {};
2128
+ const bits = [];
2129
+ if (cfg.provider) bits.push(cfg.provider);
2130
+ if (cfg.model) bits.push(cfg.model);
2131
+ if (cfg.temperature != null) bits.push(`temp=${cfg.temperature}`);
2132
+ if (cfg.reasoningEffort) bits.push(`effort=${cfg.reasoningEffort}`);
2133
+ if (req.usage != null && req.usage.input + req.usage.output > 0) bits.push(`in=${req.usage.input} out=${req.usage.output}`);
2134
+ if (req.durationMs != null) bits.push(fmtMs(req.durationMs));
2135
+ if (bits.length > 0) { L.push(`**${t("detail.request")}**: ${bits.join(" · ")}`); L.push(""); }
2136
+ const diff = req.promptDiff ?? null;
2137
+ if (diff != null && !diff.isInitial) {
2138
+ L.push(`**${t("detail.promptDiff")}**: ${diff.kind} · ${diff.prevSystemChars} → ${diff.curSystemChars}`);
2139
+ if (diff.toolsAdded.length > 0) L.push(`- + ${diff.toolsAdded.join(", ")}`);
2140
+ if (diff.toolsRemoved.length > 0) L.push(`- - ${diff.toolsRemoved.join(", ")}`);
2141
+ if (Array.isArray(diff.toolsChanged) && diff.toolsChanged.length > 0) L.push(`- ~ ${diff.toolsChanged.join(", ")}`);
2142
+ L.push("");
2143
+ if (diff.textDiff != null) {
2144
+ const diffLines = [];
2145
+ for (const line of diff.textDiff.removed) diffLines.push(`- ${line}`);
2146
+ for (const line of diff.textDiff.added) diffLines.push(`+ ${line}`);
2147
+ L.push(...fencedBlock(diffLines.join("\n"), "diff"));
2148
+ L.push("");
2149
+ }
2150
+ }
2151
+ }
2152
+ for (const cell of station.cells ?? []) {
2153
+ if (cell.kind === "assistant") {
2154
+ if (cell.thinking) { L.push(`**💭**`); L.push(""); L.push(...fencedBlock(cell.thinking)); L.push(""); }
2155
+ if (cell.text) {
2156
+ L.push("**✍**");
2157
+ L.push("");
2158
+ // Prose is emitted raw so emphasis/lists survive, but a run of 3+
2159
+ // backticks would open a fence and swallow every following block —
2160
+ // model output that explains code does this routinely. Escaping the
2161
+ // backticks keeps the text readable and the document well-formed.
2162
+ L.push(proseSafe(cell.text));
2163
+ L.push("");
2164
+ }
2165
+ } else if (cell.kind === "tool") {
2166
+ L.push(`**🔧 ${cell.name ?? "?"}**${cell.durationMs != null ? ` _(${fmtMs(cell.durationMs)})_` : ""}`);
2167
+ if (cell.args) { L.push(""); L.push(...fencedBlock(prettyArgs(String(cell.args)) || String(cell.args), "json")); }
2168
+ if (cell.errorName) L.push(`\n> ✗ ${cell.errorName}`);
2169
+ if (cell.resultText) {
2170
+ const full = String(cell.resultText);
2171
+ // Truncate only with an explicit marker: a silently shortened result
2172
+ // would make the pack look authoritative while hiding the tail.
2173
+ L.push("");
2174
+ L.push(...fencedBlock(full.length > STEP_RESULT_LIMIT ? `${full.slice(0, STEP_RESULT_LIMIT)}\n…(${fmtInt(full.length)} ${t("detail.chars")})` : full));
2175
+ }
2176
+ // Sub-calls are part of "why did this step go wrong": keep them.
2177
+ for (const sub of cell.subCalls ?? []) {
2178
+ L.push("");
2179
+ // pushSubLines already prints the child's result line; printing it
2180
+ // again here duplicated every sub-call result in the export.
2181
+ pushSubLines(L, sub, 1, t);
2182
+ }
2183
+ L.push("");
2184
+ }
2185
+ }
2186
+ // Special stations (orphan tool / error / retry / max-tokens / command /
2187
+ // compaction) keep their payload on the STATION, not in `cells`. Without this
2188
+ // the "copy this step" button produced a near-empty file for six station types.
2189
+ const extras = [];
2190
+ if (station.kind === "orphan-tool") {
2191
+ if (station.name) extras.push(`**🔧 ${station.name}**`);
2192
+ if (station.args) { extras.push(""); extras.push(...fencedBlock(prettyArgs(String(station.args)) || String(station.args), "json")); }
2193
+ if (station.isError) extras.push(`\n> ✗ ${station.errorName ?? t("kpi.errors")}`);
2194
+ if (station.resultText) { extras.push(""); extras.push(...fencedBlock(station.resultText)); }
2195
+ } else if (station.kind === "error") {
2196
+ extras.push(`**${t("node.error")}**${station.code != null ? ` \`${station.code}\`` : ""}`);
2197
+ if (station.message) { extras.push(""); extras.push(...fencedBlock(station.message)); }
2198
+ } else if (station.kind === "retry") {
2199
+ extras.push(`**${t("node.retry")}** · ${numOr(station.retry)}/${numOr(station.maxRetries)}${station.provider ? ` · ${station.provider}` : ""}${station.retryState ? ` · ${station.retryState}` : ""}`);
2200
+ if (station.message) { extras.push(""); extras.push(...fencedBlock(station.message)); }
2201
+ if (station.code != null) extras.push(`> \`${station.code}\``);
2202
+ } else if (station.kind === "maxTokens") {
2203
+ extras.push(`**${t("node.maxTokens")}**`);
2204
+ } else if (station.kind === "unknown") {
2205
+ extras.push(`**${t("node.unknown")}**${station.eventType ? ` \`${station.eventType}\`` : ""}`);
2206
+ if (station.payload) { extras.push(""); extras.push(...fencedBlock(station.payload, "json")); }
2207
+ } else if (station.kind === "command") {
2208
+ extras.push(`**${t("node.command")}** \`${station.name ?? ""}${station.args ? ` ${station.args}` : ""}\``);
2209
+ if (station.outcomeText) { extras.push(""); extras.push(...fencedBlock(station.outcomeText)); }
2210
+ } else if (station.kind === "compaction") {
2211
+ extras.push(`**${t("node.compaction")}**${station.count != null ? ` · ${station.count} ${t("detail.items")}` : ""}${station.tokens != null ? ` · ${fmtTokens(station.tokens)}` : ""}`);
2212
+ if (station.summary) { extras.push(""); extras.push(proseSafe(station.summary)); }
2213
+ }
2214
+ if (extras.length > 0) { L.push(...extras); L.push(""); }
2215
+ if (Array.isArray(messages) && messages.length > 0) {
2216
+ L.push(`---`);
2217
+ L.push("");
2218
+ L.push(`## ${t("detail.requestApprox")}`);
2219
+ L.push("");
2220
+ // Full bodies, not one-line previews: the pack is meant to be read offline.
2221
+ for (const m of messages) {
2222
+ const body = String(m.text ?? "");
2223
+ L.push(`### ${m.role} (${body.length})`);
2224
+ L.push("");
2225
+ L.push(body === "" ? `_\`${JSON.stringify(m.content ?? null)}\`_` : body);
2226
+ L.push("");
2227
+ }
2228
+ }
2229
+ return L.join("\n");
2230
+ }
2231
+ /** Render the whole trace as a Markdown study note (per-step flow + request configs). */
2232
+ /**
2233
+ * Markdown fenced block whose fence is longer than any backtick run inside.
2234
+ *
2235
+ * A fixed ``` fence breaks the moment the content contains one — a tool result
2236
+ * that is literally a README (```bash … ```) closes the block early, and every
2237
+ * heading after it ends up inside a code block or garbled. CommonMark allows
2238
+ * fence lengths ≥3, and a fence only closes on a run of at least equal length,
2239
+ * so choosing max(3, longestRun + 1) is both correct and minimal.
2240
+ */
2241
+ /**
2242
+ * Make untrusted prose safe to emit raw into the export.
2243
+ *
2244
+ * Prose is emitted raw so emphasis and lists survive, but two constructs in it
2245
+ * can restructure the whole document:
2246
+ *
2247
+ * - a run of 3+ backticks opens a fence and swallows every following block
2248
+ * (a model explaining code produces these constantly, and a stream that was
2249
+ * cut off mid-answer leaves an UNCLOSED one that eats the rest of the file);
2250
+ * - `</details>` closes the collapsible block we opened around reasoning, so
2251
+ * the remainder of the step renders outside its own section.
2252
+ *
2253
+ * Escaping only the dangerous characters keeps the text readable.
2254
+ */
2255
+ function proseSafe(content) {
2256
+ // `String(Symbol)` throws. Prose normally IS a string, but this is the choke point
2257
+ // every text block passes through, so it must not be the one place that can take
2258
+ // the render down; `asText` also turns an object into its JSON instead of
2259
+ // "[object Object]".
2260
+ return asText(content)
2261
+ .replace(/`{3,}/g, (run) => "\\`".repeat(run.length))
2262
+ .replace(/<(\/?)(details)\b/gi, "&lt;$1$2");
2263
+ }
2264
+ function fencedBlock(content, lang) {
2265
+ const text = String(content ?? "");
2266
+ let longest = 0;
2267
+ for (const run of text.match(/`+/g) ?? []) if (run.length > longest) longest = run.length;
2268
+ const fence = "`".repeat(Math.max(3, longest + 1));
2269
+ const info = typeof lang === "string" && lang !== "" ? lang : "";
2270
+ return [fence + info, text, fence];
2271
+ }
2272
+ /**
2273
+ * Give ids to form fields the host ships without one.
2274
+ *
2275
+ * DevTools audits form fields *page-wide*: the host's sidebar session search
2276
+ * (`input.bhn1Oq_searchInput`) has neither `id` nor `name`, so every page load
2277
+ * reports "A form field element should have an id or name attribute". We cannot
2278
+ * edit host code, but the element is in the same document, so we can annotate it.
2279
+ *
2280
+ * Deliberately conservative:
2281
+ * - only fields with NEITHER attribute are touched (an id the host sets always wins);
2282
+ * - only `id` is set, never `name` — a `name` changes what the surrounding form
2283
+ * would submit, and the audit is satisfied by either one;
2284
+ * - our own inputs are skipped (they carry ids already);
2285
+ * - the id is namespaced and de-duplicated, so we never collide with the host.
2286
+ * Returns the number of fields annotated, which makes it testable.
2287
+ */
2288
+ function annotateNamelessFormFields() {
2289
+ if (typeof document === "undefined") return 0;
2290
+ let touched = 0;
2291
+ for (const el of document.querySelectorAll("input,textarea,select")) {
2292
+ if (el.closest(".dstv_root") != null) continue;
2293
+ if (el.id !== "" || el.getAttribute("name") !== null) continue;
2294
+ const slug = String(el.getAttribute("class") ?? "").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
2295
+ const base = "dsh-field-" + (slug !== "" ? slug : String(el.tagName || "field").toLowerCase());
2296
+ let candidate = base;
2297
+ for (let n = 2; document.getElementById(candidate) !== null; n += 1) candidate = base + "-" + n;
2298
+ el.id = candidate;
2299
+ touched += 1;
2300
+ }
2301
+ return touched;
2302
+ }
2303
+ /**
2304
+ * Minimal Markdown parsing for assistant bodies.
2305
+ *
2306
+ * The host's own `AssistantMarkdown` needs a dozen internal services
2307
+ * (loadImage/usePresentation/renderSlot/…), so it cannot be reused here. This is
2308
+ * the subset that actually appears in model output: headings, fences, lists,
2309
+ * quotes, tables, rules, paragraphs, and inline code/strong/links.
2310
+ *
2311
+ * Produces plain descriptors only — no HTML strings anywhere, so rendering later
2312
+ * cannot inject markup. Deliberately shallow: no nested emphasis, no HTML blocks,
2313
+ * no reference links. Unknown syntax degrades to literal text, which is honest.
2314
+ */
2315
+ function mdInline(src) {
2316
+ const s = String(src ?? "");
2317
+ const out = [];
2318
+ // Text is accumulated as a SLICE RANGE: `buf += c` copies the whole buffer per
2319
+ // character, which is quadratic by itself.
2320
+ let runStart = 0;
2321
+ const flush = (end) => { if (end > runStart) out.push({ t: "text", text: s.slice(runStart, end) }); };
2322
+
2323
+ // Resolving each marker with a fresh indexOf rescanning to end-of-string made
2324
+ // this quadratic: 64K unclosed `[` took 221 ms and 256K took 2.6 s, and the
2325
+ // output feeds card previews on every render. Build next-occurrence tables in
2326
+ // ONE backwards pass instead; lookups are then O(1) and the whole parse is O(n).
2327
+ // A newline resets a table, because no construct here spans lines.
2328
+ const buildNext = (code) => {
2329
+ const a = new Int32Array(s.length + 1);
2330
+ a[s.length] = -1;
2331
+ let next = -1;
2332
+ for (let i = s.length - 1; i >= 0; i -= 1) {
2333
+ if (s.charCodeAt(i) === 10) { a[i] = -1; next = -1; continue; }
2334
+ a[i] = next;
2335
+ if (s.charCodeAt(i) === code) next = i;
2336
+ }
2337
+ return a;
2338
+ };
2339
+ const atBacktick = buildNext(96); // `
2340
+ const atStar = buildNext(42); // *
2341
+ const atBracket = buildNext(93); // ]
2342
+ const atParen = buildNext(41); // )
2343
+
2344
+ for (let i = 0; i < s.length; ) {
2345
+ const c = s[i];
2346
+ if (c === "`") {
2347
+ const end = atBacktick[i + 1];
2348
+ if (end > i) { flush(i); out.push({ t: "code", text: s.slice(i + 1, end) }); i = end + 1; runStart = i; continue; }
2349
+ }
2350
+ if (c === "*" && s[i + 1] === "*") {
2351
+ let end = -1;
2352
+ for (let k = atStar[i + 2]; k >= 0 && k + 1 < s.length; k = atStar[k + 1]) {
2353
+ if (s[k + 1] === "*") { end = k; break; }
2354
+ }
2355
+ if (end > i + 1) { flush(i); out.push({ t: "strong", text: s.slice(i + 2, end) }); i = end + 2; runStart = i; continue; }
2356
+ i += 2;
2357
+ continue;
2358
+ }
2359
+ if (c === "[") {
2360
+ // `atBracket` yields the next `]` STRICTLY AFTER a position, so asking for
2361
+ // position i+1 skipped a `]` sitting exactly there. An empty label —
2362
+ // `[](https://x)` — is legal Markdown, and missing it did not merely lose
2363
+ // that link: the scanner carried on and the NEXT `[label](href)` paired with
2364
+ // the earlier bracket, so the rendered link read
2365
+ // "](https://x) and [说明" with someone else's href, silently swallowing the
2366
+ // text in between. Check the immediate position first.
2367
+ const close = s[i + 1] === "]" ? i + 1 : atBracket[i + 1];
2368
+ if (close > i && s[close + 1] === "(") {
2369
+ const end = atParen[close + 2];
2370
+ if (end > close) {
2371
+ flush(i);
2372
+ const label = s.slice(i + 1, close);
2373
+ const href = s.slice(close + 2, end);
2374
+ // An empty label would render `<a></a>`: an invisible, unclickable
2375
+ // element that still occupies the link styling. Show the target
2376
+ // instead, so the reader can see where it goes.
2377
+ out.push({ t: "link", text: label !== "" ? label : href, href });
2378
+ i = end + 1; runStart = i; continue;
2379
+ }
2380
+ }
2381
+ // Unmatched bracket: advance by one so the scan never restarts.
2382
+ i += 1;
2383
+ continue;
2384
+ }
2385
+ i += 1;
2386
+ }
2387
+ flush(s.length);
2388
+ return out;
2389
+ }
2390
+ /** Block-level split. Returns descriptors; see mdInline for the inline level. */
2391
+ function mdBlocks(src) {
2392
+ const lines = String(src ?? "").replace(/\r\n?/g, "\n").split("\n");
2393
+ const blocks = [];
2394
+ let i = 0;
2395
+ while (i < lines.length) {
2396
+ const line = lines[i];
2397
+ const fence = /^\s*(`{3,}|~{3,})(.*)$/.exec(line);
2398
+ if (fence !== null) {
2399
+ const marker = fence[1][0] === "~" ? "~" : "`";
2400
+ const need = fence[1].length;
2401
+ const lang = fence[2].trim();
2402
+ const body = [];
2403
+ i += 1;
2404
+ while (i < lines.length) {
2405
+ // The closing run must use the SAME character and be at least as long.
2406
+ const close = new RegExp("^\\s*" + (marker === "~" ? "~" : "`") + "{" + need + ",}\\s*$");
2407
+ if (close.test(lines[i])) { i += 1; break; }
2408
+ body.push(lines[i]);
2409
+ i += 1;
2410
+ }
2411
+ blocks.push({ type: "code", lang, text: body.join("\n") });
2412
+ continue;
2413
+ }
2414
+ const head = /^(#{1,6})\s+(.*)$/.exec(line);
2415
+ if (head !== null) { blocks.push({ type: "h", level: head[1].length, text: head[2].trim() }); i += 1; continue; }
2416
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { blocks.push({ type: "hr" }); i += 1; continue; }
2417
+ if (/^\s*>\s?/.test(line)) {
2418
+ const quoted = [];
2419
+ while (i < lines.length && /^\s*>\s?/.test(lines[i])) { quoted.push(lines[i].replace(/^\s*>\s?/, "")); i += 1; }
2420
+ blocks.push({ type: "quote", lines: quoted });
2421
+ continue;
2422
+ }
2423
+ // Table: a header row followed by a |---|---| separator.
2424
+ if (line.includes("|") && i + 1 < lines.length && /^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(lines[i + 1])) {
2425
+ // `\|` is the escape for a literal pipe inside a cell — the only way to
2426
+ // put one in a table at all. Splitting on every `|` cut such a cell in
2427
+ // two, so `| a \| b | c |` became THREE columns ("a \", "b", "c") and
2428
+ // every cell after the escape shifted one column left under the header.
2429
+ const cells = (l) => {
2430
+ const body = l.replace(/^\s*\|/, "").replace(/\|\s*$/, "");
2431
+ const out = [];
2432
+ let cur = "";
2433
+ for (let k = 0; k < body.length; k += 1) {
2434
+ const ch = body[k];
2435
+ if (ch === "\\" && body[k + 1] === "|") { cur += "|"; k += 1; continue; }
2436
+ if (ch === "|") { out.push(cur.trim()); cur = ""; continue; }
2437
+ cur += ch;
2438
+ }
2439
+ out.push(cur.trim());
2440
+ return out;
2441
+ };
2442
+ const header = cells(line);
2443
+ i += 2;
2444
+ const rows = [];
2445
+ while (i < lines.length && lines[i].includes("|") && !/^\s*$/.test(lines[i])) { rows.push(cells(lines[i])); i += 1; }
2446
+ blocks.push({ type: "table", head: header, rows });
2447
+ continue;
2448
+ }
2449
+ const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
2450
+ if (li !== null) {
2451
+ const ordered = /\d/.test(li[2]);
2452
+ // Keep the starting number: "7. Resume / 8. Verify" must render as 7,8 —
2453
+ // an <ol> defaults to 1, which silently renumbered the list.
2454
+ const startAt = ordered ? parseInt(li[2], 10) : 1;
2455
+ const items = [];
2456
+ while (i < lines.length) {
2457
+ const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i]);
2458
+ // A different list marker starts a NEW list: "7. a / - b" was parsed as
2459
+ // one ordered list with two items, renumbering the bullet to 8.
2460
+ if (m !== null && (/\d/.test(m[2])) !== ordered) break;
2461
+ if (m === null) {
2462
+ // A lazy continuation line belongs to the previous item — but a fence
2463
+ // opener or closer ends the list. Swallowing it turned a code block
2464
+ // after a list into list prose ("const x=1" became an <li>).
2465
+ const isFence = /^\s*(`{3,}|~{3,})/.test(lines[i]);
2466
+ if (!isFence && items.length > 0 && !/^\s*$/.test(lines[i]) && !/^\s*#{1,6}\s/.test(lines[i])) { items[items.length - 1].push(lines[i].trim()); i += 1; continue; }
2467
+ break;
2468
+ }
2469
+ items.push([m[3]]);
2470
+ i += 1;
2471
+ }
2472
+ blocks.push(ordered ? { type: "ol", items, start: Number.isFinite(startAt) && startAt > 1 ? startAt : 1 } : { type: "ul", items });
2473
+ continue;
2474
+ }
2475
+ if (/^\s*$/.test(line)) { i += 1; continue; }
2476
+ const para = [];
2477
+ while (i < lines.length && !/^\s*$/.test(lines[i]) && !/^\s*(`{3,}|#{1,6}\s|>\s?|[-*+]\s|\d+[.)]\s)/.test(lines[i])) {
2478
+ para.push(lines[i]);
2479
+ i += 1;
2480
+ }
2481
+ if (para.length === 0) { para.push(lines[i]); i += 1; }
2482
+ blocks.push({ type: "p", text: para.join("\n") });
2483
+ }
2484
+ return blocks;
2485
+ }
2486
+ /** Markdown with markers stripped, for one-line previews. */
2487
+ function markdownToPlain(src) {
2488
+ let out = "";
2489
+ for (const part of mdInline(src)) out += part.text;
2490
+ return out;
2491
+ }
2492
+ function buildTraceMarkdown(tree, t) {
2493
+ const L = [];
2494
+ L.push(`# ${t("export.title")}`);
2495
+ L.push("");
2496
+ const s = tree.stats;
2497
+ L.push(`> ${t("node.turn")} ${s.turns} · ${t("node.step")} ${s.steps} · ${t("node.tool")} ${s.tools} · ${t("kpi.errors")} ${s.errors} · ${t("kpi.tokensIn")} ${fmtTokens(s.tokensIn)} · ${t("kpi.tokensOut")} ${fmtTokens(s.tokensOut)}${s.lastModel ? ` · ${s.lastModel}` : ""}`);
2498
+ // The panel warns about a damaged or drifting log in its header; the export used
2499
+ // to state only the totals, so a saved "study notes" file silently claimed a
2500
+ // clean read of a log the screen was actively flagging. Same rule as the error
2501
+ // code / retry metadata: the file must carry what the panel shows.
2502
+ {
2503
+ const warns = [];
2504
+ if (tree.contract != null && tree.contract.ok !== true) warns.push(t("view.malformed").replace("{n}", String((tree.contract.problems ?? []).length)));
2505
+ if (tree.nodeStats != null && tree.nodeStats.unknown > 0) warns.push(t("view.drift").replace("{n}", String(tree.nodeStats.unknown)));
2506
+ if (tree.nodeStats != null && tree.nodeStats.invalid > 0) warns.push(t("view.invalid").replace("{n}", String(tree.nodeStats.invalid)));
2507
+ if (tree.unplacedRequests > 0) warns.push(t("view.unplacedReq").replace("{n}", String(tree.unplacedRequests)));
2508
+ if (warns.length > 0) { L.push(""); L.push(`> ⚠ ${warns.join(" · ")}`); }
2509
+ }
2510
+ let firstPrompt = null;
2511
+ const reqLine = (st) => {
2512
+ const r = st.request;
2513
+ if (r == null) return null;
2514
+ const cfg = r.config ?? {};
2515
+ const bits = [];
2516
+ if (cfg.provider) bits.push(cfg.provider);
2517
+ if (cfg.model) bits.push(cfg.model);
2518
+ if (cfg.temperature != null) bits.push(`temp=${cfg.temperature}`);
2519
+ if (cfg.reasoningEffort) bits.push(`effort=${cfg.reasoningEffort}`);
2520
+ if (r.usage !== null && r.usage.input + r.usage.output > 0) bits.push(`in=${r.usage.input} out=${r.usage.output}`);
2521
+ if (r.durationMs != null) bits.push(fmtMs(r.durationMs));
2522
+ return bits.length > 0 ? bits.join(" · ") : null;
2523
+ };
2524
+ for (const st of tree.stations) {
2525
+ if (st.tag !== void 0 && st.tag !== null) { L.push(""); L.push(`## ${st.tag}`); }
2526
+ L.push("");
2527
+ if (st.kind === "user") {
2528
+ L.push(`### 👤 ${st.who}`);
2529
+ L.push("");
2530
+ L.push(st.text !== "" ? proseSafe(st.text) : "…");
2531
+ } else if (st.kind === "step") {
2532
+ L.push(`### 🤖 ${st.label} _(${st.detail})_`);
2533
+ if (st.meta.length > 0) { L.push(""); L.push(`_${st.meta.join(" · ")}_`); }
2534
+ const rl = reqLine(st);
2535
+ if (rl !== null) { L.push(""); L.push(`> 📨 ${rl}`); }
2536
+ if (st.request?.prompt != null && firstPrompt === null) firstPrompt = st.request.prompt;
2537
+ for (const cell of st.cells) {
2538
+ if (cell.kind === "assistant") {
2539
+ if (cell.thinking !== "") { L.push(""); L.push(`<details><summary>💭 ${t("chip.thinking")} (${cell.thinking.length})</summary>`); L.push(""); L.push(proseSafe(cell.thinking)); L.push("</details>"); }
2540
+ if (cell.text !== "") { L.push(""); L.push(proseSafe(cell.text)); }
2541
+ } else if (cell.kind === "tool") {
2542
+ L.push("");
2543
+ L.push(`#### ${cell.isError ? "✗" : "✓"} 🔧 ${cell.name}${cell.durationMs != null ? ` _(${fmtMs(cell.durationMs)})_` : ""}`);
2544
+ if (cell.args !== "") { L.push(""); L.push(...fencedBlock(prettyArgs(cell.args) || cell.args, "json")); }
2545
+ if (cell.resultText !== "") { L.push(""); L.push(`**${t("detail.result")}**`); L.push(""); L.push(...fencedBlock(cell.resultText.length > 4000 ? `${cell.resultText.slice(0, 4000)}\n…(${fmtInt(cell.resultText.length)} ${t("detail.chars")})` : cell.resultText)); }
2546
+ for (const sub of cell.subCalls) {
2547
+ L.push("");
2548
+ pushSubLines(L, sub, 1, t);
2549
+ }
2550
+ }
2551
+ }
2552
+ } else if (st.kind === "orphan-tool") {
2553
+ L.push(`### ⤷ ${t("node.orphanTool")} · ${st.name}`);
2554
+ L.push("");
2555
+ L.push(`_${t("orphan.badge")} · ${anchorOf(st) ?? "—"}_`);
2556
+ if (st.args !== "") { L.push(""); L.push(...fencedBlock(prettyArgs(st.args) || st.args, "json")); }
2557
+ if (st.displayText !== "") { L.push(""); L.push(...fencedBlock(st.displayText.length > 4000 ? `${st.displayText.slice(0, 4000)}\n…(${fmtInt(st.displayText.length)} ${t("detail.chars")})` : st.displayText)); }
2558
+ } else if (st.kind === "compaction") {
2559
+ L.push(`### ♺ ${st.label}${Number.isSafeInteger(st.count) ? ` _(${numOr(st.count)} ${t("meta.steps")} / ${fmtTokens(st.tokens)} ${t("meta.tokens")})_` : ""}`);
2560
+ if (st.summary !== "") { L.push(""); L.push(st.summary); }
2561
+ if (st.crequest?.outputText) { L.push(""); L.push(`<details><summary>${t("detail.compactionOutput")}</summary>`); L.push(""); L.push(st.crequest.outputText); L.push("</details>"); }
2562
+ } else if (st.kind === "error") {
2563
+ L.push(`### ✗ ${st.label}${st.code != null ? ` \`${st.code}\`` : ""}`);
2564
+ L.push(""); L.push(st.message || "…");
2565
+ } else if (st.kind === "retry") {
2566
+ // The detail panel shows the retry counter, the provider and the error
2567
+ // code; the export showed none of them, so the Markdown copy of a failed
2568
+ // step was strictly less useful than the screen it was copied from —
2569
+ // "which retry failed, and with what code" is exactly what a reader
2570
+ // pastes into a bug report.
2571
+ const retryBits = [];
2572
+ if (Number.isFinite(st.retry)) retryBits.push(`#${numOr(st.retry)}${Number.isSafeInteger(st.maxRetries) ? `/${numOr(st.maxRetries)}` : ""}`);
2573
+ if (st.provider) retryBits.push(String(st.provider));
2574
+ if (st.code != null) retryBits.push(`code: ${st.code}`);
2575
+ if (st.retryState) retryBits.push(String(st.retryState));
2576
+ L.push(`### ↻ ${st.label}${retryBits.length > 0 ? ` (${retryBits.join(" · ")})` : ""}`);
2577
+ if (st.message) { L.push(""); L.push(st.message); }
2578
+ } else if (st.kind === "maxTokens") {
2579
+ L.push(`### ⛔ ${st.label}`);
2580
+ } else if (st.kind === "command") {
2581
+ L.push(`### ⚡ /${st.name}${st.args !== "" ? ` ${st.args}` : ""}`);
2582
+ if (st.outcomeText) { L.push(""); L.push(st.outcomeText); }
2583
+ } else if (st.kind === "unknown") {
2584
+ L.push(`### ? ${t("node.unknown")}${st.eventType ? ` \`${st.eventType}\`` : ""}`);
2585
+ if (st.payload) { L.push(""); L.push(...fencedBlock(st.payload, "json")); }
2586
+ }
2587
+ }
2588
+ if (firstPrompt !== null) {
2589
+ L.push("");
2590
+ L.push("---");
2591
+ L.push("");
2592
+ L.push(`## ${t("export.appendix")}`);
2593
+ L.push("");
2594
+ L.push(`<details><summary>🧠 ${t("detail.systemPrompt")} (${fmtInt(firstPrompt.systemChars)} ${t("detail.chars")})</summary>`);
2595
+ L.push("");
2596
+ L.push(...fencedBlock(firstPrompt.system));
2597
+ L.push("</details>");
2598
+ // The request tab renders this catalog through `safeToolList`; the export path
2599
+ // read the RAW array and crashed on a `null` hole (`Cannot read properties of
2600
+ // null (reading 'name')`), so clicking "copy whole trace" produced nothing at
2601
+ // all. Use the same normalizer here.
2602
+ const exportTools = safeToolList(firstPrompt.tools);
2603
+ if (exportTools.length > 0) {
2604
+ L.push("");
2605
+ L.push(`**${t("detail.toolsCatalog")} (${exportTools.length})**: ${exportTools.map((tool) => `\`${tool.name}\``).join(" ")}`);
2606
+ }
2607
+ }
2608
+ L.push("");
2609
+ return L.join("\n");
2610
+ }
2611
+ /** T2: upper bound for a clock-scaled idle band, so one huge pause cannot dominate the rail. */
2612
+ const GAP_MAX_PX = 220;
2613
+ /**
2614
+ * T2: width in px for one idle band under clock mode. Log-scaled so a 10x longer
2615
+ * pause does not take 10x the room, and capped so one huge pause cannot dominate
2616
+ * the rail. Returns null when clock mode is off (band keeps its natural width).
2617
+ */
2618
+ function clockGapWidth(gapMs, clockAxisOn) {
2619
+ if (clockAxisOn !== true) return null;
2620
+ if (!Number.isFinite(gapMs) || gapMs <= 0) return null;
2621
+ // base 10 / coeff 15 over log2(seconds): 30s≈84px, 5m≈134px, 1h≈187px,
2622
+ // reaching the 220px cap only past ~4h. A steeper curve saturates by 5m
2623
+ // and loses all discrimination inside the range that actually occurs.
2624
+ const px = 10 + Math.log2(1 + gapMs / 1000) * 15;
2625
+ return `${Math.min(GAP_MAX_PX, Math.round(px))}px`;
2626
+ }
2627
+ //#endregion