dsh-mobile-plugin 0.5.81 → 0.5.82

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 (55) hide show
  1. package/lib/frpc/provision.cjs +21 -17
  2. package/lib/frpc/runner.cjs +193 -165
  3. package/lib/impl.js +53 -80
  4. package/lib/mirror/pusher.cjs +60 -10
  5. package/lib/mobile/events.js +2 -1
  6. package/lib/mobile/feedback.js +6 -5
  7. package/lib/mobile/file-read.js +4 -2
  8. package/lib/mobile/mux.js +148 -21
  9. package/lib/mobile/paired-devices.js +2 -1
  10. package/lib/mobile/pairing.js +3 -2
  11. package/lib/mobile/relay-control.js +27 -33
  12. package/lib/mobile/session-changes.js +8 -2
  13. package/lib/mobile/session-delivery.js +5 -1
  14. package/lib/mobile/session-file.js +46 -25
  15. package/lib/mobile/session-head.js +7 -3
  16. package/lib/mobile/session-snapshot.js +5 -1
  17. package/lib/mobile/session-step.js +13 -7
  18. package/lib/mobile/session-stop-summary.js +6 -1
  19. package/lib/mobile/stream-registry.js +48 -53
  20. package/lib/mobile/stream.js +17 -2
  21. package/lib/mobile/uploads.js +190 -163
  22. package/lib/p2p/session.cjs +169 -70
  23. package/lib/p2p/wiring.cjs +4 -2
  24. package/lib/panel/index.html +17 -15
  25. package/lib/relay/blob-upload.cjs +103 -0
  26. package/lib/relay/config-store.js +81 -0
  27. package/lib/relay/control.js +94 -46
  28. package/lib/relay/core.js +9 -13
  29. package/lib/relay/lan-proxy.js +44 -7
  30. package/lib/relay/pairing-payload.cjs +14 -5
  31. package/lib/relay/preview-webapp.cjs +150 -0
  32. package/lib/relay/preview.js +35 -8
  33. package/lib/relay/protocol.js +6 -4
  34. package/lib/relay/relay-probe.js +112 -21
  35. package/lib/relay/tunnel-forwarder.cjs +4 -2
  36. package/lib/relay/tunnel.js +39 -8
  37. package/lib/remote/controller.cjs +33 -3
  38. package/lib/remote/host-control.cjs +11 -2
  39. package/lib/remote/router.cjs +83 -33
  40. package/lib/remote/transport.cjs +32 -5
  41. package/lib/remote/tunnel-helper.cjs +51 -25
  42. package/lib/remote/tunnels.cjs +27 -3
  43. package/lib/routes/control-plane.js +25 -17
  44. package/lib/routes/mobile-api.js +21 -18
  45. package/lib/shared/fresh-request.js +32 -1
  46. package/lib/shared/route-order.cjs +118 -132
  47. package/lib/shared/sse-write.js +29 -10
  48. package/lib/shared/via-header.js +5 -12
  49. package/lib/shell/transport-host.js +9 -1
  50. package/lib/sidecar-facade-worker.cjs +156 -112
  51. package/lib/sidecar-facade.cjs +6 -1
  52. package/lib/sidecar-lifecycle.cjs +6 -2
  53. package/lib/tailcat/host-process.cjs +32 -8
  54. package/lib/tailcat/session.cjs +27 -10
  55. package/package.json +6 -6
package/lib/impl.js CHANGED
@@ -1,4 +1,5 @@
1
- // 局域网入口稳定与设备验证恢复共用一份端口状态。
1
+ // 配置 schema 与投影拆到 lib/relay/config-store.js,装配层只留装配与状态仓外壳(行数兜底)。
2
+ // 装配移动 API、设备吊销与独立直连生命周期,并向本机面板提供真实上报目的地。
2
3
  /**
3
4
  * 插件实现(随包发布的基础代):装配路由、移动端 API 网关与 sidecar 生命周期。
4
5
  * 只做装配——镜像推送在 `lib/mirror/pusher.cjs`、sidecar 生命周期在
@@ -11,10 +12,10 @@ import { createRequire } from 'node:module'
11
12
  import os from 'node:os'
12
13
  import path from 'node:path'
13
14
  import { fileURLToPath } from 'node:url'
14
- import z from '@deepseek-ai/schemastery'
15
15
 
16
16
  const require = createRequire(import.meta.url)
17
17
  const core = require('./relay/core.js')
18
+ const { RemoteControlSettingsSchema, configOf } = require('./relay/config-store.js')
18
19
  const pairingApproval = require('./relay/pairing-policy.js')
19
20
  const { sendJson, sendHtml, htmlEtag } = require('./shared/http-util.js')
20
21
  // 控制面守卫(localOnly)与移动端守卫(guarded)都住在这里;两套守卫并排放,
@@ -110,77 +111,7 @@ export const inject = ['webServer']
110
111
  const API_PROXY_GRACE_MS = 3000
111
112
 
112
113
  export const REMOTE_CONTROL_SETTINGS_NAMESPACE = 'mobile-remote-control'
113
- export const RemoteControlSettingsSchema = z.object({
114
- enabled: z.boolean().default(false),
115
- relayUrl: z.string().default(''),
116
- // 完整的中转地址列表,`relayUrls[0]` 恒等于 `relayUrl`(见 docs/relay-multi-address.md)。
117
- // 这一轮**行为不变**:隧道仍然只按 `relayUrl` 连,列表只是「以后要有地方落」的形状。
118
- relayUrls: z.array(z.string()).default([]),
119
- lanEnabled: z.boolean().default(true),
120
- lanPort: z.number().step(1).min(1024).max(65535).default(18787),
121
- name: z.string().default(''),
122
- // Pairing approval policy; see lib/relay/pairing-policy.js for the two modes and
123
- // why 'code' is not the old popup. Kept in the config schema so /api/relay/config
124
- // can change it, and so an unknown value is rejected on write.
125
- pairingPolicy: z.union(pairingApproval.POLICIES.map(value => z.const(value))).default(pairingApproval.DEFAULT_POLICY),
126
- // 新配对设备的权限档位(只读 / 可答审批 / 全权)。配对时在电脑侧选定,展开成 permissions
127
- // 写进凭据记录(见 lib/mobile/permissions.js)。缺省 full = 与今天单 token 全给等价。
128
- pairingTier: z.union(permissions.TIER_NAMES.map(t => z.const(t))).default(permissions.DEFAULT_TIER), approvalAutoReview: z.boolean().default(false), // 审批自动审阅档(默认关,见 mobile/auto-review.js)
129
- // 是否把本机网络地址加密上报给「总控」(地址目录)。默认开 = 与历史行为一致;
130
- // 关掉后宿主不再跑总控上报客户端,手机换网后拿不到这台电脑的新地址(见 relay/control.js)。
131
- controlReportEnabled: z.boolean().default(true),
132
- // 桌面设置页那两颗侧边栏图标(手机 / 电脑)的可见性。默认全开;老 relay.json 没这两格时
133
- // 由 configOf 收成 true,界面不会在升级后突然少一颗。只给桌面控制面写,手机端配置口不收。
134
- desktopPhoneIcon: z.boolean().default(true),
135
- desktopComputerIcon: z.boolean().default(true),
136
- // 中转注册密钥(对偶于中转的 TUNNEL_REGISTER_SECRET)。桌面版拿不到 shell
137
- // 环境变量,所以它和其他配置一样存在 relay.json(0600),由 /api/relay/config
138
- // 在回环上写入;status / pairing / 二维码都不回显它。
139
- registerSecret: z.string().max(512).default(''),
140
- // 手机优先用哪条地址:空 = 不指定(按宿主网卡优先级排)。选择只挪候选顺序、不删候选,
141
- // 理由与边界见 relay/lan-network.cjs 的 orderCandidates 与 relay.json 那条地图条目。
142
- preferredLanAddress: z.string().max(64).default(''),
143
- // 用户手填的直连地址(`manualLanUrl`,内网穿透域名)也随二维码一起走,见 lan-network.cjs。
144
- manualLanUrl: z.string().max(200).default(''),
145
- // 用户手填的 IPv6 直连地址(`manualIpv6Url`,形如 `http://[240e::1]:18787`):与上一条并列,
146
- // 只是拨的是 IPv6;网卡扫不到的那条固定地址靠它兜底,候选口径见 lan-network.cjs。
147
- manualIpv6Url: z.string().max(200).default(''),
148
- // 用户手填的「TCP 直连」目标(`manualTcpUrl`,形如 `主机:端口` / `http://主机:端口`,IPv6 方括号)。
149
- // 与上面两条并列、同样不进 sidecar;它只决定手机用裸 TCP 拨哪个目标(详见 lan-network.cjs)。
150
- manualTcpUrl: z.string().max(200).default(''),
151
- })
152
-
153
-
154
- function configOf(state) {
155
- // 两格必须一起算:`relayUrls` 是完整列表、`relayUrl` 是它的首项(契约见
156
- // docs/relay-multi-address.md),任何一处只写一个都会让读的一方看到矛盾的两份值。
157
- const relay = core.relayAddressesOf(state)
158
- return {
159
- enabled: Boolean(state.enabled),
160
- relayUrl: relay.relayUrl,
161
- relayUrls: relay.relayUrls,
162
- lanEnabled: Boolean(state.lanEnabled),
163
- lanPort: Number.isInteger(state.lanPort) ? state.lanPort : 18787,
164
- name: typeof state.name === 'string' ? state.name : '',
165
- // The schema rejects anything outside the enum, so in practice this only
166
- // ever normalises a value written before pairingPolicy existed.
167
- pairingPolicy: pairingApproval.normalize(state.pairingPolicy),
168
- pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, // 未知值收敛回 full
169
- approvalAutoReview: state.approvalAutoReview === true, // 非 true 一律当关
170
- // 只有明确写成 false 才算关;老状态文件没这一格时按开(与历史行为一致)。
171
- controlReportEnabled: state.controlReportEnabled !== false,
172
- // 没写过的老配置按显示处理:这两颗是入口,不因为升级就凭空消失。
173
- desktopPhoneIcon: state.desktopPhoneIcon !== false,
174
- desktopComputerIcon: state.desktopComputerIcon !== false,
175
- // 密钥只往 sidecar 和状态文件走:status() / pairingPayload() 都单独取字段,
176
- // 不会把它回显给手机、二维码或日志。
177
- registerSecret: typeof state.registerSecret === 'string' ? state.registerSecret : '',
178
- preferredLanAddress: typeof state.preferredLanAddress === 'string' ? state.preferredLanAddress : '',
179
- manualLanUrl: typeof state.manualLanUrl === 'string' ? state.manualLanUrl : '',
180
- manualIpv6Url: typeof state.manualIpv6Url === 'string' ? state.manualIpv6Url : '',
181
- manualTcpUrl: typeof state.manualTcpUrl === 'string' ? state.manualTcpUrl : '',
182
- }
183
- }
114
+ export { RemoteControlSettingsSchema }
184
115
 
185
116
  // 0.2.0 之前这份配置注册在宿主 settings 的 `mobile-remote-control` 命名空间里
186
117
  // (`ctx.settings.register(ns, schema, { base: configOf(state), applies: 'live' })`),
@@ -233,6 +164,7 @@ function createConfigStore(state) {
233
164
  // 函数),否则界面说停用了、实际还在连公用。放在收敛之后、落盘之前,保证
234
165
  // relayUrls[0] === relayUrl 的不变式与「真停用」一起成立。
235
166
  core.stripPublicRelay(parsed)
167
+ core.expandDefaultPublicRelays(parsed)
236
168
  Object.assign(state, parsed)
237
169
  core.saveState(state)
238
170
  if (options.notify !== false) notify()
@@ -367,7 +299,7 @@ function apply(ctx) {
367
299
  const lanPorts = createLanPortPolicy({ state, saveState: core.saveState })
368
300
  const lanPortInUse = lanPorts.port
369
301
  const resolveLanPort = lanPorts.resolve
370
- const advertisedLanPort = () => (effectiveLanEnabled() ? sidecarLifecycle.getAdvertisedLanPort() : state.lanPort)
302
+ const advertisedLanPort = () => sidecarLifecycle.getAdvertisedLanPort()
371
303
  // 总控上报客户端:把本机全部地址报给总控,拿回设备令牌交给 APP(见 relay/control.js)。
372
304
  // 生命周期挂在下面的 effect 上;配置变更由 applyServices → control.sync() 驱动。
373
305
  // 隧道状态取值器在下面 sidecar 装配完成后才拿到,这里先放占位,装配完换成权威那个。
@@ -391,7 +323,12 @@ function apply(ctx) {
391
323
  // sidecar 子进程的全部生命周期:起停、配置下发、自重启、健康轮询。
392
324
  // **传输进程归稳定外壳**:优先取外壳持有的那份(换代时它不重启,隧道跨代存活);外壳不在
393
325
  // (实现被单独挂载 / 测试)时退回本地创建,行为与从前一致。配置由这一代组装后交给它。
394
- const buildSidecarConfig = (lanPort) => ({ enabled: state.enabled, relayUrl: state.relayUrl, relayUrls: core.relayAddressesOf(state).relayUrls, instanceId: state.instanceId, previousInstanceId: state.previousInstanceId || '', pairingCode: state.pairingCode, pairingTicket: state.pairingTicket || '', pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, name: state.name, upstreamPort: ctx.webServer.port, upstreamHost: ctx.webServer.host, lanPort, lanEnabled: effectiveLanEnabled(), lanSecret: state.lanSecret, registerSecret: state.registerSecret })
326
+ // 父进程地址在这一代挂载时取一次缓存住。下发配置的闭包会被外壳持有的 sidecar 跨代调用,
327
+ // 那时本代 ctx 已 inactive,现读 ctx.webServer 会抛 "cannot get required service webServer
328
+ // in inactive context",导致重启与配置下发全失败(隧道、frpc、P2P 都起不来)。
329
+ const webPortForSidecar = ctx.webServer.port
330
+ const webHostForSidecar = ctx.webServer.host
331
+ const buildSidecarConfig = (lanPort) => ({ enabled: state.enabled, relayUrl: state.relayUrl, relayUrls: core.relayAddressesOf(state).relayUrls, instanceId: state.instanceId, previousInstanceId: state.previousInstanceId || '', pairingCode: state.pairingCode, pairingTicket: state.pairingTicket || '', pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, name: state.name, upstreamPort: webPortForSidecar, upstreamHost: webHostForSidecar, lanPort, lanEnabled: effectiveLanEnabled(), lanSecret: state.lanSecret, registerSecret: state.registerSecret })
395
332
  let hostedSidecar = null
396
333
  try { hostedSidecar = typeof ctx.get === 'function' ? ctx.get('dshMobileSidecarHost') || null : null } catch { hostedSidecar = null }
397
334
  const sidecarLifecycle = hostedSidecar || createSidecarLifecycle({
@@ -437,6 +374,8 @@ function apply(ctx) {
437
374
  getPort: advertisedLanPort,
438
375
  getHistoryKey: () => core.ensureHistoryKey(state),
439
376
  getRelayConnected: () => relayConnectedOf(),
377
+ getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
378
+ log: warn,
440
379
  onIdentityConflict: rotateNow,
441
380
  })
442
381
  if (controlHost && controlHost.client && typeof controlHost.setProviders === 'function') {
@@ -446,6 +385,7 @@ function apply(ctx) {
446
385
  getPort: advertisedLanPort,
447
386
  getHistoryKey: () => core.ensureHistoryKey(state),
448
387
  getRelayConnected: () => relayConnectedOf(),
388
+ getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
449
389
  onIdentityConflict: rotateNow,
450
390
  })
451
391
  }
@@ -569,6 +509,14 @@ function apply(ctx) {
569
509
  try { frpHost = typeof ctx.get === 'function' ? ctx.get('dshMobileTransportFrp') || null : null } catch { frpHost = null }
570
510
  const frpRunner = frpHost && frpHost.runner ? frpHost.runner : createFrpcRunner({ portOf: advertisedLanPort })
571
511
  if (frpHost && typeof frpHost.setPortProvider === 'function') frpHost.setPortProvider(advertisedLanPort)
512
+ mount('frpc 公网地址', () => ctx.effect(() => {
513
+ if (typeof frpRunner.setAddressListener !== 'function') return () => {}
514
+ frpRunner.setAddressListener(async (address, isCurrent) => {
515
+ if (!isCurrent() || state.manualTcpUrl === address) return
516
+ await settings.update({ manualTcpUrl: address })
517
+ })
518
+ return () => frpRunner.setAddressListener(null)
519
+ }, `${name}: frpc address`))
572
520
  if (!(frpHost && frpHost.runner)) {
573
521
  mount('frpc 直连进程', () => ctx.effect(() => {
574
522
  if (frpRunner.shouldAutoStart()) void frpRunner.start()
@@ -576,6 +524,14 @@ function apply(ctx) {
576
524
  }, `${name}: frpc runner`))
577
525
  }
578
526
 
527
+ // closed按唯一连接计数;仅承载本次回执的mux由service有界排空后关闭。
528
+ const dropDeviceStreams = (deviceId, res) => {
529
+ return streamRegistry.drop(deviceId, state.instanceId)
530
+ + preview.dropDevice(deviceId, state.instanceId)
531
+ + (mux.dropDevice?.(deviceId, state.instanceId, res) || 0)
532
+ }
533
+ const dropAllDeviceStreams = (res) => streamRegistry.dropAll(state.instanceId) + preview.dropAll(state.instanceId) + (mux.dropAll?.(state.instanceId, res) || 0)
534
+
579
535
  mount('控制面路由', () => registerControlPlaneRoutes({
580
536
  registerRoute,
581
537
  // 更新的机制住在外壳(`lib/index.js`)里,代这边只把它开成本机接口。取不到就如实报
@@ -606,6 +562,7 @@ function apply(ctx) {
606
562
  p2p,
607
563
  // FRP 直连:导入配置后的启停与运行状态(见 lib/frpc/runner.cjs)。
608
564
  frp: frpRunner,
565
+ getControlTargetUrl: () => control.targetUrl,
609
566
  restartSidecar,
610
567
  // 「手机上最近来过没有」——控制面状态里补给面板用(见 ./mobile/activity.cjs)。
611
568
  mobileActivity: activity.snapshot,
@@ -621,7 +578,8 @@ function apply(ctx) {
621
578
  getLanProxyStats: () => sidecarLifecycle.getSnapshot()?.streams?.lan ?? null,
622
579
  // 吊销时收掉这台设备已经开着的流(§3.3):token 换了只保证「下一次请求」被拒,
623
580
  // 一条已经开着的 SSE 不会自己停,被踢的手机还能继续收消息直到它自己重连。
624
- dropDeviceStreams: (deviceId) => streamRegistry.drop(deviceId),
581
+ dropDeviceStreams,
582
+ dropAllDeviceStreams,
625
583
  }))
626
584
 
627
585
 
@@ -667,7 +625,13 @@ function apply(ctx) {
667
625
  // `ownWebPort` 是同一条边界上的唯一例外:用户显式要求手机能打开网页版(2026-11-03),
668
626
  // 所以 `mode=webapp` 那一档只放行这一个端口(且目标必须是环回)。同样用取值器。
669
627
  const preview = createPreviewService({
670
- authorized,
628
+ authorized: (req) => {
629
+ const outcome = authOutcome(req)
630
+ if (!outcome.ok) return false
631
+ req.__dshRecord = outcome.record
632
+ req.__dshInstanceId = state.instanceId
633
+ return true
634
+ },
671
635
  protectedPorts: () => {
672
636
  const ports = new Set([ctx.webServer.port, lanPortInUse()])
673
637
  ports.delete(0)
@@ -682,8 +646,14 @@ function apply(ctx) {
682
646
  // 对话页长连接(mux):一条手机 WS 上按 id 多路复用,逐条转成本地回环请求打到移动 API。
683
647
  // 鉴权口径与预览升级路由同一套(设备凭据有效即可);逐路由权限仍由回环 HTTP 的 guarded 判,
684
648
  // mux 只是搬运工,不另立权限面。帧契约见 `docs/mux-long-connection-design.md` §11。
685
- const muxPermission = permissions.createUpgradePermission({ credentials, instanceId: state.instanceId, presentedCredential })
686
- const muxAuthorize = (req) => { try { return Boolean(muxPermission.recordOf(req)) } catch { return false } }
649
+ const muxAuthorize = (req) => {
650
+ try {
651
+ const outcome = authOutcome(req)
652
+ if (!outcome.ok || !outcome.record) return false
653
+ req.__dshRecord = outcome.record
654
+ return true
655
+ } catch { return false }
656
+ }
687
657
  // mux 优先用**稳定外壳**持有的那份(换代时已建立的手机 WS 不断);外壳不在时本地创建兜底。
688
658
  // 升级路由由外壳直接挂(见 shell/transport-host.js),这一代不再重复注册。
689
659
  let muxHost = null
@@ -735,7 +705,8 @@ function apply(ctx) {
735
705
  // 「这台电脑上还连着哪些手机」的两条路由(见 mobile/paired-devices.js):凭据库真源 +
736
706
  // 吊销时收掉被踢设备在途的 SSE。
737
707
  credentials,
738
- dropDeviceStreams: (deviceId) => streamRegistry.drop(deviceId),
708
+ dropDeviceStreams,
709
+ dropAllDeviceStreams,
739
710
  // 取值器而非快照对象:snapshot 会被 applySidecarConfig 整体替换,闭包捕获对象会让
740
711
  // 连接信息永远停在进程启动那一刻。
741
712
  getSidecarSnapshot: sidecarLifecycle.getSnapshot,
@@ -770,6 +741,8 @@ function apply(ctx) {
770
741
  getSidecar: sidecarLifecycle.getSidecar,
771
742
  credentials,
772
743
  activeGuard,
744
+ dropDeviceStreams,
745
+ dropAllDeviceStreams,
773
746
  },
774
747
  }))
775
748
  mount('服务同步', () => ctx.effect(() => {
@@ -1,3 +1,4 @@
1
+ // blob后台轮次绑定effect代次,停止后不续发旧快照或记录迟到确认。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -355,7 +356,7 @@ function createMirrorPusher(deps) {
355
356
  *
356
357
  * `scope=file` 的 key 按当初记账的归属会话一起删。
357
358
  */
358
- const deleteRemovedSessionBlobs = async (sidecar) => {
359
+ const deleteRemovedSessionBlobs = async (sidecar, isCurrent) => {
359
360
  if (typeof sidecar.deleteBlobs !== 'function') return;
360
361
  const deleted = deletedSessionIdsOf(ctx);
361
362
  if (!deleted || deleted.size === 0) return;
@@ -366,22 +367,28 @@ function createMirrorPusher(deps) {
366
367
  .filter(([, rec]) => rec && goneSet.has(rec.sessionId))
367
368
  .map(([key]) => key);
368
369
  for (let i = 0; i < goneMessages.length; i += MAX_DELETE_KEYS_PER_FRAME) {
370
+ if (!isCurrent()) return;
369
371
  const keys = goneMessages.slice(i, i + MAX_DELETE_KEYS_PER_FRAME);
370
372
  try {
371
373
  await sidecar.deleteBlobs({ scope: 'messages', keys });
374
+ if (!isCurrent()) return;
372
375
  for (const key of keys) pushedMessageBlobs.delete(key);
373
376
  blobLogClear(`delete:messages:${keys[0]}`);
374
377
  } catch (error) {
378
+ if (!isCurrent()) return;
375
379
  blobLog(`delete:messages:${keys[0]}`, errorText(error));
376
380
  }
377
381
  }
378
382
  for (let i = 0; i < goneFiles.length; i += MAX_DELETE_KEYS_PER_FRAME) {
383
+ if (!isCurrent()) return;
379
384
  const keys = goneFiles.slice(i, i + MAX_DELETE_KEYS_PER_FRAME);
380
385
  try {
381
386
  await sidecar.deleteBlobs({ scope: 'file', keys });
387
+ if (!isCurrent()) return;
382
388
  for (const key of keys) pushedFileBlobs.delete(key);
383
389
  blobLogClear(`delete:file:${keys[0]}`);
384
390
  } catch (error) {
391
+ if (!isCurrent()) return;
385
392
  blobLog(`delete:file:${keys[0]}`, errorText(error));
386
393
  }
387
394
  }
@@ -398,17 +405,41 @@ function createMirrorPusher(deps) {
398
405
  * `MAX_BLOB_MESSAGE_FRAMES_PER_ROUND` 条、文件最多 `MAX_BLOB_FILE_FRAMES_PER_ROUND` 条,
399
406
  * 超出的下一轮再推。
400
407
  */
401
- const pushHistoryBlobs = async (payload, creds) => {
408
+ let blobRoundRunning = false;
409
+ let blobStopped = false;
410
+ let blobGeneration = 0;
411
+ let nextBlobRound = null;
412
+ const scheduleHistoryBlobs = (payload, creds) => {
413
+ if (blobStopped) return;
414
+ // 只保留最新一份待办,不让慢上行阻塞镜像tick、revision广播或堆积快照。
415
+ nextBlobRound = { payload, creds, generation: blobGeneration };
416
+ if (blobRoundRunning) return;
417
+ blobRoundRunning = true;
418
+ const run = async () => {
419
+ try {
420
+ while (!blobStopped && nextBlobRound) {
421
+ const round = nextBlobRound;
422
+ nextBlobRound = null;
423
+ await pushHistoryBlobs(round.payload, round.creds, round.generation);
424
+ await new Promise(resolve => setImmediate(resolve));
425
+ }
426
+ } finally { blobRoundRunning = false; }
427
+ };
428
+ void run();
429
+ };
430
+ const pushHistoryBlobs = async (payload, creds, generation) => {
402
431
  // blob 是加法:它自己炸了不许把一次已经成功的镜像推送翻成失败(调用方会把异常记成
403
432
  // 推送失败)。所以整趟兜一层,失败只留一行诊断。
404
433
  try {
405
- await pushHistoryBlobsUnlocked(payload, creds);
434
+ await pushHistoryBlobsUnlocked(payload, creds, generation);
406
435
  } catch (error) {
407
436
  blobLog('round', errorText(error));
408
437
  }
409
438
  };
410
439
 
411
- const pushHistoryBlobsUnlocked = async (payload, creds) => {
440
+ const pushHistoryBlobsUnlocked = async (payload, creds, generation) => {
441
+ const isCurrent = () => !blobStopped && generation === blobGeneration;
442
+ if (!isCurrent()) return;
412
443
  let hk = '';
413
444
  try { hk = getHistoryKey() || ''; } catch { hk = ''; }
414
445
  if (!hk) return;
@@ -435,7 +466,8 @@ function createMirrorPusher(deps) {
435
466
  }
436
467
  blobHistoryKey = hk;
437
468
 
438
- await deleteRemovedSessionBlobs(sidecar);
469
+ await deleteRemovedSessionBlobs(sidecar, isCurrent);
470
+ if (!isCurrent()) return;
439
471
 
440
472
  // 一台设备凭据都没有(还没配对过 / 刚吊销完):推上去也没人能拉,中转那边还要求 creds
441
473
  // 非空。删除已经在上面做过了,剩下的不发,省得每轮撞一条注定被拒的帧。
@@ -454,8 +486,14 @@ function createMirrorPusher(deps) {
454
486
  for (let i = 0; i < targets.length; i += MAX_CREDS_ONLY_BATCH) {
455
487
  const batch = targets.slice(i, i + MAX_CREDS_ONLY_BATCH);
456
488
  for (const target of batch) {
457
- try { await sidecar.pushBlob({ ...target, creds: digestList, cipher: '' }); }
458
- catch (error) { allOk = false; blobLog(`creds:${target.scope}:${target.key}`, errorText(error)); }
489
+ if (!isCurrent()) return;
490
+ try {
491
+ await sidecar.pushBlob({ ...target, creds: digestList, cipher: '' });
492
+ if (!isCurrent()) return;
493
+ } catch (error) {
494
+ if (!isCurrent()) return;
495
+ allOk = false; blobLog(`creds:${target.scope}:${target.key}`, errorText(error));
496
+ }
459
497
  }
460
498
  if (!allOk) break; // 下一轮再来,别在这一轮把 stderr 刷满
461
499
  }
@@ -469,6 +507,7 @@ function createMirrorPusher(deps) {
469
507
  let fileBudget = MAX_BLOB_FILE_FRAMES_PER_ROUND;
470
508
  const messages = payload && payload.messages && typeof payload.messages === 'object' ? payload.messages : {};
471
509
  for (const [sessionId, body] of Object.entries(messages)) {
510
+ if (!isCurrent()) return;
472
511
  if (messageBudget <= 0) break;
473
512
  if (!canMessages) break;
474
513
  if (!isBlobEligible(body)) continue;
@@ -481,10 +520,12 @@ function createMirrorPusher(deps) {
481
520
  catch (error) { blobLog(`build:messages:${sessionId}`, errorText(error)); continue; }
482
521
  try {
483
522
  await sidecar.pushBlob(frame);
523
+ if (!isCurrent()) return;
484
524
  pushedMessageBlobs.set(sessionId, { fingerprint });
485
525
  blobLogClear(`put:messages:${sessionId}`);
486
526
  messageBudget -= 1;
487
527
  } catch (error) {
528
+ if (!isCurrent()) return;
488
529
  blobLog(`put:messages:${sessionId}`, errorText(error));
489
530
  }
490
531
  }
@@ -495,6 +536,7 @@ function createMirrorPusher(deps) {
495
536
  // 这一段今天在 `history-blob.cjs` 里没有生产者(见 decisions 里 d2838e82 那条:文件 scope
496
537
  // 「今天没有」),所以 `canFiles` 为假时整段不跑 —— 不跑不等于没写,真接上了这里自己就通。
497
538
  for (const source of (canFiles ? collectFileBlobSources(payload) : [])) {
539
+ if (!isCurrent()) return;
498
540
  if (fileBudget <= 0) break;
499
541
  const stat = statFileSource(source);
500
542
  if (!stat) continue;
@@ -514,11 +556,13 @@ function createMirrorPusher(deps) {
514
556
  catch (error) { blobLog(`build:file:${source.key}`, errorText(error)); continue; }
515
557
  try {
516
558
  await sidecar.pushBlob(frame);
559
+ if (!isCurrent()) return;
517
560
  pushedFileBlobs.set(source.key, { fingerprint, sessionId: source.sessionId });
518
561
  blobLogClear(`put:file:${source.key}`);
519
562
  blobLogClear(`file-too-large:${source.key}`);
520
563
  fileBudget -= 1;
521
564
  } catch (error) {
565
+ if (!isCurrent()) return;
522
566
  blobLog(`put:file:${source.key}`, errorText(error));
523
567
  }
524
568
  }
@@ -555,7 +599,7 @@ function createMirrorPusher(deps) {
555
599
  // 镜像判重跳过时**仍然过一遍 blob**:blob 自己有指纹判重(推成功才记账),所以这里
556
600
  // 通常一条都不发;但上一轮 blob 推送失败、或设备集合刚变过,就得靠这一趟补上 ——
557
601
  // 否则镜像内容不变的那些轮次里,失败的 blob 永远等不到重试。
558
- await pushHistoryBlobs(payload, payload.creds);
602
+ scheduleHistoryBlobs(payload, payload.creds);
559
603
  return false;
560
604
  }
561
605
  try {
@@ -568,7 +612,7 @@ function createMirrorPusher(deps) {
568
612
  lastPushedCreds = credsKey;
569
613
  recordMirrorPush(true, null)
570
614
  // 镜像已落地之后再推历史 blob:同一份载荷、同一批凭据摘要。失败不影响上面这次成功。
571
- await pushHistoryBlobs(payload, payload.creds);
615
+ scheduleHistoryBlobs(payload, payload.creds);
572
616
  // 基准只在真的推进去(或被判重跳过)之后才前移:推送失败必须能在下一轮重试,
573
617
  // 否则「清单变了」会被一次失败吃掉,中转镜像永远停在旧版(见 processBgQueue 的门)。
574
618
  lastPushedListRevision = listRevision;
@@ -1139,6 +1183,8 @@ function createMirrorPusher(deps) {
1139
1183
 
1140
1184
  /** 返回 effect 的清理函数,交给 index.js 用 ctx.effect 挂载(与原有形状一致)。 */
1141
1185
  const start = () => {
1186
+ const generation = ++blobGeneration;
1187
+ blobStopped = false;
1142
1188
  let disposed = false;
1143
1189
  const ac = new AbortController();
1144
1190
  void (async () => {
@@ -1190,7 +1236,11 @@ function createMirrorPusher(deps) {
1190
1236
  // 已经 clearInterval,unref 是给「宿主进程要退出、effect 清理还没轮到」的那一瞬间兜底。
1191
1237
  if (bgTimer && typeof bgTimer.unref === 'function') bgTimer.unref();
1192
1238
  void pushMirror();
1193
- return () => { disposed = true; ac.abort(); clearInterval(bgTimer); };
1239
+ return () => {
1240
+ disposed = true;
1241
+ if (generation === blobGeneration) { blobStopped = true; blobGeneration += 1; nextBlobRound = null; }
1242
+ ac.abort(); clearInterval(bgTimer);
1243
+ };
1194
1244
  };
1195
1245
 
1196
1246
  return {
@@ -1,3 +1,4 @@
1
+ // 转发设备事件,并按已鉴权实例登记可吊销的 SSE 连接。
1
2
  /**
2
3
  * 设备流响应声明心跳周期,供客户端检测首帧缺失。
3
4
  * 设备级事件流(GET /api/mobile/v1/events/stream):手机上侧栏那条 SSE。
@@ -137,7 +138,7 @@ async function handleDeviceStream(ctx, req, res) {
137
138
  res.write(': connected\n\n');
138
139
  const ac = new AbortController();
139
140
  // 按设备登记这条流:吊销时宿主主动断它(§3.3)。设备级流同样是「开着就一直收」。
140
- const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res);
141
+ const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res, req.__dshRecord?.instanceId);
141
142
  // 听**响应**的关闭,不是请求的:`req` 那条 'close' 在 IncomingMessage 上表示「入站请求已经
142
143
  // 读完」,一次普通 GET 走完就会触发,而这条 SSE 连接此刻还好好的 —— 听它会当场把自己掐掉。
143
144
  // 真正的「手机那头走了」落在 `res` 上;与 `/session/stream` 同一个口径。
@@ -1,5 +1,5 @@
1
1
  'use strict';
2
- // AI 查清问题后直接把反馈提交到分发平台;GitHub PR 这条只写进说明(2026-11-18)。
2
+ // AI 查清问题后直接把反馈提交到分发平台;官方回复在维护者反馈队列跟进,AI 代提的不进 App 反馈列表(2026-11-20)。
3
3
 
4
4
  /**
5
5
  * 给模型的「反馈」能力:用户在用插件 / App 时遇到问题,AI 先排查;真查出原因后,由 AI
@@ -8,7 +8,8 @@
8
8
  * ## 两条途径
9
9
  *
10
10
  * - **分发平台**:公开反馈接口,与 App 里的反馈页同一个(`/api/sdk/feedback`)。插件把
11
- * 当前连接的设备身份一并带上,提交后能收到官方回复。这条本模块能真的替用户提交。
11
+ * 当前连接的设备身份一并带上。官方回复在维护者反馈队列里跟进(`npm run feedback` 查看),
12
+ * 这条由 AI 代提的反馈不会出现在 App 的反馈列表里。这条本模块能真的替用户提交。
12
13
  * - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
13
14
  * 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
14
15
  *
@@ -44,7 +45,7 @@ function feedbackChannels() {
44
45
  {
45
46
  kind: 'distribution',
46
47
  name: 'APP 分发系统反馈',
47
- description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。插件会自动带上当前连接的设备身份;提交后能在 App 里收到官方回复。',
48
+ description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。插件会自动带上当前连接的设备身份;官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。',
48
49
  endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
49
50
  requiresLogin: false,
50
51
  },
@@ -150,7 +151,7 @@ async function submitFeedback(deps, content, threadKey, deviceId) {
150
151
  return {
151
152
  threadKey: key,
152
153
  message: key
153
- ? `已提交到分发平台,反馈线程 ${key}。之后 App 里能收到官方回复。`
154
+ ? `已提交到分发平台,反馈线程 ${key}。官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。`
154
155
  : '已提交到分发平台。',
155
156
  };
156
157
  }
@@ -165,7 +166,7 @@ function registerFeedbackTool(ctx, deps) {
165
166
  ctx.tools.register(defineTool({
166
167
  name: 'dsh_feedback',
167
168
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
168
- + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; the user gets official replies in the app. '
169
+ + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; official replies are followed up in the maintainer feedback queue (run `npm run feedback`), and this AI-submitted feedback will not appear in the in-app feedback list. '
169
170
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
170
171
  + 'Use `channels` to list both routes. Only submit after you have actually found the cause: describe the problem, what you checked, and the reproduction or suggested fix.',
171
172
  parameters: {
@@ -1,3 +1,4 @@
1
+ // 按既有允许区读取文件,并将字节范围交给统一响应实现。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -14,7 +15,7 @@
14
15
  * 2. 认出允许区之后的失败分开报:盘上没有 404 `missing`、不是普通文件 400 `not-a-file`、
15
16
  * 超过 512MB 413 `too-large`。码与文案跟 `/session/file` 同一套,App 那边一套分支就够。
16
17
  * 3. 字节流式回写,不在插件进程里缓冲。响应那一半(明文的整份 / 206 一段、协议 v2 的分块
17
- * 信封,含 `offset` 的校验与起始块序号)**直接调 `/session/file` 那一份**:两边抄一份形状
18
+ * 信封,含 `offset` / `length` 校验与起始块序号)**直接调 `/session/file` 那一份**:两边抄一份形状
18
19
  * 必然漂,而漂了的症状是「手机上永远下载中」或「取回来的那段解不开」,没有报错。
19
20
  */
20
21
 
@@ -124,7 +125,7 @@ async function resolveReadableFile(ctx, declared, sessionId) {
124
125
  }
125
126
 
126
127
  /**
127
- * POST { path(绝对), sessionId? } → 该文件的原始字节。
128
+ * POST { path(绝对), sessionId?, offset?, length? } → 该文件范围的原始字节。
128
129
  *
129
130
  * @param {object} ctx 插件上下文
130
131
  * @param {object} req node:http IncomingMessage
@@ -168,6 +169,7 @@ async function handleFileRead(ctx, req, res) {
168
169
  size: info.size,
169
170
  header,
170
171
  rawOffset: body && body.offset,
172
+ rawLength: body && body.length,
171
173
  });
172
174
  }
173
175