dsh-mobile-plugin 0.5.117 → 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.
- package/README.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +2 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/port-conflict.md +42 -0
- package/lib/client.js +28 -1
- package/lib/cloudflared/wiring.cjs +88 -10
- package/lib/impl.js +51 -6
- package/lib/mirror/pusher.cjs +150 -139
- package/lib/mobile/events.js +2 -1
- package/lib/mobile/host-bridge/event-synthesis.js +38 -10
- package/lib/mobile/host-web.js +52 -7
- package/lib/mobile/notification-prefs.js +2 -2
- package/lib/mobile/relay-control.js +10 -29
- package/lib/mobile/rpc.js +7 -4
- package/lib/mobile/session-cache.js +8 -0
- package/lib/mobile/sessions.js +26 -6
- package/lib/panel/index.html +13 -13
- package/lib/relay/address-slot.cjs +38 -0
- package/lib/relay/config-store.js +23 -0
- package/lib/relay/core.js +6 -0
- package/lib/relay/ingress-guard.cjs +111 -0
- package/lib/relay/lan-proxy.js +56 -2
- package/lib/relay/status.js +8 -0
- package/lib/remote/controller.cjs +19 -5
- package/lib/remote/shell.cjs +14 -1
- package/lib/routes/control-plane.js +38 -1
- package/lib/sidecar-facade-worker.cjs +17 -5
- package/lib/zeronews/runner.cjs +23 -6
- package/lib/zeronews/wiring.cjs +21 -2
- package/package.json +15 -15
package/lib/mirror/pusher.cjs
CHANGED
|
@@ -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') =>
|
|
849
|
+
const pushSessionNow = async (sessionId, priority = 'event') => {
|
|
828
850
|
try {
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
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
|
-
|
|
849
|
-
|
|
850
|
-
|
|
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
|
-
|
|
929
|
-
workspaces.buildWorkspacesBody(ctx)
|
|
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
|
-
|
|
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
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
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
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
return
|
|
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
|
|
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
|
-
|
|
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
|
|
1072
|
-
|
|
1073
|
-
);
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
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);
|
package/lib/mobile/events.js
CHANGED
|
@@ -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
|
-
/**
|
|
388
|
+
/** 设备级:工作区基线与全局投影并发接收,长流互不等待结束。 */
|
|
388
389
|
async function* deviceFrames(ctx, signal) {
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
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 时收窄成单会话视角。 */
|
package/lib/mobile/host-web.js
CHANGED
|
@@ -9,8 +9,13 @@
|
|
|
9
9
|
*
|
|
10
10
|
* 令牌是凭据,所以这条端点走 `guarded`——只有已配对设备拿得到,令牌也绝不进日志。
|
|
11
11
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
12
|
+
* 令牌有两条来路:老宿主的 `connection.browserAuth`,以及 0.2.3-alpha.1 起认证拆包后由
|
|
13
|
+
* `webserver/entry-url` 事件同步交回的入口。后者是兼容适配,事件名与字段格式属宿主内部
|
|
14
|
+
* 约定,本仓无法独立证实,待真机验证。
|
|
15
|
+
*
|
|
16
|
+
* 两个值都现取,不缓存:端口会被配置改,连接服务会随宿主重启换一份实例,令牌是否在同一
|
|
17
|
+
* 实例内轮换也无据可查(同步 emit 很便宜,宁可每次现取)。任何一环取不到都如实回
|
|
18
|
+
* 「不可用」,让 App 退回「请在电脑上打开网页版」;这里抛错只会把一次能力探测
|
|
14
19
|
* 变成一条 500,反而看不出是哪一格缺了。
|
|
15
20
|
*/
|
|
16
21
|
|
|
@@ -31,17 +36,57 @@ function hostPortOf(ctx) {
|
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
/**
|
|
34
|
-
*
|
|
39
|
+
* 新宿主兜底:主动派发一次 `webserver/entry-url`,让认证监听器把入口同步填进数组。
|
|
40
|
+
*
|
|
41
|
+
* baseUrl 用已知端口自拼,不调 `webServer.getOrigin()` —— 本仓只用 `webServer.port/.host`,
|
|
42
|
+
* 那个方法是否存在无法证实。事件名、入口的 `url` 字段和 `token` 参数也都是宿主内部约定,
|
|
43
|
+
* 本仓 0 命中;宿主再改版这条兜底会再失效,这是兼容适配不是根因已证。
|
|
44
|
+
*
|
|
45
|
+
* 只认环回且端口就是本插件 web 端口的入口:同一事件会跑所有监听器,别的服务的入口也带
|
|
46
|
+
* 自己的 token,不按 origin/host 过滤就会把凭据串给人家。
|
|
47
|
+
*/
|
|
48
|
+
function launchTokenFromEntries(ctx) {
|
|
49
|
+
const port = hostPortOf(ctx);
|
|
50
|
+
const webServer = ctx?.webServer;
|
|
51
|
+
if (port === null || !webServer || typeof ctx?.emit !== 'function') return null;
|
|
52
|
+
const entries = [];
|
|
53
|
+
ctx.emit(webServer, 'webserver/entry-url', `http://127.0.0.1:${port}`, entries);
|
|
54
|
+
if (!Array.isArray(entries)) return null;
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
const raw = entry && entry.url;
|
|
57
|
+
if (typeof raw !== 'string') continue;
|
|
58
|
+
let url;
|
|
59
|
+
try {
|
|
60
|
+
url = new URL(raw);
|
|
61
|
+
} catch {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (url.protocol !== 'http:') continue;
|
|
65
|
+
if (url.hostname !== '127.0.0.1' && url.hostname !== 'localhost') continue;
|
|
66
|
+
if (url.port !== String(port)) continue;
|
|
67
|
+
const token = url.searchParams.get('token');
|
|
68
|
+
if (typeof token === 'string' && token.length > 0) return token;
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 网页版的一次性登录令牌。
|
|
75
|
+
*
|
|
76
|
+
* 老宿主挂在连接服务的 `browserAuth` 上;0.2.3-alpha.1 起认证拆到独立包、这个字段被删掉,
|
|
77
|
+
* 就走 `webserver/entry-url` 同步收回(见 `launchTokenFromEntries`)。两条路都给不出才算
|
|
78
|
+
* 这台宿主现在没有令牌。
|
|
35
79
|
*
|
|
36
80
|
* 用 `ctx.get('connection')` 而不是把它写进 `inject`:注入一个这个宿主版本里没有的服务,
|
|
37
|
-
* 会让整行永远 pending(见 `host-bridge/transport.js` 里 `peerOf`
|
|
38
|
-
*
|
|
81
|
+
* 会让整行永远 pending(见 `host-bridge/transport.js` 里 `peerOf` 的注释)。值不是非空字符串
|
|
82
|
+
* 也算取不到。任何异常一律回 null,能力探测不该变成 500。
|
|
39
83
|
*/
|
|
40
84
|
function launchTokenOf(ctx) {
|
|
41
85
|
try {
|
|
42
86
|
const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : null;
|
|
43
|
-
const
|
|
44
|
-
|
|
87
|
+
const legacy = connection && connection.browserAuth ? connection.browserAuth.launchToken : null;
|
|
88
|
+
if (typeof legacy === 'string' && legacy.length > 0) return legacy;
|
|
89
|
+
return launchTokenFromEntries(ctx);
|
|
45
90
|
} catch {
|
|
46
91
|
return null;
|
|
47
92
|
}
|
|
@@ -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: '
|
|
41
|
+
done: 'ring',
|
|
42
42
|
failed: 'ring',
|
|
43
43
|
approval: 'ring',
|
|
44
44
|
question: 'ring',
|
|
@@ -31,6 +31,9 @@ const { probeInstanceId, verifyRelayRegistration } = require('../relay/verify.js
|
|
|
31
31
|
const { probeRelayHealth, relayFailureMessage } = require('../relay/relay-probe.js');
|
|
32
32
|
const { canListen } = require('../relay/port-allocator.cjs');
|
|
33
33
|
const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
|
|
34
|
+
// 地址分栏校验与面板保存路径共用同一份实现和文案(面板那条路曾只挡类型 / 长度,Tailscale
|
|
35
|
+
// 这类存了也不生效的地址能被默默存下)。
|
|
36
|
+
const { addressSlotProblem } = require('../relay/address-slot.cjs');
|
|
34
37
|
const { sendJson, readJsonBody } = require('../shared/http-util');
|
|
35
38
|
const WebSocket = require('ws');
|
|
36
39
|
const { controlWsUrl } = require('../relay/control.js');
|
|
@@ -354,33 +357,6 @@ function createRelayControlHandlers(deps) {
|
|
|
354
357
|
};
|
|
355
358
|
}
|
|
356
359
|
|
|
357
|
-
/**
|
|
358
|
-
* 地址分栏校验:什么地址能进哪个栏。返回一句中文错误,空串表示没问题。
|
|
359
|
-
*
|
|
360
|
-
* - 优先的局域网地址必须在这台电脑当前检测到的局域网 / 公网候选里(空串 = 清掉,合法)。
|
|
361
|
-
* 候选拿不到时(端口没监听 / 局域网关)不硬拦,交给排序层按「不在清单里」自然忽略。
|
|
362
|
-
* - 直连地址不能填成某条中转:两者是不同通道,串栏正是「局域网栏出现中转地址」的根源。
|
|
363
|
-
*/
|
|
364
|
-
function addressSlotProblem(patch) {
|
|
365
|
-
if (patch.preferredLanAddress) {
|
|
366
|
-
const view = addressView();
|
|
367
|
-
const candidates = [...(view.lan || []), ...(view.public || [])]
|
|
368
|
-
.map((item) => String((item && item.address) || '').trim()).filter(Boolean);
|
|
369
|
-
if (candidates.length && !candidates.includes(patch.preferredLanAddress)) {
|
|
370
|
-
return '优先的局域网地址不在这台电脑当前检测到的地址里';
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
if (patch.manualLanUrl) {
|
|
374
|
-
const want = core.normalizeRelayUrl(patch.manualLanUrl);
|
|
375
|
-
const relays = [state.relayUrl, state.publicRelayAddress, ...(Array.isArray(state.relayUrls) ? state.relayUrls : [])]
|
|
376
|
-
.map((url) => (typeof url === 'string' ? core.normalizeRelayUrl(url) : '')).filter(Boolean);
|
|
377
|
-
if (want && relays.includes(want)) {
|
|
378
|
-
return '直连地址不能填成中转地址:这两条是不同通道,请把中转填到中转那一栏';
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
return '';
|
|
382
|
-
}
|
|
383
|
-
|
|
384
360
|
/** 故障台账摘要:只给最近几条的 kind / 时间 / 一句话,**不带堆栈**。 */
|
|
385
361
|
function faultsView() {
|
|
386
362
|
const guard = typeof activeGuard === 'function' ? activeGuard() : null;
|
|
@@ -462,8 +438,13 @@ function createRelayControlHandlers(deps) {
|
|
|
462
438
|
}
|
|
463
439
|
// 「什么地址能进哪个栏」在宿主这一侧也核一遍:面板前端会核,但 APP 也可以直接推上来,
|
|
464
440
|
// 只靠前端等于没核。两类错误都当场拒:优先的局域网地址不在当前检测到的候选里;直连地址
|
|
465
|
-
// 填成了某条中转(两条是不同通道,串栏正是这个 bug
|
|
466
|
-
|
|
441
|
+
// 填成了某条中转(两条是不同通道,串栏正是这个 bug 的根源)。判据与面板保存路径共用
|
|
442
|
+
// `relay/address-slot.cjs`,避免两条路各写一遍又分叉。
|
|
443
|
+
const slotProblem = addressSlotProblem(
|
|
444
|
+
parsed.patch,
|
|
445
|
+
state,
|
|
446
|
+
typeof lanPortInUse === 'function' ? lanPortInUse() : state.lanPort,
|
|
447
|
+
);
|
|
467
448
|
if (slotProblem) {
|
|
468
449
|
return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: slotProblem } });
|
|
469
450
|
}
|