dsh-mobile-plugin 0.5.118 → 0.5.120

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 (41) hide show
  1. package/README.md +2 -2
  2. package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +3 -2
  3. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network-guide.md +1 -1
  4. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +2 -4
  5. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/port-conflict.md +42 -0
  6. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay-server.md +1 -1
  7. package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +11 -15
  8. package/lib/cloudflared/wiring.cjs +88 -10
  9. package/lib/impl.js +59 -22
  10. package/lib/mirror/pusher.cjs +150 -139
  11. package/lib/mobile/channel-proxy.js +204 -0
  12. package/lib/mobile/channels.js +100 -0
  13. package/lib/mobile/events.js +2 -1
  14. package/lib/mobile/host-bridge/endpoints.js +3 -0
  15. package/lib/mobile/host-bridge/event-synthesis.js +38 -10
  16. package/lib/mobile/permissions.js +5 -2
  17. package/lib/mobile/push-notify.js +39 -106
  18. package/lib/mobile/rpc.js +7 -4
  19. package/lib/mobile/session-cache.js +8 -0
  20. package/lib/mobile/sessions.js +26 -6
  21. package/lib/panel/index.html +25 -25
  22. package/lib/relay/address-slot.cjs +1 -1
  23. package/lib/relay/config-store.js +23 -4
  24. package/lib/relay/control.js +2 -2
  25. package/lib/relay/core.js +27 -156
  26. package/lib/relay/ingress-guard.cjs +111 -0
  27. package/lib/relay/lan-proxy.js +56 -2
  28. package/lib/relay/pairing-check.cjs +181 -0
  29. package/lib/relay/pairing-payload.cjs +7 -19
  30. package/lib/relay/protocol.js +1 -2
  31. package/lib/relay/relay-probe.js +1 -1
  32. package/lib/relay/status.js +8 -0
  33. package/lib/remote/host-control.cjs +1 -1
  34. package/lib/routes/control-plane.js +53 -18
  35. package/lib/routes/mobile-api.js +11 -21
  36. package/lib/sidecar-facade-worker.cjs +18 -11
  37. package/lib/zeronews/runner.cjs +11 -3
  38. package/lib/zeronews/wiring.cjs +12 -2
  39. package/package.json +14 -13
  40. package/lib/mobile/notification-prefs.js +0 -205
  41. package/lib/mobile/push-notify-route.js +0 -37
@@ -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);
@@ -0,0 +1,204 @@
1
+ // 2026-11-26:手机够不着的渠道,由电脑代发模型请求(只转发模型调用,会话仍在手机上)。
2
+ 'use strict';
3
+
4
+ /**
5
+ * `POST /api/mobile/v1/channels/chat`:手机借这台电脑的手,向一条自建渠道发一次流式对话。
6
+ *
7
+ * 为什么需要:手机上的本机 Agent 是自己直连渠道的,但渠道地址可能是 `127.0.0.1`(Ollama、
8
+ * one-api 跑在这台电脑上)、或者只在内网可达 —— 手机拨不到。这样一条渠道不该变成「用不了」,
9
+ * 让电脑转一手就通了。
10
+ *
11
+ * 边界:**只转发模型调用这一层**。会话记录、手机侧的工具循环仍在手机上,这条路由不建会话、
12
+ * 不写任何日志、不碰工作区。请求体只收 OpenAI 兼容对话的四样东西(messages / model /
13
+ * tools / 生成参数),渠道的地址与 Key 一律用宿主自己那一份,手机给什么 id 就查什么 id。
14
+ *
15
+ * 回包是 SSE:把上游的 `data:` 逐条解析出来,按同一条流式通道(`writeSse`)回给手机 ——
16
+ * 协议 v2 的设备逐帧加密,与 `/session/stream` 同一套封装(见 `createFrameSealer`)。
17
+ * 上游中途失败时补一帧 `{ dshError }`,手机据此把它翻成界面上的失败原因。
18
+ */
19
+
20
+ const { readJsonBody } = require('../shared/http-util');
21
+ const { writeSse } = require('../shared/sse-write.js');
22
+ const { customChannelWithKey } = require('./channels.js');
23
+ const { createFrameSealer } = require('./stream.js');
24
+
25
+ /** 请求体上限:一条带图带文件的对话也远小于这个数。 */
26
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
27
+ /** 上游单次连接的超时:模型第一个字常常要等十几秒,给足。 */
28
+ const UPSTREAM_IDLE_MS = 120_000;
29
+
30
+ /** 渠道地址 → chat/completions 地址。规则与桌面端、手机端同一份:写了 `/v1` 就不再补。 */
31
+ function chatCompletionUrlOf(baseUrl) {
32
+ const root = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
33
+ if (root === '') return '';
34
+ return root.endsWith('/v1') ? `${root}/chat/completions` : `${root}/v1/chat/completions`;
35
+ }
36
+
37
+ /**
38
+ * 手机报上来的对话原样交给渠道:只放行 OpenAI 兼容的那几个字段,其余一律不转发。
39
+ *
40
+ * 不把整个 body 透传是有意的:透传等于让手机决定这次请求的地址、Key、流开关,
41
+ * 那就不再是「借电脑的手发一次对话」了。
42
+ */
43
+ function upstreamBodyOf(body, model) {
44
+ const pick = (key) => (body && typeof body === 'object' ? body[key] : undefined);
45
+ const messages = pick('messages');
46
+ const out = {
47
+ model,
48
+ stream: true,
49
+ messages: Array.isArray(messages) ? messages : [],
50
+ };
51
+ const tools = pick('tools');
52
+ if (Array.isArray(tools) && tools.length > 0) {
53
+ out.tools = tools;
54
+ out.tool_choice = pick('toolChoice') === 'none' ? 'none' : 'auto';
55
+ }
56
+ const maxTokens = Number(pick('maxTokens'));
57
+ if (Number.isFinite(maxTokens) && maxTokens > 0) out.max_tokens = Math.trunc(maxTokens);
58
+ const temperature = Number(pick('temperature'));
59
+ if (Number.isFinite(temperature) && temperature >= 0) out.temperature = temperature;
60
+ return out;
61
+ }
62
+
63
+ /** 一条 SSE 记录里的 `data:` 正文;不是 data 行就回 null(注释行、event 行都不算)。 */
64
+ function dataOfRecord(record) {
65
+ const lines = record.split('\n');
66
+ const parts = [];
67
+ for (const line of lines) {
68
+ if (!line.startsWith('data:')) continue;
69
+ parts.push(line.slice(5).replace(/^ /, ''));
70
+ }
71
+ return parts.length > 0 ? parts.join('\n') : null;
72
+ }
73
+
74
+ /**
75
+ * 把上游的字节流切成一条条 SSE 记录(空行分隔),逐条交出去。
76
+ *
77
+ * 只认 `\n\n`:OpenAI 兼容端点用的都是这个分隔符,`\r\n\r\n` 顺带兼容一下。
78
+ */
79
+ function createRecordSplitter(onRecord) {
80
+ let buffer = '';
81
+ return (chunk) => {
82
+ buffer += chunk;
83
+ for (;;) {
84
+ const at = buffer.search(/\r?\n\r?\n/);
85
+ if (at < 0) return;
86
+ const record = buffer.slice(0, at);
87
+ buffer = buffer.slice(at + (buffer[at] === '\r' ? 4 : 2));
88
+ if (record.trim() !== '') onRecord(record);
89
+ }
90
+ };
91
+ }
92
+
93
+ /** 上游回了一个非 2xx:把状态码原样带给手机,界面按同一套错误分类翻。 */
94
+ async function upstreamFailureOf(response) {
95
+ let detail = '';
96
+ try {
97
+ detail = (await response.text()).slice(0, 400);
98
+ } catch { /* 读不到正文就只报状态码 */ }
99
+ return detail;
100
+ }
101
+
102
+ /**
103
+ * POST /api/mobile/v1/channels/chat(token)
104
+ * { id, model, messages, tools?, toolChoice?, maxTokens?, temperature? }
105
+ * → SSE:上游的每条 `data:` 原样成帧;失败时补一帧 `{ dshError: { code, status? } }`。
106
+ */
107
+ async function handleChannelChat(ctx, req, res) {
108
+ const body = await readJsonBody(req, MAX_BODY_BYTES);
109
+ const id = body && typeof body.id === 'string' ? body.id.trim() : '';
110
+ const model = body && typeof body.model === 'string' ? body.model.trim() : '';
111
+ if (!id || !model) {
112
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
113
+ res.end(JSON.stringify({ ok: false, error: { code: 'bad-request', message: '需要渠道 id 与模型' } }));
114
+ return;
115
+ }
116
+
117
+ const found = await customChannelWithKey(ctx, id);
118
+ if (found.error) {
119
+ res.writeHead(found.status || 400, { 'content-type': 'application/json; charset=utf-8' });
120
+ res.end(JSON.stringify({ ok: false, error: found.error }));
121
+ return;
122
+ }
123
+ const url = chatCompletionUrlOf(found.channel.baseUrl);
124
+ if (url === '') {
125
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
126
+ res.end(JSON.stringify({ ok: false, error: { code: 'bad-request', message: '这条渠道没有可用地址' } }));
127
+ return;
128
+ }
129
+
130
+ const controller = new AbortController();
131
+ const closed = () => controller.abort();
132
+ res.on('close', closed);
133
+ const timer = setTimeout(closed, UPSTREAM_IDLE_MS);
134
+
135
+ let upstream;
136
+ try {
137
+ upstream = await fetch(url, {
138
+ method: 'POST',
139
+ signal: controller.signal,
140
+ headers: {
141
+ 'content-type': 'application/json',
142
+ accept: 'text/event-stream',
143
+ ...(found.apiKey === '' ? {} : { authorization: `Bearer ${found.apiKey}` }),
144
+ },
145
+ body: JSON.stringify(upstreamBodyOf(body, model)),
146
+ });
147
+ } catch (error) {
148
+ clearTimeout(timer);
149
+ res.off('close', closed);
150
+ res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' });
151
+ res.end(JSON.stringify({ ok: false, error: { code: 'upstream-unreachable', message: String(error && error.message).slice(0, 200) } }));
152
+ return;
153
+ }
154
+
155
+ if (!upstream.ok || !upstream.body) {
156
+ const detail = await upstreamFailureOf(upstream);
157
+ clearTimeout(timer);
158
+ res.off('close', closed);
159
+ res.writeHead(upstream.status || 502, { 'content-type': 'application/json; charset=utf-8' });
160
+ res.end(JSON.stringify({ ok: false, error: { code: 'upstream-failed', message: detail } }));
161
+ return;
162
+ }
163
+
164
+ // 协议 v2 的设备逐帧加密:封装器由请求那一步挂上的解封信息生成(见 createFrameSealer)。
165
+ // 要在 writeHead 之前算好,`x-dsh-proto` 只能在头发出去之前声明。
166
+ const sealFrame = createFrameSealer(req);
167
+ res.writeHead(200, {
168
+ 'content-type': 'text/event-stream; charset=utf-8',
169
+ 'cache-control': 'no-cache',
170
+ connection: 'keep-alive',
171
+ 'x-accel-buffering': 'no',
172
+ 'content-encoding': 'identity',
173
+ ...(sealFrame ? { 'x-dsh-proto': '2' } : {}),
174
+ });
175
+ res.write(': connected\n\n');
176
+
177
+ const pump = createRecordSplitter((record) => {
178
+ const data = dataOfRecord(record);
179
+ if (data === null || data === '[DONE]') return;
180
+ let payload;
181
+ try {
182
+ payload = JSON.parse(data);
183
+ } catch {
184
+ return; // 半截 / 非 JSON 的 data 直接跳过,别把坏帧塞给手机
185
+ }
186
+ writeSse(res, payload, { sealFrame });
187
+ });
188
+
189
+ try {
190
+ const decoder = new TextDecoder('utf-8');
191
+ for await (const chunk of upstream.body) {
192
+ if (controller.signal.aborted || res.writableEnded) break;
193
+ pump(decoder.decode(chunk, { stream: true }));
194
+ }
195
+ } catch {
196
+ if (!res.writableEnded) writeSse(res, { dshError: { code: 'upstream-interrupted' } }, { sealFrame });
197
+ } finally {
198
+ clearTimeout(timer);
199
+ res.off('close', closed);
200
+ try { res.end(); } catch { /* 已关闭 */ }
201
+ }
202
+ }
203
+
204
+ module.exports = { handleChannelChat, chatCompletionUrlOf, upstreamBodyOf, createRecordSplitter, dataOfRecord };