Skip to content

The agent that grows with you

fix(desktop): launch Store relaunch waiter with a hidden console

Ryan Hill56b54712350d
diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.ts
index 92d50e9ae53..fa2347cfd47 100644
--- a/apps/desktop/electron/updater-process.ts
+++ b/apps/desktop/electron/updater-process.ts
@@ -296,13 +296,15 @@ export function resolvePosixScriptHandoff(
* Survival past our own exit does not need `detached`: libuv's per-process
* job object has JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK, so grandchildren
* (`start`'s powershell) are never members and Windows does not tie a
- * process's lifetime to its parent. `start` returns immediately, so the
+ * process's lifetime to its parent. By default `start` returns immediately, so the
* spawned pid is the WRAPPER's — callers must not use it as a marker owner
- * (the script claims the marker itself with its own $PID).
+ * (the script claims the marker itself with its own $PID). Set waitForExit to
+ * keep the wrapper alive for callers that need to cancel its process tree.
*/
export function wrapHandoffForDetachedConsole(
handoff: UpdateScriptHandoff,
- extraArgs: string[]
+ extraArgs: string[],
+ waitForExit = false
): {
command: string
args: string[]
@@ -311,7 +313,18 @@ export function wrapHandoffForDetachedConsole(
} {
return {
command: 'cmd.exe',
- args: ['/d', '/s', '/c', 'start', '', '/b', handoff.command, ...handoff.args, ...extraArgs],
+ args: [
+ '/d',
+ '/s',
+ '/c',
+ 'start',
+ '',
+ '/b',
+ ...(waitForExit ? ['/wait'] : []),
+ handoff.command,
+ ...handoff.args,
+ ...extraArgs
+ ],
detached: false
}
}
diff --git a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts
index 9cb405fa317..14b5d66e020 100644
--- a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts
+++ b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts
@@ -8,6 +8,7 @@ import path from 'node:path'
import { test, vi } from 'vitest'
import {
+ POWERSHELL_PATH,
RELAUNCH_WAITER_LOG_TAIL_BYTES,
type RelaunchWaiterHandle,
type SpawnWaiter,
@@ -46,18 +47,20 @@ for (const mode of [
const readyFile: string = path.join(stage, 'ready.txt')
assert.equal(
command,
- path.win32.join(
- process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows',
- 'System32',
- 'WindowsPowerShell',
- 'v1.0',
- 'powershell.exe'
- )
+ path.win32.join(process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows', 'System32', 'cmd.exe')
)
- assert.deepEqual(options, { cwd: stage, detached: true, stdio: 'ignore', windowsHide: true })
+ assert.deepEqual(options, { cwd: stage, detached: false, stdio: 'ignore', windowsHide: true })
assert.notEqual(stage, path.dirname(scriptPath))
assert.deepEqual(fs.readFileSync(path.join(stage, 'update-relaunch-waiter.ps1')), fs.readFileSync(scriptPath))
assert.deepEqual(args, [
+ '/d',
+ '/s',
+ '/c',
+ 'start',
+ '',
+ '/b',
+ '/wait',
+ POWERSHELL_PATH,
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
@@ -117,7 +120,15 @@ for (const mode of [
identityName: 'disposable-waiter-test',
scriptPath
},
- { spawn: start, handshakeTimeoutMs: mode.ready ? 10_000 : 2_000, cancelTimeoutMs: 2_000, pollMs: 20 }
+ {
+ spawn: start,
+ kill: child => {
+ child.kill()
+ },
+ handshakeTimeoutMs: mode.ready ? 10_000 : 2_000,
+ cancelTimeoutMs: 2_000,
+ pollMs: 20
+ }
)
if (!mode.ready && mode.refuseKill) {
diff --git a/apps/desktop/electron/updater/relaunch-waiter-spawn.windows-live.test.ts b/apps/desktop/electron/updater/relaunch-waiter-spawn.windows-live.test.ts
new file mode 100644
index 00000000000..c0d66d11422
--- /dev/null
+++ b/apps/desktop/electron/updater/relaunch-waiter-spawn.windows-live.test.ts
@@ -0,0 +1,88 @@
+import { spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { buildSync } from 'esbuild'
+import { expect, it } from 'vitest'
+
+it.runIf(process.platform === 'win32').each([false, true])(
+ 'a real hidden PowerShell waiter survives parent exit unless cancelled (cancel=%s)',
+ async cancel => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'waiter native '))
+ const script = path.join(root, 'waiter.ps1')
+ const result = path.join(root, 'result.json')
+ const completed = path.join(root, 'completed.txt')
+ const bundle = path.join(root, 'waiter.cjs')
+ fs.writeFileSync(
+ script,
+ `
+param([int]$ProcessId, [long]$ProcessStartTimeMs, [string]$IdentityName, [string]$ReadyFile, [int]$TimeoutSeconds)
+Set-Content -LiteralPath ($IdentityName + '.pid') -Value $PID
+Set-Content -LiteralPath $ReadyFile -Value 'ready'
+$deadline = (Get-Date).AddSeconds(20)
+while (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) {
+ if ((Get-Date) -gt $deadline) { exit 3 }
+ Start-Sleep -Milliseconds 100
+}
+Set-Content -LiteralPath $IdentityName -Value 'parent exited'
+`
+ )
+ buildSync({
+ entryPoints: [path.resolve(import.meta.dirname, 'relaunch-waiter.ts')],
+ outfile: bundle,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs'
+ })
+
+ try {
+ const parent = spawnSync(
+ process.execPath,
+ [
+ '-e',
+ `
+const fs = require('node:fs');
+const { startRelaunchWaiter } = require(${JSON.stringify(bundle)});
+(async () => {
+ const logs = [];
+ const handle = await startRelaunchWaiter({
+ processId: process.pid, processStartTimeMs: Date.now() - process.uptime() * 1000,
+ identityName: ${JSON.stringify(completed)}, scriptPath: ${JSON.stringify(script)}
+ }, { log: message => logs.push(message) });
+ if (${cancel} && handle) await handle.cancel();
+ fs.writeFileSync(${JSON.stringify(result)}, JSON.stringify({ ready: !!handle, logs }));
+})().catch(error => { console.error(error); process.exitCode = 1; });
+`
+ ],
+ { encoding: 'utf8', windowsHide: true, timeout: 30_000 }
+ )
+
+ expect(parent.status, parent.stderr).toBe(0)
+ const registration = JSON.parse(fs.readFileSync(result, 'utf8'))
+ expect(registration.ready, registration.logs.join('\n')).toBe(true)
+
+ if (cancel) {
+ const workerPid = Number(fs.readFileSync(completed + '.pid', 'utf8').trim())
+ expect(() => process.kill(workerPid, 0)).toThrow()
+ expect(fs.existsSync(completed)).toBe(false)
+ } else {
+ await expect.poll(() => fs.existsSync(completed), { timeout: 10_000 }).toBe(true)
+ expect(fs.readFileSync(completed, 'utf8').trim()).toBe('parent exited')
+ }
+ } finally {
+ if (fs.existsSync(completed + '.pid')) {
+ const workerPid = Number(fs.readFileSync(completed + '.pid', 'utf8').trim())
+
+ try {
+ process.kill(workerPid)
+ } catch {
+ /* The fixture already exited. */
+ }
+ }
+
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ },
+ 45_000
+)
diff --git a/apps/desktop/electron/updater/relaunch-waiter.ts b/apps/desktop/electron/updater/relaunch-waiter.ts
index e2191af9d07..5567be38e7c 100644
--- a/apps/desktop/electron/updater/relaunch-waiter.ts
+++ b/apps/desktop/electron/updater/relaunch-waiter.ts
@@ -1,11 +1,13 @@
// Stage the waiter outside the package and await its old-version snapshot.
// A failed handshake cancels our child instead of leaving a delayed relaunch.
-import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process'
+import { type ChildProcess, execFile, spawn as nodeSpawn } from 'node:child_process'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
+import { wrapHandoffForDetachedConsole } from '../updater-process'
+
export const RELAUNCH_WAITER_SCRIPT = 'update-relaunch-waiter.ps1'
/**
@@ -56,6 +58,8 @@ export type SpawnWaiter = (
export interface RelaunchWaiterDeps {
spawn?: SpawnWaiter
+ /** Stop the owned wrapper and its waiter before releasing the staging directory. */
+ kill?: (child: ChildProcess) => void | Promise<void>
/** Handshake deadline in ms (tests shrink this). */
handshakeTimeoutMs?: number
/** Poll interval for the ready file (tests shrink this). */
@@ -188,11 +192,25 @@ export async function startRelaunchWaiter(
let child: ChildProcess
try {
- child = spawn(
- POWERSHELL_PATH,
- buildRelaunchWaiterArgs({ ...options, scriptPath: staging.scriptPath }, staging.readyFile),
- { detached: true, stdio: 'ignore', windowsHide: true, cwd: staging.stageDir }
+ // PowerShell 5.1 exits before executing -File under DETACHED_PROCESS.
+ // /b shares cmd's hidden console; /wait retains a live cancellation root.
+ // The PowerShell grandchild survives Electron's libuv job being closed.
+ const wrapped = wrapHandoffForDetachedConsole(
+ {
+ command: POWERSHELL_PATH,
+ args: buildRelaunchWaiterArgs({ ...options, scriptPath: staging.scriptPath }, staging.readyFile),
+ scriptPath: staging.scriptPath
+ },
+ [],
+ true
)
+
+ child = spawn(path.win32.resolve(POWERSHELL_PATH, '../../../cmd.exe'), wrapped.args, {
+ detached: wrapped.detached,
+ stdio: 'ignore',
+ windowsHide: true,
+ cwd: staging.stageDir
+ })
} catch (error) {
log(`[updates] relaunch waiter: spawning ${POWERSHELL_PATH} threw: ${errorText(error)}`)
@@ -223,7 +241,18 @@ export async function startRelaunchWaiter(
cancellation ??= (async () => {
if (!closed) {
if (child.pid !== undefined) {
- child.kill()
+ if (deps.kill) {
+ await deps.kill(child)
+ } else {
+ await new Promise<void>((resolve, reject) => {
+ execFile(
+ path.win32.resolve(POWERSHELL_PATH, '../../../taskkill.exe'),
+ ['/PID', String(child.pid), '/T', '/F'],
+ { windowsHide: true, timeout: cancelTimeoutMs },
+ error => (error ? reject(error) : resolve())
+ )
+ })
+ }
}
let timeout: ReturnType<typeof setTimeout> | undefined