dsh-remote-plugin 0.7.3 → 0.7.5

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.en.md CHANGED
@@ -1,72 +1,53 @@
1
1
  # dsh-remote-plugin
2
2
 
3
- The official DSH bundle plugin for DSH Remote. It adds a DSH sidebar entry, a compact status panel, a full admin console, and a gateway managed alongside DSH.
3
+ The DSH bundle plugin for DSH Remote adds a sidebar entry, status panel, admin console, and a bundled gateway that respects the user's start/stop intent.
4
4
 
5
5
  [English](README.en.md) · [中文](README.md)
6
6
 
7
- ## Install
7
+ ## Install and connect
8
8
 
9
9
  ```sh
10
- dsh plugin --profile web add dsh-remote-plugin
10
+ dsh plugin --profile web add dsh-remote-plugin@latest
11
11
  dsh plugin --profile web list --depth 0
12
-
13
- # Optional version pin
14
- dsh plugin --profile web add dsh-remote-plugin@0.6.8
15
12
  ```
16
13
 
17
- The second command verifies installation in the `web` profile. Completely restart DSH Web and hard-refresh with Ctrl+F5. For a user service, a typical restart is `systemctl --user restart dsh-web`; for a manual setup, stop the old `dsh web` process and launch it again.
18
-
19
- Open `http://127.0.0.1:8787/health` on the DSH host before pairing a phone. Once it returns JSON, connect the phone to `http://PC-LAN-IP:8787` or the host's Tailscale IP. Do not use `127.0.0.1` or `localhost` on the phone; those point to the phone itself.
20
-
21
- ## What the plugin provides
14
+ Use the actual profile for custom setups. DSH Desktop uses its own plugin manager and needs a complete exit/reopen. For Web, fully restart DSH Web, hard-refresh with Ctrl+F5 and open Remote in the sidebar.
22
15
 
23
- - Compact panel: gateway state, connected devices, token usage, and quick actions.
24
- - Admin console: port, upstream, devices, requests, token statistics, QR pairing, and token rotation.
25
- - Bundled `gateway.cjs`: Bearer-token gateway listening on `0.0.0.0:8787` by default.
26
- - Self-healing lifecycle: relaunches the gateway after a DSH restart or unexpected exit; start and stop it from the panel.
27
- - `/fs/*` file endpoints: list, download, chunked upload, resume, pause/continue/cancel, and SHA-256 verification.
28
- - Mobile, desktop, and admin WebUI assets, plus the Android APK distributed with the plugin.
16
+ On the host, open `http://127.0.0.1:8787/health`, then pair through the admin QR code. A phone connects to `http://PC-LAN-IP:8787` with its token, not its own localhost. RCs use `@next`; pin an existing version with `@<version>`.
29
17
 
30
- ## Mobile capabilities
18
+ ## Capabilities and limits
31
19
 
32
- The Android app / mobile WebUI has five main destinations: Sessions, Files, Home, Stats, and Settings. Session detail supports goals, subagent interruption, model selection, fullscreen input, slash commands, and image attachments. Images can come from the camera or gallery and are sent as image content in `session.prompt`.
20
+ - Status panel, admin console, Doctor, automatic management and explicit stop intent.
21
+ - Bearer authentication, optional per-device keys and short-lived WS tickets.
22
+ - mux/host downlinks, independent long polling, weak-network settings and local history.
23
+ - Allowed file roots, resumable chunks, hashes, previews/downloads and image attachments.
24
+ - Current-host plugin management and optional context/cost insights.
25
+ - Mobile navigation: Sessions, Files, Home, Plugins, Settings; five Web themes.
26
+ - Existing Android APKs are bundled when available; notifications/background require device permissions.
27
+ - Windows Desktop lifecycle control is experimental, needs verified instance evidence and does not configure login startup.
28
+ - HarmonyOS is a separate source project; release CI does not build HAPs. Insights and Web GenUI are not ported.
29
+ - Android ASR was removed; the feature-test page retains navigation only.
33
30
 
34
- Notification settings include approval / question notifications, background polling, peak reminders, task completion notices, and announcement history. Announcements update from a central HTTPS source every 30 seconds while the app is in the foreground, with gateway-cache and bundled-file fallback. Four themes are retained: Default Deep Space, Sunset, Elbphilharmonie, and Prairie Tower.
31
+ ## Configuration and troubleshooting
35
32
 
36
- ## Gateway configuration
33
+ Plugin port priority: `DSH_REMOTE_GATEWAY_PORT` → `~/.dsh-remote/gateway-port` → 8787. Bind address priority: `DSH_REMOTE_GATEWAY_HOST` → `HOST` → gateway-host file → `0.0.0.0`. The plugin passes the actual DSH upstream.
37
34
 
38
- - Port priority: `DSH_REMOTE_GATEWAY_PORT` → `~/.dsh-remote/gateway-port` → `8787`.
39
- - Token: `~/.dsh-remote/token`, generated on first run.
40
- - Self-healing: `~/.dsh-remote/gateway.enabled`; use `DSH_REMOTE_AUTOSTART=0` to disable automatic management.
41
- - File roots: registered DSH workspaces are allowed automatically; configure other directories with `DSH_REMOTE_FS_ROOT`, separated by `:` on Linux/macOS and `;` on Windows.
42
- - Upload limit: `DSH_REMOTE_FS_MAX_UPLOAD`, 2 GB by default.
43
- - Central announcements: override the default HTTPS endpoint with `DSH_REMOTE_ANNOUNCEMENTS_URL`, or set it to an empty string to disable the central source.
44
- - DSH upstream: `http://127.0.0.1:3080` by default.
35
+ The token defaults to `~/.dsh-remote/token`; `DSH_REMOTE_AUTOSTART=0` disables automatic management. File roots, DSH workspaces and Windows defaults have specific authorization boundaries; see configuration.
45
36
 
46
- The token grants remote control of DSH. Keep it private. For cross-network access, prefer Tailscale or another authenticated secure tunnel.
47
-
48
- ## Gateway cannot be opened
49
-
50
- ```bash
51
- curl -i http://127.0.0.1:8787/health
52
- ss -ltnp | grep ':8787'
53
- curl -i http://127.0.0.1:3080/
54
- ```
37
+ For local refusal, check the actual profile, full restart and port ownership. Degraded upstream means troubleshoot DSH. For phone access, check network/firewall; for 401, pair again; for stale assets, hard-refresh. Embedded admin uses the DSH login boundary; standalone admin uses the Remote master token. A transient gateway is not necessarily a persistent systemd service.
55
38
 
56
- - If port 8787 refuses locally, verify the `web` profile installation, gateway state in the plugin panel, a real DSH Web restart, and port ownership.
57
- - If `/health` works but `upstreamOk` is false, the gateway is running; troubleshoot DSH Web on port 3080.
58
- - If local access works but the phone fails, use the host LAN/Tailscale IP and permit inbound TCP 8787. Do not expose port 3080 publicly.
59
- - A 401 response means the token is wrong; pair again or copy the current `~/.dsh-remote/token`.
60
- - For a blank/stale page after an upgrade, hard-refresh or fully close and reopen the app.
39
+ Keep QR codes and credentials private. Prefer Tailscale across networks. Remote device/master tokens and the DSH upstream Cookie have separate roles.
61
40
 
62
- The managed gateway may be a transient process. Do not rely on `systemctl --user restart dsh-remote-gateway.service`; use Start Gateway in the plugin panel or restart DSH Web to trigger self-healing.
41
+ ## Documentation
63
42
 
64
- ## Links
43
+ - [Documentation index](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/README.md)
44
+ - [Installation](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/getting-started.md)
45
+ - [Configuration](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/configuration.md)
46
+ - [Troubleshooting](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/troubleshooting.md)
47
+ - [Main project](https://github.com/Blank-not-black/dsh-Remote)
48
+ - [Releases](https://github.com/Blank-not-black/dsh-Remote/releases)
65
49
 
66
- - Admin page: `http://<gateway-ip>:8787/admin`
67
- - Desktop WebUI: `http://<gateway-ip>:8787`
68
- - Main project: [dsh-Remote](https://github.com/Blank-not-black/dsh-Remote)
69
- - Stable releases: [GitHub Releases](https://github.com/Blank-not-black/dsh-Remote/releases/latest)
50
+ Checked against repository 0.7.4 on 2026-10-12. This does not verify current npm tags, installed devices or all platform behavior. Detailed guides are currently in Chinese.
70
51
 
71
52
  ## License
72
53
 
package/README.md CHANGED
@@ -1,72 +1,53 @@
1
1
  # dsh-remote-plugin
2
2
 
3
- DSH Remote 的官方 bundle 插件:在 DSH 侧边栏提供入口,打开快速状态面板和完整管理控制台,并内置随 DSH 自动启停的远程网关。
3
+ DSH Remote 的 DSH bundle 插件:提供侧栏入口、快速面板、管理控制台及受用户启停意图约束的内置网关。
4
4
 
5
5
  **中文** · [English](README.en.md)
6
6
 
7
- ## 安装
7
+ ## 安装与连接
8
8
 
9
9
  ```sh
10
- dsh plugin --profile web add dsh-remote-plugin
10
+ dsh plugin --profile web add dsh-remote-plugin@latest
11
11
  dsh plugin --profile web list --depth 0
12
-
13
- # 也可以安装指定版本
14
- dsh plugin --profile web add dsh-remote-plugin@0.6.8
15
12
  ```
16
13
 
17
- 第二条命令用于确认插件安装在正确的 `web` profile。然后完整重启 DSH Web 进程并 Ctrl+F5 强刷浏览器,左侧边栏会出现 DSH Remote 入口。如果 DSH Web 由 systemd 用户服务管理,可执行 `systemctl --user restart dsh-web`;手动运行时则需停止旧的 `dsh web` 进程后重新启动。
18
-
19
- 安装后先在 DSH 主机访问 `http://127.0.0.1:8787/health`。看到 JSON 后再用手机连接 `http://电脑局域网IP:8787`;手机上的 `127.0.0.1` 和 `localhost` 指向手机自己,不是 DSH 主机。
20
-
21
- ## 插件提供什么
14
+ 示例针对 Web profile;自定义 profile 使用实际名称。DSH Desktop 从自身插件管理入口安装,完整退出并重开。Web 安装完成后完整重启 DSH Web,Ctrl+F5,从侧栏打开 Remote。
22
15
 
23
- - 快速面板:网关状态、在线设备、Token 用量和快捷操作;
24
- - 管理控制台:端口、上游、设备、请求、Token 统计、二维码和令牌轮换;
25
- - 内置 `gateway.cjs`:默认监听 `0.0.0.0:8787`,带 Bearer token 鉴权;
26
- - 网关自愈:DSH 重启或网关意外退出后自动拉起,可在面板中停止或启动;
27
- - `/fs/*` 文件端点:列表、下载、分块上传、断点续传、暂停/继续/取消和 SHA-256 校验;
28
- - 手机端、桌面端和管理页 WebUI,以及随插件分发的 Android APK。
16
+ 在主机访问 `http://127.0.0.1:8787/health`,然后从管理控制台扫码。手机手动连接填 `http://电脑局域网IP:8787` 与令牌,不能填手机 localhost。RC 使用 `@next`,固定版本使用 `@<已发布版本>`。
29
17
 
30
- ## 手机端能力
18
+ ## 当前能力与限制
31
19
 
32
- Android 应用 / 手机 WebUI 采用五个主要页面:会话、文件、主页、统计、设置。会话详情支持目标控制、子代理中断、模型切换、全屏输入、斜杠命令和图片附件。图片附件可从相机或相册选择,并以 `session.prompt` 图片内容发送到当前会话。
20
+ - 快速状态、完整管理控制台、Doctor、自启/自愈与明确停止意图。
21
+ - Bearer token、可选独立设备密钥、短时 WS ticket。
22
+ - mux/host 下行、独立长轮询、弱网设置与历史缓存。
23
+ - 文件多根、分块续传、校验、预览/下载与图片附件。
24
+ - 当前主机插件管理与可选上下文/费用洞察。
25
+ - 手机导航:会话、文件、主页、插件、设置;五套 Web 主题。
26
+ - Android APK 在已有构建产物时随包分发,通知与后台需设备权限。
27
+ - Windows Desktop 控制是实验能力,需可信实例证据,不提供登录自启。
28
+ - HarmonyOS 为独立源码工程,当前 release CI 不构建 HAP;会话洞察和 Web GenUI 未移植。
29
+ - Android ASR 桥已移除,功能测试页保留导航;不要沿用旧说明。
33
30
 
34
- 通知设置支持审批 / 提问通知、后台轮询、峰谷提醒、任务完成提醒和历史公告。公告通过中央 HTTPS 源更新,App 前台每 30 秒检查,中央源不可达时回退网关缓存或安装包内公告。当前保留四套主题:默认深空、落日、易北爱乐厅、草原孤塔。
31
+ ## 配置与排查
35
32
 
36
- ## 网关配置
33
+ 插件端口优先级:`DSH_REMOTE_GATEWAY_PORT` → `~/.dsh-remote/gateway-port` → 8787。监听地址优先级:`DSH_REMOTE_GATEWAY_HOST` → `HOST` → gateway-host 文件 → `0.0.0.0`。插件从当前 DSH 实例传入上游。
37
34
 
38
- - 网关端口优先级:`DSH_REMOTE_GATEWAY_PORT` 环境变量 → `~/.dsh-remote/gateway-port` → `8787`;
39
- - 令牌:`~/.dsh-remote/token`,首次运行自动生成;
40
- - 自愈开关:`~/.dsh-remote/gateway.enabled`,或使用 `DSH_REMOTE_AUTOSTART=0` 禁用自动管理;
41
- - 文件根目录:DSH 已登记工作区会自动放行;其他目录用 `DSH_REMOTE_FS_ROOT` 配置,Linux/macOS 使用 `:`,Windows 使用 `;`;
42
- - 文件上限:`DSH_REMOTE_FS_MAX_UPLOAD`,默认 2GB;
43
- - 中央公告:`DSH_REMOTE_ANNOUNCEMENTS_URL` 可覆盖默认 HTTPS 地址,设为空字符串可禁用中央源;
44
- - DSH 上游:默认 `http://127.0.0.1:3080`。
35
+ 令牌默认 `~/.dsh-remote/token`;`DSH_REMOTE_AUTOSTART=0` 禁用自动管理。文件授权、工作区及 Windows 默认根存在边界,详见完整配置参考。
45
36
 
46
- 令牌等同于 DSH 远程操作凭证,请不要公开或提交到仓库。局域网访问建议配合防火墙;跨网络访问建议使用 Tailscale 或其他带认证的安全隧道。
47
-
48
- ## 网关打不开
49
-
50
- ```bash
51
- curl -i http://127.0.0.1:8787/health
52
- ss -ltnp | grep ':8787'
53
- curl -i http://127.0.0.1:3080/
54
- ```
37
+ 本机拒绝连接先检查实际 profile、完整重启与端口;上游 degraded 检查 DSH;手机不可达检查网络和防火墙;401 重新配对;升级界面旧先强刷。插件内嵌管理页使用 DSH 登录边界,独立管理页使用 Remote 主令牌。不要把 transient 网关当成固定可 restart 的 systemd 服务。
55
38
 
56
- - 8787 本机也拒绝连接:检查插件是否装在 `web` profile、插件面板的网关开关、DSH Web 是否真正重启,以及 8787 是否被占用。
57
- - `/health` 能打开但 `upstreamOk: false`:网关已运行,应检查 DSH Web 的 3080 端口。
58
- - 本机能打开但手机不能:使用电脑局域网/Tailscale IP,并允许防火墙 TCP 8787 入站;不需要对公网放行 3080。
59
- - 出现 401:重新扫码或复制 `~/.dsh-remote/token`。
60
- - 页面黑屏/功能未更新:Ctrl+F5 强刷,手机端完全退出后重开。
39
+ 配对二维码包含凭证,不公开;跨网络优先 Tailscale。主令牌、设备令牌与 DSH 上游 Cookie 不混用。
61
40
 
62
- 插件网关可能以 transient 进程运行,不要依赖 `systemctl --user restart dsh-remote-gateway.service`。优先在插件面板启动网关,或重启 DSH Web 触发自愈。
41
+ ## 文档
63
42
 
64
- ## 相关地址
43
+ - [完整文档](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/README.md)
44
+ - [安装与连接](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/getting-started.md)
45
+ - [配置](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/configuration.md)
46
+ - [故障排查](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/troubleshooting.md)
47
+ - [主项目与下载](https://github.com/Blank-not-black/dsh-Remote)
48
+ - [GitHub Releases](https://github.com/Blank-not-black/dsh-Remote/releases)
65
49
 
66
- - 管理页:`http://<网关IP>:8787/admin`
67
- - 桌面 WebUI:`http://<网关IP>:8787`
68
- - 主项目:[dsh-Remote](https://github.com/Blank-not-black/dsh-Remote)
69
- - 正式版本:[GitHub Releases](https://github.com/Blank-not-black/dsh-Remote/releases/latest)
50
+ 说明按仓库 0.7.4(2026-10-12)核对,不代表当前 npm 标签、设备实装或所有平台验收结果。
70
51
 
71
52
  ## License
72
53
 
Binary file
package/gateway.cjs CHANGED
@@ -36,6 +36,51 @@ const fs = require('node:fs')
36
36
  const path = require('node:path')
37
37
  const os = require('node:os')
38
38
  const crypto = require('node:crypto')
39
+ const zlib = require('node:zlib')
40
+ const { pipeline } = require('node:stream')
41
+
42
+ // Compression is local to Remote responses, without changing DSH prototypes.
43
+ const HTTP_COMPRESSION = process.env.GATEWAY_HTTP_COMPRESSION !== '0'
44
+ function acceptsGzip(req) {
45
+ const choices = new Map(String(req.headers['accept-encoding'] || '').toLowerCase().split(',').map(part => {
46
+ const [name, ...params] = part.trim().split(';')
47
+ const weight = params.find(p => /^\s*q\s*=/.test(p))
48
+ const q = weight ? Number(weight.split('=')[1]) : 1
49
+ return [name, Number.isFinite(q) && q >= 0 && q <= 1 ? q : 0]
50
+ }))
51
+ return (choices.get('gzip') ?? choices.get('*') ?? 0) > 0
52
+ }
53
+ function compressibleType(type) {
54
+ return /^(?:text\/(?:html|css|plain|javascript|xml)|application\/(?:javascript|json|manifest\+json|xml)|image\/svg\+xml)(?:;|$)/i.test(String(type || ''))
55
+ }
56
+ function addEncodingVary(headers, existing = '') {
57
+ const values = (String(existing || '') + ',' + String(headers.vary || '')).split(',').map(v => v.trim()).filter(Boolean)
58
+ if (!values.some(v => v.toLowerCase() === 'accept-encoding' || v === '*')) values.push('Accept-Encoding')
59
+ headers.vary = values.join(', ')
60
+ return headers
61
+ }
62
+ function sendHttpBody(res, status, headers, body, compress = false) {
63
+ const data = Buffer.isBuffer(body) ? body : Buffer.from(String(body || ''))
64
+ const req = res.req, out = { ...headers }
65
+ if (compress) addEncodingVary(out, res.getHeader?.('vary'))
66
+ const finish = bytes => {
67
+ if (res.destroyed || res.writableEnded) return
68
+ res.writeHead(status, { ...out, 'content-length': bytes.length })
69
+ res.end(req?.method === 'HEAD' ? undefined : bytes)
70
+ }
71
+ if (!compress || !HTTP_COMPRESSION || !req || req.method === 'HEAD' || status !== 200 || data.length < 1024
72
+ || req.headers.range || out['content-encoding'] || /no-transform/i.test(out['cache-control'] || '')
73
+ || !compressibleType(out['content-type']) || !acceptsGzip(req)) return finish(data)
74
+ zlib.gzip(data, { level: 3 }, (error, zipped) => {
75
+ if (error || zipped.length >= data.length) return finish(data)
76
+ out['content-encoding'] = 'gzip'
77
+ finish(zipped)
78
+ })
79
+ }
80
+ function compressibleRpc(req) {
81
+ const pathname = String(req?.url || '').split('?')[0]
82
+ return ['/api/session.history', '/api/session.list', '/api/workspace.list', '/api/host.describe'].includes(pathname)
83
+ }
39
84
 
40
85
  // Crash records deliberately contain facts and source positions, never arbitrary error text.
41
86
  const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homedir(),'.dsh-remote','crashes.jsonl')
@@ -1203,13 +1248,18 @@ async function desktopProcessEvidence(config) {
1203
1248
  const d = config.desktop
1204
1249
  const script = '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $rows=@(' + [d.root.pid,d.host.pid].map(pid =>
1205
1250
  "Get-CimInstance Win32_Process -Filter 'ProcessId=" + pid + "' | ForEach-Object { @{pid=$_.ProcessId;parent=$_.ParentProcessId;executable=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')} }").join('; ') +
1206
- '); $owners=@(Get-NetTCPConnection -State Listen -LocalPort ' + UPSTREAM_PORT + ' -ErrorAction SilentlyContinue | ForEach-Object {$_.OwningProcess}); @{rows=$rows;owners=$owners} | ConvertTo-Json -Compress -Depth 4'
1251
+ '); $owners=@(Get-NetTCPConnection -State Listen -LocalPort ' + UPSTREAM_PORT + ' -ErrorAction SilentlyContinue | ForEach-Object {@{pid=$_.OwningProcess;address=$_.LocalAddress}}); @{rows=$rows;owners=$owners} | ConvertTo-Json -Compress -Depth 4'
1207
1252
  const result = await execFileResult('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',script],10000)
1208
1253
  if (!result.ok) throw new Error('无法读取 Desktop 进程身份: ' + result.stderr)
1209
1254
  return JSON.parse(result.stdout)
1210
1255
  }
1211
1256
  function verifyDesktopEvidence(config, evidence) {
1212
- const d=config.desktop, rows=evidence.rows || [], owners=evidence.owners || []
1257
+ const d=config.desktop, rows=evidence.rows || []
1258
+ const target=UPSTREAM.hostname.replace(/^\[|\]$/g,'').toLowerCase()
1259
+ const owners=(evidence.owners || []).filter(owner=>typeof owner==='number' ||
1260
+ (owner.address==='0.0.0.0' && !target.includes(':')) || owner.address==='::' ||
1261
+ (target==='localhost' ? ['127.0.0.1','::1'].includes(owner.address) : owner.address===target))
1262
+ .map(owner=>typeof owner==='number'?owner:owner.pid)
1213
1263
  const root=rows.find(row=>row.pid===d.root.pid), host=rows.find(row=>row.pid===d.host.pid)
1214
1264
  const sameExecutable=row=>row?.executable && path.resolve(row.executable).toLowerCase()===path.resolve(config.executable).toLowerCase()
1215
1265
  const rootValid=sameExecutable(root) && root.started===d.root.started && !/--(?:type|expose-internals)\b/.test(root.command || '')
@@ -1266,7 +1316,7 @@ function dshPortOccupied() {
1266
1316
  })
1267
1317
  }
1268
1318
 
1269
- async function dshProcessStatus() {
1319
+ async function dshProcessStatus({ cachedProbe = false } = {}) {
1270
1320
  const base = { ok: true, supported: true, manager: 'process', service: 'dsh-process', running: false, mainPid: 0, canRestart: false }
1271
1321
  try { readDshLaunch() } catch (err) {
1272
1322
  return { ...base, supported: false, code: 'LAUNCH_CONFIG_INVALID', message: '缺少有效 DSH 启动配置,请先从 DSH Web 启动 Remote 插件', detail: err.message }
@@ -1277,7 +1327,7 @@ async function dshProcessStatus() {
1277
1327
  return { ...base, running: true, mainPid: dshManagedChild.pid, owned: true, canRestart: true, activeState: 'active', subState: 'running' }
1278
1328
  }
1279
1329
  const occupied = await dshPortOccupied()
1280
- const probe = occupied ? await probeDshUpstream() : null
1330
+ const probe = occupied ? await (cachedProbe ? refreshHealthProbe() : probeDshUpstream()) : null
1281
1331
  return { ...base, running: !!probe?.ok, occupied, owned: false,
1282
1332
  activeState: occupied ? (probe?.ok ? 'active' : 'inactive') : dshManagedExit ? 'failed' : 'inactive',
1283
1333
  subState: occupied ? 'external' : 'stopped',
@@ -1328,17 +1378,17 @@ async function executeDshProcessAction(action) {
1328
1378
  })
1329
1379
  }
1330
1380
 
1331
- async function dshServiceStatus() {
1381
+ async function dshServiceStatus(options = {}) {
1332
1382
  if (!/^[A-Za-z0-9_.@-]+$/.test(DSH_SERVICE)) {
1333
1383
  return { ok: false, supported: false, running: false, service: DSH_SERVICE, code: 'INVALID_SERVICE', message: 'DSH_REMOTE_DSH_SERVICE 服务名配置不合法' }
1334
1384
  }
1335
1385
  if (!DSH_CONTROL_SUPPORT.supported) {
1336
1386
  return { ok: true, supported: false, running: false, service: DSH_SERVICE, ...DSH_CONTROL_SUPPORT }
1337
1387
  }
1338
- if (DSH_CONTROL_MODE === 'process') return dshProcessStatus()
1388
+ if (DSH_CONTROL_MODE === 'process') return dshProcessStatus(options)
1339
1389
  if (process.platform === 'win32') {
1340
1390
  const service = await windowsServiceStatus()
1341
- if (DSH_CONTROL_MODE === 'auto' && service.code === 'SERVICE_NOT_FOUND') return dshProcessStatus()
1391
+ if (DSH_CONTROL_MODE === 'auto' && service.code === 'SERVICE_NOT_FOUND') return dshProcessStatus(options)
1342
1392
  return { ...service, manager: 'windows' }
1343
1393
  }
1344
1394
  const r = await execFileResult(SYSTEMCTL, [
@@ -1408,12 +1458,12 @@ function delay(ms) {
1408
1458
  return new Promise(resolvePromise => setTimeout(resolvePromise, ms))
1409
1459
  }
1410
1460
 
1411
- async function probeDshUpstream() {
1461
+ async function probeDshUpstream(timeoutMs = 2500) {
1412
1462
  const startedAt = Date.now()
1413
1463
  try {
1414
1464
  const probe = await fetch(new URL(DSH_HEALTH_PATH, UPSTREAM), {
1415
1465
  headers: dshUpstreamHeaders(),
1416
- signal: AbortSignal.timeout(Math.min(2500, UPSTREAM_REQUEST_TIMEOUT_MS)),
1466
+ signal: AbortSignal.timeout(Math.min(timeoutMs, UPSTREAM_REQUEST_TIMEOUT_MS)),
1417
1467
  cache: 'no-store',
1418
1468
  })
1419
1469
  return {
@@ -1480,14 +1530,21 @@ async function desktopCrashEvidence(config) {
1480
1530
  }
1481
1531
  let desktopWatchBusy=false
1482
1532
  const desktopCrashSeen=new Set()
1533
+ const desktopMissingSince=new Map()
1483
1534
  async function checkDesktopCrash() {
1484
- if(!AUTO_RESTART||desktopWatchBusy||(dshControlOperation&&!dshControlOperation.done))return
1535
+ if(!AUTO_RESTART||!DSH_CONTROL_SUPPORT.supported||desktopWatchBusy||(dshControlOperation&&!dshControlOperation.done))return
1485
1536
  let config;try{config=readDshLaunch()}catch{return}
1486
1537
  if(config.kind!=='desktop')return
1487
1538
  const alive=pid=>{try{process.kill(pid,0);return true}catch(e){return e.code!=='ESRCH'}}
1488
- if(alive(config.desktop.root.pid)&&alive(config.desktop.host.pid))return
1539
+ if(alive(config.desktop.root.pid)&&alive(config.desktop.host.pid)){desktopMissingSince.clear();return}
1489
1540
  const identity=config.desktop.root.started+':'+config.desktop.root.pid+':'+config.desktop.host.pid
1490
1541
  if(desktopCrashSeen.has(identity)||recoveryTimers.has('desktop'))return
1542
+ if(!desktopMissingSince.has(identity)){desktopMissingSince.clear();desktopMissingSince.set(identity,Date.now())}
1543
+ // Event logs can arrive late, but a normal quit must not poll crash logs forever.
1544
+ if(Date.now()-desktopMissingSince.get(identity)>=120000){
1545
+ desktopCrashSeen.add(identity);if(desktopCrashSeen.size>20)desktopCrashSeen.delete(desktopCrashSeen.values().next().value)
1546
+ desktopMissingSince.delete(identity);return
1547
+ }
1491
1548
  desktopWatchBusy=true
1492
1549
  try{
1493
1550
  if(await desktopCrashEvidence(config)){
@@ -2167,11 +2224,10 @@ function eventPollPayload(kind, since, waitSupported = false) {
2167
2224
  function sendEventPollResponse(waiter, payload) {
2168
2225
  if (waiter.req.destroyed || waiter.res.destroyed) return
2169
2226
  cors(waiter.res)
2170
- waiter.res.writeHead(200, {
2227
+ sendHttpBody(waiter.res, 200, {
2171
2228
  'content-type': 'application/json; charset=utf-8',
2172
2229
  'cache-control': 'no-store'
2173
- })
2174
- waiter.res.end(JSON.stringify(payload))
2230
+ }, JSON.stringify(payload), true)
2175
2231
  }
2176
2232
 
2177
2233
  function finishEventPollWaiter(waiter, send = true) {
@@ -2255,11 +2311,10 @@ function serveEventPoll(req, res, url) {
2255
2311
  const payload = eventPollPayload(kind, since, waitSupported)
2256
2312
  if (payload.events.length || wait <= 0 || EVENT_POLL_WAIT_MAX <= 0) {
2257
2313
  cors(res)
2258
- res.writeHead(200, {
2314
+ sendHttpBody(res, 200, {
2259
2315
  'content-type': 'application/json; charset=utf-8',
2260
2316
  'cache-control': 'no-store'
2261
- })
2262
- res.end(JSON.stringify(payload))
2317
+ }, JSON.stringify(payload), true)
2263
2318
  return
2264
2319
  }
2265
2320
  const waiter = { req, res, kind, since, timer: null }
@@ -2527,7 +2582,7 @@ function applyModernSessionFrame(sessionId, value) {
2527
2582
  modernState.sessionCursors.set(sessionId, value.cursor)
2528
2583
  legacyPush('mux', { type: 'session/subscribed', sessionId, lastSeq: value.cursor })
2529
2584
  for (const record of value.records || []) {
2530
- if (record?.event) legacyPush('mux', { type: 'session/event', sessionId, event: record.event })
2585
+ if (record?.event) legacyPush('mux', { type: 'session/event', sessionId, event: record.event, replay: true })
2531
2586
  }
2532
2587
  for (const [key, projection] of Object.entries(value.projections?.values || {})) {
2533
2588
  applyModernProjection(sessionId, key, projection, value.projections?.asOfSeq ?? value.cursor)
@@ -3207,6 +3262,7 @@ function serveStatic(req, res, url) {
3207
3262
  return
3208
3263
  }
3209
3264
  fs.stat(filePath, (err, st) => {
3265
+ if (res.destroyed || res.writableEnded) return
3210
3266
  if (err || !st.isFile()) {
3211
3267
  res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
3212
3268
  res.end('404 Not Found')
@@ -3215,40 +3271,38 @@ function serveStatic(req, res, url) {
3215
3271
  const ext = path.extname(filePath).toLowerCase()
3216
3272
  const lastModified = st.mtime.toUTCString()
3217
3273
  const mtimeSec = Math.floor(st.mtime.getTime() / 1000) * 1000
3274
+ const type = MIME[ext] || 'application/octet-stream'
3275
+ const text = compressibleType(type)
3276
+ const zipped = HTTP_COMPRESSION && text && st.size >= 1024 && req.method !== 'HEAD' && !req.headers.range && acceptsGzip(req)
3277
+ const etag = `W/"${st.size}-${st.mtimeMs}-${zipped ? 'gzip' : 'identity'}"`
3218
3278
  cors(res)
3219
3279
  const ims = req.headers['if-modified-since']
3220
- if (ims && new Date(ims).getTime() >= mtimeSec) {
3221
- res.writeHead(304, { 'last-modified': lastModified })
3280
+ const matched = req.headers['if-none-match']
3281
+ const cache = pathname === '/harmonyos-update.json' ? 'no-store' : ext === '.html' || ext === '.js' || ext === '.css' ? 'no-cache' : 'public, max-age=300'
3282
+ const headers = { 'content-type': type, 'cache-control': cache, 'last-modified': lastModified, etag }
3283
+ if (text) addEncodingVary(headers, res.getHeader('vary'))
3284
+ if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : ims && new Date(ims).getTime() >= mtimeSec)) {
3285
+ res.writeHead(304, headers)
3222
3286
  res.end()
3223
3287
  return
3224
3288
  }
3225
- res.writeHead(200, {
3226
- 'content-type': MIME[ext] || 'application/octet-stream',
3227
- 'cache-control': pathname === '/harmonyos-update.json' ? 'no-store' : ext === '.html' || ext === '.js' || ext === '.css' ? 'no-cache' : 'public, max-age=300',
3228
- 'content-length': st.size,
3229
- 'last-modified': lastModified
3230
- })
3289
+ if (zipped) headers['content-encoding'] = 'gzip'
3290
+ else headers['content-length'] = st.size
3291
+ res.writeHead(200, headers)
3231
3292
  if (req.method === 'HEAD') res.end()
3232
- else fs.createReadStream(filePath).pipe(res)
3293
+ else {
3294
+ const stream = fs.createReadStream(filePath)
3295
+ const done = error => { if (error && !res.destroyed) res.destroy() }
3296
+ if (zipped) pipeline(stream, zlib.createGzip({ level: 3 }), res, done)
3297
+ else pipeline(stream, res, done)
3298
+ }
3233
3299
  })
3234
3300
  }
3235
3301
 
3236
3302
  // ---------- 管理 API ----------
3237
3303
  function upstreamReachable(cb) {
3238
- const req = UPSTREAM_TRANSPORT.request({
3239
- hostname: UPSTREAM_HOSTNAME,
3240
- port: UPSTREAM_PORT,
3241
- method: 'GET',
3242
- path: '/health',
3243
- headers: dshUpstreamHeaders(),
3244
- timeout: 1500
3245
- }, (res) => {
3246
- res.resume()
3247
- cb(true)
3248
- })
3249
- req.on('error', () => cb(false))
3250
- req.on('timeout', () => { req.destroy(); cb(false) })
3251
- req.end()
3304
+ void refreshHealthProbe()
3305
+ cb(healthProbeState.reachable)
3252
3306
  }
3253
3307
 
3254
3308
  async function serveAdminApi(req, res, url) {
@@ -4740,11 +4794,10 @@ async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
4740
4794
 
4741
4795
  function sendBufferedUpstreamResponse(res, response) {
4742
4796
  cors(res)
4743
- res.writeHead(response.status || 502, {
4797
+ sendHttpBody(res, response.status || 502, {
4744
4798
  'content-type': response.headers?.get?.('content-type') || 'application/json; charset=utf-8',
4745
4799
  'cache-control': 'no-store',
4746
- })
4747
- res.end(response.raw || '')
4800
+ }, response.raw || '', compressibleRpc(res.req))
4748
4801
  }
4749
4802
 
4750
4803
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
@@ -4780,8 +4833,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
4780
4833
  }
4781
4834
  }
4782
4835
  cors(res)
4783
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4784
- res.end(JSON.stringify(translated))
4836
+ sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
4785
4837
  }
4786
4838
 
4787
4839
  async function proxyModernApi(req, res, url) {
@@ -4828,8 +4880,7 @@ async function proxyModernApi(req, res, url) {
4828
4880
  sendBufferedUpstreamResponse(res, legacy)
4829
4881
  return true
4830
4882
  }
4831
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4832
- res.end(JSON.stringify(translated))
4883
+ sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
4833
4884
  return true
4834
4885
  } catch (error) {
4835
4886
  if (!res.headersSent) {
@@ -4911,7 +4962,9 @@ function proxyApi(req, res, url) {
4911
4962
  // Credential exchange is restricted to named client endpoints. Administrative
4912
4963
  // plugin routes must authenticate the master token before reaching DSH.
4913
4964
  const remoteClientPath = ['/remote/api/command', '/remote/api/command-status', '/remote/admin/api/dsh'].includes(url.pathname)
4965
+ || (url.pathname === '/remote/api/session-file' && ['GET','HEAD'].includes(req.method))
4914
4966
  || (url.pathname === '/remote/api/insights/cost' && req.method === 'GET')
4967
+ || /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
4915
4968
  || /^\/remote\/api\/plugins\/(state|details|market|operations|recover)$/.test(url.pathname)
4916
4969
  const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
4917
4970
  const ok = remoteAdminPath ? adminAuthorized(req, url) : remoteClientPath ? controlAuthorized(req, url) : authorized(req, url)
@@ -4933,13 +4986,42 @@ function proxyApi(req, res, url) {
4933
4986
  }
4934
4987
 
4935
4988
  // ---------- 其它 ----------
4936
- async function dshControlDescription() {
4989
+ // Expensive OS/upstream checks run once in the background; public status never
4990
+ // grants restart authority. Actual lifecycle actions still verify fresh evidence.
4991
+ let healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
4992
+ let healthProbeTask = null
4993
+ function refreshHealthProbe(force = false) {
4994
+ if (healthProbeTask) return healthProbeTask
4995
+ if (!force && healthProbeState.checkedAt && Date.now() - healthProbeState.checkedAt < 5000) return Promise.resolve(healthProbeState)
4996
+ healthProbeTask = probeDshUpstream(5000).then(value => {
4997
+ healthProbeState = { ...value, checkedAt: Date.now() }
4998
+ return healthProbeState
4999
+ }).finally(() => { healthProbeTask = null })
5000
+ return healthProbeTask
5001
+ }
5002
+ let controlDescriptionState = null
5003
+ let controlDescriptionTask = null
5004
+ let controlDescriptionAt = 0
5005
+ async function dshControlDescription(force = false) {
4937
5006
  if (!DSH_CONTROL_SUPPORT.supported) return DSH_CONTROL_SUPPORT
4938
5007
  if (process.platform !== 'win32' && DSH_CONTROL_MODE !== 'process') return DSH_CONTROL_SUPPORT
4939
- const status = await dshServiceStatus()
4940
- return { supported: status.supported, manager: status.manager || DSH_CONTROL_SUPPORT.manager,
4941
- ...(status.code ? { code: status.code, message: status.message } : {}),
4942
- ...(status.canRestart !== undefined ? { canRestart: status.canRestart } : {}) }
5008
+ if (DSH_CONTROL_MODE === 'process') {
5009
+ try { readDshLaunch() } catch (error) {
5010
+ return { supported: false, manager: 'process', code: 'LAUNCH_CONFIG_INVALID', message: '缺少有效 DSH 启动配置,请先从 DSH 插件重新生成', canRestart: false }
5011
+ }
5012
+ }
5013
+ if (!controlDescriptionTask && (force || Date.now() - controlDescriptionAt >= 5000)) {
5014
+ controlDescriptionTask = dshServiceStatus({ cachedProbe: true }).then(status => {
5015
+ controlDescriptionState = { supported: status.supported, manager: status.manager || DSH_CONTROL_SUPPORT.manager,
5016
+ ...(status.code ? { code: status.code, message: status.message } : {}),
5017
+ ...(status.canRestart !== undefined ? { canRestart: status.canRestart } : {}) }
5018
+ controlDescriptionAt = Date.now()
5019
+ }).catch(() => {
5020
+ controlDescriptionState = { supported: false, code: 'STATUS_PARSE_FAILED', message: '无法读取 DSH 生命周期状态', canRestart: false }
5021
+ controlDescriptionAt = Date.now()
5022
+ }).finally(() => { controlDescriptionTask = null })
5023
+ }
5024
+ return controlDescriptionState || { ...DSH_CONTROL_SUPPORT, canRestart: false, checking: true }
4943
5025
  }
4944
5026
 
4945
5027
  async function serveHealth(req, res, url) {
@@ -4955,30 +5037,11 @@ async function serveHealth(req, res, url) {
4955
5037
  clients: state.clients,
4956
5038
  }]))
4957
5039
  const liveness = { ok: true, pid: process.pid, uptimeMs: Math.max(0, Date.now() - STARTED_AT), runtime: runtimeState }
4958
- if (url?.searchParams.get('probe') === 'live') {
4959
- cors(res)
4960
- res.writeHead(200, { 'content-type': 'application/json' })
4961
- res.end(JSON.stringify({ ok: true, service: 'dsh-remote', version: VERSION, probe: 'live', liveness }))
4962
- return
4963
- }
4964
- let upstreamOk = false
4965
- let upstreamReachable = false
4966
- let upstreamStatus = 0
4967
- let upstreamError = ''
4968
- let timer = null
4969
- try {
4970
- const ctrl = new AbortController()
4971
- timer = setTimeout(() => ctrl.abort(), 5000)
4972
- const probeUrl = new URL(DSH_HEALTH_PATH, UPSTREAM).toString()
4973
- const probe = await fetch(probeUrl, { headers: dshUpstreamHeaders(), signal: ctrl.signal, cache: 'no-store' })
4974
- upstreamReachable = true
4975
- upstreamStatus = probe.status
4976
- upstreamOk = probe.ok
4977
- } catch (err) {
4978
- upstreamError = String(err?.message || err || '')
4979
- } finally {
4980
- if (timer) clearTimeout(timer)
4981
- }
5040
+ const live = url?.searchParams.get('probe') === 'live'
5041
+ const probeTask = refreshHealthProbe()
5042
+ // A small cold-start budget preserves useful readiness on fast local upstreams.
5043
+ if (!live && !healthProbeState.checkedAt) await Promise.race([probeTask, delay(100)])
5044
+ const { ok: upstreamOk, reachable: upstreamReachable, status: upstreamStatus, error: upstreamError } = healthProbeState
4982
5045
  const eventsOk = eventHealth.mux.connected && eventHealth.host.connected
4983
5046
  const readiness = { ok: upstreamOk && eventsOk, upstreamOk, eventsOk }
4984
5047
  const status = readiness.ok ? 'ready' : upstreamReachable ? 'degraded' : 'offline'
@@ -4988,6 +5051,7 @@ async function serveHealth(req, res, url) {
4988
5051
  res.end(JSON.stringify({
4989
5052
  ok: true,
4990
5053
  service: 'dsh-remote',
5054
+ ...(live ? { probe: 'live' } : {}),
4991
5055
  status,
4992
5056
  liveness,
4993
5057
  readiness,
@@ -5001,6 +5065,8 @@ async function serveHealth(req, res, url) {
5001
5065
  upstreamOk,
5002
5066
  upstreamReachable,
5003
5067
  upstreamStatus,
5068
+ upstreamCheckedAt: healthProbeState.checkedAt,
5069
+ upstreamChecking: !!healthProbeTask,
5004
5070
  ...(upstreamError ? { upstreamError } : {}),
5005
5071
  events: eventHealth,
5006
5072
  runtime: runtimeState,
@@ -5424,6 +5490,10 @@ server.on('clientError', (err, socket) => {
5424
5490
  })
5425
5491
 
5426
5492
  server.listen(PORT, HOST, () => {
5493
+ void refreshHealthProbe()
5494
+ void dshControlDescription()
5495
+ const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)
5496
+ healthRefresh.unref?.()
5427
5497
  recordCrash('gateway','startup')
5428
5498
  const crashWatch=setInterval(()=>{void checkDesktopCrash()},5000);crashWatch.unref?.()
5429
5499
  const clientToken = deviceKeyState.enabled ? deviceKeyState.keys[0]?.token : TOKEN