dsh-trajectory-traceview-plus 0.11.5 → 0.11.7

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
  }
@@ -1398,7 +1498,22 @@
1398
1498
  const p = snap?.partial;
1399
1499
  if (p != null && Array.isArray(p.blocks) && p.blocks.length > 0) {
1400
1500
  const turn = typeof p.turn === "number" ? p.turn : 0;
1401
- const seq = lastTurnEntry != null ? lastTurnEntry.seq + 0.5 : 0.5;
1501
+ // The in-flight step belongs at the END of its turn, not just after the turn's
1502
+ // first event. `+0.5` was added to the turn's EARLIEST seq, so a partial that
1503
+ // arrived while steps 1 and 2 already existed sorted BEFORE step 1: the
1504
+ // "running" card appeared to the left of finished work (measured order
1505
+ // user → step3(live) → step1 → step2). Take the turn's largest known seq.
1506
+ const seq = (() => {
1507
+ if (lastTurnEntry == null) return 0.5;
1508
+ let maxSeq = lastTurnEntry.seq;
1509
+ for (const st0 of lastTurnEntry.steps?.values() ?? []) {
1510
+ if (Number.isFinite(st0.seq) && st0.seq > maxSeq) maxSeq = st0.seq;
1511
+ }
1512
+ for (const s0 of lastTurnEntry.stations) {
1513
+ if (Number.isFinite(s0.seq) && s0.seq > maxSeq) maxSeq = s0.seq;
1514
+ }
1515
+ return maxSeq + 0.5;
1516
+ })();
1402
1517
  flushUser(turn, seq);
1403
1518
  const e = ensureTurn(turn, seq);
1404
1519
  const step = stepOf(p.step);
@@ -1469,19 +1584,27 @@
1469
1584
  } else if (b.kind === "tool-call") {
1470
1585
  if (claimedCall(turn, b.callId)) continue;
1471
1586
  claimCall(turn, b.callId);
1472
- const res = takeResult(b.callId);
1587
+ const res = takeResult(b.callId, turn, seq);
1473
1588
  st.toolCount += 1;
1474
1589
  if (res?.isError === true) st.hasError = true;
1475
1590
  const schema = schemasById.get(b.callId);
1591
+ const subPack3 = mapSubCalls(res?.subCalls, t);
1476
1592
  st.cells.push({
1477
1593
  id: cellId("t", b.callId, st.cells.length), kind: "tool", callId: b.callId,
1478
1594
  name: typeof b.name === "string" && b.name !== "" ? b.name : t("node.tool"),
1479
1595
  args: argsText(b.argsRaw),
1480
1596
  resultText: res !== undefined ? blocksText(res.content, t) : "",
1597
+ // The result's own seq. A copied `tvp1:e19` anchor used to die the moment a page
1598
+ // load brought in the call header: seq 19 stopped being a station of its own and became
1599
+ // a cell of the step at 15, so the anchor said "not loaded" while the output was on
1600
+ // screen. `resultSeq` lets the resolver walk that back to the owning step.
1601
+ resultSeq: res !== undefined && Number.isSafeInteger(res.seq) ? res.seq : null,
1481
1602
  isError: res?.isError === true,
1482
1603
  errorName: res?.error?.name,
1483
1604
  durationMs: null, running: res === undefined,
1484
- subCalls: mapSubCalls(res?.subCalls, t),
1605
+ subCalls: subPack3.list,
1606
+ subCallsTotal: subPack3.total,
1607
+ subCallsTruncated: subPack3.truncated,
1485
1608
  schema: schema != null ? { name: schema.name, description: schema.description, parameters: schema.parameters } : null
1486
1609
  });
1487
1610
  }
@@ -1495,7 +1618,7 @@
1495
1618
  // Binary search: `turnsBySeq` is already sorted. The previous linear scan ran
1496
1619
  // once per compaction/special event, so a log with many of both cost
1497
1620
  // O(events x turns) — measured 105 ms at 1000 turns, and it grows from there.
1498
- const turnForSeq = (s) => {
1621
+ const turnForSeq = (s, turnHint) => {
1499
1622
  let lo = 0;
1500
1623
  let hi = turnsBySeq.length - 1;
1501
1624
  let best = null;
@@ -1504,7 +1627,21 @@
1504
1627
  if (turnsBySeq[mid].seq <= s) { best = turnsBySeq[mid]; lo = mid + 1; }
1505
1628
  else hi = mid - 1;
1506
1629
  }
1507
- return best ?? lastTurnEntry ?? ensureTurn(0, s);
1630
+ if (best !== null) return best;
1631
+ // The event sits BEFORE every turn boundary in this window. That is the normal
1632
+ // shape after paging: a page can start on a tool RESULT whose call sits above
1633
+ // it, and the result's own turn then has no boundary at or before its seq.
1634
+ //
1635
+ // The fallback used to be `lastTurnEntry` — the turn created LAST — so the
1636
+ // orphan was filed under the newest turn and `ensureTurn` lowered that turn's
1637
+ // seq to the orphan's. Sorting by seq then put the NEWEST turn first and split
1638
+ // the timeline: turn 68 → 65 → 66 → 67, with ~1h52m of apparent rewind in the
1639
+ // gap bars, and the export filed the result under the wrong turn (§13.83).
1640
+ //
1641
+ // Prefer the event's OWN turn when the log states one (the orphan's node
1642
+ // carries `turn`), else the earliest turn — never the last.
1643
+ const hinted = turnMap.get(typeof turnHint === "number" ? turnHint : NaN);
1644
+ return hinted ?? turnsBySeq[0] ?? ensureTurn(0, s);
1508
1645
  };
1509
1646
  const consumedCompactionReqs = new Set();
1510
1647
  // Index the exact-replacementSeq match instead of scanning every request per
@@ -1521,7 +1658,7 @@
1521
1658
  }
1522
1659
  for (const n of nodes) {
1523
1660
  if (n.kind === "compaction") {
1524
- const e = turnForSeq(n.seq);
1661
+ const e = turnForSeq(n.seq, n.turn);
1525
1662
  // Pair with the compaction provider request: exact replacementSeq
1526
1663
  // match first, else the nearest unconsumed compaction request that
1527
1664
  // completed within a minute before this marker landed.
@@ -1536,6 +1673,13 @@
1536
1673
  let best = null;
1537
1674
  for (const r of compactionReqs) {
1538
1675
  if (consumedCompactionReqs.has(r)) continue;
1676
+ // A request that NAMES a different replacementSeq belongs to that
1677
+ // marker. Time-proximity used to override the declaration, so a
1678
+ // marker at seq 20 displayed the output of the request for seq 10 —
1679
+ // a marker outside the window — and `unplacedRequests` stayed 0, so
1680
+ // nothing said the text was someone else's. Leaving it unconsumed
1681
+ // makes the view report it instead of borrowing it.
1682
+ if (Number.isSafeInteger(r.replacementSeq) && r.replacementSeq !== n.seq) continue;
1539
1683
  const doneAt = Number.isFinite(r.completedAt) ? r.completedAt : r.startedAt;
1540
1684
  if (!Number.isFinite(doneAt)) continue;
1541
1685
  const gap = n.time - doneAt;
@@ -1586,7 +1730,7 @@
1586
1730
  const e = ensureTurn(typeof n.turn === "number" ? n.turn : 0, n.seq);
1587
1731
  e.stations.push({ id: `x${n.seq}`, kind: "maxTokens", time: n.time, seq: n.seq, label: t("node.maxTokens") });
1588
1732
  } else if (n.kind === "command") {
1589
- const e = turnForSeq(n.seq);
1733
+ const e = turnForSeq(n.seq, n.turn);
1590
1734
  e.stations.push({
1591
1735
  id: `c${n.seq}`, kind: "command", time: n.time, seq: n.seq,
1592
1736
  name: asText(n.name) !== "" ? asText(n.name) : `/${asText(n.commandId) || "?"}`, args: asText(n.args),
@@ -1597,7 +1741,7 @@
1597
1741
  // The contract's own fallback surface. Rendering nothing would hide a
1598
1742
  // real event that exists in the session log, and the review tool's whole
1599
1743
  // promise is that what the log recorded is what the reader sees.
1600
- const e = turnForSeq(n.seq);
1744
+ const e = turnForSeq(n.seq, n.turn);
1601
1745
  e.stations.push({
1602
1746
  id: `k${n.seq}`, kind: "unknown", time: n.time, seq: n.seq,
1603
1747
  eventType: typeof n.type === "string" ? n.type : "",
@@ -1639,9 +1783,10 @@
1639
1783
  return `ot${base}${seen === 0 ? "" : `_${String(seen)}`}`;
1640
1784
  };
1641
1785
  for (const n of orphans) {
1642
- const e = turnForSeq(n.seq);
1786
+ const e = turnForSeq(n.seq, n.turn);
1643
1787
  const text = blocksText(n.content, t);
1644
- const subCalls = mapSubCalls(n.subCalls, t);
1788
+ const subCallPack = mapSubCalls(n.subCalls, t);
1789
+ const subCalls = subCallPack.list;
1645
1790
  // Anchor issuance is centralized in the "special stations" branch below
1646
1791
  // (it re-checks `seq` for integer-ness and stamps anchorKey/synthetic).
1647
1792
  e.stations.push({
@@ -1668,6 +1813,14 @@
1668
1813
  displayText: text !== "" ? text : (n.error?.code ?? n.error?.name ?? ""),
1669
1814
  isError: n.isError === true,
1670
1815
  subCalls,
1816
+ subCallsTotal: subCallPack.total,
1817
+ subCallsTruncated: subCallPack.truncated,
1818
+ // Set when this same callId ALREADY produced a result earlier in the window —
1819
+ // i.e. this is a compaction replay, not a missing call.
1820
+ replayOf: (() => {
1821
+ const used = consumedByCallId.get(n.callId);
1822
+ return used !== void 0 && used.length > 0 ? used[0] : null;
1823
+ })(),
1671
1824
  hasError: n.isError === true
1672
1825
  });
1673
1826
  }
@@ -1677,9 +1830,9 @@
1677
1830
  // Sort turns by their earliest known seq first (turn 0 "system events" may
1678
1831
  // be created late by a stray compaction/command and would otherwise land last).
1679
1832
  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;
1833
+ let mseq = orderKey(e.seq);
1834
+ for (const st of e.stations) mseq = Math.min(mseq, orderKey(st.seq));
1835
+ for (const st of e.steps?.values() ?? []) mseq = Math.min(mseq, orderKey(st.seq));
1683
1836
  e.minSeq = mseq;
1684
1837
  }
1685
1838
  turns.sort((a, b) => a.minSeq - b.minSeq);
@@ -1693,7 +1846,7 @@
1693
1846
  const turnNodes = turns.map((e) => {
1694
1847
  const pieceList = [];
1695
1848
  for (const s of e.stations) {
1696
- pieceList.push({ at: s.seq, kind: s.kind, data: s });
1849
+ pieceList.push({ at: orderKey(s.seq), kind: s.kind, data: s });
1697
1850
  if (s.kind === "orphan-tool") {
1698
1851
  stats.tools += 1;
1699
1852
  if (s.isError === true) stats.errors += 1;
@@ -1702,7 +1855,7 @@
1702
1855
  const stepNums = e.steps === void 0 ? [] : [...e.steps.keys()].sort((a, b) => a - b);
1703
1856
  for (const s of stepNums) {
1704
1857
  const st = e.steps.get(s);
1705
- pieceList.push({ at: st.seq, kind: "step", data: st, stepNum: s });
1858
+ pieceList.push({ at: orderKey(st.seq), kind: "step", data: st, stepNum: s });
1706
1859
  }
1707
1860
  pieceList.sort((a, b) => a.at - b.at);
1708
1861
 
@@ -1775,6 +1928,15 @@
1775
1928
  tools: Array.isArray(found.prompt.tools) ? found.prompt.tools : [],
1776
1929
  systemChars: typeof found.prompt.system === "string" ? found.prompt.system.length : 0
1777
1930
  } : null,
1931
+ // Present only when the request header's own prompt text is empty AND an older
1932
+ // system event exists: the reader then sees the real text, labelled as coming from
1933
+ // outside the window, instead of "0 chars".
1934
+ systemFrom: (() => {
1935
+ const own = found.prompt != null && typeof found.prompt.system === "string" ? found.prompt.system : "";
1936
+ if (own !== "") return null;
1937
+ const older = systemPromptBefore(Number(r.startSeq));
1938
+ return older !== null ? { seq: Number(older.seq), text: older.text, update: older.update === true } : null;
1939
+ })(),
1778
1940
  promptChangeKind: r.promptChange?.kind ?? null,
1779
1941
  promptDiff: promptDiffOf(r.promptChange, found.prompt),
1780
1942
  startSeq: r.startSeq ?? null
@@ -2038,7 +2200,8 @@
2038
2200
  : station.kind === "user" ? t("node.user")
2039
2201
  : station.kind === "error" ? t("node.error")
2040
2202
  : station.kind === "compaction" ? t("node.compaction")
2041
- : station.kind === "orphan-tool" ? t("node.orphanTool")
2203
+ // Same distinction as the card: a compaction replay is not a missing call.
2204
+ : station.kind === "orphan-tool" ? t(station.replayOf !== null && station.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")
2042
2205
  : station.kind === "unknown" ? t("node.unknown")
2043
2206
  : String(station.kind);
2044
2207
  const parts = [`${position} / ${total}`, kind];
@@ -2200,6 +2363,16 @@
2200
2363
  // again here duplicated every sub-call result in the export.
2201
2364
  pushSubLines(L, sub, 1, t);
2202
2365
  }
2366
+ // Say it when the list was cut. A file that silently stops at 1,999 of
2367
+ // 20,000 reads as "this was everything", which is the one outcome this
2368
+ // view promises never to produce.
2369
+ if (cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal)) {
2370
+ const shown = (cell.subCalls ?? []).length;
2371
+ L.push("");
2372
+ L.push(`> ${typeof t === "function"
2373
+ ? t("detail.subCallsCut").replace("{shown}", fmtInt(shown)).replace("{total}", fmtInt(cell.subCallsTotal))
2374
+ : `showing the first ${String(shown)} of ${String(cell.subCallsTotal)}`}`);
2375
+ }
2203
2376
  L.push("");
2204
2377
  }
2205
2378
  }
@@ -2279,7 +2452,27 @@
2279
2452
  // "[object Object]".
2280
2453
  return asText(content)
2281
2454
  .replace(/`{3,}/g, (run) => "\\`".repeat(run.length))
2282
- .replace(/<(\/?)(details)\b/gi, "&lt;$1$2");
2455
+ // GFM fences with TILDES too, and only backticks were escaped: prose ending in an
2456
+ // unclosed "~~~" turned every following station into code (verified with Pandoc
2457
+ // by the boundary review). Same treatment: leading tildes of a run this long
2458
+ // get escaped, so the run is no longer a fence opener.
2459
+ .replace(/(^|\n)(~{3,})/g, (m, lead, run) => lead + "\\~".repeat(run.length))
2460
+ .replace(/<(\/?)(details)\b/gi, "&lt;$1$2")
2461
+ // A content line that starts with `#` becomes a real heading in the export and
2462
+ // silently re-sections the document (measured: a compaction summary containing
2463
+ // "### 伪造标题" produced a section the panel never showed). Escaping turns it
2464
+ // back into text; a Markdown renderer still displays the bare `#`.
2465
+ .replace(/^(\s*)(#{1,6})\s/gm, "$1\\$2 ");
2466
+ }
2467
+ /**
2468
+ * Free text that sits INSIDE a generated line (a heading, a label).
2469
+ *
2470
+ * `proseSafe` keeps newlines, which is right for a paragraph and wrong for a heading:
2471
+ * a tool name or a slash-command's arguments containing "\n### …" forges a section in
2472
+ * the exported Markdown. Flatten first, then apply the same escaping.
2473
+ */
2474
+ function inlineSafe(content) {
2475
+ return proseSafe(asText(content).replace(/\s+/g, " ").trim());
2283
2476
  }
2284
2477
  function fencedBlock(content, lang) {
2285
2478
  const text = String(content ?? "");
@@ -2408,6 +2601,27 @@
2408
2601
  return out;
2409
2602
  }
2410
2603
  /** Block-level split. Returns descriptors; see mdInline for the inline level. */
2604
+ /**
2605
+ * Is this line a Markdown table separator (`|---|:--:|`)?
2606
+ *
2607
+ * Equivalent to `/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/`, but linear. The regex was
2608
+ * quadratic on failure: two overlapping classes around the mandatory `-` let it
2609
+ * re-split a long dash run for every possible position.
2610
+ */
2611
+ const WHITESPACE_CHAR = /\s/;
2612
+ function isTableSeparator(line) {
2613
+ if (typeof line !== "string") return false;
2614
+ let dashes = 0;
2615
+ for (let i = 0; i < line.length; i += 1) {
2616
+ const ch = line[i];
2617
+ if (ch === "-") { dashes += 1; continue; }
2618
+ // `\s` in the original class, plus the pipe. Testing one character at a time
2619
+ // keeps the whole thing linear and preserves CRLF and Unicode-space behaviour.
2620
+ if (ch === "|" || ch === ":" || WHITESPACE_CHAR.test(ch)) continue;
2621
+ return false;
2622
+ }
2623
+ return dashes > 0;
2624
+ }
2411
2625
  function mdBlocks(src) {
2412
2626
  const lines = String(src ?? "").replace(/\r\n?/g, "\n").split("\n");
2413
2627
  const blocks = [];
@@ -2441,7 +2655,12 @@
2441
2655
  continue;
2442
2656
  }
2443
2657
  // Table: a header row followed by a |---|---| separator.
2444
- if (line.includes("|") && i + 1 < lines.length && /^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(lines[i + 1])) {
2658
+ // The separator test used to be `/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/`. Its two
2659
+ // character classes overlap on `-`, so a long dash run that FAILS backtracks over
2660
+ // every split: measured 2,000 hyphens 96 ms, 4,000 575 ms, 8,000 2.1 s,
2661
+ // 16,000 7.4 s — a synchronous stall inside the detail panel, on content a model
2662
+ // can emit. Same predicate, one linear pass (§13.84).
2663
+ if (line.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
2445
2664
  // `\|` is the escape for a literal pipe inside a cell — the only way to
2446
2665
  // put one in a table at all. Splitting on every `|` cut such a cell in
2447
2666
  // two, so `| a \| b | c |` became THREE columns ("a \", "b", "c") and
@@ -2503,6 +2722,30 @@
2503
2722
  }
2504
2723
  return blocks;
2505
2724
  }
2725
+ /**
2726
+ * Hard caps for text that goes into a STATION CARD.
2727
+ *
2728
+ * A card shows at most four clamped lines, but `dstv_clamp4` only hides the overflow:
2729
+ * the text node and the `title` attribute both kept the whole string. Measured with a
2730
+ * 1 MB assistant message: 1,575 ms to paint one card and 1,000,007 characters in the
2731
+ * DOM (the tooltip alone carried the megabyte). The full text stays available through
2732
+ * copy, the detail panel and the export — the card is a thumbnail, not a viewer.
2733
+ */
2734
+ // 20 000, not 2 000: group 20 of the browser probe renders a 20k body in full and
2735
+ // requires a one-character edit deep inside it to repaint the card. The cap exists to
2736
+ // stop megabyte messages, not to change what a long-but-normal message looks like.
2737
+ const CARD_TEXT_MAX = 20000;
2738
+ const CARD_TITLE_MAX = 300;
2739
+ /** Clamp a string for rendering inside a card, marking that it was cut. */
2740
+ function cardText(v) {
2741
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
2742
+ return s.length > CARD_TEXT_MAX ? `${s.slice(0, CARD_TEXT_MAX)}…` : s;
2743
+ }
2744
+ /** Clamp a string for a `title` tooltip: a tooltip longer than this is unreadable. */
2745
+ function cardTitle(v) {
2746
+ const s = typeof v === "string" ? v : v == null ? "" : String(v);
2747
+ return s.length > CARD_TITLE_MAX ? `${s.slice(0, CARD_TITLE_MAX)}…` : s;
2748
+ }
2506
2749
  /** Markdown with markers stripped, for one-line previews. */
2507
2750
  function markdownToPlain(src) {
2508
2751
  let out = "";
@@ -2514,7 +2757,11 @@
2514
2757
  L.push(`# ${t("export.title")}`);
2515
2758
  L.push("");
2516
2759
  const s = tree.stats;
2517
- L.push(`> ${t("node.turn")} ${s.turns} · ${t("node.step")} ${s.steps} · ${t("node.tool")} ${s.tools} · ${t("kpi.errors")} ${s.errors} · ${t("kpi.tokensIn")} ${fmtTokens(s.tokensIn)} · ${t("kpi.tokensOut")} ${fmtTokens(s.tokensOut)}${s.lastModel ? ` · ${s.lastModel}` : ""}`);
2760
+ // The header KPI strip carries FIVE numbers, and the export carried four: a
2761
+ // reader who saw "900 ms 工具总耗时" on screen and pasted the export into a bug
2762
+ // report lost exactly that number. Same rule as the warning lines below — the
2763
+ // file states what the screen states.
2764
+ L.push(`> ${t("node.turn")} ${s.turns} · ${t("node.step")} ${s.steps} · ${t("node.tool")} ${s.tools} · ${t("kpi.errors")} ${s.errors} · ${t("kpi.toolTime")} ${fmtDur(s.toolMs)} · ${t("kpi.tokensIn")} ${fmtTokens(s.tokensIn)} · ${t("kpi.tokensOut")} ${fmtTokens(s.tokensOut)}${s.lastModel ? ` · ${s.lastModel}` : ""}`);
2518
2765
  // The panel warns about a damaged or drifting log in its header; the export used
2519
2766
  // to state only the totals, so a saved "study notes" file silently claimed a
2520
2767
  // clean read of a log the screen was actively flagging. Same rule as the error
@@ -2567,21 +2814,29 @@
2567
2814
  L.push("");
2568
2815
  pushSubLines(L, sub, 1, t);
2569
2816
  }
2817
+ if (cell.subCallsTruncated === true && Number.isSafeInteger(cell.subCallsTotal)) {
2818
+ L.push("");
2819
+ L.push(`> ${t("detail.subCallsCut").replace("{shown}", fmtInt(cell.subCalls.length)).replace("{total}", fmtInt(cell.subCallsTotal))}`);
2820
+ }
2570
2821
  }
2571
2822
  }
2572
2823
  } else if (st.kind === "orphan-tool") {
2573
- L.push(`### ⤷ ${t("node.orphanTool")} · ${st.name}`);
2824
+ L.push(`### ⤷ ${t(st.replayOf !== null && st.replayOf !== void 0 ? "node.replayedTool" : "node.orphanTool")} · ${st.name}`);
2574
2825
  L.push("");
2575
- L.push(`_${t("orphan.badge")} · ${anchorOf(st) ?? "—"}_`);
2826
+ L.push(`_${t(st.replayOf !== null && st.replayOf !== void 0 ? "orphan.replayBadge" : "orphan.badge").replace("{seq}", String(st.replayOf ?? ""))} · ${anchorOf(st) ?? "—"}_`);
2576
2827
  if (st.args !== "") { L.push(""); L.push(...fencedBlock(prettyArgs(st.args) || st.args, "json")); }
2577
2828
  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)); }
2829
+ if (st.subCallsTruncated === true && Number.isSafeInteger(st.subCallsTotal)) {
2830
+ L.push("");
2831
+ L.push(`> ${t("detail.subCallsCut").replace("{shown}", fmtInt((st.subCalls || []).length)).replace("{total}", fmtInt(st.subCallsTotal))}`);
2832
+ }
2578
2833
  } else if (st.kind === "compaction") {
2579
2834
  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>"); }
2835
+ if (st.summary !== "") { L.push(""); L.push(proseSafe(st.summary)); }
2836
+ 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
2837
  } else if (st.kind === "error") {
2583
2838
  L.push(`### ✗ ${st.label}${st.code != null ? ` \`${st.code}\`` : ""}`);
2584
- L.push(""); L.push(st.message || "…");
2839
+ L.push(""); L.push(st.message ? proseSafe(st.message) : "…");
2585
2840
  } else if (st.kind === "retry") {
2586
2841
  // The detail panel shows the retry counter, the provider and the error
2587
2842
  // code; the export showed none of them, so the Markdown copy of a failed
@@ -2594,12 +2849,12 @@
2594
2849
  if (st.code != null) retryBits.push(`code: ${st.code}`);
2595
2850
  if (st.retryState) retryBits.push(String(st.retryState));
2596
2851
  L.push(`### ↻ ${st.label}${retryBits.length > 0 ? ` (${retryBits.join(" · ")})` : ""}`);
2597
- if (st.message) { L.push(""); L.push(st.message); }
2852
+ if (st.message) { L.push(""); L.push(proseSafe(st.message)); }
2598
2853
  } else if (st.kind === "maxTokens") {
2599
2854
  L.push(`### ⛔ ${st.label}`);
2600
2855
  } else if (st.kind === "command") {
2601
- L.push(`### ⚡ /${st.name}${st.args !== "" ? ` ${st.args}` : ""}`);
2602
- if (st.outcomeText) { L.push(""); L.push(st.outcomeText); }
2856
+ L.push(`### ⚡ /${inlineSafe(st.name)}${st.args !== "" ? ` ${inlineSafe(st.args)}` : ""}`);
2857
+ if (st.outcomeText) { L.push(""); L.push(proseSafe(st.outcomeText)); }
2603
2858
  } else if (st.kind === "unknown") {
2604
2859
  L.push(`### ? ${t("node.unknown")}${st.eventType ? ` \`${st.eventType}\`` : ""}`);
2605
2860
  if (st.payload) { L.push(""); L.push(...fencedBlock(st.payload, "json")); }