The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): Linux relaunches survive an abort mid-shutdown and keep the NVIDIA witness clean
Teknium2b6a5162aeb8
diff --git a/apps/desktop/electron/app-relaunch.test.ts b/apps/desktop/electron/app-relaunch.test.tsindex b726433726c..d7aeb61e574 100644--- a/apps/desktop/electron/app-relaunch.test.ts+++ b/apps/desktop/electron/app-relaunch.test.ts@@ -1,7 +1,9 @@+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, test, vi } from 'vitest'import { createAppRelauncher, relaunchApp } from './app-relaunch'@@ -30,40 +32,79 @@ function noNewPrivs(statusText: string): string | undefined {return /^NoNewPrivs:\s*(\d)/m.exec(statusText)?.[1]}+// What main.ts does around a relaunch, in its own process: request it, then exit after the+// backend wait or die during it. Chromium's fatal "GPU process isn't usable" abort can land in+// that wait, and app.relaunch() comes back from it because its helper starts at once.+const OLD_PROCESS = `+import { createAppRelauncher, relaunchApp } from './app-relaunch'++const [exe, death] = process.argv.slice(2)+const events: string[] = []+const relauncher = createAppRelauncher(+ {+ commandLine: { hasSwitch: () => false },+ relaunch: () => events.push('electron relaunch'),+ releaseSingleInstanceLock: () => events.push('release'),+ exit: code => {+ process.stdout.write([...events, 'exit ' + code].join(','))+ process.exit(code)+ }+ },+ 'linux',+ exe,+ process.env+)++relaunchApp(relauncher, { args: ['--disable-gpu'] })+if (death === 'exit') relauncher.exit(0)+else process.kill(process.pid, 'SIGKILL')+`+// Electron's Linux relauncher sets PR_SET_NO_NEW_PRIVS on the new process; the backend and// the agent's terminal inherit it and sudo refuses. The new process must be an ordinary child.test.skipIf(process.platform !== 'linux')(- 'a Linux relaunch starts this executable at exit, unlocked, in its own session, without no_new_privs',+ 'a Linux relaunch comes back after an exit or a hard death, unlocked, in its own session, without no_new_privs',async () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-relaunch-'))- const report = path.join(dir, 'report')const exe = path.join(dir, 'hermes')- const events: string[] = []+ const oldProcess = path.join(dir, 'old-process.cjs')fs.writeFileSync(exe,- `#!/bin/sh\nprintf '%s\\n' "$*" "$(cut -d' ' -f6 /proc/$$/stat) $$" "$(grep NoNewPrivs /proc/$$/status)" > "${report}.part"\nmv "${report}.part" "${report}"\n`,+ `#!/bin/sh\nprintf '%s\\n' "$*" "$(cut -d' ' -f6 /proc/$$/stat) $$" "$(grep NoNewPrivs /proc/$$/status)" > "$REPORT.part"\nmv "$REPORT.part" "$REPORT"\n`,{ mode: 0o755 })+ buildSync({+ stdin: { contents: OLD_PROCESS, resolveDir: import.meta.dirname, loader: 'ts' },+ outfile: oldProcess,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ external: ['electron'],+ logLevel: 'silent'+ })try {- const env = { PATH: process.env.PATH, [LAUNCHER_READY_FD_ENV]: '4' }- const relauncher = createAppRelauncher(recordingApp(events), 'linux', exe, env)-- relaunchApp(relauncher, { args: ['--disable-gpu'] }, env)- // Scheduled only: the old process still owns the lock, its windows and the backend.- expect(events).toEqual([])-- relauncher.exit(0)-- await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })- const [args, session, privs] = fs.readFileSync(report, 'utf8').split('\n')- const [sid, pid] = session.split(' ')-- expect(events).toEqual(['release', 'exit 0'])- expect(args).toBe('--disable-gpu')- expect(sid).toBe(pid)- expect(noNewPrivs(privs)).toBe(noNewPrivs(fs.readFileSync('/proc/self/status', 'utf8')))+ for (const [death, events] of [+ ['exit', 'release,exit 0'],+ ['kill', '']+ ]) {+ const report = path.join(dir, `report-${death}`)++ const run = spawnSync(process.execPath, [oldProcess, exe, death], {+ encoding: 'utf8',+ env: { PATH: process.env.PATH, REPORT: report, [LAUNCHER_READY_FD_ENV]: '4' }+ })++ expect(run.stdout).toBe(events)+ await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })+ const [args, session, privs] = fs.readFileSync(report, 'utf8').split('\n')+ const [sid, pid] = session.split(' ')++ expect(args).toBe('--disable-gpu')+ expect(sid).toBe(pid)+ expect(noNewPrivs(privs)).toBe(noNewPrivs(fs.readFileSync('/proc/self/status', 'utf8')))+ }} finally {fs.rmSync(dir, { recursive: true, force: true })}diff --git a/apps/desktop/electron/app-relaunch.ts b/apps/desktop/electron/app-relaunch.tsindex f44d437288a..8b66ac639da 100644--- a/apps/desktop/electron/app-relaunch.ts+++ b/apps/desktop/electron/app-relaunch.ts@@ -1,17 +1,20 @@+import type { ChildProcess } from 'node:child_process'+import type { RelaunchOptions } from 'electron'import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'import { restoreLaunchTmpdir } from './linux-sandbox-relaunch'-import { canRelaunch, relaunchNow, relaunchTarget } from './relaunch-target'+import { canRelaunch, relaunchTarget, spawnRelaunch } from './relaunch-target'interface RelaunchHost {relaunch(options: RelaunchOptions): void}/**- * Every self-relaunch through Electron's app.relaunch (GPU fallbacks, update- * swap) goes through here; the Linux --no-sandbox early restart spawns its- * target itself (relaunch-target.ts relaunchNow) and drops the fd there.+ * Every self-relaunch site (GPU fallbacks, update swap) goes through here; the+ * Linux --no-sandbox early restart calls createAppRelauncher's relaunch+ * directly and drops the fd itself. Both start the new process through+ * createAppRelauncher.* The launcher's ready pipe is not inherited by the relaunched process, so a* carried `HERMES_DESKTOP_READY_FD` names whatever file reuses that descriptor* number there, and the reveal byte would be written into it.@@ -34,12 +37,13 @@ export interface AppRelauncher {* On Linux, Electron's relauncher starts the new process with* PR_SET_NO_NEW_PRIVS, which every descendant inherits: the backend and the* agent's terminal can no longer use sudo, pkexec or any setuid helper, and a- * FUSE-mounted AppImage cannot mount itself again. Linux therefore only- * records the relaunch, and `exit()` starts the target as an ordinary detached- * child right before exiting, after the backend is down and the- * single-instance lock is dropped, so the child 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.+ * 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.*/export function createAppRelauncher(app: AppRelauncher,@@ -51,7 +55,7 @@ export function createAppRelauncher(return app}- let pendingArgs: string[] | null = null+ let helper: ChildProcess | null = null// JS keeps running for a moment after app.exit(); a relaunch requested then would start a second child.let exiting = false@@ -59,34 +63,44 @@ export function createAppRelauncher(commandLine: app.commandLine,releaseSingleInstanceLock: () => app.releaseSingleInstanceLock(),relaunch: options => {- if (!exiting) {- pendingArgs = options.args ?? process.argv.slice(1)+ if (exiting) {+ return}- },- exit: code => {- exiting = true- try {- if (pendingArgs) {- // The new process skips `hermes desktop`: it needs the launcher's short socket TMPDIR,- // not the long one main.ts restored after the lock (linux-sandbox-relaunch.ts).- const childEnv = { ...env }- restoreLaunchTmpdir(childEnv)- const target = relaunchTarget(execPath, env)+ const args = options.args ?? process.argv.slice(1)+ const target = relaunchTarget(execPath, env)+ // The new process skips `hermes desktop`: it needs the launcher's short socket TMPDIR,+ // not the long one main.ts restored after the lock (linux-sandbox-relaunch.ts).+ const childEnv = { ...env }+ restoreLaunchTmpdir(childEnv)+ // The latest request wins.+ helper?.kill()+ helper = null- if (canRelaunch(target, 'relaunching through Electron instead', childEnv)) {- relaunchNow(app, pendingArgs, target, childEnv)- } else {- // The backend is already down: Electron's relauncher is the last way back.- app.relaunch({ args: pendingArgs })- }+ if (canRelaunch(target, 'relaunching through Electron instead', childEnv)) {+ try {+ helper = spawnRelaunch(target, args, childEnv, execPath)- pendingArgs = null+ return+ } catch (error) {+ // A synchronous spawn throw (E2BIG) must not cost the restart.+ console.error(+ `[hermes] relaunching ${target} failed (${String(error)}); relaunching through Electron instead`+ )}- } finally {- // A synchronous spawn throw (E2BIG) must not leave the app running with its lock released.- app.exit(code)}++ app.relaunch({ args })+ },+ exit: code => {+ exiting = true++ // The helper's target takes the lock once this process is gone.+ if (helper) {+ app.releaseSingleInstanceLock()+ }++ app.exit(code)}}}diff --git a/apps/desktop/electron/linux-sandbox-relaunch.test.ts b/apps/desktop/electron/linux-sandbox-relaunch.test.tsindex ecfe89cbc04..1fc07c15e17 100644--- a/apps/desktop/electron/linux-sandbox-relaunch.test.ts+++ b/apps/desktop/electron/linux-sandbox-relaunch.test.ts@@ -1,5 +1,5 @@import type * as childProcess from 'node:child_process'-import { type ChildProcess, spawn } from 'node:child_process'+import { spawn } from 'node:child_process'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -23,20 +23,6 @@ vi.mock('node:child_process', async importOriginal => {return { ...actual, spawn: vi.fn(actual.spawn) }})-// The next relaunch's spawn, recorded instead of run: under vitest the target-// would be node itself.-function recordNextSpawn(): { env?: NodeJS.ProcessEnv } {- const seen: { env?: NodeJS.ProcessEnv } = {}-- vi.mocked(spawn).mockImplementationOnce(((_file: string, _args: string[], options: { env?: NodeJS.ProcessEnv }) => {- seen.env = options.env-- return { on: () => undefined, unref: () => undefined } as unknown as ChildProcess- }) as typeof spawn)-- return seen-}-const argv = ['/opt/Hermes/hermes', '--ozone-platform=x11', 'hermes://session/abc']function restoreEnv(saved: NodeJS.ProcessEnv) {@@ -101,82 +87,6 @@ describe('Linux runtime --no-sandbox relaunch', () => {).toBeNull()})- // The relaunch skips `hermes desktop`, so it must not inherit the long TMPDIR- // main.ts restored after the lock: that path hangs requestSingleInstanceLock().- it.skipIf(process.platform !== 'linux')('relaunches with the short socket TMPDIR the launcher chose', async () => {- const saved = { ...process.env }- const shortDir = '/run/user/1000/hermes-desktop'- const longDir = `/home/u/.hermes/profiles/${'p'.repeat(80)}/cache/scratch`-- try {- process.env.TMPDIR = shortDir- process.env.HERMES_DESKTOP_TMPDIR = longDir- delete process.env.ELECTRON_DISABLE_SANDBOX- vi.resetModules()- const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')-- // main.ts: the lock is held, the backend's directory comes back.- process.env.TMPDIR = longDir- delete process.env.HERMES_DESKTOP_TMPDIR-- const relaunch = recordNextSpawn()-- const relaunched = relaunchIfNoSandboxCameTooLate(- {- commandLine: { hasSwitch: name => name === 'no-sandbox' },- releaseSingleInstanceLock: () => undefined,- exit: () => undefined- },- () => undefined- )-- expect(relaunched).toBe(true)- expect(relaunch.env?.TMPDIR).toBe(shortDir)- expect(relaunch.env?.HERMES_DESKTOP_TMPDIR).toBe(longDir)- } finally {- restoreEnv(saved)- }- })-- // Hermes started from another app's AppImage (an IDE or terminal) inherits- // that app's APPDIR/APPIMAGE and its mount on PATH and LD_LIBRARY_PATH;- // app.relaunch kept them, so the restart must start Hermes with that env whole.- it.skipIf(process.platform !== 'linux')("restarts with another app's AppImage env intact", async () => {- const saved = { ...process.env }- const mount = '/tmp/.mount_IdeAbC123'-- const foreign = {- APPDIR: mount,- APPIMAGE: '/home/u/Apps/Ide.AppImage',- LD_LIBRARY_PATH: `${mount}/usr/lib`,- PATH: `${mount}/usr/bin:/usr/local/bin:/usr/bin:/bin`,- SHELL: `${mount}/usr/bin/zsh`- }-- try {- delete process.env.ELECTRON_DISABLE_SANDBOX- delete process.env.HERMES_DESKTOP_TMPDIR- Object.assign(process.env, foreign)- vi.resetModules()- const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')- const relaunch = recordNextSpawn()-- const relaunched = relaunchIfNoSandboxCameTooLate(- {- commandLine: { hasSwitch: name => name === 'no-sandbox' },- releaseSingleInstanceLock: () => undefined,- exit: () => undefined- },- () => undefined- )-- expect(relaunched).toBe(true)- expect(relaunch.env).toMatchObject(foreign)- } finally {- restoreEnv(saved)- }- })-// main.ts wires the NVIDIA recovery's cleanExit in: the restart happens after// createNvidiaEglRecovery wrote its `booting` witness, and the next launch// must not read that deliberate exit as a GPU abort mid-boot.@@ -204,12 +114,11 @@ describe('Linux runtime --no-sandbox relaunch', () => {vi.resetModules()const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')const recovery = launch()- recordNextSpawn()const relaunched = relaunchIfNoSandboxCameTooLate({commandLine: { hasSwitch: name => name === 'no-sandbox' },- releaseSingleInstanceLock: () => undefined,+ relaunch: () => undefined,exit: () => undefined},() => recovery.cleanExit()@@ -263,12 +172,11 @@ describe('Linux runtime --no-sandbox relaunch', () => {] as const) {writeLinuxGpuMarker(userData, prior)const decision = launch()- recordNextSpawn()relaunchIfNoSandboxCameTooLate({commandLine: { hasSwitch: name => name === 'no-sandbox' },- releaseSingleInstanceLock: () => undefined,+ relaunch: () => undefined,exit: () => undefined},() => clearLinuxGpuBootMarker(userData, decision.nextMarker.state === 'fallback')@@ -283,64 +191,10 @@ describe('Linux runtime --no-sandbox relaunch', () => {})- // Electron's relauncher execs with PR_SET_NO_NEW_PRIVS, inherited by the- // backend and the agent's terminal: sudo and pkexec would stop working for- // good. An unpacked app restarts as an ordinary child instead.- it.skipIf(process.platform !== 'linux')(- 'restarts an unpacked app as an ordinary child that can still gain privileges',- async () => {- const saved = { ...process.env }- const savedArgv = process.argv- const savedExecPath = process.execPath- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-unpacked-relaunch-'))- const report = path.join(dir, 'report')- const exe = path.join(dir, 'hermes')- const events: string[] = []-- fs.writeFileSync(- exe,- `#!/bin/sh\nprintf '%s\\n' "$*" "$(grep NoNewPrivs /proc/self/status | tr -d ' \\t')" > "${report}.part"\nmv "${report}.part" "${report}"\n`,- { mode: 0o755 }- )-- try {- delete process.env.ELECTRON_DISABLE_SANDBOX- delete process.env.APPIMAGE- delete process.env.APPDIR- process.argv = [exe, 'hermes://session/abc']- process.execPath = exe- vi.resetModules()- const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')-- relaunchIfNoSandboxCameTooLate(- {- commandLine: { hasSwitch: name => name === 'no-sandbox' },- relaunch: () => events.push('electron-relaunch'),- releaseSingleInstanceLock: () => events.push('release'),- exit: () => events.push('exit')- } as Parameters<typeof relaunchIfNoSandboxCameTooLate>[0],- () => undefined- )-- await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })- const [args, noNewPrivs] = fs.readFileSync(report, 'utf8').split('\n')-- expect(events).toEqual(['release', 'exit'])- expect(args).toBe('hermes://session/abc --no-sandbox')- expect(noNewPrivs).toBe(fs.readFileSync('/proc/self/status', 'utf8').match(/NoNewPrivs:\s*(\d)/)?.[0].replace(/\s/g, ''))- } finally {- process.argv = savedArgv- process.execPath = savedExecPath- restoreEnv(saved)- fs.rmSync(dir, { recursive: true, force: true })- }- }- )-// Electron's relauncher execs its target with PR_SET_NO_NEW_PRIVS: the image's// runtime then cannot FUSE-mount, and the old mount dies with this process.it.skipIf(process.platform !== 'linux')(- 'starts a mounted AppImage again as a detached child after dropping the lock',+ 'starts a mounted AppImage again as a detached child once this process is gone',async () => {const saved = { ...process.env }const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-appimage-relaunch-'))@@ -362,26 +216,32 @@ describe('Linux runtime --no-sandbox relaunch', () => {delete process.env.ELECTRON_DISABLE_SANDBOXvi.resetModules()const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')+ const { createAppRelauncher } = await import('./app-relaunch')process.env.TMPDIR = dirdelete process.env.HERMES_DESKTOP_TMPDIRprocess.env.APPIMAGE = imageprocess.env.APPDIR = path.dirname(process.execPath)- relaunchIfNoSandboxCameTooLate(+ const relauncher = createAppRelauncher({commandLine: { hasSwitch: name => name === 'no-sandbox' },+ relaunch: () => events.push('electron relaunch'),releaseSingleInstanceLock: () => events.push('release'),- exit: () => events.push('exit')+ exit: code => events.push(`exit ${code}`)},- () => undefined+ 'linux')+ relaunchIfNoSandboxCameTooLate(relauncher, () => events.push('beforeExit'))+ expect(events).toEqual(['beforeExit', 'release', 'exit 0'])+ // This process is gone: the waiting helper's stdin closes.+ vi.mocked(spawn).mock.results.at(-1)!.value.stdin.end()+await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })const [args, session, tmpdir, readyFd] = fs.readFileSync(report, 'utf8').split('\n')const [sid, pid] = session.split(' ')- expect(events).toEqual(['release', 'exit'])expect(args.split(' ').at(-1)).toBe('--no-sandbox')// Its own session: nothing that ends this process's session takes it down.expect(sid).toBe(pid)diff --git a/apps/desktop/electron/linux-sandbox-relaunch.ts b/apps/desktop/electron/linux-sandbox-relaunch.tsindex 5119e43f491..92169ff134b 100644--- a/apps/desktop/electron/linux-sandbox-relaunch.ts+++ b/apps/desktop/electron/linux-sandbox-relaunch.ts@@ -17,7 +17,7 @@// `hermes desktop` — restarts once with the flag on argv instead.import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'-import { canRelaunch, type RelaunchHost, relaunchNow, relaunchTarget } from './relaunch-target'+import { canRelaunch, relaunchTarget } from './relaunch-target'import { alreadyHasNoSandbox, buildNoSandboxRelaunchArgs } from './windows-sandbox-fallback'export interface SandboxRelaunch {@@ -71,8 +71,10 @@ export function linuxNoSandboxRelaunch(options: {}}-interface SandboxRelaunchHost extends RelaunchHost {+/** The app's relauncher (app-relaunch.ts createAppRelauncher), which owns how the target starts. */+interface SandboxRelaunchHost {commandLine: { hasSwitch(name: string): boolean }+ relaunch(options: { args: string[] }): voidexit(code: number): void}@@ -100,10 +102,8 @@ export function relaunchIfNoSandboxCameTooLate(host: SandboxRelaunchHost, before// number would make the next process write its reveal byte into whatever// file reuses that descriptor.delete process.env[LAUNCHER_READY_FD_ENV]- restoreLaunchTmpdir(process.env)- // Before the relaunch: the target starts at once and reads the boot witnesses.+ host.relaunch({ args: relaunch.args })beforeExit()- relaunchNow(host, relaunch.args, relaunch.target, process.env)host.exit(0)return truediff --git a/apps/desktop/electron/relaunch-target.test.ts b/apps/desktop/electron/relaunch-target.test.tsindex 8f4e33f4086..d0d731eb67a 100644--- a/apps/desktop/electron/relaunch-target.test.ts+++ b/apps/desktop/electron/relaunch-target.test.ts@@ -6,7 +6,7 @@ import path from 'node:path'import { describe, expect, it, vi } from 'vitest'-import { ownAppImage, relaunchNow } from './relaunch-target'+import { ownAppImage, spawnRelaunch } from './relaunch-target'vi.mock('node:child_process', async importOriginal => {const actual = await importOriginal<typeof childProcess>()@@ -42,13 +42,13 @@ describe('ownAppImage', () => {})})-describe('relaunchNow', () => {+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// mount and its squashfuse daemon alive for the new app's whole life; once// it is closed, the new image must not look anything up through that mount.- // A spawn error arrives after the caller exited, so an image that cannot run- // must keep this instance, its lock and its env instead.+ // A spawn error can arrive after the caller exited, so an image that cannot+ // run must keep this instance, its lock and its env instead.it.skipIf(process.platform !== 'linux')('starts the image free of this mount, and stays put when it cannot',async () => {@@ -71,7 +71,7 @@ describe('relaunchNow', () => {relaunchIfNoSandboxCameTooLate({commandLine: { hasSwitch: name => name === 'no-sandbox' },- releaseSingleInstanceLock: () => events.push('release'),+ relaunch: () => events.push('relaunch'),exit: () => events.push('exit')},() => events.push('beforeExit')@@ -86,7 +86,7 @@ describe('relaunchNow', () => {{ mode: 0o755 })// Node marks every inherited fd close-on-exec at startup and Electron's- // main does not, so the command relaunchNow spawns runs from a shell+ // 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.const realSpawn = (await vi.importActual<typeof childProcess>('node:child_process')).spawn@@ -96,15 +96,16 @@ describe('relaunchNow', () => {fs.writeFileSync(held, '')// This mount's AppRun prepended it to PATH; the mount is gone soon after the child starts.const mount = path.join(dir, '.mount_HermesQ7x2Lp')- relaunchNow(- { releaseSingleInstanceLock: () => events.push('release') },- [],- image,- { ...process.env, APPDIR: mount, PATH: `${mount}:${mount}/usr/sbin:/usr/bin:/bin` }- )+ const helper = spawnRelaunch(image, [], {+ ...process.env,+ APPDIR: mount,+ PATH: `${mount}:${mount}/usr/sbin:/usr/bin:/bin`+ })++ // The helper's stdin closes when this process is gone.+ helper.stdin!.end()await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })- expect(events).toEqual(['release'])const [childPath, ...fds] = fs.readFileSync(report, 'utf8').split('\n')expect(childPath).toBe('/usr/bin:/bin')expect(fds.join('\n')).not.toContain(held)@@ -133,10 +134,9 @@ describe('relaunchNow', () => {const mount = '/run/user/1000/.mount_HermesQ7x2Lp'const image = '/home/u/Apps/Hermes.AppImage'- relaunchNow(- { releaseSingleInstanceLock: () => undefined },- [],+ spawnRelaunch(image,+ [],{APPIMAGE: image,LD_LIBRARY_PATH: `${mount}/usr/lib`,@@ -165,12 +165,10 @@ describe('relaunchNow', () => {// 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')).spawnvi.mocked(spawn).mockImplementationOnce((file, args, options) =>- realSpawn(file, args, { ...options, stdio: [...Array<'ignore'>(12).fill('ignore'), fd] })+ realSpawn(file, args, { ...options, stdio: ['pipe', ...Array<'ignore'>(11).fill('ignore'), fd] }))- relaunchNow({ releaseSingleInstanceLock: () => {} }, [], exe, {- PATH: process.env.PATH- })+ spawnRelaunch(exe, [], { PATH: process.env.PATH }).stdin!.end()await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })expect(fs.readFileSync(report, 'utf8')).not.toContain(held)diff --git a/apps/desktop/electron/relaunch-target.ts b/apps/desktop/electron/relaunch-target.tsindex 4a685e1a4b4..780b57a0013 100644--- a/apps/desktop/electron/relaunch-target.ts+++ b/apps/desktop/electron/relaunch-target.ts@@ -1,4 +1,4 @@-import { spawn } from 'node:child_process'+import { type ChildProcess, spawn } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'@@ -73,10 +73,6 @@ export function relaunchTarget(execPath: string = process.execPath, env: NodeJS.return image && !extracted ? image : execPath}-export interface RelaunchHost {- releaseSingleInstanceLock(): void-}-function executableError(file: string): string | null {try {fs.accessSync(file, fs.constants.X_OK)@@ -88,7 +84,7 @@ function executableError(file: string): string | null {}/**- * The shell that runs EXEC_WITH_STDIO_ONLY. dash (Debian/Ubuntu /bin/sh)+ * The shell that runs EXEC_AFTER_EXIT. dash (Debian/Ubuntu /bin/sh)* cannot name fds above 9, and after `ready` Chromium holds dozens there, so* bash closes them where it exists. `-p` keeps BASH_ENV, ENV and exported* functions from running in it while still passing them to the image; bash@@ -111,7 +107,7 @@ function trampolineShell(env: NodeJS.ProcessEnv): { file: string; args: string[]/*** Whether `target` can start this app again. A spawn failure is reported- * asynchronously, after the caller has already exited, so the target and the+ * asynchronously, possibly after the caller has exited, so the target and the* shell that starts it are checked up front and a refusal is logged now with* what the caller does instead.*/@@ -133,15 +129,22 @@ export function canRelaunch(return true}+// 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.+//// libuv's spawn keeps every descriptor this process inherited without// O_CLOEXEC, which Chromium's launcher (app.relaunch) closes. Ours include the// AppImage runtime's keepalive pipe, whose last reader keeps this process's// FUSE mount and squashfuse daemon alive, and the launcher's ready pipe. The// child therefore goes through a shell (trampolineShell), which drops every fd-// above 2 and then execs the image. POSIX only promises redirections on fds+// above 2 and then execs the target. POSIX only promises redirections on fds// 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_WITH_STDIO_ONLY = `big=+const EXEC_AFTER_EXIT = `while read -r _; do :; done+exec </dev/null+big=(eval 'exec 10<&-') 2>/dev/null && big=1for f in /proc/self/fd/*; don=\${f##*/}@@ -207,22 +210,24 @@ function withoutMountEntries(env: NodeJS.ProcessEnv, execPath: string): NodeJS.P}/**- * Start `target` with `args` as an ordinary detached child; the caller exits- * right after. Electron's relauncher (app.relaunch) execs with- * PR_SET_NO_NEW_PRIVS, which every descendant inherits: sudo, pkexec and any- * setuid helper stop working in the backend and the agent's terminal, and a- * relaunched AppImage runtime cannot mount through the setuid fusermount.- * Check `canRelaunch(target)` first. The child takes the single-instance lock- * itself, so the lock is dropped first.+ * Start `target` with `args` once this process is gone, as an ordinary+ * detached child: Electron's relauncher execs with PR_SET_NO_NEW_PRIVS, which+ * locks sudo, pkexec and FUSE out of the new app and all its descendants.+ * Check `canRelaunch(target)` first; kill the returned helper to cancel.*/-export function relaunchNow(- host: RelaunchHost,+export function spawnRelaunch(+ target: string,args: string[],- target: string = relaunchTarget(),env: NodeJS.ProcessEnv = process.env,execPath: string = process.execPath-): void {- host.releaseSingleInstanceLock()+): ChildProcess {+ const shell = trampolineShell(env)++ if (shell.fallback) {+ console.warn(+ `[hermes] relaunching through /bin/sh (${shell.fallback}); file descriptors above 9 may stay open in the new process`+ )+ }// Only a restart of our own image file (relaunchTarget returns it only when// ownAppImage claims it) drops the dying mount. Any other target keeps the env@@ -231,20 +236,15 @@ export function relaunchNow(// restores, and another app's AppImage env is the user's, as app.relaunch kept it.const ownImage = env.APPIMAGE && posix.resolve(target) === posix.resolve(env.APPIMAGE)const childEnv = ownImage ? withoutMountEntries(env, execPath) : env- const shell = trampolineShell(env)- if (shell.fallback) {- console.warn(- `[hermes] relaunching through /bin/sh (${shell.fallback}); file descriptors above 9 may stay open in the new process`- )- }-- const child = spawn(shell.file, [...shell.args, '-c', EXEC_WITH_STDIO_ONLY, target, ...args], {+ const child = spawn(shell.file, [...shell.args, '-c', EXEC_AFTER_EXIT, target, ...args], {detached: true,- stdio: 'ignore',+ stdio: ['pipe', 'ignore', 'ignore'],env: childEnv})child.on('error', error => console.error(`[hermes] relaunching ${target} failed: ${error.message}`))child.unref()++ return child}