dsh-mobile-plugin 0.5.90 → 0.5.91

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.
Files changed (42) hide show
  1. package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +14 -3
  2. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv4.md +38 -0
  3. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv6.md +36 -0
  4. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/selfhost-common.md +44 -0
  5. package/docs/extension-authoring.md +4 -4
  6. package/extension-registry/index.json +5 -1
  7. package/host.js +7 -15
  8. package/lib/client.js +20 -12
  9. package/lib/host-compat.cjs +4 -1
  10. package/lib/host-preset-patches.cjs +40 -0
  11. package/lib/impl.js +30 -22
  12. package/lib/index.js +3 -0
  13. package/lib/mobile/agent-presets.js +12 -0
  14. package/lib/mobile/answer-sources.js +3 -2
  15. package/lib/mobile/archive-clean.js +5 -0
  16. package/lib/mobile/history-derive.js +3 -7
  17. package/lib/mobile/host-bridge/shims.js +20 -3
  18. package/lib/mobile/host-bridge.js +30 -1
  19. package/lib/mobile/live-steps.js +4 -3
  20. package/lib/mobile/plugin-self.js +4 -0
  21. package/lib/mobile/relay-control.js +63 -0
  22. package/lib/mobile/session-cache.js +12 -1
  23. package/lib/mobile/session-models.js +1 -1
  24. package/lib/mobile/session-presets.js +5 -2
  25. package/lib/mobile/session-send.js +0 -4
  26. package/lib/mobile/session-step.js +3 -2
  27. package/lib/mobile/stats-collect.cjs +26 -8
  28. package/lib/mobile/step-index.js +4 -3
  29. package/lib/mobile/subagents.js +0 -5
  30. package/lib/mobile/tool-result-state.js +12 -0
  31. package/lib/panel/index.html +27 -28
  32. package/lib/relay/lan-discovery.cjs +18 -3
  33. package/lib/relay/lan-proxy.js +22 -2
  34. package/lib/routes/control-plane.js +13 -2
  35. package/lib/session-cleanup.cjs +17 -0
  36. package/lib/shared/session-storage.cjs +82 -0
  37. package/lib/shell/first-install.js +102 -0
  38. package/lib/shell/updater.js +6 -5
  39. package/lib/sidecar-facade-worker.cjs +2 -0
  40. package/lib/tailcat/wiring.cjs +2 -2
  41. package/package.json +2 -2
  42. package/lib/mobile/ai-recipient.cjs +0 -61
@@ -1,3 +1,4 @@
1
+ // 归档清理在确认 JSONL 路由后才入队,SQLite 失败沿既有错误响应返回。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -18,6 +19,7 @@ const { invalidateSessionList } = require('./sessions.js');
18
19
  const { unwrap } = require('./envelope.js');
19
20
  const { collectStats, DELETING_COLLECT_BUDGET_MS } = require('./stats-collect.cjs');
20
21
  const { queueArchivedClearIds } = require('../session-cleanup.cjs');
22
+ const { assertSessionCleanupSupported, assertSessionCleanupStillJsonl } = require('../shared/session-storage.cjs');
21
23
 
22
24
  /**
23
25
  * 清理前这次补采的预算。
@@ -53,6 +55,8 @@ async function handleClearArchived(ctx, req, res) {
53
55
  const archivedIds = Array.isArray(workspaceResponse.value?.archivedSessionIds) ? workspaceResponse.value.archivedSessionIds : [];
54
56
  const selected = archivedIds.filter((id) => typeof id === 'string' && id);
55
57
  if (selected.length === 0) return { status: 200, body: { ok: true, deleted: 0 } };
58
+ const storageFailure = (error) => ({ status: 409, body: { ok: false, error: { code: error.code || 'session-cleanup-unsupported', message: error.message } } });
59
+ try { await assertSessionCleanupSupported(ctx, selected); } catch (error) { return storageFailure(error); }
56
60
  // 清理之前先把这批会话的用量最后采一次:之后再读它们的统计就没了(日志要删),
57
61
  // 而统计账本要保留历史 —— 漏掉这一刀,最后一段用量会凭空消失。
58
62
  // 采不上不挡清理:统计偏旧好过用户点不动这个按钮。
@@ -66,6 +70,7 @@ async function handleClearArchived(ctx, req, res) {
66
70
  } catch {
67
71
  /* 旁路 */
68
72
  }
73
+ try { await assertSessionCleanupStillJsonl(ctx, selected); } catch (error) { return storageFailure(error); }
69
74
  // 排不进队列就整次失败(路由回 500):回「已清理」却没排上,重启之后它们原样回来。
70
75
  queueArchivedClearIds(selected);
71
76
  // 宿主那份快照可能还带着它们,先在本进程压住:手机列表与归档列表立刻看不到。
@@ -1,3 +1,4 @@
1
+ // 历史工具卡、过程清单和补丁共用工具结果状态。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -246,7 +247,7 @@ function toolResultPatchesFor(events, items, options = {}) {
246
247
  }
247
248
  }
248
249
  return [...buildToolResultMap(events).entries()].map(([callId, result]) => {
249
- const state = result.isError ? (result.code === 'interrupted' ? 'stopped' : 'error') : 'ok';
250
+ const state = toolStepState(result);
250
251
  if (!bodies || delivered.has(callId)) return { callId, state };
251
252
  return {
252
253
  callId,
@@ -289,12 +290,7 @@ function parseBlocks(blocks, toolResults) {
289
290
  if (result) {
290
291
  output = result.output;
291
292
  images = result.images;
292
- // 对齐桌面 toolRowModel 状态派生:error.code === 'interrupted' → stopped, isError → error, ok
293
- if (result.isError) {
294
- state = result.code === 'interrupted' ? 'stopped' : 'error';
295
- } else {
296
- state = 'ok';
297
- }
293
+ state = toolStepState(result);
298
294
  }
299
295
  }
300
296
  out.push({
@@ -1,3 +1,4 @@
1
+ // 工作区快照读取已激活的宿主登记服务,缺服务时才取 Remote 跟随流。
1
2
  // 子代理目录保留 rc.5 名字与关系,根可用性由已验证的 catalog 创建链决定。
2
3
  'use strict';
3
4
  /** 没有 1:1 端点、需要跨端点合成或翻译的几处(翻页游标、模型目录、跟随流、投影基线)。 */
@@ -117,13 +118,29 @@ async function modelCatalog(ctx, payload, signal) {
117
118
  }
118
119
 
119
120
  /**
120
- * `workspace.list` → `workspace.follow` 的首帧 baseline。
121
+ * `workspace.list` 读取 Host 的完整工作区投影,缺登记服务时取 `workspace.follow` 首帧。
121
122
  *
122
- * 0.2.0 的 workspace 只有 follow(流),没有一次性 list;但它的 baseline 值恰好就是
123
- * 旧 list 的返回体(items + archivedSessionIds + pinnedSessionIds),所以取首帧即可。
123
+ * `ctx.get` 默认只返回已激活的服务,登记服务完成持久化加载与历史引导后才可读。
124
+ * 字段与宿主 WorkspaceFeed.baseline / workspaceView 一致,不依赖另行挂载的 Remote controller。
124
125
  */
125
126
  async function workspaceListViaFollow(ctx, signal) {
126
127
  try {
128
+ if (signal) signal.throwIfAborted();
129
+ const registry = ctx.get && ctx.get('workspaceRegistry');
130
+ if (registry) {
131
+ return ok({
132
+ items: registry.list().map(workspace => ({
133
+ workspaceId: workspace.id,
134
+ path: workspace.path,
135
+ title: workspace.title,
136
+ sessionIds: [...workspace.sessionIds],
137
+ createdAt: workspace.createdAt,
138
+ updatedAt: workspace.updatedAt,
139
+ })),
140
+ archivedSessionIds: [...registry.archivedSessionIds],
141
+ pinnedSessionIds: [...registry.pinnedSessionIds],
142
+ });
143
+ }
127
144
  const frames = await openStream(ctx, 'workspace', 'follow', {}, deadline(signal, SYNTHETIC_DEADLINE_MS));
128
145
  for await (const frame of frames) {
129
146
  if (frame && frame.type === 'baseline' && frame.value) return ok(frame.value);
@@ -57,6 +57,35 @@ function createApiProxy(ctx) {
57
57
  };
58
58
  }
59
59
 
60
+ /**
61
+ * apiProxy 服务本体:**启动即提供**、方法被调用时才决定走哪条路——
62
+ * 宿主自己的真服务在(旧运行时)就用它,不在(新运行时)就用上面那份网关兼容桥。
63
+ *
64
+ * 为什么要这样推迟判据:宿主的服务可能晚于本插件出现,而 App 打开后第一批接口
65
+ * (会话列表)随时可能打进来。若在服务尚未提供时读 `ctx.apiProxy`,cordis 会抛
66
+ * `cannot get property "apiProxy" without inject`——手机侧就是「加载会话列表失败」。
67
+ * 返回的代理让这个空档不存在:先有个可用对象,宿主那份一出现,下一次调用自动接上。
68
+ *
69
+ * @param {object} ctx 本代隔离上下文
70
+ * @param {() => object|null} hostProxyOf 取宿主真服务的取值器(取不到返回 null)
71
+ */
72
+ function createApiProxyService(ctx, hostProxyOf) {
73
+ const compat = createApiProxy(ctx);
74
+ return new Proxy(compat, {
75
+ get(target, prop, receiver) {
76
+ if (typeof prop !== 'symbol') {
77
+ const host = hostProxyOf();
78
+ if (host && prop in host) return host[prop];
79
+ }
80
+ return Reflect.get(target, prop, receiver);
81
+ },
82
+ has(target, prop) {
83
+ const host = hostProxyOf();
84
+ return (host != null && prop in host) || prop in target;
85
+ },
86
+ });
87
+ }
88
+
60
89
  /** 包存在时先等宿主提供旧协议服务,包缺席时直接使用网关兼容桥。 */
61
90
  function runtimeProvidesApiProxy() {
62
91
  try {
@@ -67,4 +96,4 @@ function runtimeProvidesApiProxy() {
67
96
  }
68
97
  }
69
98
 
70
- module.exports = { createApiProxy, runtimeProvidesApiProxy, UNAVAILABLE };
99
+ module.exports = { createApiProxy, createApiProxyService, runtimeProvidesApiProxy, UNAVAILABLE };
@@ -1,3 +1,4 @@
1
+ // 实时工具清单和详情共用持久化工具结果的状态口径。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -24,6 +25,7 @@ const TEXT_MAX = 200_000;
24
25
 
25
26
  const { liveStepTurnOf, liveStepWriterOf, liveStepSinkOf } = require('./session-cache.js');
26
27
  const { reasoningText, reasoningStepSummary, toolStepSummary } = require('./step-index.js');
28
+ const { toolResultState } = require('./tool-result-state.js');
27
29
  const { createTurnFacts, absorbTurnFact, rebuildTurnFacts, turnFactsSnapshot, turnChangesSnapshot, resultCallId } = require('./turn-facts.js');
28
30
 
29
31
  function bucketOf(ctx) {
@@ -399,12 +401,11 @@ function noteLiveEvent(ctx, sessionId, event, writerId) {
399
401
  .join('');
400
402
  const diffs = data.meta && Array.isArray(data.meta.diffs) ? data.meta.diffs : undefined;
401
403
  const code = data.error && typeof data.error.code === 'string' ? data.error.code : undefined;
402
- // 失败有两种写法:`message.isError` 与 `data.error.code`(宿主两种都发过),任一都算失败。
403
- const failed = isError || code !== undefined;
404
+ const state = toolResultState({ isError: isError || data.error != null, code });
404
405
  turn.tools.set(callId, {
405
406
  ...current,
406
407
  output: output.length > TEXT_MAX ? output.slice(0, TEXT_MAX) : output,
407
- ...(failed ? { error: code === 'interrupted' ? 'stopped' : 'error' } : { error: null }),
408
+ error: state === 'ok' ? null : state,
408
409
  ...(diffs ? { diffs } : {}),
409
410
  });
410
411
  refreshToolStep(turn, callId);
@@ -94,6 +94,8 @@ function snapshot(ctx) {
94
94
  shellChanged: false,
95
95
  autoUpdate: false,
96
96
  autoIntervalMs: null,
97
+ /** 没有外壳就读不到这个标记;按「不用提示」处理。 */
98
+ firstInstallPendingRestart: false,
97
99
  };
98
100
  }
99
101
  let raw = {};
@@ -114,6 +116,8 @@ function snapshot(ctx) {
114
116
  shellChanged: raw.shellChanged === true,
115
117
  autoUpdate: raw.autoUpdate === true,
116
118
  autoIntervalMs: typeof raw.autoIntervalMs === 'number' && Number.isFinite(raw.autoIntervalMs) ? raw.autoIntervalMs : null,
119
+ /** 第一次装进一台正在跑的 DSH、还没重启过:App 据此要求用户回电脑重启一次。 */
120
+ firstInstallPendingRestart: raw.firstInstallPendingRestart === true,
117
121
  };
118
122
  }
119
123
 
@@ -32,6 +32,51 @@ const { probeRelayHealth, relayFailureMessage } = require('../relay/relay-probe.
32
32
  const { canListen } = require('../relay/port-allocator.cjs');
33
33
  const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
34
34
  const { sendJson, readJsonBody } = require('../shared/http-util');
35
+ const WebSocket = require('ws');
36
+ const { controlWsUrl } = require('../relay/control.js');
37
+ const { openHistoryBlob } = require('../mirror/history-blob.cjs');
38
+
39
+ /**
40
+ * 让**电脑自己**去总控取一份「总控此刻存着的地址」并解开(用本机 HK),供「立即同步」直接比。
41
+ *
42
+ * 手机原来是自己连总控取这份——那就得先攥着总控令牌,重开 / 令牌换了就取不到,于是「立即同步」
43
+ * 恰在最需要它的场景失灵。电脑本来就握着令牌和 HK,让它顺手取回来交给手机比,手机就只需要
44
+ * 能连上插件这一件事。
45
+ *
46
+ * 取不到(没开上报 / 没令牌 / 没 HK / 暂离线 / 解不开)一律回 null,由上层如实说「没比成」。
47
+ */
48
+ function queryControlDirectory(url, token, instanceId, historyKey, timeoutMs = 4000) {
49
+ return new Promise((resolve) => {
50
+ if (!url || !token || !instanceId || !historyKey) return resolve(null);
51
+ let settled = false;
52
+ let ws = null;
53
+ const finish = (value) => {
54
+ if (settled) return;
55
+ settled = true;
56
+ clearTimeout(timer);
57
+ try { ws?.close(); } catch { /* 已关 */ }
58
+ resolve(value);
59
+ };
60
+ const timer = setTimeout(() => finish(null), timeoutMs);
61
+ timer.unref?.();
62
+ try {
63
+ const base = controlWsUrl(url);
64
+ ws = new WebSocket(`${base}/ws/app?instanceId=${encodeURIComponent(instanceId)}&token=${encodeURIComponent(token)}`);
65
+ ws.on('open', () => { try { ws.send(JSON.stringify({ type: 'watch' })); } catch { finish(null); } });
66
+ ws.on('message', (raw) => {
67
+ let msg;
68
+ try { msg = JSON.parse(typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8')); } catch { return; }
69
+ if (msg && msg.type === 'snapshot' && msg.online === false) return finish(null);
70
+ if (!msg || (msg.type !== 'snapshot' && msg.type !== 'update')) return;
71
+ const payload = typeof msg.payload === 'string' ? msg.payload : '';
72
+ if (!payload) return finish(null);
73
+ try { finish(openHistoryBlob(historyKey, 'control', instanceId, payload)); } catch { finish(null); }
74
+ });
75
+ ws.on('error', () => finish(null));
76
+ ws.on('close', () => finish(null));
77
+ } catch { finish(null); }
78
+ });
79
+ }
35
80
 
36
81
  /** 改配置的请求体上限:几个短字符串,4KB 很宽。 */
37
82
  const CONFIG_BODY_MAX = 4 * 1024;
@@ -217,6 +262,7 @@ function createRelayControlHandlers(deps) {
217
262
  getControl = null,
218
263
  syncControl = null,
219
264
  controlAddresses = null,
265
+ getHistoryKey = null,
220
266
  } = deps || {};
221
267
 
222
268
  /**
@@ -638,6 +684,21 @@ function createRelayControlHandlers(deps) {
638
684
  await new Promise((resolve) => setTimeout(resolve, CONTROL_SYNC_POLL_MS));
639
685
  snapshot = getControl() || {};
640
686
  }
687
+ // 让电脑自己把「总控此刻存着的地址」取回来、解开,一并发给手机:手机据此直接比对,
688
+ // 不再需要自己攥着总控令牌(那正是「重开 / 令牌失效就同步不了」的根源)。取不到就 null,
689
+ // 手机回退到老路径(自己连总控),行为不变。
690
+ let stored = null;
691
+ if (snapshot.published === true && snapshot.connected === true && typeof getHistoryKey === 'function') {
692
+ try {
693
+ const historyKey = getHistoryKey() || '';
694
+ const plain = await queryControlDirectory(snapshot.url, snapshot.token, state && state.instanceId, historyKey);
695
+ if (plain && Array.isArray(plain.addresses)) {
696
+ stored = plain.addresses
697
+ .map((item) => ({ kind: typeof item?.kind === 'string' ? item.kind : '', url: String(item?.url || '').trim() }))
698
+ .filter((item) => item.url);
699
+ }
700
+ } catch { stored = null; }
701
+ }
641
702
  sendJson(res, 200, {
642
703
  ok: true,
643
704
  control: {
@@ -646,6 +707,8 @@ function createRelayControlHandlers(deps) {
646
707
  published: snapshot.published === true,
647
708
  },
648
709
  addresses: typeof controlAddresses === 'function' ? controlAddresses() : [],
710
+ // 总控此刻存着的地址明文(电脑解好给手机比的);取不到为 null。
711
+ stored,
649
712
  at: Date.now(),
650
713
  });
651
714
  }
@@ -1,3 +1,4 @@
1
+ // 会话缓存集中保存按 ctx 隔离的状态,持久化修订随服务身份换代。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -143,12 +144,21 @@ function sessionListResponseState(ctx, deviceKey = 'legacy') {
143
144
  function sessionCleanupStateOf(ctx) {
144
145
  let state = deletedSessionState.get(ctx);
145
146
  if (!state) {
146
- state = { deleted: new Set() };
147
+ state = { deleted: new Set(), persistenceRevision: null };
147
148
  deletedSessionState.set(ctx, state);
148
149
  }
149
150
  return state;
150
151
  }
151
152
 
153
+ /** 会话存储观测状态:修订只在同一持久化服务身份内比较,不写进跨进程账本。 */
154
+ function sessionPersistenceRevisionStateOf(ctx, identity) {
155
+ const state = sessionCleanupStateOf(ctx);
156
+ if (!state.persistenceRevision || state.persistenceRevision.identity !== identity) {
157
+ state.persistenceRevision = { identity, sessions: new Map() };
158
+ }
159
+ return state.persistenceRevision;
160
+ }
161
+
152
162
  function rememberDeletedSessionIds(ctx, sessionIds) {
153
163
  const state = sessionCleanupStateOf(ctx);
154
164
  for (const sessionId of sessionIds) {
@@ -520,6 +530,7 @@ module.exports = {
520
530
  invalidateSessionList,
521
531
  rememberDeletedSessionIds,
522
532
  deletedSessionIdsOf,
533
+ sessionPersistenceRevisionStateOf,
523
534
  dropSessionListCache,
524
535
  sessionPreviewStateOf,
525
536
  sessionPreviewInFlightStateOf,
@@ -109,7 +109,7 @@ function safeModelsValue(value, language = 'en') {
109
109
  }
110
110
 
111
111
  function modelsBody(value, fetchedAt, language = 'en') {
112
- const result = { ok: true, ...safeModelsValue(value, language), capabilities: { expectedAiRecipient: true } };
112
+ const result = { ok: true, ...safeModelsValue(value, language) };
113
113
  const revision = result.revision;
114
114
  result.meta = {
115
115
  ...(result.meta && typeof result.meta === 'object' ? result.meta : {}),
@@ -1,3 +1,4 @@
1
+ // 预设清单保留宿主的异常诊断字符串,兼容旧版布尔状态。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -37,13 +38,15 @@ async function handleAgentPresets(ctx, req, res) {
37
38
  isDefault: item.isDefault === true,
38
39
  ...(typeof item.name === 'string' && item.name ? { name: item.name } : {}),
39
40
  ...(typeof item.description === 'string' && item.description ? { description: item.description } : {}),
40
- ...(item.broken === true ? { broken: true } : {}),
41
+ ...(typeof item.broken === 'string' && item.broken.trim()
42
+ ? { broken: item.broken }
43
+ : item.broken === true ? { broken: true } : {}),
41
44
  });
42
45
  }
43
46
  const body = {
44
47
  ok: true,
45
48
  presets,
46
- // 与条目内的 isDefault / broken 同口径:宿主只该给布尔,非布尔一律当 false,
49
+ // authorable / hasDocument 与 isDefault 只认布尔;broken 另有诊断字符串契约,
47
50
  // 不让 'yes' / 1 这种值被 App 当成「可以自己写预设」。
48
51
  authorable: value != null && value.authorable === true,
49
52
  hasDocument: value != null && value.hasDocument === true,
@@ -31,7 +31,6 @@ const { promptErrorObject, MODEL_UNAVAILABLE_ERROR } = require('./history-derive
31
31
  const { withIdempotency, requestIdOf } = require('./idempotency.js');
32
32
  const { invoke, UNAVAILABLE: GATEWAY_UNAVAILABLE } = require('./host-bridge/transport.js');
33
33
  const { selectSessionModel } = require('./host-bridge/session-model.js');
34
- const { expectedAiRecipientError } = require('./ai-recipient.cjs');
35
34
  const { recordSessionRead } = require('./session-last-turn.js');
36
35
  const { imageSizeOf } = require('./local-images.js');
37
36
  const attachmentStore = require('./attachment-store.js');
@@ -199,9 +198,6 @@ async function handleSend(ctx, req, res) {
199
198
  }
200
199
  }
201
200
 
202
- const recipientError = await expectedAiRecipientError(ctx, { sessionId: body.sessionId, expected: body.expectedAiRecipient, selection: modelSelection });
203
- if (recipientError) return sendJson(res, 400, { ok: false, error: recipientError });
204
-
205
201
  let promptResponse;
206
202
  try {
207
203
  promptResponse = await promptOnce(ctx, typeof body.clientMessageId === 'string' ? body.clientMessageId : '', {
@@ -1,4 +1,4 @@
1
- // 按步骤定位历史详情,并将连接取消传入所有回拉窗口。
1
+ // 按步骤定位详情、透传连接取消,并与历史清单共用工具状态。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -23,6 +23,7 @@ const { callSessions } = require('./rpc.js');
23
23
  const { requestSignal } = require('../shared/fresh-request');
24
24
  const { liveStepOf } = require('./live-steps.js');
25
25
  const { reasoningText, textOfParts } = require('./step-index.js');
26
+ const { toolResultState } = require('./tool-result-state.js');
26
27
 
27
28
  /** 详情单段文本的上限(参数 / 输出 / 思考全文各自适用)。 */
28
29
  const DETAIL_MAX_CHARS = 200_000;
@@ -155,7 +156,7 @@ async function historyStep(ctx, { sessionId, kind, callId, seq, index, resultSeq
155
156
  const failed = (envelope ? envelope.isError === true : false) || (message && message.isError === true);
156
157
  const code = result.data && result.data.error && typeof result.data.error.code === 'string'
157
158
  ? result.data.error.code : undefined;
158
- state = failed ? (code === 'interrupted' ? 'stopped' : 'error') : 'ok';
159
+ state = toolResultState({ isError: failed || result.data.error != null, code });
159
160
  const text = capText(textOfParts(parts));
160
161
  output = text.text;
161
162
  if (text.truncated) diffs = undefined;
@@ -1,3 +1,4 @@
1
+ // 用权威持久化修订判断事件增量,旧宿主保留 JSONL 文件水位。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -38,8 +39,10 @@ const { unwrap } = require('./envelope.js');
38
39
  const { callSessions } = require('./rpc.js');
39
40
  const { sessionPreviewFor } = require('./session-preview.js');
40
41
  const { dshHome } = require('../shared/paths');
42
+ const { readSessionStorage, sqliteRoutedSessionIds } = require('../shared/session-storage.cjs');
41
43
  const ledger = require('./stats-ledger.cjs');
42
44
  const { requestModelOf } = require('./request-model.cjs');
45
+ const { sessionPersistenceRevisionStateOf } = require('./session-cache.js');
43
46
 
44
47
  /** 同一条会话两次采集之间的最小间隔(打开页面时的重复请求直接复用上一轮结果)。 */
45
48
  const COLLECT_INTERVAL_MS = 60_000;
@@ -714,10 +717,16 @@ async function collectOnce(ctx, options = {}) {
714
717
  const names = await workspaceNames(ctx);
715
718
  // 这一轮有没有真改过账本:定期采集在空闲时应当一个字节都不写。
716
719
  let touched = false;
717
- // 会话 id → 日志路径:跳过判据要问「磁盘上那份还在长吗」(见下面的 `logStampOf`)。
718
- // 一轮建一次:整棵目录 enumerate + 逐条 stat,实测不到一百毫秒,比它换掉的「几十条会话
719
- // 各读一次事件流」便宜得多。定向补采也照建 —— 那一路只有几条会话,但判据本身要用到它。
720
- const logFiles = sessionLogIndex();
720
+ // 新宿主一次元数据列举替代逐条 stat;读取失败也不回落到可能已停止写入的旧 JSONL。
721
+ let storage = null;
722
+ let storageFailed = false;
723
+ try { storage = await readSessionStorage(ctx); } catch { storageFailed = true; }
724
+ const logFiles = !storage && !storageFailed ? sessionLogIndex() : new Map();
725
+ let routed = new Set();
726
+ if (!storage && !storageFailed) {
727
+ try { routed = sqliteRoutedSessionIds(); } catch { storageFailed = true; }
728
+ }
729
+ const revisionState = storage ? sessionPersistenceRevisionStateOf(ctx, storage.identity) : null;
721
730
 
722
731
  // 消失检测只在「采整份列表」时做:定向补采拿到的是子集,凭它判「会话没了」会误标。
723
732
  if (!wanted) {
@@ -803,10 +812,16 @@ async function collectOnce(ctx, options = {}) {
803
812
  // 上一轮读到的位置 —— 两边一致、日志却一直在写,于是这条会话被永久跳过。指纹用
804
813
  // 「字节数 + 修改时刻」(拿不到就当长过,宁可多读一轮),记在 `seenLogSize` /
805
814
  // `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;
815
+ // 挂载持久化服务时以其选中的逻辑日志为准;保留的迁移源不再参与跳过判断。
816
+ const snapshot = storage && storage.snapshots.get(sessionId);
817
+ const observed = snapshot && revisionState.sessions.get(sessionId);
818
+ const stamp = storage || storageFailed || routed.has(sessionId) ? null : logStampOf(logFiles.get(sessionId));
819
+ const logUnchanged = storage
820
+ ? !!(snapshot && observed && observed.revision === snapshot.revision && observed.lastSeq === record?.lastSeq
821
+ && (!Number.isSafeInteger(snapshot.eventCount) || num(record?.lastSeq) >= snapshot.eventCount - 1))
822
+ : stamp !== null
823
+ && num(record && record.seenLogSize) === stamp.size
824
+ && num(record && record.seenLogMtime) === stamp.mtime;
810
825
  const seqCaughtUp = record
811
826
  && num(record.seenSeq) > 0
812
827
  && num(record.lastSeq) >= num(record.seenSeq);
@@ -946,6 +961,9 @@ async function collectOnce(ctx, options = {}) {
946
961
  saved.seenLogSize = stamp.size;
947
962
  saved.seenLogMtime = stamp.mtime;
948
963
  }
964
+ if (snapshot && !window.truncated) {
965
+ revisionState.sessions.set(sessionId, { revision: snapshot.revision, lastSeq: saved.lastSeq });
966
+ }
949
967
  // 宿主累计只作诊断与差额对账用,按天记账不看它。
950
968
  saved.watermark = host;
951
969
  saved.collectedAt = now;
@@ -1,3 +1,4 @@
1
+ // 步骤摘要与工具结果状态保持历史、时间线和详情同源。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -8,6 +9,8 @@
8
9
  * 与详情端点(session-step)都从这里取,避免「清单里写一种说法、详情里又是另一种」。
9
10
  */
10
11
 
12
+ const { toolResultState } = require('./tool-result-state.js');
13
+
11
14
  /** 一步摘要的字数上限:清单是一行省略,再长也看不见,白白占线路。 */
12
15
  const STEP_SUMMARY_MAX = 72;
13
16
 
@@ -107,9 +110,7 @@ function toolStepSummary(name, rawArgs) {
107
110
 
108
111
  /** 工具结果的成败 → 一步的状态(与 App 那份 UI 用同一套词)。 */
109
112
  function toolStepState(result) {
110
- if (!result) return 'running';
111
- if (result.isError) return result.code === 'interrupted' ? 'stopped' : 'error';
112
- return 'ok';
113
+ return toolResultState(result);
113
114
  }
114
115
 
115
116
  /** 内容块里那段文本(工具结果两种形状都认,见 history-derive 的 toolResultParts)。 */
@@ -18,7 +18,6 @@ const { unwrap } = require('./sessions.js');
18
18
  const { promptOnceFor } = require('./session-cache.js');
19
19
  const { inlineUploadedImageBlocks } = require('./uploads.js');
20
20
  const { subagentPromptCapabilities } = require('./host-bridge/endpoints.js');
21
- const { expectedAiRecipientError } = require('./ai-recipient.cjs');
22
21
 
23
22
  // 子代理条数上限。长程会话实测能派到两百多个(反馈 #19 / #20),早先的 100 会把后面的整段
24
23
  // 静默截掉、手机上看不见也点不进。现在按实际数量取,只留一个防异常宿主的兜底量级。
@@ -255,10 +254,6 @@ async function handleSubagentPrompt(ctx, req, res) {
255
254
  // 续话与主会话发送走同一条重试链路(乐观行 + 超时后自动 / 手点重发),所以同样按
256
255
  // `clientMessageId` 去重:没有它,超时的那一发多半已经在子会话里说过了,重试会说第二遍
257
256
  // (口径见 session-cache 的 `promptOnceFor`)。
258
- const recipientError = await expectedAiRecipientError(ctx, {
259
- sessionId: childSessionId, expected: body.expectedAiRecipient, selection: body.modelSelection, child: true,
260
- });
261
- if (recipientError) return sendJson(res, 400, { ok: false, error: recipientError });
262
257
  const response = clientMessageId
263
258
  ? await promptOnceFor(ctx, `subagent:${parentSessionId}:${childSessionId}:${clientMessageId}`, call)
264
259
  : await call();
@@ -0,0 +1,12 @@
1
+ // 工具结果的取消、失败与成功状态由历史和实时路径共用。
2
+ 'use strict';
3
+
4
+ /** 已落定结果只按持久化错误码认取消;普通运行失败仍保留失败态。 */
5
+ function toolResultState(result) {
6
+ if (!result) return 'running';
7
+ const code = result.code;
8
+ if (code === 'interrupted' || code === 'ABORTED' || code === 'ABORTED_BEFORE_DISPATCH') return 'stopped';
9
+ return result.isError || code !== undefined ? 'error' : 'ok';
10
+ }
11
+
12
+ module.exports = { toolResultState };