The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the AppImage relaunch frees the old mount and survives an unrunnable image
Tekniumb15eb10717cf
diff --git a/apps/desktop/electron/linux-sandbox-relaunch.ts b/apps/desktop/electron/linux-sandbox-relaunch.tsindex ca17caa0638..ea4a14a67b9 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 { type RelaunchHost, relaunchNow, type RelaunchStrategy, relaunchStrategy } from './relaunch-target'+import { canRelaunch, type RelaunchHost, relaunchNow, type RelaunchStrategy, relaunchStrategy } from './relaunch-target'import { alreadyHasNoSandbox, buildNoSandboxRelaunchArgs } from './windows-sandbox-fallback'export interface SandboxRelaunch {@@ -85,7 +85,9 @@ export function relaunchIfNoSandboxCameTooLate(host: SandboxRelaunchHost): booleenv: process.env})- if (!relaunch) {+ // An image that cannot start leaves this instance running, as before the+ // relaunch existed, instead of exiting with nothing to replace it.+ if (!relaunch || !canRelaunch(relaunch.strategy)) {return false}diff --git a/apps/desktop/electron/relaunch-target.test.ts b/apps/desktop/electron/relaunch-target.test.tsindex a66e8937f0d..83223300587 100644--- a/apps/desktop/electron/relaunch-target.test.ts+++ b/apps/desktop/electron/relaunch-target.test.ts@@ -1,10 +1,18 @@+import type * as childProcess 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'-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'-import { ownAppImage } from './relaunch-target'+import { ownAppImage, relaunchNow } from './relaunch-target'++vi.mock('node:child_process', async importOriginal => {+ const actual = await importOriginal<typeof childProcess>()++ return { ...actual, spawn: vi.fn(actual.spawn) }+})describe('ownAppImage', () => {// The runtime builds APPDIR from the raw $TMPDIR; process.execPath has its@@ -33,3 +41,81 @@ describe('ownAppImage', () => {}})})++describe('relaunchNow', () => {+ // 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.+ it.skipIf(process.platform !== 'linux')(+ 'starts the image free of this mount, and stays put when it cannot',+ async () => {+ const saved = { ...process.env }+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-relaunch-fds-'))+ const image = path.join(dir, 'Hermes.AppImage')+ const report = path.join(dir, 'fds')+ const held = path.join(dir, 'held')+ const events: string[] = []++ try {+ process.env.TMPDIR = dir+ process.env.APPIMAGE = image+ process.env.APPDIR = path.dirname(process.execPath)+ delete process.env.ELECTRON_DISABLE_SANDBOX+ vi.resetModules()+ const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')++ expect(+ relaunchIfNoSandboxCameTooLate({+ commandLine: { hasSwitch: name => name === 'no-sandbox' },+ relaunch: () => events.push('relaunch'),+ releaseSingleInstanceLock: () => events.push('release'),+ exit: () => events.push('exit')+ })+ ).toBe(false)+ expect(events).toEqual([])+ expect(process.env.TMPDIR).toBe(dir)++ fs.writeFileSync(+ image,+ `#!/bin/sh\n{ echo "$PATH"; ls -l /proc/$$/fd; } > "${report}.part"\nmv "${report}.part" "${report}"\n`,+ { 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+ // 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+ vi.mocked(spawn).mockImplementationOnce((file, args, options) =>+ realSpawn('/bin/sh', ['-c', 'exec 3<"$0" 9<"$0"; exec "$@"', held, file, ...args], options)+ )+ 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(+ { relaunch: () => events.push('relaunch'), releaseSingleInstanceLock: () => events.push('release') },+ [],+ { kind: 'appimage', image },+ { ...process.env, APPDIR: mount, PATH: `${mount}:${mount}/usr/sbin:/usr/bin:/bin` }+ )++ 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)+ } finally {+ for (const key of Object.keys(process.env)) {+ if (!(key in saved)) {+ delete process.env[key]+ }+ }++ Object.assign(process.env, saved)+ fs.rmSync(dir, { recursive: true, force: true })+ }+ }+ )+})diff --git a/apps/desktop/electron/relaunch-target.ts b/apps/desktop/electron/relaunch-target.tsindex 4971a9f68fe..71c51fb717a 100644--- a/apps/desktop/electron/relaunch-target.ts+++ b/apps/desktop/electron/relaunch-target.ts@@ -92,10 +92,91 @@ export interface RelaunchHost {releaseSingleInstanceLock(): void}+/**+ * Whether `strategy` can start this app again. A spawn failure is reported+ * asynchronously, after the caller has already exited, so the image is+ * checked up front and a refusal is logged now; the caller then keeps running+ * in place of the relaunch.+ */+export function canRelaunch(strategy: RelaunchStrategy): boolean {+ if (strategy.kind === 'electron') {+ return true+ }++ try {+ fs.accessSync(strategy.image, fs.constants.X_OK)++ return true+ } catch (error) {+ const reason = (error as NodeJS.ErrnoException).code ?? String(error)+ console.error(`[hermes] cannot start ${strategy.image} again (${reason}); continuing without the relaunch`)++ return false+ }+}++// 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.+const EXEC_WITH_STDIO_ONLY = `big=+(eval 'exec 10<&-') 2>/dev/null && big=1+for f in /proc/self/fd/*; do+ n=\${f##*/}+ case $n in+ 0 | 1 | 2) continue ;;+ [3-9]) ;;+ *) [ -n "$big" ] || continue ;;+ esac+ eval "exec $n<&-"+done+exec "$0" "$@"`++/**+ * `env` without the PATH-style entries inside this mount, which the image's+ * AppRun prepended (PATH, LD_LIBRARY_PATH, XDG_DATA_DIRS, ...). The new+ * image's AppRun prepends its own, while this mount goes away as soon as the+ * child stops holding it: a lookup through it while its FUSE daemon exits+ * fails with ENOTCONN, which aborted the new AppRun's `env bash`.+ */+function withoutMountEntries(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ const appDir = env.APPDIR && posix.resolve(env.APPDIR)++ if (!appDir) {+ return env+ }++ const inMount = (entry: string) => entry === appDir || entry.startsWith(`${appDir}/`)+ const cleaned: NodeJS.ProcessEnv = { ...env }++ for (const [key, value] of Object.entries(env)) {+ const entries = value?.split(':') ?? []++ if (!entries.some(inMount)) {+ continue+ }++ const kept = entries.filter(entry => !inMount(entry)).join(':')++ if (kept) {+ cleaned[key] = kept+ } else {+ delete cleaned[key]+ }+ }++ return cleaned+}+/*** Start this app again with `args`; the caller exits right after.- * The detached child outlives this process (and its mount) and takes the- * single-instance lock itself, so the lock is dropped first.+ * Check `canRelaunch(strategy)` first. The detached child outlives this+ * process (and its mount) and takes the single-instance lock itself, so the+ * lock is dropped first.*/export function relaunchNow(host: RelaunchHost,@@ -110,7 +191,13 @@ export function relaunchNow(}host.releaseSingleInstanceLock()- const child = spawn(strategy.image, args, { detached: true, stdio: 'ignore', env })++ const child = spawn('/bin/sh', ['-c', EXEC_WITH_STDIO_ONLY, strategy.image, ...args], {+ detached: true,+ stdio: 'ignore',+ env: withoutMountEntries(env)+ })+child.on('error', error => console.error(`[hermes] relaunching ${strategy.image} failed: ${error.message}`))child.unref()}