dsh-plugin-weapp-gateway 0.8.38 → 0.8.47

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/lib/index.mjs CHANGED
@@ -159,6 +159,10 @@ import QRCode from 'qrcode'
159
159
  import { createHistoryCache, historyCacheKey } from './history-cache.mjs'
160
160
  import { parseSessionTarget, TEAM_PROJECTION_KINDS } from './session-target.mjs'
161
161
  import { createFileUploadManager, FILE_UPLOAD_REQUEST_TYPES, FILE_UPLOAD_DEFAULTS } from './file-upload.mjs'
162
+ import { assistantFinish, failureDetails, toolResultDetails, turnReasonDetails } from './session-event-details.mjs'
163
+ import { createNetworkDiagnostics } from './network-diagnostics.mjs'
164
+ import { isTailscaleIp, tailscaleInterfaceStatus } from './tailscale-addresses.mjs'
165
+ import { createUiState } from './ui-state.mjs'
162
166
 
163
167
  const { createRegistry } = devicesModule
164
168
 
@@ -433,6 +437,7 @@ function buildWireEvent(session, event) {
433
437
  }
434
438
  return Object.assign(base, {
435
439
  event: { type: 'assistant/message', turn: d.turn, step: d.step, text, reasoning, toolCalls,
440
+ ...(assistantFinish(d) ? { finish: assistantFinish(d) } : {}),
436
441
  ...(d.interrupted === true ? { interrupted: true } : {}),
437
442
  ...(d.usage === undefined ? {} : { usage: d.usage }),
438
443
  ...(images.length ? { images } : {}),
@@ -442,7 +447,15 @@ function buildWireEvent(session, event) {
442
447
  })
443
448
  }
444
449
  case 'assistant/attempt':
445
- return Object.assign(base, { event: { type: event.type, turn: d.turn, step: d.step, stream: d.stream } })
450
+ return Object.assign(base, { event: { type: event.type, turn: d.turn, step: d.step, stream: d.stream,
451
+ ...(assistantFinish(d) ? { finish: assistantFinish(d) } : {}) } })
452
+ case 'llm/retry':
453
+ case 'llm/retry-started':
454
+ return Object.assign(base, { event: { type: event.type, turn: d.turn, step: d.step,
455
+ retryId: d.retryId, retry: d.retry,
456
+ ...(event.type === 'llm/retry' ? { provider: d.provider, mode: d.mode,
457
+ maxRetries: d.maxRetries, delayMs: d.delayMs, failure: failureDetails(d.failure) } : {}),
458
+ } })
446
459
  case 'session/title':
447
460
  return Object.assign(base, {
448
461
  event: {
@@ -474,6 +487,7 @@ function buildWireEvent(session, event) {
474
487
  callId: d.message?.toolCallId ?? d.message?.source?.callId,
475
488
  isError: d.message?.isError === true || !!d.error || ((d.message && d.message.content) || []).some(block => block?.type === 'tool-result' && block.isError === true),
476
489
  preview,
490
+ ...toolResultDetails(d),
477
491
  ...(d.error ? { error: d.error } : {}),
478
492
  },
479
493
  })
@@ -541,7 +555,8 @@ function buildWireEvent(session, event) {
541
555
  case 'step/start':
542
556
  case 'step/end':
543
557
  return Object.assign(base, {
544
- event: { type: event.type, turn: d.turn, step: d.step, reason: wireTurnReason(d.reason) },
558
+ event: { type: event.type, turn: d.turn, step: d.step, reason: wireTurnReason(d.reason),
559
+ ...(turnReasonDetails(d.reason) ? { reasonDetails: turnReasonDetails(d.reason) } : {}) },
545
560
  })
546
561
  default:
547
562
  return Object.assign(base, { event: { type: event.type } })
@@ -945,20 +960,31 @@ function createFileTransferManager(api, options) {
945
960
  if (!stat.isDirectory()) {
946
961
  return fileTransferError('file-workspace-unavailable', 'the session working directory is unavailable', requestType, sessionId)
947
962
  }
948
- return { root }
963
+ return { root, inputRoot: path.resolve(item.cwd) }
949
964
  } catch {
950
965
  return fileTransferError('file-workspace-unavailable', 'the session working directory is unavailable', requestType, sessionId)
951
966
  }
952
967
  }
953
968
 
954
969
  const resolveWorkspaceTarget = async (sessionId, rawPath, requestType, inputOptions) => {
955
- const requested = normalizedWorkspaceInput(rawPath, inputOptions)
970
+ // Only the resolver accepts native absolute paths from recorded deliveries
971
+ // or Markdown links. Download requests remain workspace-relative.
972
+ const absoluteInput = inputOptions?.allowAbsolute === true
973
+ && typeof rawPath === 'string' && path.isAbsolute(rawPath.trim())
974
+ const requested = absoluteInput
975
+ ? (rawPath.includes('\0') || rawPath.trim().split(/[\\/]+/).includes('..') ? null : rawPath.trim())
976
+ : normalizedWorkspaceInput(rawPath, inputOptions)
956
977
  if (!requested) {
957
- return fileTransferError('bad-request', `${requestType} requires a relative workspace path`, requestType, sessionId)
978
+ return fileTransferError('bad-request', `${requestType} requires a valid ${inputOptions?.allowAbsolute ? '' : 'relative '}workspace path`, requestType, sessionId)
958
979
  }
959
980
  const rootResult = await resolveSessionRoot(sessionId, requestType)
960
981
  if (rootResult.kind === 'error') return rootResult
961
- const candidate = path.resolve(rootResult.root, requested)
982
+ // macOS commonly exposes one workspace as both /var/... and /private/var/...
983
+ // (and cwd itself may be a symlink). Map only the known cwd alias before
984
+ // enforcing the canonical root, then still verify the target's realpath.
985
+ const candidate = absoluteInput && isInsideWorkspace(rootResult.inputRoot, requested)
986
+ ? path.resolve(rootResult.root, path.relative(rootResult.inputRoot, requested))
987
+ : path.resolve(rootResult.root, requested)
962
988
  if (!isInsideWorkspace(rootResult.root, candidate)) {
963
989
  return fileTransferError('file-not-allowed', 'path must stay inside the session working directory', requestType, sessionId)
964
990
  }
@@ -1019,6 +1045,30 @@ function createFileTransferManager(api, options) {
1019
1045
  }
1020
1046
  }
1021
1047
 
1048
+ // 文件卡片与正文文件引用:把工作目录相对路径或主机原生绝对路径解析成
1049
+ // 下载协议需要的相对路径与预览元数据。解析不需要先遍历目录,因此文件位于
1050
+ // build/ 等未加载过的子目录时也能直接打开。
1051
+ const resolveFile = async (msg) => {
1052
+ const session = requireSessionId(msg)
1053
+ if (session.error) return session.error
1054
+ const requestId = typeof msg.requestId === 'string' && msg.requestId.trim() ? msg.requestId.trim() : null
1055
+ if (!requestId) return fileTransferError('bad-request', 'file-resolve requires a requestId', 'file-resolve', session.value)
1056
+ const resolved = await resolveWorkspaceTarget(session.value, msg.path, 'file-resolve', { allowAbsolute: true })
1057
+ if (resolved.kind === 'error') return resolved
1058
+ if (!resolved.stat.isFile()) {
1059
+ return fileTransferError('file-not-regular', 'only regular files can be previewed', 'file-resolve', session.value)
1060
+ }
1061
+ if (resolved.stat.size > options.fileDownloadMaxBytes) {
1062
+ return fileTransferError('file-too-large', 'file exceeds the configured download limit', 'file-resolve', session.value)
1063
+ }
1064
+ return {
1065
+ kind: 'file-resolved', requestId, sessionId: session.value,
1066
+ path: workspaceRelativePath(resolved.root, resolved.target),
1067
+ name: path.basename(resolved.target), mediaType: fileMediaType(resolved.target),
1068
+ size: resolved.stat.size, modifiedAt: resolved.stat.mtimeMs,
1069
+ }
1070
+ }
1071
+
1022
1072
  const open = async (client, msg) => {
1023
1073
  const requestId = typeof msg.requestId === 'string' && msg.requestId.trim() ? msg.requestId.trim() : null
1024
1074
  const session = requireSessionId(msg)
@@ -1160,6 +1210,7 @@ function createFileTransferManager(api, options) {
1160
1210
  return fileTransferError('file-download-disabled', 'file downloads are disabled by gateway configuration', msg.type)
1161
1211
  }
1162
1212
  if (msg.type === 'file-list') return fileList(msg)
1213
+ if (msg.type === 'file-resolve') return resolveFile(msg)
1163
1214
  if (msg.type === 'file-download-open') return open(client, msg)
1164
1215
  if (msg.type === 'file-download-read') return read(client, msg)
1165
1216
  if (msg.type === 'file-download-cancel') return cancel(client, msg)
@@ -1355,12 +1406,14 @@ function trimConversationEvent(event) {
1355
1406
  case 'assistant/message':
1356
1407
  case 'assistant/attempt': {
1357
1408
  const { stream, ...data } = event.data || {}
1358
- return { ...event, data }
1409
+ const finish = assistantFinish(event.data || {})
1410
+ return { ...event, data: { ...data, ...(finish ? { finish } : {}) } }
1359
1411
  }
1360
1412
  case 'tool/result': {
1361
1413
  const d = event.data || {}
1362
1414
  const message = d.message
1363
- if (!message || !Array.isArray(message.content)) return event
1415
+ const details = toolResultDetails(d)
1416
+ if (!message || !Array.isArray(message.content)) return { ...event, data: { ...d, ...details } }
1364
1417
  let changed = false
1365
1418
  const truncateBlock = (block) => {
1366
1419
  if (!block || typeof block !== 'object') return block
@@ -1374,8 +1427,8 @@ function trimConversationEvent(event) {
1374
1427
  return block
1375
1428
  }
1376
1429
  const content = message.content.map(truncateBlock)
1377
- if (!changed) return event
1378
- return { ...event, data: { ...d, message: { ...message, content } } }
1430
+ if (!changed) return { ...event, data: { ...d, ...details } }
1431
+ return { ...event, data: { ...d, ...details, message: { ...message, content } } }
1379
1432
  }
1380
1433
  default:
1381
1434
  return event
@@ -2422,18 +2475,46 @@ function extractCredential(req, allowQueryToken) {
2422
2475
  return undefined
2423
2476
  }
2424
2477
 
2478
+ const CLIENT_DEVICE_ID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/
2479
+ // A raw subprotocol must also be a valid RFC 6455 token. In particular, ':'
2480
+ // is valid in the header form but cannot be constructed by browser clients.
2481
+ const CLIENT_DEVICE_ID_SUBPROTOCOL_PATTERN = /^[A-Za-z0-9._-]{8,128}$/
2482
+ const MAX_ENCODED_DEVICE_NAME_LENGTH = 512
2483
+
2425
2484
  function extractClientDeviceId(req) {
2426
- const value = req.headers['x-dsh-device-id']
2427
- if (typeof value !== 'string') return undefined
2428
- const normalized = value.trim()
2429
- return /^[A-Za-z0-9._:-]{8,128}$/.test(normalized) ? normalized : undefined
2485
+ const header = req.headers['x-dsh-device-id']
2486
+ if (typeof header === 'string') {
2487
+ const normalized = header.trim()
2488
+ if (CLIENT_DEVICE_ID_PATTERN.test(normalized)) return normalized
2489
+ }
2490
+ // 浏览器等客户端无法设置自定义握手头,而子协议是浏览器唯一能自定义的握手元数据。
2491
+ // 让这类客户端把同一安装级设备 ID 放进 `dsh-device.<id>` 子协议即可完成配对。
2492
+ // 设备 ID 不是凭证:配对仍需要一次性配对码,长期 token 仍由 claimPairing() 签发。
2493
+ for (const protocol of parseProtocols(req)) {
2494
+ if (!protocol.startsWith('dsh-device.')) continue
2495
+ const normalized = protocol.slice('dsh-device.'.length).trim()
2496
+ if (CLIENT_DEVICE_ID_SUBPROTOCOL_PATTERN.test(normalized)) return normalized
2497
+ }
2498
+ return undefined
2430
2499
  }
2431
2500
 
2432
2501
  function extractClientDeviceName(req) {
2433
2502
  const value = req.headers['x-dsh-device-name']
2434
- if (typeof value !== 'string' || value.length > 512 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return undefined
2435
- const name = Buffer.from(value, 'base64').toString('utf8').trim()
2436
- return name && !/[\u0000-\u001f\u007f\ufffd]/.test(name) ? name.slice(0, 80) : undefined
2503
+ if (typeof value === 'string' && value.length <= MAX_ENCODED_DEVICE_NAME_LENGTH
2504
+ && /^[A-Za-z0-9+/]*={0,2}$/.test(value)) {
2505
+ const name = Buffer.from(value, 'base64').toString('utf8').trim()
2506
+ if (name && !/[\u0000-\u001f\u007f\ufffd]/.test(name)) return name.slice(0, 80)
2507
+ }
2508
+ // 同理,浏览器把设备名放进 `dsh-device-name.<base64url>`;设备名只用于展示,
2509
+ // 不参与鉴权。
2510
+ for (const protocol of parseProtocols(req)) {
2511
+ if (!protocol.startsWith('dsh-device-name.')) continue
2512
+ const encoded = protocol.slice('dsh-device-name.'.length)
2513
+ if (encoded.length > MAX_ENCODED_DEVICE_NAME_LENGTH || !/^[A-Za-z0-9_-]+$/.test(encoded)) continue
2514
+ const name = Buffer.from(encoded, 'base64url').toString('utf8').trim()
2515
+ if (name && !/[\u0000-\u001f\u007f\ufffd]/.test(name)) return name.slice(0, 80)
2516
+ }
2517
+ return undefined
2437
2518
  }
2438
2519
 
2439
2520
  function rejectUpgrade(socket, status, message, probe) {
@@ -2446,6 +2527,8 @@ function isLocalHostname(hostname) {
2446
2527
  return normalized === 'localhost' || normalized === '::1' || /^127(?:\.\d{1,3}){3}$/.test(normalized)
2447
2528
  }
2448
2529
 
2530
+ // 与客户端保持一致:只增加 Tailscale 的 100.64.0.0/10,不扩大到整个 100/8。
2531
+ // 这样局域网监听会接受同一 tailnet 的手机来源,ws:// Tailscale 地址也能用于配对。
2449
2532
  function isPrivateNetworkHostname(hostname) {
2450
2533
  let normalized = hostname.replace(/^\[|\]$/g, '').split('%')[0].toLowerCase()
2451
2534
  if (normalized.startsWith('::ffff:')) normalized = normalized.slice('::ffff:'.length)
@@ -2453,6 +2536,7 @@ function isPrivateNetworkHostname(hostname) {
2453
2536
  const octets = normalized.split('.').map((part) => Number(part))
2454
2537
  if (octets.length === 4 && octets.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
2455
2538
  return octets[0] === 10 ||
2539
+ (octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127) ||
2456
2540
  (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
2457
2541
  (octets[0] === 192 && octets[1] === 168) ||
2458
2542
  (octets[0] === 169 && octets[1] === 254)
@@ -2788,6 +2872,7 @@ const plugin = {
2788
2872
  relayEnsureTimer.unref?.()
2789
2873
  }
2790
2874
  const registry = createRegistry(deviceFile, { pairingTtlMs: options.pairingTtlMs })
2875
+ const uiState = createUiState(`${deviceFile}.ui.json`)
2791
2876
  const wss = new WebSocketServer({
2792
2877
  noServer: true,
2793
2878
  maxPayload: options.maxPayloadBytes,
@@ -2798,6 +2883,7 @@ const plugin = {
2798
2883
  },
2799
2884
  })
2800
2885
  const clients = new Set()
2886
+ const networkDiagnostics = createNetworkDiagnostics({ clients, devices: () => registry.list() })
2801
2887
  const sessionReplay = createSessionReplay()
2802
2888
  const pluginInstallOwners = new Map()
2803
2889
  const pendingQuestions = new Map()
@@ -2852,6 +2938,9 @@ const plugin = {
2852
2938
  ...(publicUrl ? [publicUrl] : []),
2853
2939
  ...(tunnel?.snapshot().publicUrl ? [tunnel.snapshot().publicUrl] : []),
2854
2940
  ...(lanListening ? lanWebSocketUrls(options, wsPath, lanBoundPort) : []),
2941
+ // Tailscale 直连地址与局域网同等作为候选:手机在同一 tailnet 时可直连,
2942
+ // 不在 tailnet 的客户端会自然失败并回退到其他候选。
2943
+ ...(lanListening ? tailscaleInterfaceStatus({ listening: true, host: options.lanHost, port: lanBoundPort, wsPath }).urls : []),
2855
2944
  ])])
2856
2945
  }
2857
2946
 
@@ -3280,6 +3369,9 @@ const plugin = {
3280
3369
  : tunnel?.snapshot().publicUrl || configuredPublicUrl() || null,
3281
3370
  platform: process.platform,
3282
3371
  cloudflare: tunnel?.snapshot() || null,
3372
+ // 本机 Tailscale 接口地址(100.64/10 或 fd7a:115c:a1e0::/48)。
3373
+ // 只用于面板展示与可选配对地址;检测到接口不等于已登录 tailnet。
3374
+ tailscale: tailscaleInterfaceStatus({ listening: lanListening, host: options.lanHost, port: lanBoundPort, wsPath }),
3283
3375
  lan: {
3284
3376
  enabled: options.lanEnabled === true,
3285
3377
  listening: lanListening,
@@ -3353,6 +3445,22 @@ const plugin = {
3353
3445
  if (body.mode === undefined && typeof body.enabled !== 'boolean') throw badRequest('mode or boolean enabled is required')
3354
3446
  setGatewayMode(body.mode !== undefined ? body.mode : (body.enabled ? 'temporary' : 'disabled'), 'changed from management UI')
3355
3447
  sendJson(res, 200, { gatewayEnabled, gatewayMode, waitExpiresAt, connectedClients: clients.size })
3448
+ } else if (req.method === 'GET' && p === '/mgw/ui') {
3449
+ sendJson(res, 200, { sidebarEntry: uiState.sidebarEntry })
3450
+ } else if (req.method === 'POST' && p === '/mgw/ui') {
3451
+ const body = await readBody(req)
3452
+ if (typeof body.sidebarEntry !== 'boolean') throw badRequest('sidebarEntry must be a boolean')
3453
+ uiState.setSidebarEntry(body.sidebarEntry)
3454
+ log(`sidebar entry ${body.sidebarEntry ? 'enabled' : 'disabled'} from management UI`)
3455
+ sendJson(res, 200, { sidebarEntry: uiState.sidebarEntry })
3456
+ } else if (req.method === 'POST' && p === '/mgw/network-test') {
3457
+ const abort = new AbortController()
3458
+ const cancel = () => abort.abort()
3459
+ res.once('close', cancel)
3460
+ try {
3461
+ const result = await networkDiagnostics.measure({ signal: abort.signal })
3462
+ if (!abort.signal.aborted) sendJson(res, 200, result)
3463
+ } finally { res.off('close', cancel) }
3356
3464
  } else if (req.method === 'POST' && p === '/mgw/cloudflare') {
3357
3465
  const body = await readBody(req)
3358
3466
  await tunnel.configure(body)
@@ -3415,26 +3523,65 @@ const plugin = {
3415
3523
  throw error
3416
3524
  }
3417
3525
  const body = await readBody(req)
3418
- const clientRoute = ['auto', 'lan', 'cloudflare', 'custom'].includes(body.route) ? body.route : null
3526
+ const clientRoute = ['auto', 'lan', 'cloudflare', 'custom', 'tailscale'].includes(body.route) ? body.route : null
3419
3527
  const cloudflareStatus = tunnel?.snapshot() || null
3420
3528
  const configuredUrl = configuredPublicUrl()
3421
3529
  const autoUrl = cloudflareStatus?.enabled && cloudflareStatus.publicReady === true
3422
3530
  ? cloudflareStatus.publicUrl
3423
3531
  : cloudflareStatus?.enabled && cloudflareStatus.publicUrl === configuredUrl && cloudflareStatus.publicReady !== true
3424
3532
  ? '' : configuredUrl
3425
- const publicUrl = clientRoute === 'auto'
3426
- ? (autoUrl ? normalizePublicUrl(autoUrl, req, wsPath) : '')
3427
- : normalizePublicUrl(body.publicUrl || configuredUrl, req, wsPath)
3533
+ // Tailscale 专用路线:只接受 ws:// + Tailscale IP。未显式给出地址时使用
3534
+ // 本机探测到的第一个地址;探测不到时明确报错,而不是退化成其他路线。
3535
+ const tailscaleUrls = lanListening
3536
+ ? tailscaleInterfaceStatus({ listening: true, host: options.lanHost, port: lanBoundPort, wsPath }).urls
3537
+ : []
3538
+ const requestedTailscaleUrl = clientRoute === 'tailscale'
3539
+ ? (() => {
3540
+ if (!lanListening) {
3541
+ const error = new Error('enable the LAN listener before generating a Tailscale pairing code')
3542
+ error.status = 409
3543
+ throw error
3544
+ }
3545
+ // 面板允许直接填主机 Tailscale IP;这里补成 ws://<ip>:<lanPort><wsPath>。
3546
+ const rawCandidate = typeof body.publicUrl === 'string' ? body.publicUrl.trim() : ''
3547
+ const bareTailscale = /^(?:\d{1,3}\.){3}\d{1,3}$/.test(rawCandidate)
3548
+ || (/^[0-9a-f:]+$/i.test(rawCandidate) && rawCandidate.includes(':'))
3549
+ const candidate = rawCandidate
3550
+ ? normalizePublicUrl(bareTailscale
3551
+ ? `ws://${rawCandidate.includes(':') ? `[${rawCandidate}]` : rawCandidate}:${lanBoundPort}${wsPath}`
3552
+ : rawCandidate, req, wsPath)
3553
+ : tailscaleUrls[0] || ''
3554
+ if (!candidate) {
3555
+ const error = new Error('no Tailscale address detected; connect this host to a tailnet and keep the LAN listener enabled')
3556
+ error.status = 409
3557
+ throw error
3558
+ }
3559
+ const parsed = new URL(candidate)
3560
+ if (parsed.protocol !== 'ws:' || !isTailscaleIp(parsed.hostname.replace(/^\[|\]$/g, ''))) {
3561
+ const error = new Error('Tailscale pairing requires a ws:// Tailscale IP address')
3562
+ error.status = 409
3563
+ throw error
3564
+ }
3565
+ return parsed.toString()
3566
+ })()
3567
+ : ''
3568
+ const publicUrl = clientRoute === 'tailscale'
3569
+ ? requestedTailscaleUrl
3570
+ : clientRoute === 'auto'
3571
+ ? (autoUrl ? normalizePublicUrl(autoUrl, req, wsPath) : '')
3572
+ : normalizePublicUrl(body.publicUrl || configuredUrl, req, wsPath)
3428
3573
  if (clientRoute) {
3429
3574
  const discoveredLan = lanListening
3430
3575
  ? lanWebSocketUrls(options, wsPath, lanBoundPort).find(isRoutablePrivateEndpoint)
3431
3576
  : ''
3432
3577
  const configuredLan = configuredEndpoints.find(isRoutablePrivateEndpoint) || ''
3433
- const appUrl = normalizePublicUrl(
3434
- body.lanUrl || body.appUrl || discoveredLan || configuredLan || (isRoutablePrivateEndpoint(publicUrl) ? publicUrl : ''),
3435
- req,
3436
- wsPath,
3437
- )
3578
+ const appUrl = clientRoute === 'tailscale'
3579
+ ? requestedTailscaleUrl
3580
+ : normalizePublicUrl(
3581
+ body.lanUrl || body.appUrl || discoveredLan || configuredLan || (isRoutablePrivateEndpoint(publicUrl) ? publicUrl : ''),
3582
+ req,
3583
+ wsPath,
3584
+ )
3438
3585
  if (!isRoutablePrivateEndpoint(appUrl)) {
3439
3586
  const error = new Error('enable or configure a reachable LAN WebSocket address before generating a multi-client QR code')
3440
3587
  error.status = 409
@@ -3449,26 +3596,37 @@ const plugin = {
3449
3596
  error.status = 409
3450
3597
  throw error
3451
3598
  }
3452
- const lanEndpoints = advertisedEndpoints(appUrl)
3453
- .filter(isRoutablePrivateEndpoint)
3599
+ const lanEndpoints = clientRoute === 'tailscale'
3600
+ ? [...new Set([appUrl, ...tailscaleUrls.map((url) => normalizePublicUrl(url, req, wsPath))])]
3601
+ .filter((url) => {
3602
+ try {
3603
+ const parsed = new URL(url)
3604
+ return parsed.protocol === 'ws:' && isTailscaleIp(parsed.hostname.replace(/^\[|\]$/g, ''))
3605
+ } catch { return false }
3606
+ })
3607
+ .slice(0, 16)
3608
+ : advertisedEndpoints(appUrl).filter(isRoutablePrivateEndpoint)
3454
3609
  const appEndpoints = [...new Set([
3455
- ...(clientRoute !== 'lan' && hasPublicRoute ? [publicUrl] : []),
3610
+ ...(clientRoute !== 'lan' && clientRoute !== 'tailscale' && hasPublicRoute ? [publicUrl] : []),
3456
3611
  ...lanEndpoints,
3457
3612
  ])].slice(0, 16)
3458
3613
  // 全网络自动选路路由表:客户端按自身能力从 lan/public/relay 中挑选,
3459
3614
  // 一个二维码同时覆盖外网与局域网(契约见 dsh-weapp/docs/auto-route-selection.md)。
3460
- // route=lan 是运营者明确选择的「只给局域网」,不泄露公网/中继信息。
3461
- const routeTable = clientRoute === 'lan' ? null : {
3462
- lan: lanEndpoints,
3463
- public: hasPublicRoute ? [publicUrl] : [],
3464
- ...(relayState.relay ? { relay: {
3465
- relay: relayState.relay.relay,
3466
- nodeId: relayState.relay.nodeId,
3467
- agentPubKey: relayState.relay.agentPubKey,
3468
- gatewayName: relayState.relay.gatewayName,
3469
- authMode: 'gateway'
3470
- } } : {})
3471
- }
3615
+ // route=lan / route=tailscale 是运营者明确选择的单一线路:不泄露公网、
3616
+ // 中继或其他局域网地址。
3617
+ const routeTable = clientRoute === 'lan' ? null
3618
+ : clientRoute === 'tailscale' ? { lan: lanEndpoints }
3619
+ : {
3620
+ lan: lanEndpoints,
3621
+ public: hasPublicRoute ? [publicUrl] : [],
3622
+ ...(relayState.relay ? { relay: {
3623
+ relay: relayState.relay.relay,
3624
+ nodeId: relayState.relay.nodeId,
3625
+ agentPubKey: relayState.relay.agentPubKey,
3626
+ gatewayName: relayState.relay.gatewayName,
3627
+ authMode: 'gateway'
3628
+ } } : {})
3629
+ }
3472
3630
  const primaryUrl = appEndpoints[0] || appUrl
3473
3631
  let miniProgramRoute = null
3474
3632
  if (clientRoute !== 'lan' && hasPublicRoute) {
@@ -3567,6 +3725,19 @@ const plugin = {
3567
3725
  qrPayload,
3568
3726
  svg,
3569
3727
  })
3728
+ } else if (req.method === 'POST' && p === '/mgw/devices/revoke-offline') {
3729
+ // 一键清除离线设备:只吊销当前没有活跃连接的设备,在线设备不受影响。
3730
+ const offline = registry.list().filter((device) => !device.online || device.connections === 0)
3731
+ const removed = []
3732
+ for (const device of offline) {
3733
+ if (!registry.revoke(device.id)) continue
3734
+ removed.push(device.id)
3735
+ for (const client of clients) {
3736
+ if (client.deviceId === device.id) client.close(4003, 'device revoked')
3737
+ }
3738
+ }
3739
+ if (removed.length > 0) log(`offline devices revoked: ${removed.length}`)
3740
+ sendJson(res, 200, { removed, count: removed.length })
3570
3741
  } else if (req.method === 'POST' && p.startsWith('/mgw/devices/') && p.endsWith('/revoke')) {
3571
3742
  const id = decodeURIComponent(p.slice('/mgw/devices/'.length, -'/revoke'.length))
3572
3743
  const revoked = registry.revoke(id)
@@ -3613,8 +3784,8 @@ const plugin = {
3613
3784
  if (credential && credential.kind === 'pairing') {
3614
3785
  const clientDeviceId = extractClientDeviceId(req)
3615
3786
  if (!clientDeviceId) {
3616
- log('pairing rejected: missing X-DSH-Device-ID (outdated client)')
3617
- rejectUpgrade(socket, 400, 'pairing requires X-DSH-Device-ID; update the iOS client')
3787
+ log('pairing rejected: missing or invalid stable device ID')
3788
+ rejectUpgrade(socket, 400, 'pairing requires a stable device ID via X-DSH-Device-ID or dsh-device.<id>')
3618
3789
  return
3619
3790
  }
3620
3791
  paired = registry.claimPairing(credential.value, clientDeviceId, extractClientDeviceName(req))
@@ -3640,6 +3811,7 @@ const plugin = {
3640
3811
 
3641
3812
  wss.handleUpgrade(req, socket, head, (ws) => {
3642
3813
  const id = ++counter
3814
+ ws.connectionId = id
3643
3815
  ws.filterSessionId = undefined
3644
3816
  const requestedChannel = req.headers['x-dsh-channel']
3645
3817
  ws.mobileChannel = ['control', 'conversation'].includes(requestedChannel) ? requestedChannel : 'legacy'
@@ -3805,7 +3977,7 @@ const plugin = {
3805
3977
  return
3806
3978
  }
3807
3979
  void fileUploads.handle(ws, msg).then(sendFrame)
3808
- } else if (msg.type === 'file-list' || msg.type === 'file-download-open' ||
3980
+ } else if (msg.type === 'file-list' || msg.type === 'file-resolve' || msg.type === 'file-download-open' ||
3809
3981
  msg.type === 'file-download-read' || msg.type === 'file-download-cancel') {
3810
3982
  fileTransfers.handle(ws, msg).then((frame) => {
3811
3983
  if (frame && ws.readyState === 1) ws.send(stringifyWireFrame(frame))
@@ -3897,6 +4069,7 @@ const plugin = {
3897
4069
  historyFormatVersion: SESSION_FORMAT_VERSION,
3898
4070
  capabilities: [
3899
4071
  'split-channels',
4072
+ 'network-diagnostics-v1',
3900
4073
  'assistant-stream-v1',
3901
4074
  'session-resume-v1',
3902
4075
  'history-format-version',
@@ -4107,7 +4280,10 @@ const plugin = {
4107
4280
 
4108
4281
  const disposeQuestions = ctx.on('user-questions/request', (request, next) => {
4109
4282
  const sessionId = request?.agent?.id === undefined ? null : String(request.agent.id)
4110
- if (!sessionId || !Array.isArray(request.questions) || !hasInteractionClient(sessionId)) return next()
4283
+ // 与审批一致:网关开启时登记所有待答提问,让稍后连接或切换会话的设备也能接收重放。
4284
+ // 是否向某个连接实时广播仍由 broadcastInteractionFrame 的 sessionId 过滤器决定;
4285
+ // startDownstreamQuestion 里保留「没有移动客户端时回退给 WebUI」的语义。
4286
+ if (!sessionId || !Array.isArray(request.questions) || !gatewayEnabled) return next()
4111
4287
  const rpcId = crypto.randomUUID()
4112
4288
  return new Promise((resolve, reject) => {
4113
4289
  const requestSignal = request.signal
@@ -4139,7 +4315,9 @@ const plugin = {
4139
4315
 
4140
4316
  const disposeApprovals = ctx.on('approval/request', (request, next) => {
4141
4317
  const sessionId = request?.agent?.id === undefined ? null : String(request.agent.id)
4142
- if (!sessionId || typeof request.toolName !== 'string' || !hasInteractionClient(sessionId)) return next()
4318
+ // 控制连接重连期间仍登记待审批,桌面端继续处理同一个请求;
4319
+ // 若桌面端仍在等待,稍后连接的设备可以重放;无可用答复时保持原有回退行为。
4320
+ if (!sessionId || typeof request.toolName !== 'string' || !gatewayEnabled) return next()
4143
4321
  const rpcId = crypto.randomUUID()
4144
4322
  const approvalId = crypto.randomUUID()
4145
4323
  return new Promise((resolve, reject) => {
@@ -4170,6 +4348,8 @@ const plugin = {
4170
4348
  pendingApprovals.set(rpcId, pending)
4171
4349
  broadcastInteractionFrame(approvalFrameFor(rpcId, pending))
4172
4350
  startDownstreamApproval(pending)
4351
+ // 登记时没有移动客户端:立刻交回 WebUI,避免挂住工具调用。
4352
+ if (!hasInteractionClient(sessionId)) fallbackApproval(pending)
4173
4353
  log(`approval requested: rpcId=${rpcId} approvalId=${approvalId} session=${sessionId} tool=${request.toolName}`)
4174
4354
  })
4175
4355
  }, { prepend: true })
@@ -4347,6 +4527,7 @@ const plugin = {
4347
4527
  clearInterval(fileTransferExpiryTimer)
4348
4528
  backgroundStreamAbort.abort()
4349
4529
  speechInput.dispose()
4530
+ networkDiagnostics.dispose()
4350
4531
  // Aborts the host Peer every Remote call speaks for, so 0.2.1 hosts end
4351
4532
  // the plugin's streams immediately instead of at Peer GC.
4352
4533
  api.dispose()
@@ -0,0 +1,126 @@
1
+ // 网关侧网络诊断:向每条已鉴权移动连接发一次 WebSocket ping,量出往返时延。
2
+ //
3
+ // 设计取自上游 mobile-gateway(v0.11.2)的 network-diagnostics,但本仓库的
4
+ // 客户端是原生 ws 对象(没有 transport adapter 抽象),所以这里直接对 ws
5
+ // 发 ping;RTC 统计(rtc-ice)不适用,测量方式固定为 websocket-ping。
6
+ //
7
+ // 仅本机管理接口调用:/mgw/network-test(loopback 由 mgw 路由统一把关),
8
+ // 移动端不主动触发测量,避免被当成探测工具。
9
+ import crypto from 'node:crypto'
10
+
11
+ const MAX_CLIENTS = 256
12
+ const CONCURRENCY = 8
13
+ const SAMPLE_WINDOW_MS = 60_000
14
+ const MAX_SAMPLES = 60
15
+
16
+ export function websocketRtt(socket, { signal, timeoutMs = 3000, now = () => performance.now() } = {}) {
17
+ return new Promise(resolve => {
18
+ if (socket.readyState !== 1 || signal?.aborted) { resolve({ status: 'cancelled', rttMs: null }); return }
19
+ const payload = Buffer.from(`mgw-net:${crypto.randomUUID()}`)
20
+ const started = now()
21
+ let timer, finished = false
22
+ const finish = result => {
23
+ if (finished) return
24
+ finished = true
25
+ clearTimeout(timer)
26
+ socket.off('pong', pong); socket.off('close', closed); socket.off('error', failed)
27
+ signal?.removeEventListener('abort', aborted)
28
+ resolve({ ...result, measurement: 'websocket-ping' })
29
+ }
30
+ const pong = data => { if (Buffer.from(data).equals(payload)) finish({ status: 'ok', rttMs: Math.max(0, now() - started) }) }
31
+ const closed = () => finish({ status: 'disconnected', rttMs: null })
32
+ const failed = () => finish({ status: 'error', rttMs: null })
33
+ const aborted = () => finish({ status: 'cancelled', rttMs: null })
34
+ socket.on('pong', pong); socket.once('close', closed); socket.once('error', failed)
35
+ signal?.addEventListener('abort', aborted, { once: true })
36
+ timer = setTimeout(() => finish({ status: 'timeout', rttMs: null }), timeoutMs)
37
+ try { socket.ping(payload, error => { if (error) failed() }) } catch { failed() }
38
+ })
39
+ }
40
+
41
+ async function abortable(operation, signal, timeoutMs = 3000) {
42
+ const safe = Promise.resolve(operation).catch(() => ({ status: 'error', rttMs: null }))
43
+ if (signal?.aborted) return { status: 'cancelled', rttMs: null }
44
+ let timer, onAbort
45
+ try {
46
+ return await Promise.race([
47
+ safe,
48
+ new Promise(resolve => {
49
+ onAbort = () => resolve({ status: 'cancelled', rttMs: null })
50
+ signal?.addEventListener('abort', onAbort, { once: true })
51
+ timer = setTimeout(() => resolve({ status: 'timeout', rttMs: null }), timeoutMs)
52
+ }),
53
+ ])
54
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort', onAbort) }
55
+ }
56
+
57
+ export function createNetworkDiagnostics({ clients, devices, now = () => Date.now() }) {
58
+ let busy = false, disposed = false, last = null, activeAbort
59
+ // ws -> [{ at, rttMs }];连接关闭后随对象回收,下一次清理时一并删掉。
60
+ const histories = new WeakMap()
61
+ return {
62
+ async measure({ signal } = {}) {
63
+ if (disposed) throw new Error('network diagnostics disposed')
64
+ if (busy) throw Object.assign(new Error('network diagnostics busy'), { status: 409 })
65
+ if (signal?.aborted) return { at: now(), devices: [] }
66
+ // 1 秒内重复点击复用上一次结果,避免管理面板连点打满 ping。
67
+ if (last && now() - last.at < 1000) return last
68
+ busy = true
69
+ const abort = new AbortController()
70
+ activeAbort = abort
71
+ const cancel = () => abort.abort()
72
+ signal?.addEventListener('abort', cancel, { once: true })
73
+ try {
74
+ const connections = [...clients].filter(client => client.readyState === 1 && client.deviceId).slice(0, MAX_CLIENTS)
75
+ const known = new Map(devices().map(device => [device.id, device]))
76
+ const rows = new Array(connections.length)
77
+ let index = 0
78
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, connections.length) }, async () => {
79
+ while (!abort.signal.aborted) {
80
+ const current = index++
81
+ if (current >= connections.length) break
82
+ const client = connections[current]
83
+ let result
84
+ try { result = await abortable(websocketRtt(client, { signal: abort.signal }), abort.signal) }
85
+ catch { result = { status: 'error', rttMs: null } }
86
+ if (!result || typeof result !== 'object') result = { status: 'unavailable', rttMs: null }
87
+ if (client.readyState !== 1 || !clients.has(client)) result = { status: 'disconnected', rttMs: null }
88
+ if (result.status !== 'ok' || !Number.isFinite(result.rttMs) || result.rttMs < 0) result.rttMs = null
89
+ const history = histories.get(client) || []
90
+ if (!abort.signal.aborted && result.status !== 'cancelled') {
91
+ history.push({ at: now(), rttMs: result.rttMs })
92
+ while (history.length && (history.length > MAX_SAMPLES || now() - history[0].at > SAMPLE_WINDOW_MS)) history.shift()
93
+ histories.set(client, history)
94
+ }
95
+ const rtts = history.map(item => item.rttMs).filter(Number.isFinite).sort((a, b) => a - b)
96
+ rows[current] = {
97
+ deviceId: client.deviceId,
98
+ name: known.get(client.deviceId)?.displayName || known.get(client.deviceId)?.name || '',
99
+ connectionId: client.connectionId ?? null,
100
+ channel: client.mobileChannel,
101
+ transport: 'websocket',
102
+ ...result,
103
+ samples: history.map(({ at, rttMs }) => ({ at, rttMs })),
104
+ p95RttMs: rtts.length ? rtts[Math.ceil(rtts.length * .95) - 1] : null,
105
+ averageRttMs: rtts.length ? rtts.reduce((a, b) => a + b, 0) / rtts.length : null,
106
+ }
107
+ }
108
+ }))
109
+ const grouped = new Map()
110
+ for (const row of rows.filter(Boolean)) {
111
+ if (!grouped.has(row.deviceId)) grouped.set(row.deviceId, { deviceId: row.deviceId, name: row.name, channels: [] })
112
+ const { deviceId, name, ...channel } = row
113
+ grouped.get(deviceId).channels.push(channel)
114
+ }
115
+ const snapshot = {
116
+ at: now(),
117
+ devices: [...grouped.values()],
118
+ truncated: [...clients].filter(client => client.readyState === 1 && client.deviceId).length > connections.length,
119
+ }
120
+ if (!abort.signal.aborted) last = snapshot
121
+ return snapshot
122
+ } finally { signal?.removeEventListener('abort', cancel); activeAbort = null; busy = false }
123
+ },
124
+ dispose() { disposed = true; activeAbort?.abort(); last = null },
125
+ }
126
+ }