dsh-trajectory-traceview-plus 0.11.4 → 0.11.6

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/lib/client.js CHANGED
@@ -73,6 +73,10 @@ window.__ModuleLoader__.load({
73
73
  "kpi.tokensIn": "请求 tokens",
74
74
  "kpi.tokensOut": "生成 tokens",
75
75
  "kpi.errors": "错误",
76
+ // The KPI counts STEPS that contain an error, not error events: one step with 24
77
+ // tool calls and 4 failures shows 1. The bare label "错误 / Errors" made that read
78
+ // as a wrong number; the chip says what it counts now.
79
+ "kpi.errorSteps": "出错步骤",
76
80
  // The Token-usage chips were hardcoded English ("in" / "out" / "cache-read" …)
77
81
  // inside a Chinese panel, while README §2 describes this section as
78
82
  // "入站(含缓存读 / 写)与出站(含思考)". Same words as the README, compact
@@ -89,6 +93,9 @@ window.__ModuleLoader__.load({
89
93
  "detail.args": "调用参数",
90
94
  "detail.noArgs": "(无参数)",
91
95
  "detail.subCalls": "子调用",
96
+ // The budget silently dropped the tail: 20,000 children rendered 1,999 with no
97
+ // indication anywhere. Say how many exist when the list was cut.
98
+ "detail.subCallsCut": "只显示前 {shown} 个(共 {total} 个)",
92
99
  "detail.position": "站点",
93
100
  "detail.result": "工具结果",
94
101
  "detail.noResult": "(无结果内容)",
@@ -103,6 +110,8 @@ window.__ModuleLoader__.load({
103
110
  "detail.items": "项",
104
111
  "detail.request": "请求配置",
105
112
  "detail.systemPrompt": "系统提示",
113
+ "detail.systemOutside": "来自窗口外的系统事件 e{seq}",
114
+ "detail.systemNone": "(当前窗口内没有系统提示)",
106
115
  "detail.toolsCatalog": "工具目录",
107
116
  "detail.messages": "消息列表",
108
117
  "detail.copy": "复制",
@@ -126,6 +135,8 @@ window.__ModuleLoader__.load({
126
135
  "gap.idle": "空闲",
127
136
  "node.orphanTool": "孤立工具结果",
128
137
  "orphan.badge": "调用不在窗口内",
138
+ "node.replayedTool": "压缩重放的工具结果",
139
+ "orphan.replayBadge": "与 e{seq} 相同(上下文压缩后重放)",
129
140
  "orphan.noText": "(无结果文本)",
130
141
  "timing.notRecorded": "未记录耗时",
131
142
  "timing.notRecordedHint": "该步骤没有 timing 记录,无法得到耗时",
@@ -259,6 +270,7 @@ window.__ModuleLoader__.load({
259
270
  "kpi.tokensIn": "Prompt tokens",
260
271
  "kpi.tokensOut": "Output tokens",
261
272
  "kpi.errors": "Errors",
273
+ "kpi.errorSteps": "steps with errors",
262
274
  "usage.in": "in",
263
275
  "usage.fresh": "fresh",
264
276
  "usage.cacheRead": "cache-read",
@@ -270,6 +282,7 @@ window.__ModuleLoader__.load({
270
282
  "detail.args": "Call arguments",
271
283
  "detail.noArgs": "(no arguments)",
272
284
  "detail.subCalls": "Sub-calls",
285
+ "detail.subCallsCut": "showing the first {shown} of {total}",
273
286
  "detail.position": "Station",
274
287
  "detail.result": "Tool result",
275
288
  "detail.noResult": "(no result content)",
@@ -284,6 +297,8 @@ window.__ModuleLoader__.load({
284
297
  "detail.items": "items",
285
298
  "detail.request": "Request config",
286
299
  "detail.systemPrompt": "System prompt",
300
+ "detail.systemOutside": "from system event e{seq} outside the window",
301
+ "detail.systemNone": "(no system prompt in this window)",
287
302
  "detail.toolsCatalog": "Tool catalog",
288
303
  "detail.messages": "Messages",
289
304
  "detail.copy": "Copy",
@@ -307,6 +322,8 @@ window.__ModuleLoader__.load({
307
322
  "gap.idle": "Idle",
308
323
  "node.orphanTool": "Orphan tool result",
309
324
  "orphan.badge": "call outside window",
325
+ "node.replayedTool": "Replayed tool result",
326
+ "orphan.replayBadge": "same as e{seq} (re-sent after compaction)",
310
327
  "orphan.noText": "(no result text)",
311
328
  "timing.notRecorded": "no duration",
312
329
  "timing.notRecordedHint": "This step has no timing record at all",
@@ -625,6 +642,11 @@ window.__ModuleLoader__.load({
625
642
  // surface one consistent, high-contrast focus indicator (WCAG 2.4.7/2.4.11).
626
643
  ".dstv_root button:focus-visible,.dstv_root summary:focus-visible,.dstv_root a:focus-visible,.dstv_root input:focus-visible{outline:2px solid var(--dstv-info);outline-offset:2px;border-radius:6px}",
627
644
  // Suppress the ring only for pointer users, never for keyboard users.
645
+ // The panel root is focusable (it owns the keyboard shortcuts), and it had NO focus
646
+ // ring: real Tab put focus on `.dstv_root` with `:focus-visible=true` and
647
+ // `outline-style:none`, so a keyboard user could not see where they were. Inset so
648
+ // the ring is not clipped by the panel's own overflow.
649
+ ".dstv_root:focus-visible{outline:2px solid var(--dstv-info);outline-offset:-2px}",
628
650
  ".dstv_root:focus:not(:focus-visible){outline:none}",
629
651
  ".dstv_station:focus:not(:focus-visible){outline:none}",
630
652
  ".dstv_search:focus-within{border-color:var(--dstv-info);box-shadow:0 0 0 2px color-mix(in srgb,var(--dstv-info) 18%,transparent)}",
@@ -664,9 +686,21 @@ window.__ModuleLoader__.load({
664
686
  ".dstv_btn[data-on=true]{color:var(--dstv-info-ink);background:color-mix(in srgb,var(--dstv-info) 12%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dstv-info) 40%,transparent)}",
665
687
  ".dstv_tbtn[data-on=true]{color:var(--dstv-info-ink);background:color-mix(in srgb,var(--dstv-info) 14%,transparent);font-weight:700}",
666
688
  ".dstv_station[data-match=true] .dstv_hcard{border-color:transparent;background:linear-gradient(var(--dsw-alias-bg-layer-1),var(--dsw-alias-bg-layer-1)) padding-box,linear-gradient(135deg,var(--dstv-warn),var(--dstv-warn)) border-box;box-shadow:0 0 12px color-mix(in srgb,var(--dstv-warn) 35%,transparent)}",
667
- ".dstv_station[data-seek-dim=true] .dstv_hcard{opacity:.5;filter:saturate(.3)}",
668
- ".dstv_station[data-seek-dim=true] .dstv_hDot{opacity:.35}",
689
+ // Searching dims the non-matches. Driven from the listbox so a keystroke does not
690
+ // rewrite every station element (§13.72): reached = not [data-dim], matched =
691
+ // [data-match]. Same visual result, one attribute instead of N.
692
+ // `.dstv_listbox` does not exist: the element carrying `data-searching` is the
693
+ // horizontally-scrolling flex row, whose class is `.dstv_hflow`. The rule matched
694
+ // nothing, so typing a query left every non-matching card at full opacity while
695
+ // the MINIMAP dimmed correctly (its selector uses `.dstv_minimap`, which is real).
696
+ // Measured after the move to a container attribute: card opacity 1 / filter none
697
+ // with `data-searching="true"` on the listbox, tick opacity .25.
698
+ ".dstv_hflow[data-searching=true] .dstv_station:not([data-dim=true]):not([data-match=true]) .dstv_hcard{opacity:.5;filter:saturate(.3)}",
699
+ ".dstv_hflow[data-searching=true] .dstv_station:not([data-dim=true]):not([data-match=true]) .dstv_hDot{opacity:.35}",
669
700
  ".dstv_miniTick[data-match=true]{box-shadow:0 0 0 1.5px var(--dstv-warn);height:14px}",
701
+ // While searching, fade the ticks that did not match. Reached-only ticks fade via
702
+ // [data-dim]; the search fade lives here so it costs no per-tick attribute (§13.72).
703
+ ".dstv_minimap[data-searching=true] .dstv_miniTick:not([data-dim=true]):not([data-match=true]){opacity:.25}",
670
704
  ".dstv_detail.full{max-height:82vh}",
671
705
  ".dstv_panelToggle{margin-left:4px}",
672
706
  ".dstv_subCard{border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:5px 8px;background:var(--dsw-alias-bg-layer-2);display:flex;flex-direction:column;gap:3px;margin-top:3px}",
@@ -976,6 +1010,17 @@ window.__ModuleLoader__.load({
976
1010
  return max;
977
1011
  }
978
1012
  /** Fresh mutable per-step accumulator used while folding assistant nodes. */
1013
+ /**
1014
+ * Ordering key for a seq that may be missing or malformed.
1015
+ *
1016
+ * `null < 20` is TRUE (null coerces to 0), so an unparsed seq did not merely sort
1017
+ * badly — it pulled its whole turn to the FRONT of the timeline. Measured: a legal
1018
+ * fractional seq (22 - 0.9, the host's interrupted-reply marker) turned the order
1019
+ * into [prefix(t2), user20, error22, user10, step(t1)] instead of
1020
+ * [user10, step(t1), user20, prefix(t2), error22]. Everything that sorts or
1021
+ * compares seqs goes through this.
1022
+ */
1023
+ const orderKey = (v) => (typeof v === "number" && Number.isFinite(v) ? v : Number.MAX_SAFE_INTEGER);
979
1024
  function newStepState(seq) {
980
1025
  return {
981
1026
  seq, time: null, cells: [], live: false, request: null,
@@ -998,14 +1043,17 @@ window.__ModuleLoader__.load({
998
1043
  * though the cap was 2,000. The cap is per tool cell, not per root.
999
1044
  */
1000
1045
  function mapSubCalls(list, tr) {
1001
- if (!Array.isArray(list)) return [];
1046
+ if (!Array.isArray(list)) return { list: [], total: 0, truncated: false };
1002
1047
  const budget = { used: 0 };
1003
1048
  const out = [];
1004
1049
  for (const sub of list) {
1005
1050
  if (budget.used >= SUB_CALL_MAX_TOTAL) break;
1006
1051
  out.push(subDetailOf(sub, 0, budget, tr));
1007
1052
  }
1008
- return out;
1053
+ // The budget silently dropped the tail: a parent with 20,000 children rendered
1054
+ // 1,999 and NOTHING anywhere said so — not the panel, not the export. Reporting
1055
+ // it is the difference between "this is all there was" and "this is all that fit".
1056
+ return { list: out, total: list.length, truncated: budget.used >= SUB_CALL_MAX_TOTAL };
1009
1057
  }
1010
1058
  /** Map one sub-call entry (settled ToolResultNode or running shape) to full detail. */
1011
1059
  function subDetailOf(sub, depth, budget, tr) {
@@ -1423,7 +1471,16 @@ window.__ModuleLoader__.load({
1423
1471
  // step. Prefer a step (the thing anchors are normally copied from); otherwise
1424
1472
  // take the first match as before.
1425
1473
  const hits = stations.filter((st) => st.anchorSeq === parsed.seq);
1426
- if (hits.length === 0) return { ok: false, reason: "not-loaded", seq: parsed.seq };
1474
+ if (hits.length === 0) {
1475
+ // An anchor copied from a tool RESULT (`e19`) outlives the result becoming a
1476
+ // station: load one more page and seq 19 is now a cell inside the step at 15.
1477
+ // Reporting "not loaded" for an output that is visibly on screen is wrong, so
1478
+ // fall back to the step that absorbed that result.
1479
+ const absorbed = stations.find((st) => st.kind === "step"
1480
+ && (st.cells ?? []).some((c) => c.kind === "tool" && c.resultSeq === parsed.seq));
1481
+ if (absorbed !== void 0) return { ok: true, station: absorbed, absorbedFrom: parsed.seq };
1482
+ return { ok: false, reason: "not-loaded", seq: parsed.seq };
1483
+ }
1427
1484
  const preferred = hits.find((st) => st.kind === "step") ?? hits[0];
1428
1485
  return { ok: true, station: preferred };
1429
1486
  }
@@ -1702,16 +1759,43 @@ window.__ModuleLoader__.load({
1702
1759
  * but total for every input.
1703
1760
  */
1704
1761
  function stepOf(v) {
1705
- const n = typeof v === "symbol" ? NaN : Number(v);
1762
+ // `Number(obj)` throws when the object has no primitive conversion at all — an
1763
+ // ordinary hostile field (`{toString: null}`) took the WHOLE view down, because
1764
+ // this runs while seating every assistant node and nothing caught it. One bad
1765
+ // number must degrade one station, never the panel (§13.84).
1766
+ let n = NaN;
1767
+ try { n = typeof v === "symbol" ? NaN : Number(v); } catch { n = NaN; }
1706
1768
  return Math.max(1, Number.isFinite(n) ? Math.trunc(n) : 1);
1707
1769
  }
1708
1770
  function seqOf(v) {
1709
1771
  if (Number.isSafeInteger(v)) return v;
1710
1772
  // BigInt is comparable and printable, so keep it when it still fits a double.
1711
1773
  if (typeof v === "bigint") { const n = Number(v); return Number.isSafeInteger(n) ? n : null; }
1774
+ // A FRACTIONAL seq is legal: the host marks an interrupted reply at `22 - 0.9`
1775
+ // so it sorts just before the turn error at 22. Dropping it to null destroyed the
1776
+ // only ordering key the node had — and because `null < 20` is true, the whole turn
1777
+ // jumped to the front of the timeline (measured order: prefix(t2), user20,
1778
+ // error22, user10, step(t1)). Anchors are unaffected: every anchor site checks
1779
+ // `Number.isSafeInteger` itself, so a fractional seq still gets no `e` anchor.
1780
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1712
1781
  return null;
1713
1782
  }
1714
1783
  function deriveTraceTree(snap, t) {
1784
+ // The official contract is explicit that `prompt.system` is empty when the
1785
+ // `system/message` node "lies outside the loaded history window" — the text itself is
1786
+ // still available on the snapshot as `systemPrompts`. Without this, a window that starts
1787
+ // mid-conversation claimed the request carried NO system prompt (0 chars, "…" on screen),
1788
+ // which is a silent lie about what the model actually saw.
1789
+ const systemPrompts = Array.isArray(snap?.systemPrompts)
1790
+ ? snap.systemPrompts.filter((s) => s != null && typeof s === "object" && typeof s.text === "string" && s.text !== "")
1791
+ .slice().sort((a, b) => (Number(a.seq) || 0) - (Number(b.seq) || 0))
1792
+ : [];
1793
+ const systemPromptBefore = (seq) => {
1794
+ if (!Number.isFinite(seq)) return null;
1795
+ let pick = null;
1796
+ for (const s of systemPrompts) { if (Number(s.seq) <= seq) pick = s; else break; }
1797
+ return pick;
1798
+ };
1715
1799
  const rawNodes = safeList(snap?.eventNodes);
1716
1800
  // Only pay for the copy when a node actually needs repairing: a well-formed
1717
1801
  // snapshot (the normal case) proceeds with the objects the host handed us.
@@ -1802,16 +1886,54 @@ window.__ModuleLoader__.load({
1802
1886
  // React warned about duplicate keys (measured: `["tdup","tdup"]`). Suffix the
1803
1887
  // ordinal unconditionally; it is what keeps same-id siblings apart.
1804
1888
  const cellId = (prefix, callId, ordinal) => `${prefix}${typeof callId === "string" ? callId : `?${String(ordinal)}`}#${String(ordinal)}`;
1805
- /** Next unclaimed result for this call id, or undefined when none is left. */
1806
- const takeResult = (callId) => {
1889
+ /**
1890
+ * Next unclaimed result for this call, or undefined when none is left.
1891
+ *
1892
+ * `turn`/`afterSeq` are not decoration: when the log omits `callId`, EVERY id-less
1893
+ * result lands in the same `resultsById` bucket under `undefined`, and "first
1894
+ * unconsumed" handed turn 2's output to turn 1's call — silently, with no
1895
+ * diagnostic (measured: CALL_A displayed ONLY-RESULT-B while CALL_B, the real
1896
+ * caller, showed nothing). Prefer a result from the SAME turn that comes AFTER
1897
+ * the call; fall back to the same turn, then to the legacy first-unconsumed so a
1898
+ * normal log behaves exactly as before.
1899
+ */
1900
+ // Which result seq was already consumed for each callId. Compaction replays tool
1901
+ // results (`tool/result` repeated under the SAME callId at a much later seq — measured
1902
+ // 13 such groups in one 17k-event session). Without this the duplicate looked like
1903
+ // "the call is outside the window", which is false: the call is right there and was
1904
+ // already answered.
1905
+ const consumedByCallId = new Map();
1906
+ const reclaimResult = (key, seq) => {
1907
+ if (key === void 0 || key === null) return;
1908
+ const list = consumedByCallId.get(key);
1909
+ if (list === void 0) consumedByCallId.set(key, [seq]);
1910
+ else list.push(seq);
1911
+ };
1912
+ const takeResult = (callId, turn, afterSeq) => {
1807
1913
  const list = resultsById.get(callId);
1808
1914
  if (list === void 0) return void 0;
1915
+ // Without an id, the bucket holds every id-less result in the window. A result
1916
+ // from ANOTHER turn is not this call's output — taking it is the silent
1917
+ // misattribution this rewrite exists to stop, so an id-less call refuses it
1918
+ // and shows "no result" instead of someone else's text.
1919
+ const idless = callId === void 0 || callId === null;
1920
+ let sameTurn = null;
1921
+ let legacy = null;
1809
1922
  for (const r of list) {
1810
1923
  if (consumedResults.has(r)) continue;
1811
- consumedResults.add(r);
1812
- return r;
1924
+ const sameTurnMatch = r.turn === turn && turn !== void 0;
1925
+ if (idless && !sameTurnMatch) continue;
1926
+ if (sameTurnMatch && Number.isFinite(afterSeq) && Number.isFinite(r.seq) && r.seq > afterSeq) {
1927
+ consumedResults.add(r);
1928
+ reclaimResult(callId, r.seq);
1929
+ return r;
1930
+ }
1931
+ if (sameTurnMatch && sameTurn === null) sameTurn = r;
1932
+ if (legacy === null) legacy = r;
1813
1933
  }
1814
- return void 0;
1934
+ const pick = sameTurn ?? legacy;
1935
+ if (pick !== null) { consumedResults.add(pick); reclaimResult(callId, pick.seq); }
1936
+ return pick ?? void 0;
1815
1937
  };
1816
1938
 
1817
1939
  // Requests keyed by `${turn}:${step}`, with prompt inheritance across
@@ -1899,12 +2021,13 @@ window.__ModuleLoader__.load({
1899
2021
  const ensureTurn = (turn, seq) => {
1900
2022
  let e = turnMap.get(turn);
1901
2023
  if (e === void 0) {
1902
- e = { turn, user: [], stations: [], seq: seq ?? Number.MAX_SAFE_INTEGER };
2024
+ e = { turn, user: [], stations: [], seq: orderKey(seq) };
1903
2025
  turnMap.set(turn, e);
1904
2026
  turns.push(e);
1905
2027
  lastTurnEntry = e;
1906
2028
  }
1907
- if (e.seq > seq) e.seq = seq;
2029
+ const ord = orderKey(seq);
2030
+ if (e.seq > ord) e.seq = ord;
1908
2031
  return e;
1909
2032
  };
1910
2033
  const flushUser = (turn, seq) => {
@@ -2004,11 +2127,11 @@ window.__ModuleLoader__.load({
2004
2127
  // `image`/`other` arrived). These used to fall through the chain and
2005
2128
  // vanish, so a future block type would render as "the model said
2006
2129
  // nothing". Name it instead of guessing at its content.
2007
- st.cells.push({ id: `u${n.seq}${st.cells.length}`, kind: "assistant", text: `${t("block.unknown")} · ${String(b.kind)}`, thinking: "" });
2130
+ st.cells.push({ id: `u${n.seq}${st.cells.length}`, kind: "assistant", text: unknownBlockLabel(b, t), thinking: "" });
2008
2131
  } else if (b.kind === "tool-call") {
2009
2132
  // every durable block is a real call, even with a repeated id
2010
2133
  claimCall(turn, b.callId);
2011
- const res = takeResult(b.callId);
2134
+ const res = takeResult(b.callId, turn, n.seq);
2012
2135
  const isRunning = res === undefined && runningById.has(b.callId);
2013
2136
  if (isRunning) st.live = true;
2014
2137
  const schema = schemasById.get(b.callId);
@@ -2024,6 +2147,7 @@ window.__ModuleLoader__.load({
2024
2147
  st.toolMs += dur ?? 0;
2025
2148
  st.toolCount += 1;
2026
2149
  if (res?.isError === true) st.hasError = true;
2150
+ const subPack1 = mapSubCalls(res?.subCalls, t);
2027
2151
  st.cells.push({
2028
2152
  id: cellId("t", b.callId, st.cells.length),
2029
2153
  kind: "tool",
@@ -2031,11 +2155,18 @@ window.__ModuleLoader__.load({
2031
2155
  name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
2032
2156
  args: argsText(b.argsRaw),
2033
2157
  resultText: res !== undefined ? blocksText(res.content, t) : "",
2158
+ // The result's own seq. A copied `tvp1:e19` anchor used to die the moment a page
2159
+ // load brought in the call header: seq 19 stopped being a station of its own and became
2160
+ // a cell of the step at 15, so the anchor said "not loaded" while the output was on
2161
+ // screen. `resultSeq` lets the resolver walk that back to the owning step.
2162
+ resultSeq: res !== undefined && Number.isSafeInteger(res.seq) ? res.seq : null,
2034
2163
  isError: res?.isError === true,
2035
2164
  errorName: res?.error?.name,
2036
2165
  durationMs: dur,
2037
2166
  running: isRunning,
2038
- subCalls: mapSubCalls(res?.subCalls, t),
2167
+ subCalls: subPack1.list,
2168
+ subCallsTotal: subPack1.total,
2169
+ subCallsTruncated: subPack1.truncated,
2039
2170
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
2040
2171
  });
2041
2172
  }
@@ -2110,13 +2241,16 @@ window.__ModuleLoader__.load({
2110
2241
  st.live = true;
2111
2242
  st.toolCount += 1;
2112
2243
  const schema = schemasById.get(c.callId);
2244
+ const subPack2 = mapSubCalls(c.subCalls, t);
2113
2245
  st.cells.push({
2114
2246
  id: cellId("t", c.callId, st.cells.length), kind: "tool", callId: c.callId,
2115
2247
  name: typeof c.name === "string" && c.name !== "" ? c.name : t("node.tool"),
2116
2248
  args: argsText(c.argsRaw),
2117
2249
  resultText: "", isError: false, errorName: void 0, durationMs: null,
2118
2250
  running: true,
2119
- subCalls: mapSubCalls(c.subCalls, t),
2251
+ subCalls: subPack2.list,
2252
+ subCallsTotal: subPack2.total,
2253
+ subCallsTruncated: subPack2.truncated,
2120
2254
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
2121
2255
  });
2122
2256
  }
@@ -2192,23 +2326,31 @@ window.__ModuleLoader__.load({
2192
2326
  // know must be NAMED, not dropped. The streaming branch was missed when the
2193
2327
  // durable one got the placeholder, so a live `file`/future block showed an
2194
2328
  // empty step (measured: cells [] for {kind:"future"} and {kind:"file"}).
2195
- st.cells.push({ id: `pu${st.cells.length}`, kind: "assistant", text: `${t("block.unknown")} · ${String(b.kind)}`, thinking: "" });
2329
+ st.cells.push({ id: `pu${st.cells.length}`, kind: "assistant", text: unknownBlockLabel(b, t), thinking: "" });
2196
2330
  } else if (b.kind === "tool-call") {
2197
2331
  if (claimedCall(turn, b.callId)) continue;
2198
2332
  claimCall(turn, b.callId);
2199
- const res = takeResult(b.callId);
2333
+ const res = takeResult(b.callId, turn, seq);
2200
2334
  st.toolCount += 1;
2201
2335
  if (res?.isError === true) st.hasError = true;
2202
2336
  const schema = schemasById.get(b.callId);
2337
+ const subPack3 = mapSubCalls(res?.subCalls, t);
2203
2338
  st.cells.push({
2204
2339
  id: cellId("t", b.callId, st.cells.length), kind: "tool", callId: b.callId,
2205
2340
  name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
2206
2341
  args: argsText(b.argsRaw),
2207
2342
  resultText: res !== undefined ? blocksText(res.content, t) : "",
2343
+ // The result's own seq. A copied `tvp1:e19` anchor used to die the moment a page
2344
+ // load brought in the call header: seq 19 stopped being a station of its own and became
2345
+ // a cell of the step at 15, so the anchor said "not loaded" while the output was on
2346
+ // screen. `resultSeq` lets the resolver walk that back to the owning step.
2347
+ resultSeq: res !== undefined && Number.isSafeInteger(res.seq) ? res.seq : null,
2208
2348
  isError: res?.isError === true,
2209
2349
  errorName: res?.error?.name,
2210
2350
  durationMs: null, running: res === undefined,
2211
- subCalls: mapSubCalls(res?.subCalls, t),
2351
+ subCalls: subPack3.list,
2352
+ subCallsTotal: subPack3.total,
2353
+ subCallsTruncated: subPack3.truncated,
2212
2354
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
2213
2355
  });
2214
2356
  }
@@ -2222,7 +2364,7 @@ window.__ModuleLoader__.load({
2222
2364
  // Binary search: `turnsBySeq` is already sorted. The previous linear scan ran
2223
2365
  // once per compaction/special event, so a log with many of both cost
2224
2366
  // O(events x turns) — measured 105 ms at 1000 turns, and it grows from there.
2225
- const turnForSeq = (s) => {
2367
+ const turnForSeq = (s, turnHint) => {
2226
2368
  let lo = 0;
2227
2369
  let hi = turnsBySeq.length - 1;
2228
2370
  let best = null;
@@ -2231,7 +2373,21 @@ window.__ModuleLoader__.load({
2231
2373
  if (turnsBySeq[mid].seq <= s) { best = turnsBySeq[mid]; lo = mid + 1; }
2232
2374
  else hi = mid - 1;
2233
2375
  }
2234
- return best ?? lastTurnEntry ?? ensureTurn(0, s);
2376
+ if (best !== null) return best;
2377
+ // The event sits BEFORE every turn boundary in this window. That is the normal
2378
+ // shape after paging: a page can start on a tool RESULT whose call sits above
2379
+ // it, and the result's own turn then has no boundary at or before its seq.
2380
+ //
2381
+ // The fallback used to be `lastTurnEntry` — the turn created LAST — so the
2382
+ // orphan was filed under the newest turn and `ensureTurn` lowered that turn's
2383
+ // seq to the orphan's. Sorting by seq then put the NEWEST turn first and split
2384
+ // the timeline: turn 68 → 65 → 66 → 67, with ~1h52m of apparent rewind in the
2385
+ // gap bars, and the export filed the result under the wrong turn (§13.83).
2386
+ //
2387
+ // Prefer the event's OWN turn when the log states one (the orphan's node
2388
+ // carries `turn`), else the earliest turn — never the last.
2389
+ const hinted = turnMap.get(typeof turnHint === "number" ? turnHint : NaN);
2390
+ return hinted ?? turnsBySeq[0] ?? ensureTurn(0, s);
2235
2391
  };
2236
2392
  const consumedCompactionReqs = new Set();
2237
2393
  // Index the exact-replacementSeq match instead of scanning every request per
@@ -2248,7 +2404,7 @@ window.__ModuleLoader__.load({
2248
2404
  }
2249
2405
  for (const n of nodes) {
2250
2406
  if (n.kind === "compaction") {
2251
- const e = turnForSeq(n.seq);
2407
+ const e = turnForSeq(n.seq, n.turn);
2252
2408
  // Pair with the compaction provider request: exact replacementSeq
2253
2409
  // match first, else the nearest unconsumed compaction request that
2254
2410
  // completed within a minute before this marker landed.
@@ -2263,6 +2419,13 @@ window.__ModuleLoader__.load({
2263
2419
  let best = null;
2264
2420
  for (const r of compactionReqs) {
2265
2421
  if (consumedCompactionReqs.has(r)) continue;
2422
+ // A request that NAMES a different replacementSeq belongs to that
2423
+ // marker. Time-proximity used to override the declaration, so a
2424
+ // marker at seq 20 displayed the output of the request for seq 10 —
2425
+ // a marker outside the window — and `unplacedRequests` stayed 0, so
2426
+ // nothing said the text was someone else's. Leaving it unconsumed
2427
+ // makes the view report it instead of borrowing it.
2428
+ if (Number.isSafeInteger(r.replacementSeq) && r.replacementSeq !== n.seq) continue;
2266
2429
  const doneAt = Number.isFinite(r.completedAt) ? r.completedAt : r.startedAt;
2267
2430
  if (!Number.isFinite(doneAt)) continue;
2268
2431
  const gap = n.time - doneAt;
@@ -2313,7 +2476,7 @@ window.__ModuleLoader__.load({
2313
2476
  const e = ensureTurn(typeof n.turn === "number" ? n.turn : 0, n.seq);
2314
2477
  e.stations.push({ id: `x${n.seq}`, kind: "maxTokens", time: n.time, seq: n.seq, label: t("node.maxTokens") });
2315
2478
  } else if (n.kind === "command") {
2316
- const e = turnForSeq(n.seq);
2479
+ const e = turnForSeq(n.seq, n.turn);
2317
2480
  e.stations.push({
2318
2481
  id: `c${n.seq}`, kind: "command", time: n.time, seq: n.seq,
2319
2482
  name: asText(n.name) !== "" ? asText(n.name) : `/${asText(n.commandId) || "?"}`, args: asText(n.args),
@@ -2324,7 +2487,7 @@ window.__ModuleLoader__.load({
2324
2487
  // The contract's own fallback surface. Rendering nothing would hide a
2325
2488
  // real event that exists in the session log, and the review tool's whole
2326
2489
  // promise is that what the log recorded is what the reader sees.
2327
- const e = turnForSeq(n.seq);
2490
+ const e = turnForSeq(n.seq, n.turn);
2328
2491
  e.stations.push({
2329
2492
  id: `k${n.seq}`, kind: "unknown", time: n.time, seq: n.seq,
2330
2493
  eventType: typeof n.type === "string" ? n.type : "",
@@ -2366,9 +2529,10 @@ window.__ModuleLoader__.load({
2366
2529
  return `ot${base}${seen === 0 ? "" : `_${String(seen)}`}`;
2367
2530
  };
2368
2531
  for (const n of orphans) {
2369
- const e = turnForSeq(n.seq);
2532
+ const e = turnForSeq(n.seq, n.turn);
2370
2533
  const text = blocksText(n.content, t);
2371
- const subCalls = mapSubCalls(n.subCalls, t);
2534
+ const subCallPack = mapSubCalls(n.subCalls, t);
2535
+ const subCalls = subCallPack.list;
2372
2536
  // Anchor issuance is centralized in the "special stations" branch below
2373
2537
  // (it re-checks `seq` for integer-ness and stamps anchorKey/synthetic).
2374
2538
  e.stations.push({
@@ -2395,6 +2559,14 @@ window.__ModuleLoader__.load({
2395
2559
  displayText: text !== "" ? text : (n.error?.code ?? n.error?.name ?? ""),
2396
2560
  isError: n.isError === true,
2397
2561
  subCalls,
2562
+ subCallsTotal: subCallPack.total,
2563
+ subCallsTruncated: subCallPack.truncated,
2564
+ // Set when this same callId ALREADY produced a result earlier in the window —
2565
+ // i.e. this is a compaction replay, not a missing call.
2566
+ replayOf: (() => {
2567
+ const used = consumedByCallId.get(n.callId);
2568
+ return used !== void 0 && used.length > 0 ? used[0] : null;
2569
+ })(),
2398
2570
  hasError: n.isError === true
2399
2571
  });
2400
2572
  }
@@ -2404,9 +2576,9 @@ window.__ModuleLoader__.load({
2404
2576
  // Sort turns by their earliest known seq first (turn 0 "system events" may
2405
2577
  // be created late by a stray compaction/command and would otherwise land last).
2406
2578
  for (const e of turns) {
2407
- let mseq = e.seq;
2408
- for (const st of e.stations) if (st.seq < mseq) mseq = st.seq;
2409
- for (const st of e.steps?.values() ?? []) if (st.seq < mseq) mseq = st.seq;
2579
+ let mseq = orderKey(e.seq);
2580
+ for (const st of e.stations) mseq = Math.min(mseq, orderKey(st.seq));
2581
+ for (const st of e.steps?.values() ?? []) mseq = Math.min(mseq, orderKey(st.seq));
2410
2582
  e.minSeq = mseq;
2411
2583
  }
2412
2584
  turns.sort((a, b) => a.minSeq - b.minSeq);
@@ -2420,7 +2592,7 @@ window.__ModuleLoader__.load({
2420
2592
  const turnNodes = turns.map((e) => {
2421
2593
  const pieceList = [];
2422
2594
  for (const s of e.stations) {
2423
- pieceList.push({ at: s.seq, kind: s.kind, data: s });
2595
+ pieceList.push({ at: orderKey(s.seq), kind: s.kind, data: s });
2424
2596
  if (s.kind === "orphan-tool") {
2425
2597
  stats.tools += 1;
2426
2598
  if (s.isError === true) stats.errors += 1;
@@ -2429,7 +2601,7 @@ window.__ModuleLoader__.load({
2429
2601
  const stepNums = e.steps === void 0 ? [] : [...e.steps.keys()].sort((a, b) => a - b);
2430
2602
  for (const s of stepNums) {
2431
2603
  const st = e.steps.get(s);
2432
- pieceList.push({ at: st.seq, kind: "step", data: st, stepNum: s });
2604
+ pieceList.push({ at: orderKey(st.seq), kind: "step", data: st, stepNum: s });
2433
2605
  }
2434
2606
  pieceList.sort((a, b) => a.at - b.at);
2435
2607
 
@@ -2502,6 +2674,15 @@ window.__ModuleLoader__.load({
2502
2674
  tools: Array.isArray(found.prompt.tools) ? found.prompt.tools : [],
2503
2675
  systemChars: typeof found.prompt.system === "string" ? found.prompt.system.length : 0
2504
2676
  } : null,
2677
+ // Present only when the request header's own prompt text is empty AND an older
2678
+ // system event exists: the reader then sees the real text, labelled as coming from
2679
+ // outside the window, instead of "0 chars".
2680
+ systemFrom: (() => {
2681
+ const own = found.prompt != null && typeof found.prompt.system === "string" ? found.prompt.system : "";
2682
+ if (own !== "") return null;
2683
+ const older = systemPromptBefore(Number(r.startSeq));
2684
+ return older !== null ? { seq: Number(older.seq), text: older.text, update: older.update === true } : null;
2685
+ })(),
2505
2686
  promptChangeKind: r.promptChange?.kind ?? null,
2506
2687
  promptDiff: promptDiffOf(r.promptChange, found.prompt),
2507
2688
  startSeq: r.startSeq ?? null
@@ -2737,6 +2918,26 @@ window.__ModuleLoader__.load({
2737
2918
  const flat = String(raw ?? "").replace(/\s+/g, " ").trim();
2738
2919
  return flat.length > 80 ? `${flat.slice(0, 80)}…` : flat;
2739
2920
  }
2921
+ /**
2922
+ * The label for a block kind this build does not know.
2923
+ *
2924
+ * It used to be `${t("block.unknown")} · ${String(b.kind)}`, which is fine for a
2925
+ * FUTURE kind ("未知内容 · image") but renders the literal string "undefined" when
2926
+ * the kind is missing entirely — and that label reaches both the card text and the
2927
+ * station's aria-label, so a screen-reader user heard "unknown content · undefined".
2928
+ * A record with no kind at all is a malformed record, not a future one, and naming
2929
+ * it "undefined" is worse than saying nothing.
2930
+ * @param b - the block whose kind is unknown.
2931
+ * @param t - the bound language function.
2932
+ * @returns the label to show.
2933
+ */
2934
+ function unknownBlockLabel(b, t) {
2935
+ const base = t("block.unknown");
2936
+ const kind = b !== null && b !== void 0 ? b.kind : void 0;
2937
+ if (typeof kind !== "string" || kind === "") return base;
2938
+ return `${base} · ${kind}`;
2939
+ }
2940
+
2740
2941
  function stationAriaLabel(station, position, total, t) {
2741
2942
  // Per-turn number: `stepNo` is a window-wide counter, so this label used to
2742
2943
  // read "步骤 1" and then "步骤 5" for the same station once older history was
@@ -2745,7 +2946,8 @@ window.__ModuleLoader__.load({
2745
2946
  : station.kind === "user" ? t("node.user")
2746
2947
  : station.kind === "error" ? t("node.error")
2747
2948
  : station.kind === "compaction" ? t("node.compaction")
2748
- : station.kind === "orphan-tool" ? t("node.orphanTool")
2949
+ // Same distinction as the card: a compaction replay is not a missing call.
2950
+ : station.kind === "orphan-tool" ? t(station.replayOf !== null && station.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")
2749
2951
  : station.kind === "unknown" ? t("node.unknown")
2750
2952
  : String(station.kind);
2751
2953
  const parts = [`${position} / ${total}`, kind];
@@ -2907,6 +3109,16 @@ window.__ModuleLoader__.load({
2907
3109
  // again here duplicated every sub-call result in the export.
2908
3110
  pushSubLines(L, sub, 1, t);
2909
3111
  }
3112
+ // Say it when the list was cut. A file that silently stops at 1,999 of
3113
+ // 20,000 reads as "this was everything", which is the one outcome this
3114
+ // view promises never to produce.
3115
+ if (cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal)) {
3116
+ const shown = (cell.subCalls ?? []).length;
3117
+ L.push("");
3118
+ L.push(`> ${typeof t === "function"
3119
+ ? t("detail.subCallsCut").replace("{shown}", fmtInt(shown)).replace("{total}", fmtInt(cell.subCallsTotal))
3120
+ : `showing the first ${String(shown)} of ${String(cell.subCallsTotal)}`}`);
3121
+ }
2910
3122
  L.push("");
2911
3123
  }
2912
3124
  }
@@ -2986,7 +3198,27 @@ window.__ModuleLoader__.load({
2986
3198
  // "[object Object]".
2987
3199
  return asText(content)
2988
3200
  .replace(/`{3,}/g, (run) => "\\`".repeat(run.length))
2989
- .replace(/<(\/?)(details)\b/gi, "&lt;$1$2");
3201
+ // GFM fences with TILDES too, and only backticks were escaped: prose ending in an
3202
+ // unclosed "~~~" turned every following station into code (verified with Pandoc
3203
+ // by the boundary review). Same treatment: leading tildes of a run this long
3204
+ // get escaped, so the run is no longer a fence opener.
3205
+ .replace(/(^|\n)(~{3,})/g, (m, lead, run) => lead + "\\~".repeat(run.length))
3206
+ .replace(/<(\/?)(details)\b/gi, "&lt;$1$2")
3207
+ // A content line that starts with `#` becomes a real heading in the export and
3208
+ // silently re-sections the document (measured: a compaction summary containing
3209
+ // "### 伪造标题" produced a section the panel never showed). Escaping turns it
3210
+ // back into text; a Markdown renderer still displays the bare `#`.
3211
+ .replace(/^(\s*)(#{1,6})\s/gm, "$1\\$2 ");
3212
+ }
3213
+ /**
3214
+ * Free text that sits INSIDE a generated line (a heading, a label).
3215
+ *
3216
+ * `proseSafe` keeps newlines, which is right for a paragraph and wrong for a heading:
3217
+ * a tool name or a slash-command's arguments containing "\n### …" forges a section in
3218
+ * the exported Markdown. Flatten first, then apply the same escaping.
3219
+ */
3220
+ function inlineSafe(content) {
3221
+ return proseSafe(asText(content).replace(/\s+/g, " ").trim());
2990
3222
  }
2991
3223
  function fencedBlock(content, lang) {
2992
3224
  const text = String(content ?? "");
@@ -3115,6 +3347,27 @@ window.__ModuleLoader__.load({
3115
3347
  return out;
3116
3348
  }
3117
3349
  /** Block-level split. Returns descriptors; see mdInline for the inline level. */
3350
+ /**
3351
+ * Is this line a Markdown table separator (`|---|:--:|`)?
3352
+ *
3353
+ * Equivalent to `/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/`, but linear. The regex was
3354
+ * quadratic on failure: two overlapping classes around the mandatory `-` let it
3355
+ * re-split a long dash run for every possible position.
3356
+ */
3357
+ const WHITESPACE_CHAR = /\s/;
3358
+ function isTableSeparator(line) {
3359
+ if (typeof line !== "string") return false;
3360
+ let dashes = 0;
3361
+ for (let i = 0; i < line.length; i += 1) {
3362
+ const ch = line[i];
3363
+ if (ch === "-") { dashes += 1; continue; }
3364
+ // `\s` in the original class, plus the pipe. Testing one character at a time
3365
+ // keeps the whole thing linear and preserves CRLF and Unicode-space behaviour.
3366
+ if (ch === "|" || ch === ":" || WHITESPACE_CHAR.test(ch)) continue;
3367
+ return false;
3368
+ }
3369
+ return dashes > 0;
3370
+ }
3118
3371
  function mdBlocks(src) {
3119
3372
  const lines = String(src ?? "").replace(/\r\n?/g, "\n").split("\n");
3120
3373
  const blocks = [];
@@ -3148,7 +3401,12 @@ window.__ModuleLoader__.load({
3148
3401
  continue;
3149
3402
  }
3150
3403
  // Table: a header row followed by a |---|---| separator.
3151
- if (line.includes("|") && i + 1 < lines.length && /^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(lines[i + 1])) {
3404
+ // The separator test used to be `/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/`. Its two
3405
+ // character classes overlap on `-`, so a long dash run that FAILS backtracks over
3406
+ // every split: measured 2,000 hyphens 96 ms, 4,000 575 ms, 8,000 2.1 s,
3407
+ // 16,000 7.4 s — a synchronous stall inside the detail panel, on content a model
3408
+ // can emit. Same predicate, one linear pass (§13.84).
3409
+ if (line.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
3152
3410
  // `\|` is the escape for a literal pipe inside a cell — the only way to
3153
3411
  // put one in a table at all. Splitting on every `|` cut such a cell in
3154
3412
  // two, so `| a \| b | c |` became THREE columns ("a \", "b", "c") and
@@ -3210,6 +3468,30 @@ window.__ModuleLoader__.load({
3210
3468
  }
3211
3469
  return blocks;
3212
3470
  }
3471
+ /**
3472
+ * Hard caps for text that goes into a STATION CARD.
3473
+ *
3474
+ * A card shows at most four clamped lines, but `dstv_clamp4` only hides the overflow:
3475
+ * the text node and the `title` attribute both kept the whole string. Measured with a
3476
+ * 1 MB assistant message: 1,575 ms to paint one card and 1,000,007 characters in the
3477
+ * DOM (the tooltip alone carried the megabyte). The full text stays available through
3478
+ * copy, the detail panel and the export — the card is a thumbnail, not a viewer.
3479
+ */
3480
+ // 20 000, not 2 000: group 20 of the browser probe renders a 20k body in full and
3481
+ // requires a one-character edit deep inside it to repaint the card. The cap exists to
3482
+ // stop megabyte messages, not to change what a long-but-normal message looks like.
3483
+ const CARD_TEXT_MAX = 20000;
3484
+ const CARD_TITLE_MAX = 300;
3485
+ /** Clamp a string for rendering inside a card, marking that it was cut. */
3486
+ function cardText(v) {
3487
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
3488
+ return s.length > CARD_TEXT_MAX ? `${s.slice(0, CARD_TEXT_MAX)}…` : s;
3489
+ }
3490
+ /** Clamp a string for a `title` tooltip: a tooltip longer than this is unreadable. */
3491
+ function cardTitle(v) {
3492
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
3493
+ return s.length > CARD_TITLE_MAX ? `${s.slice(0, CARD_TITLE_MAX)}…` : s;
3494
+ }
3213
3495
  /** Markdown with markers stripped, for one-line previews. */
3214
3496
  function markdownToPlain(src) {
3215
3497
  let out = "";
@@ -3274,21 +3556,29 @@ window.__ModuleLoader__.load({
3274
3556
  L.push("");
3275
3557
  pushSubLines(L, sub, 1, t);
3276
3558
  }
3559
+ if (cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal)) {
3560
+ L.push("");
3561
+ L.push(`> ${t("detail.subCallsCut").replace("{shown}", fmtInt(cell.subCalls.length)).replace("{total}", fmtInt(cell.subCallsTotal))}`);
3562
+ }
3277
3563
  }
3278
3564
  }
3279
3565
  } else if (st.kind === "orphan-tool") {
3280
- L.push(`### ⤷ ${t("node.orphanTool")} · ${st.name}`);
3566
+ L.push(`### ⤷ ${t(st.replayOf !== null && st.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")} · ${st.name}`);
3281
3567
  L.push("");
3282
- L.push(`_${t("orphan.badge")} · ${anchorOf(st) ?? "—"}_`);
3568
+ L.push(`_${t(st.replayOf !== null && st.replayOf !== void 0 ? "orphan.replayBadge" : "orphan.badge").replace("{seq}", String(st.replayOf ?? ""))} · ${anchorOf(st) ?? "—"}_`);
3283
3569
  if (st.args !== "") { L.push(""); L.push(...fencedBlock(prettyArgs(st.args) || st.args, "json")); }
3284
3570
  if (st.displayText !== "") { L.push(""); L.push(...fencedBlock(st.displayText.length > 4000 ? `${st.displayText.slice(0, 4000)}\n…(${fmtInt(st.displayText.length)} ${t("detail.chars")})` : st.displayText)); }
3571
+ if (st.subCallsTruncated === true && Number.isSafeInteger(st.subCallsTotal)) {
3572
+ L.push("");
3573
+ L.push(`> ${t("detail.subCallsCut").replace("{shown}", fmtInt((st.subCalls || []).length)).replace("{total}", fmtInt(st.subCallsTotal))}`);
3574
+ }
3285
3575
  } else if (st.kind === "compaction") {
3286
3576
  L.push(`### ♺ ${st.label}${Number.isSafeInteger(st.count) ? ` _(${numOr(st.count)} ${t("meta.steps")} / ${fmtTokens(st.tokens)} ${t("meta.tokens")})_` : ""}`);
3287
- if (st.summary !== "") { L.push(""); L.push(st.summary); }
3288
- if (st.crequest?.outputText) { L.push(""); L.push(`<details><summary>${t("detail.compactionOutput")}</summary>`); L.push(""); L.push(st.crequest.outputText); L.push("</details>"); }
3577
+ if (st.summary !== "") { L.push(""); L.push(proseSafe(st.summary)); }
3578
+ if (st.crequest?.outputText) { L.push(""); L.push(`<details><summary>${t("detail.compactionOutput")}</summary>`); L.push(""); L.push(proseSafe(st.crequest.outputText)); L.push("</details>"); }
3289
3579
  } else if (st.kind === "error") {
3290
3580
  L.push(`### ✗ ${st.label}${st.code != null ? ` \`${st.code}\`` : ""}`);
3291
- L.push(""); L.push(st.message || "…");
3581
+ L.push(""); L.push(st.message ? proseSafe(st.message) : "…");
3292
3582
  } else if (st.kind === "retry") {
3293
3583
  // The detail panel shows the retry counter, the provider and the error
3294
3584
  // code; the export showed none of them, so the Markdown copy of a failed
@@ -3301,12 +3591,12 @@ window.__ModuleLoader__.load({
3301
3591
  if (st.code != null) retryBits.push(`code: ${st.code}`);
3302
3592
  if (st.retryState) retryBits.push(String(st.retryState));
3303
3593
  L.push(`### ↻ ${st.label}${retryBits.length > 0 ? ` (${retryBits.join(" · ")})` : ""}`);
3304
- if (st.message) { L.push(""); L.push(st.message); }
3594
+ if (st.message) { L.push(""); L.push(proseSafe(st.message)); }
3305
3595
  } else if (st.kind === "maxTokens") {
3306
3596
  L.push(`### ⛔ ${st.label}`);
3307
3597
  } else if (st.kind === "command") {
3308
- L.push(`### ⚡ /${st.name}${st.args !== "" ? ` ${st.args}` : ""}`);
3309
- if (st.outcomeText) { L.push(""); L.push(st.outcomeText); }
3598
+ L.push(`### ⚡ /${inlineSafe(st.name)}${st.args !== "" ? ` ${inlineSafe(st.args)}` : ""}`);
3599
+ if (st.outcomeText) { L.push(""); L.push(proseSafe(st.outcomeText)); }
3310
3600
  } else if (st.kind === "unknown") {
3311
3601
  L.push(`### ? ${t("node.unknown")}${st.eventType ? ` \`${st.eventType}\`` : ""}`);
3312
3602
  if (st.payload) { L.push(""); L.push(...fencedBlock(st.payload, "json")); }
@@ -3617,6 +3907,32 @@ window.__ModuleLoader__.load({
3617
3907
  function TraceMapView({ useSession, useTrajectory, t, viewRequest, completeViewRequest, loadOlder, sessionKey }) {
3618
3908
  const scrollerRef = (0, react.useRef)(null);
3619
3909
  const minimapRef = (0, react.useRef)(null);
3910
+ // Per-station rendered elements, so an unchanged card keeps its element identity and
3911
+ // React skips the subtree entirely. Cleared when the session changes (ids are only
3912
+ // unique within a session) — see `stationSig`'s comment.
3913
+
3914
+ const cardElCache = (0, react.useRef)(new Map());
3915
+ const tickElCache = (0, react.useRef)(new Map());
3916
+ // The caches live as long as the view, but their contents are only valid for one
3917
+ // language and one session: station ids are per-session, and a cached element holds
3918
+ // already-translated text. Clearing on change keeps `t` and `sessionKey` out of the
3919
+ // per-element signature (they would invalidate every card anyway).
3920
+ const sigCacheRef = (0, react.useRef)({ arr: null, sigs: [] });
3921
+ const cacheScopeRef = (0, react.useRef)({ t: null, sessionKey: null });
3922
+ // A cached element keeps the closures it was built with. Those closures would go
3923
+ // stale the moment the view re-renders (arrow keys read the current selection, seek
3924
+ // reads the current window) — so the cards call THROUGH this ref, which is refreshed
3925
+ // on every render. Element identity stays cacheable, behaviour stays current.
3926
+ const handlersRef = (0, react.useRef)({ seek: null, keyDown: null });
3927
+
3928
+
3929
+ if (cacheScopeRef.current.t !== t || cacheScopeRef.current.sessionKey !== sessionKey) {
3930
+ cacheScopeRef.current = { t, sessionKey };
3931
+ cardElCache.current.clear();
3932
+ tickElCache.current.clear();
3933
+ sigCacheRef.current.arr = null;
3934
+ sigCacheRef.current.sigs = [];
3935
+ }
3620
3936
  const searchRef = (0, react.useRef)(null);
3621
3937
  const initDone = (0, react.useRef)(false);
3622
3938
  // Which session this panel is showing. The host reuses one component instance
@@ -3625,6 +3941,10 @@ window.__ModuleLoader__.load({
3625
3941
  // applied to a completely different transcript. `sessionKey` arrives from the
3626
3942
  // slot's `inject`; when the host does not provide one, behaviour is unchanged.
3627
3943
  const sessionRef = (0, react.useRef)(sessionKey);
3944
+ // The session key that the CURRENT `revealed`/`query` values belong to. They lag one
3945
+ // render behind a key change (the clear is scheduled, not applied), and writing that
3946
+ // pair under the new key leaked one session's position into another.
3947
+ const stateKeyRef = (0, react.useRef)(sessionKey);
3628
3948
  // ── view state that survives a tab switch ─────────────────────────────
3629
3949
  // The host UNMOUNTS this panel when the reader looks at the conversation and
3630
3950
  // remounts it on return (measured: root count 0 → 1). Without this, every
@@ -3643,7 +3963,11 @@ window.__ModuleLoader__.load({
3643
3963
  // moment the reader typed a query — while the timeline had not moved at all —
3644
3964
  // and then the FIRST "next" went to match 2, so match 1 was only reachable by
3645
3965
  // wrapping all the way round.
3646
- const [matchPtr, setMatchPtr] = (0, react.useState)(-1);
3966
+ // The CURRENT match is tracked by STATION ID, not by array index. An index into
3967
+ // `matches` silently changes meaning when the station list grows: after a page
3968
+ // load the counter read "2/3" while the selection still sat on the record that
3969
+ // used to be match 2 of 2 and had become match 3 of 3.
3970
+ const [matchId, setMatchId] = (0, react.useState)(null);
3647
3971
  const [follow, setFollow] = (0, react.useState)(true);
3648
3972
  const [panelFull, setPanelFull] = (0, react.useState)(false);
3649
3973
  const [anchorNote, setAnchorNote] = (0, react.useState)(null);
@@ -3710,9 +4034,13 @@ window.__ModuleLoader__.load({
3710
4034
  requests: snap.requests,
3711
4035
  callSchemas: snap.callSchemas,
3712
4036
  runningCalls: snap.runningCalls,
4037
+ // Passed through for the "system prompt sits outside the loaded window"
4038
+ // case: the contract leaves `request.prompt.system` EMPTY there, and the
4039
+ // real text only exists on the snapshot.
4040
+ systemPrompts: snap.systemPrompts,
3713
4041
  partial: partialRef.current
3714
4042
  }, t),
3715
- [snap.eventNodes, snap.requests, snap.callSchemas, snap.runningCalls, partialSig, streamTick, t]
4043
+ [snap.eventNodes, snap.requests, snap.callSchemas, snap.runningCalls, snap.systemPrompts, partialSig, streamTick, t]
3716
4044
  );
3717
4045
  const stations = tree.stations;
3718
4046
  const stationsRef = (0, react.useRef)(stations);
@@ -3750,14 +4078,36 @@ window.__ModuleLoader__.load({
3750
4078
  setFollow(true);
3751
4079
  setRevealed(null); // overview: show the whole new transcript
3752
4080
  setQueryRaw("");
3753
- setMatchPtr(0);
4081
+ setMatchId(null);
3754
4082
  setOlderNote(null);
3755
4083
  setPanelFull(false);
3756
4084
  setTab("detail");
4085
+ // The anchor box kept the previous conversation's text: harmless (it is not
4086
+ // stored, and the note is fixed wording) but it reads as if it still referred to
4087
+ // the session on screen. Everything else in this reset block is per-session, so
4088
+ // this belongs here too.
4089
+ setAnchorInput("");
4090
+ setAnchorNote(null);
3757
4091
  }, [sessionKey]);
3758
4092
 
3759
4093
  // Remember where the reader was, so a host-initiated remount resumes there.
4094
+ //
4095
+ // The key and the VALUES can belong to different sessions for one render: when
4096
+ // `sessionKey` changes, the reset effect above only SCHEDULES the clear, so this
4097
+ // effect still sees the previous session's `revealed`/`query` next to the NEW key.
4098
+ // Writing that pair files session A's position under session B, and the next mount
4099
+ // of B then restores a selection it never had.
4100
+ //
4101
+ // HONEST LIMIT: probe group 8b catches the SYMPTOM ("view state leaked into
4102
+ // another session") but does not isolate this guard — removing it leaves the probe
4103
+ // green in 2/2 runs (§13.78 hit the same wall with the cache-scope clear). The guard
4104
+ // stays because the mis-write is wrong on its face, not because a red would prove it.
3760
4105
  (0, react.useEffect)(() => {
4106
+ if (stateKeyRef.current !== sessionKey) {
4107
+ // Values in this render still belong to the previous session; drop them.
4108
+ stateKeyRef.current = sessionKey;
4109
+ return;
4110
+ }
3761
4111
  writeViewState(sessionKey, revealed, queryRaw);
3762
4112
  }, [sessionKey, revealed, queryRaw]);
3763
4113
 
@@ -3899,15 +4249,23 @@ window.__ModuleLoader__.load({
3899
4249
  const stepPrev = () => {
3900
4250
  setPlaying(false);
3901
4251
  setFollow(false);
3902
- if (revealed === null) { if (N > 0) setRevealed(N); return; }
3903
- if (R > 1) setRevealed(R - 1);
4252
+ // Functional update: held-down arrow keys arrive faster than React can re-render,
4253
+ // and reading `revealed` from the closure merged those repeats into a single step.
4254
+ // Measured: 20 synthetic presses in one tick advanced ONE station; with a 200 ms gap
4255
+ // they advanced 20. Real key auto-repeat sits in between, so the updater form is the
4256
+ // honest one.
4257
+ setRevealed((r) => {
4258
+ if (r === null) return N > 0 ? Math.min(N, Math.max(1, N)) : null;
4259
+ return r > 1 ? r - 1 : r;
4260
+ });
3904
4261
  };
3905
4262
  const stepNext = () => {
3906
4263
  setPlaying(false);
3907
4264
  setFollow(false);
3908
- if (revealed === null) { if (N > 0) setRevealed(1); return; }
3909
- if (R < N) setRevealed(R + 1);
3910
- else setRevealed(null);
4265
+ setRevealed((r) => {
4266
+ if (r === null) return N > 0 ? 1 : null;
4267
+ return r < N ? r + 1 : null;
4268
+ });
3911
4269
  };
3912
4270
  const toEnd = () => {
3913
4271
  setPlaying(false);
@@ -4156,7 +4514,7 @@ window.__ModuleLoader__.load({
4156
4514
 
4157
4515
  // ── follow mode: keep the newest station in view while live ──────────
4158
4516
  (0, react.useEffect)(() => {
4159
- if (!follow || revealed !== null) return;
4517
+ if (!follow || !followTipRef.current) return;
4160
4518
  const sc = scrollerRef.current;
4161
4519
  if (sc === null) return;
4162
4520
  try { sc.scrollLeft = sc.scrollWidth; } catch { /* noop */ }
@@ -4168,7 +4526,9 @@ window.__ModuleLoader__.load({
4168
4526
  const matchSet = (0, react.useMemo)(() => new Set(matches), [matches]);
4169
4527
  const searching = query !== "";
4170
4528
  const scopeNote = searchScopeNote(hasMore, loadingOlder, t);
4171
- (0, react.useEffect)(() => { setMatchPtr(-1); }, [query]);
4529
+ const matchPtr = (0, react.useMemo)(() => (matchId === null ? -1
4530
+ : matches.findIndex((i) => stations[i]?.id === matchId)), [matchId, matches, stations]);
4531
+ (0, react.useEffect)(() => { setMatchId(null); }, [query]);
4172
4532
  const gotoMatch = (dir) => {
4173
4533
  if (matches.length === 0) return;
4174
4534
  // A fresh query has no current match yet, so the FIRST step has to land on an
@@ -4176,7 +4536,7 @@ window.__ModuleLoader__.load({
4176
4536
  // where the match set shrank between keystrokes.
4177
4537
  const base = matchPtr < 0 || matchPtr >= matches.length ? (dir > 0 ? -1 : 0) : matchPtr;
4178
4538
  const next = ((base + dir) % matches.length + matches.length) % matches.length;
4179
- setMatchPtr(next);
4539
+ setMatchId(stations[matches[next]]?.id ?? null);
4180
4540
  seek(matches[next]);
4181
4541
  };
4182
4542
  const onSearchKey = (ev) => {
@@ -4209,7 +4569,12 @@ window.__ModuleLoader__.load({
4209
4569
  * (a selected `e30` became `e20`). Station ids are stable across rebuilds, so
4210
4570
  * remember the selected id and re-derive the position from it.
4211
4571
  */
4212
- const selectedIdRef = (0, react.useRef)(null);
4572
+ // `undefined` = "not recorded yet", `null` = "recorded, the overview is selected".
4573
+ // The distinction matters: a remount restores `revealed` BEFORE the station list
4574
+ // arrives, and writing `null` at that moment froze the pin as "nothing selected"
4575
+ // for good — the next page load then kept the INDEX and showed a different record
4576
+ // (measured: T6 → T3 after a remount onto an empty first frame).
4577
+ const selectedIdRef = (0, react.useRef)(void 0);
4213
4578
  const stationsSignature = (0, react.useMemo)(() => stations.map((st) => st.id).join("\u0000"), [stations]);
4214
4579
  // Read the station from the list directly: `activeStation` is declared further
4215
4580
  // down, and touching a `const` before its declaration throws ReferenceError on
@@ -4219,20 +4584,45 @@ window.__ModuleLoader__.load({
4219
4584
  // backwards page (same position, different station) and OVERWROTE the pinned
4220
4585
  // id with whatever now sat at that index, so the repair effect then "confirmed"
4221
4586
  // the wrong station. Verified live: e29532 became e28913 after loading history.
4222
- const prevRevealedRef = (0, react.useRef)(revealed);
4587
+ // Seeded with a SENTINEL, not with `revealed`. On a remount the view restores a
4588
+ // selection from storage, so initialising with the restored number made the first
4589
+ // effect run look like "nothing changed" and `selectedIdRef` was never written. The
4590
+ // pin-by-id repair then had nothing to work with, and the first page load after a
4591
+ // remount kept the INDEX instead of the station: measured "6 / 10 用户 T6" became
4592
+ // "6 / 13 用户 T3" once three older stations were prepended.
4593
+ const prevRevealedRef = (0, react.useRef)(void 0);
4594
+ // "The reader is at the LIVE TIP" — recorded when the SELECTION changes, using the
4595
+ // station count at that moment. Follow mode used to scroll only in the overview
4596
+ // (`revealed === null`), so with a station selected a newly streamed record stayed
4597
+ // off-screen even though 跟随 was on: measured 13 stations, station 13 selected,
4598
+ // a 14th arrives, `scrollLeft` unchanged and the new card 268 px past the right
4599
+ // edge. Appending a station must not clear this flag; only a deliberate jump to an
4600
+ // older record does.
4601
+ const followTipRef = (0, react.useRef)(true);
4223
4602
  (0, react.useEffect)(() => {
4224
4603
  const selectionChanged = prevRevealedRef.current !== revealed;
4225
4604
  prevRevealedRef.current = revealed;
4226
- if (!selectionChanged) return;
4605
+ // Re-run when the COUNT changes too: a restored selection can arrive before the
4606
+ // station list does, and without this the pin stayed unrecorded for ever.
4607
+ // Paging is still safe — once an id is recorded, `!changed` bails out below.
4608
+ if (!selectionChanged && selectedIdRef.current !== void 0) return;
4609
+ followTipRef.current = revealed === null
4610
+ || revealed >= stationsRef.current.length;
4611
+ if (revealed === null) { selectedIdRef.current = null; return; }
4612
+ // No stations yet: leave the pin UNRECORDED rather than recording "nothing",
4613
+ // so the arrival of the list can still fill it in.
4614
+ if (stationsRef.current.length === 0) return;
4227
4615
  selectedIdRef.current = revealed === null ? null
4228
4616
  : (stationsRef.current[Math.min(stationsRef.current.length - 1, Math.max(0, revealed - 1))]?.id ?? null);
4229
4617
  // stationsRef is intentionally read through the ref: depending on `stations`
4230
4618
  // here would re-fire on paging, which is the bug being fixed.
4231
4619
  // eslint-disable-next-line react-hooks/exhaustive-deps
4232
- }, [revealed]);
4620
+ }, [revealed, N]);
4233
4621
  (0, react.useEffect)(() => {
4234
4622
  const id = selectedIdRef.current;
4235
- if (id === null) return;
4623
+ // `void 0` means the pin has not been recorded yet (data was not ready); do not
4624
+ // treat that as "the overview is selected".
4625
+ if (id === null || id === void 0) return;
4236
4626
  const at = stations.findIndex((st) => st.id === id);
4237
4627
  // Gone from the window (should not happen for a prepend) or already correct.
4238
4628
  if (at < 0 || at + 1 === revealed) return;
@@ -4338,6 +4728,17 @@ window.__ModuleLoader__.load({
4338
4728
  seek(i); ev.preventDefault(); ev.stopPropagation();
4339
4729
  }
4340
4730
  };
4731
+ // Refreshed after commit; a cached element reads it at click/key time. A layout
4732
+ // effect rather than a render-time assignment, because a render React throws away
4733
+ // would otherwise leave the abandoned pass's handler behind.
4734
+ //
4735
+ // DECLARED HERE, above `if (N === 0)` and its early return: a hook below that
4736
+ // branch is skipped on the empty/loading render, and React aborts the whole panel
4737
+ // with "Rendered fewer hooks than expected".
4738
+ (0, react.useLayoutEffect)(() => {
4739
+ handlersRef.current.seek = seek;
4740
+ handlersRef.current.keyDown = stationOnKeyDown;
4741
+ });
4341
4742
  const onKeyDown = (ev) => {
4342
4743
  const k = ev.key;
4343
4744
  // Browser and OS shortcuts must win. The panel root is focusable
@@ -4348,6 +4749,12 @@ window.__ModuleLoader__.load({
4348
4749
  // scrolling to the top. Bail out on any modifier combination.
4349
4750
  if (ev.ctrlKey === true || ev.metaKey === true || ev.altKey === true) return;
4350
4751
  const tag = ev.target && ev.target.tagName ? String(ev.target.tagName).toLowerCase() : "";
4752
+ // Bail out when the key belongs to a text field. HONEST STATUS: with today's markup
4753
+ // this branch is UNREACHABLE — every input inside the panel (search, anchor) has its
4754
+ // own onKeyDown that calls stopPropagation for every key, so nothing arrives here from
4755
+ // a field. It is kept as a guard for the next field someone adds, and the probe
4756
+ // assertion ("End inside the anchor box does not clear the selection") therefore
4757
+ // cannot be made to fail by deleting this line; do not mistake it for coverage.
4351
4758
  if (tag === "input" || tag === "textarea" || tag === "select" || (ev.target && ev.target.isContentEditable === true)) return;
4352
4759
  if (k === "/" || k === "f") {
4353
4760
  if (searchRef.current !== null && typeof searchRef.current.focus === "function") { searchRef.current.focus(); ev.preventDefault(); }
@@ -4525,7 +4932,12 @@ window.__ModuleLoader__.load({
4525
4932
  type: "search",
4526
4933
  autoComplete: "off",
4527
4934
  "aria-label": t("search.label"),
4528
- value: query,
4935
+ // Bind the RAW text, not the trimmed match string. Rendering the
4936
+ // trimmed value made a controlled input swallow the space the user
4937
+ // had just typed: "alpha␣" was re-rendered as "alpha", so the next
4938
+ // word ran into it ("alphabeta") and a phrase search could never be
4939
+ // typed one key at a time. Matching still uses `query` (trimmed).
4940
+ value: queryRaw,
4529
4941
  placeholder: t("action.search"),
4530
4942
  onChange: (ev) => setQueryRaw(ev.target != null ? ev.target.value : ""),
4531
4943
  onKeyDown: onSearchKey
@@ -4650,6 +5062,137 @@ window.__ModuleLoader__.load({
4650
5062
  });
4651
5063
  }
4652
5064
 
5065
+ /**
5066
+ * Element cache for the station list and the minimap.
5067
+ *
5068
+ * Why: the list renders EVERY station on every state change. Measured on a
5069
+ * 900-station window, one keystroke in the search box cost 1.3–2.2 s of main
5070
+ * thread — typing a query was unusable. The tree fold is NOT the cost (that is
5071
+ * memoised and does not re-run on a keystroke); the cost is rebuilding ~900 card
5072
+ * subtrees and ~900 minimap buttons to flip `data-seek-dim` on the handful of
5073
+ * stations that actually matched.
5074
+ *
5075
+ * Rebuilding an element and re-rendering it are different costs, and React bails
5076
+ * out of the second when the ELEMENT IS THE SAME OBJECT (referential equality).
5077
+ * So: cache the element per station and return the previous one when nothing the
5078
+ * card reads has changed. Compared by VALUE — each fold allocates fresh station
5079
+ * objects, so nothing else here can be compared by identity (§13.72).
5080
+ *
5081
+ * The signature covers exactly what the card body reads: the station fields
5082
+ * `renderStationCard` + the axis zone touch, its position, its neighbour's edge
5083
+ * (the idle band), and the four per-station booleans the parent computes.
5084
+ */
5085
+ // FNV-1a over the fields the card reads, accumulated WITHOUT building a
5086
+ // concatenated string. The first version joined every field into one string —
5087
+ // harmlessly fast on the fixture, but a real 1000-node window carries ~1.1 MB of
5088
+ // tool output, and joining that per station per render made a keystroke cost
5089
+ // 1.17 s again. A rolling hash over each field is linear either way, but it
5090
+ // allocates nothing (§13.73).
5091
+
5092
+ const stationSig = (s) => {
5093
+ if (s == null) return "";
5094
+ let h = 2166136261;
5095
+ const mix = (v) => {
5096
+ if (v === null || v === void 0) { h = (h ^ 31) * 16777619 >>> 0; return; }
5097
+ if (typeof v === "number") {
5098
+ h = (h ^ (v | 0)) * 16777619 >>> 0;
5099
+ h = (h ^ (Math.floor(v * 1000) | 0)) * 16777619 >>> 0;
5100
+ return;
5101
+ }
5102
+ if (typeof v === "boolean") { h = (h ^ (v ? 1 : 2)) * 16777619 >>> 0; return; }
5103
+ const str = String(v);
5104
+ h = (h ^ str.length) * 16777619 >>> 0;
5105
+ for (let i = 0; i < str.length; i += 1) h = ((h ^ str.charCodeAt(i)) * 16777619) >>> 0;
5106
+ };
5107
+ mix(s.kind); mix(s.id); mix(s.label); mix(s.who); mix(s.text);
5108
+ mix(s.displayText); mix(s.summary); mix(s.message); mix(s.name);
5109
+ mix(s.args); mix(s.payload); mix(s.eventType); mix(s.replace); mix(s.retry);
5110
+ mix(s.isError); mix(s.hasError); mix(s.live); mix(s.synthetic); mix(s.tag);
5111
+ mix(s.time); mix(s.startMs); mix(s.endMs); mix(s.seq); mix(s.toolMs); mix(s.maxToolMs);
5112
+ // The duration bar divides by a GLOBAL denominator (`stats.maxToolMs ||
5113
+ // stats.toolMs`), not by this station's own maximum. Mixing only the station
5114
+ // fields meant every cached bar kept its old width when a DIFFERENT station
5115
+ // became the slowest one — a stale proportion bar, caught by review.
5116
+ // Hash the EFFECTIVE denominator, not both inputs. `stats.toolMs` is only a
5117
+ // fallback for a zero max, but hashing it made every card depend on the SUM of
5118
+ // all tool durations: one slow tool changed the total, so a 900-station window
5119
+ // rebuilt all 900 cards to widen a single bar. Measured by the perf review:
5120
+ // 900 rebuilds -> 1 with the effective denominator.
5121
+ mix(Math.max(1, stats.maxToolMs || stats.toolMs));
5122
+ mix(s.outcomeText); mix(s.outcomeKind);
5123
+ if (Array.isArray(s.meta)) { mix(s.meta.length); for (const m of s.meta) mix(m); }
5124
+ else mix(s.meta);
5125
+ // EVERY cell field the card renders, not just the shape. The first version
5126
+ // hashed only kind/isError/running — so a settled step whose assistant cell text
5127
+ // changed kept the OLD text on the card (verified: ALPHA-ONE stayed on screen
5128
+ // while the detail panel showed ALPHA-TWO). `resultText` is deliberately absent:
5129
+ // the card does not render it and it is by far the largest field (§13.75).
5130
+ if (Array.isArray(s.cells)) {
5131
+ mix(s.cells.length);
5132
+ for (const c of s.cells) {
5133
+ mix(c.kind); mix(c.id);
5134
+ mix(c.text); mix(c.thinking);
5135
+ mix(c.name); mix(c.args); mix(c.errorName);
5136
+ mix(c.durationMs); mix(c.isError === true); mix(c.running === true);
5137
+ }
5138
+ } else mix(-1);
5139
+ // The hash alone is not enough: FNV-1a is 32-bit and `mix` folds a number into
5140
+ // 64 bits of state, so two REAL inputs can land on the same value. Measured by
5141
+ // review: seq-identical user stations at time 1700000000000 and 1704294967296
5142
+ // produced the same signature, and the cached card kept 06:13:20 while the
5143
+ // minimap tick (whose signature carries `fmtClock`) had already moved to 23:16:07.
5144
+ // Appending the RENDERED text of the two derived values the card shows gives a
5145
+ // second, non-hash channel — a collision now has to happen in both.
5146
+ //
5147
+ // `s.turn` was missing entirely: a station re-projected from turn 1 to turn 2
5148
+ // kept an aria-label reading "轮次 1" while the projection said 2.
5149
+ return h.toString(36)
5150
+ + "\u0002" + fmtClock(s.time)
5151
+ + "\u0002" + (s.turn === null || s.turn === void 0 ? "" : String(s.turn));
5152
+ };
5153
+ /**
5154
+ * Sub-calls can nest (a tool that itself calls tools). The detail panel rendered
5155
+ * ONE level: everything from `sub.subCalls` down was invisible, while both the
5156
+ * single-step copy and the whole-trace export printed the whole chain — so the
5157
+ * screen showed strictly less than the file you could copy from it.
5158
+ *
5159
+ * Recursive now. `depth` only feeds the React key and a data attribute; there is
5160
+ * no visual indentation budget to blow.
5161
+ */
5162
+ const renderSubCalls = (subs, depth) => subs.map((sub, i) => {
5163
+ const subPretty = prettyArgs(sub.argsRaw);
5164
+ const nested = Array.isArray(sub.subCalls) ? sub.subCalls : [];
5165
+ return jsxs("div", {
5166
+ className: "dstv_subCard",
5167
+ "data-depth": depth > 0 ? String(depth) : undefined,
5168
+ children: [
5169
+ jsxs("span", {
5170
+ className: "dstv_subHead",
5171
+ children: [
5172
+ 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"),
5173
+ jsx("span", { className: "tname", children: `${depth > 0 ? "↳↳" : "↳"} ${sub.name}` }, "sName"),
5174
+ jsx("span", { className: "dstv_chips", children: [
5175
+ sub.running ? jsx("span", { className: "dstv_chip run", children: t("chip.running") }, "sRun") : null,
5176
+ sub.isError ? jsx("span", { className: "dstv_chip err", children: sub.errorName != null ? String(sub.errorName) : t("chip.error") }, "sErr") : null,
5177
+ sub.durationMs != null ? jsx("span", { className: "dstv_chip", children: fmtMs(sub.durationMs) }, "sDur") : null
5178
+ ] }, "sChips")
5179
+ ]
5180
+ }, "sHead"),
5181
+ sub.argsRaw !== "" ? jsxs("details", { className: "dstv_det", open: false, children: [
5182
+ jsx("summary", { children: [t("detail.args"), jsx("span", { className: "sub", children: `${sub.argsRaw.length}${t("detail.chars")}` }, "sALen")] }, "sASum"),
5183
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", children: subPretty !== "" ? subPretty : t("detail.noArgs") }, "sACode") }, "sAInner")
5184
+ ] }, "sArgs") : null,
5185
+ sub.resultText !== "" ? jsxs("details", { className: "dstv_det", open: sub.isError, children: [
5186
+ jsx("summary", { children: [sub.isError ? `✗ ${t("detail.result")}` : `✓ ${t("detail.result")}`, jsx("span", { className: "sub", children: String(sub.resultText.length) }, "sRLen")] }, "sRSum"),
5187
+ jsx("div", { className: "inner", children: jsxs("div", { children: [
5188
+ jsx(CopyBtn, { text: sub.resultText, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "sResCopy"),
5189
+ jsx("div", { className: "dstv_code", style: { marginTop: 4 }, children: sub.resultText }, "sResCode")
5190
+ ] }) }, "sRInner")
5191
+ ] }, "sRes") : null,
5192
+ nested.length > 0 ? jsx("div", { className: "dstv_subKids", children: renderSubCalls(nested, depth + 1) }, "sKids") : null
5193
+ ]
5194
+ }, `ts${depth}-${i}`);
5195
+ });
4653
5196
  const renderStationCard = (s, cardKey) => {
4654
5197
  if (s.kind === "user") {
4655
5198
  return jsxs("div", {
@@ -4657,7 +5200,7 @@ window.__ModuleLoader__.load({
4657
5200
  children: [
4658
5201
  jsx("span", { className: "dstv_name", children: s.who }, "uName"),
4659
5202
  s.time != null ? jsx("span", { className: "dstv_spanRow", children: jsx("span", { className: "dstv_spanEdge", children: fmtClock(s.time) }, "uClk") }, "uSpan") : null,
4660
- jsx("div", { className: "dstv_text dstv_clamp3", title: s.text, children: s.text || "…" }, "uText")
5203
+ jsx("div", { className: "dstv_text dstv_clamp3", title: cardTitle(s.text), children: cardText(s.text) || "…" }, "uText")
4661
5204
  ]
4662
5205
  }, cardKey);
4663
5206
  }
@@ -4695,8 +5238,8 @@ window.__ModuleLoader__.load({
4695
5238
  className: "dstv_cellRow",
4696
5239
  children: [
4697
5240
  jsx("span", { className: "dstv_cellName", children: t("node.assistant") }, "aName"),
4698
- cell.thinking !== "" ? jsx("div", { className: "dstv_text dstv_clamp2 sec", title: cell.thinking, children: `💭 ${markdownToPlain(cell.thinking)}` }, "aThink") : null,
4699
- cell.text !== "" ? jsx("div", { className: "dstv_text dstv_clamp2", title: cell.text, children: markdownToPlain(cell.text) }, "aText") : null
5241
+ cell.thinking !== "" ? jsx("div", { className: "dstv_text dstv_clamp2 sec", title: cardTitle(cell.thinking), children: `💭 ${cardText(markdownToPlain(cardText(cell.thinking)))}` }, "aThink") : null,
5242
+ cell.text !== "" ? jsx("div", { className: "dstv_text dstv_clamp2", title: cardTitle(cell.text), children: cardText(markdownToPlain(cardText(cell.text))) }, "aText") : null
4700
5243
  ]
4701
5244
  }, `a${cell.id}`);
4702
5245
  }
@@ -4735,12 +5278,20 @@ window.__ModuleLoader__.load({
4735
5278
  className: "dstv_name",
4736
5279
  children: [
4737
5280
  jsx("span", { className: s.isError ? "dstv_bad" : "dstv_ok", children: s.isError ? "✗" : "⤷" }, "oIcon"),
4738
- `${t("node.orphanTool")} · ${s.name}`,
4739
- jsx("span", { className: "dstv_chips", children: [jsx("span", { className: "dstv_chip info", children: t("orphan.badge") }, "oBadge")] }, "oChips")
5281
+ // A compaction REPLAY is a different thing from "the call is outside
5282
+ // the window": the call is right there and was already answered.
5283
+ // Saying the call is missing sends the reader looking for a bug.
5284
+ `${t(s.replayOf !== null && s.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")} · ${s.name}`,
5285
+ jsx("span", {
5286
+ className: "dstv_chips",
5287
+ children: [jsx("span", { className: "dstv_chip info", children: s.replayOf !== null && s.replayOf !== void 0
5288
+ ? t("orphan.replayBadge").replace("{seq}", String(s.replayOf))
5289
+ : t("orphan.badge") }, "oBadge")]
5290
+ }, "oChips")
4740
5291
  ]
4741
5292
  }, "oName"),
4742
- s.args !== "" ? jsx("div", { className: "dstv_text dstv_clamp2 sec", title: s.args, children: s.args }, "oArgs") : null,
4743
- jsx("div", { className: "dstv_text dstv_clamp4", title: body, children: body }, "oText")
5293
+ s.args !== "" ? jsx("div", { className: "dstv_text dstv_clamp2 sec", title: cardTitle(s.args), children: cardText(s.args) }, "oArgs") : null,
5294
+ jsx("div", { className: "dstv_text dstv_clamp4", title: cardTitle(body), children: cardText(body) }, "oText")
4744
5295
  ]
4745
5296
  }, cardKey);
4746
5297
  }
@@ -4749,7 +5300,7 @@ window.__ModuleLoader__.load({
4749
5300
  className: "dstv_hcard compactionCard",
4750
5301
  children: [
4751
5302
  jsx("span", { className: "dstv_name", children: `♺ ${t("node.compaction")}` }, "cName"),
4752
- jsx("div", { className: "dstv_text dstv_clamp2", title: s.summary, children: s.summary || "…" }, "cText")
5303
+ jsx("div", { className: "dstv_text dstv_clamp2", title: cardTitle(s.summary), children: cardText(s.summary) || "…" }, "cText")
4753
5304
  ]
4754
5305
  }, cardKey);
4755
5306
  }
@@ -4758,7 +5309,7 @@ window.__ModuleLoader__.load({
4758
5309
  className: "dstv_hcard errorCard",
4759
5310
  children: [
4760
5311
  jsx("span", { className: "dstv_name", children: `✗ ${t("node.error")}` }, "eName"),
4761
- jsx("div", { className: "dstv_text dstv_clamp2", title: s.message, children: s.message || "…" }, "eText")
5312
+ jsx("div", { className: "dstv_text dstv_clamp2", title: cardTitle(s.message), children: cardText(s.message) || "…" }, "eText")
4762
5313
  ]
4763
5314
  }, cardKey);
4764
5315
  }
@@ -4767,7 +5318,7 @@ window.__ModuleLoader__.load({
4767
5318
  className: "dstv_hcard retryCard",
4768
5319
  children: [
4769
5320
  jsx("span", { className: "dstv_name", children: `↻ ${t("node.retry")}${Number.isFinite(s.retry) ? ` #${s.retry}` : ""}` }, "rName"),
4770
- jsx("div", { className: "dstv_text sec dstv_clamp2", title: s.message, children: s.message || "…" }, "rText")
5321
+ jsx("div", { className: "dstv_text sec dstv_clamp2", title: cardTitle(s.message), children: cardText(s.message) || "…" }, "rText")
4771
5322
  ]
4772
5323
  }, cardKey);
4773
5324
  }
@@ -4786,7 +5337,7 @@ window.__ModuleLoader__.load({
4786
5337
  `${t("node.unknown")}${s.eventType !== "" ? ` · ${s.eventType}` : ""}`,
4787
5338
  jsx("span", { className: "dstv_chips", children: jsx("span", { className: "dstv_chip", children: `seq ${s.seq}` }, "ukSeq") }, "ukChips")
4788
5339
  ] }, "ukName"),
4789
- s.payload !== "" ? jsx("div", { className: "dstv_text sec dstv_clamp3", title: s.payload, children: s.payload }, "ukText") : null
5340
+ s.payload !== "" ? jsx("div", { className: "dstv_text sec dstv_clamp3", title: cardTitle(s.payload), children: cardText(s.payload) }, "ukText") : null
4790
5341
  ]
4791
5342
  }, cardKey);
4792
5343
  }
@@ -4814,6 +5365,9 @@ window.__ModuleLoader__.load({
4814
5365
  const minimapTicks = jsx("div", {
4815
5366
  className: "dstv_minimap",
4816
5367
  ref: minimapRef,
5368
+ // Same reason as the listbox: search dimming is one attribute on the strip,
5369
+ // not one per tick, so a keystroke does not rebuild every tick element.
5370
+ "data-searching": searching ? "true" : undefined,
4817
5371
  children: stations.map((s, i) => {
4818
5372
  const reached = i < R;
4819
5373
  let k = s.kind;
@@ -4821,14 +5375,45 @@ window.__ModuleLoader__.load({
4821
5375
  if (s.kind === "maxTokens") k = "error";
4822
5376
  const done = reached && (s.kind !== "step" || !s.live);
4823
5377
  const matched = searching && matchSet.has(i);
4824
- return jsx("button", {
5378
+ // Two DIFFERENT derived values, and the signature must hash each one.
5379
+ // `data-active` is `revealed !== null && i === R - 1`; the tab stop is that
5380
+ // OR the overview's first tick. Hashing only the tab stop made the two states
5381
+ // collide at i == 0: overview gives tab=1/active=0, selecting the first
5382
+ // station gives tab=1/active=1, so the cached tick kept `data-active`
5383
+ // undefined and the strip highlighted nothing (measured: three stations,
5384
+ // overview, click tick 0 → cards show selection 0, minimap active set []).
5385
+ const tickActive = revealed !== null && i === R - 1;
5386
+ const tickTab = tickActive || (revealed === null && i === 0);
5387
+ // Same element-identity trick as the station cards: an unchanged tick keeps
5388
+ // its element and React skips it (§13.72).
5389
+ const tickSig = s.kind + "\u0002" + String(i) + "\u0002" + (reached ? "1" : "0")
5390
+ + (done ? "1" : "0") + (matched ? "1" : "0") + (s.live === true ? "1" : "0")
5391
+ + (k === "tool" || k === "step" ? String(s.cells.length) : "")
5392
+ // The highlight and the "N / total" part of the aria-label change with the
5393
+ // selection and with the window length. Missing either leaves the old
5394
+ // highlight cached — caught by the minimap assertion, not by reasoning.
5395
+ //
5396
+ // The tab stop is the SAME expression as `tabIndex` below, including its
5397
+ // overview half (`revealed === null && i === 0`). Hashing only the active
5398
+ // half left tick 0 with `tabIndex: 0` after any selection, so the strip had
5399
+ // TWO tab stops (measured: [0, 5] after selecting station 5).
5400
+ + "\u0002" + (tickTab ? "1" : "0")
5401
+ + "\u0002" + (tickActive ? "1" : "0")
5402
+ // `data-k` reads the DERIVED kind, which is "tool" for a step that contains
5403
+ // one — hash the value actually used rather than re-deriving it here.
5404
+ + "\u0002" + k
5405
+ + "\u0002" + minimapTickLabel(s) + "\u0002" + fmtClock(s.time)
5406
+ + "\u0002" + String(stations.length);
5407
+ const tickHit = tickElCache.current.get(i);
5408
+ if (tickHit !== undefined && tickHit.sig === tickSig && tickHit.t === t) return tickHit.el;
5409
+ const tickEl = jsx("button", {
4825
5410
  type: "button",
4826
5411
  className: "dstv_miniTick",
4827
5412
  "data-tick-idx": String(i),
4828
5413
  "data-k": k,
4829
5414
  "data-done": done ? "true" : undefined,
4830
- "data-dim": reached ? (searching && !matched ? "true" : undefined) : "true",
4831
- "data-active": revealed !== null && i === R - 1 ? "true" : undefined,
5415
+ "data-dim": reached ? undefined : "true",
5416
+ "data-active": tickActive ? "true" : undefined,
4832
5417
  "data-live": s.kind === "step" && s.live === true ? "true" : undefined,
4833
5418
  "data-match": matched ? "true" : undefined,
4834
5419
  // Roving tabindex, same as the station list. This strip is a SECOND
@@ -4839,17 +5424,46 @@ window.__ModuleLoader__.load({
4839
5424
  // ...but exactly one tick must stay reachable, or the whole strip
4840
5425
  // disappears from the keyboard in the overview state. Same rule as
4841
5426
  // the station list: the active one, else the first.
4842
- tabIndex: (revealed !== null && i === R - 1) || (revealed === null && i === 0) ? 0 : -1,
5427
+ tabIndex: tickTab ? 0 : -1,
4843
5428
  // `s.label` is undefined for user stations, so the tooltip read
4844
5429
  // "undefined · 6:13:20 AM" and the button had no accessible name at
4845
5430
  // all. Fall back to the kind and always expose aria-label.
4846
5431
  title: `${minimapTickLabel(s)}${fmtClock(s.time) !== "" ? ` · ${fmtClock(s.time)}` : ""}`,
4847
5432
  "aria-label": `${t("detail.position")} ${String(i + 1)} / ${String(stations.length)} · ${minimapTickLabel(s)}${fmtClock(s.time) !== "" ? ` · ${fmtClock(s.time)}` : ""}`,
4848
- onClick: (ev) => { ev.stopPropagation(); seek(i); }
5433
+ onClick: (ev) => { ev.stopPropagation(); handlersRef.current.seek(i); }
4849
5434
  }, `mini${i}`);
5435
+ tickElCache.current.set(i, { sig: tickSig, t, el: tickEl });
5436
+ return tickEl;
4850
5437
  })
4851
5438
  }, "rootMini");
4852
5439
 
5440
+ // One signature per station, computed once per TREE rather than once per render.
5441
+ // The per-render version re-hashed every cell body on every keystroke and replay
5442
+ // tick: a real 1.11 MB window cost 105 ms per rebuild instead of 30 ms. `stations`
5443
+ // identity only changes when the fold produces a new tree, so keying on it is
5444
+ // exactly "recompute when the content could have changed".
5445
+ //
5446
+ // A ref rather than useMemo on purpose: this sits BELOW the `if (N === 0)` early
5447
+ // return, and a hook here would be skipped on the empty/loading render (§13.75).
5448
+ const sigPack = sigCacheRef.current;
5449
+ if (sigPack.arr !== stations) {
5450
+ sigPack.arr = stations;
5451
+ sigPack.sigs = stations.map(stationSig);
5452
+ // Drop what the new window no longer contains. A live station is replaced by its
5453
+ // durable twin (new id) on every fold, and paging in older history shifts every
5454
+ // index, so without this the element maps only ever grow — each entry pinning a
5455
+ // whole card subtree and its station closure (§13.75).
5456
+ if (cardElCache.current.size > stations.length || tickElCache.current.size > stations.length) {
5457
+ const live = new Set(stations.map((st) => st.id));
5458
+ for (const key of [...cardElCache.current.keys()]) {
5459
+ if (!live.has(key)) cardElCache.current.delete(key);
5460
+ }
5461
+ for (const key of [...tickElCache.current.keys()]) {
5462
+ if (!(key >= 0 && key < stations.length)) tickElCache.current.delete(key);
5463
+ }
5464
+ }
5465
+ }
5466
+ const sigOf = (i) => (i < 0 || i >= sigPack.sigs.length ? "" : sigPack.sigs[i]);
4853
5467
  const body = jsxs("div", {
4854
5468
  children: [
4855
5469
  jsx("div", {
@@ -4860,10 +5474,17 @@ window.__ModuleLoader__.load({
4860
5474
  role: "listbox",
4861
5475
  "aria-label": t("view.label"),
4862
5476
  "aria-orientation": "horizontal",
5477
+ // Dimming non-matches while searching is a CSS job, not a per-card one.
5478
+ // Setting it per station meant the FIRST keystroke invalidated all 900
5479
+ // cards (2.4 s at 900 stations); one attribute on the list lets the
5480
+ // stylesheet do it and leaves every card's element identity intact.
5481
+ "data-searching": searching ? "true" : undefined,
4863
5482
  children: [
4864
5483
  revealed !== null && playheadLeft !== null ? jsx("span", { className: "dstv_playhead", "aria-hidden": "true", style: { left: `${playheadLeft}px` }, children: jsx("i", {}) }, "ph") : null,
4865
5484
  stations.map((s, i) => {
4866
5485
  const reached = i < R;
5486
+ const isActive = revealed !== null && i === R - 1;
5487
+ const matched = searching && matchSet.has(i);
4867
5488
  // G4-T3: idle gap vs the previous station's end (falls back to its
4868
5489
  // start / time). Rendered as an inline band so a long pause between
4869
5490
  // two steps is visible without opening either one.
@@ -4906,14 +5527,27 @@ window.__ModuleLoader__.load({
4906
5527
  else if (s.kind === "unknown") dotCls += " unknown";
4907
5528
  else if (s.kind === "step" && s.cells.some((c) => c.kind === "tool")) dotCls += " tool";
4908
5529
  if (s.kind === "step" && s.live === true) dotCls += " live";
4909
- const matched = searching && matchSet.has(i);
4910
5530
  const clock = fmtClock(s.time);
4911
- const isActive = revealed !== null && i === R - 1;
4912
- return jsxs("div", {
5531
+ // Everything below is a pure function of (station, neighbour, position,
5532
+ // N, found-in-search). If none of those moved, hand React the element
5533
+ // it already rendered and it skips the whole subtree.
5534
+ const sig = [
5535
+ sigOf(i), sigOf(i - 1), String(i), String(N),
5536
+ reached ? "1" : "0", isActive ? "1" : "0",
5537
+ matched ? "1" : "0", clockAxis ? "1" : "0",
5538
+ // The overview state is its own dependency: station 0 is the roving
5539
+ // tab stop in the overview and is not once a selection exists, even
5540
+ // though neither `reached` nor `isActive` changes for it. Caught by
5541
+ // the roving-tab-stop assertion, not by reasoning (§13.72).
5542
+ revealed === null ? "1" : "0"
5543
+ ].join("\u0002");
5544
+ const hit = cardElCache.current.get(s.id);
5545
+ if (hit !== undefined && hit.sig === sig) return hit.el;
5546
+ const el = jsxs("div", {
4913
5547
  className: "dstv_station",
4914
5548
  "data-station-idx": String(i),
4915
5549
  "data-dim": reached ? undefined : "true",
4916
- "data-seek-dim": searching && !matched && reached ? "true" : undefined,
5550
+
4917
5551
  "data-match": matched ? "true" : undefined,
4918
5552
  "data-active": isActive ? "true" : undefined,
4919
5553
  role: "option",
@@ -4926,8 +5560,8 @@ window.__ModuleLoader__.load({
4926
5560
  "aria-selected": revealed === null ? "false" : (isActive ? "true" : "false"),
4927
5561
  "aria-label": stationAriaLabel(s, i + 1, N, t),
4928
5562
  tabIndex: isActive || (revealed === null && i === 0) ? 0 : -1,
4929
- onKeyDown: (ev) => stationOnKeyDown(ev, i),
4930
- onClick: () => seek(i),
5563
+ onKeyDown: (ev) => handlersRef.current.keyDown(ev, i),
5564
+ onClick: () => handlersRef.current.seek(i),
4931
5565
  children: [
4932
5566
  ...gapPrefix,
4933
5567
  jsxs("div", {
@@ -4957,6 +5591,8 @@ window.__ModuleLoader__.load({
4957
5591
  }, `card${s.id}`)
4958
5592
  ]
4959
5593
  }, s.id);
5594
+ cardElCache.current.set(s.id, { sig, el });
5595
+ return el;
4960
5596
  })
4961
5597
  ]
4962
5598
  })
@@ -5007,7 +5643,7 @@ window.__ModuleLoader__.load({
5007
5643
  if (s.kind === "orphan-tool") {
5008
5644
  const body = s.displayText !== "" ? s.displayText : t("orphan.noText");
5009
5645
  return jsxs("div", { className: "dstv_dBody", children: [
5010
- jsx("span", { className: "dstv_dLabel", children: `${t("node.orphanTool")} · ${s.name}` }, "oLbl"),
5646
+ jsx("span", { className: "dstv_dLabel", children: `${t(s.replayOf !== null && s.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")} · ${s.name}` }, "oLbl"),
5011
5647
  jsx("div", { className: "dstv_dSection", children: [
5012
5648
  jsx("span", { className: "dstv_chip info", children: t("orphan.badge") }, "oBadge"),
5013
5649
  jsx("span", { className: "dstv_chip", children: `callId ${s.callId}` }, "oCid")
@@ -5080,40 +5716,10 @@ window.__ModuleLoader__.load({
5080
5716
  ] }, `dr${cell.id}`) : null,
5081
5717
  cell.resultText === "" && !cell.isError && !cell.running ? jsx("span", { className: "dstv_dLabel sec", children: t("detail.noResult") }, "tNoRes") : null,
5082
5718
  cell.subCalls.length > 0 ? jsxs("details", { className: "dstv_det", open: cell.subCalls.some((sub) => sub.isError), children: [
5083
- 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"),
5719
+ jsx("summary", { children: [`${t("detail.subCalls")} (${cell.subCalls.length})${cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal) ? ` · ${t("detail.subCallsCut").replace("{shown}", String(cell.subCalls.length)).replace("{total}", String(cell.subCallsTotal))}` : ""}`, cell.subCalls.some((sub) => sub.isError) ? jsx("span", { className: "dstv_chip err", children: t("chip.error") }, "tSubErr") : null] }, "tSubSum"),
5084
5720
  jsx("div", {
5085
5721
  className: "inner",
5086
- children: cell.subCalls.map((sub, i) => {
5087
- const subPretty = prettyArgs(sub.argsRaw);
5088
- return jsxs("div", {
5089
- className: "dstv_subCard",
5090
- children: [
5091
- jsxs("span", {
5092
- className: "dstv_subHead",
5093
- children: [
5094
- 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"),
5095
- jsx("span", { className: "tname", children: `↳ ${sub.name}` }, "sName"),
5096
- jsx("span", { className: "dstv_chips", children: [
5097
- sub.running ? jsx("span", { className: "dstv_chip run", children: t("chip.running") }, "sRun") : null,
5098
- sub.isError ? jsx("span", { className: "dstv_chip err", children: sub.errorName != null ? String(sub.errorName) : t("chip.error") }, "sErr") : null,
5099
- sub.durationMs != null ? jsx("span", { className: "dstv_chip", children: fmtMs(sub.durationMs) }, "sDur") : null
5100
- ] }, "sChips")
5101
- ]
5102
- }, "sHead"),
5103
- sub.argsRaw !== "" ? jsxs("details", { className: "dstv_det", open: false, children: [
5104
- jsx("summary", { children: [t("detail.args"), jsx("span", { className: "sub", children: `${sub.argsRaw.length}${t("detail.chars")}` }, "sALen")] }, "sArgSum"),
5105
- jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", children: subPretty !== "" ? subPretty : t("detail.noArgs") }, "sArgCode") }, "sArgInner")
5106
- ] }, "sArgs") : null,
5107
- sub.resultText !== "" ? jsxs("details", { className: "dstv_det", open: sub.isError, children: [
5108
- jsx("summary", { children: [sub.isError ? `✗ ${t("detail.result")}` : `✓ ${t("detail.result")}`, jsx("span", { className: "sub", children: String(sub.resultText.length) }, "sRLen")] }, "sResSum"),
5109
- jsx("div", { className: "inner", children: jsxs("div", { children: [
5110
- jsx(CopyBtn, { text: sub.resultText, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "sResCopy"),
5111
- jsx("div", { className: "dstv_code", style: { marginTop: 4 }, children: sub.resultText }, "sResCode")
5112
- ] }) }, "sResInner")
5113
- ] }, "sRes") : null
5114
- ]
5115
- }, `ts${i}`);
5116
- })
5722
+ children: renderSubCalls(cell.subCalls, 0)
5117
5723
  }, "tSubInner")
5118
5724
  ] }, `ds${cell.id}`) : null
5119
5725
  ] }, `dt${cell.id}`);
@@ -5213,6 +5819,12 @@ window.__ModuleLoader__.load({
5213
5819
  // fields can be drifted. Normalise ONCE here — every reader below
5214
5820
  // (`tools.map`, the JSON previews, the React keys) then sees a safe shape.
5215
5821
  const tools = safeToolList(req.prompt?.tools);
5822
+ // The contract says `prompt.system` is EMPTY when the system node sits outside the
5823
+ // loaded window; the snapshot still carries it (`systemFrom`, filled by the fold).
5824
+ // Showing "0 chars" there was a silent lie about what the model saw.
5825
+ const savedPrompt = req.systemFrom !== null && req.systemFrom !== void 0 ? req.systemFrom : null;
5826
+ const systemText = (req.prompt?.system ?? "") !== "" ? req.prompt.system
5827
+ : (savedPrompt !== null ? String(savedPrompt.text ?? "") : "");
5216
5828
  const diff = req.promptDiff ?? null;
5217
5829
  const evidenceChips = evidenceOf(req, activeMessages, hasMore);
5218
5830
 
@@ -5223,7 +5835,7 @@ window.__ModuleLoader__.load({
5223
5835
  temperature: cfg.temperature,
5224
5836
  reasoningEffort: cfg.reasoningEffort,
5225
5837
  maxTokens: cfg.maxTokens,
5226
- system: req.prompt?.system ?? "",
5838
+ system: systemText,
5227
5839
  tools: tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })),
5228
5840
  messages: messages.map((m) => m.role === "note"
5229
5841
  ? { role: "user", content: [{ type: "text", text: m.text }] }
@@ -5237,7 +5849,7 @@ window.__ModuleLoader__.load({
5237
5849
  // else; the request tab was the only place that called JSON directly.
5238
5850
  const payloadJson = safeJsonPreview(payload, Number.MAX_SAFE_INTEGER, 2);
5239
5851
  const sysToolsJson = safeJsonPreview(tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })), Number.MAX_SAFE_INTEGER, 2);
5240
- 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);
5852
+ const sysJson = safeJsonPreview({ system: systemText, tools: tools.map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.parameters })) }, Number.MAX_SAFE_INTEGER, 2);
5241
5853
 
5242
5854
  return jsxs("div", { className: "dstv_dBody", children: [
5243
5855
  // config + lifecycle chips
@@ -5290,13 +5902,14 @@ window.__ModuleLoader__.load({
5290
5902
  req.prompt !== null ? jsxs("div", { className: "dstv_dSection", children: [
5291
5903
  jsxs("div", { className: "dstv_dSecHead", children: [
5292
5904
  jsx("span", { children: `🧠 ${t("detail.systemPrompt")}` }, "spHead"),
5293
- jsx("span", { className: "sub", children: `${fmtInt(req.prompt.systemChars)} ${t("detail.chars")}` }, "spLen"),
5905
+ jsx("span", { className: "sub", children: `${fmtInt(systemText.length)} ${t("detail.chars")}` }, "spLen"),
5906
+ savedPrompt !== null ? jsx("span", { className: "sub", children: t("detail.systemOutside").replace("{seq}", String(savedPrompt.seq)) }, "spOut") : null,
5294
5907
  jsx("span", { className: "grow" }, "spGrow"),
5295
5908
  jsx(CopyBtn, { text: sysJson, label: t("detail.copy"), okLabel: t("detail.copied"), failLabel: t("anchor.copyFailed") }, "spCopy")
5296
5909
  ] }, "spSecHead"),
5297
5910
  jsxs("details", { className: "dstv_det", open: false, children: [
5298
5911
  jsx("summary", { children: [t("detail.systemPrompt")] }, "spSum"),
5299
- jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", style: { maxHeight: 220 }, children: req.prompt.system || "…" }, "spCode") }, "spInner")
5912
+ jsx("div", { className: "inner", children: jsx("div", { className: "dstv_code", style: { maxHeight: 220 }, children: systemText !== "" ? systemText : t("detail.systemNone") }, "spCode") }, "spInner")
5300
5913
  ] }, "spDet")
5301
5914
  ] }, "spSec") : null,
5302
5915
  // tool catalog
@@ -5435,7 +6048,18 @@ window.__ModuleLoader__.load({
5435
6048
  okLabel: t("anchor.copied"),
5436
6049
  failLabel: t("anchor.copyFailed")
5437
6050
  }, "dExportStep"),
5438
- jsx("button", { type: "button", className: "dstv_btn dstv_panelToggle", title: panelFull ? t("action.collapsePanel") : t("action.expandPanel"), onClick: () => setPanelFull((v) => !v), children: panelFull ? "⤡" : "⤢" }, "dToggle")
6051
+ jsx("button", {
6052
+ type: "button",
6053
+ className: "dstv_btn dstv_panelToggle",
6054
+ title: panelFull ? t("action.collapsePanel") : t("action.expandPanel"),
6055
+ // A glyph is not a name. Chromium's AX tree announced this control as
6056
+ // "button, ⤢" — the arrow is a picture, and a screen reader user had
6057
+ // to guess what it does. The title alone is a tooltip, not a name.
6058
+ "aria-label": panelFull ? t("action.collapsePanel") : t("action.expandPanel"),
6059
+ "aria-expanded": panelFull ? "true" : "false",
6060
+ onClick: () => setPanelFull((v) => !v),
6061
+ children: panelFull ? "⤡" : "⤢"
6062
+ }, "dToggle")
5439
6063
  ]
5440
6064
  }, "dHead"),
5441
6065
  // The key must include WHAT is being rendered, not just where. An error
@@ -5463,7 +6087,7 @@ window.__ModuleLoader__.load({
5463
6087
  jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: String(stats.turns) }, "kvNum"), jsx("span", { children: t("node.turn") }, "kvLbl")] }, "kTurns"),
5464
6088
  jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: String(stats.steps) }, "kvNum"), jsx("span", { children: t("node.step") }, "kvLbl")] }, "kSteps"),
5465
6089
  jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: String(stats.tools) }, "kvNum"), jsx("span", { children: t("node.tool") }, "kvLbl")] }, "kTools"),
5466
- 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"),
6090
+ jsxs("span", { className: `dstv_kpi${stats.errors > 0 ? " err" : ""}`, children: [jsx("b", { children: String(stats.errors) }, "kvNum"), jsx("span", { children: t("kpi.errorSteps") }, "kvLbl")] }, "kErr"),
5467
6091
  jsxs("span", { className: "dstv_kpi", children: [jsx("b", { children: fmtDur(stats.toolMs) }, "kvNum"), jsx("span", { children: t("kpi.toolTime") }, "kvLbl")] }, "kDur"),
5468
6092
  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,
5469
6093
  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,