The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the --no-sandbox early restart keeps sudo working in the backend
Teknium7fd71996d0d1
diff --git a/apps/desktop/electron/linux-sandbox-relaunch.test.ts b/apps/desktop/electron/linux-sandbox-relaunch.test.tsindex 1ff0d668e96..e32c9e1ede6 100644--- a/apps/desktop/electron/linux-sandbox-relaunch.test.ts+++ b/apps/desktop/electron/linux-sandbox-relaunch.test.ts@@ -1,3 +1,5 @@+import type * as childProcess from 'node:child_process'+import { type ChildProcess, spawn } from 'node:child_process'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -8,6 +10,26 @@ import { createLinuxGpuBootWindow } from './linux-gpu-fallback'import { createNvidiaEglRecovery } from './linux-nvidia-egl-recovery'import { linuxNoSandboxRelaunch } from './linux-sandbox-relaunch'+vi.mock('node:child_process', async importOriginal => {+ const actual = await importOriginal<typeof childProcess>()++ 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) {@@ -32,7 +54,7 @@ describe('Linux runtime --no-sandbox relaunch', () => {expect(relaunch).toEqual({args: ['--ozone-platform=x11', 'hermes://session/abc', '--no-sandbox'],- strategy: { kind: 'electron' }+ target: process.execPath})// The relaunched process started unsandboxed, so it never restarts again.@@ -90,14 +112,11 @@ describe('Linux runtime --no-sandbox relaunch', () => {process.env.TMPDIR = longDirdelete process.env.HERMES_DESKTOP_TMPDIR- let relaunchEnv: NodeJS.ProcessEnv = {}+ const relaunch = recordNextSpawn()const relaunched = relaunchIfNoSandboxCameTooLate({commandLine: { hasSwitch: name => name === 'no-sandbox' },- relaunch: () => {- relaunchEnv = { ...process.env }- },releaseSingleInstanceLock: () => undefined,exit: () => undefined},@@ -105,8 +124,8 @@ describe('Linux runtime --no-sandbox relaunch', () => {)expect(relaunched).toBe(true)- expect(relaunchEnv.TMPDIR).toBe(shortDir)- expect(relaunchEnv.HERMES_DESKTOP_TMPDIR).toBe(longDir)+ expect(relaunch.env?.TMPDIR).toBe(shortDir)+ expect(relaunch.env?.HERMES_DESKTOP_TMPDIR).toBe(longDir)} finally {restoreEnv(saved)}@@ -139,11 +158,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' },- relaunch: () => undefined,releaseSingleInstanceLock: () => undefined,exit: () => undefined},@@ -158,6 +177,60 @@ 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')(@@ -192,7 +265,6 @@ describe('Linux runtime --no-sandbox relaunch', () => {relaunchIfNoSandboxCameTooLate({commandLine: { hasSwitch: name => name === 'no-sandbox' },- relaunch: () => events.push('relaunch'),releaseSingleInstanceLock: () => events.push('release'),exit: () => events.push('exit')},@@ -230,7 +302,7 @@ describe('Linux runtime --no-sandbox relaunch', () => {env: { APPIMAGE: '/home/u/Apps/Hermes.AppImage', APPDIR: appDir },launchedWithoutSandbox: false})- ).toEqual({ args: ['--no-sandbox'], strategy: { kind: 'electron' } })+ ).toEqual({ args: ['--no-sandbox'], target: `${appDir}/hermes` })})it('relaunches the AppImage itself rather than its vanishing mount', () => {@@ -245,7 +317,7 @@ describe('Linux runtime --no-sandbox relaunch', () => {expect(relaunch).toEqual({args: ['--no-sandbox'],- strategy: { kind: 'appimage', image: '/home/u/Apps/Hermes.AppImage' }+ target: '/home/u/Apps/Hermes.AppImage'})})@@ -263,7 +335,7 @@ describe('Linux runtime --no-sandbox relaunch', () => {expect(relaunch).toEqual({args: ['--no-sandbox'],- strategy: { kind: 'appimage', image: '/home/u/Apps/Hermes.AppImage' }+ target: '/home/u/Apps/Hermes.AppImage'})})@@ -286,7 +358,7 @@ describe('Linux runtime --no-sandbox relaunch', () => {})).toEqual({args: ['--ozone-platform=x11', 'hermes://session/abc', '--no-sandbox'],- strategy: { kind: 'electron' }+ target: '/opt/Hermes/hermes'})}})diff --git a/apps/desktop/electron/linux-sandbox-relaunch.ts b/apps/desktop/electron/linux-sandbox-relaunch.tsindex 4e51a526d64..5119e43f491 100644--- a/apps/desktop/electron/linux-sandbox-relaunch.ts+++ b/apps/desktop/electron/linux-sandbox-relaunch.ts@@ -17,12 +17,13 @@// `hermes desktop` — restarts once with the flag on argv instead.import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'-import { canRelaunch, type RelaunchHost, relaunchNow, type RelaunchStrategy, relaunchStrategy } from './relaunch-target'+import { canRelaunch, type RelaunchHost, relaunchNow, relaunchTarget } from './relaunch-target'import { alreadyHasNoSandbox, buildNoSandboxRelaunchArgs } from './windows-sandbox-fallback'export interface SandboxRelaunch {args: string[]- strategy: RelaunchStrategy+ /** The file the relaunch starts (relaunchTarget). */+ target: string}// Captured when this module is evaluated, before main.ts sets@@ -66,7 +67,7 @@ export function linuxNoSandboxRelaunch(options: {return {args: buildNoSandboxRelaunchArgs(options.argv.slice(1)),- strategy: relaunchStrategy(options.execPath ?? process.execPath, options.env)+ target: relaunchTarget(options.execPath ?? process.execPath, options.env)}}@@ -90,7 +91,7 @@ export function relaunchIfNoSandboxCameTooLate(host: SandboxRelaunchHost, before// 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)) {+ if (!relaunch || !canRelaunch(relaunch.target)) {return false}@@ -100,9 +101,9 @@ export function relaunchIfNoSandboxCameTooLate(host: SandboxRelaunchHost, before// file reuses that descriptor.delete process.env[LAUNCHER_READY_FD_ENV]restoreLaunchTmpdir(process.env)- // Before the relaunch: an AppImage target starts at once and reads the witness.+ // Before the relaunch: the target starts at once and reads the boot witnesses.beforeExit()- relaunchNow(host, relaunch.args, relaunch.strategy, process.env)+ 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 8dd298ff637..3a845dad30b 100644--- a/apps/desktop/electron/relaunch-target.test.ts+++ b/apps/desktop/electron/relaunch-target.test.ts@@ -71,7 +71,6 @@ describe('relaunchNow', () => {relaunchIfNoSandboxCameTooLate({commandLine: { hasSwitch: name => name === 'no-sandbox' },- relaunch: () => events.push('relaunch'),releaseSingleInstanceLock: () => events.push('release'),exit: () => events.push('exit')},@@ -98,9 +97,9 @@ describe('relaunchNow', () => {// 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') },+ { releaseSingleInstanceLock: () => events.push('release') },[],- { kind: 'appimage', image },+ image,{ ...process.env, APPDIR: mount, PATH: `${mount}:${mount}/usr/sbin:/usr/bin:/bin` })diff --git a/apps/desktop/electron/relaunch-target.ts b/apps/desktop/electron/relaunch-target.tsindex 71c51fb717a..5108115b28c 100644--- a/apps/desktop/electron/relaunch-target.ts+++ b/apps/desktop/electron/relaunch-target.ts@@ -57,59 +57,40 @@ export function ownAppImage(execPath: string, env: NodeJS.ProcessEnv): string |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 }-/**- * How this app starts itself again.+ * The file that starts this app 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.+ * process.execPath of a FUSE-mounted AppImage lives in this process's mount,+ * which the runtime unmounts as soon as we exit, so a mounted image relaunches+ * its image file. 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 relaunchStrategy(- execPath: string = process.execPath,- env: NodeJS.ProcessEnv = process.env-): RelaunchStrategy {+export function relaunchTarget(execPath: string = process.execPath, env: NodeJS.ProcessEnv = process.env): string {const image = ownAppImage(execPath, env)+ const extracted = env.APPDIR && posix.basename(posix.resolve(env.APPDIR)).startsWith('appimage_extracted_')- if (!image || (env.APPDIR && posix.basename(posix.resolve(env.APPDIR)).startsWith('appimage_extracted_'))) {- return { kind: 'electron' }- }-- return { kind: 'appimage', image }+ return image && !extracted ? image : execPath}export interface RelaunchHost {- relaunch(options: { args: string[] }): voidreleaseSingleInstanceLock(): void}/**- * Whether `strategy` can start this app again. A spawn failure is reported- * asynchronously, after the caller has already exited, so the image is+ * 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(strategy: RelaunchStrategy): boolean {- if (strategy.kind === 'electron') {- return true- }-+export function canRelaunch(target: string): boolean {try {- fs.accessSync(strategy.image, fs.constants.X_OK)+ fs.accessSync(target, 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`)+ console.error(`[hermes] cannot start ${target} again (${reason}); continuing without the relaunch`)return false}@@ -173,31 +154,33 @@ function withoutMountEntries(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {}/**- * Start this app again with `args`; the caller exits right after.- * 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.+ * 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.*/export function relaunchNow(host: RelaunchHost,args: string[],- strategy: RelaunchStrategy = relaunchStrategy(),+ target: string = relaunchTarget(),env: NodeJS.ProcessEnv = process.env): void {- if (strategy.kind === 'electron') {- host.relaunch({ args })-- return- }-host.releaseSingleInstanceLock()- const child = spawn('/bin/sh', ['-c', EXEC_WITH_STDIO_ONLY, strategy.image, ...args], {+ // The executable of an unpacked or extracted app lives in a directory that+ // outlives this process and that no AppRun re-enters: keep its environment.+ const appDir = env.APPDIR && posix.resolve(env.APPDIR)+ const childEnv = appDir && isInside(appDir, posix.resolve(target)) ? env : withoutMountEntries(env)++ const child = spawn('/bin/sh', ['-c', EXEC_WITH_STDIO_ONLY, target, ...args], {detached: true,stdio: 'ignore',- env: withoutMountEntries(env)+ env: childEnv})- child.on('error', error => console.error(`[hermes] relaunching ${strategy.image} failed: ${error.message}`))+ child.on('error', error => console.error(`[hermes] relaunching ${target} failed: ${error.message}`))child.unref()}