Skip to content

The agent that grows with you

fix(desktop): a genuine AppImage comes back from the --no-sandbox relaunch

Tekniuma51047836b84
diff --git a/apps/desktop/electron/linux-sandbox-relaunch.test.ts b/apps/desktop/electron/linux-sandbox-relaunch.test.ts
index 2cadea7a7df..e851272c9a2 100644
--- a/apps/desktop/electron/linux-sandbox-relaunch.test.ts
+++ b/apps/desktop/electron/linux-sandbox-relaunch.test.ts
@@ -1,9 +1,23 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
import { describe, expect, it, vi } from 'vitest'
import { linuxNoSandboxRelaunch } from './linux-sandbox-relaunch'
const argv = ['/opt/Hermes/hermes', '--ozone-platform=x11', 'hermes://session/abc']
+function restoreEnv(saved: NodeJS.ProcessEnv) {
+ for (const key of Object.keys(process.env)) {
+ if (!(key in saved)) {
+ delete process.env[key]
+ }
+ }
+
+ Object.assign(process.env, saved)
+}
+
describe('Linux runtime --no-sandbox relaunch', () => {
it('moves a runtime-only --no-sandbox onto argv exactly once', () => {
const relaunch = linuxNoSandboxRelaunch({
@@ -14,7 +28,10 @@ describe('Linux runtime --no-sandbox relaunch', () => {
launchedWithoutSandbox: false
})
- expect(relaunch).toEqual({ args: ['--ozone-platform=x11', 'hermes://session/abc', '--no-sandbox'] })
+ expect(relaunch).toEqual({
+ args: ['--ozone-platform=x11', 'hermes://session/abc', '--no-sandbox'],
+ strategy: { kind: 'electron' }
+ })
// The relaunched process started unsandboxed, so it never restarts again.
expect(
@@ -78,6 +95,7 @@ describe('Linux runtime --no-sandbox relaunch', () => {
relaunch: () => {
relaunchEnv = { ...process.env }
},
+ releaseSingleInstanceLock: () => undefined,
exit: () => undefined
})
@@ -85,14 +103,80 @@ describe('Linux runtime --no-sandbox relaunch', () => {
expect(relaunchEnv.TMPDIR).toBe(shortDir)
expect(relaunchEnv.HERMES_DESKTOP_TMPDIR).toBe(longDir)
} finally {
- for (const key of Object.keys(process.env)) {
- if (!(key in saved)) {
- delete process.env[key]
- }
- }
+ restoreEnv(saved)
+ }
+ })
- Object.assign(process.env, saved)
+ // 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',
+ async () => {
+ const saved = { ...process.env }
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-appimage-relaunch-'))
+ const report = path.join(dir, 'report')
+ const image = path.join(dir, 'Hermes.AppImage')
+ const shortDir = '/run/user/1000/hermes-desktop'
+ const events: string[] = []
+
+ fs.writeFileSync(
+ image,
+ `#!/bin/sh\nprintf '%s\\n' "$*" "$(cut -d' ' -f6 /proc/$$/stat) $$" "$TMPDIR" "\${HERMES_DESKTOP_READY_FD:-unset}" > "${report}.part"\nmv "${report}.part" "${report}"\n`,
+ { mode: 0o755 }
+ )
+
+ try {
+ process.env.TMPDIR = shortDir
+ process.env.HERMES_DESKTOP_TMPDIR = dir
+ process.env.HERMES_DESKTOP_READY_FD = '3'
+ delete process.env.ELECTRON_DISABLE_SANDBOX
+ vi.resetModules()
+ const { relaunchIfNoSandboxCameTooLate } = await import('./linux-sandbox-relaunch')
+
+ process.env.TMPDIR = dir
+ delete process.env.HERMES_DESKTOP_TMPDIR
+ process.env.APPIMAGE = image
+ process.env.APPDIR = path.dirname(process.execPath)
+
+ relaunchIfNoSandboxCameTooLate({
+ commandLine: { hasSwitch: name => name === 'no-sandbox' },
+ relaunch: () => events.push('relaunch'),
+ releaseSingleInstanceLock: () => events.push('release'),
+ exit: () => events.push('exit')
+ })
+
+ 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)
+ expect(tmpdir).toBe(shortDir)
+ expect(readyFd).toBe('unset')
+ } finally {
+ restoreEnv(saved)
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
}
+ )
+
+ // --appimage-extract-and-run users run without FUSE, which the image needs;
+ // the extracted directory is a plain one Electron can relaunch from.
+ it('relaunches the extracted executable of --appimage-extract-and-run, not the image', () => {
+ const appDir = '/run/user/1000/appimage_extracted_0123456789abcdef'
+
+ expect(
+ linuxNoSandboxRelaunch({
+ platform: 'linux',
+ runtimeNoSandbox: true,
+ argv: [`${appDir}/hermes`],
+ execPath: `${appDir}/hermes`,
+ env: { APPIMAGE: '/home/u/Apps/Hermes.AppImage', APPDIR: appDir },
+ launchedWithoutSandbox: false
+ })
+ ).toEqual({ args: ['--no-sandbox'], strategy: { kind: 'electron' } })
})
it('relaunches the AppImage itself rather than its vanishing mount', () => {
@@ -105,7 +189,10 @@ describe('Linux runtime --no-sandbox relaunch', () => {
launchedWithoutSandbox: false
})
- expect(relaunch).toEqual({ args: ['--no-sandbox'], execPath: '/home/u/Apps/Hermes.AppImage' })
+ expect(relaunch).toEqual({
+ args: ['--no-sandbox'],
+ strategy: { kind: 'appimage', image: '/home/u/Apps/Hermes.AppImage' }
+ })
})
// The type-2 runtime mounts under $TMPDIR/.mount_<name><random>; a launch that
@@ -120,7 +207,10 @@ describe('Linux runtime --no-sandbox relaunch', () => {
launchedWithoutSandbox: false
})
- expect(relaunch).toEqual({ args: ['--no-sandbox'], execPath: '/home/u/Apps/Hermes.AppImage' })
+ expect(relaunch).toEqual({
+ args: ['--no-sandbox'],
+ strategy: { kind: 'appimage', image: '/home/u/Apps/Hermes.AppImage' }
+ })
})
// AppImage apps (terminals, IDEs) export APPIMAGE/APPDIR to everything they
@@ -140,7 +230,10 @@ describe('Linux runtime --no-sandbox relaunch', () => {
env,
launchedWithoutSandbox: false
})
- ).toEqual({ args: ['--ozone-platform=x11', 'hermes://session/abc', '--no-sandbox'] })
+ ).toEqual({
+ args: ['--ozone-platform=x11', 'hermes://session/abc', '--no-sandbox'],
+ strategy: { kind: 'electron' }
+ })
}
})
})
diff --git a/apps/desktop/electron/linux-sandbox-relaunch.ts b/apps/desktop/electron/linux-sandbox-relaunch.ts
index 5df546a672b..ca17caa0638 100644
--- a/apps/desktop/electron/linux-sandbox-relaunch.ts
+++ b/apps/desktop/electron/linux-sandbox-relaunch.ts
@@ -17,12 +17,12 @@
// `hermes desktop` — restarts once with the flag on argv instead.
import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'
-import { relaunchExecPath } from './relaunch-target'
+import { type RelaunchHost, relaunchNow, type RelaunchStrategy, relaunchStrategy } from './relaunch-target'
import { alreadyHasNoSandbox, buildNoSandboxRelaunchArgs } from './windows-sandbox-fallback'
export interface SandboxRelaunch {
args: string[]
- execPath?: string
+ strategy: RelaunchStrategy
}
// Captured when this module is evaluated, before main.ts sets
@@ -64,21 +64,20 @@ export function linuxNoSandboxRelaunch(options: {
return null
}
- const args = buildNoSandboxRelaunchArgs(options.argv.slice(1))
- const execPath = relaunchExecPath(options.execPath ?? process.execPath, options.env)
-
- return execPath ? { args, execPath } : { args }
+ return {
+ args: buildNoSandboxRelaunchArgs(options.argv.slice(1)),
+ strategy: relaunchStrategy(options.execPath ?? process.execPath, options.env)
+ }
}
-interface RelaunchHost {
+interface SandboxRelaunchHost extends RelaunchHost {
commandLine: { hasSwitch(name: string): boolean }
- relaunch(options: SandboxRelaunch): void
exit(code: number): void
}
// Call once, in the lock-owning instance, after every runtime switch source
// (sandbox ladder, config.yaml) has run and before `ready`.
-export function relaunchIfNoSandboxCameTooLate(host: RelaunchHost): boolean {
+export function relaunchIfNoSandboxCameTooLate(host: SandboxRelaunchHost): boolean {
const relaunch = linuxNoSandboxRelaunch({
platform: process.platform,
runtimeNoSandbox: host.commandLine.hasSwitch('no-sandbox'),
@@ -96,7 +95,7 @@ export function relaunchIfNoSandboxCameTooLate(host: RelaunchHost): boolean {
// file reuses that descriptor.
delete process.env[LAUNCHER_READY_FD_ENV]
restoreLaunchTmpdir(process.env)
- host.relaunch(relaunch)
+ relaunchNow(host, relaunch.args, relaunch.strategy, process.env)
host.exit(0)
return true
diff --git a/apps/desktop/electron/relaunch-target.test.ts b/apps/desktop/electron/relaunch-target.test.ts
new file mode 100644
index 00000000000..a66e8937f0d
--- /dev/null
+++ b/apps/desktop/electron/relaunch-target.test.ts
@@ -0,0 +1,35 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { describe, expect, it } from 'vitest'
+
+import { ownAppImage } from './relaunch-target'
+
+describe('ownAppImage', () => {
+ // The runtime builds APPDIR from the raw $TMPDIR; process.execPath has its
+ // symlinks resolved (TMPDIR=~/tmp on Fedora Atomic, /home -> /var/home).
+ it.skipIf(process.platform === 'win32')('follows a symlinked TMPDIR to the mount it names', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-appdir-link-'))
+
+ try {
+ const mount = path.join(root, 'var-home', '.mount_HermesQ7x2Lp')
+ fs.mkdirSync(mount, { recursive: true })
+ fs.writeFileSync(path.join(mount, 'hermes'), '')
+ fs.mkdirSync(path.join(root, 'other', '.mount_HermesQ7x2Lp'), { recursive: true })
+ fs.symlinkSync(path.join(root, 'var-home'), path.join(root, 'home'))
+ fs.symlinkSync(path.join(root, 'other'), path.join(root, 'elsewhere'))
+ const exe = fs.realpathSync(path.join(mount, 'hermes'))
+ const appImage = '/home/u/Apps/Hermes.AppImage'
+
+ expect(ownAppImage(exe, { APPIMAGE: appImage, APPDIR: path.join(root, 'home', '.mount_HermesQ7x2Lp') })).toBe(
+ appImage
+ )
+ expect(
+ ownAppImage(exe, { APPIMAGE: appImage, APPDIR: path.join(root, 'elsewhere', '.mount_HermesQ7x2Lp') })
+ ).toBeUndefined()
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/apps/desktop/electron/relaunch-target.ts b/apps/desktop/electron/relaunch-target.ts
index d429ce5501b..4971a9f68fe 100644
--- a/apps/desktop/electron/relaunch-target.ts
+++ b/apps/desktop/electron/relaunch-target.ts
@@ -1,8 +1,24 @@
+import { spawn } from 'node:child_process'
+import fs from 'node:fs'
import path from 'node:path'
// AppImage is Linux-only; POSIX semantics keep the answer identical on every test host.
const posix = path.posix
+function isInside(dir: string, file: string): boolean {
+ const inside = posix.relative(dir, file)
+
+ return Boolean(inside) && !inside.startsWith('..') && !posix.isAbsolute(inside)
+}
+
+function realpathOrNull(target: string): string | null {
+ try {
+ return fs.realpathSync(target)
+ } catch {
+ return null
+ }
+}
+
/**
* The AppImage file this executable runs from, or undefined when it is not one.
*
@@ -29,19 +45,72 @@ export function ownAppImage(execPath: string, env: NodeJS.ProcessEnv): string |
return posix.dirname(exe).split('/').some(segment => segment.startsWith('.mount_')) ? appImage : undefined
}
- const inside = posix.relative(posix.resolve(appDir), exe)
+ if (isInside(posix.resolve(appDir), exe)) {
+ return appImage
+ }
+
+ // The runtime builds APPDIR from the raw $TMPDIR, while process.execPath has
+ // its symlinks resolved: TMPDIR=~/tmp on Fedora Atomic (/home -> /var/home).
+ const realAppDir = realpathOrNull(appDir)
+ const realExe = realpathOrNull(exe)
- return inside && !inside.startsWith('..') && !posix.isAbsolute(inside) ? appImage : undefined
+ return realAppDir && realExe && isInside(realAppDir, realExe) ? appImage : undefined
}
+export type RelaunchStrategy =
+ /** Electron's app.relaunch(): process.execPath again once this process exits. */
+ | { kind: 'electron' }
+ /** A FUSE-mounted AppImage: the image file again, started now as a detached child. */
+ | { kind: 'appimage'; image: string }
+
/**
- * The executable that starts this app again, or undefined for Electron's
- * default (process.execPath). A real AppImage runs from a mount that
- * disappears when this process exits, so it relaunches the image file instead.
+ * How this app starts itself again.
+ *
+ * Electron's relauncher execs its target with PR_SET_NO_NEW_PRIVS, so a
+ * relaunched AppImage runtime cannot mount through the setuid fusermount
+ * (EPERM, exit 127), and process.execPath lives in this process's FUSE mount,
+ * which the runtime unmounts as soon as we exit. A mounted AppImage therefore
+ * starts its image file as an ordinary child. Under --appimage-extract-and-run
+ * APPDIR is a plain directory and the image would need the FUSE those users
+ * lack, so the executable in it is relaunched as usual.
*/
-export function relaunchExecPath(
+export function relaunchStrategy(
execPath: string = process.execPath,
env: NodeJS.ProcessEnv = process.env
-): string | undefined {
- return ownAppImage(execPath, env)
+): RelaunchStrategy {
+ const image = ownAppImage(execPath, env)
+
+ if (!image || (env.APPDIR && posix.basename(posix.resolve(env.APPDIR)).startsWith('appimage_extracted_'))) {
+ return { kind: 'electron' }
+ }
+
+ return { kind: 'appimage', image }
+}
+
+export interface RelaunchHost {
+ relaunch(options: { args: string[] }): void
+ releaseSingleInstanceLock(): void
+}
+
+/**
+ * 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.
+ */
+export function relaunchNow(
+ host: RelaunchHost,
+ args: string[],
+ strategy: RelaunchStrategy = relaunchStrategy(),
+ env: NodeJS.ProcessEnv = process.env
+): void {
+ if (strategy.kind === 'electron') {
+ host.relaunch({ args })
+
+ return
+ }
+
+ host.releaseSingleInstanceLock()
+ const child = spawn(strategy.image, args, { detached: true, stdio: 'ignore', env })
+ child.on('error', error => console.error(`[hermes] relaunching ${strategy.image} failed: ${error.message}`))
+ child.unref()
}