dsh-plugin-weapp-gateway 0.8.59 → 0.8.60

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/PROTOCOL.md CHANGED
@@ -125,7 +125,7 @@ const pairingText = Buffer.from(JSON.stringify(payload), 'utf8').toString('base6
125
125
 
126
126
  本机管理接口 `POST /mgw/gateway` 接受 `{"mode":"disabled|temporary|persistent"}` 中的一个具体值,例如 `{"mode":"persistent"}`。兼容旧 `{"enabled":true}`(临时开启)与 false(关闭);不能同时传 `mode` 和 `enabled`。返回 `gatewayEnabled`、`gatewayMode`、`waitExpiresAt`、`connectedClients`。参数错误返回 400;保存失败返回 500 且不改变当前运行模式。
127
127
 
128
- `GET /mgw/status` 增加身份、地址列表及 `gatewayMode`。模式的持久化不影响配对码有效期和文件传输超时。自动超时关闭若遇到磁盘写入失败,会保持当前进程关闭并记录错误;重启可能仍按旧保存模式运行,需修复存储后再次保存选择。
128
+ `GET /mgw/status` 增加身份、地址列表及 `gatewayMode`。Linux 上额外返回 `backgroundService`(`{ supported, available, enabled, managed, linger, unit, reason }`):表示整个 DSH Web 是否由 systemd 用户服务托管。`POST /mgw/background-service`(仅本机管理面)接受 `{"enabled":boolean}`:开启时写入 `0600` 启动快照与服务单元、`enable` 并交接进程(`202`,当前进程随后退出,由服务接管);关闭只执行 `disable`,当前进程继续运行。不支持的环境(非 Linux、非 `dsh web` 启动、无 systemd 用户服务)返回 `409` 与原因。后台托管时 `POST /mgw/tools/restart-web`、`/mgw/tools/stop-web` 改由 systemd 执行,避免停止后不再自动拉起。模式的持久化不影响配对码有效期和文件传输超时。自动超时关闭若遇到磁盘写入失败,会保持当前进程关闭并记录错误;重启可能仍按旧保存模式运行,需修复存储后再次保存选择。
129
129
 
130
130
  Windows/macOS PC 可从本机管理接口 `POST /mgw/cloudflare` 一键启用 Quick Tunnel:`{"enabled":true,"mode":"quick"}`,无需账户、域名或 Token;返回的随机公网地址在 `GET /mgw/status` 的 `cloudflare.publicUrl` 中,隧道重启后可能变化,App 需重新扫码确认。固定地址可用命名 Tunnel:`{"enabled":true,"mode":"named","hostname":"gateway.example.com","token":"<Tunnel Token>"}`;后续更新可省略 Token 或传空字符串以保留已保存的 Token,关闭时只需 `{"enabled":false}`。状态字段返回模式、支持状态、公开地址、本机入口端口、连接状态和错误,但绝不返回 Token。启用时网关自动切为常驻模式;配置与 Token 保存在独立的 `0600` 文件中。插件会在需要时下载并校验 Cloudflare 官方 `cloudflared` 二进制。两种模式仅在 `127.0.0.1:3082`(可配置)接受已鉴权的 `/ws/mobile` WebSocket,其他 HTTP 路径返回 404;网关关闭或插件卸载时该入口及受管进程一同停止。
131
131
 
@@ -1077,7 +1077,9 @@ WebUI 中的“任务”与“进行中的目标”分别对应 DSH 的 `todos`
1077
1077
  | type | 参数 | 说明 |
1078
1078
  |---|---|---|
1079
1079
  | `agent-presets` | — | preset 名册(含 `isDefault` 标记) |
1080
- | `session-agent-preset` | `sessionId`, `requestId?` | 读取当前会话的 `agentPreset` 和 `locked` |
1080
+ | `session-agent-preset` | `sessionId`, `requestId?` | 读取当前会话的 `agentPreset` 和 `locked`;成功响应可含 `agentPreset: null`(旧会话未记录预设),不代表查询失败 |
1081
+
1082
+ 健康摘要 `health.daily-summary` 继续使用带时区偏移的 `start` / `end` 与 IANA `timeZone`(最长 8 天)。旧手机会返回 `{ steps, sleepMinutes }`;`schemaVersion: 2` 的回包额外带实际查询的 `start`、`end` 与固定 `metrics`(13 项:步数、睡眠、步行跑步距离、楼层、活动/静息能量、运动时间、心率、静息心率、心率变异性、血氧、呼吸频率、体重),每项含 `value`(数字或 `null`)、`unit`、`aggregation`,体重另带窗口内 `recordedAt`。网关校验单位、聚合方式、数值范围、时间窗口与旧字段一致性后原样转发,绝不接受任意 HealthKit 记录或附加字段。详见 [健康摘要协议](docs/health-summary.md)。
1081
1083
  | `select-agent-preset` | `sessionId`, `agentPreset`, `requestId?` | 在首次对话前修改当前会话模式,保持 session ID |
1082
1084
  | `defaults` | — | 读取默认 Agent 预设、默认权限及动态可选默认权限(`permissionDefaultOptions`) |
1083
1085
  | `set-default` | `target`(agent-preset\|permission), `value` | 修改默认预设/默认权限(全局) |
package/README.md CHANGED
@@ -6,6 +6,13 @@
6
6
 
7
7
  `dsh-plugin-weapp-gateway` · DeepSeek Harness 移动客户端连接插件
8
8
 
9
+ ### v0.8.60 · 同步上游 0.12.2(Linux 后台服务 + 健康摘要 v2)
10
+
11
+ - **Linux 持久化后台运行**:通用设置新增开关(仅 Linux 且通过 `dsh web` 启动时显示)。开启后由 systemd 用户服务托管整个 DSH Web:SSH 断开继续运行、开机自启、异常退出自动重启(60 秒内最多 5 次);写入 `0600` 启动快照与服务单元,服务名 `dsh-weapp-gateway-<id>.service`。关闭只取消自启,当前进程继续运行。后台托管时工具菜单的重启/停止改由 systemd 执行。
12
+ - 管理接口:`GET /mgw/status` 增加 `backgroundService`;新增 `POST /mgw/background-service`(仅本机,交接时返回 202 并在短暂重连后由服务接管);不支持环境返回 409 并说明原因(含 `sudo loginctl enable-linger <uid>` 提示)。
13
+ - **健康摘要 v2**:`health.daily-summary` / `phone_health_daily_summary` 支持 `schemaVersion: 2` 的 13 项固定指标(步数、睡眠、步行跑步距离、楼层、活动/静息能量、运动时间、心率、静息心率、心率变异性 SDNN、血氧、呼吸频率、体重),逐项校验单位、聚合方式、数值范围、时间窗口与旧字段一致性;继续兼容旧版手机仅返回步数与睡眠。
14
+ - **旧会话空预设修复**:`agentPreset: null`(未记录预设的历史会话)不再被判为状态不可用——查询成功、允许续聊、已开始会话仍拒绝切换;缺失字段与损坏值仍拒绝。
15
+ - 新增 `test/background-service.test.mjs`,并补充 lan(状态形状 + 路由鉴权)、gateway(双通道空预设)、device-tools(健康 v2 正反例)、session-preset(空预设语义)测试;文档新增 `docs/linux-background-service.md`、`docs/health-summary.md`。全量测试通过。
9
16
  ### v0.8.59 · 修复 Tailscale 状态形状测试(套件回归)
10
17
 
11
18
  - v0.8.57 内嵌 `tailscale serve` 后,`GET /mgw/status` 的 `tailscale` 字段新增 `serveUrl` 与 `serve` 快照,但 `test/lan.test.mjs` 仍按旧的 `{addresses, urls}` 形状断言,导致全量测试变红(产品行为正确,测试过期)。
@@ -0,0 +1,29 @@
1
+ # 健康摘要协议
2
+
3
+
4
+ 继续使用 `phone_health_daily_summary` / `health.daily-summary`,参数仍为带时区偏移的 `start`、`end` 和 IANA `timeZone`,最长 8 天;不新增网关白名单。`schemaVersion: 2` 的结果保留顶层 `steps`、`sleepMinutes`、`timeZone`、`coverage`、`availability`、`collectedAt`,并新增实际查询的 `start`、`end` 与 `metrics`。
5
+
6
+ 每个 `metrics` 项包含 `value`(数字或 `null`)、`unit`、`aggregation`;体重有记录时还带 `recordedAt`。单位固定,不受设备地区设置影响。下表的“平均”是查询窗口内 HealthKit 的样本统计均值,不是实时测量或按天的趋势序列。
7
+
8
+ | metrics 字段 | 数据 | unit | aggregation |
9
+ | --- | --- | --- | --- |
10
+ | `steps` | 步数 | `count` | `sum` |
11
+ | `sleepMinutes` | 睡眠时长 | `min` | `union-duration` |
12
+ | `walkingRunningDistance` | 步行与跑步距离 | `m` | `sum` |
13
+ | `flightsClimbed` | 已爬楼层 | `count` | `sum` |
14
+ | `activeEnergy` | 活动能量 | `kcal` | `sum` |
15
+ | `basalEnergy` | 静息能量 | `kcal` | `sum` |
16
+ | `exerciseMinutes` | Apple 运动时间 | `min` | `sum` |
17
+ | `heartRate` | 平均心率 | `bpm` | `average` |
18
+ | `restingHeartRate` | 平均静息心率 | `bpm` | `average` |
19
+ | `heartRateVariability` | 平均心率变异性(SDNN) | `ms` | `average` |
20
+ | `oxygenSaturation` | 平均血氧饱和度(例如 98,而非 0.98) | `%` | `average` |
21
+ | `respiratoryRate` | 平均呼吸频率 | `breaths/min` | `average` |
22
+ | `bodyMass` | 窗口内最新体重(不查窗口外旧记录) | `kg` | `latest` |
23
+
24
+ 数值查询仅纳入完整落在请求窗口中的样本。睡眠允许跨窗口,裁剪后合并重叠区间,只统计睡着的阶段,避免多来源重复计时;不计入清醒或仅卧床时间。所有数值使用 HealthKit 统计查询,体重使用窗口内按结束时间倒序的单条查询。逐项查询均可取消,原有关闭连接器、网关撤权、租约失效、后台与超时约束继续有效。
25
+
26
+ 已有用户更新 App 后,在手机连接器页将“健康”关闭再开启,系统会对新增数据类型请求授权;用户可逐项拒绝,旧权限不自动扩大。没有记录或未共享的数据返回 `null`,不会冒报为 0,也不据此断言用户拒绝授权。没有手表或其他数据来源时,部分类型可能一直没有记录。仍然只读,不导出原始逐条记录,不申请写入权限。
27
+
28
+
29
+ 部署顺序:先更新网关的 v2 回包校验,再更新手机 App。新网关继续接受旧版手机仅含步数和睡眠的回包;旧网关会将 v2 新字段判为 invalid_result。
@@ -0,0 +1,23 @@
1
+ # Linux 持久化后台运行
2
+
3
+ 在网关设置的「通用」页面开启「持久化后台运行」,即可将当前 `dsh web` 实例交给 systemd 用户服务托管。SSH 断开、用户退出登录后继续运行,服务器重启后自动启动;异常退出时自动重试(60 秒内最多启动 5 次)。开启时整个 DSH Web 会重启,网页和手机会短暂断开,正在执行的任务可能中断,请等任务结束后再开启。
4
+
5
+ 仅在 Linux 上显示此开关,要求通过 `dsh web` 启动,并且 systemd 用户服务可访问。不依赖公网接入 Helper,也不需要为 DSH 提供 root 权限。不支持无 systemd 的容器或发行版;此时开关禁用并显示原因。
6
+
7
+ 开启时检查 linger,必要时尝试为当前用户启用。如果权限不足,页面提示在服务器执行 `sudo loginctl enable-linger <用户 UID>`,完成后重新开启开关。linger 的作用参见 [systemd 官方文档](https://www.freedesktop.org/software/systemd/man/latest/loginctl.html)。关闭开关不会禁用用户的 linger,避免影响其他用户服务。
8
+
9
+ 关闭开关会取消下次开机自动启动,当前 DSH Web 仍在后台运行;通过网关右上角工具菜单可以停止。后台托管时,工具菜单中的重启、停止均交给 systemd,停止后不会立即自动拉起;若开关仍开启,服务器下次启动仍会启动服务。
10
+
11
+ 服务名为 `dsh-weapp-gateway-<实例标识>.service`,可从 `/mgw/status` 的 `backgroundService.unit` 读取。同一工作目录、DSH_HOME 和启动参数对应同一个服务,不同实例分别保存。设置保存于 `${XDG_CONFIG_HOME:-~/.config}/systemd/user/`;服务文件及启动快照权限为 0600。启动快照包含当前 Node 路径、DSH 参数、工作目录和环境变量(可能包含凭据),不要公开或提交这些文件。Node、DSH 或插件安装位置改变后,应从新安装启动并重新开启开关,以更新启动快照。
12
+
13
+ 命令行管理(把 `<服务名>` 替换为实际名称):
14
+
15
+ ```sh
16
+ systemctl --user status <服务名>
17
+ journalctl --user -u <服务名> -n 100
18
+ systemctl --user restart <服务名>
19
+ systemctl --user stop <服务名>
20
+ systemctl --user disable <服务名>
21
+ ```
22
+
23
+ 「网关运行模式」中的「常驻开启」控制是否持续接受手机连接;如需服务器重启后持续提供手机入口,请同时选择「常驻开启」。
@@ -0,0 +1,34 @@
1
+ // The systemd-owned runner waits for the foreground server to release its ports.
2
+ import fs from 'node:fs/promises'
3
+ import { spawn } from 'node:child_process'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ export const processStartTime = stat => stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]
7
+
8
+ export async function waitForPrevious(previous, { read = file => fs.readFile(file, 'utf8'), pause = ms => new Promise(resolve => setTimeout(resolve, ms)), now = Date.now } = {}) {
9
+ if (await read('/proc/sys/kernel/random/boot_id') !== previous.boot) return
10
+ const deadline = now() + 30_000
11
+ while (true) {
12
+ let stat
13
+ try { stat = await read(`/proc/${previous.pid}/stat`) } catch (error) { if (error.code === 'ENOENT') return; throw error }
14
+ if (processStartTime(stat) !== processStartTime(previous.identity) || stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z ')) return
15
+ if (now() >= deadline) throw new Error('原 DSH Web 未在 30 秒内退出,后台接管失败')
16
+ await pause(200)
17
+ }
18
+ }
19
+
20
+ export async function launch(spec) {
21
+ await waitForPrevious(spec.previous)
22
+ const child = spawn(spec.execPath, spec.args, { cwd: spec.cwd, env: spec.env, stdio: ['ignore', 'inherit', 'inherit'] })
23
+ let stopping = false
24
+ for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { stopping = true; child.kill(signal) })
25
+ child.once('error', error => { console.error(error.message); process.exitCode = 1 })
26
+ child.once('exit', (code, signal) => { process.exitCode = stopping ? 0 : code ?? (signal ? 1 : 0) })
27
+ }
28
+
29
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
30
+ try { await launch(JSON.parse(await fs.readFile(process.argv[2], 'utf8'))) } catch (error) {
31
+ console.error(error.message)
32
+ process.exitCode = 1
33
+ }
34
+ }
@@ -0,0 +1,102 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+ import fs from 'node:fs/promises'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { createHash } from 'node:crypto'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { webRestartAvailable } from './gateway-tools.mjs'
9
+
10
+ const execute = promisify(execFile)
11
+ const MARKER = '# Managed by dsh-plugin-weapp-gateway\n'
12
+
13
+ // systemd performs specifier and environment expansion even without a shell.
14
+ export function unitQuote(value) {
15
+ if (/[\x00-\x1f\x7f]/.test(value)) throw new Error('后台服务路径包含不支持的控制字符')
16
+ return '"' + value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%').replaceAll('$', () => '$$') + '"'
17
+ }
18
+
19
+ export function createBackgroundService({ profile, runtime = process, home = os.homedir(), run = execute, readProc = file => fs.readFile(file, 'utf8') } = {}) {
20
+ const argv = runtime.argv.slice(1)
21
+ const flagEnd = argv.indexOf('--')
22
+ const noOpen = argv.indexOf('--no-open')
23
+ if (noOpen >= 0 && (flagEnd < 0 || noOpen < flagEnd)) argv.splice(noOpen, 1)
24
+ const id = createHash('sha256').update(JSON.stringify([runtime.cwd(), runtime.env.DSH_HOME || '', argv])).digest('hex').slice(0, 16)
25
+ const unit = `dsh-weapp-gateway-${id}.service`
26
+ const directory = path.join(runtime.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'systemd', 'user')
27
+ const unitPath = path.join(directory, unit)
28
+ const specPath = path.join(directory, `${unit}.json`)
29
+ const managed = runtime.env.DSH_BACKGROUND_UNIT === unit
30
+ const command = async (exe, args) => (await run(exe, args, { timeout: 10_000, maxBuffer: 64 * 1024 })).stdout.trim()
31
+ const systemctl = (...args) => command('systemctl', ['--user', '--no-ask-password', ...args])
32
+ const supported = () => runtime.platform === 'linux' && webRestartAvailable(typeof profile === 'function' ? profile() : profile, runtime)
33
+ let pending = false
34
+
35
+ const status = async () => {
36
+ const result = { supported: supported(), available: false, enabled: false, managed, unit }
37
+ if (!result.supported) return { ...result, reason: '仅支持 Linux 上通过 dsh web 启动的实例' }
38
+ try {
39
+ await systemctl('show-environment')
40
+ result.available = true
41
+ result.linger = await command('loginctl', ['show-user', String(runtime.getuid()), '--property=Linger', '--value']) === 'yes'
42
+ try { result.enabled = await systemctl('is-enabled', unit) === 'enabled' } catch { /* not installed */ }
43
+ if (!result.linger) result.reason = `需要允许退出登录后运行;请在服务器执行 sudo loginctl enable-linger ${runtime.getuid()}`
44
+ } catch {
45
+ result.available = false
46
+ result.reason = '无法连接 systemd 用户服务,请确认服务器使用 systemd 且当前用户的 user manager 已启动'
47
+ }
48
+ return result
49
+ }
50
+
51
+ const configure = async enabled => {
52
+ if (pending) throw new Error('后台服务正在切换,请稍后重试')
53
+ pending = true
54
+ try {
55
+ const current = await status()
56
+ if (!current.available) throw new Error(current.reason)
57
+ if (!enabled) {
58
+ await systemctl('disable', unit)
59
+ return { ...await status(), handoff: false }
60
+ }
61
+ if (!current.linger) {
62
+ try { await command('loginctl', ['--no-ask-password', 'enable-linger', String(runtime.getuid())]) } catch {
63
+ throw new Error(current.reason)
64
+ }
65
+ if (!(await status()).linger) throw new Error(current.reason)
66
+ }
67
+ let previous
68
+ try { previous = await fs.readFile(unitPath, 'utf8') } catch (error) { if (error.code !== 'ENOENT') throw error }
69
+ if (previous && !previous.startsWith(MARKER)) throw new Error('拒绝覆盖非网关管理的 systemd 服务')
70
+ // Do not start a second server over an already running service.
71
+ if (!managed) {
72
+ let active = false
73
+ try { active = await systemctl('is-active', unit) === 'active' } catch { /* inactive */ }
74
+ if (active) throw new Error('此工作目录已有后台服务运行,请连接该实例或先停止它')
75
+ }
76
+ const launchArgv = runtime.argv.slice(1)
77
+ const end = launchArgv.indexOf('--')
78
+ if (!launchArgv.slice(0, end < 0 ? launchArgv.length : end).includes('--no-open')) launchArgv.splice(end < 0 ? launchArgv.length : end, 0, '--no-open')
79
+ const env = { ...runtime.env, DSH_BACKGROUND_UNIT: unit }
80
+ for (const key of ['INVOCATION_ID', 'NOTIFY_SOCKET', 'JOURNAL_STREAM', 'SYSTEMD_EXEC_PID', 'LISTEN_PID', 'LISTEN_FDS', 'LISTEN_FDNAMES']) delete env[key]
81
+ const spec = { execPath: runtime.execPath, args: [...runtime.execArgv, ...launchArgv], cwd: runtime.cwd(), env,
82
+ previous: { pid: runtime.pid, identity: await readProc(`/proc/${runtime.pid}/stat`), boot: await readProc('/proc/sys/kernel/random/boot_id') } }
83
+ await fs.mkdir(directory, { recursive: true })
84
+ // Credentials inherited from the launching shell must only be readable by this user.
85
+ await fs.writeFile(`${specPath}.tmp`, JSON.stringify(spec), { mode: 0o600 })
86
+ await fs.chmod(`${specPath}.tmp`, 0o600)
87
+ await fs.rename(`${specPath}.tmp`, specPath)
88
+ const runner = fileURLToPath(new URL('./background-service-runner.mjs', import.meta.url))
89
+ await fs.writeFile(unitPath, `${MARKER}[Unit]\nDescription=DSH Web weapp gateway\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=simple\nExecStart=${[runtime.execPath, runner, specPath].map(unitQuote).join(' ')}\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=30\nKillMode=control-group\n\n[Install]\nWantedBy=default.target\n`, { mode: 0o600 })
90
+ await systemctl('daemon-reload')
91
+ await systemctl('enable', unit)
92
+ if (!managed) {
93
+ try { await systemctl('start', unit) } catch (error) {
94
+ await systemctl('disable', unit).catch(() => {})
95
+ throw error
96
+ }
97
+ }
98
+ return { ...await status(), handoff: !managed }
99
+ } finally { pending = false }
100
+ }
101
+ return { status, configure, managed, control: action => systemctl('--no-block', action, unit) }
102
+ }
package/lib/client.js CHANGED
@@ -637,6 +637,7 @@ window.__ModuleLoader__.load({
637
637
  const [connectionHelpOpen, setConnectionHelpOpen] = React.useState(false)
638
638
  const [toolsOpen, setToolsOpen] = React.useState(false)
639
639
  const [toolBusy, setToolBusy] = React.useState(false)
640
+ const [backgroundBusy, setBackgroundBusy] = React.useState(false)
640
641
  const [toolNotice, setToolNotice] = React.useState('')
641
642
  const stoppedRef = React.useRef(false)
642
643
  const [publicIp, setPublicIp] = React.useState('')
@@ -827,8 +828,39 @@ window.__ModuleLoader__.load({
827
828
  }
828
829
  }
829
830
 
831
+ // Linux 持久化后台运行:交给 systemd 用户服务托管整个 DSH Web。
832
+ const toggleBackgroundService = async (event) => {
833
+ const enabled = event.target.checked
834
+ if (backgroundBusy || toolBusy) return
835
+ setBackgroundBusy(true)
836
+ setError(null)
837
+ try {
838
+ const oldPid = status?.webPid
839
+ const data = await request('/mgw/background-service', {
840
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enabled }),
841
+ })
842
+ setStatus((current) => ({ ...current, backgroundService: data }))
843
+ if (data.handoff) {
844
+ setToolNotice('正在切换到后台服务,连接会短暂中断,请等待自动重连…')
845
+ const deadline = Date.now() + 60_000
846
+ while (Date.now() < deadline) {
847
+ await new Promise((resolve) => window.setTimeout(resolve, 700))
848
+ try {
849
+ const next = await request('/mgw/status')
850
+ if (next.webPid !== oldPid && next.backgroundService?.managed) { window.location.reload(); return }
851
+ } catch { /* 前台进程正在退出,忽略 */ }
852
+ }
853
+ throw new Error('后台接管超时,请在服务器使用 journalctl --user -u <服务名> 查看服务日志。')
854
+ }
855
+ setToolNotice(enabled
856
+ ? '持久化后台运行已开启。'
857
+ : '已关闭自动启动;当前进程继续运行,可通过右上角工具停止 DSH Web。')
858
+ } catch (cause) { setError(cause.message) }
859
+ finally { setBackgroundBusy(false) }
860
+ }
861
+
830
862
  const runTool = async (tool) => {
831
- if (toolBusy) return
863
+ if (toolBusy || backgroundBusy) return
832
864
  setToolsOpen(false)
833
865
  setToolBusy(true)
834
866
  setToolNotice('')
@@ -1341,6 +1373,29 @@ window.__ModuleLoader__.load({
1341
1373
  toolNotice ? React.createElement('div', { style: { ...styles.muted, marginBottom: 10 } }, toolNotice) : null,
1342
1374
  (error || deviceLoadError || statusLoadError) ? React.createElement('div', { style: styles.error, role: 'alert' }, error || deviceLoadError || statusLoadError) : null,
1343
1375
  React.createElement('div', { hidden: activeSection !== 'general' },
1376
+ // Linux 专属:持久化后台运行(systemd 用户服务)。其他平台不渲染。
1377
+ status?.platform === 'linux' ? React.createElement('section', { style: styles.card },
1378
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1379
+ React.createElement('div', null,
1380
+ React.createElement('strong', null, '持久化后台运行'),
1381
+ React.createElement('p', { style: styles.muted }, '由 systemd 托管整个 DSH Web,SSH 断开后继续运行,服务器重启后自动启动。开启时会短暂重连。'),
1382
+ status.backgroundService?.reason ? React.createElement('p', { style: styles.muted }, status.backgroundService.reason) : null,
1383
+ status.backgroundService?.unit ? React.createElement('p', { style: { ...styles.muted, opacity: .75 } }, `服务名:${status.backgroundService.unit}`) : null),
1384
+ React.createElement('label', { style: { ...styles.switch, opacity: status.backgroundService?.available || status.backgroundService?.managed ? (backgroundBusy ? .55 : 1) : .55 },
1385
+ title: status.backgroundService?.available ? '切换持久化后台运行' : (status.backgroundService?.reason || '当前环境不支持') },
1386
+ React.createElement('input', {
1387
+ type: 'checkbox',
1388
+ role: 'switch',
1389
+ 'aria-label': '持久化后台运行',
1390
+ 'aria-checked': !!status.backgroundService?.managed,
1391
+ checked: !!status.backgroundService?.managed,
1392
+ disabled: backgroundBusy || !(status.backgroundService?.available || status.backgroundService?.managed),
1393
+ onChange: toggleBackgroundService,
1394
+ style: styles.switchInput,
1395
+ }),
1396
+ React.createElement('span', { style: { ...styles.switchTrack, background: status.backgroundService?.managed ? colors.success : colors.muted } }),
1397
+ React.createElement('span', { style: { ...styles.switchKnob, left: status.backgroundService?.managed ? 21 : 3 } }))),
1398
+ ) : null,
1344
1399
  React.createElement('section', { style: styles.card },
1345
1400
  React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'center' } },
1346
1401
  React.createElement('div', null,
@@ -163,7 +163,31 @@ export function validateResult(tool, value) {
163
163
  if (tool === 'music.search') return keys(value, [...metadata, 'items']) && Array.isArray(value.items) && value.items.length <= 20 && value.items.every(row => keys(row, value.source === 'android-media-store' ? ['id', 'title', 'artist', 'album', 'artworkURL', 'durationSeconds'] : ['id', 'title', 'artist']) && (value.source !== 'android-media-store' || (musicDetails(row, true) && (row.album === undefined || (typeof row.album === 'string' && row.album.length <= 500)))) && typeof row.id === 'string' && /^\d{1,20}$/.test(row.id) && typeof row.title === 'string' && row.title.length <= 500 && typeof row.artist === 'string' && row.artist.length <= 500)
164
164
  if (tool.startsWith('music.') && ['android-media-store', 'android-media-session'].includes(value.source)) return keys(value, ['playbackState', 'playbackSeconds', 'requested', 'source', 'status', 'playerPackage', 'track']) && Number.isInteger(value.playbackState) && value.playbackState >= 0 && value.playbackState <= 5 && (value.playbackSeconds === undefined || number(value.playbackSeconds)) && (value.requested === undefined || value.requested === tool) && (value.status === undefined || value.status === 'handoff-requested') && (value.playerPackage === undefined || (text(value.playerPackage, 255) && /^[A-Za-z0-9_.]+$/.test(value.playerPackage))) && (value.track === undefined || (keys(value.track, ['title', 'artist', 'album']) && Object.values(value.track).every(item => typeof item === 'string' && item.length <= 500)))
165
165
  if (tool.startsWith('music.')) return keys(value, ['playbackState', 'playbackSeconds', 'requested']) && Number.isInteger(value.playbackState) && value.playbackState >= 0 && value.playbackState <= 5 && (value.playbackSeconds === undefined || number(value.playbackSeconds)) && (value.requested === undefined || value.requested === tool)
166
- if (tool === 'health.daily-summary') return keys(value, [...metadata, 'steps', 'sleepMinutes']) && (value.steps === null || number(value.steps)) && (value.sleepMinutes === null || number(value.sleepMinutes))
166
+ if (tool === 'health.daily-summary') {
167
+ if (!(value.steps === null || number(value.steps)) || !(value.sleepMinutes === null || number(value.sleepMinutes))) return false
168
+ // 旧版手机保持原回包;v2 是固定摘要 schema,绝不是任意 HealthKit 记录。
169
+ if (value.schemaVersion === undefined) return keys(value, [...metadata, 'steps', 'sleepMinutes'])
170
+ if (value.schemaVersion !== 2 || !keys(value, [...metadata, 'steps', 'sleepMinutes', 'schemaVersion', 'metrics', 'start', 'end']) ||
171
+ !offsetDate(value.start) || !offsetDate(value.end) || !validZone(value.timeZone)) return false
172
+ const start = Date.parse(value.start), end = Date.parse(value.end)
173
+ if (end <= start || end - start > 8 * 86400000) return false
174
+ const definitions = {
175
+ steps: ['count', 'sum'], sleepMinutes: ['min', 'union-duration'], walkingRunningDistance: ['m', 'sum'],
176
+ flightsClimbed: ['count', 'sum'], activeEnergy: ['kcal', 'sum'], basalEnergy: ['kcal', 'sum'], exerciseMinutes: ['min', 'sum'],
177
+ heartRate: ['bpm', 'average'], restingHeartRate: ['bpm', 'average'], heartRateVariability: ['ms', 'average'],
178
+ oxygenSaturation: ['%', 'average'], respiratoryRate: ['breaths/min', 'average'], bodyMass: ['kg', 'latest'],
179
+ }
180
+ if (!keys(value.metrics, Object.keys(definitions)) || Object.keys(value.metrics).length !== Object.keys(definitions).length) return false
181
+ for (const [name, [unit, aggregation]] of Object.entries(definitions)) {
182
+ const row = value.metrics[name]
183
+ if (!keys(row, name === 'bodyMass' ? ['value', 'unit', 'aggregation', 'recordedAt'] : ['value', 'unit', 'aggregation']) ||
184
+ row.unit !== unit || row.aggregation !== aggregation || !(row.value === null || number(row.value))) return false
185
+ if (name === 'oxygenSaturation' && row.value > 100) return false
186
+ if (name === 'bodyMass' && (row.value === null ? row.recordedAt !== undefined :
187
+ !offsetDate(row.recordedAt) || Date.parse(row.recordedAt) < start || Date.parse(row.recordedAt) > end)) return false
188
+ }
189
+ return value.metrics.steps.value === value.steps && value.metrics.sleepMinutes.value === value.sleepMinutes
190
+ }
167
191
  if (tool !== 'photos.select' || !keys(value, ['images']) || !Array.isArray(value.images) || value.images.length !== 1) return false
168
192
  return value.images.every(image => keys(image, ['mediaType', 'width', 'height', 'data']) && image.mediaType === 'image/jpeg' &&
169
193
  Number.isInteger(image.width) && image.width > 0 && image.width <= 768 &&
@@ -256,13 +256,16 @@ export function createDshHostAdapter(typertGateway, peer, connection, { runtimeV
256
256
  const snapshot = await sessionSnapshot({ address: { kind: 'session', sessionId }, maxMessages: 1 }, signal)
257
257
  const values = snapshot.projections.values
258
258
  const metadata = values?.sessionListMetadata
259
- if (typeof values?.agentPreset !== 'string' || !metadata || typeof metadata.blank !== 'boolean'
259
+ // Host 明确允许 null,表示没有记录预设;不能把它当作查询失败。
260
+ // 缺失字段和损坏值仍拒绝,锁定状态独立使用持久化元数据判断。
261
+ const preset = values?.agentPreset
262
+ if (!(preset === null || (typeof preset === 'string' && preset.trim())) || !metadata || typeof metadata.blank !== 'boolean'
260
263
  || !(metadata.lastPromptAt === null || Number.isFinite(metadata.lastPromptAt))) {
261
264
  throw Object.assign(new Error('session preset state is unavailable'), { code: 'agent-preset/unavailable' })
262
265
  }
263
266
  const durableLock = !metadata.blank || metadata.lastPromptAt !== null
264
267
  if (durableLock) admittedPrompts.delete(sessionId)
265
- return { sessionId, agentPreset: values.agentPreset, locked: durableLock || admittedPrompts.has(sessionId) }
268
+ return { sessionId, agentPreset: preset, locked: durableLock || admittedPrompts.has(sessionId) }
266
269
  }
267
270
 
268
271
  const commands = {
package/lib/index.mjs CHANGED
@@ -161,6 +161,7 @@ import { createCompletionNotifications } from './completion-notifications.mjs'
161
161
  import { gatewayProbeHeader } from './gateway-probe.mjs'
162
162
  import { checkPluginUpdate, installLatestPlugin } from './plugin-updates.mjs'
163
163
  import { webRestartAvailable, prepareWebRestart } from './gateway-tools.mjs'
164
+ import { createBackgroundService } from './background-service.mjs'
164
165
  import { createClawbotService } from './clawbot/service.mjs'
165
166
  import QRCode from 'qrcode'
166
167
  import { createHistoryCache, historyCacheKey } from './history-cache.mjs'
@@ -3489,6 +3490,8 @@ const plugin = {
3489
3490
  // ---- device management routes (loopback-gated admin surface) ----
3490
3491
  let restartPending = false
3491
3492
  let pluginUpdatePending = false
3493
+ // Linux 持久化后台运行:systemd 用户服务托管整个 DSH Web。
3494
+ const backgroundService = createBackgroundService({ profile: () => ctx.get?.('profileContext') })
3492
3495
  const disposeMgmt = webServer.register({
3493
3496
  kind: 'prefix',
3494
3497
  path: '/mgw',
@@ -3546,6 +3549,7 @@ const plugin = {
3546
3549
  ? tunnel.snapshot().publicUrl
3547
3550
  : tunnel?.snapshot().publicUrl) || configuredPublicUrl() || null,
3548
3551
  platform: process.platform,
3552
+ backgroundService: await backgroundService.status(),
3549
3553
  cloudflare: tunnel?.snapshot() || null,
3550
3554
  // 本机 Tailscale 接口地址(100.64/10 或 fd7a:115c:a1e0::/48)。
3551
3555
  // 只用于面板展示与可选配对地址;检测到接口不等于已登录 tailnet。
@@ -3567,6 +3571,32 @@ const plugin = {
3567
3571
  },
3568
3572
  relayConnector: relayConnector.snapshot(),
3569
3573
  })
3574
+ } else if (req.method === 'POST' && p === '/mgw/background-service') {
3575
+ // 开启/关闭 systemd 后台托管。仅本机管理面可用。
3576
+ if (!isLoopback(req)) {
3577
+ sendJson(res, 403, { error: 'forbidden', message: '后台服务设置仅允许本机访问' })
3578
+ return
3579
+ }
3580
+ const body = await readBody(req)
3581
+ if (typeof body.enabled !== 'boolean') throw badRequest('boolean enabled is required')
3582
+ const backgroundStatus = await backgroundService.status()
3583
+ if (!backgroundStatus.available) {
3584
+ sendJson(res, 409, { error: 'unavailable', message: backgroundStatus.reason })
3585
+ return
3586
+ }
3587
+ if (restartPending) {
3588
+ sendJson(res, 409, { error: 'restart-pending', message: 'DSH Web 正在重启或切换后台服务' })
3589
+ return
3590
+ }
3591
+ restartPending = true
3592
+ let result
3593
+ try { result = await backgroundService.configure(body.enabled) } catch (error) {
3594
+ restartPending = false
3595
+ throw error
3596
+ }
3597
+ if (result.handoff) res.once('finish', () => setTimeout(() => process.kill(process.pid, 'SIGTERM'), 100))
3598
+ else restartPending = false
3599
+ sendJson(res, result.handoff ? 202 : 200, result)
3570
3600
  } else if (req.method === 'POST' && p === '/mgw/tools/restart-web') {
3571
3601
  if (!isLoopback(req)) {
3572
3602
  sendJson(res, 403, { error: 'forbidden', message: 'Web restart is loopback-only' })
@@ -3581,6 +3611,15 @@ const plugin = {
3581
3611
  return
3582
3612
  }
3583
3613
  restartPending = true
3614
+ if (backgroundService.managed) {
3615
+ // 后台托管时重启交给 systemd,避免退出后不再自动拉起。
3616
+ res.once('finish', () => backgroundService.control('restart').catch(error => {
3617
+ restartPending = false
3618
+ log(`background restart failed: ${error.message}`)
3619
+ }))
3620
+ sendJson(res, 202, { restarting: true })
3621
+ return
3622
+ }
3584
3623
  try {
3585
3624
  await prepareWebRestart()
3586
3625
  } catch (error) {
@@ -3603,6 +3642,14 @@ const plugin = {
3603
3642
  return
3604
3643
  }
3605
3644
  restartPending = true
3645
+ if (backgroundService.managed) {
3646
+ res.once('finish', () => backgroundService.control('stop').catch(error => {
3647
+ restartPending = false
3648
+ log(`background stop failed: ${error.message}`)
3649
+ }))
3650
+ sendJson(res, 202, { stopping: true })
3651
+ return
3652
+ }
3606
3653
  res.once('finish', () => setTimeout(() => process.kill(process.pid, 'SIGTERM'), 100))
3607
3654
  sendJson(res, 202, { stopping: true })
3608
3655
  } else if (req.method === 'GET' && p === '/mgw/tailscale') {
@@ -69,7 +69,7 @@ const SHORTCUTS = [
69
69
  ['phone_reminders_list', 'reminders.list', '读取本轮来源手机的未完成待办。iPhone 为 Apple Reminders;Android 仅当前主机创建的 Whaleness 提醒。问手机待办时直接调用,不要先查飞书审批或扫描技能。', true],
70
70
  ['phone_calendar_busy', 'calendar.busy', '读取本轮来源手机系统日历的忙闲区间,不返回日程标题和参与人。', true],
71
71
  ['phone_location_current', 'location.current', '直接获取本轮来源手机的近似当前位置。', false],
72
- ['phone_health_daily_summary', 'health.daily-summary', '直接读取本轮来源手机已授权的步数与睡眠摘要,用于日常健康回顾。无数据也可能是未授权,不当作零值或诊断。', true],
72
+ ['phone_health_daily_summary', 'health.daily-summary', '读取本轮来源手机已授权的健康与活动摘要:步数、睡眠、步行跑步距离、楼层、活动及静息能量、运动时间、心率、静息心率、心率变异性SDNN、血氧、呼吸频率和体重。metrics 含 value/unit/aggregation;心肺指标为查询窗口平均,体重为窗口内最新值并带 recordedAt。旧版手机可能仅返回步数和睡眠。无数据也可能是未共享,不能当作零值、实时测量或诊断。', true],
73
73
  ]
74
74
  const MAP_FIELDS = {
75
75
  'maps.markers.create': { name: 'phone_maps_marker_create', description: '按用户明确指令保存命名地点标记,可带地址和备注。存于当前手机的 Whaleness,按主机隔离,不是写入苹果地图收藏。标记当前位置先取位置,标记地址先解析坐标;不猜坐标。同名地点不会自动覆盖。operationId 用新 UUID,重试必须原样复用。', required: ['operationId', 'name', 'latitude', 'longitude'], properties: { operationId: { type: 'string' }, name: { type: 'string' }, latitude: { type: 'number' }, longitude: { type: 'number' }, address: { type: 'string' }, notes: { type: 'string' } } },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-weapp-gateway",
3
- "version": "0.8.59",
3
+ "version": "0.8.60",
4
4
  "description": "鲸尾网关助手:DeepSeek Harness 移动客户端连接与会话同步,支持安全配对、远程访问、上下文、编队、额度和语音输入",
5
5
  "main": "lib/index.mjs",
6
6
  "files": [
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "bin": "bin/setup-ip.mjs",
32
32
  "scripts": {
33
- "test": "node --test test/tool-images.test.mjs test/dsh-runtime-version.test.mjs && node --test test/logging.test.mjs && node test/dsh-022.test.mjs && node test/device-tools.test.mjs && node test/external-files.test.mjs && node test/team-mode.test.mjs && node test/android-connectors.test.mjs && node test/workspace-changes.test.mjs && node test/devices.test.mjs && node test/dsh-runtime-version.test.mjs && node test/wire-json.test.mjs && node --test test/history-cache.test.mjs && node test/session-target.test.mjs && node test/setup-ip.test.mjs && node test/host-adapter.test.mjs && node test/file-upload-adapter.test.mjs && node test/file-upload.test.mjs && node test/agent-team.test.mjs && node test/account-bridge.test.mjs && node test/context-bridge.test.mjs && node test/cost-meter.test.mjs && node --test test/cost-meter-dashboard.test.mjs && node test/clawbot-service.test.mjs && node test/speech-input.test.mjs && node test/plugin-management.test.mjs && node test/model-config.test.mjs && node test/plugin-updates.test.mjs && node test/session-preset.test.mjs && node test/session-follower.test.mjs && node test/completion-notifications.test.mjs && node --test test/workspace-changes.test.mjs && node --test test/question-replay.test.mjs && node --test test/network-diagnostics.test.mjs && node --test test/tailscale-addresses.test.mjs && node --test test/ui-state.test.mjs && node test/gateway.test.mjs && node test/auth.test.mjs && node test/lan.test.mjs && node test/cloudflared-binary.test.mjs && node test/cloudflare-tunnel.test.mjs && node --test test/public-endpoint-check.test.mjs && node test/gateway-tools.test.mjs && node test/relay-connector.test.mjs && node test/restart-reconnect.test.mjs && node test/multi-gateway.test.mjs",
33
+ "test": "node --test test/background-service.test.mjs && node --test test/tool-images.test.mjs test/dsh-runtime-version.test.mjs && node --test test/logging.test.mjs && node test/dsh-022.test.mjs && node test/device-tools.test.mjs && node test/external-files.test.mjs && node test/team-mode.test.mjs && node test/android-connectors.test.mjs && node test/workspace-changes.test.mjs && node test/devices.test.mjs && node test/dsh-runtime-version.test.mjs && node test/wire-json.test.mjs && node --test test/history-cache.test.mjs && node test/session-target.test.mjs && node test/setup-ip.test.mjs && node test/host-adapter.test.mjs && node test/file-upload-adapter.test.mjs && node test/file-upload.test.mjs && node test/agent-team.test.mjs && node test/account-bridge.test.mjs && node test/context-bridge.test.mjs && node test/cost-meter.test.mjs && node --test test/cost-meter-dashboard.test.mjs && node test/clawbot-service.test.mjs && node test/speech-input.test.mjs && node test/plugin-management.test.mjs && node test/model-config.test.mjs && node test/plugin-updates.test.mjs && node test/session-preset.test.mjs && node test/session-follower.test.mjs && node test/completion-notifications.test.mjs && node --test test/workspace-changes.test.mjs && node --test test/question-replay.test.mjs && node --test test/network-diagnostics.test.mjs && node --test test/tailscale-addresses.test.mjs && node --test test/ui-state.test.mjs && node test/gateway.test.mjs && node test/auth.test.mjs && node test/lan.test.mjs && node test/cloudflared-binary.test.mjs && node test/cloudflare-tunnel.test.mjs && node --test test/public-endpoint-check.test.mjs && node test/gateway-tools.test.mjs && node test/relay-connector.test.mjs && node test/restart-reconnect.test.mjs && node test/multi-gateway.test.mjs",
34
34
  "test:official": "node test/dsh-022-official.test.mjs && node test/tool-images-official.test.mjs && node test/workspace-changes-official.test.mjs && node test/host-official.test.mjs && node test/speech-official.test.mjs && node test/agent-team-official.test.mjs && node test/file-upload-official.test.mjs && node test/package-install.test.mjs",
35
35
  "test:ui": "node --test test/connection-choice-ui.test.cjs test/network-diagnostics-ui.test.cjs test/client-device-panel.render.test.cjs"
36
36
  },