dsh-trajectory-traceview-plus 0.0.0-stage → 0.10.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.
package/src/40-view.js ADDED
@@ -0,0 +1,2130 @@
1
+ //#region horizontal timeline + replay component
2
+ const EMPTY_SNAPSHOT = { eventNodes: [], runningCalls: [], partial: null };
3
+ const SPEEDS_MS = [1500, 750, 375];
4
+ const SPEED_LABELS = ["×1", "×2", "×4"];
5
+ const STATION_W = 264;
6
+ /** G4-T3: gaps shorter than this are normal scheduling noise, not an idle pause. */
7
+ const GAP_MIN_MS = 30_000;
8
+ /** G2: bound on back-paging while chasing an anchor, and on waiting for the re-projection. */
9
+ const ANCHOR_MAX_PAGES = 40;
10
+ const ANCHOR_REVEAL_TRIES = 12;
11
+ const ANCHOR_REVEAL_MS = 250;
12
+
13
+ /** Tool glyphs by tool name (fallback wrench). */
14
+ function toolGlyph(name) {
15
+ const n = String(name ?? "").toLowerCase();
16
+ if (n.includes("pwsh") || n.includes("bash") || n.includes("shell") || n.includes("terminal") || n.includes("code_runtime") || n.includes("run_code")) return "⌨";
17
+ if (n.includes("read") || n.includes("view") || n.includes("cat")) return "📄";
18
+ if (n.includes("write") || n.includes("edit") || n.includes("str-replace") || n.includes("insert")) return "✎";
19
+ if (n.includes("grep") || n.includes("glob") || n.includes("find") || n.includes("search")) return "🔍";
20
+ if (n.includes("web") || n.includes("http")) return "🌐";
21
+ if (n.includes("todo")) return "☑";
22
+ if (n.includes("subagent") || n.includes("fork")) return "🤖";
23
+ if (n.includes("workflow")) return "⚙";
24
+ if (n.includes("goal")) return "🎯";
25
+ if (n.includes("skill")) return "✨";
26
+ if (n.includes("ask")) return "❓";
27
+ return "🔧";
28
+ }
29
+
30
+ /** Copy `text` to the clipboard; finish(ok) reports success. */
31
+ function copyText(text, finish) {
32
+ try {
33
+ if (typeof navigator !== "undefined" && typeof navigator.clipboard !== "undefined" && typeof navigator.clipboard.writeText === "function") {
34
+ navigator.clipboard.writeText(text).then(() => finish(true), () => finish(false));
35
+ return;
36
+ }
37
+ } catch { /* fall through */ }
38
+ // Legacy fallback. This is the ONLY path on plain http:// (where
39
+ // `navigator.clipboard` does not exist), i.e. the common case — so its side
40
+ // effects matter:
41
+ // - `ta.select()` moves focus into the textarea. When the textarea is removed
42
+ // the focused element is gone and focus falls back to <body>, so every copy
43
+ // threw a keyboard or screen-reader user back to the top of the document.
44
+ // - An editable textarea that takes focus pops the on-screen keyboard on iOS,
45
+ // so copying raised a keyboard that then had nothing to type into.
46
+ // `readonly` suppresses both; the element is restored and focus returned.
47
+ try {
48
+ const prev = typeof document.activeElement !== "undefined" ? document.activeElement : null;
49
+ const ta = document.createElement("textarea");
50
+ ta.value = text;
51
+ ta.setAttribute("readonly", "");
52
+ ta.setAttribute("aria-hidden", "true");
53
+ ta.setAttribute("tabindex", "-1");
54
+ ta.style.position = "fixed";
55
+ ta.style.top = "0";
56
+ ta.style.left = "0";
57
+ ta.style.opacity = "0";
58
+ ta.style.pointerEvents = "none";
59
+ document.body.appendChild(ta);
60
+ ta.select();
61
+ const ok = document.execCommand("copy");
62
+ document.body.removeChild(ta);
63
+ // Return focus where it was. `preventScroll` keeps the timeline from
64
+ // jumping while we restore it.
65
+ if (prev !== null && typeof prev.focus === "function") {
66
+ try { prev.focus({ preventScroll: true }); } catch { /* focus is a nicety */ }
67
+ }
68
+ finish(ok);
69
+ } catch { finish(false); }
70
+ }
71
+
72
+ /**
73
+ * Render Markdown descriptors as React elements.
74
+ *
75
+ * Everything is built from `jsx`/`jsxs` and plain strings: no `innerHTML`, no
76
+ * `dangerouslySetInnerHTML`, so model output can never become markup. Links get
77
+ * `rel="noreferrer noopener"` because the target came from the transcript.
78
+ */
79
+ /**
80
+ * Allowlist for links taken from the transcript. `http(s)` and `mailto` are inert;
81
+ * angle-bracket-free relative URLs are allowed too. Everything else — notably
82
+ * `javascript:` and `vbscript:` — returns null so the caller renders text instead.
83
+ * The check is done on a whitespace/control-stripped, lowercased copy, because
84
+ * `java\nscript:` and leading spaces are the usual bypasses.
85
+ */
86
+ function safeHref(raw) {
87
+ const s = String(raw ?? "").replace(/[\u0000-\u0020\u007f]+/g, "");
88
+ if (s === "") return null;
89
+ // A bare relative reference has no scheme at all.
90
+ if (/^[#/?]/.test(s)) return raw;
91
+ const m = /^([a-z][a-z0-9+.-]*):/i.exec(s);
92
+ if (m === null) return raw;
93
+ const scheme = m[1].toLowerCase();
94
+ return scheme === "http" || scheme === "https" || scheme === "mailto" ? raw : null;
95
+ }
96
+ function renderMdInline(parts, keyBase) {
97
+ return parts.map((p, i) => {
98
+ const k = keyBase + "i" + i;
99
+ if (p.t === "code") return jsx("code", { className: "dstv_mdCode", children: p.text }, k);
100
+ if (p.t === "strong") return jsx("strong", { className: "dstv_mdBold", children: p.text }, k);
101
+ if (p.t === "link") {
102
+ // The href comes from MODEL OUTPUT. React does not sanitise URLs, so a
103
+ // `javascript:` or `vbscript:` link was rendered into the DOM verbatim and
104
+ // ran on click. Allow only inert schemes; anything else degrades to text
105
+ // (never to a guessed "safe" URL).
106
+ const href = safeHref(p.href);
107
+ if (href === null) return jsx("span", { className: "dstv_mdLinkBlocked", children: p.text }, k);
108
+ return jsx("a", { className: "dstv_mdLink", href, target: "_blank", rel: "noreferrer noopener", children: p.text }, k);
109
+ }
110
+ return p.text;
111
+ });
112
+ }
113
+ function MarkdownText({ text }) {
114
+ const blocks = (0, react.useMemo)(() => mdBlocks(text), [text]);
115
+ const nodes = blocks.map((b, i) => {
116
+ const k = "md" + i;
117
+ if (b.type === "h") {
118
+ const tag = "h" + Math.min(6, Math.max(1, b.level));
119
+ return jsx(tag, { className: "dstv_mdH dstv_mdH" + b.level, children: renderMdInline(mdInline(b.text), k) }, k);
120
+ }
121
+ if (b.type === "code") {
122
+ return jsxs("div", { className: "dstv_mdFence", children: [
123
+ b.lang !== "" ? jsx("span", { className: "dstv_mdLang", children: b.lang }, k + "L") : null,
124
+ jsx("pre", { className: "dstv_mdPre", children: jsx("code", { children: b.text }, k + "C") }, k + "P")
125
+ ] }, k);
126
+ }
127
+ if (b.type === "ul" || b.type === "ol") {
128
+ const tag = b.type === "ul" ? "ul" : "ol";
129
+ // Carry the start number through to the element; without it an <ol>
130
+ // renumbers from 1 and "7. Resume" silently became "1. Resume".
131
+ const listProps = { className: "dstv_mdList", children: b.items.map((it, j) => jsx("li", { children: renderMdInline(mdInline(it.join(" ")), k + "j" + j) }, k + "j" + j)) };
132
+ if (b.type === "ol" && Number.isFinite(b.start) && b.start > 1) listProps.start = b.start;
133
+ return jsx(tag, listProps, k);
134
+ }
135
+ if (b.type === "quote") {
136
+ return jsx("blockquote", { className: "dstv_mdQuote", children: renderMdInline(mdInline(b.lines.join("\n")), k) }, k);
137
+ }
138
+ if (b.type === "table") {
139
+ return jsxs("table", { className: "dstv_mdTable", children: [
140
+ jsx("thead", { children: jsx("tr", { children: b.head.map((c, j) => jsx("th", { children: renderMdInline(mdInline(c), k + "h" + j) }, k + "h" + j)) }, k + "hr") }, k + "hd"),
141
+ jsx("tbody", { children: b.rows.map((row, r) => jsx("tr", { children: row.map((c, j) => jsx("td", { children: renderMdInline(mdInline(c), k + "r" + r + "c" + j) }, k + "r" + r + "c" + j)) }, k + "r" + r)) }, k + "bd")
142
+ ] }, k);
143
+ }
144
+ if (b.type === "hr") return jsx("hr", { className: "dstv_mdHr" }, k);
145
+ return jsx("p", { className: "dstv_mdP", children: renderMdInline(mdInline(b.text), k) }, k);
146
+ });
147
+ if (nodes.length === 0) return null;
148
+ return jsx("div", { className: "dstv_md", children: nodes }, "mdRoot");
149
+ }
150
+ /** Small inline copy button with transient feedback. */
151
+ function CopyBtn({ text, label, okLabel, failLabel }) {
152
+ // Three states, not two. A failed copy used to return silently: the button
153
+ // never changed, so the click looked ignored and the user pasted whatever was
154
+ // in the clipboard from before. `navigator.clipboard` is unavailable on plain
155
+ // http:// (non-secure context) and `execCommand` can refuse too, so failure is
156
+ // a normal outcome that has to be visible.
157
+ const [copyState, setCopyState] = (0, react.useState)("idle");
158
+ // Only one feedback timer may be pending. Clicking twice within the window
159
+ // started a SECOND timer without cancelling the first, so the earlier one
160
+ // fired first and cleared the state the newer click had just set — the button
161
+ // reverted to its idle label and the second copy looked ignored, which is
162
+ // exactly the confusion this three-state feedback exists to prevent.
163
+ const resetRef = (0, react.useRef)(null);
164
+ const doCopy = () => {
165
+ copyText(text, (ok) => {
166
+ setCopyState(ok ? "ok" : "fail");
167
+ if (resetRef.current !== null) clearTimeout(resetRef.current);
168
+ resetRef.current = setTimeout(() => { resetRef.current = null; setCopyState("idle"); }, 1400);
169
+ });
170
+ };
171
+ (0, react.useEffect)(() => () => {
172
+ if (resetRef.current !== null) { clearTimeout(resetRef.current); resetRef.current = null; }
173
+ }, []);
174
+ return jsx("button", {
175
+ type: "button",
176
+ className: "dstv_copyBtn",
177
+ "data-ok": copyState === "ok" ? "true" : undefined,
178
+ "data-fail": copyState === "fail" ? "true" : undefined,
179
+ onClick: (ev) => { ev.stopPropagation(); doCopy(); },
180
+ // `failLabel` arrives as a prop: this is a module-level component and `t`
181
+ // is NOT in its scope — calling it here threw ReferenceError, but only
182
+ // when a copy actually failed, which no test could reach.
183
+ children: copyState === "ok" ? `✓ ${okLabel}` : copyState === "fail" ? `✗ ${failLabel ?? "!"}` : label
184
+ });
185
+ }
186
+
187
+ /**
188
+ * One bad station must not take the whole view down. A read-only review tool
189
+ * that blanks out because a single field had an unexpected shape is worse than
190
+ * the crash itself: the session is still there, the reader just cannot see it.
191
+ *
192
+ * `render` is CALLED INSIDE the boundary (not passed as an already-built
193
+ * element) — an eagerly built element throws in the parent render, where no
194
+ * boundary can catch it.
195
+ */
196
+ class RenderBoundary extends (react.Component ?? class {}) {
197
+ constructor(props) {
198
+ super(props);
199
+ this.state = { err: null };
200
+ this.retry = () => this.setState({ err: null });
201
+ }
202
+ static getDerivedStateFromError(err) { return { err }; }
203
+ render() {
204
+ if (this.state.err !== null) {
205
+ const msg = String((this.state.err && this.state.err.message) || this.state.err).slice(0, 240);
206
+ return jsxs("div", { className: `dstv_boundary${this.props.wide === true ? " detail" : ""}`, children: [
207
+ jsx("span", { className: "dstv_name", children: `⚠ ${this.props.label}` }, "bName"),
208
+ jsx("div", { className: "dstv_text sec", children: msg }, "bMsg"),
209
+ jsx("div", { className: "dstv_text sec", children: this.props.hint }, "bHint"),
210
+ jsx("button", { type: "button", className: "dstv_btn", onClick: this.retry, children: this.props.retryLabel }, "bRetry")
211
+ ] });
212
+ }
213
+ return this.props.render();
214
+ }
215
+ }
216
+
217
+ /** Trace view tab: horizontal timeline with replay transport, minimap, search,
218
+ * follow mode, and a bottom panel showing step details incl. the raw request
219
+ * sent to the model. Honors the conversation `inspect` deep-link (chat tool
220
+ * click → locate the station owning that call) and `loadOlder` history. */
221
+ /**
222
+ * Persist exactly two pieces of view state per conversation so a host remount does
223
+ * not throw the reader back to "overview, empty search". Everything else (replay,
224
+ * tab, follow) is deliberately NOT restored: resuming a replay you left is more
225
+ * surprising than helpful, and the tab choice is cheap to redo.
226
+ *
227
+ * sessionStorage, not localStorage: this is scratch state for one tab, it must not
228
+ * leak into another tab or another window, and it should die with the tab.
229
+ * Every access is guarded — a host with storage disabled must behave exactly as
230
+ * before, not throw.
231
+ */
232
+ const VIEW_STATE_PREFIX = "dstv:view:1:";
233
+ function viewStateKey(sessionKey) {
234
+ if (typeof sessionKey !== "string" || sessionKey === "") return null;
235
+ return VIEW_STATE_PREFIX + sessionKey;
236
+ }
237
+ function readViewState(sessionKey) {
238
+ const empty = { revealed: null, query: "" };
239
+ const key = viewStateKey(sessionKey);
240
+ if (key === null) return empty;
241
+ try {
242
+ const raw = window.sessionStorage.getItem(key);
243
+ if (raw === null) return empty;
244
+ const parsed = JSON.parse(raw);
245
+ if (parsed === null || typeof parsed !== "object") return empty;
246
+ const revealed = Number.isSafeInteger(parsed.revealed) && parsed.revealed > 0 ? parsed.revealed : null;
247
+ const query = typeof parsed.query === "string" ? parsed.query.slice(0, 200) : "";
248
+ return { revealed, query };
249
+ } catch { return empty; }
250
+ }
251
+ function writeViewState(sessionKey, revealed, query) {
252
+ const key = viewStateKey(sessionKey);
253
+ if (key === null) return;
254
+ try {
255
+ const revealedOrNull = Number.isSafeInteger(revealed) && revealed > 0 ? revealed : null;
256
+ const queryText = typeof query === "string" ? query.slice(0, 200) : "";
257
+ if (revealedOrNull === null && queryText === "") { window.sessionStorage.removeItem(key); return; }
258
+ window.sessionStorage.setItem(key, JSON.stringify({ revealed: revealedOrNull, query: queryText }));
259
+ } catch { /* storage disabled or full: behave exactly as before */ }
260
+ }
261
+
262
+ function TraceMapView({ useSession, useTrajectory, t, viewRequest, completeViewRequest, loadOlder, sessionKey }) {
263
+ const scrollerRef = (0, react.useRef)(null);
264
+ const minimapRef = (0, react.useRef)(null);
265
+ const searchRef = (0, react.useRef)(null);
266
+ const initDone = (0, react.useRef)(false);
267
+ // Which session this panel is showing. The host reuses one component instance
268
+ // across conversation switches, so every piece of local UI state below (replay
269
+ // position, search text, selected tab, follow mode) survived the switch and was
270
+ // applied to a completely different transcript. `sessionKey` arrives from the
271
+ // slot's `inject`; when the host does not provide one, behaviour is unchanged.
272
+ const sessionRef = (0, react.useRef)(sessionKey);
273
+ // ── view state that survives a tab switch ─────────────────────────────
274
+ // The host UNMOUNTS this panel when the reader looks at the conversation and
275
+ // remounts it on return (measured: root count 0 → 1). Without this, every
276
+ // return dropped the reader back to the overview with the search box empty.
277
+ // Scoped per sessionKey in sessionStorage: per-tab, gone when the tab closes,
278
+ // and never shared between conversations.
279
+ const restoredRef = (0, react.useRef)(null);
280
+ if (restoredRef.current === null) restoredRef.current = readViewState(sessionKey);
281
+ // useState order matters (render-repro forces slot 4 = tab): keep these four first.
282
+ const [revealed, setRevealed] = (0, react.useState)(restoredRef.current.revealed); // null = overview (everything shown)
283
+ const [playing, setPlaying] = (0, react.useState)(false);
284
+ const [speedIdx, setSpeedIdx] = (0, react.useState)(0);
285
+ const [tab, setTab] = (0, react.useState)("detail");
286
+ const [queryRaw, setQueryRaw] = (0, react.useState)(restoredRef.current.query);
287
+ // -1 means "no match is current". The old 0 made the counter read "1/3" the
288
+ // moment the reader typed a query — while the timeline had not moved at all —
289
+ // and then the FIRST "next" went to match 2, so match 1 was only reachable by
290
+ // wrapping all the way round.
291
+ const [matchPtr, setMatchPtr] = (0, react.useState)(-1);
292
+ const [follow, setFollow] = (0, react.useState)(true);
293
+ const [panelFull, setPanelFull] = (0, react.useState)(false);
294
+ const [anchorNote, setAnchorNote] = (0, react.useState)(null);
295
+ const [clockAxis, setClockAxis] = (0, react.useState)(false);
296
+ const [olderBusy, setOlderBusy] = (0, react.useState)(false);
297
+ const [olderNote, setOlderNote] = (0, react.useState)(null);
298
+ const [exportState, setExportState] = (0, react.useState)("idle");
299
+ // One pending feedback timer for the export button (see doExport).
300
+ const exportResetRef = (0, react.useRef)(null);
301
+ const [anchorInput, setAnchorInput] = (0, react.useState)("");
302
+ const [hash, setHash] = (0, react.useState)(() => (typeof location !== "undefined" ? location.hash : ""));
303
+ /**
304
+ * Height of the host's floating composer that covers the bottom of our view.
305
+ * The composer is a sticky, z-index:7 overlay inside the conversation area, so
306
+ * our panel scrolls underneath it and the last rows become unreadable. Measure
307
+ * it at runtime instead of guessing a constant: its height changes with the
308
+ * input's line count and with the window width.
309
+ */
310
+ const [composerH, setComposerH] = (0, react.useState)(0);
311
+ /**
312
+ * Horizontal position of the replay marker, measured from the active station
313
+ * element rather than computed.
314
+ *
315
+ * The old formula `26 + (R-1)*STATION_W + STATION_W/2` assumed stations are
316
+ * 264px wide with no gaps. They are not: each station carries `padding:0 2px`,
317
+ * and idle bands of varying width sit between stations, so the marker drifted
318
+ * left by a growing amount and pointed at the PREVIOUS card (user reported
319
+ * "I picked step 66, it points at step 65"). Measuring the real element cannot
320
+ * drift, whatever the layout does later.
321
+ */
322
+ const [playheadLeft, setPlayheadLeft] = (0, react.useState)(null);
323
+
324
+ const snap = useTrajectory === void 0 ? EMPTY_SNAPSHOT : useTrajectory((v) => v ?? EMPTY_SNAPSHOT);
325
+ const hasMore = useSession((s) => s.hasMore === true);
326
+ const loadingOlder = useSession((s) => s.loadingOlder === true);
327
+ // The session reports `openState: "loading"` while its log is still being read
328
+ // (host enum: loading | open | error). Without it, a cold open renders the
329
+ // "no trajectory data yet" copy for a second or two — a false statement the
330
+ // user reads as "this session has nothing".
331
+ const sessionLoading = useSession((s) => s.openState === "loading");
332
+ // Live text still has to arrive, so `partial` is read through a ref and the
333
+ // rebuild is driven by a coarse tick instead of by every token. The memo key
334
+ // is the history slices plus "which step is streaming" — all of which change
335
+ // only when the tree actually has to change.
336
+ const streaming = snap.partial != null;
337
+ const partialSig = streaming ? `${snap.partial.turn ?? 0}:${snap.partial.step ?? 0}` : "";
338
+ const partialRef = (0, react.useRef)(null);
339
+ partialRef.current = snap.partial;
340
+ const [streamTick, setStreamTick] = (0, react.useState)(0);
341
+ (0, react.useEffect)(() => {
342
+ if (!streaming) return void 0;
343
+ // Rebuilding the whole tree while the tab is hidden burns CPU for a
344
+ // document nobody is looking at. The next tick after returning refreshes
345
+ // it anyway, so skipping hidden ticks loses nothing visible.
346
+ const id = setInterval(() => {
347
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
348
+ setStreamTick((v) => v + 1);
349
+ }, STREAM_REBUILD_MS);
350
+ return () => clearInterval(id);
351
+ }, [streaming, partialSig]);
352
+ const tree = (0, react.useMemo)(
353
+ () => deriveTraceTree({
354
+ eventNodes: snap.eventNodes,
355
+ requests: snap.requests,
356
+ callSchemas: snap.callSchemas,
357
+ runningCalls: snap.runningCalls,
358
+ partial: partialRef.current
359
+ }, t),
360
+ [snap.eventNodes, snap.requests, snap.callSchemas, snap.runningCalls, partialSig, streamTick, t]
361
+ );
362
+ const stations = tree.stations;
363
+ const stationsRef = (0, react.useRef)(stations);
364
+ stationsRef.current = stations;
365
+ const hasMoreRef = (0, react.useRef)(hasMore);
366
+ hasMoreRef.current = hasMore;
367
+ const N = stations.length;
368
+ const R = revealed === null ? N : Math.min(Math.max(1, revealed), N);
369
+ const stats = tree.stats;
370
+ const live = tree.currentStepNo !== null;
371
+
372
+ const speedMs = SPEEDS_MS[speedIdx] ?? SPEEDS_MS[0];
373
+
374
+ // Replay engine: advance the playhead while playing.
375
+ (0, react.useEffect)(() => {
376
+ if (!playing) return undefined;
377
+ // Same reasoning as the streaming tick: replay is a visual animation, so
378
+ // advancing it in a hidden tab only spends CPU. Playback resumes from the
379
+ // same position when the tab becomes visible again.
380
+ const id = setInterval(() => {
381
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
382
+ setRevealed((r) => (r === null ? N : Math.min(r, N) + 1));
383
+ }, speedMs);
384
+ return () => clearInterval(id);
385
+ }, [playing, speedMs, N]);
386
+
387
+ // Reset per-session UI state when the conversation changes. Runs only on an
388
+ // actual identity change, so mounting with a key already set is a no-op.
389
+ (0, react.useEffect)(() => {
390
+ const prev = sessionRef.current;
391
+ sessionRef.current = sessionKey;
392
+ if (prev === void 0 || sessionKey === void 0) return;
393
+ if (prev === sessionKey) return;
394
+ setPlaying(false);
395
+ setFollow(true);
396
+ setRevealed(null); // overview: show the whole new transcript
397
+ setQueryRaw("");
398
+ setMatchPtr(0);
399
+ setOlderNote(null);
400
+ setPanelFull(false);
401
+ setTab("detail");
402
+ }, [sessionKey]);
403
+
404
+ // Remember where the reader was, so a host-initiated remount resumes there.
405
+ (0, react.useEffect)(() => {
406
+ writeViewState(sessionKey, revealed, queryRaw);
407
+ }, [sessionKey, revealed, queryRaw]);
408
+
409
+ // Drop the export feedback timer with the panel, so a pending reset cannot fire
410
+ // against a component that no longer exists.
411
+ (0, react.useEffect)(() => () => {
412
+ if (exportResetRef.current !== null) { clearTimeout(exportResetRef.current); exportResetRef.current = null; }
413
+ }, []);
414
+
415
+ // Stop at the end.
416
+ (0, react.useEffect)(() => {
417
+ if (playing && R >= N) {
418
+ setPlaying(false);
419
+ setRevealed(null);
420
+ }
421
+ }, [R, playing, N]);
422
+
423
+ // Center the active station — scroll ONLY our own scroller (never outer ancestors).
424
+ /**
425
+ * "No motion" is a stated preference, not a cosmetic nit: replay auto-scroll
426
+ * and smooth centering are exactly the kind of movement it exists to stop.
427
+ * CSS alone cannot reach `scrollTo({behavior:"smooth"})`, so honour it here too.
428
+ */
429
+ const reduceMotion = () => {
430
+ try { return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; } catch { return false; }
431
+ };
432
+ // Measure the active station and place the marker over it. Runs after every
433
+ // render that can move it (selection, resize, history paging) and on scroll
434
+ // container resize, because offsets are relative to the flow element.
435
+ (0, react.useEffect)(() => {
436
+ if (revealed === null) { setPlayheadLeft(null); return undefined; }
437
+ const measureHead = () => {
438
+ const sc = scrollerRef.current;
439
+ if (sc === null) return;
440
+ const el = sc.querySelector(`[data-station-idx="${String(R - 1)}"]`);
441
+ if (el === null) return;
442
+ // offsetLeft is relative to the offsetParent (.dstv_hflow), which is the
443
+ // same coordinate space the absolutely positioned marker uses.
444
+ const docLeft = el.offsetLeft + el.offsetWidth / 2;
445
+ if (Number.isFinite(docLeft)) setPlayheadLeft(docLeft);
446
+ };
447
+ measureHead();
448
+ window.addEventListener("resize", measureHead);
449
+ return () => window.removeEventListener("resize", measureHead);
450
+ }, [revealed, R, N]);
451
+
452
+ /**
453
+ * Keep the active minimap tick inside the strip.
454
+ *
455
+ * The strip needs ~5px per station, so a long session cannot fit it (3,600
456
+ * stations = ~18,000px). It scrolls instead of dragging the panel sideways —
457
+ * but a scrolling strip that never follows the playhead shows only the OLDEST
458
+ * stations, so the "where am I" marker is permanently off-screen while the
459
+ * user steps forward. Scroll the strip to the active tick, and only the strip:
460
+ * `scrollIntoView` on an inner element also moves outer ancestors.
461
+ */
462
+ const revealTick = (idx) => {
463
+ const mm = minimapRef.current;
464
+ if (mm === null) return;
465
+ const el = mm.querySelector(`[data-tick-idx="${String(idx)}"]`);
466
+ if (el === null) return;
467
+ if (mm.scrollWidth <= mm.clientWidth + 1) return; // strip fits; nothing to do
468
+ const want = el.offsetLeft + el.offsetWidth / 2 - mm.clientWidth / 2;
469
+ const target = Math.max(0, Math.min(mm.scrollWidth - mm.clientWidth, want));
470
+ if (Math.abs(mm.scrollLeft - target) < 2) return;
471
+ mm.scrollLeft = target;
472
+ };
473
+ (0, react.useEffect)(() => {
474
+ if (revealed === null) return;
475
+ revealTick(R - 1);
476
+ }, [revealed, R, N]);
477
+
478
+ const centerStation = (idx) => {
479
+ const sc = scrollerRef.current;
480
+ if (sc === null) return;
481
+ const el = sc.querySelector(`[data-station-idx="${String(idx)}"]`);
482
+ if (el === null || typeof el.getBoundingClientRect !== "function") return;
483
+ const rect = el.getBoundingClientRect();
484
+ const srect = sc.getBoundingClientRect();
485
+ const target = Math.max(0, rect.left - srect.left + sc.scrollLeft + el.offsetWidth / 2 - sc.clientWidth / 2);
486
+ if (typeof sc.scrollTo === "function") {
487
+ try { sc.scrollTo({ left: target, behavior: reduceMotion() ? "auto" : "smooth" }); } catch { sc.scrollLeft = target; }
488
+ } else {
489
+ sc.scrollLeft = target;
490
+ }
491
+ };
492
+
493
+ (0, react.useEffect)(() => {
494
+ if (revealed === null) return;
495
+ // Under "reduce motion" an auto-scrolling replay is a position jump every
496
+ // tick — the exact movement the preference exists to stop. Keep the selected
497
+ // station in view only when the user is driving (follow), otherwise let
498
+ // replay advance without the viewport chasing it.
499
+ if (playing === true && reduceMotion() && follow !== true) return;
500
+ centerStation(R - 1);
501
+ }, [R, revealed]);
502
+
503
+ // First landing: if the AI is mid-flight, land on its current station.
504
+ (0, react.useEffect)(() => {
505
+ if (initDone.current || N === 0) return;
506
+ initDone.current = true;
507
+ const li = stations.findIndex((s) => s.kind === "step" && s.live === true);
508
+ if (li >= 0) setRevealed(li + 1);
509
+ }, [N, stations]);
510
+
511
+ /**
512
+ * Move the roving focus to a station: select it, scroll it into view and put
513
+ * the DOM focus there so the next ArrowRight continues from it.
514
+ */
515
+ const focusStation = (i) => {
516
+ seek(i);
517
+ const sc = scrollerRef.current;
518
+ if (sc === null) return;
519
+ const el = sc.querySelector(`[data-station-idx="${String(i)}"]`);
520
+ if (el === null) return;
521
+ if (typeof el.focus === "function") { try { el.focus({ preventScroll: true }); } catch { el.focus(); } }
522
+ centerStation(i);
523
+ };
524
+ const seek = (i) => {
525
+ setPlaying(false);
526
+ setFollow(false);
527
+ setRevealed(Math.min(N, Math.max(1, i + 1)));
528
+ };
529
+ const toStart = () => {
530
+ if (N === 0) return;
531
+ setPlaying(false);
532
+ setFollow(false);
533
+ setRevealed(1);
534
+ };
535
+ // The two directions must treat the OVERVIEW state symmetrically. `revealed`
536
+ // is null there (everything is shown, nothing selected) and `R` reads as N, so
537
+ // the old bodies behaved completely differently on the state the reader is in
538
+ // when the tab first opens:
539
+ // → `R < N` is false → `setRevealed(null)` → still null → THE KEY DID NOTHING
540
+ // ← `R > 1` is true → jumped to station N-1, skipping the newest one
541
+ // The hint says "← → 逐站", so the first thing a new reader tries is →, and it
542
+ // was inert on every session. Overview means "past the end": → restarts at the
543
+ // first station (exactly what the play button does), ← starts from the last.
544
+ const stepPrev = () => {
545
+ setPlaying(false);
546
+ setFollow(false);
547
+ if (revealed === null) { if (N > 0) setRevealed(N); return; }
548
+ if (R > 1) setRevealed(R - 1);
549
+ };
550
+ const stepNext = () => {
551
+ setPlaying(false);
552
+ setFollow(false);
553
+ if (revealed === null) { if (N > 0) setRevealed(1); return; }
554
+ if (R < N) setRevealed(R + 1);
555
+ else setRevealed(null);
556
+ };
557
+ const toEnd = () => {
558
+ setPlaying(false);
559
+ setFollow(true);
560
+ setRevealed(null);
561
+ };
562
+ const togglePlay = () => {
563
+ if (N === 0) return;
564
+ if (playing) { setPlaying(false); return; }
565
+ setFollow(false);
566
+ const cur = revealed === null ? N : Math.min(revealed, N);
567
+ if (cur >= N) setRevealed(1);
568
+ setPlaying(true);
569
+ };
570
+ const cycleSpeed = () => setSpeedIdx((i) => (i + 1) % SPEEDS_MS.length);
571
+
572
+ const locateCurrent = () => {
573
+ const li = stations.findIndex((s) => s.kind === "step" && s.live === true);
574
+ if (li < 0 || scrollerRef.current === null) return;
575
+ setPlaying(false);
576
+ setRevealed(li + 1);
577
+ };
578
+
579
+ // ── chat → trace deep link: reveal the station owning inspect.callId ──
580
+ // ── anchor deep links (§4.4) ─────────────────────────────────────────
581
+ // Two entry points: the official `viewRequest.focus` handed to views by
582
+ // conversation.view, and our own `#tvp1:...` hash. Both funnel into
583
+ // resolveAnchorInStations; synthetic hits are reported, never silently
584
+ // redirected.
585
+ const focusAnchor = viewRequest != null && typeof viewRequest.focus === "string" ? viewRequest.focus : null;
586
+ let decodedHashAnchor = null;
587
+ try { decodedHashAnchor = typeof location !== "undefined" && location.hash !== "" ? decodeURIComponent(location.hash.replace(/^#/, "")) : null; } catch { decodedHashAnchor = null; }
588
+ // `hash` is read through state so a hashchange re-runs this whole block.
589
+ const hashAnchorNow = decodedHashAnchor;
590
+ const anchorToApply = focusAnchor ?? (hashAnchorNow !== null && hashAnchorNow !== "" ? hashAnchorNow : null);
591
+ // Stable identity for "which anchor am I currently trying to land on", so the
592
+ // resolve effect can track the attempt itself instead of the raw props.
593
+ // `anchorInput` must NOT be part of this token. It is the typed value, and the
594
+ // typed value is applied by the Enter handler — putting it here made the effect
595
+ // re-run on EVERY keystroke, so typing `tvp1:t2s1` fired eight failed parses and
596
+ // flashed "unrecognised anchor format" eight times before the ninth succeeded.
597
+ const anchorToken = (0, react.useMemo)(() => [anchorToApply, hash].map((v) => (typeof v === "string" ? v : "")).join("\u0000"), [anchorToApply, hash]);
598
+ // An anchor search can page for tens of seconds. If the panel unmounts (the
599
+ // host re-mounts the view on a conversation switch) or the session changes,
600
+ // the loop kept going: `stationsRef` freezes at its last value, so the
601
+ // "did the projection change?" test never sees progress, the inner back-off
602
+ // runs all 12 tries, and the next page still reports growth — up to 40 pages
603
+ // of history pulled for a session nobody is looking at. Nothing it then calls
604
+ // can be seen, so every await must re-check whether we are still here.
605
+ const aliveRef = (0, react.useRef)(true);
606
+ (0, react.useEffect)(() => {
607
+ aliveRef.current = true;
608
+ return () => { aliveRef.current = false; };
609
+ }, [sessionKey]);
610
+ const anchorApply = (0, react.useCallback)(async (raw) => {
611
+ const parsed = parseAnchor(raw);
612
+ if (parsed.ok !== true) {
613
+ setAnchorNote(t("anchor.bad"));
614
+ return false;
615
+ }
616
+ // 1) already loaded? then this is pure navigation
617
+ let resolved = resolveAnchorInStations(parsed, stationsRef.current);
618
+ // Set when back-paging stopped at the page budget while history still exists.
619
+ let capHit = false;
620
+ // 2) not loaded: page backwards until the target appears.
621
+ // Deliberately NOT `session.loadThrough(seq)`: measured on a real session,
622
+ // loadThrough only moves `baseSeq` / `hasMore` on the session snapshot and
623
+ // never rebuilds the trajectory projection, so the stations list stays put
624
+ // (57 -> 57 even after it reported success). `loadOlder` does re-project
625
+ // (57 -> 118), so that is the only paging that can actually reveal a node.
626
+ // Paging is bounded by BOTH the page budget and the seq we were asked for.
627
+ if (resolved.ok !== true && resolved.reason === "not-loaded") {
628
+ const target = anchorLoadTarget(parsed);
629
+ setAnchorNote(t("anchor.searching"));
630
+ let pages = 0;
631
+ // Why paging stopped matters to the user: "hit the page budget but more
632
+ // history exists" is recoverable (pull manually and retry), while "no more
633
+ // history" means the record is simply not in this session.
634
+ let capped = false;
635
+ while (resolved.ok !== true && pages < ANCHOR_MAX_PAGES && hasMoreRef.current === true) {
636
+ // Stop as soon as the window provably covers the anchor: paging
637
+ // further back can only add older records, never the requested one.
638
+ // Applies to `e` (by seq) and `p`/`t` (by turn) — the latter used to
639
+ // fall through to the page budget every time.
640
+ if (target !== 0 || parsed.form === "p" || parsed.form === "t") {
641
+ if (anchorCoveredByWindow(parsed, stationsRef.current)) break;
642
+ }
643
+ if (aliveRef.current !== true) return false;
644
+ const before = stationsRef.current.length;
645
+ const beforeArr = stationsRef.current;
646
+ let moved = false;
647
+ try { moved = await loadOlder(); } catch { moved = false; }
648
+ if (aliveRef.current !== true) return false;
649
+ pages += 1;
650
+ // A deep link can legitimately page 40 times (measured 101 s on a
651
+ // long session). A static "loading…" gave no sign of progress, so
652
+ // the user could not tell a slow search from a hung one.
653
+ setAnchorNote(t("anchor.searchingPages")
654
+ .replace("{n}", String(pages))
655
+ .replace("{max}", String(ANCHOR_MAX_PAGES))
656
+ .replace("{stations}", String(stationsRef.current.length)));
657
+ // Wait for the derived tree to catch up, then re-resolve.
658
+ // Back off instead of always paying a full 250 ms: React normally
659
+ // re-derives within a frame, so the first check is cheap and later
660
+ // ones stretch out. Deep links page up to 40 times, and the fixed
661
+ // delay alone added ~10 s to that path.
662
+ //
663
+ // Do NOT re-scan the same list. Re-running the O(n) anchor scan over
664
+ // an unchanged array returned "not-loaded" every time it already had,
665
+ // for nothing — up to 12 times a page, 40 pages deep, with 3,600
666
+ // stations in the window. Scan only once the projection replaced the
667
+ // array (identity, not length: see below).
668
+ for (let i = 0; i < ANCHOR_REVEAL_TRIES; i += 1) {
669
+ await new Promise((r) => setTimeout(r, Math.min(ANCHOR_REVEAL_MS, 20 * 2 ** i)));
670
+ if (aliveRef.current !== true) return false;
671
+ // Identity, not just length: the derived tree builds a NEW array
672
+ // every projection, so an unchanged reference is the only cheap
673
+ // proof that re-scanning would return exactly what it returned
674
+ // before. A same-length replacement (which paging never does, but
675
+ // a re-projection could) still gets scanned.
676
+ if (stationsRef.current === beforeArr) continue;
677
+ resolved = resolveAnchorInStations(parsed, stationsRef.current);
678
+ break;
679
+ }
680
+ if (resolved.ok === true) break;
681
+ if (stationsRef.current.length === before && moved !== true) break; // no progress
682
+ }
683
+ capped = resolved.ok !== true && pages >= ANCHOR_MAX_PAGES && hasMoreRef.current === true;
684
+ capHit = capped;
685
+ }
686
+ if (resolved.ok !== true) {
687
+ setAnchorNote(
688
+ resolved.reason === "synthetic" || resolved.reason === "synthetic-tool" ? t("anchor.notPersisted")
689
+ : resolved.reason !== "not-loaded" ? t("anchor.bad")
690
+ : capHit ? t("anchor.capped").replace("{n}", String(ANCHOR_MAX_PAGES))
691
+ : t("anchor.notLoaded"));
692
+ return false;
693
+ }
694
+ const idx = stationsRef.current.indexOf(resolved.station);
695
+ if (idx >= 0) {
696
+ setPlaying(false);
697
+ setFollow(false);
698
+ setRevealed(idx + 1);
699
+ setTab("detail");
700
+ }
701
+ if (resolved.synthetic === true) setAnchorNote(t("anchor.notPersisted"));
702
+ else if (typeof resolved.upgraded === "string") setAnchorNote(t("anchor.upgraded").replace("{ref}", `${ANCHOR_PREFIX}${resolved.upgraded}`));
703
+ else setAnchorNote(null);
704
+ return true;
705
+ }, [t, loadOlder]);
706
+ // One search at a time, whichever entry point asked for it (see
707
+ // createFlightGuard: only an identical anchor is deduplicated).
708
+ const anchorFlight = (0, react.useMemo)(() => createFlightGuard(), []);
709
+ const anchorApplyGuarded = (raw) => {
710
+ // Both entry points (the URL/view request effect and the typed jump) go
711
+ // through here, so the liveness check belongs here rather than duplicated in
712
+ // each `.then`: a search that outlives the panel must not report success and
713
+ // then write its anchor into whatever conversation is on screen now.
714
+ if (aliveRef.current !== true) return Promise.resolve(false);
715
+ if (!anchorFlight.tryStart(raw)) return Promise.resolve(false);
716
+ return Promise.resolve(anchorApply(raw)).finally(() => anchorFlight.finish(raw));
717
+ };
718
+ // Tracks which anchor token has already been applied. The effect used to depend
719
+ // on `N` as well, so EVERY new station (a live session) re-ran it: it re-applied
720
+ // the anchor that had just been mirrored into the URL and yanked `revealed` back,
721
+ // so a deep-linked reader could not step away from the anchor at all.
722
+ const appliedAnchorRef = (0, react.useRef)(null);
723
+ (0, react.useEffect)(() => {
724
+ if (N === 0) return;
725
+ // Only the URL / view-request path runs here; a typed anchor is applied by
726
+ // the Enter handler, which is the moment the user actually asked for it.
727
+ const wanted = anchorToApply !== null && anchorToApply !== "" ? anchorToApply : "";
728
+ if (wanted === "") return;
729
+ // `N` must stay in the dependency list: a deep link can arrive before the
730
+ // projection has any stations, and the retry on growth is what makes it
731
+ // land at all. What must NOT happen is re-applying an anchor that already
732
+ // succeeded — that is what yanked the reader back. So remember only the
733
+ // token that LANDED; a failed attempt stays retryable.
734
+ if (appliedAnchorRef.current === anchorToken) return;
735
+ let cancelled = false;
736
+ void anchorApplyGuarded(wanted).then((ok) => {
737
+ if (cancelled) return;
738
+ if (ok) appliedAnchorRef.current = anchorToken;
739
+ // a successful landing becomes shareable: mirror it into the URL
740
+ if (ok && typeof location !== "undefined") {
741
+ const next = nextHashFor(location.hash, wanted);
742
+ if (next.changed === true) {
743
+ try { history.replaceState(null, "", next.hash); setHash(next.hash); } catch { /* hash is a convenience, never fatal */ }
744
+ }
745
+ }
746
+ });
747
+ if (typeof completeViewRequest === "function") completeViewRequest();
748
+ return () => { cancelled = true; };
749
+ }, [anchorToken, N]);
750
+
751
+ // hash navigation: a pasted/retyped #tvp1:... (or browser back) must land too
752
+ (0, react.useEffect)(() => {
753
+ if (typeof window === "undefined") return void 0;
754
+ const onHash = () => setHash(typeof location !== "undefined" ? location.hash : "");
755
+ window.addEventListener("hashchange", onHash);
756
+ return () => window.removeEventListener("hashchange", onHash);
757
+ }, []);
758
+
759
+ // ── host composer clearance ───────────────────────────────────────────
760
+ (0, react.useEffect)(() => {
761
+ const measure = () => {
762
+ const seat = document.querySelector('[class*="composerSeat"]');
763
+ if (seat === null) { setComposerH(0); return; }
764
+ const r = seat.getBoundingClientRect();
765
+ // Only reserve space when it really floats over the viewport bottom.
766
+ const covered = r.height > 0 && r.bottom >= window.innerHeight - 24 ? Math.round(r.height) : 0;
767
+ setComposerH((prev) => (prev === covered ? prev : covered));
768
+ };
769
+ // Polling is the only reliable way to notice the composer growing (its
770
+ // height depends on the input's line count), but a hidden tab does not
771
+ // need it: pause while the document is hidden and re-measure on return.
772
+ const onVisible = () => { if (document.visibilityState === "visible") measure(); };
773
+ measure();
774
+ window.addEventListener("resize", measure);
775
+ document.addEventListener("visibilitychange", onVisible);
776
+ const id = window.setInterval(() => {
777
+ if (document.visibilityState !== "hidden") measure();
778
+ }, 1500);
779
+ return () => {
780
+ window.removeEventListener("resize", measure);
781
+ document.removeEventListener("visibilitychange", onVisible);
782
+ window.clearInterval(id);
783
+ };
784
+ }, []);
785
+
786
+ // ── keep host form fields auditable (see annotateNamelessFormFields) ──
787
+ // The host sidebar builds its session search lazily, so a single pass on mount
788
+ // can run before it exists. Poll for a bounded window instead of watching the
789
+ // whole document forever; each pass is a cheap attribute check that returns
790
+ // immediately once every field has an id.
791
+ (0, react.useEffect)(() => {
792
+ annotateNamelessFormFields();
793
+ let ticks = 0;
794
+ const id = window.setInterval(() => {
795
+ ticks += 1;
796
+ annotateNamelessFormFields();
797
+ if (ticks >= 40) window.clearInterval(id);
798
+ }, 500);
799
+ return () => window.clearInterval(id);
800
+ }, []);
801
+
802
+ // ── follow mode: keep the newest station in view while live ──────────
803
+ (0, react.useEffect)(() => {
804
+ if (!follow || revealed !== null) return;
805
+ const sc = scrollerRef.current;
806
+ if (sc === null) return;
807
+ try { sc.scrollLeft = sc.scrollWidth; } catch { /* noop */ }
808
+ }, [N, follow, revealed]);
809
+
810
+ // ── search ────────────────────────────────────────────────────────────
811
+ const query = String(queryRaw ?? "").trim();
812
+ const matches = (0, react.useMemo)(() => matchStations(stations, query), [stations, query]);
813
+ const matchSet = (0, react.useMemo)(() => new Set(matches), [matches]);
814
+ const searching = query !== "";
815
+ const scopeNote = searchScopeNote(hasMore, loadingOlder, t);
816
+ (0, react.useEffect)(() => { setMatchPtr(-1); }, [query]);
817
+ const gotoMatch = (dir) => {
818
+ if (matches.length === 0) return;
819
+ // A fresh query has no current match yet, so the FIRST step has to land on an
820
+ // end of the ring — not on match 2 of 3. Clamp covers the stale-pointer case
821
+ // where the match set shrank between keystrokes.
822
+ const base = matchPtr < 0 || matchPtr >= matches.length ? (dir > 0 ? -1 : 0) : matchPtr;
823
+ const next = ((base + dir) % matches.length + matches.length) % matches.length;
824
+ setMatchPtr(next);
825
+ seek(matches[next]);
826
+ };
827
+ const onSearchKey = (ev) => {
828
+ ev.stopPropagation();
829
+ if (ev.key === "Enter") { gotoMatch(ev.shiftKey ? -1 : 1); ev.preventDefault(); }
830
+ else if (ev.key === "Escape") { setQueryRaw(""); ev.preventDefault(); }
831
+ };
832
+ const clearSearch = () => {
833
+ setQueryRaw("");
834
+ if (searchRef.current !== null && typeof searchRef.current.focus === "function") searchRef.current.focus();
835
+ };
836
+
837
+ /**
838
+ * Keep the SAME station selected when the window grows backwards.
839
+ *
840
+ * `revealed` is a position, so paging in earlier history inserted stations
841
+ * before the current one and silently moved the reader to a different record
842
+ * (a selected `e30` became `e20`). Station ids are stable across rebuilds, so
843
+ * remember the selected id and re-derive the position from it.
844
+ */
845
+ const selectedIdRef = (0, react.useRef)(null);
846
+ const stationsSignature = (0, react.useMemo)(() => stations.map((st) => st.id).join("\u0000"), [stations]);
847
+ // Read the station from the list directly: `activeStation` is declared further
848
+ // down, and touching a `const` before its declaration throws ReferenceError on
849
+ // EVERY render — the whole view failed to mount from 0.9.23 to 0.9.25.
850
+ // Record the identity ONLY when the user's selection changes — never when the
851
+ // station list changes. Depending on the id itself re-ran this effect after a
852
+ // backwards page (same position, different station) and OVERWROTE the pinned
853
+ // id with whatever now sat at that index, so the repair effect then "confirmed"
854
+ // the wrong station. Verified live: e29532 became e28913 after loading history.
855
+ const prevRevealedRef = (0, react.useRef)(revealed);
856
+ (0, react.useEffect)(() => {
857
+ const selectionChanged = prevRevealedRef.current !== revealed;
858
+ prevRevealedRef.current = revealed;
859
+ if (!selectionChanged) return;
860
+ selectedIdRef.current = revealed === null ? null
861
+ : (stationsRef.current[Math.min(stationsRef.current.length - 1, Math.max(0, revealed - 1))]?.id ?? null);
862
+ // stationsRef is intentionally read through the ref: depending on `stations`
863
+ // here would re-fire on paging, which is the bug being fixed.
864
+ // eslint-disable-next-line react-hooks/exhaustive-deps
865
+ }, [revealed]);
866
+ (0, react.useEffect)(() => {
867
+ const id = selectedIdRef.current;
868
+ if (id === null) return;
869
+ const at = stations.findIndex((st) => st.id === id);
870
+ // Gone from the window (should not happen for a prepend) or already correct.
871
+ if (at < 0 || at + 1 === revealed) return;
872
+ setRevealed(at + 1);
873
+ // Depends on the station list only: this is a repair pass after it changes.
874
+ // eslint-disable-next-line react-hooks/exhaustive-deps
875
+ }, [stationsSignature]);
876
+
877
+ // ── turn hopping ──────────────────────────────────────────────────────
878
+ const turnStarts = (0, react.useMemo)(() => {
879
+ const out = [];
880
+ for (let i = 0; i < stations.length; i += 1) if (stations[i].tag != null) out.push(i);
881
+ return out;
882
+ }, [stations]);
883
+ const chosenIdx = Math.min(N - 1, Math.max(0, revealed !== null ? R - 1 : N - 1));
884
+ const activeIdx = chosenIdx;
885
+ const activeStation = stations[activeIdx]; // undefined while N === 0 (empty view)
886
+ // Lazy: rebuild the model-visible message list only for the selected step.
887
+ // (Hook sits above the empty-state early return so hook order never changes.)
888
+ const activeReqStartSeq = activeStation !== void 0 && activeStation.kind === "step" && activeStation.request !== null ? activeStation.request.startSeq : null;
889
+ const activeMessages = (0, react.useMemo)(() => (activeReqStartSeq != null ? reconstructMessages(tree.nodes ?? [], activeReqStartSeq, t) : []), [activeReqStartSeq, tree.nodes]);
890
+ /**
891
+ * The "copy this step" Markdown is built from every tool result in the step, so
892
+ * it is expensive (663 ms for a 256 KB result — 100% of that render). It is only
893
+ * read when the button is clicked, and was recomputed on every render: replay,
894
+ * search typing, hover. Memoise it on the inputs it actually depends on.
895
+ */
896
+ const stepMarkdown = (0, react.useMemo)(() => (activeStation === void 0 ? "" : buildStepMarkdown(activeStation, activeMessages, hasMore, t)), [activeStation, activeMessages, hasMore, t]);
897
+ const jumpTurn = (dir) => {
898
+ if (turnStarts.length === 0) return;
899
+ let target = -1;
900
+ if (dir < 0) {
901
+ for (let i = turnStarts.length - 1; i >= 0; i -= 1) if (turnStarts[i] < activeIdx) { target = turnStarts[i]; break; }
902
+ if (target < 0) target = turnStarts[0];
903
+ } else {
904
+ for (let i = 0; i < turnStarts.length; i += 1) if (turnStarts[i] > activeIdx) { target = turnStarts[i]; break; }
905
+ if (target < 0) target = turnStarts[turnStarts.length - 1];
906
+ }
907
+ seek(target);
908
+ };
909
+
910
+ // ── load older history ────────────────────────────────────────────────
911
+ // `hasMore` says the SESSION has older history; it says nothing about whether
912
+ // this view was handed a way to fetch it. The slot's `inject` returns `{}` when
913
+ // the session binding is gone, so `loadOlder` can legitimately be absent while
914
+ // `hasMore` is still true — and the button was rendered ENABLED and did nothing
915
+ // at all when pressed, because `doLoadOlder` bails out silently. A control that
916
+ // looks clickable and provably cannot act is worse than no control.
917
+ const canPage = typeof loadOlder === "function";
918
+ const doLoadOlder = () => {
919
+ if (!canPage || olderBusy === true || loadingOlder) return;
920
+ setOlderBusy(true);
921
+ setOlderNote(null);
922
+ Promise.resolve()
923
+ .then(() => loadOlder())
924
+ // A failed page used to be indistinguishable from a fast one: the button
925
+ // flipped to "loading", flipped back, and the timeline did not grow. The
926
+ // user retries a request that is already being refused (offline, expired
927
+ // session, host error) with no way to know why nothing appears.
928
+ .catch(() => setOlderNote(t("action.loadOlderFailed")))
929
+ .finally(() => setOlderBusy(false));
930
+ };
931
+
932
+ // ── export the whole trace as Markdown study notes ────────────────────
933
+ const doExport = (ev) => {
934
+ if (ev != null && typeof ev.stopPropagation === "function") ev.stopPropagation();
935
+ const md = buildTraceMarkdown(tree, t);
936
+ // Same rule as CopyBtn: a failed copy is a real outcome (non-secure context,
937
+ // refused permission), and returning silently made the button look dead —
938
+ // the user believes the whole trace is on the clipboard when it is not.
939
+ copyText(md, (ok) => {
940
+ setExportState(ok ? "ok" : "fail");
941
+ // Same one-timer rule as CopyBtn: without clearing the previous timer a
942
+ // second click's feedback is wiped early by the first click's timeout.
943
+ if (exportResetRef.current !== null) clearTimeout(exportResetRef.current);
944
+ exportResetRef.current = setTimeout(() => { exportResetRef.current = null; setExportState("idle"); }, 1600);
945
+ });
946
+ };
947
+
948
+ /**
949
+ * Keyboard/screen-reader access. The timeline is a horizontal list of items,
950
+ * so it announces itself as one and lets Tab land on the current station
951
+ * (roving tabindex) instead of forcing a pass over ~66 tab stops. Arrow keys
952
+ * keep their playback meaning on the root handler; a FOCUSED station uses
953
+ * them to move selection, which is what a listbox user expects.
954
+ */
955
+ const stationOnKeyDown = (ev, i) => {
956
+ // Same rule as the panel-level handler: a station button must not swallow a
957
+ // browser shortcut. It calls stopPropagation, so the guard above cannot help.
958
+ if (ev.ctrlKey === true || ev.metaKey === true || ev.altKey === true) return;
959
+ const k = ev.key;
960
+ if (k === "ArrowRight" || k === "ArrowDown") {
961
+ const next = Math.min(N - 1, i + 1);
962
+ focusStation(next); ev.preventDefault(); ev.stopPropagation();
963
+ } else if (k === "ArrowLeft" || k === "ArrowUp") {
964
+ const prev = Math.max(0, i - 1);
965
+ focusStation(prev); ev.preventDefault(); ev.stopPropagation();
966
+ } else if (k === "Home") {
967
+ focusStation(0); ev.preventDefault(); ev.stopPropagation();
968
+ } else if (k === "End") {
969
+ focusStation(N - 1); ev.preventDefault(); ev.stopPropagation();
970
+ } else if (k === "Enter" || k === " ") {
971
+ seek(i); ev.preventDefault(); ev.stopPropagation();
972
+ }
973
+ };
974
+ const onKeyDown = (ev) => {
975
+ const k = ev.key;
976
+ // Browser and OS shortcuts must win. The panel root is focusable
977
+ // (`tabIndex: 0`), so once the user clicks anywhere inside it these keys
978
+ // arrive here first: Ctrl/Cmd+R stopped reloading the page and toggled the
979
+ // request tab, Ctrl/Cmd+F stopped browser find and focused our search box,
980
+ // Alt+Left stopped going back and stepped the timeline, Ctrl+Home stopped
981
+ // scrolling to the top. Bail out on any modifier combination.
982
+ if (ev.ctrlKey === true || ev.metaKey === true || ev.altKey === true) return;
983
+ const tag = ev.target && ev.target.tagName ? String(ev.target.tagName).toLowerCase() : "";
984
+ if (tag === "input" || tag === "textarea" || tag === "select" || (ev.target && ev.target.isContentEditable === true)) return;
985
+ if (k === "/" || k === "f") {
986
+ if (searchRef.current !== null && typeof searchRef.current.focus === "function") { searchRef.current.focus(); ev.preventDefault(); }
987
+ return;
988
+ }
989
+ // Space activates buttons, summaries (toggle <details>) and links by
990
+ // default. The old guard excluded only `button`, so pressing Space on a
991
+ // `<summary>` both toggled the section and started playback.
992
+ if (k === " " && (tag === "button" || tag === "summary" || tag === "a")) return;
993
+ if (k === "ArrowRight") { stepNext(); ev.preventDefault(); }
994
+ else if (k === "ArrowLeft") { stepPrev(); ev.preventDefault(); }
995
+ else if (k === "Home") { toStart(); ev.preventDefault(); }
996
+ else if (k === "End") { toEnd(); ev.preventDefault(); }
997
+ else if (k === " ") { togglePlay(); ev.preventDefault(); }
998
+ else if (k === "PageUp") { jumpTurn(-1); ev.preventDefault(); }
999
+ else if (k === "PageDown") { jumpTurn(1); ev.preventDefault(); }
1000
+ else if (k === "r" || k === "R") {
1001
+ const aSt = stations[activeIdx];
1002
+ const can = aSt !== void 0 && ((aSt.kind === "step" && aSt.request !== null) || (aSt.kind === "compaction" && aSt.crequest != null));
1003
+ if (can) { setTab(tab === "request" ? "detail" : "request"); ev.preventDefault(); }
1004
+ }
1005
+ };
1006
+
1007
+ const fmtClock = (ms) => {
1008
+ // Guard: reject missing/implausible values (seq numbers sneak in as < year 2000).
1009
+ if (ms == null || !Number.isFinite(ms) || ms < 946684800000) return "";
1010
+ try { return new Date(ms).toLocaleTimeString(); } catch { return ""; }
1011
+ };
1012
+
1013
+ const legendItems = [
1014
+ { color: "var(--dstv-info)", label: t("node.user") },
1015
+ { color: "var(--dstv-ok)", label: t("node.step") },
1016
+ { color: "var(--dstv-warn)", label: t("node.tool") },
1017
+ { color: "var(--dstv-unknown)", label: t("node.compaction") },
1018
+ { color: "var(--dstv-err)", label: t("meta.error") }
1019
+ ];
1020
+
1021
+ const header = jsxs("div", {
1022
+ className: "dstv_head",
1023
+ children: [
1024
+ jsx("span", { className: "dstv_title", children: t("view.label") }, "hTitle"),
1025
+ tree.currentStepNo !== null ? jsxs("span", {
1026
+ className: "dstv_stat",
1027
+ children: [
1028
+ jsx("i", { className: "dstv_dot", "data-live": true }, "hDot"),
1029
+ `${t("stat.current")} ${t("node.step")} ${String(tree.currentStepNo)}`
1030
+ ]
1031
+ }, "hLive") : null,
1032
+ jsx("span", {
1033
+ className: "dstv_legend",
1034
+ children: legendItems.map((item) => jsxs("span", { children: [jsx("i", { style: { background: item.color } }, "lgDot"), item.label] }, item.label))
1035
+ }, "hLegend"),
1036
+ N > 0 ? jsxs("span", {
1037
+ className: "dstv_transport",
1038
+ children: [
1039
+ jsx("button", { type: "button", className: "dstv_tbtn", title: t("action.toStart"), "aria-label": t("action.toStart"), onClick: toStart, children: jsx("span", { "aria-hidden": "true", children: "⏮" }, "toStartIc") }, "toStart"),
1040
+ jsx("button", { type: "button", className: "dstv_tbtn", title: t("action.prevTurn"), "aria-label": t("action.prevTurn"), onClick: () => jumpTurn(-1), children: jsx("span", { "aria-hidden": "true", children: "⇤" }, "prevTurnIc") }, "prevTurn"),
1041
+ jsx("button", { type: "button", className: "dstv_tbtn", title: t("action.prev"), "aria-label": t("action.prev"), onClick: stepPrev, children: jsx("span", { "aria-hidden": "true", children: "◀" }, "prevIc") }, "prev"),
1042
+ jsx("button", { type: "button", className: "dstv_tbtn dstv_playBtn", title: playing ? t("action.pause") : t("action.play"), "aria-label": playing ? t("action.pause") : t("action.play"), onClick: togglePlay, children: jsx("span", { "aria-hidden": "true", children: playing ? "❚❚" : "▶" }, "playIc") }, "play"),
1043
+ jsx("button", { type: "button", className: "dstv_tbtn", title: t("action.nextTurn"), "aria-label": t("action.nextTurn"), onClick: () => jumpTurn(1), children: jsx("span", { "aria-hidden": "true", children: "⇥" }, "nextTurnIc") }, "nextTurn"),
1044
+ jsx("button", { type: "button", className: "dstv_tbtn", title: t("action.toEnd"), "aria-label": t("action.toEnd"), onClick: toEnd, children: jsx("span", { "aria-hidden": "true", children: "⏭" }, "toEndIc") }, "toEnd"),
1045
+ jsx("button", { type: "button", className: "dstv_tbtn", title: t("action.speed"), "aria-label": `${t("action.speed")} ${SPEED_LABELS[speedIdx] ?? SPEED_LABELS[0]}`, onClick: cycleSpeed, children: SPEED_LABELS[speedIdx] ?? SPEED_LABELS[0] }, "speed"),
1046
+ jsx("button", { type: "button", className: "dstv_tbtn", "data-on": follow ? "true" : undefined, title: t("action.follow"), "aria-label": t("action.follow"), "aria-pressed": follow ? "true" : "false", onClick: () => setFollow((f) => !f), children: jsx("span", { "aria-hidden": "true", children: "⇣" }, "followIc") }, "follow")
1047
+ ]
1048
+ }, "hTransport") : null,
1049
+ tree.currentStepNo !== null ? jsx("button", { type: "button", className: "dstv_btn", title: t("action.locate"), onClick: locateCurrent, children: `⌖ ${t("action.locate")}` }, "hLocate") : null,
1050
+ hasMore ? jsx("button", {
1051
+ type: "button",
1052
+ className: "dstv_btn",
1053
+ title: t("action.loadOlder"),
1054
+ disabled: !canPage || olderBusy === true || loadingOlder,
1055
+ onClick: doLoadOlder,
1056
+ children: olderBusy === true || loadingOlder ? `⏳ ${t("action.loadingOlder")}` : `⬆ ${t("action.loadOlder")}`
1057
+ }, "hOlder") : null,
1058
+ N > 0 ? jsx("button", {
1059
+ type: "button",
1060
+ className: "dstv_btn",
1061
+ "data-on": clockAxis ? "true" : undefined,
1062
+ title: t("action.clockAxisHint"),
1063
+ onClick: () => setClockAxis((v) => !v),
1064
+ children: clockAxis ? `⏱ ${t("action.clockAxisOn")}` : `⏱ ${t("action.clockAxis")}`
1065
+ }, "hClock") : null,
1066
+ N > 0 ? jsx("button", {
1067
+ type: "button",
1068
+ className: "dstv_btn",
1069
+ title: t("action.exportMd"),
1070
+ onClick: doExport,
1071
+ "data-fail": exportState === "fail" ? "true" : undefined,
1072
+ children: exportState === "ok" ? `✓ ${t("action.exported")}`
1073
+ : exportState === "fail" ? `✗ ${t("anchor.copyFailed")}`
1074
+ : "📋 Markdown"
1075
+ }, "hExport") : null,
1076
+ stats.lastModel != null ? jsx("span", { className: "dstv_modelChip", title: stats.lastModel, children: `🤖 ${stats.lastModel}` }, "hModel") : null,
1077
+ // Announce anchor progress: paging can take many seconds with no other
1078
+ // feedback for screen-reader users (the chip changing is silent).
1079
+ jsx("span", { className: "dstv_visuallyHidden", "aria-live": "polite", "aria-atomic": "true", children: [anchorNote, olderNote].filter((x) => x !== null).join(" · ") }, "hAnchorLive"),
1080
+ anchorNote !== null ? jsx("span", { className: "dstv_chip warn", title: anchorNote, children: anchorNote }, "hAnchorNote") : null,
1081
+ olderNote !== null ? jsx("span", { className: "dstv_chip warn", title: olderNote, children: olderNote }, "hOlderNote") : null,
1082
+ // A malformed record alongside healthy ones used to be reported ONLY on the
1083
+ // empty branch, so a partly-broken session looked perfectly fine in the
1084
+ // header while silently dropping data.
1085
+ tree.contract != null && tree.contract.ok !== true && N > 0 ? jsx("span", {
1086
+ className: "dstv_chip warn",
1087
+ title: `${t("view.malformedTip")} [${(tree.contract.problems ?? []).join(", ")}]`,
1088
+ children: `⚠ ${t("view.malformed").replace("{n}", String(tree.contract.problems.length))}`
1089
+ }, "hMalformed") : null,
1090
+ tree.nodeStats != null && tree.nodeStats.unknown > 0 ? jsx("span", {
1091
+ className: "dstv_chip warn",
1092
+ title: `${t("view.driftTip")}${tree.nodeStats.kinds.length > 0 ? ` [${tree.nodeStats.kinds.join(", ")}]` : ""}`,
1093
+ children: `⚠ ${t("view.drift").replace("{n}", String(tree.nodeStats.unknown))}`
1094
+ }, "hDrift") : null,
1095
+ tree.unplacedRequests > 0 ? jsx("span", {
1096
+ className: "dstv_warn",
1097
+ title: t("view.unplacedReqTip"),
1098
+ children: `⚠ ${t("view.unplacedReq").replace("{n}", String(tree.unplacedRequests))}`
1099
+ }, "hReq") : null,
1100
+ tree.nodeStats != null && tree.nodeStats.invalid > 0 ? jsx("span", {
1101
+ className: "dstv_chip warn",
1102
+ title: t("view.invalidTip"),
1103
+ children: `⚠ ${t("view.invalid").replace("{n}", String(tree.nodeStats.invalid))}`
1104
+ }, "hInvalid") : null,
1105
+ jsxs("span", {
1106
+ className: "dstv_search dstv_anchorBar",
1107
+ "data-active": anchorInput.trim() !== "" ? "true" : undefined,
1108
+ children: [
1109
+ jsx("span", { className: "dstv_sbtn", style: { cursor: "default" }, children: "🔗" }, "aIco"),
1110
+ jsx("input", {
1111
+ className: "dstv_searchInput dstv_anchorInput",
1112
+ // `id` + `name` are not decoration: browsers key autofill and form
1113
+ // semantics on them, and DevTools flags the field as nameless without
1114
+ // them (aria-label alone does not satisfy that check).
1115
+ id: "dstv-anchor-input",
1116
+ name: "dstv-anchor",
1117
+ type: "text",
1118
+ autoComplete: "off",
1119
+ value: anchorInput,
1120
+ // A placeholder is not an accessible name: screen readers may skip
1121
+ // it, and it disappears the moment the field has content.
1122
+ "aria-label": t("anchor.jumpLabel"),
1123
+ placeholder: t("anchor.jumpPlaceholder"),
1124
+ title: t("anchor.jumpTip"),
1125
+ onChange: (ev) => setAnchorInput(ev.target != null ? ev.target.value : ""),
1126
+ onKeyDown: (ev) => {
1127
+ ev.stopPropagation();
1128
+ if (ev.key === "Enter") {
1129
+ ev.preventDefault();
1130
+ const wanted = anchorInput.trim();
1131
+ // Mirror a successful typed jump into the URL. Only the
1132
+ // URL-driven path used to do this, so pressing Enter left
1133
+ // the old hash in place and the next arriving station
1134
+ // re-applied it, snatching the selection back.
1135
+ void anchorApplyGuarded(wanted).then((ok) => {
1136
+ if (!ok || typeof location === "undefined") return;
1137
+ const next = nextHashFor(location.hash, wanted);
1138
+ if (next.changed !== true) return;
1139
+ try { history.replaceState(null, "", next.hash); setHash(next.hash); } catch { /* hash is a convenience */ }
1140
+ });
1141
+ }
1142
+ else if (ev.key === "Escape") { setAnchorInput(""); setAnchorNote(null); ev.preventDefault(); }
1143
+ }
1144
+ }, "aIn"),
1145
+ anchorInput.trim() !== "" ? jsx("button", { type: "button", className: "dstv_sbtn", title: t("anchor.clear"), "aria-label": t("anchor.clear"), onClick: () => { setAnchorInput(""); setAnchorNote(null); }, children: jsx("span", { "aria-hidden": "true", children: "✕" }, "aClrIc") }, "aClr") : null
1146
+ ]
1147
+ }, "hAnchor"),
1148
+ jsxs("span", {
1149
+ className: "dstv_search",
1150
+ "data-active": searching ? "true" : undefined,
1151
+ children: [
1152
+ jsx("span", { className: "dstv_sbtn", style: { cursor: "default" }, children: "🔍" }, "sIco"),
1153
+ jsx("input", {
1154
+ ref: searchRef,
1155
+ className: "dstv_searchInput",
1156
+ id: "dstv-search-input",
1157
+ name: "dstv-search",
1158
+ type: "search",
1159
+ autoComplete: "off",
1160
+ "aria-label": t("search.label"),
1161
+ value: query,
1162
+ placeholder: t("action.search"),
1163
+ onChange: (ev) => setQueryRaw(ev.target != null ? ev.target.value : ""),
1164
+ onKeyDown: onSearchKey
1165
+ }, "sIn"),
1166
+ // Announced: this text changes on every keystroke and after every
1167
+ // next/prev jump, and it is the ONLY feedback that a search found
1168
+ // nothing or moved to the third of five matches. Without a live
1169
+ // region a screen reader user typed into the box and heard nothing.
1170
+ searching ? jsx("span", {
1171
+ className: `dstv_searchCount${matches.length === 0 ? " none" : ""}`,
1172
+ role: "status",
1173
+ "aria-live": "polite",
1174
+ "aria-atomic": "true",
1175
+ children: matches.length === 0 ? t("search.none")
1176
+ // `-` while nothing is selected: "1/3" claimed a position the
1177
+ // timeline did not actually hold.
1178
+ : matchPtr < 0 ? `–/${matches.length} ${t("search.matches")}`
1179
+ : `${matchPtr + 1}/${matches.length} ${t("search.matches")}`
1180
+ }, "sCnt") : null,
1181
+ // Without a loader this must be a NOTICE, not a disabled button:
1182
+ // the tooltip says "click here to load earlier history", which a
1183
+ // disabled control cannot honour. The warning itself still matters
1184
+ // (the search really is limited to the loaded range), so keep the
1185
+ // text and drop only the affordance.
1186
+ searching && scopeNote !== null ? (canPage ? jsx("button", {
1187
+ type: "button",
1188
+ className: "dstv_scope",
1189
+ title: t("search.scopeTip"),
1190
+ disabled: olderBusy === true || loadingOlder,
1191
+ onClick: doLoadOlder,
1192
+ children: `⬆ ${scopeNote}`
1193
+ }, "sScope") : jsx("span", {
1194
+ // `data-static` drops the pointer cursor and the hover highlight:
1195
+ // `.dstv_scope` is styled as a button, so a bare span would still
1196
+ // LOOK clickable — the same lie one layer down.
1197
+ className: "dstv_scope",
1198
+ "data-static": "true",
1199
+ title: t("search.scopeTipStatic"),
1200
+ children: `⬆ ${scopeNote}`
1201
+ }, "sScope")) : null,
1202
+ // `title` is NOT the accessible name when the element has content: the
1203
+ // name is computed from the descendants first, so these two announced
1204
+ // "↑" / "↓" and the tooltip became a description. Every other glyph
1205
+ // control here (the clear button, the follow toggle) already carries
1206
+ // `aria-label`; these two were the exception.
1207
+ searching && matches.length > 0 ? jsx("button", { type: "button", className: "dstv_sbtn", title: t("action.searchPrev"), "aria-label": t("action.searchPrev"), onClick: () => gotoMatch(-1), children: jsx("span", { "aria-hidden": "true", children: "↑" }, "sPrevIc") }, "sPrev") : null,
1208
+ searching && matches.length > 0 ? jsx("button", { type: "button", className: "dstv_sbtn", title: t("action.searchNext"), "aria-label": t("action.searchNext"), onClick: () => gotoMatch(1), children: jsx("span", { "aria-hidden": "true", children: "↓" }, "sNextIc") }, "sNext") : null,
1209
+ searching ? jsx("button", { type: "button", className: "dstv_sbtn", title: t("action.searchClear"), "aria-label": t("action.searchClear"), onClick: clearSearch, children: jsx("span", { "aria-hidden": "true", children: "✕" }, "sClrIc") }, "sClr") : null
1210
+ ]
1211
+ }, "hSearch")
1212
+ ]
1213
+ }, "rootHead");
1214
+
1215
+ if (N === 0) {
1216
+ if (sessionLoading === true) {
1217
+ // Skeleton, not prose: the count is unknown yet, so any number here would
1218
+ // be invented. Three pulsing cards communicate "being read" and keep the
1219
+ // layout from jumping when the real cards arrive.
1220
+ return jsxs("div", {
1221
+ className: "dstv_root",
1222
+ // The host renders no <main>, so axe flagged every node in this panel
1223
+ // under "region: content not contained by landmarks" (27 nodes). Declaring
1224
+ // the panel a labelled landmark cleared our elements (measured27 ->6; the
1225
+ //6 left belong to the host sidebar) and gives a jump target.
1226
+ role: "region",
1227
+ "aria-label": t("view.label"),
1228
+ tabIndex: 0,
1229
+ children: [header, jsxs("div", {
1230
+ className: "dstv_empty dstv_loading",
1231
+ role: "status",
1232
+ "aria-live": "polite",
1233
+ "aria-busy": "true",
1234
+ children: [
1235
+ jsx("span", { className: "dstv_spinner", "aria-hidden": "true" }, "spin"),
1236
+ jsx("div", { className: "dstv_loadingText", children: t("view.loading") }, "ldTxt"),
1237
+ jsx("div", {
1238
+ className: "dstv_skeletonRow",
1239
+ "aria-hidden": "true",
1240
+ children: [0, 1, 2].map((i) => jsx("span", { className: "dstv_skeleton", style: { animationDelay: `${i * 120}ms` } }, `sk${i}`))
1241
+ }, "skRow")
1242
+ ]
1243
+ }, "rootLoading")]
1244
+ });
1245
+ }
1246
+ // A contract violation must NOT look like "you have no data yet": the two
1247
+ // states have completely different fixes for the user.
1248
+ // Two independent triggers, because a kind rename keeps the field names valid:
1249
+ // (a) the snapshot itself is malformed / missing eventNodes
1250
+ // (b) the snapshot is well-formed but nothing in it is recognizable
1251
+ const structureBroken = tree.contract != null && tree.contract.ok !== true;
1252
+ const everythingUnknown = isEverythingUnknown(tree.nodes, tree.nodeStats);
1253
+ const incompatible = structureBroken || everythingUnknown;
1254
+ return jsxs("div", {
1255
+ className: "dstv_root",
1256
+ // The host renders no <main>, so axe flagged every node in this panel
1257
+ // under "region: content not contained by landmarks" (27 nodes). Declaring
1258
+ // the panel a labelled landmark cleared our elements (measured27 ->6; the
1259
+ //6 left belong to the host sidebar) and gives a jump target.
1260
+ role: "region",
1261
+ "aria-label": t("view.label"),
1262
+ tabIndex: 0,
1263
+ children: [header, jsxs("div", {
1264
+ className: "dstv_empty",
1265
+ children: [
1266
+ jsx("span", { className: incompatible ? "dstv_emptyGlyph warn" : "dstv_emptyGlyph", children: incompatible ? "⚠" : "◉" }, "emptyGlyph"),
1267
+ incompatible
1268
+ ? jsxs("div", { className: "dstv_incompat", children: [
1269
+ jsx("strong", { children: t("view.incompatible") }, "incT"),
1270
+ jsx("div", { className: "dstv_incompatHint", children: t("view.incompatibleHint") }, "incH"),
1271
+ jsx("code", { className: "dstv_incompatCodes", children: [
1272
+ ...(tree.contract.problems ?? []),
1273
+ ...everythingUnknown ? [`unrecognized-kinds: ${(tree.nodeStats.kinds ?? []).join("|")}`] : []
1274
+ ].join(", ") }, "incP")
1275
+ ] }, "incompat")
1276
+ : t("view.empty"),
1277
+ jsx("span", {
1278
+ className: "dstv_emptyLegend",
1279
+ children: legendItems.map((item) => jsxs("span", { children: [jsx("i", { style: { background: item.color } }, "eDot"), item.label] }, item.label))
1280
+ }, "emptyLegend")
1281
+ ]
1282
+ }, "rootEmpty")]
1283
+ });
1284
+ }
1285
+
1286
+ const renderStationCard = (s, cardKey) => {
1287
+ if (s.kind === "user") {
1288
+ return jsxs("div", {
1289
+ className: "dstv_hcard userCard",
1290
+ children: [
1291
+ jsx("span", { className: "dstv_name", children: s.who }, "uName"),
1292
+ s.time != null ? jsx("span", { className: "dstv_spanRow", children: jsx("span", { className: "dstv_spanEdge", children: fmtClock(s.time) }, "uClk") }, "uSpan") : null,
1293
+ jsx("div", { className: "dstv_text dstv_clamp3", title: s.text, children: s.text || "…" }, "uText")
1294
+ ]
1295
+ }, cardKey);
1296
+ }
1297
+ if (s.kind === "step") {
1298
+ return jsxs("div", {
1299
+ className: `dstv_hcard ${s.hasError ? "stepCardErr" : "stepCardOk"}`,
1300
+ children: [
1301
+ jsxs("span", {
1302
+ className: "dstv_name",
1303
+ children: [
1304
+ s.live === true ? jsx("i", { className: "dstv_dot", "data-live": true }, "stIcon") : s.hasError ? jsx("span", { className: "dstv_bad", "aria-hidden": "true", children: "✗" }, "stIcon") : jsx("span", { className: "dstv_ok", "aria-hidden": "true", children: "✓" }, "stIcon"),
1305
+ jsx("span", { className: "dstv_nameText", children: s.label }, "stLbl"),
1306
+ jsx("span", { className: "dstv_chips", children: s.meta.map((m, i) => jsx("span", { className: "dstv_chip", title: m, children: m }, `sm${i}`)) }, "stChips")
1307
+ ]
1308
+ }, "stName"),
1309
+ // G4-T1: exact span. Per spec, a missing edge shows only the edge
1310
+ // that exists — never a fabricated 00:00:00, and never a bogus
1311
+ // end time for a step that is still running.
1312
+ s.startMs != null || s.endMs != null || s.live === true
1313
+ ? jsx("div", {
1314
+ className: "dstv_spanRow",
1315
+ title: `${t("detail.start")} → ${t("detail.end")}`,
1316
+ children: jsxs(fragment, { children: [
1317
+ s.startMs != null ? jsx("span", { className: "dstv_spanEdge", children: fmtClock(s.startMs) }, "sp0") : null,
1318
+ s.startMs != null ? jsx("span", { className: "dstv_spanArrow", "aria-hidden": "true", children: "→" }, "spA") : null,
1319
+ s.endMs != null
1320
+ ? jsx("span", { className: "dstv_spanEdge", children: fmtClock(s.endMs) }, "sp1")
1321
+ : s.live === true ? jsx("span", { className: "dstv_spanLive", children: t("chip.running") }, "spLive") : null
1322
+ ] })
1323
+ }, "stSpan")
1324
+ : null,
1325
+ s.cells.map((cell) => {
1326
+ if (cell.kind === "assistant") {
1327
+ return jsxs("div", {
1328
+ className: "dstv_cellRow",
1329
+ children: [
1330
+ jsx("span", { className: "dstv_cellName", children: t("node.assistant") }, "aName"),
1331
+ cell.thinking !== "" ? jsx("div", { className: "dstv_text dstv_clamp2 sec", title: cell.thinking, children: `💭 ${markdownToPlain(cell.thinking)}` }, "aThink") : null,
1332
+ cell.text !== "" ? jsx("div", { className: "dstv_text dstv_clamp2", title: cell.text, children: markdownToPlain(cell.text) }, "aText") : null
1333
+ ]
1334
+ }, `a${cell.id}`);
1335
+ }
1336
+ if (cell.kind === "tool") {
1337
+ return jsxs("div", {
1338
+ className: "dstv_cellRow",
1339
+ children: [
1340
+ jsxs("span", {
1341
+ className: "dstv_cellName",
1342
+ title: cell.args !== "" ? `${cell.name} ${String(cell.args).slice(0, TITLE_PREVIEW_CHARS)}` : undefined,
1343
+ children: [
1344
+ cell.running === true ? jsx("i", { className: "dstv_dot", "data-live": true }, "tIcon") : cell.isError ? jsx("span", { className: "dstv_bad", "aria-hidden": "true", children: "✗" }, "tIcon") : jsx("span", { className: "dstv_ok", "aria-hidden": "true", children: "✓" }, "tIcon"),
1345
+ `${toolGlyph(cell.name)} ${cell.name}`,
1346
+ cell.isError ? jsx("span", { className: "dstv_chip err", children: t("chip.error") }, "tErr") : null,
1347
+ cell.running ? jsx("span", { className: "dstv_chip run", children: t("chip.running") }, "tRun") : null
1348
+ ]
1349
+ }, "tName"),
1350
+ cell.args !== "" ? jsx("div", { className: "dstv_argsPrev", title: String(cell.args).slice(0, TITLE_PREVIEW_CHARS), children: `${cell.args.replace(/\s+/g, " ").slice(0, 64)}…` }, "tArgs") : null,
1351
+ (cell.durationMs != null || cell.running === true) ? jsx("div", { className: `dstv_durBar${cell.running === true ? " run" : ""}`, children: jsx("i", { style: { width: cell.running === true ? "100%" : `${Math.max(8, Math.round((cell.durationMs / Math.max(1, stats.maxToolMs || stats.toolMs)) * 100))}%` } }) }, "tDur") : null,
1352
+ cell.isError && cell.errorName != null ? jsx("div", { className: "dstv_text sec dstv_clamp2", children: `✗ ${cell.errorName}` }, "tErrName") : null
1353
+ ]
1354
+ }, `t${cell.id}`);
1355
+ }
1356
+ return jsx("div", { className: "dstv_cellRow", children: `${t("node.subtool")} · ${cell.name}` }, `s${cell.id}`);
1357
+ })
1358
+ ]
1359
+ }, cardKey);
1360
+ }
1361
+ // Special kind cards
1362
+ if (s.kind === "orphan-tool") {
1363
+ const body = s.displayText !== "" ? s.displayText : t("orphan.noText");
1364
+ return jsxs("div", {
1365
+ className: `dstv_hcard ${s.isError ? "stepCardErr" : "stepCardOk"}`,
1366
+ children: [
1367
+ jsxs("span", {
1368
+ className: "dstv_name",
1369
+ children: [
1370
+ jsx("span", { className: s.isError ? "dstv_bad" : "dstv_ok", children: s.isError ? "✗" : "⤷" }, "oIcon"),
1371
+ `${t("node.orphanTool")} · ${s.name}`,
1372
+ jsx("span", { className: "dstv_chips", children: [jsx("span", { className: "dstv_chip info", children: t("orphan.badge") }, "oBadge")] }, "oChips")
1373
+ ]
1374
+ }, "oName"),
1375
+ s.args !== "" ? jsx("div", { className: "dstv_text dstv_clamp2 sec", title: s.args, children: s.args }, "oArgs") : null,
1376
+ jsx("div", { className: "dstv_text dstv_clamp4", title: body, children: body }, "oText")
1377
+ ]
1378
+ }, cardKey);
1379
+ }
1380
+ if (s.kind === "compaction") {
1381
+ return jsxs("div", {
1382
+ className: "dstv_hcard compactionCard",
1383
+ children: [
1384
+ jsx("span", { className: "dstv_name", children: `♺ ${t("node.compaction")}` }, "cName"),
1385
+ jsx("div", { className: "dstv_text dstv_clamp2", title: s.summary, children: s.summary || "…" }, "cText")
1386
+ ]
1387
+ }, cardKey);
1388
+ }
1389
+ if (s.kind === "error") {
1390
+ return jsxs("div", {
1391
+ className: "dstv_hcard errorCard",
1392
+ children: [
1393
+ jsx("span", { className: "dstv_name", children: `✗ ${t("node.error")}` }, "eName"),
1394
+ jsx("div", { className: "dstv_text dstv_clamp2", title: s.message, children: s.message || "…" }, "eText")
1395
+ ]
1396
+ }, cardKey);
1397
+ }
1398
+ if (s.kind === "retry") {
1399
+ return jsxs("div", {
1400
+ className: "dstv_hcard retryCard",
1401
+ children: [
1402
+ jsx("span", { className: "dstv_name", children: `↻ ${t("node.retry")}${Number.isFinite(s.retry) ? ` #${s.retry}` : ""}` }, "rName"),
1403
+ jsx("div", { className: "dstv_text sec dstv_clamp2", title: s.message, children: s.message || "…" }, "rText")
1404
+ ]
1405
+ }, cardKey);
1406
+ }
1407
+ if (s.kind === "maxTokens") {
1408
+ return jsxs("div", {
1409
+ className: "dstv_hcard maxTokensCard",
1410
+ children: [jsx("span", { className: "dstv_name", children: `⛔ ${t("node.maxTokens")}` }, "mName")]
1411
+ }, cardKey);
1412
+ }
1413
+ if (s.kind === "unknown") {
1414
+ return jsxs("div", {
1415
+ className: "dstv_hcard unknownCard",
1416
+ children: [
1417
+ jsxs("span", { className: "dstv_name", children: [
1418
+ jsx("span", { className: "dstv_bad", style: { background: "var(--dstv-muted)" }, children: "?" }, "ukIcon"),
1419
+ `${t("node.unknown")}${s.eventType !== "" ? ` · ${s.eventType}` : ""}`,
1420
+ jsx("span", { className: "dstv_chips", children: jsx("span", { className: "dstv_chip", children: `seq ${s.seq}` }, "ukSeq") }, "ukChips")
1421
+ ] }, "ukName"),
1422
+ s.payload !== "" ? jsx("div", { className: "dstv_text sec dstv_clamp3", title: s.payload, children: s.payload }, "ukText") : null
1423
+ ]
1424
+ }, cardKey);
1425
+ }
1426
+ if (s.kind === "command") {
1427
+ return jsxs("div", {
1428
+ className: "dstv_hcard commandCard",
1429
+ children: [
1430
+ jsx("span", { className: "dstv_name", children: `⚡ ${s.name}` }, "cmName"),
1431
+ s.args !== "" ? jsx("div", { className: "dstv_argsPrev", children: s.args }, "cmArgs") : null,
1432
+ s.outcomeKind === "error" ? jsx("div", { className: "dstv_text sec dstv_clamp2", children: `✗ ${s.outcomeText || t("meta.error")}` }, "cmOut") : null
1433
+ ]
1434
+ }, cardKey);
1435
+ }
1436
+ return jsx("div", { className: "dstv_hcard", children: s.label }, cardKey);
1437
+ };
1438
+
1439
+ // ── minimap: one tick per station, color-coded, click to seek ───────────
1440
+ // A tick needs a readable name: user stations carry no `label`, and the old
1441
+ // tooltip interpolated it directly, producing "undefined · 6:13:20 AM".
1442
+ const minimapTickLabel = (s) => {
1443
+ if (typeof s.label === "string" && s.label !== "") return s.label;
1444
+ if (s.kind === "user") return s.who ?? t("node.user");
1445
+ return t("node.unknown");
1446
+ };
1447
+ const minimapTicks = jsx("div", {
1448
+ className: "dstv_minimap",
1449
+ ref: minimapRef,
1450
+ children: stations.map((s, i) => {
1451
+ const reached = i < R;
1452
+ let k = s.kind;
1453
+ if (s.kind === "step") k = s.cells.some((c) => c.kind === "tool") ? "tool" : "step";
1454
+ if (s.kind === "maxTokens") k = "error";
1455
+ const done = reached && (s.kind !== "step" || !s.live);
1456
+ const matched = searching && matchSet.has(i);
1457
+ return jsx("button", {
1458
+ type: "button",
1459
+ className: "dstv_miniTick",
1460
+ "data-tick-idx": String(i),
1461
+ "data-k": k,
1462
+ "data-done": done ? "true" : undefined,
1463
+ "data-dim": reached ? (searching && !matched ? "true" : undefined) : "true",
1464
+ "data-active": revealed !== null && i === R - 1 ? "true" : undefined,
1465
+ "data-live": s.kind === "step" && s.live === true ? "true" : undefined,
1466
+ "data-match": matched ? "true" : undefined,
1467
+ // Roving tabindex, same as the station list. This strip is a SECOND
1468
+ // navigation affordance for the SAME stations: leaving every tick
1469
+ // tabbable made it N extra Tab stops (measured 200 at 200 stations,
1470
+ // so 3,600 on a long session) that a keyboard user had to cross to
1471
+ // reach the panel below — for a control that only seeks.
1472
+ // ...but exactly one tick must stay reachable, or the whole strip
1473
+ // disappears from the keyboard in the overview state. Same rule as
1474
+ // the station list: the active one, else the first.
1475
+ tabIndex: (revealed !== null && i === R - 1) || (revealed === null && i === 0) ? 0 : -1,
1476
+ // `s.label` is undefined for user stations, so the tooltip read
1477
+ // "undefined · 6:13:20 AM" and the button had no accessible name at
1478
+ // all. Fall back to the kind and always expose aria-label.
1479
+ title: `${minimapTickLabel(s)}${fmtClock(s.time) !== "" ? ` · ${fmtClock(s.time)}` : ""}`,
1480
+ "aria-label": `${t("detail.position")} ${String(i + 1)} / ${String(stations.length)} · ${minimapTickLabel(s)}${fmtClock(s.time) !== "" ? ` · ${fmtClock(s.time)}` : ""}`,
1481
+ onClick: (ev) => { ev.stopPropagation(); seek(i); }
1482
+ }, `mini${i}`);
1483
+ })
1484
+ }, "rootMini");
1485
+
1486
+ const body = jsxs("div", {
1487
+ children: [
1488
+ jsx("div", {
1489
+ className: "dstv_scroller",
1490
+ ref: scrollerRef,
1491
+ children: jsxs("div", {
1492
+ className: "dstv_hflow",
1493
+ role: "listbox",
1494
+ "aria-label": t("view.label"),
1495
+ "aria-orientation": "horizontal",
1496
+ children: [
1497
+ revealed !== null && playheadLeft !== null ? jsx("span", { className: "dstv_playhead", "aria-hidden": "true", style: { left: `${playheadLeft}px` }, children: jsx("i", {}) }, "ph") : null,
1498
+ stations.map((s, i) => {
1499
+ const reached = i < R;
1500
+ // G4-T3: idle gap vs the previous station's end (falls back to its
1501
+ // start / time). Rendered as an inline band so a long pause between
1502
+ // two steps is visible without opening either one.
1503
+ const prevStation = i > 0 ? stations[i - 1] : void 0;
1504
+ const prevEdge = prevStation === void 0 ? null
1505
+ : prevStation.endMs != null ? prevStation.endMs
1506
+ : prevStation.startMs != null ? prevStation.startMs
1507
+ : prevStation.time != null ? prevStation.time : null;
1508
+ const curEdge = s.startMs != null ? s.startMs : s.time != null ? s.time : null;
1509
+ // `time` comes from the log. A BigInt makes `curEdge - prevEdge` throw
1510
+ // ("Cannot mix BigInt and other types") and a Symbol throws too, so one
1511
+ // damaged timestamp took down the whole timeline render. `Number.isFinite`
1512
+ // is false for both without throwing.
1513
+ const gapMs = Number.isFinite(prevEdge) && Number.isFinite(curEdge) ? curEdge - prevEdge : null;
1514
+ const showGap = gapMs !== null && gapMs >= GAP_MIN_MS;
1515
+ // T2: in clock mode the idle band is widened in proportion to real
1516
+ // elapsed time (log-scaled and capped), so a long pause looks long.
1517
+ // Station cards keep their fixed width — only the idle spacing scales.
1518
+ const gapWidth = showGap ? clockGapWidth(gapMs, clockAxis) : null;
1519
+ // A listbox may own only `option` (or `group`) children. The idle band is
1520
+ // decoration — the station's own aria-label already carries the timing —
1521
+ // so leaving it exposed put a non-option, non-tabbable span inside the
1522
+ // list: screen readers reported extra items in the count and read
1523
+ // "⏸ idle 5.0 min" as if it were a station. The playhead next to it was
1524
+ // already hidden; this one was missed.
1525
+ const gapPrefix = showGap ? [jsx("span", {
1526
+ className: `dstv_gapBand${clockAxis ? " scaled" : ""}`,
1527
+ style: gapWidth !== null ? { width: gapWidth, minWidth: gapWidth } : undefined,
1528
+ title: `${t("gap.idle")} ${fmtMs(gapMs)}`,
1529
+ "aria-hidden": "true",
1530
+ children: `⏸ ${fmtMs(gapMs)}`
1531
+ }, `gap${s.id}`)] : [];
1532
+ let dotCls = "dstv_hDot";
1533
+ if (s.kind === "user") dotCls += " user";
1534
+ else if (s.kind === "compaction") dotCls += " compaction";
1535
+ else if (s.kind === "error" || s.kind === "maxTokens") dotCls += " error";
1536
+ else if (s.kind === "retry") dotCls += " retry";
1537
+ else if (s.kind === "command") dotCls += " command";
1538
+ else if (s.kind === "orphan-tool") dotCls += " orphan";
1539
+ else if (s.kind === "unknown") dotCls += " unknown";
1540
+ else if (s.kind === "step" && s.cells.some((c) => c.kind === "tool")) dotCls += " tool";
1541
+ if (s.kind === "step" && s.live === true) dotCls += " live";
1542
+ const matched = searching && matchSet.has(i);
1543
+ const clock = fmtClock(s.time);
1544
+ const isActive = revealed !== null && i === R - 1;
1545
+ return jsxs("div", {
1546
+ className: "dstv_station",
1547
+ "data-station-idx": String(i),
1548
+ "data-dim": reached ? undefined : "true",
1549
+ "data-seek-dim": searching && !matched && reached ? "true" : undefined,
1550
+ "data-match": matched ? "true" : undefined,
1551
+ "data-active": isActive ? "true" : undefined,
1552
+ role: "option",
1553
+ // Overview (revealed === null) shows everything, so no station
1554
+ // is "selected"; announcing all-false would tell a screen-reader
1555
+ // user the list has a selection when it does not.
1556
+ // ARIA 1.2 requires every role="option" to expose aria-selected.
1557
+ // Omitting it in the overview state made screen readers guess
1558
+ // (NVDA says "not selected", VoiceOver sometimes skips it).
1559
+ "aria-selected": revealed === null ? "false" : (isActive ? "true" : "false"),
1560
+ "aria-label": stationAriaLabel(s, i + 1, N, t),
1561
+ tabIndex: isActive || (revealed === null && i === 0) ? 0 : -1,
1562
+ onKeyDown: (ev) => stationOnKeyDown(ev, i),
1563
+ onClick: () => seek(i),
1564
+ children: [
1565
+ ...gapPrefix,
1566
+ jsxs("div", {
1567
+ className: "dstv_axisZone",
1568
+ children: [
1569
+ s.tag !== null && s.tag !== void 0 ? jsx("span", { className: "dstv_tag", title: s.tag, children: s.tag }, "axTag") : null,
1570
+ jsx("span", { className: `dstv_axSeg${reached ? " on" : ""}` }, "axSeg"),
1571
+ jsx("span", { className: dotCls, "data-active": revealed !== null && i === R - 1 ? "true" : undefined }, "axDot"),
1572
+ jsxs("span", {
1573
+ className: "dstv_axLabel",
1574
+ children: [
1575
+ // Show the PER-TURN step number, not the window-wide one:
1576
+ // paging older history shifts `stepNo` for every newer station,
1577
+ // so this label used to renumber as you scrolled back
1578
+ // (turn 5's first step read "1" then "5"). `turnStep` is stable.
1579
+ s.kind === "step" ? String(s.turnStep ?? s.stepNo) : String(i + 1),
1580
+ clock !== "" ? jsx("span", { className: "clock", children: ` ${clock}` }, "axClk") : null
1581
+ ]
1582
+ }, "axLbl")
1583
+ ]
1584
+ }, "stAxis"),
1585
+ jsx(RenderBoundary, {
1586
+ label: t("error.render"),
1587
+ retryLabel: t("error.retry"),
1588
+ hint: t("error.renderHint"),
1589
+ render: () => renderStationCard(s, `card${s.id}`)
1590
+ }, `card${s.id}`)
1591
+ ]
1592
+ }, s.id);
1593
+ })
1594
+ ]
1595
+ })
1596
+ }, "bodyScroller"),
1597
+ jsx("div", { className: "dstv_hint", children: t("hint.text") }, "bodyHint")
1598
+ ]
1599
+ }, "rootBody");
1600
+
1601
+ // ── Detail panel ────────────────────────────────────────────────────────
1602
+ // Status must come from the station's own evidence, for every kind:
1603
+ // - a `command` whose outcome has not arrived yet is still RUNNING, and one
1604
+ // with outcome.kind === "error" failed (rc.2 marks both explicitly);
1605
+ // - an `orphan-tool` carries isError itself.
1606
+ // Reading only `kind === "error"` here labelled a failed command and a failed
1607
+ // orphan tool as "Done".
1608
+ const activeLive = (activeStation.kind === "step" && activeStation.live === true)
1609
+ || (activeStation.kind === "command" && activeStation.outcomeKind == null)
1610
+ || (activeStation.kind === "orphan-tool" && activeStation.live === true);
1611
+ const activeError = activeStation.kind === "step" ? activeStation.hasError
1612
+ : activeStation.kind === "error" ? true
1613
+ : activeStation.kind === "command" ? activeStation.outcomeKind === "error"
1614
+ : activeStation.kind === "orphan-tool" ? activeStation.isError === true || activeStation.hasError === true
1615
+ : false;
1616
+ const canRequest = (activeStation.kind === "step" && activeStation.request !== null) || (activeStation.kind === "compaction" && activeStation.crequest != null);
1617
+ const showTab = tab === "request" && canRequest ? "request" : "detail";
1618
+
1619
+ const renderDetailBody = (s) => {
1620
+ if (s.kind === "unknown") {
1621
+ // Say exactly what the log said. The reader's question about an
1622
+ // unsupported event is "which one, and what did it carry".
1623
+ return jsxs("div", { className: "dstv_dBody", children: [
1624
+ jsx("span", { className: "dstv_dLabel", children: t("node.unknown") }, "uLbl"),
1625
+ jsxs("div", { className: "dstv_dSection", children: [
1626
+ jsx("span", { className: "dstv_chip warn", children: t("node.unknown") }, "uBadge"),
1627
+ s.eventType !== "" ? jsx("span", { className: "dstv_chip", children: s.eventType }, "uType") : null,
1628
+ s.seq != null ? jsx("span", { className: "dstv_chip", children: `seq ${s.seq}` }, "uSeq") : null
1629
+ ] }, "uMeta"),
1630
+ s.eventType !== "" ? jsxs("div", { className: "dstv_dSection", children: [
1631
+ jsx("span", { className: "dstv_dLabel", children: t("detail.eventType") }, "uTLbl"),
1632
+ jsx("pre", { className: "dstv_dText", children: s.eventType }, "uTypeText")
1633
+ ] }, "uTypeSec") : null,
1634
+ jsxs("div", { className: "dstv_dSection", children: [
1635
+ jsx("span", { className: "dstv_dLabel", children: t("detail.rawPayload") }, "uPLbl"),
1636
+ jsx("pre", { className: "dstv_dText", children: s.payload !== "" ? s.payload : "—" }, "uPayload")
1637
+ ] }, "uPayloadSec")
1638
+ ] });
1639
+ }
1640
+ if (s.kind === "orphan-tool") {
1641
+ const body = s.displayText !== "" ? s.displayText : t("orphan.noText");
1642
+ return jsxs("div", { className: "dstv_dBody", children: [
1643
+ jsx("span", { className: "dstv_dLabel", children: `${t("node.orphanTool")} · ${s.name}` }, "oLbl"),
1644
+ jsx("div", { className: "dstv_dSection", children: [
1645
+ jsx("span", { className: "dstv_chip info", children: t("orphan.badge") }, "oBadge"),
1646
+ jsx("span", { className: "dstv_chip", children: `callId ${s.callId}` }, "oCid")
1647
+ ] }, "oMeta"),
1648
+ s.args !== "" ? jsxs("div", { className: "dstv_dSection", children: [
1649
+ jsx("span", { className: "dstv_dLabel", children: t("detail.args") }, "oALbl"),
1650
+ jsx("pre", { className: "dstv_dText", children: s.args }, "oArgs")
1651
+ ] }) : null,
1652
+ jsxs("div", { className: "dstv_dSection", children: [
1653
+ jsx("span", { className: "dstv_dLabel", children: t("detail.result") }, "oRLbl"),
1654
+ jsx("pre", { className: "dstv_dText", children: body }, "oRes")
1655
+ ] })
1656
+ ] });
1657
+ }
1658
+ if (s.kind === "user") {
1659
+ // Same caption-over-card shape as the assistant sections, and the text is
1660
+ // Markdown too: users paste code blocks and lists just as often.
1661
+ return jsxs("div", { className: "dstv_dBody", children: jsxs("div", { className: "dstv_dSection dstv_dSectionBody", children: [
1662
+ jsx("span", { className: "dstv_dLabel", children: s.who }, "dLbl"),
1663
+ jsx("div", { className: "dstv_dText dstv_dMarkdown", children: s.text !== "" ? jsx(MarkdownText, { text: s.text }, "uMd") : "…" }, "dTxt")
1664
+ ] }) });
1665
+ }
1666
+ if (s.kind === "step") {
1667
+ const cellsBody = jsxs("div", { className: "dstv_dBody", children: s.cells.map((cell) => {
1668
+ if (cell.kind === "assistant") {
1669
+ // The label is a caption ABOVE a bordered body, not a prefix of it:
1670
+ // an inline label glued model prose to the header and the reply read
1671
+ // as one run-on block.
1672
+ return jsxs("div", { className: "dstv_dSection dstv_dSectionBody", children: [
1673
+ jsx("span", { className: "dstv_dLabel", children: t("node.assistant") }, "aLbl"),
1674
+ cell.thinking !== "" ? jsxs("details", { className: "dstv_det", open: false, children: [
1675
+ jsx("summary", { children: [`💭 ${t("chip.thinking")}`, jsx("span", { className: "sub", children: String(cell.thinking.length) }, "aThLen")] }, "aThSum"),
1676
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_dText sec", children: jsx(MarkdownText, { text: cell.thinking }, "aThMd") }, "aThText") }, "aThInner")
1677
+ ] }, `dth${cell.id}`) : null,
1678
+ cell.text !== "" ? jsx("div", { className: "dstv_dText dstv_dMarkdown", children: jsx(MarkdownText, { text: cell.text }, "aMd") }, "aText") : null
1679
+ ] }, `da${cell.id}`);
1680
+ }
1681
+ if (cell.kind === "tool") {
1682
+ const pretty = prettyArgs(cell.args);
1683
+ const hasResult = cell.resultText !== "" || cell.isError;
1684
+ return jsxs("div", { className: "dstv_dTool", children: [
1685
+ jsxs("span", { className: "dstv_name", title: cell.args !== "" ? `${cell.name} ${String(cell.args).slice(0, TITLE_PREVIEW_CHARS)}` : undefined, children: [
1686
+ cell.running === true ? jsx("i", { className: "dstv_dot", "data-live": true }, "tIcon") : cell.isError ? jsx("span", { className: "dstv_bad", "aria-hidden": "true", children: "✗" }, "tIcon") : jsx("span", { className: "dstv_ok", "aria-hidden": "true", children: "✓" }, "tIcon"),
1687
+ `${toolGlyph(cell.name)} ${cell.name}`,
1688
+ jsx("span", { className: "dstv_chips", children: [
1689
+ cell.running ? jsx("span", { className: "dstv_chip run", children: t("chip.running") }, "cRun") : null,
1690
+ cell.isError ? jsx("span", { className: "dstv_chip err", children: t("chip.error") }, "cErr") : null,
1691
+ cell.durationMs != null ? jsx("span", { className: "dstv_chip", children: fmtMs(cell.durationMs) }, "cDur") : null
1692
+ ] }, "tChips")
1693
+ ] }, "tName"),
1694
+ jsxs("details", { className: "dstv_det", open: false, children: [
1695
+ jsx("summary", { children: [t("detail.args"), jsx("span", { className: "sub", children: `${cell.args.length}${t("detail.chars")}` }, "aLen")] }, "tArgSum"),
1696
+ jsx("div", { className: "inner", children: [
1697
+ jsxs("div", { style: { display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }, children: [
1698
+ jsx("span", { className: "dstv_dLabel", style: { margin: 0 }, children: t("node.tool") }, "tArgLbl"),
1699
+ jsx(CopyBtn, { text: cell.args, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "tArgCopy")
1700
+ ] }, "tArgHead"),
1701
+ jsx("div", { className: "dstv_code", children: pretty !== "" ? pretty : t("detail.noArgs") }, "tArgCode")
1702
+ ] }, "tArgInner")
1703
+ ] }, `da${cell.id}`),
1704
+ hasResult ? jsxs("details", { className: "dstv_det", open: true, children: [
1705
+ jsx("summary", { children: [cell.isError ? `✗ ${t("detail.result")}` : `✓ ${t("detail.result")}`, jsx("span", { className: "sub", children: String(cell.resultText.length) }, "rLen")] }, "tResSum"),
1706
+ jsx("div", { className: "inner", children: [
1707
+ jsxs("div", { style: { display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }, children: [
1708
+ jsx("span", { className: `dstv_dLabel${cell.isError ? " err" : ""}`, style: { margin: 0 }, children: cell.isError && cell.errorName != null ? `✗ ${cell.errorName}` : t("detail.result") }, "tResLbl"),
1709
+ jsx(CopyBtn, { text: cell.resultText, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "tResCopy")
1710
+ ] }, "tResHead"),
1711
+ jsx("div", { className: "dstv_code", children: cell.resultText !== "" ? cell.resultText : t("detail.noResult") }, "tResCode")
1712
+ ] }, "tResInner")
1713
+ ] }, `dr${cell.id}`) : null,
1714
+ cell.resultText === "" && !cell.isError && !cell.running ? jsx("span", { className: "dstv_dLabel sec", children: t("detail.noResult") }, "tNoRes") : null,
1715
+ cell.subCalls.length > 0 ? jsxs("details", { className: "dstv_det", open: cell.subCalls.some((sub) => sub.isError), children: [
1716
+ jsx("summary", { children: [`${t("detail.subCalls")} (${cell.subCalls.length})`, cell.subCalls.some((sub) => sub.isError) ? jsx("span", { className: "dstv_chip err", children: t("chip.error") }, "tSubErr") : null] }, "tSubSum"),
1717
+ jsx("div", {
1718
+ className: "inner",
1719
+ children: cell.subCalls.map((sub, i) => {
1720
+ const subPretty = prettyArgs(sub.argsRaw);
1721
+ return jsxs("div", {
1722
+ className: "dstv_subCard",
1723
+ children: [
1724
+ jsxs("span", {
1725
+ className: "dstv_subHead",
1726
+ children: [
1727
+ sub.running ? jsx("i", { className: "dstv_dot", "data-live": true }, "sIcon") : sub.isError ? jsx("span", { className: "dstv_bad", children: "✗" }, "sIcon") : jsx("span", { className: "dstv_ok", children: "✓" }, "sIcon"),
1728
+ jsx("span", { className: "tname", children: `↳ ${sub.name}` }, "sName"),
1729
+ jsx("span", { className: "dstv_chips", children: [
1730
+ sub.running ? jsx("span", { className: "dstv_chip run", children: t("chip.running") }, "sRun") : null,
1731
+ sub.isError ? jsx("span", { className: "dstv_chip err", children: sub.errorName != null ? String(sub.errorName) : t("chip.error") }, "sErr") : null,
1732
+ sub.durationMs != null ? jsx("span", { className: "dstv_chip", children: fmtMs(sub.durationMs) }, "sDur") : null
1733
+ ] }, "sChips")
1734
+ ]
1735
+ }, "sHead"),
1736
+ sub.argsRaw !== "" ? jsxs("details", { className: "dstv_det", open: false, children: [
1737
+ jsx("summary", { children: [t("detail.args"), jsx("span", { className: "sub", children: `${sub.argsRaw.length}${t("detail.chars")}` }, "sALen")] }, "sArgSum"),
1738
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", children: subPretty !== "" ? subPretty : t("detail.noArgs") }, "sArgCode") }, "sArgInner")
1739
+ ] }, "sArgs") : null,
1740
+ sub.resultText !== "" ? jsxs("details", { className: "dstv_det", open: sub.isError, children: [
1741
+ jsx("summary", { children: [sub.isError ? `✗ ${t("detail.result")}` : `✓ ${t("detail.result")}`, jsx("span", { className: "sub", children: String(sub.resultText.length) }, "sRLen")] }, "sResSum"),
1742
+ jsx("div", { className: "inner", children: jsxs("div", { children: [
1743
+ jsx(CopyBtn, { text: sub.resultText, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "sResCopy"),
1744
+ jsx("div", { className: "dstv_code", style: { marginTop: 4 }, children: sub.resultText }, "sResCode")
1745
+ ] }) }, "sResInner")
1746
+ ] }, "sRes") : null
1747
+ ]
1748
+ }, `ts${i}`);
1749
+ })
1750
+ }, "tSubInner")
1751
+ ] }, `ds${cell.id}`) : null
1752
+ ] }, `dt${cell.id}`);
1753
+ }
1754
+ return jsx("div", { className: "dstv_dTool", children: `${t("node.subtool")} · ${cell.name}` }, `ds${cell.id}`);
1755
+ }) }, "dCells");
1756
+ return cellsBody;
1757
+ }
1758
+ // special stations
1759
+ if (s.kind === "compaction") {
1760
+ return jsxs("div", { className: "dstv_dBody", children: [
1761
+ jsx("span", { className: "dstv_dLabel", children: s.label }, "cLbl"),
1762
+ jsx("div", { className: "dstv_dText", children: s.summary || "…" }, "cTxt"),
1763
+ s.count != null || s.tokens != null ? jsx("div", { className: "dstv_cfgChips", children: [
1764
+ Number.isSafeInteger(s.count) ? jsx("span", { className: "dstv_cfgChip", children: [`${numOr(s.count)} ${t("meta.steps")}`] }, "cCnt") : null,
1765
+ s.tokens != null ? jsx("span", { className: "dstv_cfgChip", children: [`${fmtTokens(s.tokens)} ${t("meta.tokens")}`] }, "cTok") : null
1766
+ ] }, "cChips") : null
1767
+ ] });
1768
+ }
1769
+ if (s.kind === "error") {
1770
+ return jsxs("div", { className: "dstv_dBody", children: [
1771
+ jsx("span", { className: "dstv_dLabel", children: s.label }, "eLbl"),
1772
+ jsx("div", { className: "dstv_dText", children: s.message || "…" }, "eTxt"),
1773
+ s.code != null ? jsx("div", { className: "dstv_cfgChips", children: jsx("span", { className: "dstv_cfgChip", children: [`code: ${s.code}`] }, "eCode") }, "eChips") : null
1774
+ ] });
1775
+ }
1776
+ if (s.kind === "retry") {
1777
+ return jsxs("div", { className: "dstv_dBody", children: [
1778
+ jsx("span", { className: "dstv_dLabel", children: s.label }, "rLbl"),
1779
+ jsx("div", { className: "dstv_dText", children: s.message || "…" }, "rTxt"),
1780
+ jsx("div", { className: "dstv_cfgChips", children: [
1781
+ Number.isFinite(s.retry) ? jsx("span", { className: "dstv_cfgChip", children: [`retry #${s.retry}${s.maxRetries != null ? `/${s.maxRetries}` : ""}`] }, "rRet") : null,
1782
+ s.provider ? jsx("span", { className: "dstv_cfgChip", children: [s.provider] }, "rProv") : null,
1783
+ s.code ? jsx("span", { className: "dstv_cfgChip", children: [`code: ${s.code}`] }, "rCode") : null,
1784
+ s.retryState ? jsx("span", { className: "dstv_cfgChip", children: [s.retryState] }, "rState") : null
1785
+ ] }, "rChips")
1786
+ ] });
1787
+ }
1788
+ if (s.kind === "maxTokens") {
1789
+ return jsxs("div", { className: "dstv_dBody", children: [
1790
+ jsx("span", { className: "dstv_dLabel", children: s.label }, "mLbl"),
1791
+ jsx("div", { className: "dstv_dText sec", children: t("node.maxTokens") }, "mTxt")
1792
+ ] });
1793
+ }
1794
+ if (s.kind === "command") {
1795
+ return jsxs("div", { className: "dstv_dBody", children: [
1796
+ jsx("span", { className: "dstv_dLabel", children: s.label }, "cmLbl"),
1797
+ jsx("div", { className: "dstv_dText", children: `/${s.name}` }, "cmTxt"),
1798
+ s.args !== "" ? jsx("div", { className: "dstv_code", children: s.args }, "cmArgs") : null,
1799
+ s.outcomeText !== "" ? jsx("div", { className: "dstv_dText sec", children: s.outcomeText }, "cmOut") : null
1800
+ ] });
1801
+ }
1802
+ return jsx("div", { className: "dstv_dBody", children: s.label });
1803
+ };
1804
+
1805
+ /** Raw-request tab for a compaction station: config, usage, and the full
1806
+ * compaction output (what the model produced as the replacement summary). */
1807
+ const renderCompactionRequestBody = (s) => {
1808
+ const cr = s.crequest;
1809
+ if (cr == null) return null;
1810
+ const cfg = cr.config ?? {};
1811
+ const usage = cr.usage;
1812
+ return jsxs("div", { className: "dstv_dBody", children: [
1813
+ jsxs("div", { className: "dstv_cfgChips", children: [
1814
+ cfg.provider ? jsx("span", { className: "dstv_cfgChip", children: ["provider ", jsx("b", { children: cfg.provider }, "v")] }, "cProv") : null,
1815
+ cfg.model ? jsx("span", { className: "dstv_cfgChip", children: ["model ", jsx("b", { children: cfg.model }, "v")] }, "cModel") : null,
1816
+ cr.status ? jsx("span", { className: `dstv_chip ${cr.status === "running" ? "run" : cr.status === "error" ? "err" : ""}`, children: cr.status }, "cStatus") : null,
1817
+ cr.durationMs != null ? jsx("span", { className: "dstv_cfgChip", children: [fmtMs(cr.durationMs)] }, "cDur") : null
1818
+ ] }, "crCfg"),
1819
+ usage !== null && usage.input + usage.output > 0 ? jsxs("div", { className: "dstv_dSection", children: [
1820
+ jsx("span", { className: "dstv_dLabel", children: `📊 ${t("detail.usage")}` }, "uLbl"),
1821
+ jsx("div", { className: "dstv_cfgChips", children: [
1822
+ usage.input > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["in ", jsx("b", { children: fmtInt(usage.input) }, "v")] }, "uIn") : null,
1823
+ usage.cacheRead > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["cache-read ", jsx("b", { children: fmtInt(usage.cacheRead) }, "v")] }, "uCR") : null,
1824
+ usage.output > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["out ", jsx("b", { children: fmtInt(usage.output) }, "v")] }, "uOut") : null
1825
+ ] }, "uChips")
1826
+ ] }, "crUsage") : null,
1827
+ cr.outputText !== "" ? jsxs("div", { className: "dstv_dSection", children: [
1828
+ jsxs("div", { className: "dstv_dSecHead", children: [
1829
+ jsx("span", { children: `📤 ${t("detail.compactionOutput")}` }, "oHead"),
1830
+ jsx("span", { className: "sub", children: `${fmtInt(cr.outputText.length)} ${t("detail.chars")}` }, "oLen"),
1831
+ jsx("span", { className: "grow" }, "oGrow"),
1832
+ jsx(CopyBtn, { text: cr.outputText, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "oCopy")
1833
+ ] }, "oSecHead"),
1834
+ jsx("div", { className: "dstv_code", style: { maxHeight: 260 }, children: cr.outputText }, "oCode")
1835
+ ] }, "crOut") : null
1836
+ ] }, "crBody");
1837
+ };
1838
+
1839
+ /** Raw-request tab: config, prompt diff, system prompt, tool catalog, reconstructed messages, usage. */
1840
+ const renderRequestBody = (s, messages) => {
1841
+ const req = s.request;
1842
+ if (req == null) return null;
1843
+ const cfg = req.config ?? {};
1844
+ const usage = req.usage;
1845
+ // The catalog comes from the host: an entry can be a hole (null) and the
1846
+ // fields can be drifted. Normalise ONCE here — every reader below
1847
+ // (`tools.map`, the JSON previews, the React keys) then sees a safe shape.
1848
+ const tools = safeToolList(req.prompt?.tools);
1849
+ const diff = req.promptDiff ?? null;
1850
+ const evidenceChips = evidenceOf(req, activeMessages, hasMore);
1851
+
1852
+ const payload = {
1853
+ provider: cfg.provider,
1854
+ model: cfg.model,
1855
+ purpose: cfg.purpose,
1856
+ temperature: cfg.temperature,
1857
+ reasoningEffort: cfg.reasoningEffort,
1858
+ maxTokens: cfg.maxTokens,
1859
+ system: req.prompt?.system ?? "",
1860
+ tools: tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })),
1861
+ messages: messages.map((m) => m.role === "note"
1862
+ ? { role: "user", content: [{ type: "text", text: m.text }] }
1863
+ : { role: m.role, content: m.content, ...(m.toolCallId != null ? { toolCallId: m.toolCallId } : {}), ...(m.isError != null ? { isError: m.isError } : {}) })
1864
+ };
1865
+ // `JSON.stringify` throws on a circular structure and on a BigInt, and what
1866
+ // arrives here is the host's own prompt/tool descriptor, not something we built.
1867
+ // A tool schema carrying a shared object reference (perfectly legal in a live
1868
+ // descriptor) therefore blanked the whole request tab instead of showing one
1869
+ // field as unrepresentable. `safeJsonPreview` already solves this everywhere
1870
+ // else; the request tab was the only place that called JSON directly.
1871
+ const payloadJson = safeJsonPreview(payload, Number.MAX_SAFE_INTEGER, 2);
1872
+ const sysToolsJson = safeJsonPreview(tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })), Number.MAX_SAFE_INTEGER, 2);
1873
+ const sysJson = safeJsonPreview({ system: req.prompt?.system ?? "", tools: tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })) }, Number.MAX_SAFE_INTEGER, 2);
1874
+
1875
+ return jsxs("div", { className: "dstv_dBody", children: [
1876
+ // config + lifecycle chips
1877
+ jsxs("div", { className: "dstv_cfgChips", children: [
1878
+ cfg.provider ? jsx("span", { className: "dstv_cfgChip", children: ["provider ", jsx("b", { children: cfg.provider }, "v")] }, "cProv") : null,
1879
+ cfg.model ? jsx("span", { className: "dstv_cfgChip", children: ["model ", jsx("b", { children: cfg.model }, "v")] }, "cModel") : null,
1880
+ cfg.temperature != null ? jsx("span", { className: "dstv_cfgChip", children: ["temp ", jsx("b", { children: String(cfg.temperature) }, "v")] }, "cTemp") : null,
1881
+ cfg.reasoningEffort ? jsx("span", { className: "dstv_cfgChip", children: ["effort ", jsx("b", { children: cfg.reasoningEffort }, "v")] }, "cEffort") : null,
1882
+ cfg.maxTokens ? jsx("span", { className: "dstv_cfgChip", children: ["max ", jsx("b", { children: fmtInt(cfg.maxTokens) }, "v")] }, "cMax") : null,
1883
+ cfg.thinking ? jsx("span", { className: "dstv_cfgChip", children: ["thinking ", jsx("b", { children: String(cfg.thinking) }, "v")] }, "cThink") : null,
1884
+ Array.isArray(cfg.stop) && cfg.stop.length > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["stop ×", jsx("b", { children: String(cfg.stop.length) }, "v")] }, "cStop") : null,
1885
+ req.status ? jsx("span", { className: `dstv_chip ${req.status === "running" ? "run" : req.status === "error" ? "err" : ""}`, children: req.status }, "cStatus") : null,
1886
+ req.durationMs != null ? jsx("span", { className: "dstv_cfgChip", children: [fmtMs(req.durationMs)] }, "cDur") : null,
1887
+ req.retry != null ? jsx("span", { className: "dstv_chip retry", children: [`↻ ${t("status.retry")} #${numOr(req.retry)}${Number.isSafeInteger(req.maxRetries) ? `/${numOr(req.maxRetries)}` : ""}`] }, "cRetry") : null
1888
+ ] }, "reqCfg"),
1889
+ req.error != null ? jsx("div", { className: "dstv_dTool", style: { borderColor: "color-mix(in srgb,var(--dstv-err) 50%,transparent)" }, children: [
1890
+ jsx("span", { className: "dstv_dLabel err", children: `✗ ${req.error}` }, "reqErr")
1891
+ ] }, "reqErrBox") : null,
1892
+ req.promptChangeKind != null && req.promptChangeKind !== "initial" && diff === null ? jsx("span", { className: "dstv_chip info", children: t("detail.promptChanged") }, "reqChanged") : null,
1893
+ diff !== null ? jsxs("div", { className: "dstv_diffBox", children: [
1894
+ jsxs("span", { className: "dstv_dLabel", style: { margin: 0 }, children: [
1895
+ "⚡ ",
1896
+ diff.isInitial || diff.kind === "initial" ? t("diff.initial") : diff.kind === "system" ? t("diff.system") : diff.kind === "tools" ? t("diff.tools") : t("diff.systemAndTools")
1897
+ ] }, "pdHead"),
1898
+ diff.isInitial || diff.kind === "initial" ? null : jsxs("div", { className: "dstv_cfgChips", children: [
1899
+ diff.systemDelta !== 0 || diff.prevSystemChars !== diff.curSystemChars ? jsx("span", { className: "dstv_diffChip delta", children: `${t("diff.systemDelta")} ${fmtInt(diff.prevSystemChars)} → ${fmtInt(diff.curSystemChars)} (${diff.systemDelta > 0 ? "+" : ""}${fmtInt(diff.systemDelta)})` }, "pdSys") : null,
1900
+ diff.toolsAdded.map((n) => jsx("span", { className: "dstv_diffChip add", title: t("diff.toolsAdded"), children: `+ ${n}` }, `pdA${n}`)),
1901
+ diff.toolsRemoved.map((n) => jsx("span", { className: "dstv_diffChip del", title: t("diff.toolsRemoved"), children: `- ${n}` }, `pdR${n}`)),
1902
+ (diff.toolsChanged ?? []).map((n) => jsx("span", { className: "dstv_diffChip mod", title: t("diff.toolsChanged"), children: `~ ${n}` }, `pdM${n}`))
1903
+ ] }, "pdChips"),
1904
+ // Q2-1: the actual changed lines, so a prompt author can see WHAT moved.
1905
+ diff.isInitial || diff.kind === "initial" ? null : (diff.textDiff != null ? jsxs("details", {
1906
+ className: "dstv_diffText",
1907
+ children: [
1908
+ jsx("summary", { children: `${t("diff.textDiff")} · ${t("diff.startLine").replace("{n}", String(diff.textDiff.startLine))}${diff.textDiff.narrows ? ` · ${t("diff.truncated").replace("{n}", String(PROMPT_DIFF_LINES))}` : ""}` }, "pdSum"),
1909
+ jsxs("div", { className: "dstv_diffBody", children: [
1910
+ diff.textDiff.removed.length > 0 ? jsxs("div", { className: "dstv_diffSide del", children: [
1911
+ jsx("div", { className: "dstv_diffLbl", children: `− ${t("diff.removed")}` }, "pdRLbl"),
1912
+ jsx("pre", { children: diff.textDiff.removed.join("\n") }, "pdPre")
1913
+ ] }, "pdRemoved") : null,
1914
+ diff.textDiff.added.length > 0 ? jsxs("div", { className: "dstv_diffSide add", children: [
1915
+ jsx("div", { className: "dstv_diffLbl", children: `+ ${t("diff.added")}` }, "pdALbl"),
1916
+ jsx("pre", { children: diff.textDiff.added.join("\n") }, "pdApre")
1917
+ ] }, "pdAdded") : null
1918
+ ] }, "pdBody")
1919
+ ]
1920
+ }, "pdText") : (diff.systemDelta !== 0 ? jsx("span", { className: "dstv_diffChip delta", children: t("diff.noText") }, "pdNoText") : null))
1921
+ ] }, "reqDiff") : null,
1922
+ // system prompt
1923
+ req.prompt !== null ? jsxs("div", { className: "dstv_dSection", children: [
1924
+ jsxs("div", { className: "dstv_dSecHead", children: [
1925
+ jsx("span", { children: `🧠 ${t("detail.systemPrompt")}` }, "spHead"),
1926
+ jsx("span", { className: "sub", children: `${fmtInt(req.prompt.systemChars)} ${t("detail.chars")}` }, "spLen"),
1927
+ jsx("span", { className: "grow" }, "spGrow"),
1928
+ jsx(CopyBtn, { text: sysJson, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "spCopy")
1929
+ ] }, "spSecHead"),
1930
+ jsxs("details", { className: "dstv_det", open: false, children: [
1931
+ jsx("summary", { children: [t("detail.systemPrompt")] }, "spSum"),
1932
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", style: { maxHeight: 220 }, children: req.prompt.system || "…" }, "spCode") }, "spInner")
1933
+ ] }, "spDet")
1934
+ ] }, "spSec") : null,
1935
+ // tool catalog
1936
+ tools.length > 0 ? jsxs("div", { className: "dstv_dSection", children: [
1937
+ jsxs("div", { className: "dstv_dSecHead", children: [
1938
+ jsx("span", { children: `🛠 ${t("detail.toolsCatalog")}` }, "tcHead"),
1939
+ jsx("span", { className: "sub", children: `${tools.length} ${t("detail.toolCount")}` }, "tcLen"),
1940
+ jsx("span", { className: "grow" }, "tcGrow"),
1941
+ // Must match `sysJson` above, which already uses the safe serializer:
1942
+ // the copy button would otherwise throw on the same descriptor that
1943
+ // renders fine, and the throw happens during render, not on click.
1944
+ jsx(CopyBtn, { text: sysToolsJson, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "tcCopy")
1945
+ ] }, "tcSecHead"),
1946
+ jsxs("details", { className: "dstv_det", open: false, children: [
1947
+ jsx("summary", { children: [`${t("detail.toolsCatalog")} (${tools.length})`] }, "tcSum"),
1948
+ jsx("div", { className: "inner", children: tools.map((tool) => jsxs("details", { className: "dstv_det", open: false, children: [
1949
+ jsx("summary", { children: [jsx("span", { className: "tname", children: tool.name !== "" ? tool.name : t("detail.toolUnnamed") }, "tn"), jsx("span", { className: "sub", children: firstLine(tool.description) }, "td")] }, `ts${tool.name}`),
1950
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", style: { maxHeight: 160 }, children: prettyJson(tool.parameters) }, "tcCode") }, `ti${tool.name}`)
1951
+ ] }, `tool${tool.name}`)) }, "tcInner")
1952
+ ] }, "tcDet")
1953
+ ] }, "tcSec") : null,
1954
+ // usage
1955
+ usage !== null && usage.input + usage.output > 0 ? jsxs("div", { className: "dstv_dSection", children: [
1956
+ jsx("span", { className: "dstv_dLabel", children: `📊 ${t("detail.usage")}` }, "uLbl"),
1957
+ jsx("div", { className: "dstv_cfgChips", children: [
1958
+ usage.input > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["in ", jsx("b", { children: fmtInt(usage.input) }, "v")] }, "uIn") : null,
1959
+ usage.raw > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["fresh ", jsx("b", { children: fmtInt(usage.raw) }, "v")] }, "uFresh") : null,
1960
+ usage.cacheRead > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["cache-read ", jsx("b", { children: fmtInt(usage.cacheRead) }, "v")] }, "uCR") : null,
1961
+ usage.cacheWrite > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["cache-write ", jsx("b", { children: fmtInt(usage.cacheWrite) }, "v")] }, "uCW") : null,
1962
+ usage.output > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["out ", jsx("b", { children: fmtInt(usage.output) }, "v")] }, "uOut") : null,
1963
+ usage.think > 0 ? jsx("span", { className: "dstv_cfgChip", children: ["think ", jsx("b", { children: fmtInt(usage.think) }, "v")] }, "uThink") : null
1964
+ ] }, "uChips")
1965
+ ] }, "uSec") : null,
1966
+ // messages
1967
+ messages.length > 0 ? jsxs("div", { className: "dstv_dSection", children: [
1968
+ jsxs("div", { className: "dstv_dSecHead", children: [
1969
+ jsx("span", { children: `💬 ${t("detail.messages")}` }, "mHead"),
1970
+ jsx("span", { className: "sub", children: `${messages.length} ${t("detail.msgCount")}` }, "mLen"),
1971
+ jsx("span", { className: "grow" }, "mGrow"),
1972
+ jsx(CopyBtn, { text: payloadJson, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "mCopy")
1973
+ ] }, "mSecHead"),
1974
+ jsxs("span", { className: "dstv_dLabel sec", children: [
1975
+ t("detail.requestApprox"),
1976
+ evidenceChips.length > 0 ? jsx("span", { className: "dstv_evRow", children: evidenceChips.map((e) => jsx("span", {
1977
+ key: e.id,
1978
+ className: `dstv_ev dstv_ev-${e.level}`,
1979
+ title: t(`evidence.${e.level}Tip`),
1980
+ children: t(`evidence.${e.level}`)
1981
+ }, e.id)) }, "evRow") : null
1982
+ ] }, "mNote"),
1983
+ jsx("div", { className: "dstv_dBody", style: { padding: 0 }, children: messages.map((m, i) => {
1984
+ const preview = m.text !== "" ? m.text : (m.role === "tool" ? `${m.toolCallId ?? ""}${m.isError ? " ✗" : ""}` : "…");
1985
+ // Key on the message's OWN identity, not its position. This list is
1986
+ // rebuilt whenever the station window grows backwards, and paging
1987
+ // PREPENDS messages: index 3 stops being the message it was, so React
1988
+ // reused the DOM node and the row that was expanded started showing a
1989
+ // different message's body. `seq` is the durable record number; the
1990
+ // hash fallback keeps abnormally shaped nodes unique anyway.
1991
+ const msgKey = `m${m.seq != null ? `s${String(m.seq)}` : `x${String(i)}`}-${m.role}`;
1992
+ return jsxs("details", { className: "dstv_det", open: i === messages.length - 1, children: [
1993
+ jsx("summary", { children: [jsx("span", { className: `dstv_msgRole ${m.role}`, children: m.role === "note" ? t("node.compaction") : m.role }, "mr"), jsx("span", { className: "dstv_msgPrev", children: firstLine(preview) }, "mp"), jsx("span", { className: "sub", children: String(m.text.length) }, "ml")] }, `${msgKey}s`),
1994
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", style: { maxHeight: 200 }, children: m.text !== "" ? m.text : safeJsonPreview(m.content, Number.MAX_SAFE_INTEGER, 2) }, "mc") }, `${msgKey}i`)
1995
+ ] }, msgKey);
1996
+ }) }, "mList")
1997
+ ] }, "mSec") : null
1998
+ ] }, "reqBody");
1999
+ };
2000
+
2001
+ let dStatus = null;
2002
+ if (activeLive) {
2003
+ dStatus = jsxs("span", { className: "dstv_chip run", children: [jsx("i", { className: "dstv_dot", "data-live": true }, "stDot"), t("chip.running")] }, "dStatus");
2004
+ } else if (activeError) {
2005
+ dStatus = jsxs("span", { className: "dstv_chip err", children: [jsx("span", { className: "dstv_bad", children: "✗" }, "stIc"), t("meta.error")] }, "dStatus");
2006
+ } else if (activeStation.kind === "step" && activeStation.interrupted === true) {
2007
+ dStatus = jsxs("span", { className: "dstv_chip retry", children: [jsx("span", { className: "dstv_bad", style: { background: "var(--dstv-warn)" }, children: "⏹" }, "stIc"), t("chip.interrupted")] }, "dStatus");
2008
+ } else {
2009
+ dStatus = jsxs("span", { className: "dstv_chip", children: [jsx("span", { className: "dstv_ok", children: "✓" }, "stIc"), t("status.done")] }, "dStatus");
2010
+ }
2011
+
2012
+ const badgeCls = activeStation.kind === "user" ? "user" : activeStation.kind === "error" ? "error" : (activeStation.kind === "compaction" || activeStation.kind === "retry" || activeStation.kind === "command" || activeStation.kind === "maxTokens" || activeStation.kind === "orphan-tool" || activeStation.kind === "unknown") ? "violet" : "";
2013
+ const badgeText = activeStation.label;
2014
+ const activeModel = activeStation.kind === "step" ? (activeStation.request?.config?.model ?? activeStation.modelHint ?? null) : (activeStation.kind === "compaction" ? activeStation.crequest?.config?.model ?? null : null);
2015
+ const activeClock = fmtClock(activeStation.time);
2016
+
2017
+ const detail = jsxs("div", {
2018
+ className: `dstv_detail${panelFull ? " full" : ""}`,
2019
+ children: [
2020
+ canRequest ? jsxs("div", { className: "dstv_tabs", children: [
2021
+ // These are tab-like in appearance but do not follow the tab pattern
2022
+ // (no tablist/tab/tabpanel wiring). Exposing the state as
2023
+ // `aria-pressed` tells a screen reader which view is active without
2024
+ // claiming a role the markup cannot honour.
2025
+ jsx("button", { type: "button", className: "dstv_tab", "data-on": showTab === "detail" ? "true" : undefined, "aria-pressed": showTab === "detail" ? "true" : "false", onClick: () => setTab("detail"), children: `🧭 ${t("tab.detail")}` }, "tabDetail"),
2026
+ // Only latch the request tab when there IS a request to show. `showTab`
2027
+ // already falls back to the detail view, so the button looked inert — but
2028
+ // the state stayed "request", and the moment the reader stepped to a
2029
+ // station that DOES have a request the panel jumped to it without anyone
2030
+ // pressing anything. `r` has this guard; the button did not.
2031
+ jsx("button", { type: "button", className: "dstv_tab", "data-on": showTab === "request" ? "true" : undefined, "aria-pressed": showTab === "request" ? "true" : "false", onClick: () => { if (canRequest) setTab("request"); }, children: `📨 ${t("tab.request")}` }, "tabRequest")
2032
+ ] }, "dTabs") : null,
2033
+ jsxs("div", {
2034
+ className: "dstv_dHead",
2035
+ children: [
2036
+ jsx("span", { className: `dstv_dBadge ${badgeCls}`, children: badgeText }, "dBadge"),
2037
+ dStatus,
2038
+ activeStation.tag !== null && activeStation.tag !== void 0 ? jsx("span", { className: "dstv_chip", children: activeStation.tag }, "dTg") : null,
2039
+ activeStation.kind === "step" && activeStation.durationMs != null
2040
+ ? jsx("span", { className: "dstv_chip info", children: `⏱ ${fmtMs(activeStation.durationMs)}` }, "dDur")
2041
+ : activeStation.kind === "step" && activeStation.timingRecorded === false
2042
+ ? jsx("span", { className: "dstv_chip", title: t("timing.notRecordedHint"), children: `⏱ ${t("timing.notRecorded")}` }, "dDurNo")
2043
+ : activeStation.kind === "step" && (activeStation.startMs == null || activeStation.endMs == null)
2044
+ ? jsx("span", { className: "dstv_chip warn", title: t("timing.edgeOutsideHint"), children: `⏱ ${t("timing.partial")}` }, "dDurPart")
2045
+ : null,
2046
+ activeStation.kind === "step" && activeStation.ttftMs != null ? jsx("span", { className: "dstv_chip", children: `${t("chip.ttft")} ${fmtMs(activeStation.ttftMs)}` }, "dTtft") : null,
2047
+ activeStation.kind === "step" && activeStation.decodeRate != null ? jsx("span", { className: "dstv_chip violet", children: `⚡ ${activeStation.decodeRate.toFixed(1)} tok/s` }, "dRate") : null,
2048
+ activeModel != null ? jsx("span", { className: "dstv_modelChip", title: activeModel, children: `🤖 ${activeModel}` }, "dModel") : null,
2049
+ activeClock !== "" ? jsx("span", { className: "dstv_chip", children: `${t("detail.time")} ${activeClock}` }, "dTime") : null,
2050
+ (() => {
2051
+ const av = anchorOf(activeStation);
2052
+ if (av === null) return null;
2053
+ // Do not offer an anchor that does not come back to THIS card:
2054
+ // `e<seq>` names a seq, and one seq can carry several stations
2055
+ // (a turn-error shares the assistant's seq). The resolver prefers
2056
+ // the step, so this button used to copy an identity that jumped
2057
+ // to a different record when pasted.
2058
+ if (!anchorResolvesToSelf(activeStation, stations)) return null;
2059
+ return jsx("span", { className: "dstv_anchorWrap", title: av, children: jsx(CopyBtn, { text: av, label: `🔗 ${t("anchor.copy")}`, okLabel: t("anchor.copied"), failLabel: t("anchor.copyFailed") }, "dAnchor") }, "dAnchorWrap");
2060
+ })(),
2061
+ activeStation.synthetic === true ? jsx("span", { className: "dstv_chip warn", children: t("anchor.notPersisted") }, "dSynth") : null,
2062
+ // Shown once, in the header: the same note used to render here as well, so
2063
+ // every anchor result appeared twice on screen.
2064
+ jsx("span", { className: "dstv_dPos", children: `${t("detail.position")} ${String(activeIdx + 1)} / ${N}` }, "dPos"),
2065
+ jsx(CopyBtn, {
2066
+ text: stepMarkdown,
2067
+ label: `📋 ${t("action.exportStep")}`,
2068
+ okLabel: t("anchor.copied"),
2069
+ failLabel: t("anchor.copyFailed")
2070
+ }, "dExportStep"),
2071
+ jsx("button", { type: "button", className: "dstv_btn dstv_panelToggle", title: panelFull ? t("action.collapsePanel") : t("action.expandPanel"), onClick: () => setPanelFull((v) => !v), children: panelFull ? "⤡" : "⤢" }, "dToggle")
2072
+ ]
2073
+ }, "dHead"),
2074
+ // The key must include WHAT is being rendered, not just where. An error
2075
+ // boundary keeps its error state until it is unmounted or the user presses
2076
+ // retry, so a fixed key pinned one station's crash onto every later
2077
+ // station: selecting a perfectly good record still showed "render failed"
2078
+ // and only a manual retry cleared it. Switching tabs had the same problem.
2079
+ // Station cards already key on `card${s.id}`; this boundary was the one
2080
+ // place that forgot, because there is only one of it.
2081
+ jsx(RenderBoundary, {
2082
+ label: t("error.render"),
2083
+ retryLabel: t("error.retry"),
2084
+ hint: t("error.renderHint"),
2085
+ wide: true,
2086
+ render: () => (showTab === "request" && canRequest
2087
+ ? activeStation.kind === "compaction" ? renderCompactionRequestBody(activeStation) : renderRequestBody(activeStation, activeMessages)
2088
+ : renderDetailBody(activeStation))
2089
+ }, `dBodySafe:${String(activeStation.id)}:${showTab}`)
2090
+ ]
2091
+ }, "rootDetail");
2092
+
2093
+ const kpis = jsxs("div", {
2094
+ className: "dstv_kpis",
2095
+ children: [
2096
+ jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: String(stats.turns) }, "kvNum"), jsx("span", { children: t("node.turn") }, "kvLbl")] }, "kTurns"),
2097
+ jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: String(stats.steps) }, "kvNum"), jsx("span", { children: t("node.step") }, "kvLbl")] }, "kSteps"),
2098
+ jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: String(stats.tools) }, "kvNum"), jsx("span", { children: t("node.tool") }, "kvLbl")] }, "kTools"),
2099
+ jsxs("span", { className: `dstv_kpi${stats.errors > 0 ? " err" : ""}`, children: [jsx("b", { children: String(stats.errors) }, "kvNum"), jsx("span", { children: t("kpi.errors") }, "kvLbl")] }, "kErr"),
2100
+ jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: fmtDur(stats.toolMs) }, "kvNum"), jsx("span", { children: t("kpi.toolTime") }, "kvLbl")] }, "kDur"),
2101
+ stats.tokensIn > 0 ? jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: fmtTokens(stats.tokensIn) }, "kvNum"), jsx("span", { children: t("kpi.tokensIn") }, "kvLbl")] }, "kTokIn") : null,
2102
+ stats.tokensOut > 0 ? jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: fmtTokens(stats.tokensOut) }, "kvNum"), jsx("span", { children: t("kpi.tokensOut") }, "kvLbl")] }, "kTokOut") : null,
2103
+ live ? jsxs("span", { className: "dstv_kpi liveKpi", children: [jsx("i", { className: "dstv_dot", "data-live": true }, "kvDot"), jsx("b", { children: `${t("stat.current")} ${t("node.step")} ${String(tree.currentStepNo ?? "")}` }, "kvTxt")] }, "kLive") : null
2104
+ ]
2105
+ }, "rootKpi");
2106
+
2107
+ return jsxs("div", {
2108
+ className: "dstv_root",
2109
+ // The host renders no <main>, so axe flagged every node in this panel
2110
+ // under "region: content not contained by landmarks" (27 nodes). Declaring
2111
+ // the panel a labelled landmark cleared our elements (measured27 ->6; the
2112
+ //6 left belong to the host sidebar) and gives a jump target.
2113
+ role: "region",
2114
+ "aria-label": t("view.label"),
2115
+ tabIndex: 0,
2116
+ onKeyDown,
2117
+ // Opt into the host's overlapping composer layout. The host detects this
2118
+ // attribute and flips the composer seat to `position:absolute;bottom:0`
2119
+ // over a scroll container that no longer reserves room for it — the same
2120
+ // thing the official trajectory view does. Without it the composer takes
2121
+ // its default in-flow seat and our view sits *above* a permanently open
2122
+ // message box, which is wrong for a read-only replay surface.
2123
+ "data-conversation-composer-overlay": "",
2124
+ // ...but an overlay covers the last rows, so the panel still reserves room
2125
+ // it can scroll clear of.
2126
+ style: composerH > 0 ? { paddingBottom: `${composerH}px` } : undefined,
2127
+ children: [header, jsx("div", { className: "dstv_progress", children: jsx("i", { style: { width: `${Math.round((R / N) * 100)}%` } }, "progFill") }, "rootProg"), kpis, minimapTicks, body, detail]
2128
+ });
2129
+ }
2130
+ //#endregion