Skip to content

The agent that grows with you

fix(desktop): Linux self-relaunches keep sudo working and come back from an AppImage

Tekniumd5c6fdb35a50
diff --git a/apps/desktop/electron/app-relaunch.test.ts b/apps/desktop/electron/app-relaunch.test.ts
index 35ea31e5d45..fb7b3f9b5b2 100644
--- a/apps/desktop/electron/app-relaunch.test.ts
+++ b/apps/desktop/electron/app-relaunch.test.ts
@@ -1,6 +1,10 @@
-import { expect, test } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
-import { relaunchApp } from './app-relaunch'
+import { expect, test, vi } from 'vitest'
+
+import { createAppRelauncher, relaunchApp } from './app-relaunch'
import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'
test('a self-relaunch never hands the launcher ready-pipe fd number to the new process', () => {
@@ -12,3 +16,68 @@ test('a self-relaunch never hands the launcher ready-pipe fd number to the new p
expect(seen).toEqual([{ args: ['--disable-gpu'], carried: undefined }])
expect(env.KEEP).toBe('1')
})
+
+function recordingApp(events: string[]) {
+ return {
+ commandLine: { hasSwitch: () => false },
+ relaunch: (options: { args?: string[] }) => events.push(`relaunch ${options.args?.join(' ')}`),
+ releaseSingleInstanceLock: () => events.push('release'),
+ exit: (code: number) => events.push(`exit ${code}`)
+ }
+}
+
+function noNewPrivs(statusText: string): string | undefined {
+ return /^NoNewPrivs:\s*(\d)/m.exec(statusText)?.[1]
+}
+
+// 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',
+ 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[] = []
+
+ fs.writeFileSync(
+ exe,
+ `#!/bin/sh\nprintf '%s\\n' "$*" "$(cut -d' ' -f6 /proc/$$/stat) $$" "$(grep NoNewPrivs /proc/$$/status)" > "${report}.part"\nmv "${report}.part" "${report}"\n`,
+ { mode: 0o755 }
+ )
+
+ 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')))
+ } 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[] = []
+ const relauncher = createAppRelauncher(recordingApp(events), platform, '/nonexistent/hermes', {})
+
+ relaunchApp(relauncher, { args: ['--no-sandbox'] }, {})
+ relauncher.exit(0)
+
+ expect(events).toEqual(['relaunch --no-sandbox', 'exit 0'])
+ }
+})
diff --git a/apps/desktop/electron/app-relaunch.ts b/apps/desktop/electron/app-relaunch.ts
index a2140be7520..2c73c0cf51c 100644
--- a/apps/desktop/electron/app-relaunch.ts
+++ b/apps/desktop/electron/app-relaunch.ts
@@ -1,6 +1,8 @@
import type { RelaunchOptions } from 'electron'
import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'
+import { restoreLaunchTmpdir } from './linux-sandbox-relaunch'
+import { relaunchNow, relaunchTarget } from './relaunch-target'
interface RelaunchHost {
relaunch(options: RelaunchOptions): void
@@ -18,3 +20,56 @@ export function relaunchApp(host: RelaunchHost, options: RelaunchOptions, env: N
delete env[LAUNCHER_READY_FD_ENV]
host.relaunch(options)
}
+
+export interface AppRelauncher {
+ commandLine: { hasSwitch(name: string): boolean }
+ relaunch(options: RelaunchOptions): void
+ releaseSingleInstanceLock(): void
+ exit(code: number): void
+}
+
+/**
+ * The `app` every relaunch site and the final exit go through.
+ *
+ * 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.
+ */
+export function createAppRelauncher(
+ app: AppRelauncher,
+ platform: NodeJS.Platform | string = process.platform,
+ execPath: string = process.execPath,
+ env: NodeJS.ProcessEnv = process.env
+): AppRelauncher {
+ if (platform !== 'linux') {
+ return app
+ }
+
+ let pendingArgs: string[] | null = null
+
+ return {
+ commandLine: app.commandLine,
+ releaseSingleInstanceLock: () => app.releaseSingleInstanceLock(),
+ relaunch: options => {
+ pendingArgs = options.args ?? process.argv.slice(1)
+ },
+ exit: code => {
+ 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)
+ relaunchNow(app, pendingArgs, relaunchTarget(execPath, env), childEnv)
+ pendingArgs = null
+ }
+
+ app.exit(code)
+ }
+ }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 854e94a1058..cf12dc19695 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -55,7 +55,7 @@ import {
} from './api-transport'
import { appIconCandidates, resolveAppIcon, shouldOverrideDockIcon } from './app-icon'
import { stageAppInstallerFile } from './app-installer-file'
-import { relaunchApp } from './app-relaunch'
+import { createAppRelauncher, relaunchApp } from './app-relaunch'
import {
appVersionInfo,
type AppVersionInfo,
@@ -751,6 +751,7 @@ function acquireSingleInstanceLock(): boolean {
}
const isPrimaryInstance: boolean = acquireSingleInstanceLock()
+const relauncher = createAppRelauncher(app)
if (!isPrimaryInstance) {
console.error('[hermes] another Hermes Desktop instance holds the single-instance lock; exiting')
@@ -935,7 +936,7 @@ const nvidiaEglRecovery = createNvidiaEglRecovery({
},
relaunch: extraArgs => {
// The persisted witness selects ANGLE next launch; argv carries it only when unwritable.
- relaunchApp(app, { args: [...process.argv.slice(1), ...extraArgs] })
+ relaunchApp(relauncher, { args: [...process.argv.slice(1), ...extraArgs] })
void exitAfterBackendShutdown(0)
}
})
@@ -1116,7 +1117,7 @@ if (IS_WINDOWS || process.platform === 'linux') {
)
try {
- relaunchApp(app, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
+ relaunchApp(relauncher, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
void exitAfterBackendShutdown(0)
} catch (error) {
console.error(`[hermes] --no-sandbox relaunch failed: ${error?.message || error}`)
@@ -1168,7 +1169,7 @@ if (IS_WINDOWS || process.platform === 'linux') {
)
try {
- relaunchApp(app, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
+ relaunchApp(relauncher, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
void exitAfterBackendShutdown(0)
} catch (error) {
console.error(`[hermes] --no-sandbox relaunch failed: ${error?.message || error}`)
@@ -1195,7 +1196,7 @@ if (IS_WINDOWS || process.platform === 'linux') {
)
try {
- relaunchApp(app, { args: buildDisableGpuRelaunchArgs(process.argv.slice(1)) })
+ relaunchApp(relauncher, { args: buildDisableGpuRelaunchArgs(process.argv.slice(1)) })
void exitAfterBackendShutdown(0)
} catch (error) {
console.error(`[hermes] --disable-gpu relaunch failed: ${error?.message || error}`)
@@ -1286,7 +1287,7 @@ let desktopSshPathOverride = ''
// Linux: a runtime `--no-sandbox` kills renderers on /dev/shm (linux-sandbox-relaunch.ts).
if (isPrimaryInstance) {
// A deliberate restart is no GPU failure: settle both ladders' boot witnesses before it.
- relaunchIfNoSandboxCameTooLate(app, () => {
+ relaunchIfNoSandboxCameTooLate(relauncher, () => {
nvidiaEglRecovery.cleanExit()
clearLinuxGpuBootMarker(app.getPath('userData'), linuxGpuFallbackSticky)
})
@@ -2852,7 +2853,7 @@ async function waitForUpdateToFinish() {
running: INSTALL_STAMP,
resourcesPath: process.resourcesPath,
relaunch: extraArgs =>
- relaunchApp(app, { args: [...buildNoSandboxRelaunchArgs(process.argv.slice(1)), ...extraArgs] }),
+ relaunchApp(relauncher, { args: [...buildNoSandboxRelaunchArgs(process.argv.slice(1)), ...extraArgs] }),
exit: () => void exitAfterBackendShutdown(0),
log: rememberLog
})
@@ -11688,7 +11689,7 @@ async function exitAfterBackendShutdown(code) {
// app.exit() skips will-quit, and every in-app relaunch lands here.
killTimedGitChildren()
- app.exit(code)
+ relauncher.exit(code)
}
// Returns the profile name whose backend was torn down, or null when the
@@ -13881,7 +13882,7 @@ function createWindow() {
)
try {
- relaunchApp(app, { args: buildDisableGpuRelaunchArgs(process.argv.slice(1)) })
+ relaunchApp(relauncher, { args: buildDisableGpuRelaunchArgs(process.argv.slice(1)) })
void exitAfterBackendShutdown(0)
} catch (err) {
rememberLog(`[renderer] GPU-disable relaunch failed: ${err?.message || err}`)
@@ -13935,7 +13936,7 @@ function createWindow() {
rememberLog('[renderer] Windows sandbox crash loop detected; relaunching once with --no-sandbox (#38216)')
try {
- relaunchApp(app, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
+ relaunchApp(relauncher, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
void exitAfterBackendShutdown(0)
} catch (err) {
rememberLog(`[renderer] --no-sandbox relaunch failed: ${err?.message || err}`)
@@ -17249,11 +17250,10 @@ ipcMain.handle('hermes:version', async (_event, scope?: { connectionId?: string;
// The About page's "Restart Hermes" button (shown when bundleSwapPending):
// load the already-swapped bundle without asking the user to quit manually.
-// app.relaunch() re-executes by path, so the fresh process picks up whatever
-// bundle now lives there.
+// The relaunch re-executes by path, so the fresh process loads the bundle now there.
ipcMain.handle('hermes:app:relaunch', async () => {
rememberLog('[updates] renderer requested an app relaunch (swapped bundle pending)')
- relaunchApp(app, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
+ relaunchApp(relauncher, { args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })
void exitAfterBackendShutdown(0)
})