dsh-mobile-plugin 0.5.118 → 0.5.119

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.
@@ -1,3 +1,4 @@
1
+ // 清单先独立落地,正文补推换挂最新清单且不阻塞后续清单轮次。
1
2
  // blob后台轮次绑定effect代次,停止后不续发旧快照或记录迟到确认。
2
3
  'use strict';
3
4
 
@@ -190,6 +191,11 @@ function createMirrorPusher(deps) {
190
191
  // pushFingerprint:后者含轮转会话的消息水位与统计投影,每轮都不同。
191
192
  let lastPushedListRevision = '';
192
193
  let lastPushedWorkspacesRevision = '';
194
+ let listBuildEpoch = 0;
195
+ let latestLists = null;
196
+ let mirrorSendEpoch = 0;
197
+ let mirrorSettledEpoch = 0;
198
+ let listPushInFlight = null;
193
199
  const pushFingerprint = (payload) => {
194
200
  const parts = [
195
201
  `s:${payload.sessions && payload.sessions.revision ? payload.sessions.revision : ''}`,
@@ -570,6 +576,9 @@ function createMirrorPusher(deps) {
570
576
 
571
577
  // 镜像推送的唯一出口:所有 pushSync 都必须经此,保证状态与真实推送一致。
572
578
  const pushMirrorPayload = async (payload) => {
579
+ // 正文可能等过构建槽;发送时只携带此刻最新的一对清单,不能把旧清单随正文写回镜像。
580
+ if (latestLists) payload = { ...payload, ...latestLists.payload };
581
+ const lists = latestLists;
573
582
  // 每一次推上去的清单都顺手记一下规模(含短路那两条路径:手机侧栏看的就是这份清单)。
574
583
  noteMirrorList(payload && payload.sessions);
575
584
  if (!tunnelConnected()) {
@@ -595,6 +604,7 @@ function createMirrorPusher(deps) {
595
604
  lastPushedListRevision = listRevision;
596
605
  lastPushedWorkspacesRevision = workspacesRevision;
597
606
  lastPushedCreds = credsKey;
607
+ announceSessionsRevision(sessionsRevisionOf(payload.sessions));
598
608
  announceSessionActivity(payload.messages);
599
609
  // 镜像判重跳过时**仍然过一遍 blob**:blob 自己有指纹判重(推成功才记账),所以这里
600
610
  // 通常一条都不发;但上一轮 blob 推送失败、或设备集合刚变过,就得靠这一趟补上 ——
@@ -602,12 +612,24 @@ function createMirrorPusher(deps) {
602
612
  scheduleHistoryBlobs(payload, payload.creds);
603
613
  return false;
604
614
  }
615
+ const sendEpoch = ++mirrorSendEpoch;
605
616
  try {
606
617
  await getSidecar().pushSync(payload)
607
618
  } catch (error) {
608
619
  recordMirrorPush(false, error instanceof Error ? error.message : String(error))
609
620
  throw error
610
621
  }
622
+ // 并行 HTTP 的确认顺序不代表发送顺序;旧确认不能倒推清单、指纹或变更信号。
623
+ if (sendEpoch < mirrorSettledEpoch || (lists && (
624
+ sessionsRevisionOf(lists.payload.sessions) !== sessionsRevisionOf(latestLists?.payload.sessions)
625
+ || lists.payload.workspaces.revision !== latestLists?.payload.workspaces.revision
626
+ ))) {
627
+ // 正文已推成功,水位仍须到达;只保留当前清单中的会话,免得迟到确认复活已归档水位。
628
+ const currentIds = new Set((latestLists?.payload.sessions.items || []).map(item => String(item.sessionId)));
629
+ announceSessionActivity(Object.fromEntries(Object.entries(payload.messages || {}).filter(([id]) => currentIds.has(id))));
630
+ return false;
631
+ }
632
+ mirrorSettledEpoch = sendEpoch;
611
633
  lastPushedFingerprint = fingerprint;
612
634
  lastPushedCreds = credsKey;
613
635
  recordMirrorPush(true, null)
@@ -824,19 +846,12 @@ function createMirrorPusher(deps) {
824
846
  sessionSignal.retain(items.map((item) => String(item?.sessionId || '')).filter(Boolean));
825
847
  };
826
848
 
827
- const pushSessionNow = (sessionId, priority = 'event') => withSessionBuildSlot(priority, async () => {
849
+ const pushSessionNow = async (sessionId, priority = 'event') => {
828
850
  try {
829
- // 清单与消息快照并行:summary 用 Promise 传进去(见 buildSessionData 的注释),
830
- // 避免为了一个真实 updatedAt 把热路径改成串行两跳。
831
- const sessionsPromise = sessions.buildSessionsResponse(ctx, 'legacy');
832
- const summaryPromise = sessionsPromise.then(
833
- (body) => (body?.body?.items || []).find((s) => String(s.sessionId) === String(sessionId)),
834
- );
835
- const [sessionsBody, workspacesBody, data] = await Promise.all([
836
- sessionsPromise,
837
- workspaces.buildWorkspacesBody(ctx).then(observeWorkspaces),
838
- // event slot covers the full push; call the unlocked builder to avoid nesting the semaphore.
839
- buildSessionDataUnlocked(sessionId, summaryPromise, { reuseCache: false }),
851
+ const epoch = ++listBuildEpoch;
852
+ const [sessionsBody, workspacesBody] = await Promise.all([
853
+ buildSessionsList(),
854
+ workspaces.buildWorkspacesBody(ctx),
840
855
  ]);
841
856
  const wsBlocked = guardWorkspaces(workspacesBody) || guardSessions(sessionsBody)
842
857
  if (!(sessionsBody?.status === 200) || wsBlocked) {
@@ -845,9 +860,10 @@ function createMirrorPusher(deps) {
845
860
  noteSessionPushFailure(sessionId, new Error(reason));
846
861
  return;
847
862
  }
848
- retainSessionSignals(sessionsBody);
849
- // 这条路径刚刚真的扫过一遍目录:把结果记进缓存,后台 tick 接下来就不必再扫。
850
- rememberSessionsBody(sessionsBody);
863
+ rememberLists(sessionsBody, workspacesBody, epoch);
864
+ await pushListSnapshot();
865
+ const summary = sessionItemsOf(sessionsBody).find((s) => String(s.sessionId) === String(sessionId));
866
+ const data = await buildSessionData(sessionId, summary, { reuseCache: false, priority });
851
867
  await pushMirrorPayload({
852
868
  kind: 'sync', at: Date.now(),
853
869
  activeSessionId: sessionId,
@@ -872,7 +888,7 @@ function createMirrorPusher(deps) {
872
888
  noteSessionPushFailure(sessionId, e);
873
889
  process.stderr.write(`[dsh-mobile-plugin] mirror push failed for session ${sessionId}: ${message}\n`);
874
890
  }
875
- });
891
+ };
876
892
 
877
893
  // 按会话单飞。同一会话同一时刻只允许一次立即推送在途;在途期间再来事件只置一次待推
878
894
  // 标记,等这次推送结束后补推一次。没有它,一轮生成里的几百条事件会叠成几百次
@@ -924,22 +940,23 @@ function createMirrorPusher(deps) {
924
940
  // 失败时要知道是哪几个会话没推上去(catch 里逐个记一笔,交给 tick 定向补推)。
925
941
  let attempted = [];
926
942
  try {
943
+ const epoch = ++listBuildEpoch;
927
944
  const [sessionsBody, workspacesBody] = await Promise.all([
928
- sessions.buildSessionsResponse(ctx, 'legacy'),
929
- workspaces.buildWorkspacesBody(ctx).then(observeWorkspaces),
945
+ buildSessionsList(),
946
+ workspaces.buildWorkspacesBody(ctx),
930
947
  ]);
931
948
  const wsBlocked = guardWorkspaces(workspacesBody) || guardSessions(sessionsBody)
932
949
  if (!(sessionsBody?.status === 200) || wsBlocked) {
933
950
  recordMirrorPush(false, wsBlocked || 'sessions 快照不可用,本次未推送')
934
951
  return
935
952
  }
936
- retainSessionSignals(sessionsBody);
937
- rememberSessionsBody(sessionsBody);
953
+ rememberLists(sessionsBody, workspacesBody, epoch);
938
954
  const list = sessionsBody.body.items || [];
939
955
  const highPrio = sessionIds
940
956
  ? list.filter(s => sessionIds.includes(String(s.sessionId)))
941
957
  : list.filter(isHighPriority);
942
958
  attempted = highPrio;
959
+ await pushListSnapshot();
943
960
  const allMessages = {}; const allStats = {}; const allModels = {};
944
961
  await Promise.all(highPrio.map(async (s) => {
945
962
  const id = String(s.sessionId);
@@ -989,14 +1006,58 @@ function createMirrorPusher(deps) {
989
1006
  // 「宿主那边可能变了」:由事件流置起,成功重建清单后清掉。它把「每 500ms 盲目重扫」
990
1007
  // 换成「事件说变了才重扫」,而兜底窗保证即使漏了事件也不会长期停在旧数据上。
991
1008
  let listDirty = false;
1009
+ let listBuildInFlight = null;
1010
+ const buildSessionsList = async () => {
1011
+ while (listBuildInFlight) {
1012
+ const pending = listBuildInFlight;
1013
+ const body = await pending;
1014
+ if (listBuildInFlight && listBuildInFlight !== pending) continue;
1015
+ if (!listDirty) return body;
1016
+ }
1017
+ listDirty = false;
1018
+ const task = sessions.buildSessionsResponse(ctx, 'legacy', undefined, false, false, null, {
1019
+ awaitPreviews: false,
1020
+ onPreviewsReady: () => { listDirty = true; },
1021
+ });
1022
+ listBuildInFlight = task;
1023
+ try { return await task; }
1024
+ finally { if (listBuildInFlight === task) listBuildInFlight = null; }
1025
+ };
992
1026
 
993
1027
  const sessionItemsOf = (body) => (body && body.body && Array.isArray(body.body.items) ? body.body.items : []);
994
1028
 
995
1029
  /** 记下一份新构建出来的清单(只记成功的;「没取到」绝不能被后续轮次当成权威数据)。 */
996
- const rememberSessionsBody = (body) => {
997
- cachedSessionsBody = body;
998
- cachedSessionsAt = Date.now();
999
- listDirty = false;
1030
+ const rememberLists = (sessionsBody, workspacesBody, epoch, rebuilt = { sessions: true, workspaces: true }) => {
1031
+ if (latestLists && epoch < latestLists.epoch) return;
1032
+ latestLists = { epoch, payload: {
1033
+ sessions: sessionsBody.body,
1034
+ workspaces: workspacesBody,
1035
+ activeSessionId: sessionItemsOf(sessionsBody).find(s => s.running)?.sessionId || null,
1036
+ } };
1037
+ cachedSessionsBody = sessionsBody;
1038
+ cachedWorkspacesBody = workspacesBody;
1039
+ if (rebuilt.sessions) cachedSessionsAt = Date.now();
1040
+ if (rebuilt.workspaces) cachedWorkspacesAt = Date.now();
1041
+ retainSessionSignals(sessionsBody);
1042
+ observeWorkspaces(workspacesBody);
1043
+ };
1044
+
1045
+ // 同一份清单只独立推一次;正文载荷另有指纹,不会把每个会话事件变成额外清单推送。
1046
+ const pushListSnapshot = async () => {
1047
+ const payload = latestLists?.payload;
1048
+ if (!payload) return;
1049
+ const revision = sessionsRevisionOf(payload.sessions);
1050
+ if (!tunnelConnected()) { announceSessionsRevision(revision); return; }
1051
+ const workspaceRevision = payload.workspaces.revision || '';
1052
+ const credsKey = credsKeyOf(credentialDigests());
1053
+ const key = `${revision}|${workspaceRevision}|${credsKey}`;
1054
+ if (revision === lastPushedListRevision && workspaceRevision === lastPushedWorkspacesRevision
1055
+ && credsKey === lastPushedCreds) return;
1056
+ if (listPushInFlight?.key === key) return listPushInFlight.task;
1057
+ const task = pushMirrorPayload({ kind: 'sync', at: Date.now(), ...payload, messages: {}, stats: {}, models: {} });
1058
+ listPushInFlight = { key, task };
1059
+ try { await task; }
1060
+ finally { if (listPushInFlight?.task === task) listPushInFlight = null; }
1000
1061
  };
1001
1062
 
1002
1063
  /**
@@ -1006,13 +1067,53 @@ function createMirrorPusher(deps) {
1006
1067
  * 复用那一份时同样要保证信号基准是对的(它是幂等的)。守卫失败不覆盖旧缓存。
1007
1068
  */
1008
1069
  const loadWorkspacesBody = async (stale) => {
1009
- if (!stale && cachedWorkspacesBody) return observeWorkspaces(cachedWorkspacesBody) || cachedWorkspacesBody;
1010
- const body = await workspaces.buildWorkspacesBody(ctx).then(observeWorkspaces);
1011
- if (body && body.ok !== false) {
1012
- cachedWorkspacesBody = body;
1013
- cachedWorkspacesAt = Date.now();
1014
- }
1015
- return body;
1070
+ if (!stale && cachedWorkspacesBody) return cachedWorkspacesBody;
1071
+ return workspaces.buildWorkspacesBody(ctx);
1072
+ };
1073
+
1074
+ let bgBodyBusy = false;
1075
+ const processBgBodies = async (listChanged) => {
1076
+ if (bgBodyBusy) return;
1077
+ bgBodyBusy = true;
1078
+ try {
1079
+ const list = sessionItemsOf(cachedSessionsBody);
1080
+ const now = Date.now();
1081
+ const hasPendingRetry = sessionPushFailures.size > 0;
1082
+ if (hasPendingRetry) {
1083
+ const known = new Set(list.map(s => String(s.sessionId)));
1084
+ for (const id of [...sessionPushFailures.keys()]) if (!known.has(id)) sessionPushFailures.delete(id);
1085
+ }
1086
+ const retryId = dueRetries(now).find(id => list.some(s => String(s.sessionId) === id));
1087
+ if (retryId) await pushSessionNow(retryId, 'batch');
1088
+ const coldRotateDue = now - lastColdRotateAt >= BG_COLD_ROTATE_MIN_INTERVAL_MS;
1089
+ if (!listChanged && !coldRotateDue) return;
1090
+ lastColdRotateAt = now;
1091
+ if (bgQueuePos >= list.length) bgQueuePos = 0;
1092
+ for (let i = 0; i < list.length; i++) {
1093
+ const idx = (bgQueuePos + i) % list.length;
1094
+ const s = list[idx];
1095
+ const candidateId = s ? String(s.sessionId) : '';
1096
+ if (!s || sessionPushFailures.has(candidateId) || isHighPriority(s)) continue;
1097
+ const id = candidateId;
1098
+ const lists = latestLists.payload;
1099
+ try {
1100
+ const data = await buildSessionData(id, s, { priority: 'cold' });
1101
+ await pushMirrorPayload({
1102
+ kind: 'sync', at: Date.now(), ...lists,
1103
+ messages: data.messages ? { [id]: data.messages } : {},
1104
+ stats: data.stats ? { [id]: data.stats } : {},
1105
+ models: data.models ? { [id]: data.models } : {},
1106
+ });
1107
+ if (data.skipReason) recordMirrorPushSkipped(data.skipReason);
1108
+ } catch (error) {
1109
+ noteSessionPushFailure(id, error);
1110
+ const message = error instanceof Error ? error.message : String(error);
1111
+ process.stderr.write(`[dsh-mobile-plugin] cold mirror push failed for session ${id}: ${message}\n`);
1112
+ }
1113
+ bgQueuePos = (idx + 1) % list.length;
1114
+ break;
1115
+ }
1116
+ } finally { bgBodyBusy = false; }
1016
1117
  };
1017
1118
 
1018
1119
  const processBgQueue = async () => {
@@ -1030,7 +1131,6 @@ function createMirrorPusher(deps) {
1030
1131
  // 省掉构建开销,也避免每 tick 记一次推送失败。
1031
1132
  if (!online && !listSignal.watching()) return;
1032
1133
  bgQueueBusy = true;
1033
- let shouldAnnounceRevision = true;
1034
1134
  try {
1035
1135
  const now = Date.now();
1036
1136
  // 清单重建判据(见 BG_LIST_REBUILD_FALLBACK_MS):构建会话清单是**全目录扫描**,
@@ -1038,9 +1138,10 @@ function createMirrorPusher(deps) {
1038
1138
  // 扫描。变没变宿主的会话事件流本来就在说,所以这里只在三种时刻真去问宿主:
1039
1139
  // 从没构建过、有事件报告过变化(listDirty)、或距上次构建超过兜底窗。
1040
1140
  const listStale = !cachedSessionsBody || listDirty || now - cachedSessionsAt >= BG_LIST_REBUILD_FALLBACK_MS;
1141
+ const epoch = listStale ? ++listBuildEpoch : latestLists?.epoch || listBuildEpoch;
1041
1142
  let sessionsBody;
1042
1143
  if (listStale) {
1043
- sessionsBody = await sessions.buildSessionsResponse(ctx, 'legacy');
1144
+ sessionsBody = await buildSessionsList();
1044
1145
  // 空列表此前只是静默 return,看不出是「真的没会话」还是「没取到」;这里让守卫
1045
1146
  // 判定并记录理由,别再无声无息。
1046
1147
  const sessionsBlocked = guardSessions(sessionsBody);
@@ -1050,7 +1151,11 @@ function createMirrorPusher(deps) {
1050
1151
  if (online) recordMirrorPush(false, sessionsBlocked);
1051
1152
  return;
1052
1153
  }
1053
- rememberSessionsBody(sessionsBody);
1154
+ // 在线时与工作区成对提交;离线局域网只需要清单信号。
1155
+ if (!online && (!latestLists || epoch >= latestLists.epoch)) {
1156
+ cachedSessionsBody = sessionsBody;
1157
+ cachedSessionsAt = Date.now();
1158
+ }
1054
1159
  } else {
1055
1160
  sessionsBody = cachedSessionsBody;
1056
1161
  }
@@ -1065,113 +1170,19 @@ function createMirrorPusher(deps) {
1065
1170
  announceSessionsRevision(revision);
1066
1171
  return;
1067
1172
  }
1068
- const list = sessionItemsOf(sessionsBody);
1069
1173
  // 工作区体也是一份重活(含几十 KB 的归档会话 id 列表),判据与清单同一套:
1070
1174
  // 清单刚重建过、或过了兜底窗才重问宿主,否则复用上一份。
1071
- const workspacesBody = await loadWorkspacesBody(
1072
- listStale || !cachedWorkspacesBody || now - cachedWorkspacesAt >= BG_LIST_REBUILD_FALLBACK_MS,
1073
- );
1074
- const workspacesRevision = workspacesBody && typeof workspacesBody.revision === 'string' ? workspacesBody.revision : '';
1075
- if (list.length === 0) {
1076
- // 空清单**也要推**。守卫放行的空清单是「用户真的清空了」(body.emptyConfirmed
1077
- // 由 mobile/sessions.js 按 items.length === 0 现算),不推的话中转镜像里那份旧
1078
- // 清单会一直挂到 15s TTL 过期,手机上已删的会话最长还能看到十几秒;而且这条路径
1079
- // 完全不记账,运维看不出镜像为什么不动。
1080
- //
1081
- // 跨包契约:中转侧对「空覆盖非空」有同口径保护,只认 emptyConfirmed === true 的空
1082
- // 清单(中转的镜像状态里同一条谓词)。这里推的是 buildSessionsResponse 的原样 body,
1083
- // 天然带这个字段。
1084
- const wsBlockedEmpty = guardWorkspaces(workspacesBody);
1085
- if (wsBlockedEmpty) {
1086
- // 工作区那份快照不可用:别拿一份「没取到」的工作区去覆盖镜像,只广播清单。
1087
- recordMirrorPush(false, wsBlockedEmpty);
1088
- announceSessionsRevision(revision);
1089
- return;
1090
- }
1091
- await pushMirrorPayload({
1092
- kind: 'sync', at: Date.now(),
1093
- activeSessionId: null,
1094
- sessions: sessionsBody.body,
1095
- workspaces: workspacesBody,
1096
- messages: {}, stats: {}, models: {},
1097
- });
1098
- announceSessionsRevision(revision);
1099
- return;
1100
- }
1101
- // 清掉已经不在清单里的会话(归档/删除),免得这张表无限长。
1102
- const hasPendingRetry = sessionPushFailures.size > 0;
1103
- if (hasPendingRetry) {
1104
- const known = new Set(list.map((s) => String(s.sessionId)));
1105
- for (const id of [...sessionPushFailures.keys()]) if (!known.has(id)) sessionPushFailures.delete(id);
1106
- }
1107
- // 失败会话只允许到期后的定向路径重试;不能让它绕过退避落入 500ms 冷轮转。
1108
- // **重试是「额外补一次」,不是「这一轮的替代品」**:旧实现 retry 之后直接 return,
1109
- // 于是只要账本里有一个到期失败会话(真机上是常态——活跃/子会话读不到历史),
1110
- // 这一 tick 就永远停在重试上:冷轮转不跑、整份清单不推,镜像从此不再更新。
1111
- const retryId = dueRetries(now).find((id) => list.some((s) => String(s.sessionId) === id));
1112
- if (retryId) await pushSessionNow(retryId, 'batch');
1113
- const coldRotateDue = now - lastColdRotateAt >= BG_COLD_ROTATE_MIN_INTERVAL_MS;
1114
- // 摘要清单也是一份要推的内容:撤销一台设备时清单往往一个字都没变,只看 revision
1115
- // 会把这一轮挡回去,被撤销的手机要等到下一个轮转窗口才失去离线镜像。
1116
- if (revision === lastPushedListRevision && workspacesRevision === lastPushedWorkspacesRevision && credsKeyOf(credentialDigests()) === lastPushedCreds && !coldRotateDue) {
1117
- // 清单与工作区都没变、也还没到轮转时间:这一轮除了刚做的重试什么都不用做。
1118
- if (retryId) announceSessionsRevision(revision);
1119
- return;
1120
- }
1121
- lastColdRotateAt = now;
1122
- if (bgQueuePos >= list.length) bgQueuePos = 0;
1123
- for (let i = 0; i < list.length; i++) {
1124
- const idx = (bgQueuePos + i) % list.length;
1125
- const s = list[idx];
1126
- const candidateId = s ? String(s.sessionId) : '';
1127
- // Failed sessions are retried only by dueRetries; cold ticks must not bypass their backoff.
1128
- if (!s || sessionPushFailures.has(candidateId) || isHighPriority(s)) continue;
1129
- const id = candidateId;
1130
- let data;
1131
- try {
1132
- data = await buildSessionData(id, s, { priority: 'cold' });
1133
- } catch (error) {
1134
- // 单个会话构建失败只影响它自己:以前这里 rethrow,等于让一个读不到的会话
1135
- // 把这一 tick 的整份清单推送一起带走。
1136
- noteSessionPushFailure(id, error);
1137
- shouldAnnounceRevision = false;
1138
- const message = error instanceof Error ? error.message : String(error);
1139
- process.stderr.write(`[dsh-mobile-plugin] cold session build failed for ${id}: ${message}\n`);
1140
- bgQueuePos = (idx + 1) % list.length;
1141
- break;
1142
- }
1143
- const wsBlocked = guardWorkspaces(workspacesBody)
1144
- if (!wsBlocked) {
1145
- try {
1146
- await pushMirrorPayload({
1147
- kind: 'sync', at: Date.now(),
1148
- activeSessionId: list.find(s2 => s2.running)?.sessionId || null,
1149
- sessions: sessionsBody.body,
1150
- workspaces: workspacesBody,
1151
- messages: data.messages ? { [id]: data.messages } : {},
1152
- stats: data.stats ? { [id]: data.stats } : {},
1153
- models: data.models ? { [id]: data.models } : {},
1154
- });
1155
- if (data.skipReason) recordMirrorPushSkipped(data.skipReason);
1156
- } catch (error) {
1157
- // The payload helper already records the transport failure; add the session retry ledger
1158
- // here without rethrowing into the generic catch (which would double-count the failure).
1159
- noteSessionPushFailure(id, error);
1160
- shouldAnnounceRevision = false;
1161
- const message = error instanceof Error ? error.message : String(error);
1162
- process.stderr.write(`[dsh-mobile-plugin] cold mirror push failed for session ${id}: ${message}\n`);
1163
- }
1164
- } else {
1165
- recordMirrorPush(false, wsBlocked);
1166
- noteSessionPushFailure(id, new Error(wsBlocked));
1167
- shouldAnnounceRevision = false;
1168
- }
1169
- bgQueuePos = (idx + 1) % list.length;
1170
- break;
1171
- }
1172
- // 所有会话都是高优先(正在跑 / 5 分钟内动过)时上面一条都没推:这一 tick 唯一
1173
- // 能做的是把「清单变了」传下去。这类变更通常已经由事件路径推过镜像,广播是幂等的。
1174
- if (shouldAnnounceRevision) announceSessionsRevision(revision);
1175
+ const workspacesStale = listStale || !cachedWorkspacesBody || now - cachedWorkspacesAt >= BG_LIST_REBUILD_FALLBACK_MS;
1176
+ const workspacesBody = await loadWorkspacesBody(workspacesStale);
1177
+ const wsBlocked = guardWorkspaces(workspacesBody);
1178
+ if (wsBlocked) { recordMirrorPush(false, wsBlocked); return; }
1179
+ const listChanged = revision !== lastPushedListRevision
1180
+ || workspacesBody.revision !== lastPushedWorkspacesRevision;
1181
+ rememberLists(sessionsBody, workspacesBody, epoch, { sessions: listStale, workspaces: workspacesStale });
1182
+ // 清单先独立落地。冷正文与到期重试不持有 bgQueueBusy,后续 tick 仍能推进新清单。
1183
+ await pushListSnapshot();
1184
+ if (!tunnelConnected()) return;
1185
+ void processBgBodies(listChanged);
1175
1186
  } catch (e) {
1176
1187
  const message = e instanceof Error ? e.message : String(e);
1177
1188
  recordMirrorPush(false, message);
@@ -1,3 +1,4 @@
1
+ // 清单事件同时识别 event.type 与 event.data.type,正文仍只走会话流。
1
2
  // 转发设备事件,并按已鉴权实例登记可吊销的 SSE 连接。
2
3
  /**
3
4
  * 设备流响应声明心跳周期,供客户端检测首帧缺失。
@@ -112,7 +113,7 @@ function listRelevantPayload(rawPayload) {
112
113
  if (type === 'session/event') {
113
114
  const ev = rawPayload.event && typeof rawPayload.event === 'object' ? rawPayload.event : null;
114
115
  const inner = ev && ev.data && typeof ev.data === 'object' ? ev.data.type : undefined;
115
- if (LIST_EVENT_INNER.has(inner)) return lightPayload(rawPayload);
116
+ if (LIST_EVENT_INNER.has(ev && ev.type) || LIST_EVENT_INNER.has(inner)) return lightPayload(rawPayload);
116
117
  return null;
117
118
  }
118
119
  return null;
@@ -1,3 +1,4 @@
1
+ // 设备级工作区与会话控制流并发接收,并在取消或结束消费时一并回收。
1
2
  // 单会话 follow 仅按明确 activate 请求恢复 Agent;历史和被动订阅保持不激活。
2
3
  'use strict';
3
4
 
@@ -384,20 +385,47 @@ async function* projectionFrames(ctx, sessionId, signal) {
384
385
  }
385
386
  }
386
387
 
387
- /** 设备级:工作区基线 + 全局投影(没有 sessionId 时能给的就这些)。 */
388
+ /** 设备级:工作区基线与全局投影并发接收,长流互不等待结束。 */
388
389
  async function* deviceFrames(ctx, signal) {
389
- const workspace = await openStream(ctx, 'workspace', 'follow', {}, signal).catch(() => null);
390
- if (workspace) {
391
- for await (const frame of tolerate(workspace, 'workspace/follow', ctx)) {
392
- if (!frame) continue;
393
- if (frame.type === 'baseline' && frame.value) {
394
- yield { payload: { type: 'host/workspace', ...frame.value } };
395
- } else if (frame.type === 'increment' || frame.type === 'change') {
396
- yield { payload: { type: 'host/workspace', ...(frame.value && typeof frame.value === 'object' ? frame.value : { change: frame }) } };
390
+ const controller = new AbortController();
391
+ const abort = () => controller.abort();
392
+ signal?.addEventListener('abort', abort, { once: true });
393
+ if (signal?.aborted) abort();
394
+ const sources = [];
395
+ try {
396
+ const childSignal = controller.signal;
397
+ const workspace = openStream(ctx, 'workspace', 'follow', {}, childSignal);
398
+ sources.push((async function* () {
399
+ const frames = await workspace;
400
+ for await (const frame of tolerate(frames, 'workspace/follow', ctx)) {
401
+ if (!frame) continue;
402
+ if (frame.type === 'baseline' && frame.value) {
403
+ yield { payload: { type: 'host/workspace', ...frame.value } };
404
+ } else if (frame.type === 'increment' || frame.type === 'change') {
405
+ yield { payload: { type: 'host/workspace', ...(frame.value && typeof frame.value === 'object' ? frame.value : { change: frame }) } };
406
+ }
407
+ }
408
+ })());
409
+ sources.push(projectionFrames(ctx, null, childSignal));
410
+ const read = index => sources[index].next().then(step => ({ index, step }), error => ({ index, error }));
411
+ const pending = new Map(sources.map((_, index) => [index, read(index)]));
412
+ while (pending.size > 0) {
413
+ const winner = await Promise.race(pending.values());
414
+ if (winner.error) {
415
+ warn(ctx, `设备事件流中断:${winner.error.message || String(winner.error)}`);
416
+ pending.delete(winner.index);
417
+ } else if (winner.step.done) {
418
+ pending.delete(winner.index);
419
+ } else {
420
+ pending.set(winner.index, read(winner.index));
421
+ yield winner.step.value;
397
422
  }
398
423
  }
424
+ } finally {
425
+ controller.abort();
426
+ signal?.removeEventListener('abort', abort);
427
+ for (const source of sources) void source.return().catch(() => {});
399
428
  }
400
- yield* projectionFrames(ctx, null, signal);
401
429
  }
402
430
 
403
431
  /** 旧 `events.mux`:设备级帧流,带 sessionId 时收窄成单会话视角。 */
@@ -36,9 +36,9 @@ const EVENT_TYPES = Object.freeze(['done', 'failed', 'approval', 'question', 'pl
36
36
  /** 三档级别:响铃(通知 + 声音)/ 静默(通知栏不响)/ 关闭(不通知)。 */
37
37
  const LEVELS = Object.freeze(['ring', 'silent', 'off']);
38
38
 
39
- /** 缺省档:等你动手才响、完成类静默。 */
39
+ /** 缺省档:五类全响铃(2026-11-25 需求变更,原先完成类静默,装上就像没提示音)。 */
40
40
  const DEFAULT_EVENT_LEVELS = Object.freeze({
41
- done: 'silent',
41
+ done: 'ring',
42
42
  failed: 'ring',
43
43
  approval: 'ring',
44
44
  question: 'ring',
package/lib/mobile/rpc.js CHANGED
@@ -1,3 +1,4 @@
1
+ // 宿主列表仅在同一失效代次内合流,新变更后的读取不能复用旧 RPC。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -14,6 +15,7 @@
14
15
  */
15
16
 
16
17
  const { MOBILE_PROMPT_RPC_PREFIX } = require('./history-derive.js');
18
+ const { sessionListResponseState } = require('./session-cache.js');
17
19
 
18
20
  // 移动端提示词的 rpcId 约定与 user 消息回溯共用,前缀常量定义放在没有依赖的
19
21
  // history-derive 里(history-derive 要用 clientMessageIdFromSource,而会话模块
@@ -40,8 +42,9 @@ function callSessions(ctx, method, payload, rpcId = 'mobile', signal, options) {
40
42
  if (method !== 'list') return invoke();
41
43
  if (options && options.fresh) return invoke();
42
44
 
45
+ const epoch = sessionListResponseState(ctx).droppedAt || 0;
43
46
  const existing = sessionListInFlight.get(ctx);
44
- if (existing) return existing;
47
+ if (existing && existing.epoch === epoch) return existing.promise;
45
48
 
46
49
  let request;
47
50
  try {
@@ -53,15 +56,15 @@ function callSessions(ctx, method, payload, rpcId = 'mobile', signal, options) {
53
56
  }
54
57
  const tracked = request.then(
55
58
  value => {
56
- if (sessionListInFlight.get(ctx) === tracked) sessionListInFlight.delete(ctx);
59
+ if (sessionListInFlight.get(ctx)?.promise === tracked) sessionListInFlight.delete(ctx);
57
60
  return value;
58
61
  },
59
62
  error => {
60
- if (sessionListInFlight.get(ctx) === tracked) sessionListInFlight.delete(ctx);
63
+ if (sessionListInFlight.get(ctx)?.promise === tracked) sessionListInFlight.delete(ctx);
61
64
  throw error;
62
65
  },
63
66
  );
64
- sessionListInFlight.set(ctx, tracked);
67
+ sessionListInFlight.set(ctx, { epoch, promise: tracked });
65
68
  return tracked;
66
69
  }
67
70
 
@@ -1,3 +1,4 @@
1
+ // 清单变更会断开旧构建的合流引用,后续读取不能继续搭旧快照。
1
2
  // 会话缓存集中保存按 ctx 隔离的状态,持久化修订随服务身份换代。
2
3
  'use strict';
3
4
 
@@ -437,6 +438,9 @@ function writeIdempotencyStateOf(ctx) {
437
438
  * @param {string} [deviceKey] 只清这一台设备的缓存;缺省清掉该 ctx 下所有设备。
438
439
  */
439
440
  function invalidateSessionList(ctx, deviceKey) {
441
+ // 宿主 list 在 ctx 内共享,任一设备写入后都要换掉其底层合流代次。
442
+ const shared = sessionListResponseState(ctx);
443
+ shared.droppedAt = (shared.droppedAt || 0) + 1;
440
444
  const byDevice = sessionListResponseCache.get(ctx);
441
445
  if (!byDevice) return;
442
446
  const keys = deviceKey === undefined ? [...byDevice.keys()] : [deviceKey];
@@ -465,6 +469,8 @@ function invalidateSessionList(ctx, deviceKey) {
465
469
  * @param {string} [deviceKey] 只丢这一台设备的缓存;缺省丢掉该 ctx 下所有设备。
466
470
  */
467
471
  function dropSessionListCache(ctx, deviceKey) {
472
+ const shared = sessionListResponseState(ctx);
473
+ shared.droppedAt = (shared.droppedAt || 0) + 1;
468
474
  const byDevice = sessionListResponseCache.get(ctx);
469
475
  if (!byDevice) return;
470
476
  const keys = deviceKey === undefined ? [...byDevice.keys()] : [deviceKey];
@@ -473,6 +479,8 @@ function dropSessionListCache(ctx, deviceKey) {
473
479
  if (!state) continue;
474
480
  state.value = null;
475
481
  state.updatedAt = 0;
482
+ state.promise = null;
483
+ state.lastRevision = '';
476
484
  state.droppedAt = (state.droppedAt || 0) + 1;
477
485
  }
478
486
  }