@moonsand/dsh-ui-optimize 0.0.0-stage → 0.8.4

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.
@@ -0,0 +1,808 @@
1
+ /**
2
+ * Restart endpoint for the DeepSeek Harness desktop application.
3
+ *
4
+ * The renderer exposes no restart channel: `app.relaunch()` lives in the Electron main
5
+ * process, and the production shell wires it only to crash recovery. The Host, however,
6
+ * runs as the application binary itself in Electron's Node mode, so it can end every
7
+ * process of this executable and start it again from the same path.
8
+ *
9
+ * Three platform facts shape the implementation, all measured on this machine:
10
+ *
11
+ * 1. A detached `powershell.exe` starts but never runs its `-EncodedCommand` script, so
12
+ * the helper is spawned as a plain child.
13
+ * 2. Every process the Host starts inherits Chromium's job object, whose kill-on-close
14
+ * flag ends the helper the moment the application's main process dies. A helper that
15
+ * kills first and starts afterwards therefore dies between those two steps.
16
+ * 3. The Scheduled Task service and the shell resolve launches in their own processes,
17
+ * outside that job, which is the only way to leave something behind that outlives
18
+ * the kill.
19
+ *
20
+ * So the order is inverted: the helper first arms a *watchdog* through the Task
21
+ * Scheduler, falls back to the shell (`explorer.exe` running a script-host watchdog),
22
+ * and only kills the application once the watchdog has proven it is alive by touching a
23
+ * marker file. Without that proof it refuses to kill anything. The watchdog waits for the
24
+ * application to disappear and starts it again, so the timing of the kill does not matter.
25
+ *
26
+ * Every step is appended to a temporary log, which is the only evidence available after
27
+ * such a restart.
28
+ *
29
+ * @module @moonsand/dsh-desktop-restart
30
+ */
31
+ import { spawn } from 'node:child_process'
32
+ import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
33
+ import { tmpdir } from 'node:os'
34
+ import { join } from 'node:path'
35
+
36
+ export const name = 'desktop-restart'
37
+
38
+ /** The web carrier is the only Host service this plugin needs. */
39
+ export const inject = ['webServer']
40
+
41
+ /** Route prefix owned by this plugin; the page calls `POST <prefix>/restart`.
42
+ * Deliberately not `/desktop-restart`: that path belongs to the standalone
43
+ * `@moonsand/dsh-desktop-restart`, and two registrations of one path throw. */
44
+ const PREFIX = '/ui-optimize/desktop'
45
+
46
+ /** The one path that performs a restart. */
47
+ const RESTART_PATH = `${PREFIX}/restart`
48
+
49
+ /** Read-only path the button polls before arming, so it can warn about running tasks. */
50
+ const STATUS_PATH = `${PREFIX}/status`
51
+
52
+ /** Arming self-test: arms a watchdog without killing anything, and reports the outcome. */
53
+ const DIAGNOSE_PATH = `${PREFIX}/diagnose`
54
+
55
+ /** Milliseconds the helper waits before arming, so the reply can flush. */
56
+ const RESTART_LEAD_MS = 300
57
+
58
+ /** How long the helper waits for the armed watchdog to prove it started. */
59
+ const ARM_POLLS = 25
60
+
61
+ /** After this long an unfinished restart no longer blocks a new attempt. */
62
+ const RETRY_WINDOW_MS = 45_000
63
+
64
+ /**
65
+ * How recently a profile manifest must have changed to look like an install that
66
+ * *just finished*.
67
+ *
68
+ * Deliberately short: an install that completed more than this many seconds ago is
69
+ * over, and refusing a restart for longer only gets in the way. The "still running"
70
+ * case does not rely on this window — the plugin manager's install-state reports and
71
+ * the process probe cover it — so there is no reason to be generous here.
72
+ */
73
+ const INSTALL_WINDOW_MS = 10_000
74
+
75
+ /**
76
+ * How long a reported install phase stays believable without a follow-up.
77
+ *
78
+ * The plugin manager announces `installing`, `cancelling` and `applying`, but it
79
+ * never announces completion, so a phase that is never superseded has to expire
80
+ * on its own.
81
+ *
82
+ * The two limits differ by two orders of magnitude on purpose. `installing` covers
83
+ * the download, which can legitimately take minutes, so a long limit only risks
84
+ * refusing a restart that a little patience would allow. `applying` is the last,
85
+ * short stage — once it is over the install is done, and holding the guard for
86
+ * minutes afterwards would block every restart right after a successful install.
87
+ */
88
+ const INSTALL_PHASE_STALE_MS = 10 * 60_000
89
+ const APPLYING_STALE_MS = 15_000
90
+
91
+ /**
92
+ * How long the phase reported last still counts, given which phase it is.
93
+ *
94
+ * @returns Milliseconds the reported phase stays believable.
95
+ */
96
+ function phaseStaleMs() {
97
+ return installPhase === 'applying' ? APPLYING_STALE_MS : INSTALL_PHASE_STALE_MS
98
+ }
99
+
100
+ /** Last install phase the plugin manager reported, and when it reported it. */
101
+ let installPhase = ''
102
+ let installPhaseSince = 0
103
+
104
+ /**
105
+ * Record an install phase announced by the plugin manager.
106
+ *
107
+ * Exported so a test can drive the decision without a live plugin manager.
108
+ *
109
+ * @param phase - `installing`, `cancelling`, `applying`, or empty to clear.
110
+ */
111
+ export function noteInstallPhase(phase) {
112
+ installPhase = typeof phase === 'string' ? phase : ''
113
+ installPhaseSince = Date.now()
114
+ }
115
+
116
+ /** Scheduled-task name used to escape the application's job object; deleted after the run. */
117
+ const TASK_NAME = 'DSH-Desktop-Restart-Watchdog'
118
+
119
+ /** Directory holding the log and the watchdog scripts. */
120
+ const HELPER_DIR = tmpdir()
121
+
122
+ /** Where the helper and the watchdog record what they did. */
123
+ const HELPER_LOG_PATH = join(HELPER_DIR, 'dsh-desktop-restart.log')
124
+
125
+ /** Watchdog script armed through the Task Scheduler. */
126
+ const WATCHDOG_PS1_PATH = join(HELPER_DIR, 'dsh-desktop-restart-watchdog.ps1')
127
+
128
+ /** Console-free launcher: the script host starts the watchdog with window style 0. */
129
+ const WATCHDOG_LAUNCHER_PATH = join(HELPER_DIR, 'dsh-desktop-restart-launch.vbs')
130
+
131
+ /** Touched by a watchdog as its first act; the helper kills nothing without it. */
132
+ const WATCHDOG_MARKER_PATH = join(HELPER_DIR, 'dsh-desktop-restart-watchdog.armed')
133
+
134
+ /** Written by a probe helper with which mechanism armed a watchdog, for diagnosis. */
135
+ const ARM_STATUS_PATH = join(HELPER_DIR, 'dsh-desktop-restart-armed.json')
136
+
137
+ /** Start time of the attempt in progress; 0 when nothing is in flight. */
138
+ let restartingSince = 0
139
+
140
+ /**
141
+ * Whether an attempt is recent enough to still count as in flight.
142
+ *
143
+ * A handler that crashed midway can never clear the marker, so the marker expires
144
+ * instead of blocking every later click.
145
+ *
146
+ * @returns true while a restart started less than the retry window ago.
147
+ */
148
+ function restartInFlight() {
149
+ return restartingSince !== 0 && Date.now() - restartingSince < RETRY_WINDOW_MS
150
+ }
151
+
152
+ /**
153
+ * Best-effort check for a package manager writing this profile right now.
154
+ *
155
+ * Killing the application mid-install can leave a half-written node_modules, so
156
+ * a restart is refused while an install is in flight. Three independent signals
157
+ * cover three different windows, and none of them alone is enough:
158
+ *
159
+ * 1. The plugin manager's own `plugin-manager/install-state` reports (`installing`,
160
+ * `cancelling`, `applying`). This is the only signal that sees an install while
161
+ * it is running, and it is authoritative — but it never reports completion, so
162
+ * a stale phase has to expire.
163
+ * 2. A freshly written manifest catches the moment an install *finishes*, because
164
+ * a package manager writes the lockfile last.
165
+ * 3. A live package-manager process is the fallback for when neither the event nor
166
+ * the lockfile is available (older host, or a plain `pnpm add` by hand).
167
+ *
168
+ * The profile location is not something a plugin is told about, so this stays
169
+ * deliberately fail-open: nothing visible plus no report means "not busy" rather
170
+ * than "block every restart".
171
+ *
172
+ * @param processCheck - Package-manager probe; injectable so tests stay hermetic.
173
+ * @returns true when an install looks in flight.
174
+ */
175
+ export async function installInProgress(processCheck = packageManagerRunning) {
176
+ if (installPhase !== '' && Date.now() - installPhaseSince < phaseStaleMs()) return true
177
+ const cwd = process.cwd()
178
+ const profile = process.env.DSH_PROFILE_DIR ?? (existsSync(join(cwd, 'pnpm-lock.yaml')) ? cwd : undefined)
179
+ if (profile !== undefined) {
180
+ const now = Date.now()
181
+ for (const manifest of [join(profile, 'pnpm-lock.yaml'), join(profile, 'node_modules', '.modules.yaml')]) {
182
+ try {
183
+ if (now - statSync(manifest).mtimeMs < INSTALL_WINDOW_MS) return true
184
+ } catch {
185
+ // A missing manifest simply does not vote.
186
+ }
187
+ }
188
+ }
189
+ return processCheck()
190
+ }
191
+
192
+ /**
193
+ * The desktop application's executable, or `undefined` on any other Host.
194
+ *
195
+ * Electron's Node mode sets `ELECTRON_RUN_AS_NODE` for the Host child it spawns from
196
+ * the application binary, so both markers together identify a desktop-managed Host.
197
+ *
198
+ * @returns Absolute executable path, or undefined when this is not the desktop shell.
199
+ */
200
+ function desktopExecutable() {
201
+ if (process.env.ELECTRON_RUN_AS_NODE !== '1') return undefined
202
+ if (typeof process.versions.electron !== 'string') return undefined
203
+ const executable = process.execPath
204
+ if (typeof executable !== 'string' || executable === '') return undefined
205
+ return executable
206
+ }
207
+
208
+ /**
209
+ * Count the Agent turns this restart would interrupt.
210
+ *
211
+ * @param ctx - Host context owning the composed services.
212
+ * @returns Number of running or queued Agents, or 0 when those services are absent.
213
+ */
214
+ function activeAgentCount(ctx) {
215
+ let count = 0
216
+ try {
217
+ const agents = ctx.get('agents')
218
+ for (const agent of agents?.list?.() ?? []) {
219
+ const queued = (agent.inbox?.nextTurn?.length ?? 0) + (agent.inbox?.nextStep?.length ?? 0)
220
+ if (agent.status === 'running' || queued > 0) count += 1
221
+ }
222
+ } catch {
223
+ return 0
224
+ }
225
+ return count
226
+ }
227
+
228
+ /**
229
+ * Quote one PowerShell single-quoted string literal.
230
+ *
231
+ * @param value - Raw text.
232
+ * @returns Literal with embedded quotes doubled.
233
+ */
234
+ function psQuote(value) {
235
+ return `'${value.replaceAll("'", "''")}'`
236
+ }
237
+
238
+ /**
239
+ * Quote one VBScript string literal.
240
+ *
241
+ * @param value - Raw text.
242
+ * @returns Literal with embedded quotes doubled.
243
+ */
244
+ function vbsQuote(value) {
245
+ return `"${value.replaceAll('"', '""')}"`
246
+ }
247
+
248
+ /**
249
+ * Build the PowerShell watchdog the Task Scheduler runs outside the application's job.
250
+ *
251
+ * Exported as a pure builder: it reads nothing but its arguments, so a test can generate a
252
+ * script and hand it to the Windows PowerShell parser without ever arming a task.
253
+ *
254
+ * It touches the marker as its first act — that is what proves to the helper that
255
+ * something outside the job is running — and in `restart` mode it does the killing
256
+ * itself. That placement is the whole point: a killer inside the job dies as soon as it
257
+ * touches the process that owns the job, which left the application half dead with a
258
+ * recovery dialog and no relaunch. Out here, killing main simply ends the application.
259
+ *
260
+ * @param executable - Absolute path of the application executable.
261
+ * @param logPath - File the watchdog appends its progress to.
262
+ * @param markerPath - File whose existence proves the watchdog is running.
263
+ * @param mode - `'restart'` to kill and relaunch, `'probe'` to leave the app alone.
264
+ * @returns PowerShell source for the watchdog.
265
+ */
266
+ export function watchdogSource(executable, logPath, markerPath, mode) {
267
+ return [
268
+ "$ErrorActionPreference = 'SilentlyContinue'",
269
+ `$exe = ${psQuote(executable)}`,
270
+ `$log = ${psQuote(logPath)}`,
271
+ `$marker = ${psQuote(markerPath)}`,
272
+ `$mode = ${psQuote(mode)}`,
273
+ // Enumerating every process and reading each one's Path is the slow half of the wait
274
+ // loops below: `.Path` opens a handle per process. Filtering by image name first drops
275
+ // that to the handful that could match, measured on this host at 2.2 ms versus 9.5 ms
276
+ // median for the full sweep, and the gap grows with the process count.
277
+ //
278
+ // `tasklist /FI` was tried first and thrown away: in this context it answers
279
+ // "Access denied" with exit 1 after 47 ms, so a watchdog built on it would report the
280
+ // application as gone in every poll — which is how a relaunch loop starts three copies
281
+ // of the app. Get-Process is the channel that actually works here.
282
+ //
283
+ // The path check stays either way, so a same-named executable in another folder is
284
+ // never mistaken for this one.
285
+ '$name = [System.Management.Automation.WildcardPattern]::Escape([IO.Path]::GetFileNameWithoutExtension($exe))',
286
+ 'function Note($line) { "$([DateTime]::Now.ToString(\'o\')) $line" | Out-File -FilePath $log -Encoding utf8 -Append }',
287
+ 'function Candidates() {',
288
+ ' $found = @()',
289
+ ' foreach ($p in (Get-Process -Name $name -ErrorAction SilentlyContinue)) {',
290
+ ' try { if ($p.Path -eq $exe) { $found += $p.Id } } catch {}',
291
+ ' }',
292
+ ' return $found',
293
+ '}',
294
+ 'function Running() {',
295
+ ' foreach ($procId in (Candidates)) { return $true }',
296
+ ' return $false',
297
+ '}',
298
+ '"$([DateTime]::Now.ToString(\'o\')) armed pid=$PID mode=$mode" | Out-File -FilePath $marker -Encoding utf8 -Append',
299
+ 'Note "watchdog start pid=$PID mode=$mode detect=name-filter"',
300
+ 'if ($mode -ne "restart") {',
301
+ ' Note "probe mode: leaving the application alone"',
302
+ ' [Threading.Thread]::Sleep(3000)',
303
+ ' Note "watchdog end"',
304
+ ' return',
305
+ '}',
306
+ '# Let the helper record that the watchdog is alive before anything dies.',
307
+ '[Threading.Thread]::Sleep(1200)',
308
+ '$procs = @(Candidates)',
309
+ 'Note ("matched pids: " + ($procs -join \',\'))',
310
+ 'foreach ($procId in $procs) {',
311
+ ' $killed = $false',
312
+ ' try { (Get-Process -Id $procId -ErrorAction Stop).Kill(); $killed = $true } catch { }',
313
+ ' if (-not $killed) { & taskkill.exe /F /PID $procId | Out-Null }',
314
+ ' Note "kill pid=$procId direct=$killed"',
315
+ '}',
316
+ 'for ($i = 0; $i -lt 60; $i++) {',
317
+ ' [Threading.Thread]::Sleep(200)',
318
+ ' if (-not (Running)) { break }',
319
+ '}',
320
+ 'Note "application gone=$(-not (Running))"',
321
+ '[Threading.Thread]::Sleep(600)',
322
+ '$attempt = 0',
323
+ '$back = $false',
324
+ 'while ($attempt -lt 3) {',
325
+ ' $attempt++',
326
+ ' try {',
327
+ ' Start-Process -FilePath $exe -WorkingDirectory (Split-Path -Parent $exe)',
328
+ ' Note "relaunch issued attempt=$attempt"',
329
+ ' } catch {',
330
+ ' Note "relaunch failed attempt=${attempt}: $_"',
331
+ ' }',
332
+ ' for ($j = 0; $j -lt 30; $j++) {',
333
+ ' [Threading.Thread]::Sleep(200)',
334
+ ' if (Running) { $back = $true; break }',
335
+ ' }',
336
+ ' Note "running again=$back attempt=$attempt"',
337
+ ' if ($back) { break }',
338
+ ' [Threading.Thread]::Sleep(800)',
339
+ '}',
340
+ 'Note "watchdog end"',
341
+ ].join('\n')
342
+ }
343
+
344
+ /**
345
+ * Windows PowerShell 5.1 executable under the system root.
346
+ *
347
+ * @returns Absolute path of powershell.exe.
348
+ */
349
+ function systemPowerShellPath() {
350
+ const root = process.env.SystemRoot ?? 'C:\\Windows'
351
+ return join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
352
+ }
353
+
354
+ /** Exit code the package-manager probe uses to report "an install is running". */
355
+ const PROBE_BUSY_EXIT = 3
356
+
357
+ /** How long the package-manager probe may take before it is treated as "not busy". */
358
+ const PROBE_TIMEOUT_MS = 4000
359
+
360
+ /**
361
+ * Whether a package manager is installing right now.
362
+ *
363
+ * The lockfile is written at the *end* of an install, so freshness alone cannot
364
+ * see an install that is still running — exactly the window where killing the
365
+ * app does the most damage. This asks the OS instead: a node process whose
366
+ * command line mentions pnpm is taken as an install in flight.
367
+ *
368
+ * The answer travels through the exit code rather than stdout on purpose: this
369
+ * sandbox refuses to spawn a child with piped stdio, and a probe that cannot
370
+ * run must read as "not busy" rather than as an error.
371
+ *
372
+ * @returns true when a package manager process is alive.
373
+ */
374
+ function packageManagerRunning() {
375
+ return new Promise((resolve) => {
376
+ const query = [
377
+ "$busy = (Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" |",
378
+ " Where-Object { $_.CommandLine -match 'pnpm' } | Measure-Object).Count",
379
+ `if ($busy -gt 0) { exit ${PROBE_BUSY_EXIT} } else { exit 0 }`,
380
+ ].join('\n')
381
+ let settled = false
382
+ const finish = (busy) => {
383
+ if (settled) return
384
+ settled = true
385
+ resolve(busy)
386
+ }
387
+ let child
388
+ try {
389
+ child = spawn(systemPowerShellPath(), ['-NoProfile', '-NonInteractive', '-Command', query], {
390
+ stdio: 'ignore',
391
+ windowsHide: true,
392
+ })
393
+ } catch {
394
+ finish(false)
395
+ return
396
+ }
397
+ child.on('error', () => finish(false))
398
+ child.on('close', (code) => finish(code === PROBE_BUSY_EXIT))
399
+ setTimeout(() => {
400
+ try {
401
+ child.kill()
402
+ } catch {
403
+ // Already gone.
404
+ }
405
+ finish(false)
406
+ }, PROBE_TIMEOUT_MS)
407
+ })
408
+ }
409
+
410
+ /**
411
+ * Build the console-free launcher the Task Scheduler starts instead of a console program.
412
+ *
413
+ * The script host is a GUI-subsystem executable, so the task creates no console at all,
414
+ * and window style `0` starts the watchdog fully hidden. Launching PowerShell straight
415
+ * from the task instead races with the console the task creates for it, which is the
416
+ * window that stayed on screen after a restart.
417
+ *
418
+ * Exported as a pure builder, like its watchdog counterpart.
419
+ *
420
+ * @param powershellPath - Absolute path of powershell.exe.
421
+ * @param watchdogPath - The watchdog script to start.
422
+ * @returns VBScript source for the launcher.
423
+ */
424
+ export function watchdogLauncherSource(powershellPath, watchdogPath) {
425
+ const command = `"${powershellPath}" -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "${watchdogPath}"`
426
+ return [
427
+ 'Option Explicit',
428
+ 'Dim shell',
429
+ 'Set shell = CreateObject("WScript.Shell")',
430
+ `shell.Run ${vbsQuote(command)}, 0, False`,
431
+ ].join('\r\n')
432
+ }
433
+
434
+ /**
435
+ * Build the helper that arms a watchdog and then ends the application.
436
+ *
437
+ * Killing by executable path — not by process tree — keeps this process alive through its
438
+ * own kill for as long as the job object allows, and the watchdog does not depend on this
439
+ * process surviving at all.
440
+ *
441
+ * Exported as a pure builder. Every path it writes is an argument, with the module's own
442
+ * status path as the default, so a test can generate a helper into a scratch directory.
443
+ *
444
+ * @param executable - Absolute path of the application executable.
445
+ * @param logPath - File the helper appends its progress to.
446
+ * @param watchdogPath - The PowerShell watchdog to arm through the Task Scheduler.
447
+ * @param launcherPath - Script-host launcher that starts the watchdog without a console.
448
+ * @param markerPath - File whose existence proves a watchdog is running.
449
+ * @param taskName - Scheduled-task name that runs the watchdog outside the job.
450
+ * @param mode - `'restart'` to kill after arming, `'probe'` to report and stop.
451
+ * @param statusPath - File the helper publishes its arming result to.
452
+ * @returns PowerShell source for the helper.
453
+ */
454
+ export function restartHelperScript(
455
+ executable,
456
+ logPath,
457
+ watchdogPath,
458
+ launcherPath,
459
+ markerPath,
460
+ taskName,
461
+ mode,
462
+ statusPath = ARM_STATUS_PATH,
463
+ ) {
464
+ return [
465
+ "$ErrorActionPreference = 'SilentlyContinue'",
466
+ `$exe = ${psQuote(executable)}`,
467
+ `$log = ${psQuote(logPath)}`,
468
+ `$watchdog = ${psQuote(watchdogPath)}`,
469
+ `$launcher = ${psQuote(launcherPath)}`,
470
+ `$marker = ${psQuote(markerPath)}`,
471
+ `$status = ${psQuote(statusPath)}`,
472
+ `$task = ${psQuote(taskName)}`,
473
+ `$mode = ${psQuote(mode)}`,
474
+ '$scriptHost = Join-Path $env:SystemRoot \'System32\\WindowsPowerShell\\v1.0\\powershell.exe\'',
475
+ 'function Note($line) { "$([DateTime]::Now.ToString(\'o\')) $line" | Out-File -FilePath $log -Encoding utf8 -Append }',
476
+ 'function WaitMarker() {',
477
+ ` for ($i = 0; $i -lt ${String(ARM_POLLS)}; $i++) {`,
478
+ ' if (Test-Path -LiteralPath $marker) { return $true }',
479
+ ' [Threading.Thread]::Sleep(200)',
480
+ ' }',
481
+ ' return $false',
482
+ '}',
483
+ 'Note "helper start pid=$PID exe=$exe"',
484
+ `[Threading.Thread]::Sleep(${String(RESTART_LEAD_MS)})`,
485
+ 'Remove-Item -LiteralPath $marker -Force -ErrorAction SilentlyContinue',
486
+ '$method = "none"',
487
+ '$armed = $false',
488
+ '',
489
+ '# Arm the watchdog outside this process tree: the Scheduled Task service is not the',
490
+ '# application, so its child neither inherits the job object nor dies with the kill.',
491
+ '$startAt = (Get-Date).AddMinutes(5).ToString(\'HH:mm\')',
492
+ '$taskHost = Join-Path $env:SystemRoot \'System32\\wscript.exe\'',
493
+ '',
494
+ '# Attempt 1: let the script host start the watchdog with window style 0. A console',
495
+ '# program launched straight from the Task Scheduler gets a bidirectional console, and',
496
+ '# -WindowStyle Hidden races with it; wscript is a GUI-subsystem host, so no console is',
497
+ '# created at all.',
498
+ '$action = "`"$taskHost`" `"$launcher`""',
499
+ '& schtasks.exe /Create /TN $task /TR $action /SC ONCE /ST $startAt /F | Out-Null',
500
+ '$created = $LASTEXITCODE',
501
+ 'Note "schtasks create exit=$created (hidden launcher)"',
502
+ 'if ($created -eq 0) {',
503
+ ' & schtasks.exe /Run /TN $task | Out-Null',
504
+ ' Note "schtasks run exit=$LASTEXITCODE (hidden launcher)"',
505
+ ' $armed = WaitMarker',
506
+ ' Note "task watchdog alive=$armed (hidden launcher)"',
507
+ ' if ($armed) { $method = "task-hidden" }',
508
+ ' & schtasks.exe /Delete /TN $task /F | Out-Null',
509
+ ' Note "schtasks delete exit=$LASTEXITCODE (hidden launcher)"',
510
+ '}',
511
+ '',
512
+ '# Attempt 2: the same task running PowerShell directly. This is the shape that may',
513
+ '# flash a console window, kept only so a machine without Windows Script Host still',
514
+ '# restarts instead of doing nothing.',
515
+ 'if (-not $armed) {',
516
+ ' $action = "`"$scriptHost`" -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$watchdog`""',
517
+ ' & schtasks.exe /Create /TN $task /TR $action /SC ONCE /ST $startAt /F | Out-Null',
518
+ ' $created = $LASTEXITCODE',
519
+ ' Note "schtasks create exit=$created (direct powershell)"',
520
+ ' if ($created -eq 0) {',
521
+ ' & schtasks.exe /Run /TN $task | Out-Null',
522
+ ' Note "schtasks run exit=$LASTEXITCODE (direct powershell)"',
523
+ ' $armed = WaitMarker',
524
+ ' Note "task watchdog alive=$armed (direct powershell)"',
525
+ ' if ($armed) { $method = "task-visible" }',
526
+ ' & schtasks.exe /Delete /TN $task /F | Out-Null',
527
+ ' Note "schtasks delete exit=$LASTEXITCODE (direct powershell)"',
528
+ ' }',
529
+ '}',
530
+ '',
531
+ '# Nothing else is attempted on purpose. Launching explorer.exe from here produced a',
532
+ '# 0xC0000142 "application could not start" dialog instead of a hidden helper: the shell',
533
+ '# is a singleton GUI process and does not survive being started from this context.',
534
+ '',
535
+ '# Refuse to kill the application without a live watchdog: a restart that closes the',
536
+ '# window and never comes back is worse than no restart at all.',
537
+ 'if (-not $armed) {',
538
+ ' Note "abort: no watchdog came alive, application left running"',
539
+ " ('{{\"armed\":false,\"mode\":\"{0}\"}}' -f $mode) | Out-File -FilePath $status -Encoding utf8",
540
+ ' Note "helper done"',
541
+ ' return',
542
+ '}',
543
+ 'Note "watchdog armed via $method"',
544
+ "('{{\"armed\":true,\"method\":\"{0}\",\"mode\":\"{1}\"}}' -f $method, $mode) | Out-File -FilePath $status -Encoding utf8",
545
+ '',
546
+ '# The helper never kills anything. It lives inside the application job, so any kill it',
547
+ '# performed could end the job and take the helper with it — that is exactly how an',
548
+ '# earlier version left the window dead with a recovery dialog. The watchdog owns the',
549
+ '# kill from outside, so this process has finished its work here.',
550
+ 'Note "helper done: watchdog owns the kill"',
551
+ ].join('\n')
552
+ }
553
+
554
+ /**
555
+ * Start the helper that arms a watchdog and kills the application.
556
+ *
557
+ * @param executable - Absolute path of the application executable.
558
+ * @param mode - `'restart'` to kill after arming, `'probe'` to report and stop.
559
+ * @returns The helper's process id, or undefined when the platform reports none.
560
+ */
561
+ function launchRestartHelper(executable, mode = 'restart') {
562
+ const script = restartHelperScript(
563
+ executable,
564
+ HELPER_LOG_PATH,
565
+ WATCHDOG_PS1_PATH,
566
+ WATCHDOG_LAUNCHER_PATH,
567
+ WATCHDOG_MARKER_PATH,
568
+ TASK_NAME,
569
+ mode,
570
+ )
571
+ const encoded = Buffer.from(script, 'utf16le').toString('base64')
572
+ // No `detached` here on purpose: a detached powershell.exe never runs its
573
+ // -EncodedCommand script on this platform. See the module doc.
574
+ const helper = spawn(
575
+ 'powershell.exe',
576
+ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded],
577
+ { stdio: 'ignore', windowsHide: true },
578
+ )
579
+ helper.on('error', () => {
580
+ // Reported through the route's answer and the helper log; nothing to recover here.
581
+ })
582
+ helper.unref()
583
+ return helper.pid
584
+ }
585
+
586
+ /**
587
+ * Whether the caller may restart this application.
588
+ *
589
+ * Two shapes are accepted. A page served by this Host sends the header below; without a
590
+ * preflight no cross-origin page can set it, and this route answers no CORS headers, so a
591
+ * third-party site cannot reach the rest. The desktop shell forwards page requests to the
592
+ * Host with `Host`, `Origin`, and cookies stripped, so on a loopback peer that absence is
593
+ * the trusted desktop shape rather than a missing signal.
594
+ *
595
+ * @param request - Node request.
596
+ * @returns true when the caller is this application's own page.
597
+ */
598
+ function sameOriginCaller(request) {
599
+ if (request.headers['x-dsh-desktop-restart'] === '1') return true
600
+ if (request.headers.host !== undefined || request.headers.origin !== undefined) return false
601
+ if (request.headers.forwarded !== undefined) return false
602
+ const address = request.socket.remoteAddress
603
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
604
+ }
605
+
606
+ /**
607
+ * Write both watchdog scripts for the current executable.
608
+ *
609
+ * @param executable - Absolute path of the application executable.
610
+ */
611
+ function writeWatchdogs(executable, mode) {
612
+ writeFileSync(WATCHDOG_PS1_PATH, watchdogSource(executable, HELPER_LOG_PATH, WATCHDOG_MARKER_PATH, mode), 'ascii')
613
+ writeFileSync(WATCHDOG_LAUNCHER_PATH, watchdogLauncherSource(systemPowerShellPath(), WATCHDOG_PS1_PATH), 'ascii')
614
+ }
615
+
616
+ /**
617
+ * Wait for a probe helper to publish its arming result.
618
+ *
619
+ * @param deadlineMs - Upper bound in milliseconds.
620
+ * @returns Parsed status, or undefined when the helper never published one.
621
+ */
622
+ async function waitForArmStatus(deadlineMs) {
623
+ const limit = Date.now() + deadlineMs
624
+ while (Date.now() < limit) {
625
+ if (existsSync(ARM_STATUS_PATH)) {
626
+ try {
627
+ // Windows PowerShell 5.1 writes UTF-8 *with* a BOM for `-Encoding utf8`, and
628
+ // JSON.parse rejects a leading BOM as an unexpected token. Strip it first.
629
+ return JSON.parse(readFileSync(ARM_STATUS_PATH, 'utf8').replace(/^\uFEFF/, ''))
630
+ } catch {
631
+ // The helper creates the file before writing it, so a parse failure here may just
632
+ // mean half a file. Keep polling until the deadline instead of giving up.
633
+ }
634
+ }
635
+ await new Promise((resolve) => setTimeout(resolve, 250))
636
+ }
637
+ return undefined
638
+ }
639
+
640
+ /**
641
+ * Answer one HTTP request on this plugin's route.
642
+ *
643
+ * @param ctx - Host context owning the composed services.
644
+ * @param request - Node request.
645
+ * @param response - Node response.
646
+ */
647
+ async function handleRequest(ctx, request, response) {
648
+ const reply = (status, body) => {
649
+ response.writeHead(status, {
650
+ 'content-type': 'application/json; charset=utf-8',
651
+ 'cache-control': 'no-store',
652
+ })
653
+ response.end(JSON.stringify(body))
654
+ }
655
+ let pathname = RESTART_PATH
656
+ try {
657
+ pathname = new URL(request.url ?? '/', 'http://127.0.0.1').pathname
658
+ } catch {
659
+ return reply(400, { ok: false, reason: 'bad-url' })
660
+ }
661
+ if (pathname === STATUS_PATH) {
662
+ if (request.method !== 'GET') return reply(405, { ok: false, reason: 'method-not-allowed' })
663
+ return reply(200, {
664
+ ok: true,
665
+ desktop: desktopExecutable() !== undefined,
666
+ restarting: restartInFlight(),
667
+ activeAgents: activeAgentCount(ctx),
668
+ logPath: HELPER_LOG_PATH,
669
+ })
670
+ }
671
+ if (pathname === DIAGNOSE_PATH) {
672
+ if (request.method !== 'POST') return reply(405, { ok: false, reason: 'method-not-allowed' })
673
+ if (!sameOriginCaller(request)) return reply(403, { ok: false, reason: 'cross-origin' })
674
+ const executable = desktopExecutable()
675
+ if (executable === undefined) return reply(409, { ok: false, reason: 'not-desktop' })
676
+ try {
677
+ rmSync(ARM_STATUS_PATH, { force: true })
678
+ writeWatchdogs(executable, 'probe')
679
+ launchRestartHelper(executable, 'probe')
680
+ } catch (error) {
681
+ return reply(500, {
682
+ ok: false,
683
+ reason: 'spawn-failed',
684
+ message: error instanceof Error ? error.message : String(error),
685
+ })
686
+ }
687
+ const status = await waitForArmStatus(15_000)
688
+ return reply(200, {
689
+ ok: status?.armed === true,
690
+ diagnostic: status ?? { armed: false, reason: 'helper did not report in time' },
691
+ logPath: HELPER_LOG_PATH,
692
+ })
693
+ }
694
+ if (pathname !== RESTART_PATH) return reply(404, { ok: false, reason: 'not-found' })
695
+ if (request.method !== 'POST') return reply(405, { ok: false, reason: 'method-not-allowed' })
696
+ if (!sameOriginCaller(request)) {
697
+ return reply(403, { ok: false, reason: 'cross-origin' })
698
+ }
699
+
700
+ const executable = desktopExecutable()
701
+ if (executable === undefined) {
702
+ return reply(409, {
703
+ ok: false,
704
+ reason: 'not-desktop',
705
+ message: 'This Host is not the desktop application, so there is no application to restart.',
706
+ })
707
+ }
708
+ if (!existsSync(executable)) {
709
+ return reply(500, { ok: false, reason: 'missing-executable', message: executable })
710
+ }
711
+ if (await installInProgress()) {
712
+ return reply(409, {
713
+ ok: false,
714
+ reason: 'installing',
715
+ message: 'A package manager is writing this profile right now; try again once the install finishes.',
716
+ })
717
+ }
718
+ if (restartInFlight()) {
719
+ return reply(202, {
720
+ ok: true,
721
+ restarting: true,
722
+ duplicate: true,
723
+ executable,
724
+ logPath: HELPER_LOG_PATH,
725
+ })
726
+ }
727
+
728
+ const activeAgents = activeAgentCount(ctx)
729
+ let helperPid
730
+ try {
731
+ writeWatchdogs(executable, 'restart')
732
+ helperPid = launchRestartHelper(executable, 'restart')
733
+ } catch (error) {
734
+ return reply(500, {
735
+ ok: false,
736
+ reason: 'spawn-failed',
737
+ message: error instanceof Error ? error.message : String(error),
738
+ })
739
+ }
740
+ if (helperPid === undefined) {
741
+ return reply(500, {
742
+ ok: false,
743
+ reason: 'spawn-failed',
744
+ message: 'The restart helper process could not be started.',
745
+ })
746
+ }
747
+ restartingSince = Date.now()
748
+ try {
749
+ ctx.logger?.('desktop-restart')?.info?.('restart requested', {
750
+ executable,
751
+ activeAgents,
752
+ helperPid,
753
+ logPath: HELPER_LOG_PATH,
754
+ })
755
+ } catch {
756
+ // Logging is best effort; the restart already owns the outcome.
757
+ }
758
+ return reply(202, {
759
+ ok: true,
760
+ restarting: true,
761
+ activeAgents,
762
+ helperPid,
763
+ executable,
764
+ logPath: HELPER_LOG_PATH,
765
+ })
766
+ }
767
+
768
+ /**
769
+ * Register the restart route for this Host's lifetime.
770
+ *
771
+ * @param ctx - Host context.
772
+ */
773
+ export function apply(ctx) {
774
+ // The plugin manager announces its own install phases on this event. Subscribing
775
+ // is what lets a restart refuse while an install is *running*, instead of only
776
+ // once it has written the lockfile at the end.
777
+ ctx.on?.('plugin-manager/install-state', (progress) => {
778
+ noteInstallPhase(progress?.phase)
779
+ })
780
+ ctx.effect(() =>
781
+ ctx.webServer.register({
782
+ kind: 'prefix',
783
+ path: PREFIX,
784
+ handler: (request, response) => {
785
+ const fail = (error) => {
786
+ try {
787
+ response.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
788
+ response.end(
789
+ JSON.stringify({
790
+ ok: false,
791
+ reason: 'internal',
792
+ message: error instanceof Error ? error.message : String(error),
793
+ }),
794
+ )
795
+ } catch {
796
+ // The response is already gone; nothing else can be reported.
797
+ }
798
+ }
799
+ try {
800
+ const pending = handleRequest(ctx, request, response)
801
+ if (pending !== undefined) pending.catch(fail)
802
+ } catch (error) {
803
+ fail(error)
804
+ }
805
+ },
806
+ }),
807
+ )
808
+ }