dsh-mcviseron-plugin 0.7.8 → 0.8.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ ## [0.8.1] - 2026-11-22
2
+
3
+ ### Fixed
4
+
5
+ - **Linux CI 测试环境差异**:`resolveRestartTarget` 的 Linux 目标单测不再假定必然是 reexec;CI runner 若带 systemd 环境变量时允许 supervisor-exit,具体模式由 `resolveProcessRestartTarget` 的独立测试覆盖。
6
+
7
+ ### Tests
8
+
9
+ - 129 项测试;typecheck、build 全绿。
10
+
11
+ ## [0.8.0] - 2026-11-22
12
+
13
+ ### Added
14
+
15
+ - **Linux / Web / 云服务器重启与关闭**:重启目标从 Windows 桌面扩展到非 Windows Host 进程。systemd / Docker / Kubernetes / PID 1 使用 supervisor-exit(退出码 75);普通 `dsh web` 使用 detached reexec helper,等待旧 PID 退出后再启动同一 argv/cwd。可用 `DSH_MCVISERON_RESTART_MODE=reexec|supervisor-exit` 覆盖。
16
+ - **设置页「重启 / 关闭」**:状态显示 desktop / reexec / supervisor-exit;新增关闭 DSH 按钮;Linux/Web 下 `set_session_end_action` 的 restart/close 可用,OS 关机仍为 Windows-only。
17
+ - **文档**:新增 [docs/linux-restart.md](docs/linux-restart.md),包含 systemd、Docker、Kubernetes 和普通 CLI 的部署/停止策略。
18
+
19
+ ### Tests
20
+
21
+ - 合计 **129 项测试**;typecheck、build 全绿。
22
+
1
23
  ## [Unreleased]
2
24
 
3
25
  ### 计划中
@@ -6,6 +28,12 @@
6
28
  - 设置行支持「立即测试」预览按钮。
7
29
  - Restart 组件支持 macOS/Linux(当前仅 Windows 桌面版)。
8
30
 
31
+ ## [Unreleased]
32
+
33
+ ### Docs
34
+
35
+ - 在 `docs/automation-tasks.md` 补充 Host Schedule 管理 API:0.2.2 的 `list({}) -> { items }`、`create(request, sessionId, signal)`、`edit({ id, action, patch }, sessionId, signal)`,以及旧版 `list({ sessionId })` / `create(sessionId, request)` / `update` / `delete` 的兼容层与 timing 映射;README 组件表加入文档链接。
36
+
9
37
  ## [0.7.8] - 2026-11-22
10
38
 
11
39
  ### Fixed
package/README.en.md CHANGED
@@ -11,10 +11,10 @@ MCviseron's **master plugin for DeepSeek Harness (DSH)**: one npm package and on
11
11
  | **Appearance · light/dark by time** | `mcviseron` top-level fields | Adds a settings row below DSH's Appearance row and switches the palette from the local wall clock |
12
12
  | **Auto-review hardening** | `mcviseron.autoReviewFix` | Stops the whole-Host shutdown from persisting Full access over an Auto session; appends a Chinese translation to the manual-approval prompt |
13
13
  | **Todo plan guard** | `mcviseron.taskGuard` | Advisory notices (optional hard stop) when multi-stage work stops updating its todo plan |
14
- | **Restart DeepSeek Harness** | `mcviseron.restart` | Button in Settings → MCviseron plugin that closes and relaunches the desktop application |
14
+ | **Restart / close DSH** | `mcviseron.restart` | Settings tab that restarts or closes the Windows desktop app or a Linux/Web/cloud DSH process (supervisor-exit or detached reexec); see [docs/linux-restart.md](docs/linux-restart.md) |
15
15
  | **After-session action** | `mcviseron.sessionEnd` | “Restart after session” dropdown in the composer; the AI tool can arm it; restart waits for running tasks |
16
16
  | **Auth-cookie cleanup** | built in | Expires old `dsh-auth-*` cookies on every page load, keeping only the current one so restarts cannot push the request header to 16 KB |
17
- | **Automation task editing** | built-in tools | `automation_task_list/create/update/delete` call the Host schedule service and persist automatically |
17
+ | **Automation task editing** | built-in tools | `automation_task_list/create/update/delete` call the Host schedule service and persist automatically; see [docs/automation-tasks.md](docs/automation-tasks.md) for API compatibility |
18
18
  | **Archive-time integration (optional)** | conditional | Shows the Archive time tab only when `@linxin666/dsh-session-archive` is detected; no registration when absent |
19
19
 
20
20
  > 0.6.1 returns to a **single** `mcviseron` entry: DSH `client-modules` only composes a browser half for an exact package-name Loader row, and subpath rows silently dropped the whole client plugin. Components still run as sub-plugins and expose Auto-review / Todo / session-end / conditional archive-time sub-pages.
@@ -44,9 +44,10 @@ MCviseron's **master plugin for DeepSeek Harness (DSH)**: one npm package and on
44
44
  - **Step-intent detection** (`detectStepIntent`): watches the official `agent/assistant-stream` text/reasoning deltas for phrases such as "Now I will …" / "接下来我会 …" and matches them against pending todos. A match adds one targeted, advisory notice per step (with a ready-to-send `todo_write` JSON); a miss, a missing stream, or malformed data is silently skipped and never blocks the task.
45
45
  - **Chinese todo display** (`translateTodoContent`): English todo titles in notices are batch-translated into "中文(English)" through the host `llm` service (cached per title, 3 s default timeout, original text on failure). Display only — the model's stored todo list is never rewritten.
46
46
 
47
- ### 4. Restart DeepSeek Harness
47
+ ### 4. Restart / close DSH
48
48
 
49
- - A "Settings → MCviseron plugin → Restart" tab asks for confirmation and restarts the desktop app.
49
+ - Windows desktop: the **Restart / close** tab asks for confirmation and restarts or closes the desktop app.
50
+ - Linux / Web / cloud: a plain `dsh web` process uses a detached reexec helper; systemd / Docker / Kubernetes / PID 1 use supervisor-exit (code 75); close exits with code 0 and the deployment policy decides whether it restarts. See [docs/linux-restart.md](docs/linux-restart.md).
50
51
  - A detached PowerShell helper closes the Electron main process; the Host performs its normal graceful shutdown when its IPC channel disconnects; the helper waits for both processes, clears `ELECTRON_RUN_AS_NODE`, and starts the application again.
51
52
  - Running tasks are interrupted (same warning as the tray Quit); plugins, settings, and session records are not modified.
52
53
  - Desktop-only: under `dsh web` the status route reports unavailable and the row hides.
@@ -154,12 +155,12 @@ Defaults: appearance off / `08:00–23:00`; auto-review both guards on, 6 s, 400
154
155
 
155
156
  | DSH version | Status |
156
157
  | --- | --- |
157
- | `0.2.2-rc.5` | ✅ pre-adapted (0.2.2-rc.5 types/deps + 126 tests; current desktop still rc.3) |
158
- | `0.2.2-rc.3` | ✅ current desktop (rc.3 types/deps + 126 tests; real runtime verified) |
159
- | `0.2.2-rc.1` | ✅ compatible (0.2.2-rc.1 types/deps + 126 tests) |
160
- | `0.2.1-rc.5` | ✅ compatible (rc.5 types/deps + 126 tests) |
161
- | `0.2.1-rc.3` | ✅ compatible (rc.3 types/deps + 126 tests) |
162
- | `0.2.1-rc.2` | ✅ current desktop runtime (126 tests + real Cordis contexts) |
158
+ | `0.2.2-rc.5` | ✅ pre-adapted (0.2.2-rc.5 types/deps + 129 tests; current desktop still rc.3) |
159
+ | `0.2.2-rc.3` | ✅ current desktop (rc.3 types/deps + 129 tests; real runtime verified) |
160
+ | `0.2.2-rc.1` | ✅ compatible (0.2.2-rc.1 types/deps + 129 tests) |
161
+ | `0.2.1-rc.5` | ✅ compatible (rc.5 types/deps + 129 tests) |
162
+ | `0.2.1-rc.3` | ✅ compatible (rc.3 types/deps + 129 tests) |
163
+ | `0.2.1-rc.2` | ✅ current desktop runtime (129 tests + real Cordis contexts) |
163
164
  | `0.2.0-rc.x` | ✅ covered by the peer range |
164
165
  | `0.1.x` | ❌ unsupported (different settings-namespace model) |
165
166
 
package/README.md CHANGED
@@ -11,10 +11,10 @@ MCviseron 的 **DeepSeek Harness(DSH)总插件**:一个 npm 包、一个 `
11
11
  | **外观 · 按时间自动切换深浅色** | `mcviseron` 顶层字段 | 「设置 → 通用 → 外观」新增选项,按本机时间切换浅/深色 |
12
12
  | **Auto review 修复** | `mcviseron.autoReviewFix` | 关机不再把 Auto 会话写成完全访问;人审提示追加中文译文 |
13
13
  | **Todo 计划守卫** | `mcviseron.taskGuard` | 多阶段任务忘记更新 todo 时发出 notice(可选硬拦截) |
14
- | **重启 DeepSeek Harness** | `mcviseron.restart` | 「设置 → MCviseron 插件」里的重启按钮:关闭并重新启动桌面应用 |
14
+ | **重启 / 关闭 DSH** | `mcviseron.restart` | 「设置 → MCviseron 插件」里的重启/关闭按钮:Windows 桌面版重启应用;Linux/Web/云服务器使用 supervisor-exit 或 detached reexec |
15
15
  | **会话后动作** | `mcviseron.sessionEnd` | 输入框左侧「会话后重启」下拉;AI 工具可设置;重启等待任务结束 |
16
16
  | **认证 cookie 清理** | 内置 | 每次页面加载过期旧 `dsh-auth-*`,只保留当前,避免重启把请求头推到 16KB |
17
- | **自动化任务编辑** | 内置工具 | `automation_task_list/create/update/delete` 直接调用 Host schedule 并自动存盘 |
17
+ | **自动化任务编辑** | 内置工具 | `automation_task_list/create/update/delete` 直接调用 Host schedule 并自动存盘;API 兼容说明见 [docs/automation-tasks.md](docs/automation-tasks.md) |
18
18
  | **归档时间集成(可选)** | 条件注册 | 仅检测到 `@linxin666/dsh-session-archive` 时显示「归档时间」子页;未安装不注册 |
19
19
 
20
20
  > 0.6.1 起回到**单一** `mcviseron` 条目:DSH `client-modules` 只给精确包名条目组合浏览器半区,子路径条目会让整个客户端插件(外观行、设置分区、重启回退)消失。组件仍在内部作为子插件运行,设置页有 Auto review / Todo / 会话后动作 / 条件归档时间子页。
@@ -48,9 +48,10 @@ MCviseron 的 **DeepSeek Harness(DSH)总插件**:一个 npm 包、一个 `
48
48
  - **中文 todo 展示**(`translateTodoContent`):notice 里的英文 todo 标题会经 `llm` 批量翻译成「中文(English)」显示,按标题缓存、超时 3 秒可配;翻译失败就显示原文。notice 里还会提示「todo 内容可以直接用中文书写」。**只影响 notice 展示,不改写模型写入的 todo 列表**。
49
49
  - notice 的 source kind 按会话格式自动选择:v4 用 `plugin:task-guard`,v3 用 `plugin` + `plugin: 'task-guard'`。
50
50
 
51
- ### 4. 重启 DeepSeek Harness
51
+ ### 4. 重启 / 关闭 DSH
52
52
 
53
- - 在「设置 → MCviseron 插件 → 重启」子页提供「重启 DeepSeek Harness」按钮,点击后确认并重启桌面应用。
53
+ - Windows 桌面版:「设置 → MCviseron 插件 → 重启 / 关闭」子页提供重启与关闭按钮,点击后确认并重启/关闭桌面应用。
54
+ - Linux / Web / 云服务器:普通 `dsh web` 使用 detached reexec;systemd / Docker / Kubernetes / PID 1 使用 supervisor-exit(退出码 75);关闭使用 exit 0,保持停止还是被托管器拉起由部署策略决定。详见 [docs/linux-restart.md](docs/linux-restart.md)。
54
55
  - 重启方式:Host 写一个临时 PowerShell 助手(detached),先关闭 Electron 主进程;Host 在 IPC 断开后按官方流程优雅关闭所有插件与会话;助手等待主进程与 Host 退出后,清除 `ELECTRON_RUN_AS_NODE` 并重新启动应用。
55
56
  - 会中断正在运行的任务(与托盘「退出」的提示一致),不会修改插件、配置或会话记录。
56
57
  - 只在桌面版可用;`dsh web` 下状态接口返回不可用,设置行自动隐藏。
@@ -85,7 +86,7 @@ MCviseron 的 **DeepSeek Harness(DSH)总插件**:一个 npm 包、一个 `
85
86
 
86
87
  设置里新增一个一级分区 **「MCviseron 插件」**(`settings.section`,id `mcviseron`),组件按需在这里拥有子页:
87
88
 
88
- - **重启**:重启 DeepSeek Harness(本组件的设置面)。
89
+ - **重启 / 关闭**:Windows 桌面版重启 Electron;Linux/Web 按进程模式重启或关闭(见 [docs/linux-restart.md](docs/linux-restart.md))。
89
90
  - **会话后动作**:启用开关、显示等待、AI 邮件提醒、邮件主题/正文模板。
90
91
  - **归档时间(条件)**:检测到第三方归档插件时显示;未安装或禁用时不注册、不显示。
91
92
  - **组件**:列出八个组件及其配置位置。
@@ -249,12 +250,12 @@ DSH 0.2 的官方设置 apiproxy 不向浏览器暴露第三方命名空间,
249
250
 
250
251
  | DSH 版本 | 状态 |
251
252
  | --- | --- |
252
- | `0.2.2-rc.5` | ✅ 预适配(0.2.2-rc.5 类型/依赖 + 126 项测试;当前桌面仍为 rc.3) |
253
- | `0.2.2-rc.3` | ✅ 当前桌面安装(rc.3 类型/依赖 + 126 项测试;真实运行时验证) |
254
- | `0.2.2-rc.1` | ✅ 兼容(0.2.2-rc.1 类型/依赖 + 126 项测试) |
255
- | `0.2.1-rc.5` | ✅ 兼容(rc.5 类型/依赖 + 126 项测试) |
256
- | `0.2.1-rc.3` | ✅ 兼容(rc.3 类型/依赖 + 126 项测试) |
257
- | `0.2.1-rc.2` | ✅ 当前桌面运行版本(126 项测试 + 真实 Cordis 上下文) |
253
+ | `0.2.2-rc.5` | ✅ 预适配(0.2.2-rc.5 类型/依赖 + 129 项测试;当前桌面仍为 rc.3) |
254
+ | `0.2.2-rc.3` | ✅ 当前桌面安装(rc.3 类型/依赖 + 129 项测试;真实运行时验证) |
255
+ | `0.2.2-rc.1` | ✅ 兼容(0.2.2-rc.1 类型/依赖 + 129 项测试) |
256
+ | `0.2.1-rc.5` | ✅ 兼容(rc.5 类型/依赖 + 129 项测试) |
257
+ | `0.2.1-rc.3` | ✅ 兼容(rc.3 类型/依赖 + 129 项测试) |
258
+ | `0.2.1-rc.2` | ✅ 当前桌面运行版本(129 项测试 + 真实 Cordis 上下文) |
258
259
  | `0.2.0-rc.x` | ✅ peer 范围覆盖(同一套设置、审批与 hook 接缝) |
259
260
  | `0.1.x` | ❌ 不支持:0.1 的插件自行注册设置命名空间,与本插件的条目 id 命名空间模型不同 |
260
261
 
@@ -320,7 +321,7 @@ test/
320
321
 
321
322
  ```bash
322
323
  pnpm install
323
- pnpm check # typecheck + 126 项测试 + 构建
324
+ pnpm check # typecheck + 129 项测试 + 构建
324
325
  ```
325
326
 
326
327
  构建产物:`lib/index.js`(master ESM)、`lib/appearance.js`、`lib/auto-review-fix.js`、`lib/task-guard.js`、`lib/restart.js` 与 `lib/client.js`(浏览器模块)。`lib/` 不入库。
@@ -27,6 +27,55 @@ DSH 官方的 `schedule_create/list/update/delete` 只在声明了
27
27
  - `weekly`:`{ time, time_zone, weekdays }`;
28
28
  - `cron`:`{ expression, time_zone }`。
29
29
 
30
+ ## Host Schedule 管理 API
31
+
32
+ 组件不直接编辑 `schedule.json`,只调用 Host 的 `ctx.schedule` 服务。DSH 0.2.2
33
+ 与旧版接口不同,组件用 `typeof schedule.edit === 'function'` 探测并分层适配:
34
+
35
+ ### DSH 0.2.2+
36
+
37
+ ```ts
38
+ // 列表:分页信封
39
+ const page = await schedule.list({}, exec.signal)
40
+ // page.items: ScheduleTask[]
41
+
42
+ // 创建:request 带 target,sessionId 作为绑定参数
43
+ const task = await schedule.create({
44
+ title: '...',
45
+ prompt: '...',
46
+ timing: { kind: 'weekly', weekly: { time: '09:00', time_zone: 'Asia/Shanghai', weekdays: [6] } },
47
+ target: { kind: 'session', sessionId },
48
+ }, sessionId, exec.signal)
49
+
50
+ // 修改 / 删除:统一走 edit
51
+ await schedule.edit({ id, action: 'update', patch }, sessionId, exec.signal)
52
+ await schedule.edit({ id, action: 'delete' }, sessionId, exec.signal)
53
+ ```
54
+
55
+ ### 旧版 API
56
+
57
+ ```ts
58
+ const tasks = await schedule.list({ sessionId }, exec.signal) // ScheduleTask[]
59
+ const task = await schedule.create(sessionId, request, exec.signal)
60
+ await schedule.update(sessionId, id, patch, exec.signal)
61
+ await schedule.delete(sessionId, id, exec.signal)
62
+ ```
63
+
64
+ ### 工具参数到 timing 的映射
65
+
66
+ | 工具参数 | Host timing |
67
+ |---|---|
68
+ | `after_seconds` | `{ kind: 'after', after_seconds }` |
69
+ | `at` | `{ kind: 'at', at }` |
70
+ | `every_seconds` | `{ kind: 'every', every_seconds }` |
71
+ | `daily` | `{ kind: 'daily', daily }` |
72
+ | `weekly` | `{ kind: 'weekly', weekly }` |
73
+ | `cron` | `{ kind: 'cron', cron }` |
74
+
75
+ `listRecords()` 同时接受 `ScheduleTask[]` 和 `{ items: ScheduleTask[] }`,避免
76
+ 0.2.2 升级后 `.find is not a function`。旧 API 的 update/delete 只在新 API 缺失时
77
+ 才使用。
78
+
30
79
  ## 自动存盘
31
80
 
32
81
  工具直接调用 `ctx.schedule`;该方法负责持久化,和官方自动化任务 UI 使用同一个
@@ -0,0 +1,96 @@
1
+ # Linux / Web / 云服务器上的重启与关闭
2
+
3
+ Windows 桌面版继续使用 Electron 主进程 + Task Scheduler 的原地重启;Linux、Web 与云服务器使用 Host 进程级方案。
4
+
5
+ ## 目标解析
6
+
7
+ `resolveRestartTarget()` 在非 Windows 平台返回 ProcessTarget:
8
+
9
+ - `execPath`:`process.execPath`(通常是 node);
10
+ - `argv`:`process.execArgv` + `process.argv.slice(1)`,即当前 dsh 命令及参数;
11
+ - `cwd`:当前工作目录;
12
+ - `mode`:`reexec` 或 `supervisor-exit`。
13
+
14
+ ### supervisor-exit
15
+
16
+ 以下任一条件成立时,重启请求只退出 Host,由外层托管器拉起:
17
+
18
+ - systemd:`INVOCATION_ID` / `JOURNAL_STREAM` / `SYSTEMD_EXEC_PID`;
19
+ - Kubernetes:`KUBERNETES_SERVICE_HOST`;
20
+ - Docker:存在 `/.dockerenv`;
21
+ - 进程 PID 为 1(容器入口);
22
+ - `DSH_MCVISERON_RESTART_MODE=supervisor-exit`(或 `exit`)。
23
+
24
+ 退出码为 **75**(`EX_TEMPFAIL`),便于 `Restart=on-failure` / Docker `on-failure` 识别为需要重启。
25
+
26
+ ### reexec
27
+
28
+ 普通 `dsh web` 进程:
29
+
30
+ 1. 写入一个 detached Node helper;
31
+ 2. helper 等待原 PID 退出;
32
+ 3. helper 用相同 `execPath`、argv、cwd 和环境启动新进程;
33
+ 4. 原进程退出。
34
+
35
+ helper 会最多等待原进程 30 秒,避免端口未释放就启动新实例。可用
36
+ `DSH_MCVISERON_RESTART_MODE=reexec` 强制该模式。
37
+
38
+ ## 关闭
39
+
40
+ 关闭请求执行 `process.exit(0)`(桌面版关闭 Electron 主进程),不再启动新进程。
41
+ 关闭后是否真正保持停止,由托管器策略决定:
42
+
43
+ ### systemd
44
+
45
+ ```ini
46
+ [Service]
47
+ ExecStart=/usr/bin/dsh web --host 0.0.0.0 --port 3000
48
+ Restart=on-failure
49
+ RestartSec=3
50
+ ```
51
+
52
+ - 重启:进程以 75 退出,systemd 重新拉起;
53
+ - 关闭:进程以 0 退出,systemd 不再拉起。
54
+
55
+ ### Docker
56
+
57
+ ```bash
58
+ docker run --restart on-failure ...
59
+ ```
60
+
61
+ - 重启:75 退出,Docker 重新拉起;
62
+ - 关闭:0 退出,保持停止。
63
+ - 若使用 `--restart unless-stopped`,关闭也会被 Docker 重新拉起;这是 Docker 策略,不是插件能覆盖的。
64
+
65
+ ### Kubernetes
66
+
67
+ ```yaml
68
+ restartPolicy: OnFailure
69
+ ```
70
+
71
+ - 重启:75 退出,kubelet 重启容器;
72
+ - 关闭:0 退出,Pod 保持 Completed。
73
+ - `restartPolicy: Always` 下关闭也会被重新拉起;需要停止时使用 `kubectl delete pod` 或调整策略。
74
+
75
+ ### 普通 CLI
76
+
77
+ 直接运行 `dsh web` 时使用 reexec helper;关闭后进程直接结束,不会被重新拉起。
78
+
79
+ ## 设置页与会话后动作
80
+
81
+ - 「重启 / 关闭」设置页同时提供重启与关闭按钮;
82
+ - 状态会显示当前模式(desktop / reexec / supervisor-exit);
83
+ - `set_session_end_action` 的 `restart` / `close` 在 Linux/Web 同样可用;
84
+ - 操作系统关机仍是 Windows-only,Linux 上不提供。
85
+
86
+ ## 安全与限制
87
+
88
+ - 路由仍只接受 loopback 请求并需要 `confirm: true`;
89
+ - 重启不会执行任意命令,只复用当前进程的 `execPath`、argv、cwd;
90
+ - supervisor-exit 依赖托管器配置;没有托管器的环境应使用 reexec;
91
+ - reexec 需要当前进程有权限启动新进程;容器内建议使用 supervisor-exit;
92
+ - 日志:`$TMPDIR/dsh-mcviseron-restart.log`(Windows 为 `%TEMP%`)。
93
+
94
+ ## 测试
95
+
96
+ `test/restart.test.ts` 覆盖 Windows 桌面目标、Linux reexec/supervisor 探测、环境变量覆盖、状态/执行路由与关闭动作;`test/session-end.test.ts` 覆盖 Linux 的 restart/close 可用性。
package/lib/client.js CHANGED
@@ -374,7 +374,7 @@ function RestartCard({ t }) {
374
374
  const body = await response.json();
375
375
  if (body.ok !== true) throw new Error("restart-status-rejected");
376
376
  if (body.available === true) {
377
- setState({ kind: "ready", appPath: typeof body.appPath === "string" ? body.appPath : "" });
377
+ setState({ kind: "ready", appPath: typeof body.appPath === "string" ? body.appPath : "", mode: typeof body.mode === "string" ? body.mode : "desktop" });
378
378
  } else {
379
379
  setState({ kind: "unavailable" });
380
380
  }
@@ -402,8 +402,25 @@ function RestartCard({ t }) {
402
402
  setState({ kind: "failed", message: error instanceof Error ? error.message : String(error) });
403
403
  }
404
404
  };
405
- const status = state.kind === "ready" ? t("page.restart.ready") : state.kind === "route-missing" ? t("page.restart.routeMissing") : state.kind === "restarting" ? t("page.restart.restarting") : state.kind === "failed" ? t("page.restart.failed") + (state.message !== "" ? " (" + state.message + ")" : "") : state.kind === "loading" ? t("restart.checking") : t("page.restart.unavailable");
405
+ const startClose = async () => {
406
+ if (!window.confirm(t("page.restart.closeConfirm"))) return;
407
+ setState({ kind: "closing" });
408
+ try {
409
+ const response = await fetch(EXECUTE, {
410
+ method: "POST",
411
+ headers: { "content-type": "application/json" },
412
+ body: JSON.stringify({ confirm: true, action: "close" })
413
+ });
414
+ if (!response.ok) throw new Error(await readError(response));
415
+ const body = await response.json();
416
+ if (body.ok !== true) throw new Error("close-rejected");
417
+ } catch (error) {
418
+ setState({ kind: "failed", message: error instanceof Error ? error.message : String(error) });
419
+ }
420
+ };
421
+ const status = state.kind === "ready" ? state.mode === "reexec" ? t("page.restart.modeProcess") : state.mode === "supervisor-exit" ? t("page.restart.modeSupervisor") : t("page.restart.ready") : state.kind === "closing" ? t("page.restart.closing") : state.kind === "route-missing" ? t("page.restart.routeMissing") : state.kind === "restarting" ? t("page.restart.restarting") : state.kind === "failed" ? t("page.restart.failed") + (state.message !== "" ? " (" + state.message + ")" : "") : state.kind === "loading" ? t("restart.checking") : t("page.restart.unavailable");
406
422
  const canRestart = state.kind === "ready" || state.kind === "failed";
423
+ const canClose = state.kind === "ready";
407
424
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: pageStyles.card, children: [
408
425
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: pageStyles.cardTitle, children: t("page.restart.title") }),
409
426
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: pageStyles.cardBody, children: t("page.restart.description") }),
@@ -413,18 +430,32 @@ function RestartCard({ t }) {
413
430
  ": ",
414
431
  state.appPath
415
432
  ] }) : null,
416
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { style: pageStyles.cardActions, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
417
- "button",
418
- {
419
- type: "button",
420
- disabled: !canRestart,
421
- onClick: () => {
422
- void startRestart();
423
- },
424
- style: canRestart ? styles.button : styles.buttonDisabled,
425
- children: state.kind === "restarting" ? t("page.restart.restarting") : t("page.restart.button")
426
- }
427
- ) })
433
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: pageStyles.cardActions, children: [
434
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
435
+ "button",
436
+ {
437
+ type: "button",
438
+ disabled: !canRestart,
439
+ onClick: () => {
440
+ void startRestart();
441
+ },
442
+ style: canRestart ? styles.button : styles.buttonDisabled,
443
+ children: state.kind === "restarting" ? t("page.restart.restarting") : t("page.restart.button")
444
+ }
445
+ ),
446
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
447
+ "button",
448
+ {
449
+ type: "button",
450
+ disabled: !canClose,
451
+ onClick: () => {
452
+ void startClose();
453
+ },
454
+ style: canClose ? styles.button : styles.buttonDisabled,
455
+ children: state.kind === "closing" ? t("page.restart.closing") : t("page.restart.close")
456
+ }
457
+ )
458
+ ] })
428
459
  ] });
429
460
  }
430
461
 
@@ -1572,12 +1603,17 @@ var zh = {
1572
1603
  "sessionEnd.failed": "\u8BBE\u7F6E\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5",
1573
1604
  "page.title": "MCviseron \u63D2\u4EF6",
1574
1605
  "page.description": "\u603B\u63D2\u4EF6\u7684\u7EC4\u4EF6\u8BBE\u7F6E\u3002\u5916\u89C2\u8BBE\u7F6E\u4ECD\u5728\u300C\u901A\u7528 \u2192 \u5916\u89C2\u300D\u4E2D\u3002",
1575
- "page.tab.restart": "\u91CD\u542F",
1606
+ "page.tab.restart": "\u91CD\u542F / \u5173\u95ED",
1576
1607
  "page.tab.components": "\u7EC4\u4EF6",
1577
- "page.restart.title": "\u91CD\u542F DeepSeek Harness",
1578
- "page.restart.description": "\u5173\u95ED\u5E76\u91CD\u65B0\u542F\u52A8\u684C\u9762\u5E94\u7528\uFF1B\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u4F1A\u88AB\u4E2D\u65AD",
1608
+ "page.restart.title": "\u91CD\u542F / \u5173\u95ED DeepSeek Harness",
1609
+ "page.restart.description": "\u91CD\u542F\u6216\u5173\u95ED\u5F53\u524D DSH\uFF08\u684C\u9762\u5E94\u7528\u3001Linux/Web \u8FDB\u7A0B\u6216\u4E91\u6258\u7BA1\u5BB9\u5668\uFF09\uFF1B\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u4F1A\u88AB\u4E2D\u65AD",
1579
1610
  "page.restart.ready": "\u53EF\u7528",
1580
- "page.restart.unavailable": "\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u91CD\u542F\uFF08\u4EC5 Windows \u684C\u9762\u7248\u53EF\u7528\uFF09",
1611
+ "page.restart.modeProcess": "Linux/Web \u8FDB\u7A0B\uFF1A\u5C06\u91CD\u65B0\u62C9\u8D77\u5F53\u524D dsh \u547D\u4EE4",
1612
+ "page.restart.modeSupervisor": "\u7531 systemd / Docker / Kubernetes \u6258\u7BA1\uFF1A\u9000\u51FA\u540E\u7531\u6258\u7BA1\u5668\u91CD\u542F",
1613
+ "page.restart.close": "\u5173\u95ED DSH",
1614
+ "page.restart.closing": "\u6B63\u5728\u5173\u95ED\u2026",
1615
+ "page.restart.closeConfirm": "\u786E\u5B9A\u8981\u5173\u95ED DSH \u5417\uFF1F\u91CD\u542F/\u5173\u95ED\u52A8\u4F5C\u4F1A\u4E2D\u65AD\u6B63\u5728\u8FD0\u884C\u7684\u4EFB\u52A1\u3002",
1616
+ "page.restart.unavailable": "\u5F53\u524D\u73AF\u5883\u6CA1\u6709\u53EF\u7528\u7684\u91CD\u542F\u76EE\u6807",
1581
1617
  "page.restart.routeMissing": "\u91CD\u542F\u63A5\u53E3\u672A\u52A0\u8F7D\uFF1A\u8BF7\u786E\u8BA4 mcviseron-restart \u6761\u76EE\u5DF2\u542F\u7528",
1582
1618
  "page.restart.appPath": "\u5E94\u7528\u8DEF\u5F84",
1583
1619
  "page.restart.button": "\u91CD\u542F",
@@ -1591,8 +1627,8 @@ var zh = {
1591
1627
  "page.components.autoReviewFixHint": "\u672C\u9875\u300CAuto review \u4FEE\u590D\u300D\u5B50\u9875",
1592
1628
  "page.components.taskGuard": "Todo \u8BA1\u5212\u5B88\u536B",
1593
1629
  "page.components.taskGuardHint": "\u672C\u9875\u300CTodo \u5B88\u536B\u300D\u5B50\u9875",
1594
- "page.components.restart": "\u91CD\u542F DeepSeek Harness",
1595
- "page.components.restartHint": "\u672C\u9875\u300C\u91CD\u542F\u300D\u5B50\u9875",
1630
+ "page.components.restart": "\u91CD\u542F / \u5173\u95ED DSH",
1631
+ "page.components.restartHint": "\u672C\u9875\u300C\u91CD\u542F / \u5173\u95ED\u300D\u5B50\u9875",
1596
1632
  "page.components.note": "\u7EC4\u4EF6\u914D\u7F6E\u5199\u5165 master \u6761\u76EE\uFF08mcviseron\uFF09\u7684 Config\uFF1B\u82E5\u7EC4\u4EF6\u4ECD\u4F7F\u7528\u65E7\u503C\uFF0C\u91CD\u542F DSH \u540E\u751F\u6548\u3002",
1597
1633
  "page.fallback.note": "\u8BBE\u7F6E\u5206\u533A\u672A\u52A0\u8F7D\uFF0C\u91CD\u542F\u5165\u53E3\u6682\u65F6\u56DE\u9000\u5230\u901A\u7528\u8BBE\u7F6E\u3002",
1598
1634
  "page.tab.autoReview": "Auto review \u4FEE\u590D",
@@ -1713,12 +1749,17 @@ var en = {
1713
1749
  "sessionEnd.failed": "Could not update the session-end action",
1714
1750
  "page.title": "MCviseron plugin",
1715
1751
  "page.description": "Settings for the master plugin components. Appearance still lives under General \u2192 Appearance.",
1716
- "page.tab.restart": "Restart",
1752
+ "page.tab.restart": "Restart / close",
1717
1753
  "page.tab.components": "Components",
1718
- "page.restart.title": "Restart DeepSeek Harness",
1719
- "page.restart.description": "Closes and relaunches the desktop application; running tasks are interrupted",
1754
+ "page.restart.title": "Restart / close DeepSeek Harness",
1755
+ "page.restart.description": "Restart or close DSH (desktop app, Linux/Web process, or cloud container); running tasks are interrupted",
1720
1756
  "page.restart.ready": "Available",
1721
- "page.restart.unavailable": "Restarting is available only in the Windows desktop app",
1757
+ "page.restart.modeProcess": "Linux/Web process: relaunch the current dsh command",
1758
+ "page.restart.modeSupervisor": "Managed by systemd / Docker / Kubernetes: exit and let the supervisor restart it",
1759
+ "page.restart.close": "Close DSH",
1760
+ "page.restart.closing": "Closing\u2026",
1761
+ "page.restart.closeConfirm": "Close DSH? Restart/close interrupts running tasks.",
1762
+ "page.restart.unavailable": "No restart target is available in this environment",
1722
1763
  "page.restart.routeMissing": "The restart route is not loaded: check that the mcviseron-restart entry is enabled",
1723
1764
  "page.restart.appPath": "App path",
1724
1765
  "page.restart.button": "Restart",
@@ -1732,8 +1773,8 @@ var en = {
1732
1773
  "page.components.autoReviewFixHint": "The Auto-review fix tab on this page",
1733
1774
  "page.components.taskGuard": "Todo plan guard",
1734
1775
  "page.components.taskGuardHint": "The Todo guard tab on this page",
1735
- "page.components.restart": "Restart DeepSeek Harness",
1736
- "page.components.restartHint": "The Restart tab on this page",
1776
+ "page.components.restart": "Restart / close DSH",
1777
+ "page.components.restartHint": "The Restart / close tab on this page",
1737
1778
  "page.components.note": "Component settings are written to the mcviseron entry config; restart DSH if a component still uses the old value.",
1738
1779
  "page.fallback.note": "The settings section is unavailable, so the restart entry falls back to General.",
1739
1780
  "page.tab.autoReview": "Auto-review fix",
package/lib/index.js CHANGED
@@ -10466,13 +10466,13 @@ var require_smtp_transport = __commonJS({
10466
10466
  var require_sendmail_transport = __commonJS({
10467
10467
  "node_modules/.pnpm/nodemailer@6.10.1/node_modules/nodemailer/lib/sendmail-transport/index.js"(exports, module) {
10468
10468
  "use strict";
10469
- var spawn = __require("child_process").spawn;
10469
+ var spawn2 = __require("child_process").spawn;
10470
10470
  var packageData = require_package();
10471
10471
  var shared = require_shared();
10472
10472
  var SendmailTransport = class {
10473
10473
  constructor(options) {
10474
10474
  options = options || {};
10475
- this._spawn = spawn;
10475
+ this._spawn = spawn2;
10476
10476
  this.options = options || {};
10477
10477
  this.name = "Sendmail";
10478
10478
  this.version = packageData.version;
@@ -12941,10 +12941,12 @@ __export(restart_exports, {
12941
12941
  launchRestart: () => launchRestart,
12942
12942
  makeRestartRoutes: () => makeRestartRoutes,
12943
12943
  makeTaskScript: () => makeTaskScript,
12944
- resolveRestartTarget: () => resolveRestartTarget
12944
+ resolveProcessRestartTarget: () => resolveProcessRestartTarget,
12945
+ resolveRestartTarget: () => resolveRestartTarget,
12946
+ restartMode: () => restartMode
12945
12947
  });
12946
- import { execFileSync } from "node:child_process";
12947
- import { appendFileSync as appendFileSync4, existsSync as existsSync2 } from "node:fs";
12948
+ import { execFileSync, spawn } from "node:child_process";
12949
+ import { appendFileSync as appendFileSync4, existsSync as existsSync2, writeFileSync } from "node:fs";
12948
12950
  import { tmpdir as tmpdir4 } from "node:os";
12949
12951
  import { basename, dirname, join as join5, resolve } from "node:path";
12950
12952
  import z3 from "@deepseek-ai/schemastery";
@@ -12959,7 +12961,9 @@ var RESTART_API = {
12959
12961
  execute: "/api/dsh-mcviseron/restart/execute"
12960
12962
  };
12961
12963
  function resolveRestartTarget(execPath, parentPid, exists, override = "", argv = [], platform = process.platform) {
12962
- if (platform !== "win32") return void 0;
12964
+ if (platform !== "win32") {
12965
+ return resolveProcessRestartTarget({ platform, execPath, argv: argv.slice(1), cwd: process.cwd() });
12966
+ }
12963
12967
  if (!Number.isSafeInteger(parentPid) || parentPid <= 0) return void 0;
12964
12968
  const configured = typeof override === "string" ? override.trim() : "";
12965
12969
  const candidate = configured !== "" ? configured : deriveDesktopAppPath(execPath, argv, exists);
@@ -12968,6 +12972,23 @@ function resolveRestartTarget(execPath, parentPid, exists, override = "", argv =
12968
12972
  if (name === "node" || name === "node.exe") return void 0;
12969
12973
  return { mainPid: parentPid, hostPid: process.pid, exePath: candidate };
12970
12974
  }
12975
+ function resolveProcessRestartTarget(options = {}) {
12976
+ const platform = options.platform ?? process.platform;
12977
+ if (platform === "win32") return void 0;
12978
+ const argv = options.argv ?? process.argv.slice(1);
12979
+ if (argv.length === 0 || argv[0] === "") return void 0;
12980
+ const env = options.env ?? process.env;
12981
+ const override = (env.DSH_MCVISERON_RESTART_MODE ?? "").trim().toLowerCase();
12982
+ const supervised = override === "supervisor-exit" || override === "exit" || override !== "reexec" && (env.INVOCATION_ID !== void 0 || env.JOURNAL_STREAM !== void 0 || env.SYSTEMD_EXEC_PID !== void 0 || env.KUBERNETES_SERVICE_HOST !== void 0 || existsSync2("/.dockerenv") || options.pid1 === true || (options.pid ?? process.pid) === 1);
12983
+ const nodeArgs = options.execArgv ?? process.execArgv;
12984
+ return {
12985
+ hostPid: options.pid ?? process.pid,
12986
+ exePath: options.execPath ?? process.execPath,
12987
+ mode: supervised ? "supervisor-exit" : "reexec",
12988
+ argv: [...nodeArgs, ...argv],
12989
+ cwd: options.cwd ?? process.cwd()
12990
+ };
12991
+ }
12971
12992
  function deriveDesktopAppPath(execPath, argv, exists) {
12972
12993
  const isNode = (value) => /^node(\.exe)?$/i.test(basename(value));
12973
12994
  if (!isNode(execPath)) return execPath;
@@ -12978,6 +12999,9 @@ function deriveDesktopAppPath(execPath, argv, exists) {
12978
12999
  const candidate = join5(resolve(runtimeDir, "../../.."), "DeepSeek Harness.exe");
12979
13000
  return exists(candidate) ? candidate : execPath;
12980
13001
  }
13002
+ function restartMode(target) {
13003
+ return target.mode ?? (target.mainPid !== void 0 ? "desktop" : "reexec");
13004
+ }
12981
13005
  var RESTART_TASK_NAME = "DSH-MCviseron-Restart";
12982
13006
  var RESTART_DELAY_SECONDS = 6;
12983
13007
  function restartLogPath() {
@@ -12994,14 +13018,62 @@ function makeTaskScript(target, taskName, delaySeconds) {
12994
13018
  ""
12995
13019
  ].join("\n");
12996
13020
  }
13021
+ function writeRestartLog(message) {
13022
+ try {
13023
+ appendFileSync4(restartLogPath(), (/* @__PURE__ */ new Date()).toISOString() + " " + message + "\n", "utf8");
13024
+ } catch {
13025
+ }
13026
+ }
13027
+ var PROCESS_HELPER = [
13028
+ "const { spawn } = require('node:child_process')",
13029
+ "const [pidText, cwd, exe, ...args] = process.argv.slice(2)",
13030
+ "const pid = Number(pidText)",
13031
+ "const started = Date.now()",
13032
+ "const start = () => {",
13033
+ " try {",
13034
+ ' const child = spawn(exe, args, { cwd, detached: true, stdio: "ignore", env: process.env })',
13035
+ " child.unref()",
13036
+ " } catch { /* the supervisor or user will see the failure */ }",
13037
+ "}",
13038
+ "const timer = setInterval(() => {",
13039
+ " let alive = false",
13040
+ " try { process.kill(pid, 0); alive = true } catch { /* parent is gone */ }",
13041
+ " if (!alive || Date.now() - started > 30_000) { clearInterval(timer); start() }",
13042
+ "}, 100)",
13043
+ "timer.unref?.()"
13044
+ ].join("\n");
13045
+ function ensureProcessHelper() {
13046
+ const path = join5(tmpdir4(), "dsh-mcviseron-restart-helper.cjs");
13047
+ writeFileSync(path, PROCESS_HELPER, "utf8");
13048
+ return path;
13049
+ }
13050
+ function launchProcessRestart(target) {
13051
+ if (target.mode === "supervisor-exit") {
13052
+ writeRestartLog("host: supervised restart requested; exit 75");
13053
+ setTimeout(() => process.exit(75), 300);
13054
+ return;
13055
+ }
13056
+ try {
13057
+ const helper = ensureProcessHelper();
13058
+ const args = [helper, String(process.pid), target.cwd ?? process.cwd(), target.exePath, ...target.argv ?? []];
13059
+ const child = spawn(process.execPath, args, { detached: true, stdio: "ignore", env: { ...process.env, DSH_MCVISERON_RESTARTED: "1" } });
13060
+ child.unref();
13061
+ writeRestartLog("host: detached re-exec helper started");
13062
+ } catch (error) {
13063
+ writeRestartLog("host: re-exec helper failed: " + (error instanceof Error ? error.message : String(error)));
13064
+ throw new Error("cannot start the Linux restart helper", { cause: error });
13065
+ }
13066
+ setTimeout(() => process.exit(0), 300);
13067
+ }
12997
13068
  function launchRestart(target) {
12998
- launchHelper(target);
13069
+ if (restartMode(target) === "desktop") launchHelper(target);
13070
+ else launchProcessRestart(target);
12999
13071
  }
13000
13072
  function closeDesktop(target) {
13001
- const pid = target?.mainPid ?? process.ppid;
13073
+ const mainPid = target?.mainPid;
13002
13074
  setTimeout(() => {
13003
13075
  try {
13004
- if (target !== void 0 || process.platform === "win32") process.kill(pid);
13076
+ if (mainPid !== void 0 && target !== void 0 && restartMode(target) === "desktop") process.kill(mainPid);
13005
13077
  else process.exit(0);
13006
13078
  } catch {
13007
13079
  try {
@@ -13030,10 +13102,12 @@ function launchHelper(target) {
13030
13102
  `, "utf8");
13031
13103
  throw new Error("cannot schedule the restart task: " + message, { cause: error });
13032
13104
  }
13105
+ const mainPid = target.mainPid;
13106
+ if (mainPid === void 0) throw new Error("desktop restart target has no main PID");
13033
13107
  setTimeout(() => {
13034
13108
  try {
13035
- process.kill(target.mainPid);
13036
- appendFileSync4(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill sent to ${target.mainPid}
13109
+ process.kill(mainPid);
13110
+ appendFileSync4(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill sent to ${mainPid}
13037
13111
  `, "utf8");
13038
13112
  } catch (error) {
13039
13113
  appendFileSync4(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill failed: ${error instanceof Error ? error.message : String(error)}
@@ -13071,7 +13145,7 @@ function makeRestartRoutes(deps) {
13071
13145
  if (req.method !== "GET" && req.method !== "POST") return json3(res, 405, { ok: false, error: "method-not-allowed" });
13072
13146
  if (!isLoopbackRequest(req)) return json3(res, 403, { ok: false, error: "forbidden" });
13073
13147
  const target = deps.target();
13074
- json3(res, 200, target === void 0 ? { ok: true, available: false, reason: "desktop-app-unavailable" } : { ok: true, available: true, appPath: target.exePath, mainPid: target.mainPid });
13148
+ json3(res, 200, target === void 0 ? { ok: true, available: false, reason: "restart-target-unavailable" } : { ok: true, available: true, mode: restartMode(target), appPath: target.exePath, mainPid: target.mainPid ?? null });
13075
13149
  } catch (error) {
13076
13150
  json3(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
13077
13151
  }
@@ -13088,13 +13162,16 @@ function makeRestartRoutes(deps) {
13088
13162
  if (body === void 0 || typeof body !== "object" || body === null || body.confirm !== true) {
13089
13163
  return json3(res, 400, { ok: false, error: "confirmation-required" });
13090
13164
  }
13165
+ const action = body.action ?? "restart";
13166
+ if (action !== "restart" && action !== "close") return json3(res, 400, { ok: false, error: "action-invalid" });
13091
13167
  const latest = now();
13092
- if (latest - lastLaunch < 5e3) return json3(res, 429, { ok: false, error: "restart-already-scheduled" });
13168
+ if (action === "restart" && latest - lastLaunch < 5e3) return json3(res, 429, { ok: false, error: "restart-already-scheduled" });
13093
13169
  const target = deps.target();
13094
- if (target === void 0) return json3(res, 409, { ok: false, error: "desktop-app-unavailable" });
13095
- deps.launch(target);
13096
- lastLaunch = latest;
13097
- json3(res, 200, { ok: true, restarting: true, appPath: target.exePath });
13170
+ if (action === "restart" && target === void 0) return json3(res, 409, { ok: false, error: "restart-target-unavailable" });
13171
+ if (action === "restart") deps.launch(target);
13172
+ else (deps.close ?? closeDesktop)(target);
13173
+ if (action === "restart") lastLaunch = latest;
13174
+ json3(res, 200, { ok: true, action, restarting: action === "restart", closing: action === "close", mode: target === void 0 ? null : restartMode(target) });
13098
13175
  } catch (error) {
13099
13176
  json3(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
13100
13177
  }
@@ -13109,7 +13186,8 @@ function apply6(ctx, config) {
13109
13186
  const appPath = typeof plain.appPath === "string" ? plain.appPath : "";
13110
13187
  const routes = makeRestartRoutes({
13111
13188
  target: () => resolveRestartTarget(process.execPath, process.ppid, existsSync2, appPath, process.argv),
13112
- launch: launchHelper
13189
+ launch: launchRestart,
13190
+ close: closeDesktop
13113
13191
  });
13114
13192
  ctx.effect(() => {
13115
13193
  const disposers = routes.map((route) => ctx.webServer.register(route));
@@ -13355,12 +13433,12 @@ function createSessionEndController(deps = {}) {
13355
13433
  };
13356
13434
  const view = (sessionId) => {
13357
13435
  const entry = entries.get(sessionId);
13358
- let available = { restart: false, close: platform === "win32", shutdown: platform === "win32" };
13436
+ let available = { restart: false, close: true, shutdown: platform === "win32" };
13359
13437
  try {
13360
13438
  const target = resolveTarget();
13361
13439
  available = {
13362
13440
  restart: target !== void 0,
13363
- close: target !== void 0 || platform === "win32",
13441
+ close: true,
13364
13442
  shutdown: platform === "win32"
13365
13443
  };
13366
13444
  } catch {
package/lib/restart.js CHANGED
@@ -2,8 +2,8 @@ import { createRequire } from 'node:module';
2
2
  const require = createRequire(import.meta.url);
3
3
 
4
4
  // src/restart/index.ts
5
- import { execFileSync } from "node:child_process";
6
- import { appendFileSync, existsSync } from "node:fs";
5
+ import { execFileSync, spawn } from "node:child_process";
6
+ import { appendFileSync, existsSync, writeFileSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { basename, dirname, join, resolve } from "node:path";
9
9
  import z from "@deepseek-ai/schemastery";
@@ -74,7 +74,9 @@ var RESTART_API = {
74
74
  execute: "/api/dsh-mcviseron/restart/execute"
75
75
  };
76
76
  function resolveRestartTarget(execPath, parentPid, exists, override = "", argv = [], platform = process.platform) {
77
- if (platform !== "win32") return void 0;
77
+ if (platform !== "win32") {
78
+ return resolveProcessRestartTarget({ platform, execPath, argv: argv.slice(1), cwd: process.cwd() });
79
+ }
78
80
  if (!Number.isSafeInteger(parentPid) || parentPid <= 0) return void 0;
79
81
  const configured = typeof override === "string" ? override.trim() : "";
80
82
  const candidate = configured !== "" ? configured : deriveDesktopAppPath(execPath, argv, exists);
@@ -83,6 +85,23 @@ function resolveRestartTarget(execPath, parentPid, exists, override = "", argv =
83
85
  if (name === "node" || name === "node.exe") return void 0;
84
86
  return { mainPid: parentPid, hostPid: process.pid, exePath: candidate };
85
87
  }
88
+ function resolveProcessRestartTarget(options = {}) {
89
+ const platform = options.platform ?? process.platform;
90
+ if (platform === "win32") return void 0;
91
+ const argv = options.argv ?? process.argv.slice(1);
92
+ if (argv.length === 0 || argv[0] === "") return void 0;
93
+ const env = options.env ?? process.env;
94
+ const override = (env.DSH_MCVISERON_RESTART_MODE ?? "").trim().toLowerCase();
95
+ const supervised = override === "supervisor-exit" || override === "exit" || override !== "reexec" && (env.INVOCATION_ID !== void 0 || env.JOURNAL_STREAM !== void 0 || env.SYSTEMD_EXEC_PID !== void 0 || env.KUBERNETES_SERVICE_HOST !== void 0 || existsSync("/.dockerenv") || options.pid1 === true || (options.pid ?? process.pid) === 1);
96
+ const nodeArgs = options.execArgv ?? process.execArgv;
97
+ return {
98
+ hostPid: options.pid ?? process.pid,
99
+ exePath: options.execPath ?? process.execPath,
100
+ mode: supervised ? "supervisor-exit" : "reexec",
101
+ argv: [...nodeArgs, ...argv],
102
+ cwd: options.cwd ?? process.cwd()
103
+ };
104
+ }
86
105
  function deriveDesktopAppPath(execPath, argv, exists) {
87
106
  const isNode = (value) => /^node(\.exe)?$/i.test(basename(value));
88
107
  if (!isNode(execPath)) return execPath;
@@ -93,6 +112,9 @@ function deriveDesktopAppPath(execPath, argv, exists) {
93
112
  const candidate = join(resolve(runtimeDir, "../../.."), "DeepSeek Harness.exe");
94
113
  return exists(candidate) ? candidate : execPath;
95
114
  }
115
+ function restartMode(target) {
116
+ return target.mode ?? (target.mainPid !== void 0 ? "desktop" : "reexec");
117
+ }
96
118
  var RESTART_TASK_NAME = "DSH-MCviseron-Restart";
97
119
  var RESTART_DELAY_SECONDS = 6;
98
120
  function restartLogPath() {
@@ -109,14 +131,62 @@ function makeTaskScript(target, taskName, delaySeconds) {
109
131
  ""
110
132
  ].join("\n");
111
133
  }
134
+ function writeRestartLog(message) {
135
+ try {
136
+ appendFileSync(restartLogPath(), (/* @__PURE__ */ new Date()).toISOString() + " " + message + "\n", "utf8");
137
+ } catch {
138
+ }
139
+ }
140
+ var PROCESS_HELPER = [
141
+ "const { spawn } = require('node:child_process')",
142
+ "const [pidText, cwd, exe, ...args] = process.argv.slice(2)",
143
+ "const pid = Number(pidText)",
144
+ "const started = Date.now()",
145
+ "const start = () => {",
146
+ " try {",
147
+ ' const child = spawn(exe, args, { cwd, detached: true, stdio: "ignore", env: process.env })',
148
+ " child.unref()",
149
+ " } catch { /* the supervisor or user will see the failure */ }",
150
+ "}",
151
+ "const timer = setInterval(() => {",
152
+ " let alive = false",
153
+ " try { process.kill(pid, 0); alive = true } catch { /* parent is gone */ }",
154
+ " if (!alive || Date.now() - started > 30_000) { clearInterval(timer); start() }",
155
+ "}, 100)",
156
+ "timer.unref?.()"
157
+ ].join("\n");
158
+ function ensureProcessHelper() {
159
+ const path = join(tmpdir(), "dsh-mcviseron-restart-helper.cjs");
160
+ writeFileSync(path, PROCESS_HELPER, "utf8");
161
+ return path;
162
+ }
163
+ function launchProcessRestart(target) {
164
+ if (target.mode === "supervisor-exit") {
165
+ writeRestartLog("host: supervised restart requested; exit 75");
166
+ setTimeout(() => process.exit(75), 300);
167
+ return;
168
+ }
169
+ try {
170
+ const helper = ensureProcessHelper();
171
+ const args = [helper, String(process.pid), target.cwd ?? process.cwd(), target.exePath, ...target.argv ?? []];
172
+ const child = spawn(process.execPath, args, { detached: true, stdio: "ignore", env: { ...process.env, DSH_MCVISERON_RESTARTED: "1" } });
173
+ child.unref();
174
+ writeRestartLog("host: detached re-exec helper started");
175
+ } catch (error) {
176
+ writeRestartLog("host: re-exec helper failed: " + (error instanceof Error ? error.message : String(error)));
177
+ throw new Error("cannot start the Linux restart helper", { cause: error });
178
+ }
179
+ setTimeout(() => process.exit(0), 300);
180
+ }
112
181
  function launchRestart(target) {
113
- launchHelper(target);
182
+ if (restartMode(target) === "desktop") launchHelper(target);
183
+ else launchProcessRestart(target);
114
184
  }
115
185
  function closeDesktop(target) {
116
- const pid = target?.mainPid ?? process.ppid;
186
+ const mainPid = target?.mainPid;
117
187
  setTimeout(() => {
118
188
  try {
119
- if (target !== void 0 || process.platform === "win32") process.kill(pid);
189
+ if (mainPid !== void 0 && target !== void 0 && restartMode(target) === "desktop") process.kill(mainPid);
120
190
  else process.exit(0);
121
191
  } catch {
122
192
  try {
@@ -145,10 +215,12 @@ function launchHelper(target) {
145
215
  `, "utf8");
146
216
  throw new Error("cannot schedule the restart task: " + message, { cause: error });
147
217
  }
218
+ const mainPid = target.mainPid;
219
+ if (mainPid === void 0) throw new Error("desktop restart target has no main PID");
148
220
  setTimeout(() => {
149
221
  try {
150
- process.kill(target.mainPid);
151
- appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill sent to ${target.mainPid}
222
+ process.kill(mainPid);
223
+ appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill sent to ${mainPid}
152
224
  `, "utf8");
153
225
  } catch (error) {
154
226
  appendFileSync(logFile, `${(/* @__PURE__ */ new Date()).toISOString()} host: kill failed: ${error instanceof Error ? error.message : String(error)}
@@ -186,7 +258,7 @@ function makeRestartRoutes(deps) {
186
258
  if (req.method !== "GET" && req.method !== "POST") return json(res, 405, { ok: false, error: "method-not-allowed" });
187
259
  if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: "forbidden" });
188
260
  const target = deps.target();
189
- json(res, 200, target === void 0 ? { ok: true, available: false, reason: "desktop-app-unavailable" } : { ok: true, available: true, appPath: target.exePath, mainPid: target.mainPid });
261
+ json(res, 200, target === void 0 ? { ok: true, available: false, reason: "restart-target-unavailable" } : { ok: true, available: true, mode: restartMode(target), appPath: target.exePath, mainPid: target.mainPid ?? null });
190
262
  } catch (error) {
191
263
  json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
192
264
  }
@@ -203,13 +275,16 @@ function makeRestartRoutes(deps) {
203
275
  if (body === void 0 || typeof body !== "object" || body === null || body.confirm !== true) {
204
276
  return json(res, 400, { ok: false, error: "confirmation-required" });
205
277
  }
278
+ const action = body.action ?? "restart";
279
+ if (action !== "restart" && action !== "close") return json(res, 400, { ok: false, error: "action-invalid" });
206
280
  const latest = now();
207
- if (latest - lastLaunch < 5e3) return json(res, 429, { ok: false, error: "restart-already-scheduled" });
281
+ if (action === "restart" && latest - lastLaunch < 5e3) return json(res, 429, { ok: false, error: "restart-already-scheduled" });
208
282
  const target = deps.target();
209
- if (target === void 0) return json(res, 409, { ok: false, error: "desktop-app-unavailable" });
210
- deps.launch(target);
211
- lastLaunch = latest;
212
- json(res, 200, { ok: true, restarting: true, appPath: target.exePath });
283
+ if (action === "restart" && target === void 0) return json(res, 409, { ok: false, error: "restart-target-unavailable" });
284
+ if (action === "restart") deps.launch(target);
285
+ else (deps.close ?? closeDesktop)(target);
286
+ if (action === "restart") lastLaunch = latest;
287
+ json(res, 200, { ok: true, action, restarting: action === "restart", closing: action === "close", mode: target === void 0 ? null : restartMode(target) });
213
288
  } catch (error) {
214
289
  json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
215
290
  }
@@ -224,7 +299,8 @@ function apply(ctx, config) {
224
299
  const appPath = typeof plain.appPath === "string" ? plain.appPath : "";
225
300
  const routes = makeRestartRoutes({
226
301
  target: () => resolveRestartTarget(process.execPath, process.ppid, existsSync, appPath, process.argv),
227
- launch: launchHelper
302
+ launch: launchRestart,
303
+ close: closeDesktop
228
304
  });
229
305
  ctx.effect(() => {
230
306
  const disposers = routes.map((route) => ctx.webServer.register(route));
@@ -244,5 +320,7 @@ export {
244
320
  launchRestart,
245
321
  makeRestartRoutes,
246
322
  makeTaskScript,
247
- resolveRestartTarget
323
+ resolveProcessRestartTarget,
324
+ resolveRestartTarget,
325
+ restartMode
248
326
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mcviseron-plugin",
3
- "version": "0.7.8",
3
+ "version": "0.8.1",
4
4
  "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing, one-shot after-session restart/close actions with task-aware waiting, and automatic auth-cookie hygiene for repeated desktop restarts, and model-editable official automation tasks.",
5
5
  "license": "Apache-2.0",
6
6
  "author": {
@@ -7,10 +7,11 @@ const EXECUTE = '/api/dsh-mcviseron/restart/execute'
7
7
 
8
8
  type RestartState =
9
9
  | { kind: 'loading' }
10
- | { kind: 'ready'; appPath: string }
10
+ | { kind: 'ready'; appPath: string; mode: string }
11
11
  | { kind: 'unavailable' }
12
12
  | { kind: 'route-missing' }
13
13
  | { kind: 'restarting' }
14
+ | { kind: 'closing' }
14
15
  | { kind: 'failed'; message: string }
15
16
 
16
17
  async function readError(response: Response): Promise<string> {
@@ -38,10 +39,10 @@ export function RestartCard({ t }: { t: (key: McviseronKey) => string }) {
38
39
  return
39
40
  }
40
41
  if (!response.ok) throw new Error(await readError(response))
41
- const body = await response.json() as { ok?: unknown; available?: unknown; appPath?: unknown }
42
+ const body = await response.json() as { ok?: unknown; available?: unknown; appPath?: unknown; mode?: unknown }
42
43
  if (body.ok !== true) throw new Error('restart-status-rejected')
43
44
  if (body.available === true) {
44
- setState({ kind: 'ready', appPath: typeof body.appPath === 'string' ? body.appPath : '' })
45
+ setState({ kind: 'ready', appPath: typeof body.appPath === 'string' ? body.appPath : '', mode: typeof body.mode === 'string' ? body.mode : 'desktop' })
45
46
  } else {
46
47
  setState({ kind: 'unavailable' })
47
48
  }
@@ -71,9 +72,32 @@ export function RestartCard({ t }: { t: (key: McviseronKey) => string }) {
71
72
  }
72
73
  }
73
74
 
75
+ const startClose = async (): Promise<void> => {
76
+ if (!window.confirm(t('page.restart.closeConfirm'))) return
77
+ setState({ kind: 'closing' })
78
+ try {
79
+ const response = await fetch(EXECUTE, {
80
+ method: 'POST',
81
+ headers: { 'content-type': 'application/json' },
82
+ body: JSON.stringify({ confirm: true, action: 'close' }),
83
+ })
84
+ if (!response.ok) throw new Error(await readError(response))
85
+ const body = await response.json() as { ok?: unknown }
86
+ if (body.ok !== true) throw new Error('close-rejected')
87
+ } catch (error) {
88
+ setState({ kind: 'failed', message: error instanceof Error ? error.message : String(error) })
89
+ }
90
+ }
91
+
74
92
  const status = state.kind === 'ready'
75
- ? t('page.restart.ready')
76
- : state.kind === 'route-missing'
93
+ ? state.mode === 'reexec'
94
+ ? t('page.restart.modeProcess')
95
+ : state.mode === 'supervisor-exit'
96
+ ? t('page.restart.modeSupervisor')
97
+ : t('page.restart.ready')
98
+ : state.kind === 'closing'
99
+ ? t('page.restart.closing')
100
+ : state.kind === 'route-missing'
77
101
  ? t('page.restart.routeMissing')
78
102
  : state.kind === 'restarting'
79
103
  ? t('page.restart.restarting')
@@ -84,6 +108,7 @@ export function RestartCard({ t }: { t: (key: McviseronKey) => string }) {
84
108
  : t('page.restart.unavailable')
85
109
 
86
110
  const canRestart = state.kind === 'ready' || state.kind === 'failed'
111
+ const canClose = state.kind === 'ready'
87
112
 
88
113
  return (
89
114
  <div style={pageStyles.card}>
@@ -102,6 +127,14 @@ export function RestartCard({ t }: { t: (key: McviseronKey) => string }) {
102
127
  >
103
128
  {state.kind === 'restarting' ? t('page.restart.restarting') : t('page.restart.button')}
104
129
  </button>
130
+ <button
131
+ type="button"
132
+ disabled={!canClose}
133
+ onClick={() => { void startClose() }}
134
+ style={canClose ? styles.button : styles.buttonDisabled}
135
+ >
136
+ {state.kind === 'closing' ? t('page.restart.closing') : t('page.restart.close')}
137
+ </button>
105
138
  </div>
106
139
  </div>
107
140
  )
@@ -38,12 +38,17 @@ export const zh = {
38
38
 
39
39
  'page.title': 'MCviseron 插件',
40
40
  'page.description': '总插件的组件设置。外观设置仍在「通用 → 外观」中。',
41
- 'page.tab.restart': '重启',
41
+ 'page.tab.restart': '重启 / 关闭',
42
42
  'page.tab.components': '组件',
43
- 'page.restart.title': '重启 DeepSeek Harness',
44
- 'page.restart.description': '关闭并重新启动桌面应用;正在运行的任务会被中断',
43
+ 'page.restart.title': '重启 / 关闭 DeepSeek Harness',
44
+ 'page.restart.description': '重启或关闭当前 DSH(桌面应用、Linux/Web 进程或云托管容器);正在运行的任务会被中断',
45
45
  'page.restart.ready': '可用',
46
- 'page.restart.unavailable': '当前环境不支持重启(仅 Windows 桌面版可用)',
46
+ 'page.restart.modeProcess': 'Linux/Web 进程:将重新拉起当前 dsh 命令',
47
+ 'page.restart.modeSupervisor': '由 systemd / Docker / Kubernetes 托管:退出后由托管器重启',
48
+ 'page.restart.close': '关闭 DSH',
49
+ 'page.restart.closing': '正在关闭…',
50
+ 'page.restart.closeConfirm': '确定要关闭 DSH 吗?重启/关闭动作会中断正在运行的任务。',
51
+ 'page.restart.unavailable': '当前环境没有可用的重启目标',
47
52
  'page.restart.routeMissing': '重启接口未加载:请确认 mcviseron-restart 条目已启用',
48
53
  'page.restart.appPath': '应用路径',
49
54
  'page.restart.button': '重启',
@@ -57,8 +62,8 @@ export const zh = {
57
62
  'page.components.autoReviewFixHint': '本页「Auto review 修复」子页',
58
63
  'page.components.taskGuard': 'Todo 计划守卫',
59
64
  'page.components.taskGuardHint': '本页「Todo 守卫」子页',
60
- 'page.components.restart': '重启 DeepSeek Harness',
61
- 'page.components.restartHint': '本页「重启」子页',
65
+ 'page.components.restart': '重启 / 关闭 DSH',
66
+ 'page.components.restartHint': '本页「重启 / 关闭」子页',
62
67
  'page.components.note': '组件配置写入 master 条目(mcviseron)的 Config;若组件仍使用旧值,重启 DSH 后生效。',
63
68
  'page.fallback.note': '设置分区未加载,重启入口暂时回退到通用设置。',
64
69
  'page.tab.autoReview': 'Auto review 修复',
@@ -183,12 +188,17 @@ export const en = {
183
188
 
184
189
  'page.title': 'MCviseron plugin',
185
190
  'page.description': 'Settings for the master plugin components. Appearance still lives under General → Appearance.',
186
- 'page.tab.restart': 'Restart',
191
+ 'page.tab.restart': 'Restart / close',
187
192
  'page.tab.components': 'Components',
188
- 'page.restart.title': 'Restart DeepSeek Harness',
189
- 'page.restart.description': 'Closes and relaunches the desktop application; running tasks are interrupted',
193
+ 'page.restart.title': 'Restart / close DeepSeek Harness',
194
+ 'page.restart.description': 'Restart or close DSH (desktop app, Linux/Web process, or cloud container); running tasks are interrupted',
190
195
  'page.restart.ready': 'Available',
191
- 'page.restart.unavailable': 'Restarting is available only in the Windows desktop app',
196
+ 'page.restart.modeProcess': 'Linux/Web process: relaunch the current dsh command',
197
+ 'page.restart.modeSupervisor': 'Managed by systemd / Docker / Kubernetes: exit and let the supervisor restart it',
198
+ 'page.restart.close': 'Close DSH',
199
+ 'page.restart.closing': 'Closing…',
200
+ 'page.restart.closeConfirm': 'Close DSH? Restart/close interrupts running tasks.',
201
+ 'page.restart.unavailable': 'No restart target is available in this environment',
192
202
  'page.restart.routeMissing': 'The restart route is not loaded: check that the mcviseron-restart entry is enabled',
193
203
  'page.restart.appPath': 'App path',
194
204
  'page.restart.button': 'Restart',
@@ -202,8 +212,8 @@ export const en = {
202
212
  'page.components.autoReviewFixHint': 'The Auto-review fix tab on this page',
203
213
  'page.components.taskGuard': 'Todo plan guard',
204
214
  'page.components.taskGuardHint': 'The Todo guard tab on this page',
205
- 'page.components.restart': 'Restart DeepSeek Harness',
206
- 'page.components.restartHint': 'The Restart tab on this page',
215
+ 'page.components.restart': 'Restart / close DSH',
216
+ 'page.components.restartHint': 'The Restart / close tab on this page',
207
217
  'page.components.note': 'Component settings are written to the mcviseron entry config; restart DSH if a component still uses the old value.',
208
218
  'page.fallback.note': 'The settings section is unavailable, so the restart entry falls back to General.',
209
219
  'page.tab.autoReview': 'Auto-review fix',
@@ -1,5 +1,5 @@
1
- import { execFileSync } from 'node:child_process'
2
- import { appendFileSync, existsSync } from 'node:fs'
1
+ import { execFileSync, spawn } from 'node:child_process'
2
+ import { appendFileSync, existsSync, writeFileSync } from 'node:fs'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { basename, dirname, join, resolve } from 'node:path'
5
5
  import type { Context } from '@deepseek-ai/cordis'
@@ -33,11 +33,17 @@ export interface RestartConfig {
33
33
  appPath?: string
34
34
  }
35
35
 
36
- /** The desktop executable and the two PIDs the helper must wait for. */
36
+ /** How the Host process is restarted. */
37
+ export type RestartMode = 'desktop' | 'reexec' | 'supervisor-exit'
38
+
39
+ /** A desktop app target or a Linux/Web process target. */
37
40
  export interface RestartTarget {
38
- mainPid: number
41
+ mainPid?: number
39
42
  hostPid: number
40
43
  exePath: string
44
+ mode?: RestartMode
45
+ argv?: readonly string[]
46
+ cwd?: string
41
47
  }
42
48
 
43
49
  /** Loopback endpoints owned by the restart component. */
@@ -69,7 +75,9 @@ export function resolveRestartTarget(
69
75
  argv: readonly string[] = [],
70
76
  platform: NodeJS.Platform = process.platform,
71
77
  ): RestartTarget | undefined {
72
- if (platform !== 'win32') return undefined
78
+ if (platform !== 'win32') {
79
+ return resolveProcessRestartTarget({ platform, execPath, argv: argv.slice(1), cwd: process.cwd() })
80
+ }
73
81
  if (!Number.isSafeInteger(parentPid) || parentPid <= 0) return undefined
74
82
  const configured = typeof override === 'string' ? override.trim() : ''
75
83
  const candidate = configured !== '' ? configured : deriveDesktopAppPath(execPath, argv, exists)
@@ -79,6 +87,52 @@ export function resolveRestartTarget(
79
87
  return { mainPid: parentPid, hostPid: process.pid, exePath: candidate }
80
88
  }
81
89
 
90
+ /** Options for a Linux/macOS/Web process restart target. */
91
+ export interface ProcessRestartOptions {
92
+ platform?: NodeJS.Platform
93
+ execPath?: string
94
+ argv?: readonly string[]
95
+ execArgv?: readonly string[]
96
+ cwd?: string
97
+ pid?: number
98
+ env?: NodeJS.ProcessEnv
99
+ pid1?: boolean
100
+ }
101
+
102
+ /**
103
+ * Resolve the restart target for a Linux/macOS/Web Host.
104
+ *
105
+ * A supervised host (systemd, Docker, Kubernetes, or PID 1) exits and lets its
106
+ * supervisor restart it. A plain CLI process gets a detached helper that waits
107
+ * for the old PID to disappear before starting the same command.
108
+ */
109
+ export function resolveProcessRestartTarget(options: ProcessRestartOptions = {}): RestartTarget | undefined {
110
+ const platform = options.platform ?? process.platform
111
+ if (platform === 'win32') return undefined
112
+ const argv = options.argv ?? process.argv.slice(1)
113
+ if (argv.length === 0 || argv[0] === '') return undefined
114
+ const env = options.env ?? process.env
115
+ const override = (env.DSH_MCVISERON_RESTART_MODE ?? '').trim().toLowerCase()
116
+ const supervised = override === 'supervisor-exit' || override === 'exit'
117
+ || (override !== 'reexec' && (
118
+ env.INVOCATION_ID !== undefined
119
+ || env.JOURNAL_STREAM !== undefined
120
+ || env.SYSTEMD_EXEC_PID !== undefined
121
+ || env.KUBERNETES_SERVICE_HOST !== undefined
122
+ || existsSync('/.dockerenv')
123
+ || options.pid1 === true
124
+ || (options.pid ?? process.pid) === 1
125
+ ))
126
+ const nodeArgs = (options.execArgv ?? process.execArgv) as readonly string[]
127
+ return {
128
+ hostPid: options.pid ?? process.pid,
129
+ exePath: options.execPath ?? process.execPath,
130
+ mode: supervised ? 'supervisor-exit' : 'reexec',
131
+ argv: [...nodeArgs, ...argv],
132
+ cwd: options.cwd ?? process.cwd(),
133
+ }
134
+ }
135
+
82
136
  /**
83
137
  * Derive the desktop application executable when the Host itself runs under a
84
138
  * plain node.exe: first `argv[0]`, then the application root recovered from the
@@ -104,6 +158,11 @@ export function deriveDesktopAppPath(
104
158
  return exists(candidate) ? candidate : execPath
105
159
  }
106
160
 
161
+ /** Return the effective action mode for a target. */
162
+ export function restartMode(target: RestartTarget): RestartMode {
163
+ return target.mode ?? (target.mainPid !== undefined ? 'desktop' : 'reexec')
164
+ }
165
+
107
166
  /** One-time task that starts the desktop application directly. */
108
167
  const RESTART_TASK_NAME = 'DSH-MCviseron-Restart'
109
168
  const RESTART_DELAY_SECONDS = 6
@@ -135,31 +194,74 @@ export function makeTaskScript(target: RestartTarget, taskName: string, delaySec
135
194
  ].join('\n')
136
195
  }
137
196
 
197
+ function writeRestartLog(message: string): void {
198
+ try {
199
+ appendFileSync(restartLogPath(), new Date().toISOString() + ' ' + message + '\n', 'utf8')
200
+ } catch { /* diagnostics must never break the action */ }
201
+ }
202
+
203
+ const PROCESS_HELPER = [
204
+ "const { spawn } = require('node:child_process')",
205
+ 'const [pidText, cwd, exe, ...args] = process.argv.slice(2)',
206
+ 'const pid = Number(pidText)',
207
+ 'const started = Date.now()',
208
+ 'const start = () => {',
209
+ ' try {',
210
+ ' const child = spawn(exe, args, { cwd, detached: true, stdio: "ignore", env: process.env })',
211
+ ' child.unref()',
212
+ ' } catch { /* the supervisor or user will see the failure */ }',
213
+ '}',
214
+ 'const timer = setInterval(() => {',
215
+ ' let alive = false',
216
+ ' try { process.kill(pid, 0); alive = true } catch { /* parent is gone */ }',
217
+ ' if (!alive || Date.now() - started > 30_000) { clearInterval(timer); start() }',
218
+ '}, 100)',
219
+ 'timer.unref?.()',
220
+ ].join('\n')
221
+
222
+ function ensureProcessHelper(): string {
223
+ const path = join(tmpdir(), 'dsh-mcviseron-restart-helper.cjs')
224
+ writeFileSync(path, PROCESS_HELPER, 'utf8')
225
+ return path
226
+ }
227
+
228
+ function launchProcessRestart(target: RestartTarget): void {
229
+ if (target.mode === 'supervisor-exit') {
230
+ writeRestartLog('host: supervised restart requested; exit 75')
231
+ setTimeout(() => process.exit(75), 300)
232
+ return
233
+ }
234
+ try {
235
+ const helper = ensureProcessHelper()
236
+ const args = [helper, String(process.pid), target.cwd ?? process.cwd(), target.exePath, ...(target.argv ?? [])]
237
+ const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore', env: { ...process.env, DSH_MCVISERON_RESTARTED: '1' } })
238
+ child.unref()
239
+ writeRestartLog('host: detached re-exec helper started')
240
+ } catch (error) {
241
+ writeRestartLog('host: re-exec helper failed: ' + (error instanceof Error ? error.message : String(error)))
242
+ throw new Error('cannot start the Linux restart helper', { cause: error })
243
+ }
244
+ setTimeout(() => process.exit(0), 300)
245
+ }
246
+
138
247
  /**
139
- * Schedule the desktop app to start again, then close its Electron main process.
140
- * Exported for the session-end action; the settings route keeps its own throttle.
141
- * @param target - resolved desktop executable and PIDs.
248
+ * Schedule the desktop app or Linux/Web process to start again.
249
+ * @param target - resolved desktop or process target.
142
250
  */
143
251
  export function launchRestart(target: RestartTarget): void {
144
- launchHelper(target)
252
+ if (restartMode(target) === 'desktop') launchHelper(target)
253
+ else launchProcessRestart(target)
145
254
  }
146
255
 
147
- /**
148
- * Close the desktop app without relaunching it.
149
- * @param target - resolved desktop target, when available.
150
- */
256
+ /** Close the desktop app or Host process without relaunching it. */
151
257
  export function closeDesktop(target?: RestartTarget): void {
152
- const pid = target?.mainPid ?? process.ppid
258
+ const mainPid = target?.mainPid
153
259
  setTimeout(() => {
154
260
  try {
155
- if (target !== undefined || process.platform === 'win32') process.kill(pid)
261
+ if (mainPid !== undefined && target !== undefined && restartMode(target) === 'desktop') process.kill(mainPid)
156
262
  else process.exit(0)
157
263
  } catch {
158
- try {
159
- process.exit(0)
160
- } catch {
161
- /* the host is already gone */
162
- }
264
+ try { process.exit(0) } catch { /* the host is already gone */ }
163
265
  }
164
266
  }, 300)
165
267
  }
@@ -182,10 +284,12 @@ function launchHelper(target: RestartTarget): void {
182
284
  appendFileSync(logFile, `${new Date().toISOString()} host: task registration failed: ${message}\n`, 'utf8')
183
285
  throw new Error('cannot schedule the restart task: ' + message, { cause: error })
184
286
  }
287
+ const mainPid = target.mainPid
288
+ if (mainPid === undefined) throw new Error('desktop restart target has no main PID')
185
289
  setTimeout(() => {
186
290
  try {
187
- process.kill(target.mainPid)
188
- appendFileSync(logFile, `${new Date().toISOString()} host: kill sent to ${target.mainPid}\n`, 'utf8')
291
+ process.kill(mainPid)
292
+ appendFileSync(logFile, `${new Date().toISOString()} host: kill sent to ${mainPid}\n`, 'utf8')
189
293
  } catch (error) {
190
294
  appendFileSync(logFile, `${new Date().toISOString()} host: kill failed: ${error instanceof Error ? error.message : String(error)}\n`, 'utf8')
191
295
  }
@@ -217,6 +321,7 @@ async function readJsonBody(req: Parameters<WebRoute['handler']>[0]): Promise<un
217
321
  export interface RestartRouteDeps {
218
322
  target: () => RestartTarget | undefined
219
323
  launch: (target: RestartTarget) => void
324
+ close?: (target?: RestartTarget) => void
220
325
  now?: () => number
221
326
  }
222
327
 
@@ -238,8 +343,8 @@ export function makeRestartRoutes(deps: RestartRouteDeps): WebRoute[] {
238
343
  if (!isLoopbackRequest(req)) return json(res, 403, { ok: false, error: 'forbidden' })
239
344
  const target = deps.target()
240
345
  json(res, 200, target === undefined
241
- ? { ok: true, available: false, reason: 'desktop-app-unavailable' }
242
- : { ok: true, available: true, appPath: target.exePath, mainPid: target.mainPid })
346
+ ? { ok: true, available: false, reason: 'restart-target-unavailable' }
347
+ : { ok: true, available: true, mode: restartMode(target), appPath: target.exePath, mainPid: target.mainPid ?? null })
243
348
  } catch (error) {
244
349
  json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
245
350
  }
@@ -257,13 +362,16 @@ export function makeRestartRoutes(deps: RestartRouteDeps): WebRoute[] {
257
362
  if (body === undefined || typeof body !== 'object' || body === null || (body as { confirm?: unknown }).confirm !== true) {
258
363
  return json(res, 400, { ok: false, error: 'confirmation-required' })
259
364
  }
365
+ const action = (body as { action?: unknown }).action ?? 'restart'
366
+ if (action !== 'restart' && action !== 'close') return json(res, 400, { ok: false, error: 'action-invalid' })
260
367
  const latest = now()
261
- if (latest - lastLaunch < 5000) return json(res, 429, { ok: false, error: 'restart-already-scheduled' })
368
+ if (action === 'restart' && latest - lastLaunch < 5000) return json(res, 429, { ok: false, error: 'restart-already-scheduled' })
262
369
  const target = deps.target()
263
- if (target === undefined) return json(res, 409, { ok: false, error: 'desktop-app-unavailable' })
264
- deps.launch(target)
265
- lastLaunch = latest
266
- json(res, 200, { ok: true, restarting: true, appPath: target.exePath })
370
+ if (action === 'restart' && target === undefined) return json(res, 409, { ok: false, error: 'restart-target-unavailable' })
371
+ if (action === 'restart') deps.launch(target!)
372
+ else (deps.close ?? closeDesktop)(target)
373
+ if (action === 'restart') lastLaunch = latest
374
+ json(res, 200, { ok: true, action, restarting: action === 'restart', closing: action === 'close', mode: target === undefined ? null : restartMode(target) })
267
375
  } catch (error) {
268
376
  json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
269
377
  }
@@ -286,7 +394,8 @@ export function apply(ctx: Context, config?: RestartConfig): void {
286
394
  const appPath = typeof plain.appPath === 'string' ? plain.appPath : ''
287
395
  const routes = makeRestartRoutes({
288
396
  target: () => resolveRestartTarget(process.execPath, process.ppid, existsSync, appPath, process.argv),
289
- launch: launchHelper,
397
+ launch: launchRestart,
398
+ close: closeDesktop,
290
399
  })
291
400
  ctx.effect(() => {
292
401
  const disposers = routes.map(route => ctx.webServer.register(route))
@@ -234,12 +234,12 @@ export function createSessionEndController(deps: SessionEndDeps = {}): SessionEn
234
234
 
235
235
  const view = (sessionId: string): SessionEndView => {
236
236
  const entry = entries.get(sessionId)
237
- let available = { restart: false, close: platform === 'win32', shutdown: platform === 'win32' }
237
+ let available = { restart: false, close: true, shutdown: platform === 'win32' }
238
238
  try {
239
239
  const target = resolveTarget()
240
240
  available = {
241
241
  restart: target !== undefined,
242
- close: target !== undefined || platform === 'win32',
242
+ close: true,
243
243
  shutdown: platform === 'win32',
244
244
  }
245
245
  } catch {