Skip to content

The agent that grows with you

fix(desktop): a Linux relaunch waits for the old process to die, not for its stdin to close

Teknium1c2ba3a3b174
diff --git a/apps/desktop/electron/app-relaunch.test.ts b/apps/desktop/electron/app-relaunch.test.ts
index d7aeb61e574..123c9cb68c0 100644
--- a/apps/desktop/electron/app-relaunch.test.ts
+++ b/apps/desktop/electron/app-relaunch.test.ts
@@ -111,6 +111,48 @@ test.skipIf(process.platform !== 'linux')(
}
)
+// Node's teardown closes the helper's stdin before Chromium has shut down (storage flush,
+// DevTools, a core dump): a target started then binds next to a live old process and loses
+// whatever that still holds, such as the DevTools port.
+const LINGERING_PROCESS = `
+import { spawnRelaunch } from './relaunch-target'
+
+process.env.OLD_PID = String(process.pid)
+spawnRelaunch(process.argv[2], [], process.env).stdin!.end()
+setTimeout(() => process.exit(0), 1000)
+`
+
+test.skipIf(process.platform !== 'linux')('a Linux relaunch starts only once the old process is dead', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-relaunch-linger-'))
+ const exe = path.join(dir, 'hermes')
+ const oldProcess = path.join(dir, 'old-process.cjs')
+ const report = path.join(dir, 'report')
+
+ fs.writeFileSync(
+ exe,
+ `#!/bin/sh\ns=$(cut -d' ' -f3 /proc/$OLD_PID/stat 2>/dev/null)\necho "\${s:-gone}" > "$REPORT.part"\nmv "$REPORT.part" "$REPORT"\n`,
+ { mode: 0o755 }
+ )
+ buildSync({
+ stdin: { contents: LINGERING_PROCESS, resolveDir: import.meta.dirname, loader: 'ts' },
+ outfile: oldProcess,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ external: ['electron'],
+ logLevel: 'silent'
+ })
+
+ try {
+ spawnSync(process.execPath, [oldProcess, exe], { env: { PATH: process.env.PATH, REPORT: report } })
+ await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })
+ // Dead: reaped already, or a zombie its parent has not collected yet.
+ expect(['gone', 'Z']).toContain(fs.readFileSync(report, 'utf8').trim())
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
+
test('macOS and Windows keep Electron app.relaunch', () => {
for (const platform of ['darwin', 'win32']) {
const events: string[] = []
diff --git a/apps/desktop/electron/app-relaunch.ts b/apps/desktop/electron/app-relaunch.ts
index 8b66ac639da..f4acb8d7540 100644
--- a/apps/desktop/electron/app-relaunch.ts
+++ b/apps/desktop/electron/app-relaunch.ts
@@ -40,10 +40,12 @@ export interface AppRelauncher {
* FUSE-mounted AppImage cannot mount itself again. Linux therefore hands the
* relaunch to an ordinary detached helper the moment it is requested, as
* app.relaunch() does, so a fatal abort during the backend-shutdown wait still
- * comes back; the helper starts the target only once this process is gone, so
- * the new process neither races the old backend nor quits as a second
- * instance. The target is the AppImage file for a mounted image (the mount
- * dies with this process), otherwise this executable.
+ * comes back. The helper starts the target once this process has died, not
+ * when Node's teardown closes its stdin (Chromium's shutdown, or a core dump,
+ * can outlast that by seconds), so the new process neither races the old
+ * backend, DevTools port or storage locks nor quits as a second instance. The
+ * target is the AppImage file for a mounted image (the mount dies with this
+ * process), otherwise this executable.
*/
export function createAppRelauncher(
app: AppRelauncher,
@@ -73,7 +75,8 @@ export function createAppRelauncher(
// not the long one main.ts restored after the lock (linux-sandbox-relaunch.ts).
const childEnv = { ...env }
restoreLaunchTmpdir(childEnv)
- // The latest request wins.
+ // The latest request wins. The cancel relies on the old helper's stdin staying open until the
+ // SIGTERM lands: closing it first would let that helper exec, starting two targets.
helper?.kill()
helper = null
diff --git a/apps/desktop/electron/linux-sandbox-relaunch.test.ts b/apps/desktop/electron/linux-sandbox-relaunch.test.ts
index 1fc07c15e17..5fafb303c91 100644
--- a/apps/desktop/electron/linux-sandbox-relaunch.test.ts
+++ b/apps/desktop/electron/linux-sandbox-relaunch.test.ts
@@ -233,6 +233,12 @@ describe('Linux runtime --no-sandbox relaunch', () => {
'linux'
)
+ // The helper waits while it is still this process's child; a shell that starts it in the
+ // background (in a session of its own, as the detached spawn gives it) and exits stands in.
+ const realSpawn = (await vi.importActual<typeof childProcess>('node:child_process')).spawn
+ vi.mocked(spawn).mockImplementationOnce((file, args, options) =>
+ realSpawn('/bin/sh', ['-c', 'exec 4<&0; setsid "$@" <&4 4<&- &', 'sh', file, ...args], options)
+ )
relaunchIfNoSandboxCameTooLate(relauncher, () => events.push('beforeExit'))
expect(events).toEqual(['beforeExit', 'release', 'exit 0'])
// This process is gone: the waiting helper's stdin closes.
diff --git a/apps/desktop/electron/relaunch-target.test.ts b/apps/desktop/electron/relaunch-target.test.ts
index d0d731eb67a..34809dda95d 100644
--- a/apps/desktop/electron/relaunch-target.test.ts
+++ b/apps/desktop/electron/relaunch-target.test.ts
@@ -42,6 +42,10 @@ describe('ownAppImage', () => {
})
})
+// The helper waits while it is still this process's child and this runner stays, so a shell that
+// starts the helper in the background (stdin kept: an async list's is /dev/null) and exits stands in.
+const EXITING_PARENT = 'exec 4<&0; "$@" <&4 4<&- &'
+
describe('spawnRelaunch', () => {
// Chromium's relauncher closes inherited fds; a libuv spawn does not. The
// AppImage runtime's keepalive pipe (fd 3) in the new image kept the old
@@ -88,10 +92,10 @@ describe('spawnRelaunch', () => {
// Node marks every inherited fd close-on-exec at startup and Electron's
// main does not, so the command spawnRelaunch spawns runs from a shell
// that holds fds 3 and 9 open on a marker file, as Electron holds the
- // runtime's keepalive pipe.
+ // runtime's keepalive pipe. That shell exits at once, as the app would.
const realSpawn = (await vi.importActual<typeof childProcess>('node:child_process')).spawn
vi.mocked(spawn).mockImplementationOnce((file, args, options) =>
- realSpawn('/bin/sh', ['-c', 'exec 3<"$0" 9<"$0"; exec "$@"', held, file, ...args], options)
+ realSpawn('/bin/sh', ['-c', `exec 3<"$0" 9<"$0"; ${EXITING_PARENT}`, held, file, ...args], options)
)
fs.writeFileSync(held, '')
// This mount's AppRun prepended it to PATH; the mount is gone soon after the child starts.
@@ -165,7 +169,10 @@ describe('spawnRelaunch', () => {
// Electron's main keeps such fds across exec; Node marks its own close-on-exec, so hand one down as fd 12.
const realSpawn = (await vi.importActual<typeof childProcess>('node:child_process')).spawn
vi.mocked(spawn).mockImplementationOnce((file, args, options) =>
- realSpawn(file, args, { ...options, stdio: ['pipe', ...Array<'ignore'>(11).fill('ignore'), fd] })
+ realSpawn('/bin/sh', ['-c', EXITING_PARENT, 'sh', file, ...args], {
+ ...options,
+ stdio: ['pipe', ...Array<'ignore'>(11).fill('ignore'), fd]
+ })
)
spawnRelaunch(exe, [], { PATH: process.env.PATH }).stdin!.end()
diff --git a/apps/desktop/electron/relaunch-target.ts b/apps/desktop/electron/relaunch-target.ts
index 780b57a0013..c0e39194dd7 100644
--- a/apps/desktop/electron/relaunch-target.ts
+++ b/apps/desktop/electron/relaunch-target.ts
@@ -130,9 +130,13 @@ export function canRelaunch(
}
// The helper starts before the caller's shutdown wait and execs the target
-// once its stdin reaches EOF: that pipe's only writer is this process, so EOF
-// is this process's exit, crash or kill, after which the target replaces the
-// helper as Electron's relauncher would.
+// once this process is gone, as Electron's relauncher would. EOF on its stdin
+// (this process is that pipe's only writer) only means Node's teardown began:
+// Chromium can still hold the DevTools port, storage locks and the GPU for
+// seconds, longer if it dumps core. The helper then waits until the kernel
+// reparents it, which happens after the dead process released its files. A
+// stuck old process holds the restart back for 600 polls (~30 s) at most, and
+// without /proc the read fails and the target starts at EOF.
//
// libuv's spawn keeps every descriptor this process inherited without
// O_CLOEXEC, which Chromium's launcher (app.relaunch) closes. Ours include the
@@ -143,6 +147,11 @@ export function canRelaunch(
// 0-9 and dash exits on `exec 10<&-`, so higher numbers are closed where the
// shell takes them (bash, busybox) and left in place under dash.
const EXEC_AFTER_EXIT = `while read -r _; do :; done
+n=0
+while [ $n -lt 600 ] && read -r _ _ _ cur _ </proc/self/stat && [ "$cur" = "$pp" ]; do
+ sleep 0.05
+ n=$((n + 1))
+done
exec </dev/null
big=
(eval 'exec 10<&-') 2>/dev/null && big=1
@@ -237,7 +246,8 @@ export function spawnRelaunch(
const ownImage = env.APPIMAGE && posix.resolve(target) === posix.resolve(env.APPIMAGE)
const childEnv = ownImage ? withoutMountEntries(env, execPath) : env
- const child = spawn(shell.file, [...shell.args, '-c', EXEC_AFTER_EXIT, target, ...args], {
+ // This pid, not the shell's $PPID: if this process dies before the shell starts, $PPID is already the new parent.
+ const child = spawn(shell.file, [...shell.args, '-c', `pp=${process.pid}\n${EXEC_AFTER_EXIT}`, target, ...args], {
detached: true,
stdio: ['pipe', 'ignore', 'ignore'],
env: childEnv