dsh-mobile-plugin 0.5.78 → 0.5.80

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.
@@ -84,6 +84,10 @@ function controlAddresses(state, port) {
84
84
  seen.add(a.url);
85
85
  dedup.push(a);
86
86
  }
87
+ // 清单里本来就有可连地址、而 TCP 这一格是空的:再补一条**空 url 的 tcp 标记**。
88
+ // 手机据此把「电脑上清掉了 TCP 目标」落到本地;老手机读到空 url 直接忽略,行为不变。
89
+ // 一条别的地址都没有时不补:那种状态下手机也没别的路可学,补了只会白建一条总控连接。
90
+ if (!tcp && dedup.length) dedup.push({ kind: 'tcp', url: '' });
87
91
  return dedup;
88
92
  }
89
93
 
@@ -113,7 +117,11 @@ function controlMeta(state, connected = false) {
113
117
  * @param {() => boolean} [deps.getRelayConnected] 中转隧道此刻通没通(宿主侧权威状态)
114
118
  * @param {(msg: string, ...rest: any[]) => void} [deps.log]
115
119
  */
116
- function createControlClient({ state, persist, getPort, getHistoryKey, getAddresses, getRelayConnected, log = () => {} }) {
120
+ function createControlClient(options = {}) {
121
+ const { persist, getPort, getHistoryKey, getAddresses, getRelayConnected, log = () => {} } = options
122
+ // `getState` 让控制客户端读到**当前这一代**的状态(换代后状态对象会换一份):老的直接传
123
+ // `state` 的用法保留为兜底,测试与旧调用方行为不变。
124
+ const getState = typeof options.getState === 'function' ? options.getState : () => options.state
117
125
  const build = typeof getAddresses === 'function'
118
126
  ? getAddresses
119
127
  : (s) => controlAddresses(s, typeof getPort === 'function' ? getPort() : undefined);
@@ -122,7 +130,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
122
130
  let sock = null;
123
131
  let running = false;
124
132
  let connected = false;
125
- let token = typeof state.controlToken === 'string' ? state.controlToken : '';
133
+ let token = typeof getState().controlToken === 'string' ? getState().controlToken : '';
126
134
  let lastSent = '';
127
135
  let attempt = 0;
128
136
  let reconnectTimer = null;
@@ -137,7 +145,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
137
145
 
138
146
  function hk() {
139
147
  try {
140
- const value = typeof getHistoryKey === 'function' ? getHistoryKey() : state.historyKey;
148
+ const value = typeof getHistoryKey === 'function' ? getHistoryKey() : getState().historyKey;
141
149
  return typeof value === 'string' ? value : '';
142
150
  } catch {
143
151
  return '';
@@ -149,7 +157,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
149
157
  const key = hk();
150
158
  if (!key) return '';
151
159
  try {
152
- return sealHistoryBlob(key, 'control', state.instanceId || '', { addresses, meta });
160
+ return sealHistoryBlob(key, 'control', getState().instanceId || '', { addresses, meta });
153
161
  } catch (error) {
154
162
  log('control: seal failed', error && error.message);
155
163
  return '';
@@ -172,20 +180,22 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
172
180
 
173
181
  function connect() {
174
182
  if (!running || sock) return;
175
- if (!state.enabled) return;
176
- const addresses = build(state);
183
+ if (!getState().enabled) return;
184
+ // 用户在面板关掉了「自动上报网络地址」:立刻不连(sync/stop 会把已在连的这条也收掉)。
185
+ if (getState().controlReportEnabled === false) return;
186
+ const addresses = build(getState());
177
187
  if (!Array.isArray(addresses) || addresses.length === 0) {
178
188
  connected = false;
179
189
  return;
180
190
  }
181
- const meta = controlMeta(state, connectedOf());
191
+ const meta = controlMeta(getState(), connectedOf());
182
192
  const payload = seal(addresses, meta);
183
193
  if (!payload) {
184
194
  connected = false;
185
195
  return;
186
196
  }
187
197
  const tokenQuery = token ? `&token=${encodeURIComponent(token)}` : '';
188
- const url = `${controlWsUrl()}/ws/device?instanceId=${encodeURIComponent(state.instanceId || '')}${tokenQuery}`;
198
+ const url = `${controlWsUrl()}/ws/device?instanceId=${encodeURIComponent(getState().instanceId || '')}${tokenQuery}`;
189
199
  let ws;
190
200
  try {
191
201
  ws = new WebSocket(url);
@@ -216,7 +226,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
216
226
  if (msg && msg.type === 'registered' && typeof msg.token === 'string') {
217
227
  if (msg.token !== token) {
218
228
  token = msg.token;
219
- state.controlToken = msg.token;
229
+ getState().controlToken = msg.token;
220
230
  try { persist?.(); } catch { /* 落盘失败下次注册还会拿到同一枚,不必打断 */ }
221
231
  }
222
232
  } else if (msg && msg.type === 'error') {
@@ -236,9 +246,9 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
236
246
  /** 复核地址与健康有没有变,变了就重新加密并 update。 */
237
247
  function tick() {
238
248
  if (!connected || !sock) return;
239
- const addresses = build(state);
249
+ const addresses = build(getState());
240
250
  if (!Array.isArray(addresses) || addresses.length === 0) return;
241
- const meta = controlMeta(state, connectedOf());
251
+ const meta = controlMeta(getState(), connectedOf());
242
252
  const signature = canonical(addresses, meta);
243
253
  if (signature !== lastSent) {
244
254
  const payload = seal(addresses, meta);
@@ -259,7 +269,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
259
269
  tickTimer = setInterval(tick, 60_000);
260
270
  if (tickTimer.unref) tickTimer.unref();
261
271
  }
262
- if (state.enabled && !sock) connect();
272
+ if (getState().enabled && getState().controlReportEnabled !== false && !sock) connect();
263
273
  return snapshot();
264
274
  }
265
275
 
@@ -277,9 +287,9 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
277
287
  attempt = 0;
278
288
  }
279
289
 
280
- /** 配置变更后调用:没开 / 没地址 / 没 HK 就停;否则起连或复核。 */
290
+ /** 配置变更后调用:没开 / 用户关了上报 / 没地址 / 没 HK 就停;否则起连或复核。 */
281
291
  function sync() {
282
- if (!state.enabled || build(state).length === 0 || !hk()) {
292
+ if (!getState().enabled || getState().controlReportEnabled === false || build(getState()).length === 0 || !hk()) {
283
293
  stop();
284
294
  return;
285
295
  }
package/lib/relay/core.js CHANGED
@@ -56,6 +56,9 @@ function defaultState() {
56
56
  // 老状态文件没这一格时靠这里兜底,别在别处再判一次「没有就拒绝」。
57
57
  pairingTier: 'full',
58
58
  lanEnabled: true, lanPort: 18787, lanSecret: crypto.randomBytes(32).toString('hex'), enabled: false,
59
+ // 是否把本机的网络地址加密上报给「总控」(地址目录)。默认开:这正是本功能一直以来的
60
+ // 行为,做成开关只为了让不想要的人能关掉(关掉后手机换网、手里没新地址就找不回这台电脑)。
61
+ controlReportEnabled: true,
59
62
  // 中转侧 TUNNEL_REGISTER_SECRET 的对偶值。为空时隧道注册会被中转以
60
63
  // close(1008, 'bad registration secret') 拒掉(除非中转根本没开校验)。
61
64
  registerSecret: '',
@@ -65,9 +65,9 @@ function pairingPayload(state, lanPort) {
65
65
  ticket: state.pairingTicket || '',
66
66
  relayUrl: relay.relayUrl,
67
67
  lanUrls: urls,
68
- // 「TCP 直连」那一条:用户配的那条直连地址(`manualLanUrl`)里能当裸 TCP 目标的,只此
69
- // 一条、不掺网卡候选。App 用它当 `tcpTarget`(经本机回环 + 原生裸 TCP 出站,ATS 不参与)。
70
- // 没有可用的就整格不写,老 App 读到会忽略。
68
+ // 「TCP 直连」那一条:设置项 `manualTcpUrl` 里能当裸 TCP 目标的,只此一条、不掺网卡候选
69
+ // (与直连地址是两条,别混)。App 用它当 `tcpTarget`(经本机回环 + 原生裸 TCP 出站,ATS 不参与)。
70
+ // 没有可用的就整格不写 —— 二维码的字节数很贵,重配对时目标由 `/connection-info` 补。
71
71
  ...(() => {
72
72
  const tcp = tcpDirectTarget(state.manualTcpUrl);
73
73
  return tcp ? { tcpUrl: tcp } : {};
@@ -123,6 +123,9 @@ function createStatusView(deps) {
123
123
  // 审批自动审阅档(默认关,见 lib/mobile/auto-review.js)。面板与手机设置页都读这一格
124
124
  // 显示开关状态;非 true 一律当关,与 `configOf(state)` 的读法同一口径。
125
125
  approvalAutoReview: state.approvalAutoReview === true,
126
+ // 「自动上报网络地址」(总控上报)开关状态。面板据此显示开关;非 false 一律当开,
127
+ // 与 `configOf(state)` 的读法同一口径(老状态文件没这一格时默认开)。
128
+ controlReportEnabled: state.controlReportEnabled !== false,
126
129
  // 桌面设置页那两颗侧边栏图标的显示开关。**只给桌面客户端读**,手机端不画它们;
127
130
  // 老机器没落过这两格时按开处理,与 configOf 的默认值同一口径。
128
131
  desktopPhoneIcon: state.desktopPhoneIcon !== false,
@@ -577,13 +577,21 @@ function registerControlPlaneRoutes(deps) {
577
577
  // 为什么白名单是「节点公钥」而不是设备 id:隧道那一层只认 WireGuard 公钥,和移动端
578
578
  // 凭据是两套东西 —— 吊销设备凭据并不会把它从隧道白名单里摘掉(见 A3-86)。所以这里
579
579
  // 单独给一个出口,否则「踢一台手机」在隧道这一层无法完成。
580
- // 点对点隧道只有一格里要说的事:这条通道起没起、打通了没有、走的是谁。
581
- // 没有白名单也没有总开关 —— 能连上的前提就是私钥对得上,比白名单更直接;开关那件事
582
- // 交给手机侧的档位(`channelMode`),电脑这边不替人做决定。
580
+ // 点对点隧道只有格里要说的事:这条通道起没起、打通了没有、走的是谁。
581
+ // 助手默认关、用户显式开启才启动(与直连隧道同一口径);走不走这条通道仍由手机侧档位
582
+ // (`channelMode`)决定 —— 这里只管本机这半边准不准它起来。
583
583
  registerRoute({ kind: 'exact', path: '/api/relay/p2p', handler: localOnly('GET', async (_req, res) => {
584
584
  const state = deps.p2p && typeof deps.p2p.status === 'function' ? deps.p2p.status() : null
585
585
  sendJson(res, 200, { ok: true, status: state })
586
586
  }) })
587
+ registerRoute({ kind: 'exact', path: '/api/relay/p2p/enabled', handler: localOnly('POST', async (req, res) => {
588
+ const body = await readJson(req)
589
+ if (deps.p2p && typeof deps.p2p.setEnabled === 'function') {
590
+ deps.p2p.setEnabled(Boolean(body && body.enabled))
591
+ }
592
+ const state = deps.p2p && typeof deps.p2p.status === 'function' ? deps.p2p.status() : null
593
+ sendJson(res, 200, { ok: true, status: state })
594
+ }) })
587
595
 
588
596
  // ── FRP 直连:导入配置 → 落盘并拉起本地 frpc ───────────────────────────────
589
597
  //
@@ -988,6 +996,9 @@ function registerControlPlaneRoutes(deps) {
988
996
  // 审批自动审阅档(默认关)。只认布尔值,别的形状一律当没带 —— 这一个是安全开关,
989
997
  // 把 'false' / 0 静默解释成 false 会让「我明明关掉了」变成一句不可查的话。
990
998
  if (typeof body?.approvalAutoReview === 'boolean') patch.approvalAutoReview = body.approvalAutoReview
999
+ // 「自动上报网络地址」(总控上报)开关。只认布尔值,别的形状当没带 —— 'false' / 0 静默
1000
+ // 解释成关会让用户以为是自己关的,而界面上再也没处改回来。
1001
+ if (typeof body?.controlReportEnabled === 'boolean') patch.controlReportEnabled = body.controlReportEnabled
991
1002
  // 桌面侧边栏那两颗图标的显示开关。非布尔值当没带:'false' / 0 静默解释成隐藏,
992
1003
  // 用户会以为是自己关的,而界面上再也找不到那颗图标去改回来。
993
1004
  if (typeof body?.desktopPhoneIcon === 'boolean') patch.desktopPhoneIcon = body.desktopPhoneIcon
@@ -1340,8 +1351,9 @@ const WEB_ACCESS_ROUTES = new Set([
1340
1351
  // 但仍留在窗口白名单里保持「路由都在白名单」这条语义统一。
1341
1352
  '/api/relay/frp/import',
1342
1353
  '/api/relay/frp/stop',
1343
- // 点对点隧道的现状(只有查看,没有开关也没有白名单:能连上的前提就是密钥对得上)。
1354
+ // 点对点隧道的现状与启停(没有白名单:能连上的前提就是密钥对得上)。
1344
1355
  '/api/relay/p2p',
1356
+ '/api/relay/p2p/enabled',
1345
1357
  '/api/relay/revoke-all',
1346
1358
  '/api/relay/config',
1347
1359
  '/api/relay/check-port',
@@ -1382,6 +1394,7 @@ const LOCAL_OPERATOR_ROUTES = new Set([
1382
1394
  '/api/relay/devices/permissions',
1383
1395
  '/api/relay/tailcat/enabled',
1384
1396
  '/api/relay/tailcat/revoke',
1397
+ '/api/relay/p2p/enabled',
1385
1398
  // FRP 直连的启停:会拉起/杀掉本机进程,属于只允许本机或局域网直连的动作。
1386
1399
  '/api/relay/frp/import',
1387
1400
  '/api/relay/frp/stop',
@@ -413,12 +413,10 @@ function registerMobileRoutes(deps) {
413
413
  lanUrls: candidates,
414
414
  lanCandidates: candidates,
415
415
  ipv6Candidates: ipv6,
416
- // 「TCP 直连」目标:从用户配的那条直连地址(manualLanUrl)解出来,只此一条、不掺网卡候选。
417
- // 与二维码里那颗同源,手机定期核对时据此刷新,保证「改了连接地址、TCP 跟着变」。
418
- ...(() => {
419
- const tcpUrl = tcpDirectTarget(state.manualTcpUrl)
420
- return tcpUrl ? { tcpUrl } : {}
421
- })(),
416
+ // 「TCP 直连」目标:从设置项 `manualTcpUrl` 解出来,只此一条、不掺网卡候选(与二维码同一来源)。
417
+ // **始终带这一格**(没配时是空串):手机据此分清「老宿主不认识这格」(整格不出现,别动它手上
418
+ // 那条)与「电脑上把目标清掉了」(空串,手机要跟着清)。只在有值时才报,会让清空永远传不下去。
419
+ tcpUrl: tcpDirectTarget(state.manualTcpUrl),
422
420
  updatedAt: lanUpdatedAt,
423
421
  lastSeen: lanUpdatedAt,
424
422
  })
@@ -857,7 +855,8 @@ function registerMobileRoutes(deps) {
857
855
 
858
856
  // 对话页长连接:一条手机 WS 上的双向多路复用(帧契约见 docs/mux-long-connection-design.md §11)。
859
857
  // 与 preview 一样是 WebSocket 升级路由,鉴权在服务自己里做(设备凭据有效即可)。
860
- registerUpgradeRoute({ path: '/api/mobile/v1/mux', handler: mux.handleUpgrade })
858
+ // mux 已归稳定外壳持有时,升级路由由外壳直接挂(换代不摘、已建立的 WS 不断),这里不再重复注册。
859
+ if (!deps.muxOwnedByShell) registerUpgradeRoute({ path: '/api/mobile/v1/mux', handler: mux.handleUpgrade })
861
860
 
862
861
  }
863
862
 
@@ -74,6 +74,167 @@ export function createRuntime() {
74
74
  let swapping = null
75
75
  /** 在飞请求计数(`beginRequest` / `endRequest` 维护)。 */
76
76
  let inFlight = 0
77
+
78
+ // ── 蓝绿路由分发表 ───────────────────────────────────────────────────
79
+ // 六条传输都归外壳之后,新旧两代可以短暂并存:新一代把它注册的路由登记到 stage 表,并给每个
80
+ // 路径挂一个**稳定分派器**(每个路径只挂一次,分派器读 live 表)。提交时原子把 live 指向
81
+ // 新代、旧代继续服务在飞请求,排空后再卸。这样换代码那一刻没有「路由暂缺 / 404」的空窗,
82
+ // 也不会因为新旧两代注册同一路径撞「duplicate route」。
83
+ let applying = false
84
+ let liveHttp = new Map()
85
+ let liveUp = new Map()
86
+ let stageHttp = null
87
+ let stageUp = null
88
+ const httpDispatchers = new Map() // path -> unregister
89
+ const upDispatchers = new Map()
90
+ let dispatchServer = null
91
+ let dispatchOuter = null
92
+ let dispatchOuterUpgrade = null
93
+
94
+ /** 外壳把真实服务器的原始 register/registerUpgrade 交给运行时(只调一次)。 */
95
+ function installDispatch(server, outer, outerUpgrade) {
96
+ dispatchServer = server
97
+ dispatchOuter = typeof outer === 'function' ? outer : null
98
+ dispatchOuterUpgrade = typeof outerUpgrade === 'function' ? outerUpgrade : null
99
+ }
100
+
101
+ /** 给 route.handler 外面套「进 +1 / 出 -1」;拿不到 handler 原样返回。 */
102
+ function wrapInFlight(route) {
103
+ if (!route || typeof route.handler !== 'function') return route
104
+ const handler = route.handler
105
+ route.handler = async (req, res) => {
106
+ inFlight += 1
107
+ try { return await handler(req, res) } finally { inFlight = Math.max(0, inFlight - 1) }
108
+ }
109
+ return route
110
+ }
111
+
112
+ function ensureHttpDispatcher(path, sample) {
113
+ if (httpDispatchers.has(path) || !dispatchServer || !dispatchOuter) return
114
+ const dispatcher = {
115
+ kind: sample && sample.kind,
116
+ path,
117
+ handler: async (req, res) => {
118
+ const live = liveHttp.get(path)
119
+ if (!live || typeof live.handler !== 'function') {
120
+ try { res.statusCode = 404 } catch { /* ignore */ }
121
+ try { res.end && res.end('') } catch { /* ignore */ }
122
+ return
123
+ }
124
+ return live.handler(req, res)
125
+ },
126
+ }
127
+ const unregister = dispatchOuter.call(dispatchServer, wrapInFlight(dispatcher))
128
+ httpDispatchers.set(path, typeof unregister === 'function' ? unregister : () => {})
129
+ }
130
+
131
+ function ensureUpDispatcher(path, sample) {
132
+ if (upDispatchers.has(path) || !dispatchServer || !dispatchOuterUpgrade) return
133
+ const dispatcher = {
134
+ ...(sample || {}),
135
+ handler: (req, socket, head) => {
136
+ const live = liveUp.get(path)
137
+ if (!live || typeof live.handler !== 'function') {
138
+ try { if (socket) socket.destroy() } catch { /* ignore */ }
139
+ return
140
+ }
141
+ return live.handler(req, socket, head)
142
+ },
143
+ }
144
+ const unregister = dispatchOuterUpgrade.call(dispatchServer, dispatcher)
145
+ upDispatchers.set(path, typeof unregister === 'function' ? unregister : () => {})
146
+ }
147
+
148
+ /** 代注册一条 HTTP 路由。装在分发表里;只有「外壳自己的路由」(非装载期)才直挂真服务器。 */
149
+ function registerRoute(route, outer, thisArg) {
150
+ if (!applying) return outer.call(thisArg, wrapInFlight(route))
151
+ if (!route || typeof route.path !== 'string') return () => {}
152
+ stageHttp.set(route.path, route)
153
+ ensureHttpDispatcher(route.path, route)
154
+ return () => {}
155
+ }
156
+
157
+ /** 代注册一条升级(WebSocket)路由,同上。 */
158
+ function registerUpgradeRoute(route, outer, thisArg) {
159
+ if (!applying) return outer.call(thisArg, route)
160
+ if (!route || typeof route.path !== 'string') return () => {}
161
+ stageUp.set(route.path, route)
162
+ ensureUpDispatcher(route.path, route)
163
+ return () => {}
164
+ }
165
+
166
+ function beginActivation() {
167
+ applying = true
168
+ stageHttp = new Map()
169
+ stageUp = new Map()
170
+ }
171
+
172
+ /** 原子提交:live 指向新代;旧代有、新代没有的分派器撤掉。返回提交前的 live 快照供回退。 */
173
+ function commitActivation() {
174
+ const prev = { http: liveHttp, up: liveUp }
175
+ for (const path of liveHttp.keys()) {
176
+ if (!stageHttp.has(path) && httpDispatchers.has(path)) {
177
+ try { httpDispatchers.get(path)() } catch { /* ignore */ }
178
+ httpDispatchers.delete(path)
179
+ }
180
+ }
181
+ for (const path of liveUp.keys()) {
182
+ if (!stageUp.has(path) && upDispatchers.has(path)) {
183
+ try { upDispatchers.get(path)() } catch { /* ignore */ }
184
+ upDispatchers.delete(path)
185
+ }
186
+ }
187
+ liveHttp = stageHttp
188
+ liveUp = stageUp
189
+ stageHttp = null
190
+ stageUp = null
191
+ applying = false
192
+ return prev
193
+ }
194
+
195
+ /** 装载失败:丢弃 staging,撤掉只为新代挂上的分派器;live 不动。 */
196
+ function rollbackActivation() {
197
+ if (stageHttp) {
198
+ for (const path of stageHttp.keys()) {
199
+ if (!liveHttp.has(path) && httpDispatchers.has(path)) {
200
+ try { httpDispatchers.get(path)() } catch { /* ignore */ }
201
+ httpDispatchers.delete(path)
202
+ }
203
+ }
204
+ }
205
+ if (stageUp) {
206
+ for (const path of stageUp.keys()) {
207
+ if (!liveUp.has(path) && upDispatchers.has(path)) {
208
+ try { upDispatchers.get(path)() } catch { /* ignore */ }
209
+ upDispatchers.delete(path)
210
+ }
211
+ }
212
+ }
213
+ stageHttp = null
214
+ stageUp = null
215
+ applying = false
216
+ }
217
+
218
+ /** 自检失败:把 live 换回旧代;新代独有分派器撤掉,旧代独有的补回(旧 fiber 一直活着)。 */
219
+ function restoreLive(prev) {
220
+ for (const path of liveHttp.keys()) {
221
+ if (!prev.http.has(path) && httpDispatchers.has(path)) {
222
+ try { httpDispatchers.get(path)() } catch { /* ignore */ }
223
+ httpDispatchers.delete(path)
224
+ }
225
+ }
226
+ for (const path of prev.http.keys()) if (!liveHttp.has(path)) ensureHttpDispatcher(path, prev.http.get(path))
227
+ for (const path of liveUp.keys()) {
228
+ if (!prev.up.has(path) && upDispatchers.has(path)) {
229
+ try { upDispatchers.get(path)() } catch { /* ignore */ }
230
+ upDispatchers.delete(path)
231
+ }
232
+ }
233
+ for (const path of prev.up.keys()) if (!liveUp.has(path)) ensureUpDispatcher(path, prev.up.get(path))
234
+ liveHttp = prev.http
235
+ liveUp = prev.up
236
+ }
237
+
77
238
  let lastError = null
78
239
  let activatedAt = null
79
240
  let detached = false
@@ -123,7 +284,8 @@ export function createRuntime() {
123
284
  * 回滚**不重新 import**:新代装失败时旧代的目录可能已经被市场删掉了,重新读盘会
124
285
  * MODULE_NOT_FOUND;而旧代的模块本体一直在内存里,重新 apply 一次就够了。
125
286
  */
126
- async function activateLoaded(loaded) {
287
+ async function activateLoaded(loaded, options = {}) {
288
+ const commit = options.commit !== false
127
289
  let timer = null
128
290
  // 用 `{ inject, apply }` 而不是裸函数:cordis 只有在**声明过** inject 的 fiber 上
129
291
  // 才允许 `ctx.webServer` 这种取值(裸函数会以 "cannot get property without inject"
@@ -135,14 +297,24 @@ export function createRuntime() {
135
297
  // 旧运行时上读 `ctx.apiProxy` 抛 "cannot get property apiProxy without inject"。
136
298
  // 测试里的假代没声明 inject 时退回外壳默认值。
137
299
  const inject = Array.isArray(loaded.inject) && loaded.inject.length > 0 ? loaded.inject : DEFAULT_INJECT
138
- const result = await Promise.race([
139
- Promise.resolve().then(() => ctx.plugin({ inject, apply: loaded.apply })),
140
- new Promise((_, reject) => {
141
- timer = setTimeout(() => reject(new Error(`装载 ${loaded.version} 超时(${ACTIVATE_TIMEOUT_MS}ms):它可能卡在等一个永远不来的依赖服务上`)), ACTIVATE_TIMEOUT_MS)
142
- }),
143
- ]).finally(() => {
300
+ beginActivation()
301
+ let result
302
+ try {
303
+ result = await Promise.race([
304
+ Promise.resolve().then(() => ctx.plugin({ inject, apply: loaded.apply })),
305
+ new Promise((_, reject) => {
306
+ timer = setTimeout(() => reject(new Error(`装载 ${loaded.version} 超时(${ACTIVATE_TIMEOUT_MS}ms):它可能卡在等一个永远不来的依赖服务上`)), ACTIVATE_TIMEOUT_MS)
307
+ }),
308
+ ])
309
+ } catch (error) {
310
+ // 装载失败:丢掉 staging、撤掉只为新代挂的分派器,live 保持旧代不动。
311
+ rollbackActivation()
312
+ throw error
313
+ } finally {
144
314
  if (timer) clearTimeout(timer)
145
- })
315
+ }
316
+ // 默认直接提交(start / attemptAll / 回滚装载);reload 要自检,先不提交,由它自己 commit。
317
+ if (commit) commitActivation()
146
318
  return { loaded, fiber: result }
147
319
  }
148
320
 
@@ -243,62 +415,61 @@ export function createRuntime() {
243
415
  // 同一份目录里改了文件:不清缓存的话,重新 import 拿回来的还是内存里那份旧实现。
244
416
  if (options.reread === true) invalidateGeneration(target.version)
245
417
 
418
+ // 先把新代模块整份读进内存(解析、依赖树、磁盘这一大段是本该慢的部分),**在动旧代之前**。
419
+ // 好处有两条:a) 新代连 import 就失败(缺文件 / 语法错 / 依赖解析不到)时,旧代毫发无损、
420
+ // 根本不进换代;b) 真正切换那一刻只剩 apply,旧路由摘掉到新路由挂上的空窗被压到最小。
421
+ const prepared = await importGeneration(target)
422
+
246
423
  await drain()
247
424
  const oldFiber = fiber
248
425
  const oldCurrent = current
249
426
  // 旧的**模块本体**要在激活新代之前抓住:`loadedCurrent` 一旦被新代覆盖,回滚就只能
250
- // 拿到刚装坏的那一份(真机上表现为「自检没过、退回去的还是坏的那个」)。
427
+ // 拿到刚装坏的那一份。
251
428
  const oldLoaded = loadedCurrent
252
- fiber = null
253
- current = null
254
- if (oldFiber) {
255
- try {
256
- await oldFiber.dispose()
257
- } catch (error) {
258
- // dispose 里的清理动作自己炸了:记下来,但不能因此不装新代。
259
- lastError = `卸载 ${oldCurrent?.version ?? '旧代'} 时出错:${error?.message || error}`
260
- }
261
- }
429
+ const oldActivatedAt = activatedAt
430
+ // 蓝绿:不再先卸旧代。新代先登记到分发表(staging),旧代继续服务在飞请求;提交后才卸
431
+ // 旧代。这样换代码那一刻没有路由空窗,也不会因为新旧两代注册同一路径撞 duplicate route。
262
432
  try {
263
- const { loaded, fiber: nextFiber } = await activate(target)
264
- fiber = nextFiber
265
- loadedCurrent = loaded
266
- current = describe(loaded, target.dir)
267
- if (oldCurrent) previous = oldCurrent
433
+ const next = await activateLoaded(prepared, { commit: false })
434
+ // 原子提交:分发表切到新代
435
+ const prevLive = commitActivation()
436
+ fiber = next.fiber
437
+ loadedCurrent = next.loaded
438
+ current = describe(next.loaded, target.dir)
268
439
  activatedAt = new Date().toISOString()
269
440
  lastError = null
270
- // 装起来了不等于**手机要打的那批接口**可用:端口没绑上、守卫没挂上、某个 handler
271
- // 永远不回包,这些都要真打一发才看得见。所以换完之后问一次自己的 `/health`。
272
- //
273
- // 不过就自己退回去 —— 这一步刻意放在宿主里,不交给手机:装坏的后果正是 App
274
- // 连不上这台设备,那时候手机上一颗按钮都发不出去。
441
+ // 自检:此刻 live 已是新代,真打一发确认手机要的那批接口能应答。
275
442
  if (options.selfCheck !== false && oldCurrent) {
276
443
  const alive = await checkSelfCheck()
277
444
  if (alive.ok === false) {
278
445
  const failure = `新版 ${target.version} 换上来之后没通过自检:${alive.reason}`
279
- // **先把刚装起来的新代卸掉**:它占着同一批路由路径,不卸就装不回旧代
280
- // (webserver: duplicate exact route)。这条是自检回滚与「装载直接抛错」两条路
281
- // 唯一的区别 —— 后者根本没有新 fiber 可卸。
282
- const brokenFiber = fiber
283
- fiber = null
284
- if (brokenFiber) {
285
- try { await brokenFiber.dispose() } catch { /* 新代自己卸不干净时,回滚仍然照试 */ }
286
- }
287
- await rollbackTo(oldCurrent, oldLoaded, failure)
446
+ // 退回旧代:分发表切回、卸新代;旧 fiber 一直活着,没有空窗。
447
+ restoreLive(prevLive)
448
+ fiber = oldFiber
449
+ loadedCurrent = oldLoaded
450
+ current = oldCurrent
451
+ activatedAt = oldActivatedAt
452
+ const brokenFiber = next.fiber
453
+ if (brokenFiber) { try { await brokenFiber.dispose() } catch { /* 卸不干净也照退 */ } }
454
+ lastRollback = { at: new Date().toISOString(), ok: true, toVersion: oldCurrent?.version ?? null, fromVersion: target.version, reason: failure }
455
+ lastError = failure
288
456
  const error = new Error(failure)
289
457
  error.code = 'self_check_failed'
290
458
  throw error
291
459
  }
292
460
  }
461
+ if (oldCurrent) previous = oldCurrent
462
+ // 成功:旧代排空后卸掉(在飞请求仍跑旧 handler 闭包)。
463
+ await drain()
464
+ if (oldFiber) {
465
+ try { await oldFiber.dispose() } catch (error) { lastError = `卸载 ${oldCurrent?.version ?? '旧代'} 时出错:${error?.message || error}` }
466
+ }
293
467
  clearBacklogRetry()
294
468
  return status()
295
469
  } catch (error) {
296
- // 自检那条已经在上面退回过一次了,别退第二遍(第二遍会把刚装回去的旧代再卸一次)。
297
- // 但它记下的「退回也失败」那句话不能在这里被覆盖掉 —— 那才是真机上最要紧的一条。
298
- if (error?.code !== 'self_check_failed') {
299
- lastError = `装载 ${target.version} 失败:${error?.message || error}`
300
- if (oldCurrent) await rollbackTo(oldCurrent, oldLoaded, lastError)
301
- }
470
+ // 装载直接抛错:activateLoaded 已 rollbackActivation,旧代毫发无损(fiber/current 没动)。
471
+ if (error?.code === 'self_check_failed') throw error
472
+ lastError = `装载 ${target.version} 失败:${error?.message || error}`
302
473
  throw error
303
474
  }
304
475
  })().finally(() => {
@@ -439,6 +610,9 @@ export function createRuntime() {
439
610
  reload,
440
611
  detach,
441
612
  status,
613
+ installDispatch,
614
+ registerRoute,
615
+ registerUpgradeRoute,
442
616
  beginRequest: () => {
443
617
  inFlight += 1
444
618
  },