dsh-mobile-plugin 0.5.46 → 0.5.48

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.
@@ -15,6 +15,7 @@ const { cutAssistantBlock, cutToolResultEvent, createToolNameIndex } = require('
15
15
  const { rememberToolResults, toolResultsFor, toolResultsVersionFor } = require('./tool-result-cache.js');
16
16
  const crypto = require('node:crypto');
17
17
  const { derivedCache } = require('../shared/derived-cache.js');
18
+ const { foldTurnFacts, turnFactsSnapshot } = require('./turn-facts.js');
18
19
 
19
20
  /** 每一轮出过的图(工具结果里的图片块),轮号 → 图。`lookback` 也扫:它才装得下更早那一页。 */
20
21
  function collectTurnImages(entries, lookbackEntries) {
@@ -44,6 +45,7 @@ const {
44
45
  toolStepSummary,
45
46
  toolStepState,
46
47
  } = require('./step-index.js');
48
+ const { deriveWorkflowRuns } = require('./workflow-runs.js');
47
49
 
48
50
  /**
49
51
  * 从 session.list 摘要行取会话标题(与桌面端侧栏同源,不再从 history 窗口猜):
@@ -170,7 +172,7 @@ function buildToolResultMap(events) {
170
172
  const images = toolResultImages(parts);
171
173
  // `seq` 只给「按需取详情」用:手机点开这一步时拿它去回拉那一小窗事件。
172
174
  map.set(src.callId, {
173
- isError,
175
+ isError: isError || kept.data.error != null,
174
176
  code,
175
177
  ...(Number.isSafeInteger(e.seq) ? { seq: e.seq } : {}),
176
178
  ...(output ? { output } : {}),
@@ -274,31 +276,6 @@ function parseBlocks(blocks, toolResults) {
274
276
  return out;
275
277
  }
276
278
 
277
- /**
278
- * 一条消息里 write/edit 成功写过的文件路径。
279
- *
280
- * 参数不下发手机(见 `wire-cut.js`),但「这一轮动过哪些文件」仍要在本机从**原始**块的
281
- * `arguments` 里派生出来:App 拿这份清单解析收尾正文里的行内文件引用。
282
- */
283
- function writtenPaths(content, toolResults) {
284
- if (!Array.isArray(content)) return [];
285
- const out = [];
286
- for (const b of content) {
287
- if (!b || typeof b !== 'object' || b.type !== 'tool-call') continue;
288
- if (b.name !== 'write' && b.name !== 'edit') continue;
289
- const callId = b.id != null ? String(b.id) : undefined;
290
- const result = callId && toolResults ? toolResults.get(callId) : undefined;
291
- if (!result || result.isError) continue;
292
- const raw = typeof b.arguments === 'string' ? b.arguments : (b.arguments != null ? JSON.stringify(b.arguments) : '');
293
- try {
294
- const args = JSON.parse(raw || '{}');
295
- const path = typeof args.path === 'string' ? args.path : typeof args.file_path === 'string' ? args.file_path : null;
296
- if (typeof path === 'string' && path) out.push(path);
297
- } catch { /* 参数不是 JSON:这条调用不算产出,与「没有参数」同处理 */ }
298
- }
299
- return out;
300
- }
301
-
302
279
  /** 从结构块里拼接纯文本(列表预览/标题回退用,仍只取 text 块)。 */
303
280
  function blocksToText(blocks) {
304
281
  return blocks.filter((b) => b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n');
@@ -523,8 +500,7 @@ function deriveMessages(events, sessionId, lookbackEvents) {
523
500
  // 预扫描 tool/result 事件(同批次事件内,结果可能在调用块之前/之后出现)。
524
501
  // `lookbackEvents` 是这一页**再往前**的一小段:倒着分页时工具结果常常落在比消息更早的位置
525
502
  // (一轮里先跑工具、最后才写正文),只看这一页就看不出这一轮出过哪些图。
526
- const toolResults = buildToolResultMap(lookbackEvents && lookbackEvents.length ? events.concat(lookbackEvents) : events);
527
- // 倒着分页时,一页的边界可能正好切在「工具调用」与「它的结果」之间:这一页只有调用,
503
+ const toolResults = buildToolResultMap(lookbackEvents && lookbackEvents.length ? events.concat(lookbackEvents) : events); // 倒着分页时,一页的边界可能正好切在「工具调用」与「它的结果」之间:这一页只有调用,
528
504
  // 结果在更新的一页(本机早就拿到过)。把那些记在进程里的结果并进来,图就跟着消息一起
529
505
  // 下发,手机侧那一行在挂载那一帧就是终高(见 tool-result-cache.js)。
530
506
  const remembered = toolResultsFor(sessionId);
@@ -581,16 +557,8 @@ function deriveMessages(events, sessionId, lookbackEvents) {
581
557
  if (bucket.length > 0) presentedByTurn.set(data.turn, bucket);
582
558
  }
583
559
 
584
- /**
585
- * 这一轮**被 write / edit 动过**的文件,按轮攒。
586
- *
587
- * 为什么按轮而不是按单条消息:一份文件是一轮里某一步写的,而收尾答复那条消息自己一个
588
- * 写操作都没有 —— 按消息算的话,正文里提到刚写好的文件时那份清单永远是空的。
589
- * 桌面 `dsh-client-ui-deliverables` 的 `selectProducedFiles(owner)` 也是按**整轮**取。
590
- *
591
- * 攒完在循环之后回填:同一轮里先发的消息也要能看到这一轮后几步才写出来的文件。
592
- */
593
- const producedByTurn = new Map();
560
+ // 模型归因、成功产出与净改动和直播同源;原始参数与 diff 只在本机折叠。
561
+ const factsByTurn = foldTurnFacts((lookbackEvents || []).concat(events));
594
562
  const producedItems = [];
595
563
 
596
564
  // 单步计时预扫描:为每条 assistant 消息派生「本轮」的 ttft / decode / 输出 token
@@ -670,6 +638,13 @@ function deriveMessages(events, sessionId, lookbackEvents) {
670
638
  */
671
639
  const stepsByTurn = new Map();
672
640
  const openerByTurn = new Map();
641
+ /**
642
+ * 工作流那四类事件(`tool-workflow/*`)原样攒着,最后交给 `workflow-runs.js` 折成树。
643
+ *
644
+ * 不在主循环里就地折:一次运行的数据横跨四条事件、还要看「开启它的那一轮有没有被中断」,
645
+ * 那些判据只有整窗看完才成立。攒的时候连 seq 一起留(要按位置归轮)。
646
+ */
647
+ const workflowEntries = [];
673
648
  let lastOpener = null;
674
649
  const collectSteps = (content, e) => {
675
650
  if (!Array.isArray(content)) return;
@@ -774,14 +749,6 @@ function deriveMessages(events, sessionId, lookbackEvents) {
774
749
  time: e.time,
775
750
  ...(turn !== undefined ? { turn } : {}),
776
751
  };
777
- // 本条消息自己写 / 改过的文件:并进**这一轮**的那一份,不单独挂在它自己头上。
778
- // 从原始块的 arguments 算(那些参数不下发手机)。
779
- const ownWrites = writtenPaths(msg.content, toolResults);
780
- if (turn !== undefined && ownWrites.length > 0) {
781
- const bucket = producedByTurn.get(turn) || new Set();
782
- for (const path of ownWrites) bucket.add(path);
783
- producedByTurn.set(turn, bucket);
784
- }
785
752
  // 回填要等循环跑完(这一轮后面几步写的也要算进来),先把这条记下来。
786
753
  if (turn !== undefined) producedItems.push({ item, turn });
787
754
  // 这一轮模型显式声明的交付文件:轮尾那张交付卡的唯一依据(与产出的清单分开)。
@@ -842,6 +809,11 @@ function deriveMessages(events, sessionId, lookbackEvents) {
842
809
  const e = entry.event || entry;
843
810
  const seq = e.seq;
844
811
  const time = e.time;
812
+ // 工作流那四类事件不在这里就地折:攒起来整窗看(见 `workflowEntries`)。
813
+ if (typeof e.type === 'string' && e.type.startsWith('tool-workflow/')) {
814
+ workflowEntries.push(entry.event ? entry : { event: e });
815
+ continue;
816
+ }
845
817
  if (e.type === 'user/message' && e.data) {
846
818
  const msg = e.data;
847
819
  const src = msg.source;
@@ -1121,15 +1093,13 @@ function deriveMessages(events, sessionId, lookbackEvents) {
1121
1093
  if (last) last.item.images = images;
1122
1094
  }
1123
1095
  }
1124
- // 产出清单按轮回填:这一轮所有 write / edit 的并集,挂到这一轮每条 assistant 消息上。
1125
- // 挂「整轮」而不是「从写那一刻起」,与桌面 `selectProducedFiles(owner)` 同口径;正文里
1126
- // 提到这一轮写的文件就能解析成可点(App 侧按文件名或整条路径唯一命中才画,见
1127
- // `viewmodels/file-mentions`)。
1128
- if (producedItems.length > 0) {
1129
- for (const { item, turn } of producedItems) {
1130
- const bucket = producedByTurn.get(turn);
1131
- if (bucket && bucket.size > 0) item.producedFiles = [...bucket];
1132
- }
1096
+ // 所属轮每个可见载体都带轻量事实,薄入口即使只剩用户行/失败行也不会丢产出。
1097
+ for (const item of out) {
1098
+ const turn = typeof item.turn === 'number' ? item.turn : turnOfSeq(item.seq, turnIndex.bySeq, turnIndex.starts);
1099
+ const facts = factsByTurn.get(turn);
1100
+ if (!facts) continue;
1101
+ if (turn !== null && turn !== undefined) item.turn = turn;
1102
+ Object.assign(item, turnFactsSnapshot(facts));
1133
1103
  }
1134
1104
  // 手动 `/compact` 在桌面上是**一件事**:`CompactionCommandCard` 只画一个 `CompactionItem`
1135
1105
  // (标题取命令名,摘要位放条数与 token 数,条数不齐时放命令结果原文),命令行那块根本不出现。
@@ -1173,9 +1143,38 @@ function deriveMessages(events, sessionId, lookbackEvents) {
1173
1143
  for (const item of out) {
1174
1144
  if (item.kind === 'compaction' && typeof item.text !== 'string') item.text = '';
1175
1145
  }
1146
+ // 工作流运行:`tool-workflow/*` 折成「运行 → 阶段 → 成员」三层(形状与桌面 `workflow-run`
1147
+ // 节点一致,见 `workflow-runs.js`)。这些事件原先整族没人认、手机上一张卡都不出现。
1148
+ //
1149
+ // 「被撇下」按**开启这次运行的那一轮**判:历史窗口里可能横跨好几轮,只有那一轮是被中断 /
1150
+ // 分叉的,这条运行才再也不会长(桌面的 `turnAbandoned` 读的正是 run-start 所在那一轮的
1151
+ // `turn.end.reason`)。所以逐条给 runId,不能整批按「当前这一轮」算。
1152
+ if (workflowEntries.length > 0) {
1153
+ const abandonedTurns = new Set();
1154
+ for (const entry of events) {
1155
+ const e = entry.event || entry;
1156
+ if (!e || e.type !== 'turn/end' || !e.data || typeof e.data.turn !== 'number') continue;
1157
+ const reason = e.data.reason && e.data.reason.kind;
1158
+ if (reason === 'interrupted' || reason === 'forked') abandonedTurns.add(e.data.turn);
1159
+ }
1160
+ const abandonedRunIds = [];
1161
+ if (abandonedTurns.size > 0) {
1162
+ for (const entry of events) {
1163
+ const e = entry.event || entry;
1164
+ if (!e || e.type !== 'tool-workflow/run-start' || !e.data) continue;
1165
+ const turn = turnOfSeq(e.seq, turnIndex.bySeq, turnIndex.starts);
1166
+ if (turn !== null && abandonedTurns.has(turn) && e.data.runId !== undefined) {
1167
+ abandonedRunIds.push(String(e.data.runId));
1168
+ }
1169
+ }
1170
+ }
1171
+ const workflowRows = abandonedRunIds.length > 0
1172
+ ? deriveWorkflowRuns(workflowEntries, { abandonedRunIds })
1173
+ : deriveWorkflowRuns(workflowEntries);
1174
+ for (const row of workflowRows) out.push(row);
1175
+ }
1176
1176
  // 严格按事件 seq 升序(与消息混排;compaction 行升级/替换后位置以最终事件为准)。
1177
- out.sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
1178
- // 存进缓存的是**已经排好序的最终结果**:调用方拿到的是同一份引用,拿去 filter / map 都好,
1177
+ out.sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)); // 存进缓存的是**已经排好序的最终结果**:调用方拿到的是同一份引用,拿去 filter / map 都好,
1179
1178
  // 但不要再就地改(要改就先拷一份)。见 shared/derived-cache.js 的说明。
1180
1179
  if (cacheKey) derivedCache.set(sessionId, cacheKey, out);
1181
1180
  return out;
@@ -24,6 +24,7 @@ const TEXT_MAX = 200_000;
24
24
 
25
25
  const { liveStepTurnOf, liveStepWriterOf, liveStepSinkOf } = require('./session-cache.js');
26
26
  const { reasoningText, reasoningStepSummary, toolStepSummary } = require('./step-index.js');
27
+ const { createTurnFacts, absorbTurnFact, rebuildTurnFacts, turnFactsSnapshot, turnChangesSnapshot, resultCallId } = require('./turn-facts.js');
27
28
 
28
29
  function bucketOf(ctx) {
29
30
  return liveStepTurnOf(ctx);
@@ -135,6 +136,10 @@ function turnOf(ctx, sessionId) {
135
136
  ended: false,
136
137
  /** 这份副本属于哪一轮(宿主 turn 号):换轮就整份作废,见 `turnForEvent`。 */
137
138
  turnNo: null,
139
+ /** 事实与详情同桶、同写入者;断流只释放写入权,下一轮才替换这份事实。 */
140
+ facts: createTurnFacts(),
141
+ factsSentRevision: -1,
142
+ factsSentSnapshot: null,
138
143
  };
139
144
  bucket.delete(sessionId);
140
145
  bucket.set(sessionId, turn);
@@ -157,6 +162,7 @@ function turnForEvent(ctx, sessionId, data) {
157
162
  const bucket = bucketOf(ctx);
158
163
  const explicitTurn = data && typeof data.turn === 'number' ? data.turn : null;
159
164
  let turn = bucket.get(sessionId);
165
+ if (turn && explicitTurn !== null && turn.turnNo !== null && turn.turnNo > explicitTurn) return null;
160
166
  if (turn && explicitTurn !== null && turn.turnNo !== null && turn.turnNo !== explicitTurn) {
161
167
  bucket.delete(sessionId);
162
168
  turn = undefined;
@@ -270,14 +276,23 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
270
276
  if (!writerAllows(ctx, sessionId, writerId)) return;
271
277
  const data = event.data && typeof event.data === 'object' ? event.data : null;
272
278
  if (event.type === 'turn/start') {
279
+ const existing = bucketOf(ctx).get(sessionId);
280
+ if (existing && data && typeof data.turn === 'number' && existing.turnNo > data.turn) return;
281
+ if (existing && existing.turnNo === (data && data.turn)) {
282
+ absorbTurnFact(existing.facts, event);
283
+ return;
284
+ }
273
285
  // 新的一轮开始:上一轮的过程副本作废(换掉了,就别再让人点开旧内容)。
274
286
  bucketOf(ctx).delete(sessionId);
275
287
  const started = turnOf(ctx, sessionId);
276
288
  if (data && typeof data.turn === 'number') started.turnNo = data.turn;
289
+ absorbTurnFact(started.facts, event);
277
290
  return;
278
291
  }
279
292
  if (!data) return;
280
293
  const turn = turnForEvent(ctx, sessionId, data);
294
+ if (!turn) return;
295
+ absorbTurnFact(turn.facts, event);
281
296
  if (event.type === 'assistant/message') {
282
297
  // 一步落定:这一步的思考按块序号收尾(后面那一步的块序号从 0 重新数)。
283
298
  closeThoughtsOfStep(turn);
@@ -294,6 +309,7 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
294
309
  // 参数到这里是齐的 —— 摘要该按它拼出来了。身份帧可能在断线 / 合并里丢过,
295
310
  // 所以这里也顺手把这一步补进清单(有就只更新)。
296
311
  turn.tools.set(callId, {
312
+ ...current,
297
313
  name: typeof block.name === 'string' && block.name ? block.name : current.name,
298
314
  argsRaw: typeof block.arguments === 'string'
299
315
  ? block.arguments
@@ -373,9 +389,9 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
373
389
  }
374
390
  if (event.type === 'tool/result') {
375
391
  const message = data.message;
376
- const src = message && message.source;
377
- if (!src || typeof src.callId !== 'string') return;
378
- const current = turn.tools.get(src.callId) || { name: '', argsRaw: '' };
392
+ const callId = resultCallId(event);
393
+ if (!callId || !message) return;
394
+ const current = turn.tools.get(callId) || { name: '', argsRaw: '' };
379
395
  const { parts, isError } = resultParts(message);
380
396
  const output = parts
381
397
  .map((part) => (part && typeof part.text === 'string' ? part.text : ''))
@@ -385,13 +401,13 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
385
401
  const code = data.error && typeof data.error.code === 'string' ? data.error.code : undefined;
386
402
  // 失败有两种写法:`message.isError` 与 `data.error.code`(宿主两种都发过),任一都算失败。
387
403
  const failed = isError || code !== undefined;
388
- turn.tools.set(src.callId, {
404
+ turn.tools.set(callId, {
389
405
  ...current,
390
406
  output: output.length > TEXT_MAX ? output.slice(0, TEXT_MAX) : output,
391
407
  ...(failed ? { error: code === 'interrupted' ? 'stopped' : 'error' } : { error: null }),
392
408
  ...(diffs ? { diffs } : {}),
393
409
  });
394
- refreshToolStep(turn, src.callId);
410
+ refreshToolStep(turn, callId);
395
411
  return;
396
412
  }
397
413
  if (event.type === 'turn/end') {
@@ -423,6 +439,64 @@ function liveStepsTurnOf(ctx, sessionId) {
423
439
  return turn && typeof turn.turnNo === 'number' ? turn.turnNo : null;
424
440
  }
425
441
 
442
+ /** 按需读取当前轮的完整事实;没有轮号时不把空壳发给客户端。 */
443
+ function liveTurnFactsOf(ctx, sessionId) {
444
+ if (!ctx || !sessionId) return null;
445
+ const turn = liveStepTurnOf(ctx).get(sessionId);
446
+ if (!turn || typeof turn.turnNo !== 'number') return null;
447
+ const facts = turnFactsSnapshot(turn.facts);
448
+ // 没有新事实不增加空控制帧;曾发过产出的轮撤销回空时仍必须发快照清除旧状态。
449
+ if (!turn.factsSentSnapshot && !facts.actualModel && !facts.modelTrail.length && !facts.producedFiles.length) return null;
450
+ return { turn: turn.turnNo, ...facts };
451
+ }
452
+
453
+ function liveTurnChangesOf(ctx, sessionId, wantedTurn, historyEntries) {
454
+ if (!ctx || !sessionId) return null;
455
+ const turn = liveStepTurnOf(ctx).get(sessionId);
456
+ if (!turn || turn.turnNo !== wantedTurn) return null;
457
+ if (!historyEntries) return turnChangesSnapshot(turn.facts);
458
+ // 仅为本次读取建临时副本,按 seq 合并授权历史;不抢直播单写者的写入权。
459
+ const merged = createTurnFacts();
460
+ for (const entry of historyEntries) {
461
+ const event = entry && entry.event ? entry.event : entry;
462
+ if (event && event.data && event.data.turn === wantedTurn) absorbTurnFact(merged, event);
463
+ }
464
+ for (const [key, fact] of turn.facts.events) {
465
+ if (!merged.events.has(key)) merged.events.set(key, fact);
466
+ }
467
+ rebuildTurnFacts(merged);
468
+ merged.truncated = merged.truncated || turn.facts.truncated;
469
+ return turnChangesSnapshot(merged);
470
+ }
471
+
472
+ function drainLiveTurnFacts(ctx, sessionId, writerId) {
473
+ if (!ctx || !sessionId || !writerAllows(ctx, sessionId, writerId)) return null;
474
+ const turn = liveStepTurnOf(ctx).get(sessionId);
475
+ if (!turn || turn.factsSentRevision === turn.facts.revision || typeof turn.turnNo !== 'number') return null;
476
+ turn.factsSentRevision = turn.facts.revision;
477
+ const snapshot = liveTurnFactsOf(ctx, sessionId);
478
+ if (!snapshot) return null;
479
+ const serialized = JSON.stringify(snapshot);
480
+ if (serialized === turn.factsSentSnapshot) return null;
481
+ turn.factsSentSnapshot = serialized;
482
+ return snapshot;
483
+ }
484
+
485
+ /** 从已授权的历史窗补齐直播事实,只吸游标之后的事件,不回放推理或参数增量。 */
486
+ function seedLiveTurnFacts(ctx, sessionId, entries, writerId) {
487
+ if (!ctx || !sessionId || !writerAllows(ctx, sessionId, writerId)) return;
488
+ const events = (entries || []).map((entry) => entry && entry.event ? entry.event : entry)
489
+ .filter(Boolean).sort((a, b) => (a.seq ?? Infinity) - (b.seq ?? Infinity));
490
+ for (const event of events) {
491
+ const data = event.data;
492
+ if (!data || typeof data.turn !== 'number') continue;
493
+ const existing = liveStepTurnOf(ctx).get(sessionId);
494
+ if (existing && existing.turnNo !== null && data.turn < existing.turnNo) continue;
495
+ const turn = turnForEvent(ctx, sessionId, data);
496
+ absorbTurnFact(turn.facts, event);
497
+ }
498
+ }
499
+
426
500
  /**
427
501
  * 取走「还没告诉过手机」的那几步。
428
502
  *
@@ -483,6 +557,10 @@ module.exports = {
483
557
  liveStepOf,
484
558
  liveStepsOf,
485
559
  liveStepsTurnOf,
560
+ liveTurnFactsOf,
561
+ liveTurnChangesOf,
562
+ drainLiveTurnFacts,
563
+ seedLiveTurnFacts,
486
564
  drainLiveSteps,
487
565
  clearLiveSteps,
488
566
  claimLiveWriter,
@@ -143,6 +143,7 @@ const MAP = Object.freeze({
143
143
  // 历史 blob 的实例密钥(HK):已配对设备的按需补发,纯只读。
144
144
  '/api/mobile/v1/history-key': V.VIEW,
145
145
  '/api/mobile/v1/session/step': V.VIEW,
146
+ '/api/mobile/v1/session/changes': V.VIEW,
146
147
  // 停止后的「本轮交代」:只读这一轮的步骤流、只算展示结构,能力面同 session/step。
147
148
  '/api/mobile/v1/session/stop-summary': V.VIEW,
148
149
  // 运行时间线:一轮跑过的每一步,只读历史与直播副本现折,不新增任何能力面。
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ /** 请求头里的真实模型身份:统计与会话事实共用,不依赖采集器或账本。 */
4
+ function requestModelOf(event) {
5
+ const config = event && event.data && event.data.header && event.data.header.config;
6
+ if (!config || typeof config.provider !== 'string' || !config.provider
7
+ || typeof config.model !== 'string' || !config.model) return null;
8
+ return { provider: config.provider, model: config.model };
9
+ }
10
+
11
+ function sameModel(left, right) {
12
+ return Boolean(left && right && left.provider === right.provider && left.model === right.model);
13
+ }
14
+
15
+ module.exports = { requestModelOf, sameModel };
@@ -65,6 +65,11 @@ const liveStepWriters = new WeakMap();
65
65
  // 的 attachLiveSteps / broadcastLiveSteps)。
66
66
  const liveStepSinks = new WeakMap();
67
67
 
68
+ // 直播中的工作流运行:这一轮收到的 `tool-workflow/*` 事件攒成一份、折成运行→阶段→成员
69
+ // (见 workflow-live.js)。与上面的直播过程副本同一类状态:属于宿主进程里「这一轮跑到哪」,
70
+ // 所以按 ctx 隔离、按会话分桶。
71
+ const workflowLiveStates = new WeakMap();
72
+
68
73
  // 隔离工作树的自动回收节流(见 worktree-lifecycle.js):上次跑的时刻与在途标记。
69
74
  // 收尾那一发挂在会话列表刷新上,是热点路径 —— 每台宿主各一份,不能跨 ctx 串。
70
75
  const isolationSweepStates = new WeakMap();
@@ -492,11 +497,22 @@ function liveStepSinkOf(ctx) {
492
497
  return state;
493
498
  }
494
499
 
500
+ /** 直播中的工作流运行:`ctx → Map<sessionId, { entries, runs }>`(见 workflow-live.js)。 */
501
+ function workflowLiveOf(ctx) {
502
+ let state = workflowLiveStates.get(ctx);
503
+ if (!state) {
504
+ state = new Map();
505
+ workflowLiveStates.set(ctx, state);
506
+ }
507
+ return state;
508
+ }
509
+
495
510
  module.exports = {
496
511
  canonicalDeviceKey,
497
512
  liveStepTurnOf,
498
513
  liveStepWriterOf,
499
514
  liveStepSinkOf,
515
+ workflowLiveOf,
500
516
  sessionModelsStateOf,
501
517
  invalidateSessionModels,
502
518
  dropSessionModelsForDevice,
@@ -0,0 +1,90 @@
1
+ 'use strict';
2
+
3
+ /** 按需读取某轮的已证实前后文本,只读会话事件/直播副本,不读工作区或 Git。 */
4
+ const { sendJson } = require('../shared/http-util');
5
+ const { callSessions } = require('./rpc.js');
6
+ const { unwrap } = require('./envelope.js');
7
+ const { foldTurnFacts, turnChangesSnapshot } = require('./turn-facts.js');
8
+ const { liveTurnChangesOf } = require('./live-steps.js');
9
+
10
+ const HISTORY_MESSAGES = 200;
11
+ const HISTORY_PAGES = 20;
12
+
13
+ function historyStatus(error) {
14
+ switch (error && error.code) {
15
+ case 'bad-request': return 400;
16
+ case 'session-not-found':
17
+ case 'subagent-not-found': return 404;
18
+ case 'subagent-unauthorized': return 403;
19
+ case 'host-unavailable': return 503;
20
+ default: return 502;
21
+ }
22
+ }
23
+
24
+ /** 有界、定向地向前翻到目标轮起点;第一发同时验证现有读会话/子代理权限。 */
25
+ async function readTurnEvents(ctx, sessionId, wantedTurn, address = {}, signal, maxPages = HISTORY_PAGES) {
26
+ const events = [];
27
+ let beforeSeq;
28
+ let turn = wantedTurn;
29
+ for (let page = 0; page < maxPages; page += 1) {
30
+ const { value, error } = unwrap(await callSessions(ctx, 'history', {
31
+ sessionId, ...address, maxMessages: HISTORY_MESSAGES,
32
+ ...(beforeSeq !== undefined ? { beforeSeq } : {}),
33
+ }, 'mobile', signal));
34
+ if (error) throw error;
35
+ const entries = value && Array.isArray(value.events) ? value.events : [];
36
+ const batch = entries.map((entry) => entry && entry.event ? entry.event : entry).filter(Boolean)
37
+ .sort((a, b) => (a.seq ?? Infinity) - (b.seq ?? Infinity));
38
+ if (turn === null || turn === undefined) {
39
+ for (const event of batch) {
40
+ if (event.data && typeof event.data.turn === 'number') turn = event.data.turn;
41
+ }
42
+ }
43
+ events.unshift(...batch);
44
+ const atStart = batch.some((event) => event.type === 'turn/start' && event.data && event.data.turn === turn);
45
+ const beforeTurn = batch.some((event) => event.data && typeof event.data.turn === 'number' && event.data.turn < turn);
46
+ if (atStart || beforeTurn || !value || value.hasMore !== true) return { events, turn, truncated: false };
47
+ const seqs = batch.map((event) => event.seq).filter(Number.isSafeInteger);
48
+ const oldest = seqs.length ? Math.min(...seqs) : null;
49
+ if (oldest === null || oldest === beforeSeq) return { events, turn, truncated: true };
50
+ beforeSeq = oldest;
51
+ }
52
+ return { events, turn, truncated: true };
53
+ }
54
+
55
+ /** GET sessionId/turn + 可选 parentSessionId/mode;返回 files:[{path,oldText?,newText?}]。 */
56
+ async function handleSessionChanges(ctx, req, res) {
57
+ const url = new URL(req.url, 'http://x');
58
+ const sessionId = url.searchParams.get('sessionId');
59
+ const rawTurn = url.searchParams.get('turn');
60
+ const turn = rawTurn !== null && /^\d+$/.test(rawTurn) ? Number(rawTurn) : null;
61
+ if (!sessionId || !Number.isSafeInteger(turn)) {
62
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 sessionId 和有效 turn' } });
63
+ }
64
+ const parentSessionId = url.searchParams.get('parentSessionId');
65
+ const mode = url.searchParams.get('mode');
66
+ const hasAddress = parentSessionId !== null || mode !== null;
67
+ if (hasAddress && (!parentSessionId || !parentSessionId.trim() || (mode !== 'one-shot' && mode !== 'continuable'))) {
68
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '子代理会话需要 parentSessionId 和有效 mode' } });
69
+ }
70
+ const address = hasAddress ? { parentSessionId, mode } : {};
71
+ const controller = new AbortController();
72
+ try {
73
+ const history = await readTurnEvents(ctx, sessionId, turn, address, controller.signal);
74
+ const facts = foldTurnFacts(history.events).get(turn);
75
+ const live = liveTurnChangesOf(ctx, sessionId, turn, history.events);
76
+ const details = live || (facts ? turnChangesSnapshot(facts) : { files: [] });
77
+ return sendJson(res, 200, {
78
+ ok: true, ...details,
79
+ ...(history.truncated ? { truncated: true } : {}),
80
+ });
81
+ } catch (error) {
82
+ const normalized = {
83
+ code: error && typeof error.code === 'string' ? error.code : 'host-call-failed',
84
+ message: error && typeof error.message === 'string' && error.message ? error.message : '读取这一轮的改动失败',
85
+ };
86
+ return sendJson(res, historyStatus(normalized), { ok: false, error: normalized });
87
+ }
88
+ }
89
+
90
+ module.exports = { handleSessionChanges, readTurnEvents, HISTORY_MESSAGES, HISTORY_PAGES };
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * 消息快照:镜像推送与 /messages 分页共用的折叠路径。
4
+ * 消息快照:镜像推送与 /messages 分页共用的折叠路径;裁剪前的上下文仍算未交付历史。
5
5
  *
6
6
  * buildMessagesSnapshot(不解析 query)与 handleMessages(解析 beforeSeq/afterSeq/limit)
7
7
  * 共用消息折叠逻辑。普通会话走 sessions.history;子代理必须携带 durable parent address,
@@ -158,7 +158,8 @@ async function handleMessages(ctx, req, res) {
158
158
  // 主路径,那两格字不许把整页拖住。`deriveMessages` 的缓存顺序:同一指纹第二次进来直接
159
159
  // 在 `derived-cache` 命中、交回同一个数组引用,本函数按引用记了 WeakMap,不再 stat 一次。
160
160
  const enriched = await withPresentedFileStats(ctx, sessionId, messages);
161
- const hasMore = !!(value && value.hasMore);
161
+ // lookback 只供折叠读上下文,没有交给客户端;即便宿主已到头,这一截仍要继续翻。
162
+ const hasMore = !!(value && value.hasMore) || !!(lookback && lookback.length);
162
163
  const items = wantThin
163
164
  ? thinEntryMessages(enriched, { hasMore })
164
165
  // 结构行(压缩 / 命令行)照发:它们由整段生命周期折出来,一次也就一两条,按 id 覆盖
@@ -31,10 +31,15 @@
31
31
  * `cacheWriteTokens` 事件里没有,恒 0。
32
32
  */
33
33
 
34
+ const fs = require('node:fs');
35
+ const path = require('node:path');
36
+
34
37
  const { unwrap } = require('./envelope.js');
35
38
  const { callSessions } = require('./rpc.js');
36
39
  const { sessionPreviewFor } = require('./session-preview.js');
40
+ const { dshHome } = require('../shared/paths');
37
41
  const ledger = require('./stats-ledger.cjs');
42
+ const { requestModelOf } = require('./request-model.cjs');
38
43
 
39
44
  /** 同一条会话两次采集之间的最小间隔(打开页面时的重复请求直接复用上一轮结果)。 */
40
45
  const COLLECT_INTERVAL_MS = 60_000;
@@ -113,6 +118,49 @@ const PERIODIC_PAGE_LIMIT = 3;
113
118
  const num = ledger.num;
114
119
  const billedOf = ledger.billedOf;
115
120
 
121
+ /** 会话日志文件名(与 `session-cleanup.cjs` 同一套:`session.v4.jsonl.zstd` 这类)。 */
122
+ const CANONICAL_LOG_FILENAME = /^session(?:\.v[1-9][0-9]*)?\.jsonl(?:\.zstd)?$/;
123
+
124
+ /**
125
+ * 会话 id → 磁盘上那份日志的绝对路径(宿主拿会话 id 当目录名)。
126
+ *
127
+ * **为什么要走一次盘**:跳过判据原先只看摘要的 `updatedAt`,而那个字段是宿主侧的「最后一次
128
+ * 提示时间」,日志在它之后还会继续写(一轮的 `assistant/message`、工具结果、子代理回包都晚
129
+ * 于最后一次用户输入)。2026-11-13 在真账本上核对:1134 条活会话里有 779 条的
130
+ * `seenUpdatedAt` 停在最后提示那一刻,其中 393 条的日志在那之后仍在增长 —— 它们被当成「一
131
+ * 点没动」跳过,那一截用量永远记不上。按会话统计下来,账本只覆盖了日志真实用量的七成上下。
132
+ *
133
+ * 走的是 `readdir` + `stat`,不是读日志:实测 1814 个日志目录整棵树 51ms、逐条 stat 10ms,
134
+ * 而它换掉的是「几十条会话各读一次事件流」那笔更贵的开销,一轮只做一次。
135
+ */
136
+ function sessionLogIndex() {
137
+ const index = new Map();
138
+ const visit = (directory) => {
139
+ let entries;
140
+ try { entries = fs.readdirSync(directory, { withFileTypes: true }); } catch { return; }
141
+ for (const entry of entries) {
142
+ const file = path.join(directory, entry.name);
143
+ if (entry.isDirectory()) { visit(file); continue; }
144
+ if (!CANONICAL_LOG_FILENAME.test(entry.name)) continue;
145
+ const sessionId = path.basename(directory);
146
+ if (!index.has(sessionId)) index.set(sessionId, file);
147
+ }
148
+ };
149
+ visit(path.join(dshHome(), 'sessions'));
150
+ return index;
151
+ }
152
+
153
+ /** 日志的成长指纹(字节数 + 修改时刻);拿不到就 null,调用方按「读不到就不跳过」处理。 */
154
+ function logStampOf(file) {
155
+ if (!file) return null;
156
+ try {
157
+ const stat = fs.statSync(file);
158
+ return { size: stat.size, mtime: Math.round(stat.mtimeMs) };
159
+ } catch {
160
+ return null;
161
+ }
162
+ }
163
+
116
164
  function normalizePath(value) {
117
165
  if (typeof value !== 'string') return '';
118
166
  return value.replace(/\/+$/, '');
@@ -300,9 +348,7 @@ function eventBodyOf(entry) {
300
348
 
301
349
  /** `request/header` 带的模型(`data.header.config` 里的 provider/model)。 */
302
350
  function headerModelOf(event) {
303
- const config = event && event.data && event.data.header && event.data.header.config;
304
- if (!config || typeof config !== 'object') return null;
305
- return ledger.sanitizeModelSelection({ provider: config.provider, model: config.model });
351
+ return ledger.sanitizeModelSelection(requestModelOf(event));
306
352
  }
307
353
 
308
354
  /** `tool/result` 指向的那次 `tool/call` 的 id。 */
@@ -668,6 +714,10 @@ async function collectOnce(ctx, options = {}) {
668
714
  const names = await workspaceNames(ctx);
669
715
  // 这一轮有没有真改过账本:定期采集在空闲时应当一个字节都不写。
670
716
  let touched = false;
717
+ // 会话 id → 日志路径:跳过判据要问「磁盘上那份还在长吗」(见下面的 `logStampOf`)。
718
+ // 一轮建一次:整棵目录 enumerate + 逐条 stat,实测不到一百毫秒,比它换掉的「几十条会话
719
+ // 各读一次事件流」便宜得多。定向补采也照建 —— 那一路只有几条会话,但判据本身要用到它。
720
+ const logFiles = sessionLogIndex();
671
721
 
672
722
  // 消失检测只在「采整份列表」时做:定向补采拿到的是子集,凭它判「会话没了」会误标。
673
723
  if (!wanted) {
@@ -747,10 +797,20 @@ async function collectOnce(ctx, options = {}) {
747
797
  //
748
798
  // `seenSeq` 由上一轮采集写下(见下面 `saved.seenSeq`),缺省 0 表示「还没有可信的
749
799
  // 游标对账」,这种情况一律不跳过。
800
+ //
801
+ // **2026-11-13 起再加一条:磁盘上那份日志必须没长过**。前面两个判据都是宿主自己报的
802
+ // 数,而它们在真机上会一起骗人:摘要 `updatedAt` 停在最后一次用户输入,游标也只追到
803
+ // 上一轮读到的位置 —— 两边一致、日志却一直在写,于是这条会话被永久跳过。指纹用
804
+ // 「字节数 + 修改时刻」(拿不到就当长过,宁可多读一轮),记在 `seenLogSize` /
805
+ // `seenLogMtime` 上,与这一轮读到的内容同一次落盘。
806
+ const stamp = logStampOf(logFiles.get(sessionId));
807
+ const logUnchanged = stamp !== null
808
+ && num(record && record.seenLogSize) === stamp.size
809
+ && num(record && record.seenLogMtime) === stamp.mtime;
750
810
  const seqCaughtUp = record
751
811
  && num(record.seenSeq) > 0
752
812
  && num(record.lastSeq) >= num(record.seenSeq);
753
- if (!options.force && seqCaughtUp && record.seenUpdatedAt
813
+ if (!options.force && seqCaughtUp && logUnchanged && record.seenUpdatedAt
754
814
  && num(summary.updatedAt) <= num(record.seenUpdatedAt)) {
755
815
  renameIfNeeded();
756
816
  if (await backfillModel(ctx, book, sessionId, record, now)) touched = true;
@@ -875,6 +935,17 @@ async function collectOnce(ctx, options = {}) {
875
935
  // `lastSeq` 对账(见上面那个跳过判据)。`truncated` 时不算数 —— 预算到点、翻页没翻完,
876
936
  // 那个位置不代表日志尾部,凭它记下等于把「没读完」当成「读完了」。
877
937
  if (!window.truncated) saved.seenSeq = Math.max(num(saved.seenSeq), num(window.newest));
938
+ // 这一轮那份日志的指纹:下一轮拿它和磁盘对账,没长过才允许跳过。
939
+ // 与 `seenSeq` 同一条规矩 —— 预算到点、翻页没翻完时那个位置不代表尾部,指纹也不记
940
+ // (记了就等于把「没读完」当成「读完了」)。
941
+ //
942
+ // 用的是**读之前**取的那一份(见上面 `const stamp`)。读的途中日志若又写了,指纹会
943
+ // 偏小,下一轮一对不上就再读一次 —— 偏保守的方向是多读一轮,而不是漏一段量。反过来
944
+ // 读完之后再取指纹就会把那批没折进去的事件算进「没长过」,那才是真的丢数。
945
+ if (!window.truncated && stamp) {
946
+ saved.seenLogSize = stamp.size;
947
+ saved.seenLogMtime = stamp.mtime;
948
+ }
878
949
  // 宿主累计只作诊断与差额对账用,按天记账不看它。
879
950
  saved.watermark = host;
880
951
  saved.collectedAt = now;