dsh-mcviseron-plugin 0.7.3 → 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.
@@ -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 {