dsh-trajectory-traceview-plus 0.11.5 → 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/src/30-helpers.js CHANGED
@@ -249,6 +249,17 @@
249
249
  return max;
250
250
  }
251
251
  /** Fresh mutable per-step accumulator used while folding assistant nodes. */
252
+ /**
253
+ * Ordering key for a seq that may be missing or malformed.
254
+ *
255
+ * `null < 20` is TRUE (null coerces to 0), so an unparsed seq did not merely sort
256
+ * badly — it pulled its whole turn to the FRONT of the timeline. Measured: a legal
257
+ * fractional seq (22 - 0.9, the host's interrupted-reply marker) turned the order
258
+ * into [prefix(t2), user20, error22, user10, step(t1)] instead of
259
+ * [user10, step(t1), user20, prefix(t2), error22]. Everything that sorts or
260
+ * compares seqs goes through this.
261
+ */
262
+ const orderKey = (v) => (typeof v === "number" && Number.isFinite(v) ? v : Number.MAX_SAFE_INTEGER);
252
263
  function newStepState(seq) {
253
264
  return {
254
265
  seq, time: null, cells: [], live: false, request: null,
@@ -271,14 +282,17 @@
271
282
  * though the cap was 2,000. The cap is per tool cell, not per root.
272
283
  */
273
284
  function mapSubCalls(list, tr) {
274
- if (!Array.isArray(list)) return [];
285
+ if (!Array.isArray(list)) return { list: [], total: 0, truncated: false };
275
286
  const budget = { used: 0 };
276
287
  const out = [];
277
288
  for (const sub of list) {
278
289
  if (budget.used >= SUB_CALL_MAX_TOTAL) break;
279
290
  out.push(subDetailOf(sub, 0, budget, tr));
280
291
  }
281
- return out;
292
+ // The budget silently dropped the tail: a parent with 20,000 children rendered
293
+ // 1,999 and NOTHING anywhere said so — not the panel, not the export. Reporting
294
+ // it is the difference between "this is all there was" and "this is all that fit".
295
+ return { list: out, total: list.length, truncated: budget.used >= SUB_CALL_MAX_TOTAL };
282
296
  }
283
297
  /** Map one sub-call entry (settled ToolResultNode or running shape) to full detail. */
284
298
  function subDetailOf(sub, depth, budget, tr) {
@@ -696,7 +710,16 @@
696
710
  // step. Prefer a step (the thing anchors are normally copied from); otherwise
697
711
  // take the first match as before.
698
712
  const hits = stations.filter((st) => st.anchorSeq === parsed.seq);
699
- if (hits.length === 0) return { ok: false, reason: "not-loaded", seq: parsed.seq };
713
+ if (hits.length === 0) {
714
+ // An anchor copied from a tool RESULT (`e19`) outlives the result becoming a
715
+ // station: load one more page and seq 19 is now a cell inside the step at 15.
716
+ // Reporting "not loaded" for an output that is visibly on screen is wrong, so
717
+ // fall back to the step that absorbed that result.
718
+ const absorbed = stations.find((st) => st.kind === "step"
719
+ && (st.cells ?? []).some((c) => c.kind === "tool" && c.resultSeq === parsed.seq));
720
+ if (absorbed !== void 0) return { ok: true, station: absorbed, absorbedFrom: parsed.seq };
721
+ return { ok: false, reason: "not-loaded", seq: parsed.seq };
722
+ }
700
723
  const preferred = hits.find((st) => st.kind === "step") ?? hits[0];
701
724
  return { ok: true, station: preferred };
702
725
  }
@@ -975,16 +998,43 @@
975
998
  * but total for every input.
976
999
  */
977
1000
  function stepOf(v) {
978
- const n = typeof v === "symbol" ? NaN : Number(v);
1001
+ // `Number(obj)` throws when the object has no primitive conversion at all — an
1002
+ // ordinary hostile field (`{toString: null}`) took the WHOLE view down, because
1003
+ // this runs while seating every assistant node and nothing caught it. One bad
1004
+ // number must degrade one station, never the panel (§13.84).
1005
+ let n = NaN;
1006
+ try { n = typeof v === "symbol" ? NaN : Number(v); } catch { n = NaN; }
979
1007
  return Math.max(1, Number.isFinite(n) ? Math.trunc(n) : 1);
980
1008
  }
981
1009
  function seqOf(v) {
982
1010
  if (Number.isSafeInteger(v)) return v;
983
1011
  // BigInt is comparable and printable, so keep it when it still fits a double.
984
1012
  if (typeof v === "bigint") { const n = Number(v); return Number.isSafeInteger(n) ? n : null; }
1013
+ // A FRACTIONAL seq is legal: the host marks an interrupted reply at `22 - 0.9`
1014
+ // so it sorts just before the turn error at 22. Dropping it to null destroyed the
1015
+ // only ordering key the node had — and because `null < 20` is true, the whole turn
1016
+ // jumped to the front of the timeline (measured order: prefix(t2), user20,
1017
+ // error22, user10, step(t1)). Anchors are unaffected: every anchor site checks
1018
+ // `Number.isSafeInteger` itself, so a fractional seq still gets no `e` anchor.
1019
+ if (typeof v === "number" && Number.isFinite(v)) return v;
985
1020
  return null;
986
1021
  }
987
1022
  function deriveTraceTree(snap, t) {
1023
+ // The official contract is explicit that `prompt.system` is empty when the
1024
+ // `system/message` node "lies outside the loaded history window" — the text itself is
1025
+ // still available on the snapshot as `systemPrompts`. Without this, a window that starts
1026
+ // mid-conversation claimed the request carried NO system prompt (0 chars, "…" on screen),
1027
+ // which is a silent lie about what the model actually saw.
1028
+ const systemPrompts = Array.isArray(snap?.systemPrompts)
1029
+ ? snap.systemPrompts.filter((s) => s != null && typeof s === "object" && typeof s.text === "string" && s.text !== "")
1030
+ .slice().sort((a, b) => (Number(a.seq) || 0) - (Number(b.seq) || 0))
1031
+ : [];
1032
+ const systemPromptBefore = (seq) => {
1033
+ if (!Number.isFinite(seq)) return null;
1034
+ let pick = null;
1035
+ for (const s of systemPrompts) { if (Number(s.seq) <= seq) pick = s; else break; }
1036
+ return pick;
1037
+ };
988
1038
  const rawNodes = safeList(snap?.eventNodes);
989
1039
  // Only pay for the copy when a node actually needs repairing: a well-formed
990
1040
  // snapshot (the normal case) proceeds with the objects the host handed us.
@@ -1075,16 +1125,54 @@
1075
1125
  // React warned about duplicate keys (measured: `["tdup","tdup"]`). Suffix the
1076
1126
  // ordinal unconditionally; it is what keeps same-id siblings apart.
1077
1127
  const cellId = (prefix, callId, ordinal) => `${prefix}${typeof callId === "string" ? callId : `?${String(ordinal)}`}#${String(ordinal)}`;
1078
- /** Next unclaimed result for this call id, or undefined when none is left. */
1079
- const takeResult = (callId) => {
1128
+ /**
1129
+ * Next unclaimed result for this call, or undefined when none is left.
1130
+ *
1131
+ * `turn`/`afterSeq` are not decoration: when the log omits `callId`, EVERY id-less
1132
+ * result lands in the same `resultsById` bucket under `undefined`, and "first
1133
+ * unconsumed" handed turn 2's output to turn 1's call — silently, with no
1134
+ * diagnostic (measured: CALL_A displayed ONLY-RESULT-B while CALL_B, the real
1135
+ * caller, showed nothing). Prefer a result from the SAME turn that comes AFTER
1136
+ * the call; fall back to the same turn, then to the legacy first-unconsumed so a
1137
+ * normal log behaves exactly as before.
1138
+ */
1139
+ // Which result seq was already consumed for each callId. Compaction replays tool
1140
+ // results (`tool/result` repeated under the SAME callId at a much later seq — measured
1141
+ // 13 such groups in one 17k-event session). Without this the duplicate looked like
1142
+ // "the call is outside the window", which is false: the call is right there and was
1143
+ // already answered.
1144
+ const consumedByCallId = new Map();
1145
+ const reclaimResult = (key, seq) => {
1146
+ if (key === void 0 || key === null) return;
1147
+ const list = consumedByCallId.get(key);
1148
+ if (list === void 0) consumedByCallId.set(key, [seq]);
1149
+ else list.push(seq);
1150
+ };
1151
+ const takeResult = (callId, turn, afterSeq) => {
1080
1152
  const list = resultsById.get(callId);
1081
1153
  if (list === void 0) return void 0;
1154
+ // Without an id, the bucket holds every id-less result in the window. A result
1155
+ // from ANOTHER turn is not this call's output — taking it is the silent
1156
+ // misattribution this rewrite exists to stop, so an id-less call refuses it
1157
+ // and shows "no result" instead of someone else's text.
1158
+ const idless = callId === void 0 || callId === null;
1159
+ let sameTurn = null;
1160
+ let legacy = null;
1082
1161
  for (const r of list) {
1083
1162
  if (consumedResults.has(r)) continue;
1084
- consumedResults.add(r);
1085
- return r;
1163
+ const sameTurnMatch = r.turn === turn && turn !== void 0;
1164
+ if (idless && !sameTurnMatch) continue;
1165
+ if (sameTurnMatch && Number.isFinite(afterSeq) && Number.isFinite(r.seq) && r.seq > afterSeq) {
1166
+ consumedResults.add(r);
1167
+ reclaimResult(callId, r.seq);
1168
+ return r;
1169
+ }
1170
+ if (sameTurnMatch && sameTurn === null) sameTurn = r;
1171
+ if (legacy === null) legacy = r;
1086
1172
  }
1087
- return void 0;
1173
+ const pick = sameTurn ?? legacy;
1174
+ if (pick !== null) { consumedResults.add(pick); reclaimResult(callId, pick.seq); }
1175
+ return pick ?? void 0;
1088
1176
  };
1089
1177
 
1090
1178
  // Requests keyed by `${turn}:${step}`, with prompt inheritance across
@@ -1172,12 +1260,13 @@
1172
1260
  const ensureTurn = (turn, seq) => {
1173
1261
  let e = turnMap.get(turn);
1174
1262
  if (e === void 0) {
1175
- e = { turn, user: [], stations: [], seq: seq ?? Number.MAX_SAFE_INTEGER };
1263
+ e = { turn, user: [], stations: [], seq: orderKey(seq) };
1176
1264
  turnMap.set(turn, e);
1177
1265
  turns.push(e);
1178
1266
  lastTurnEntry = e;
1179
1267
  }
1180
- if (e.seq > seq) e.seq = seq;
1268
+ const ord = orderKey(seq);
1269
+ if (e.seq > ord) e.seq = ord;
1181
1270
  return e;
1182
1271
  };
1183
1272
  const flushUser = (turn, seq) => {
@@ -1281,7 +1370,7 @@
1281
1370
  } else if (b.kind === "tool-call") {
1282
1371
  // every durable block is a real call, even with a repeated id
1283
1372
  claimCall(turn, b.callId);
1284
- const res = takeResult(b.callId);
1373
+ const res = takeResult(b.callId, turn, n.seq);
1285
1374
  const isRunning = res === undefined && runningById.has(b.callId);
1286
1375
  if (isRunning) st.live = true;
1287
1376
  const schema = schemasById.get(b.callId);
@@ -1297,6 +1386,7 @@
1297
1386
  st.toolMs += dur ?? 0;
1298
1387
  st.toolCount += 1;
1299
1388
  if (res?.isError === true) st.hasError = true;
1389
+ const subPack1 = mapSubCalls(res?.subCalls, t);
1300
1390
  st.cells.push({
1301
1391
  id: cellId("t", b.callId, st.cells.length),
1302
1392
  kind: "tool",
@@ -1304,11 +1394,18 @@
1304
1394
  name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
1305
1395
  args: argsText(b.argsRaw),
1306
1396
  resultText: res !== undefined ? blocksText(res.content, t) : "",
1397
+ // The result's own seq. A copied `tvp1:e19` anchor used to die the moment a page
1398
+ // load brought in the call header: seq 19 stopped being a station of its own and became
1399
+ // a cell of the step at 15, so the anchor said "not loaded" while the output was on
1400
+ // screen. `resultSeq` lets the resolver walk that back to the owning step.
1401
+ resultSeq: res !== undefined && Number.isSafeInteger(res.seq) ? res.seq : null,
1307
1402
  isError: res?.isError === true,
1308
1403
  errorName: res?.error?.name,
1309
1404
  durationMs: dur,
1310
1405
  running: isRunning,
1311
- subCalls: mapSubCalls(res?.subCalls, t),
1406
+ subCalls: subPack1.list,
1407
+ subCallsTotal: subPack1.total,
1408
+ subCallsTruncated: subPack1.truncated,
1312
1409
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1313
1410
  });
1314
1411
  }
@@ -1383,13 +1480,16 @@
1383
1480
  st.live = true;
1384
1481
  st.toolCount += 1;
1385
1482
  const schema = schemasById.get(c.callId);
1483
+ const subPack2 = mapSubCalls(c.subCalls, t);
1386
1484
  st.cells.push({
1387
1485
  id: cellId("t", c.callId, st.cells.length), kind: "tool", callId: c.callId,
1388
1486
  name: typeof c.name === "string" && c.name !== "" ? c.name : t("node.tool"),
1389
1487
  args: argsText(c.argsRaw),
1390
1488
  resultText: "", isError: false, errorName: void 0, durationMs: null,
1391
1489
  running: true,
1392
- subCalls: mapSubCalls(c.subCalls, t),
1490
+ subCalls: subPack2.list,
1491
+ subCallsTotal: subPack2.total,
1492
+ subCallsTruncated: subPack2.truncated,
1393
1493
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1394
1494
  });
1395
1495
  }
@@ -1469,19 +1569,27 @@
1469
1569
  } else if (b.kind === "tool-call") {
1470
1570
  if (claimedCall(turn, b.callId)) continue;
1471
1571
  claimCall(turn, b.callId);
1472
- const res = takeResult(b.callId);
1572
+ const res = takeResult(b.callId, turn, seq);
1473
1573
  st.toolCount += 1;
1474
1574
  if (res?.isError === true) st.hasError = true;
1475
1575
  const schema = schemasById.get(b.callId);
1576
+ const subPack3 = mapSubCalls(res?.subCalls, t);
1476
1577
  st.cells.push({
1477
1578
  id: cellId("t", b.callId, st.cells.length), kind: "tool", callId: b.callId,
1478
1579
  name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
1479
1580
  args: argsText(b.argsRaw),
1480
1581
  resultText: res !== undefined ? blocksText(res.content, t) : "",
1582
+ // The result's own seq. A copied `tvp1:e19` anchor used to die the moment a page
1583
+ // load brought in the call header: seq 19 stopped being a station of its own and became
1584
+ // a cell of the step at 15, so the anchor said "not loaded" while the output was on
1585
+ // screen. `resultSeq` lets the resolver walk that back to the owning step.
1586
+ resultSeq: res !== undefined && Number.isSafeInteger(res.seq) ? res.seq : null,
1481
1587
  isError: res?.isError === true,
1482
1588
  errorName: res?.error?.name,
1483
1589
  durationMs: null, running: res === undefined,
1484
- subCalls: mapSubCalls(res?.subCalls, t),
1590
+ subCalls: subPack3.list,
1591
+ subCallsTotal: subPack3.total,
1592
+ subCallsTruncated: subPack3.truncated,
1485
1593
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1486
1594
  });
1487
1595
  }
@@ -1495,7 +1603,7 @@
1495
1603
  // Binary search: `turnsBySeq` is already sorted. The previous linear scan ran
1496
1604
  // once per compaction/special event, so a log with many of both cost
1497
1605
  // O(events x turns) — measured 105 ms at 1000 turns, and it grows from there.
1498
- const turnForSeq = (s) => {
1606
+ const turnForSeq = (s, turnHint) => {
1499
1607
  let lo = 0;
1500
1608
  let hi = turnsBySeq.length - 1;
1501
1609
  let best = null;
@@ -1504,7 +1612,21 @@
1504
1612
  if (turnsBySeq[mid].seq <= s) { best = turnsBySeq[mid]; lo = mid + 1; }
1505
1613
  else hi = mid - 1;
1506
1614
  }
1507
- return best ?? lastTurnEntry ?? ensureTurn(0, s);
1615
+ if (best !== null) return best;
1616
+ // The event sits BEFORE every turn boundary in this window. That is the normal
1617
+ // shape after paging: a page can start on a tool RESULT whose call sits above
1618
+ // it, and the result's own turn then has no boundary at or before its seq.
1619
+ //
1620
+ // The fallback used to be `lastTurnEntry` — the turn created LAST — so the
1621
+ // orphan was filed under the newest turn and `ensureTurn` lowered that turn's
1622
+ // seq to the orphan's. Sorting by seq then put the NEWEST turn first and split
1623
+ // the timeline: turn 68 → 65 → 66 → 67, with ~1h52m of apparent rewind in the
1624
+ // gap bars, and the export filed the result under the wrong turn (§13.83).
1625
+ //
1626
+ // Prefer the event's OWN turn when the log states one (the orphan's node
1627
+ // carries `turn`), else the earliest turn — never the last.
1628
+ const hinted = turnMap.get(typeof turnHint === "number" ? turnHint : NaN);
1629
+ return hinted ?? turnsBySeq[0] ?? ensureTurn(0, s);
1508
1630
  };
1509
1631
  const consumedCompactionReqs = new Set();
1510
1632
  // Index the exact-replacementSeq match instead of scanning every request per
@@ -1521,7 +1643,7 @@
1521
1643
  }
1522
1644
  for (const n of nodes) {
1523
1645
  if (n.kind === "compaction") {
1524
- const e = turnForSeq(n.seq);
1646
+ const e = turnForSeq(n.seq, n.turn);
1525
1647
  // Pair with the compaction provider request: exact replacementSeq
1526
1648
  // match first, else the nearest unconsumed compaction request that
1527
1649
  // completed within a minute before this marker landed.
@@ -1536,6 +1658,13 @@
1536
1658
  let best = null;
1537
1659
  for (const r of compactionReqs) {
1538
1660
  if (consumedCompactionReqs.has(r)) continue;
1661
+ // A request that NAMES a different replacementSeq belongs to that
1662
+ // marker. Time-proximity used to override the declaration, so a
1663
+ // marker at seq 20 displayed the output of the request for seq 10 —
1664
+ // a marker outside the window — and `unplacedRequests` stayed 0, so
1665
+ // nothing said the text was someone else's. Leaving it unconsumed
1666
+ // makes the view report it instead of borrowing it.
1667
+ if (Number.isSafeInteger(r.replacementSeq) && r.replacementSeq !== n.seq) continue;
1539
1668
  const doneAt = Number.isFinite(r.completedAt) ? r.completedAt : r.startedAt;
1540
1669
  if (!Number.isFinite(doneAt)) continue;
1541
1670
  const gap = n.time - doneAt;
@@ -1586,7 +1715,7 @@
1586
1715
  const e = ensureTurn(typeof n.turn === "number" ? n.turn : 0, n.seq);
1587
1716
  e.stations.push({ id: `x${n.seq}`, kind: "maxTokens", time: n.time, seq: n.seq, label: t("node.maxTokens") });
1588
1717
  } else if (n.kind === "command") {
1589
- const e = turnForSeq(n.seq);
1718
+ const e = turnForSeq(n.seq, n.turn);
1590
1719
  e.stations.push({
1591
1720
  id: `c${n.seq}`, kind: "command", time: n.time, seq: n.seq,
1592
1721
  name: asText(n.name) !== "" ? asText(n.name) : `/${asText(n.commandId) || "?"}`, args: asText(n.args),
@@ -1597,7 +1726,7 @@
1597
1726
  // The contract's own fallback surface. Rendering nothing would hide a
1598
1727
  // real event that exists in the session log, and the review tool's whole
1599
1728
  // promise is that what the log recorded is what the reader sees.
1600
- const e = turnForSeq(n.seq);
1729
+ const e = turnForSeq(n.seq, n.turn);
1601
1730
  e.stations.push({
1602
1731
  id: `k${n.seq}`, kind: "unknown", time: n.time, seq: n.seq,
1603
1732
  eventType: typeof n.type === "string" ? n.type : "",
@@ -1639,9 +1768,10 @@
1639
1768
  return `ot${base}${seen === 0 ? "" : `_${String(seen)}`}`;
1640
1769
  };
1641
1770
  for (const n of orphans) {
1642
- const e = turnForSeq(n.seq);
1771
+ const e = turnForSeq(n.seq, n.turn);
1643
1772
  const text = blocksText(n.content, t);
1644
- const subCalls = mapSubCalls(n.subCalls, t);
1773
+ const subCallPack = mapSubCalls(n.subCalls, t);
1774
+ const subCalls = subCallPack.list;
1645
1775
  // Anchor issuance is centralized in the "special stations" branch below
1646
1776
  // (it re-checks `seq` for integer-ness and stamps anchorKey/synthetic).
1647
1777
  e.stations.push({
@@ -1668,6 +1798,14 @@
1668
1798
  displayText: text !== "" ? text : (n.error?.code ?? n.error?.name ?? ""),
1669
1799
  isError: n.isError === true,
1670
1800
  subCalls,
1801
+ subCallsTotal: subCallPack.total,
1802
+ subCallsTruncated: subCallPack.truncated,
1803
+ // Set when this same callId ALREADY produced a result earlier in the window —
1804
+ // i.e. this is a compaction replay, not a missing call.
1805
+ replayOf: (() => {
1806
+ const used = consumedByCallId.get(n.callId);
1807
+ return used !== void 0 && used.length > 0 ? used[0] : null;
1808
+ })(),
1671
1809
  hasError: n.isError === true
1672
1810
  });
1673
1811
  }
@@ -1677,9 +1815,9 @@
1677
1815
  // Sort turns by their earliest known seq first (turn 0 "system events" may
1678
1816
  // be created late by a stray compaction/command and would otherwise land last).
1679
1817
  for (const e of turns) {
1680
- let mseq = e.seq;
1681
- for (const st of e.stations) if (st.seq < mseq) mseq = st.seq;
1682
- for (const st of e.steps?.values() ?? []) if (st.seq < mseq) mseq = st.seq;
1818
+ let mseq = orderKey(e.seq);
1819
+ for (const st of e.stations) mseq = Math.min(mseq, orderKey(st.seq));
1820
+ for (const st of e.steps?.values() ?? []) mseq = Math.min(mseq, orderKey(st.seq));
1683
1821
  e.minSeq = mseq;
1684
1822
  }
1685
1823
  turns.sort((a, b) => a.minSeq - b.minSeq);
@@ -1693,7 +1831,7 @@
1693
1831
  const turnNodes = turns.map((e) => {
1694
1832
  const pieceList = [];
1695
1833
  for (const s of e.stations) {
1696
- pieceList.push({ at: s.seq, kind: s.kind, data: s });
1834
+ pieceList.push({ at: orderKey(s.seq), kind: s.kind, data: s });
1697
1835
  if (s.kind === "orphan-tool") {
1698
1836
  stats.tools += 1;
1699
1837
  if (s.isError === true) stats.errors += 1;
@@ -1702,7 +1840,7 @@
1702
1840
  const stepNums = e.steps === void 0 ? [] : [...e.steps.keys()].sort((a, b) => a - b);
1703
1841
  for (const s of stepNums) {
1704
1842
  const st = e.steps.get(s);
1705
- pieceList.push({ at: st.seq, kind: "step", data: st, stepNum: s });
1843
+ pieceList.push({ at: orderKey(st.seq), kind: "step", data: st, stepNum: s });
1706
1844
  }
1707
1845
  pieceList.sort((a, b) => a.at - b.at);
1708
1846
 
@@ -1775,6 +1913,15 @@
1775
1913
  tools: Array.isArray(found.prompt.tools) ? found.prompt.tools : [],
1776
1914
  systemChars: typeof found.prompt.system === "string" ? found.prompt.system.length : 0
1777
1915
  } : null,
1916
+ // Present only when the request header's own prompt text is empty AND an older
1917
+ // system event exists: the reader then sees the real text, labelled as coming from
1918
+ // outside the window, instead of "0 chars".
1919
+ systemFrom: (() => {
1920
+ const own = found.prompt != null && typeof found.prompt.system === "string" ? found.prompt.system : "";
1921
+ if (own !== "") return null;
1922
+ const older = systemPromptBefore(Number(r.startSeq));
1923
+ return older !== null ? { seq: Number(older.seq), text: older.text, update: older.update === true } : null;
1924
+ })(),
1778
1925
  promptChangeKind: r.promptChange?.kind ?? null,
1779
1926
  promptDiff: promptDiffOf(r.promptChange, found.prompt),
1780
1927
  startSeq: r.startSeq ?? null
@@ -2038,7 +2185,8 @@
2038
2185
  : station.kind === "user" ? t("node.user")
2039
2186
  : station.kind === "error" ? t("node.error")
2040
2187
  : station.kind === "compaction" ? t("node.compaction")
2041
- : station.kind === "orphan-tool" ? t("node.orphanTool")
2188
+ // Same distinction as the card: a compaction replay is not a missing call.
2189
+ : station.kind === "orphan-tool" ? t(station.replayOf !== null && station.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")
2042
2190
  : station.kind === "unknown" ? t("node.unknown")
2043
2191
  : String(station.kind);
2044
2192
  const parts = [`${position} / ${total}`, kind];
@@ -2200,6 +2348,16 @@
2200
2348
  // again here duplicated every sub-call result in the export.
2201
2349
  pushSubLines(L, sub, 1, t);
2202
2350
  }
2351
+ // Say it when the list was cut. A file that silently stops at 1,999 of
2352
+ // 20,000 reads as "this was everything", which is the one outcome this
2353
+ // view promises never to produce.
2354
+ if (cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal)) {
2355
+ const shown = (cell.subCalls ?? []).length;
2356
+ L.push("");
2357
+ L.push(`> ${typeof t === "function"
2358
+ ? t("detail.subCallsCut").replace("{shown}", fmtInt(shown)).replace("{total}", fmtInt(cell.subCallsTotal))
2359
+ : `showing the first ${String(shown)} of ${String(cell.subCallsTotal)}`}`);
2360
+ }
2203
2361
  L.push("");
2204
2362
  }
2205
2363
  }
@@ -2279,7 +2437,27 @@
2279
2437
  // "[object Object]".
2280
2438
  return asText(content)
2281
2439
  .replace(/`{3,}/g, (run) => "\\`".repeat(run.length))
2282
- .replace(/<(\/?)(details)\b/gi, "&lt;$1$2");
2440
+ // GFM fences with TILDES too, and only backticks were escaped: prose ending in an
2441
+ // unclosed "~~~" turned every following station into code (verified with Pandoc
2442
+ // by the boundary review). Same treatment: leading tildes of a run this long
2443
+ // get escaped, so the run is no longer a fence opener.
2444
+ .replace(/(^|\n)(~{3,})/g, (m, lead, run) => lead + "\\~".repeat(run.length))
2445
+ .replace(/<(\/?)(details)\b/gi, "&lt;$1$2")
2446
+ // A content line that starts with `#` becomes a real heading in the export and
2447
+ // silently re-sections the document (measured: a compaction summary containing
2448
+ // "### 伪造标题" produced a section the panel never showed). Escaping turns it
2449
+ // back into text; a Markdown renderer still displays the bare `#`.
2450
+ .replace(/^(\s*)(#{1,6})\s/gm, "$1\\$2 ");
2451
+ }
2452
+ /**
2453
+ * Free text that sits INSIDE a generated line (a heading, a label).
2454
+ *
2455
+ * `proseSafe` keeps newlines, which is right for a paragraph and wrong for a heading:
2456
+ * a tool name or a slash-command's arguments containing "\n### …" forges a section in
2457
+ * the exported Markdown. Flatten first, then apply the same escaping.
2458
+ */
2459
+ function inlineSafe(content) {
2460
+ return proseSafe(asText(content).replace(/\s+/g, " ").trim());
2283
2461
  }
2284
2462
  function fencedBlock(content, lang) {
2285
2463
  const text = String(content ?? "");
@@ -2408,6 +2586,27 @@
2408
2586
  return out;
2409
2587
  }
2410
2588
  /** Block-level split. Returns descriptors; see mdInline for the inline level. */
2589
+ /**
2590
+ * Is this line a Markdown table separator (`|---|:--:|`)?
2591
+ *
2592
+ * Equivalent to `/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/`, but linear. The regex was
2593
+ * quadratic on failure: two overlapping classes around the mandatory `-` let it
2594
+ * re-split a long dash run for every possible position.
2595
+ */
2596
+ const WHITESPACE_CHAR = /\s/;
2597
+ function isTableSeparator(line) {
2598
+ if (typeof line !== "string") return false;
2599
+ let dashes = 0;
2600
+ for (let i = 0; i < line.length; i += 1) {
2601
+ const ch = line[i];
2602
+ if (ch === "-") { dashes += 1; continue; }
2603
+ // `\s` in the original class, plus the pipe. Testing one character at a time
2604
+ // keeps the whole thing linear and preserves CRLF and Unicode-space behaviour.
2605
+ if (ch === "|" || ch === ":" || WHITESPACE_CHAR.test(ch)) continue;
2606
+ return false;
2607
+ }
2608
+ return dashes > 0;
2609
+ }
2411
2610
  function mdBlocks(src) {
2412
2611
  const lines = String(src ?? "").replace(/\r\n?/g, "\n").split("\n");
2413
2612
  const blocks = [];
@@ -2441,7 +2640,12 @@
2441
2640
  continue;
2442
2641
  }
2443
2642
  // Table: a header row followed by a |---|---| separator.
2444
- if (line.includes("|") && i + 1 < lines.length && /^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(lines[i + 1])) {
2643
+ // The separator test used to be `/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/`. Its two
2644
+ // character classes overlap on `-`, so a long dash run that FAILS backtracks over
2645
+ // every split: measured 2,000 hyphens 96 ms, 4,000 575 ms, 8,000 2.1 s,
2646
+ // 16,000 7.4 s — a synchronous stall inside the detail panel, on content a model
2647
+ // can emit. Same predicate, one linear pass (§13.84).
2648
+ if (line.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
2445
2649
  // `\|` is the escape for a literal pipe inside a cell — the only way to
2446
2650
  // put one in a table at all. Splitting on every `|` cut such a cell in
2447
2651
  // two, so `| a \| b | c |` became THREE columns ("a \", "b", "c") and
@@ -2503,6 +2707,30 @@
2503
2707
  }
2504
2708
  return blocks;
2505
2709
  }
2710
+ /**
2711
+ * Hard caps for text that goes into a STATION CARD.
2712
+ *
2713
+ * A card shows at most four clamped lines, but `dstv_clamp4` only hides the overflow:
2714
+ * the text node and the `title` attribute both kept the whole string. Measured with a
2715
+ * 1 MB assistant message: 1,575 ms to paint one card and 1,000,007 characters in the
2716
+ * DOM (the tooltip alone carried the megabyte). The full text stays available through
2717
+ * copy, the detail panel and the export — the card is a thumbnail, not a viewer.
2718
+ */
2719
+ // 20 000, not 2 000: group 20 of the browser probe renders a 20k body in full and
2720
+ // requires a one-character edit deep inside it to repaint the card. The cap exists to
2721
+ // stop megabyte messages, not to change what a long-but-normal message looks like.
2722
+ const CARD_TEXT_MAX = 20000;
2723
+ const CARD_TITLE_MAX = 300;
2724
+ /** Clamp a string for rendering inside a card, marking that it was cut. */
2725
+ function cardText(v) {
2726
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
2727
+ return s.length > CARD_TEXT_MAX ? `${s.slice(0, CARD_TEXT_MAX)}…` : s;
2728
+ }
2729
+ /** Clamp a string for a `title` tooltip: a tooltip longer than this is unreadable. */
2730
+ function cardTitle(v) {
2731
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
2732
+ return s.length > CARD_TITLE_MAX ? `${s.slice(0, CARD_TITLE_MAX)}…` : s;
2733
+ }
2506
2734
  /** Markdown with markers stripped, for one-line previews. */
2507
2735
  function markdownToPlain(src) {
2508
2736
  let out = "";
@@ -2567,21 +2795,29 @@
2567
2795
  L.push("");
2568
2796
  pushSubLines(L, sub, 1, t);
2569
2797
  }
2798
+ if (cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal)) {
2799
+ L.push("");
2800
+ L.push(`> ${t("detail.subCallsCut").replace("{shown}", fmtInt(cell.subCalls.length)).replace("{total}", fmtInt(cell.subCallsTotal))}`);
2801
+ }
2570
2802
  }
2571
2803
  }
2572
2804
  } else if (st.kind === "orphan-tool") {
2573
- L.push(`### ⤷ ${t("node.orphanTool")} · ${st.name}`);
2805
+ L.push(`### ⤷ ${t(st.replayOf !== null && st.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")} · ${st.name}`);
2574
2806
  L.push("");
2575
- L.push(`_${t("orphan.badge")} · ${anchorOf(st) ?? "—"}_`);
2807
+ L.push(`_${t(st.replayOf !== null && st.replayOf !== void 0 ? "orphan.replayBadge" : "orphan.badge").replace("{seq}", String(st.replayOf ?? ""))} · ${anchorOf(st) ?? "—"}_`);
2576
2808
  if (st.args !== "") { L.push(""); L.push(...fencedBlock(prettyArgs(st.args) || st.args, "json")); }
2577
2809
  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)); }
2810
+ if (st.subCallsTruncated === true && Number.isSafeInteger(st.subCallsTotal)) {
2811
+ L.push("");
2812
+ L.push(`> ${t("detail.subCallsCut").replace("{shown}", fmtInt((st.subCalls || []).length)).replace("{total}", fmtInt(st.subCallsTotal))}`);
2813
+ }
2578
2814
  } else if (st.kind === "compaction") {
2579
2815
  L.push(`### ♺ ${st.label}${Number.isSafeInteger(st.count) ? ` _(${numOr(st.count)} ${t("meta.steps")} / ${fmtTokens(st.tokens)} ${t("meta.tokens")})_` : ""}`);
2580
- if (st.summary !== "") { L.push(""); L.push(st.summary); }
2581
- if (st.crequest?.outputText) { L.push(""); L.push(`<details><summary>${t("detail.compactionOutput")}</summary>`); L.push(""); L.push(st.crequest.outputText); L.push("</details>"); }
2816
+ if (st.summary !== "") { L.push(""); L.push(proseSafe(st.summary)); }
2817
+ 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>"); }
2582
2818
  } else if (st.kind === "error") {
2583
2819
  L.push(`### ✗ ${st.label}${st.code != null ? ` \`${st.code}\`` : ""}`);
2584
- L.push(""); L.push(st.message || "…");
2820
+ L.push(""); L.push(st.message ? proseSafe(st.message) : "…");
2585
2821
  } else if (st.kind === "retry") {
2586
2822
  // The detail panel shows the retry counter, the provider and the error
2587
2823
  // code; the export showed none of them, so the Markdown copy of a failed
@@ -2594,12 +2830,12 @@
2594
2830
  if (st.code != null) retryBits.push(`code: ${st.code}`);
2595
2831
  if (st.retryState) retryBits.push(String(st.retryState));
2596
2832
  L.push(`### ↻ ${st.label}${retryBits.length > 0 ? ` (${retryBits.join(" · ")})` : ""}`);
2597
- if (st.message) { L.push(""); L.push(st.message); }
2833
+ if (st.message) { L.push(""); L.push(proseSafe(st.message)); }
2598
2834
  } else if (st.kind === "maxTokens") {
2599
2835
  L.push(`### ⛔ ${st.label}`);
2600
2836
  } else if (st.kind === "command") {
2601
- L.push(`### ⚡ /${st.name}${st.args !== "" ? ` ${st.args}` : ""}`);
2602
- if (st.outcomeText) { L.push(""); L.push(st.outcomeText); }
2837
+ L.push(`### ⚡ /${inlineSafe(st.name)}${st.args !== "" ? ` ${inlineSafe(st.args)}` : ""}`);
2838
+ if (st.outcomeText) { L.push(""); L.push(proseSafe(st.outcomeText)); }
2603
2839
  } else if (st.kind === "unknown") {
2604
2840
  L.push(`### ? ${t("node.unknown")}${st.eventType ? ` \`${st.eventType}\`` : ""}`);
2605
2841
  if (st.payload) { L.push(""); L.push(...fencedBlock(st.payload, "json")); }