The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): Linux relaunches close the old process's fds above 9
Teknium599087ec6130
diff --git a/apps/desktop/electron/app-relaunch.test.ts b/apps/desktop/electron/app-relaunch.test.tsindex fb7b3f9b5b2..b726433726c 100644--- a/apps/desktop/electron/app-relaunch.test.ts+++ b/apps/desktop/electron/app-relaunch.test.ts@@ -81,3 +81,30 @@ test('macOS and Windows keep Electron app.relaunch', () => {expect(events).toEqual(['relaunch --no-sandbox', 'exit 0'])}})++// The exit path runs after the backend is down: a target that cannot start falls back to+// Electron's relauncher. JS keeps running briefly after app.exit(), and a relaunch requested+// then (a second Restart) must not start another process.+test.skipIf(process.platform !== 'linux')('a Linux relaunch whose target cannot start uses Electron, once', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-relaunch-noexec-'))+ const exe = path.join(dir, 'hermes')+ const events: string[] = []+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {})++ fs.writeFileSync(exe, '', { mode: 0o644 })++ try {+ const relauncher = createAppRelauncher(recordingApp(events), 'linux', exe, { PATH: process.env.PATH })++ relaunchApp(relauncher, { args: ['--disable-gpu'] }, {})+ relauncher.exit(0)+ relaunchApp(relauncher, { args: ['--no-sandbox'] }, {})+ relauncher.exit(0)++ expect(events).toEqual(['relaunch --disable-gpu', 'exit 0', 'exit 0'])+ expect(logged).toHaveBeenCalledTimes(1)+ } finally {+ logged.mockRestore()+ fs.rmSync(dir, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/electron/app-relaunch.ts b/apps/desktop/electron/app-relaunch.tsindex 8467652529d..3ecce785587 100644--- a/apps/desktop/electron/app-relaunch.ts+++ b/apps/desktop/electron/app-relaunch.ts@@ -52,14 +52,20 @@ export function createAppRelauncher(}let pendingArgs: string[] | null = null+ // JS keeps running for a moment after app.exit(); a relaunch requested then would start a second child.+ let exiting = falsereturn {commandLine: app.commandLine,releaseSingleInstanceLock: () => app.releaseSingleInstanceLock(),relaunch: options => {- pendingArgs = options.args ?? process.argv.slice(1)+ if (!exiting) {+ pendingArgs = options.args ?? process.argv.slice(1)+ }},exit: code => {+ exiting = true+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).@@ -67,7 +73,7 @@ export function createAppRelauncher(restoreLaunchTmpdir(childEnv)const target = relaunchTarget(execPath, env)- if (canRelaunch(target)) {+ 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.diff --git a/apps/desktop/electron/relaunch-target.test.ts b/apps/desktop/electron/relaunch-target.test.tsindex 41f94bf382a..8f4e33f4086 100644--- a/apps/desktop/electron/relaunch-target.test.ts+++ b/apps/desktop/electron/relaunch-target.test.ts@@ -147,4 +147,36 @@ describe('relaunchNow', () => {expect(childEnv).toEqual({ APPIMAGE: image, PATH: '/tmp/.mount_IdeAbC123/usr/bin:/usr/bin' })})++ // After `ready` Chromium holds dozens of fds above 9 without O_CLOEXEC+ // (crashpad client socket, DevTools listener, caches); dash, Debian's+ // /bin/sh, cannot close them, and each relaunch carried the last one's.+ it.skipIf(process.platform !== 'linux')('starts the target without an fd above 9 this process holds', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-relaunch-high-fd-'))+ const exe = path.join(dir, 'hermes')+ const report = path.join(dir, 'fds')+ const held = path.join(dir, 'held')+ const fd = fs.openSync(held, 'w')++ try {+ fs.writeFileSync(exe, `#!/bin/sh\nls -l /proc/$$/fd > "${report}.part"\nmv "${report}.part" "${report}"\n`, {+ mode: 0o755+ })+ // 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: [...Array<'ignore'>(12).fill('ignore'), fd] })+ )++ relaunchNow({ releaseSingleInstanceLock: () => {} }, [], exe, {+ PATH: process.env.PATH+ })++ await vi.waitFor(() => expect(fs.existsSync(report)).toBe(true), { timeout: 5000 })+ expect(fs.readFileSync(report, 'utf8')).not.toContain(held)+ } finally {+ fs.closeSync(fd)+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })})diff --git a/apps/desktop/electron/relaunch-target.ts b/apps/desktop/electron/relaunch-target.tsindex 286c6184dda..1cc2876ff9f 100644--- a/apps/desktop/electron/relaunch-target.ts+++ b/apps/desktop/electron/relaunch-target.ts@@ -77,39 +77,70 @@ export interface RelaunchHost {releaseSingleInstanceLock(): void}-/**- * Whether `target` can start this app again. A spawn failure is reported- * asynchronously, after the caller has already exited, so the target is- * checked up front and a refusal is logged now; the caller then keeps running- * in place of the relaunch.- */-export function canRelaunch(target: string): boolean {+function executableError(file: string): string | null {try {- fs.accessSync(target, fs.constants.X_OK)+ fs.accessSync(file, fs.constants.X_OK)- return true+ return null} catch (error) {- const reason = (error as NodeJS.ErrnoException).code ?? String(error)- console.error(`[hermes] cannot start ${target} again (${reason}); continuing without the relaunch`)+ return (error as NodeJS.ErrnoException).code ?? String(error)+ }+}- return false+/**+ * The shell that runs EXEC_WITH_STDIO_ONLY. 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+ * rewrites an exported SHELLOPTS/BASHOPTS for its children, so an env that+ * carries one keeps /bin/sh.+ */+function trampolineShell(env: NodeJS.ProcessEnv): { file: string; args: string[] } {+ if (env.SHELLOPTS === undefined && env.BASHOPTS === undefined && !executableError('/bin/bash')) {+ return { file: '/bin/bash', args: ['-p'] }}++ return { file: '/bin/sh', args: [] }+}++/**+ * Whether `target` can start this app again. A spawn failure is reported+ * asynchronously, after the caller has already 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.+ */+export function canRelaunch(+ target: string,+ instead = 'continuing without the relaunch',+ env: NodeJS.ProcessEnv = process.env+): boolean {+ for (const file of [target, trampolineShell(env).file]) {+ const reason = executableError(file)++ if (reason) {+ console.error(`[hermes] cannot start ${file} (${reason}); ${instead}`)++ return false+ }+ }++ return true}// 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 /bin/sh, which drops every fd above 2 and then-// execs the image. 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.+// child therefore goes through a shell (trampolineShell), which drops every fd+// above 2 and then execs the image. 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=(eval 'exec 10<&-') 2>/dev/null && big=1for f in /proc/self/fd/*; don=\${f##*/}case $n in- 0 | 1 | 2) continue ;;+ 0 | 1 | 2 | '' | *[!0-9]*) continue ;;[3-9]) ;;*) [ -n "$big" ] || continue ;;esac@@ -194,8 +225,9 @@ 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)- const child = spawn('/bin/sh', ['-c', EXEC_WITH_STDIO_ONLY, target, ...args], {+ const child = spawn(shell.file, [...shell.args, '-c', EXEC_WITH_STDIO_ONLY, target, ...args], {detached: true,stdio: 'ignore',env: childEnv