The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): publish the owned detached backend PID once
ethernetf22ca4b297a9
diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.tsindex b5640e46ba5..37accb15f07 100644--- a/apps/desktop/electron/managed-ssh-update.test.ts+++ b/apps/desktop/electron/managed-ssh-update.test.ts@@ -1,6 +1,6 @@import assert from 'node:assert/strict'import { exec as execCallback } from 'node:child_process'-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'import os from 'node:os'import path from 'node:path'import { promisify } from 'node:util'@@ -280,38 +280,61 @@ test('POSIX managed launcher is detached, correlation-scoped, and never publisheassert.match(command, /while \[ ! -e/)})-test.runIf(process.platform !== 'win32')('POSIX managed launcher executes the updater command and atomically publishes its status', async () => {- const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-launch-'))+test.runIf(process.platform !== 'win32').each([0, 23])(+ 'POSIX managed launcher executes the updater command and atomically publishes status %i',+ async (exitCode: number): Promise<void> => {+ const home: string = await mkdtemp(path.join(os.tmpdir(), 'hermes managed launch '))+ const shell: string = (await exec('command -v bash', { shell: 'bash' })).stdout.trim()+ const launcher: string = path.join(home, 'hermes launcher')++ try {+ await writeFile(+ launcher,+ `#!${shell}\nprintf '%s\\n' "$@" "$HERMES_HOME" "$HERMES_UPDATE_CORRELATION_ID" "$HERMES_UPDATE_ORIGIN_PROFILE" "$HERMES_UPDATE_ORIGIN_HOME" "$HERMES_UPDATE_OUTPUT_PATH"\nexit ${exitCode}\n`,+ { encoding: 'utf8', mode: 0o700 }+ )++ const command: string = buildPosixManagedUpdateLaunch(+ {+ ssh: { exec: async (): Promise<string> => '' },+ platform: 'Linux',+ hermesPath: launcher,+ hermesHome: home+ },+ CORRELATION+ )- try {- const command = buildPosixManagedUpdateLaunch(- {- ssh: { exec: async () => '' },- platform: 'Linux',- hermesPath: '/bin/true',- hermesHome: home- },- CORRELATION- )+ const { stdout, stderr } = await exec(command, { shell, env: { ...process.env, HOME: home, HERMES_HOME: home } })+ const statusPath: string = path.join(home, `.update_exit_code.${CORRELATION}`)+ const logPath: string = path.join(home, 'logs', `desktop-update-${CORRELATION}.log`)+ let status: string | undefined++ for (let attempt: number = 0; attempt < 100; attempt += 1) {+ try {+ status = await readFile(statusPath, 'utf8')- const { stdout } = await exec(command, { shell: '/bin/sh' })- const statusPath = path.join(home, `.update_exit_code.${CORRELATION}`)- let status = ''+ break+ } catch (error: unknown) {+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) {+ throw error+ }- for (let attempt = 0; attempt < 50 && !status; attempt += 1) {- try {- status = await readFile(statusPath, 'utf8')- } catch {- await new Promise(resolve => setTimeout(resolve, 10))+ await new Promise<void>(resolve => setTimeout(resolve, 25))+ }}- }- assert.match(stdout, /MANAGED_UPDATE_STARTED/)- assert.equal(status, '0')- } finally {- await rm(home, { force: true, recursive: true })+ const log: string = await readFile(logPath, 'utf8')+ assert.match(stdout, /MANAGED_UPDATE_STARTED/)+ assert.equal(stderr, '')+ assert.equal(status, String(exitCode), `updater output: ${log}`)+ assert.deepEqual(log.trimEnd().split('\n'), ['update', '--yes', home, CORRELATION, 'default', home, logPath])+ assert.equal((await stat(statusPath)).mode & 0o777, 0o600)+ assert.equal((await readdir(home)).some((name: string): boolean => name.endsWith('.tmp')), false)+ } finally {+ await rm(home, { force: true, recursive: true })+ }}-})+)test('Windows managed launcher starts a hidden child and leaves exit 75 to the external coordinator', () => {const command = buildWindowsManagedUpdateLaunch(@@ -388,7 +411,7 @@ test.runIf(process.platform !== 'win32')('POSIX observer reads the exact correlaCORRELATION)- const { stdout } = await exec(command, { shell: '/bin/sh' })+ const { stdout } = await exec(command, { shell: 'sh' })const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)assert.equal(parsed.marker, 'absent')@@ -419,7 +442,7 @@ test.runIf(process.platform !== 'win32')('managed observer unwraps a named profiCORRELATION)- const { stdout } = await exec(command, { shell: '/bin/sh' })+ const { stdout } = await exec(command, { shell: 'sh' })const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)assert.equal(parsed.marker, 'live')diff --git a/apps/desktop/electron/remote-lifecycle-spawn.test.ts b/apps/desktop/electron/remote-lifecycle-spawn.test.tsnew file mode 100644index 00000000000..a61f99ec834--- /dev/null+++ b/apps/desktop/electron/remote-lifecycle-spawn.test.ts@@ -0,0 +1,310 @@+import assert from 'node:assert/strict'+import { type ChildProcess, exec as execCallback, type ExecOptionsWithStringEncoding, spawn } from 'node:child_process'+import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'++import { expect, test } from 'vitest'++import {+ buildSpawnCommand,+ cleanupStale,+ connectReservationPath,+ expandRemotePath,+ fingerprintToken,+ LOCKFILE_SCHEMA_VERSION,+ lockfilePath,+ pidIsOurDashboard,+ PROTOCOL_VERSION,+ readLockfile,+ spawnLogPath,+ spawnTokenPath+} from './remote-lifecycle'+import type { SshConnection } from './ssh-connection'++const exec: (command: string, options?: ExecOptionsWithStringEncoding) => Promise<{ stdout: string; stderr: string }> =+ promisify(execCallback)++const ownershipId: string = '0123456789abcdef0123456789abcdef'+const spawnNonce: string = '0123456789abcdef'+interface SpawnVariant {+ launcher: 'setsid' | 'nohup'+ owned: boolean+}++const variants: SpawnVariant[] = [+ ...(process.platform === 'linux'+ ? [+ { launcher: 'setsid' as const, owned: false },+ { launcher: 'setsid' as const, owned: true }+ ]+ : []),+ { launcher: 'nohup', owned: false },+ { launcher: 'nohup', owned: true }+]++interface ChildReport {+ pid: number+ sessionId: number+ hupIgnored: boolean+ mutexFds: number[]+}++interface SpawnLock {+ schemaVersion: number+ ownershipId: string+ spawnNonce: string+ pid: number+ port: number+ profile: string+ hermesPath: string+ hermesHome: string+ logPath: string+ tokenFingerprint: string+ protocolVersion: number+ startedAt: string+}++interface SpawnFixture {+ root: string+ shell: string+ env: NodeJS.ProcessEnv+ command: string+ lock: SpawnLock+ marker: string+ run: (command: string) => Promise<{ stdout: string; stderr: string }>+ ssh: Pick<SshConnection, 'exec'>+ localPath: (remotePath: string) => string+ dispose: () => Promise<void>+}++async function spawnFixture(launcher: 'setsid' | 'nohup', owned: boolean): Promise<SpawnFixture> {+ const root: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-spawn-'))+ const bin: string = path.join(root, 'bin')+ const shell: string = (await exec('command -v sh', { shell: 'sh' })).stdout.trim()+ const localPath = (remotePath: string): string => remotePath.replace(/^~/, root)+ const env: NodeJS.ProcessEnv = { HOME: root, HERMES_HOME: path.join(root, '.hermes'), PATH: bin, LANG: 'C.UTF-8' }++ const run = async (command: string): Promise<{ stdout: string; stderr: string }> =>+ exec(command, { shell, env, timeout: 10_000 })++ const ssh: Pick<SshConnection, 'exec'> = {+ exec: async (command: string): Promise<string> => (await run(command)).stdout+ }++ const hermesPath: string = path.join(root, 'fake hermes')+ const hermesHome: string = path.join(root, '.hermes')+ const marker: string = path.join(hermesHome, '.hermes-update-in-progress')++ const lock: SpawnLock = {+ schemaVersion: LOCKFILE_SCHEMA_VERSION,+ ownershipId,+ spawnNonce,+ pid: 0,+ port: 0,+ profile: 'ops__PID__',+ hermesPath,+ hermesHome,+ logPath: spawnLogPath(ownershipId, spawnNonce),+ tokenFingerprint: fingerprintToken('fixture-token'),+ protocolVersion: PROTOCOL_VERSION,+ startedAt: new Date().toISOString()+ }++ await mkdir(bin)+ await mkdir(hermesHome)+ await mkdir(path.join(root, 'reports'))++ // Restrict capability discovery, not the reported host OS. The fallback runs+ // real nohup with no setsid executable anywhere on the child's PATH.+ for (const tool of [+ 'sh',+ 'python3',+ 'mkdir',+ 'dirname',+ 'rm',+ 'cat',+ 'sed',+ 'head',+ 'sleep',+ 'mv',+ 'env',+ 'ps',+ launcher+ ]) {+ const executable: string = (await exec(`command -v ${tool}`, { shell })).stdout.trim()+ await symlink(executable, path.join(bin, tool))+ }++ await writeFile(+ hermesPath,+ `#!${path.join(bin, 'python3')}+import json,os,signal,time+from pathlib import Path+pid=os.getpid()+mutex=Path(os.environ['HERMES_HOME'])/'.hermes-update-in-progress.mutex'+identity=mutex.stat()+fds=[]+for fd in range(3,256):+ try:+ candidate=os.fstat(fd)+ if (candidate.st_dev,candidate.st_ino)==(identity.st_dev,identity.st_ino):fds.append(fd)+ except OSError:pass+report={'pid':pid,'sessionId':os.getsid(0),'hupIgnored':signal.getsignal(signal.SIGHUP)==signal.SIG_IGN,'mutexFds':fds}+p=Path(os.environ['HOME'])/'reports'/str(pid)+p.with_suffix('.tmp').write_text(json.dumps(report),encoding='utf-8')+p.with_suffix('.tmp').replace(p)+time.sleep(30)+`,+ { encoding: 'utf8', mode: 0o700 }+ )++ const command: string = buildSpawnCommand(hermesPath, lock.profile, {+ hermesHome,+ logPath: lock.logPath,+ spawnNonce,+ tokenFilePath: spawnTokenPath(ownershipId, spawnNonce),+ ownershipId: owned ? ownershipId : undefined,+ reservationNonce: spawnNonce,+ lockMetadata: owned ? lock : undefined+ })++ const dispose = async (): Promise<void> => {+ for (const name of await readdir(path.join(root, 'reports'))) {+ if (!/^[1-9][0-9]*$/.test(name)) {+ continue+ }++ const report: ChildReport = JSON.parse(await readFile(path.join(root, 'reports', name), 'utf8'))++ try {+ if (await pidIsOurDashboard(ssh, report.pid, spawnNonce, hermesPath, hermesHome, ownershipId, lock.profile)) {+ process.kill(report.pid, 'SIGKILL')+ }+ } catch (error) {+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) {+ throw error+ }+ }+ }++ await rm(root, { recursive: true, force: true })+ }++ return { root, shell, env, command, lock, marker, run, ssh, localPath, dispose }+}++async function reports(fixture: SpawnFixture): Promise<ChildReport[]> {+ const names: string[] = (await readdir(path.join(fixture.root, 'reports'))).filter((name: string): boolean =>+ /^[1-9][0-9]*$/.test(name)+ )++ return Promise.all(+ names.map(async (name: string): Promise<ChildReport> =>+ JSON.parse(await readFile(path.join(fixture.root, 'reports', name), 'utf8'))+ )+ )+}++test.skipIf(process.platform === 'win32').each(variants)(+ '$launcher spawn (ownership=$owned) returns only the detached child PID and preserves ownership',+ async ({ launcher, owned }: SpawnVariant): Promise<void> => {+ const fixture: SpawnFixture = await spawnFixture(launcher, owned)++ const foreign: ChildProcess = spawn('python3', ['-c', 'import time;time.sleep(30)'], {+ env: fixture.env,+ stdio: 'ignore'+ })++ assert.ok(foreign.pid)++ try {+ const parentSession: number = Number(+ (await fixture.run('python3 -c "import os;print(os.getsid(0))"')).stdout.trim()+ )++ const results: { stdout: string; stderr: string }[] = await Promise.all(+ Array.from({ length: owned ? 2 : 1 }, (): Promise<{ stdout: string; stderr: string }> =>+ fixture.run(fixture.command)+ )+ )++ const result: { stdout: string; stderr: string } | undefined = results.find(+ (output: { stdout: string }): boolean => output.stdout !== 'EXISTING'+ )++ assert.ok(result)++ if (owned) {+ assert.equal(results.filter((output: { stdout: string }): boolean => output.stdout === 'EXISTING').length, 1)+ }++ await expect.poll(async (): Promise<number> => (await reports(fixture)).length, { timeout: 5_000 }).toBe(1)+ const [report]: ChildReport[] = await reports(fixture)+ assert.match(result.stdout, /^[1-9][0-9]*\n$/)+ assert.equal(result.stdout.trim(), String(report.pid))+ assert.equal(result.stderr, '')+ assert.deepEqual(report.mutexFds, [])+ assert.ok(process.kill(report.pid, 0), 'the reported child survives the spawning shell exiting')++ if (launcher === 'setsid') {+ assert.notEqual(report.sessionId, parentSession)+ } else {+ assert.equal(report.sessionId, parentSession)+ assert.equal(report.hupIgnored, true)+ process.kill(report.pid, 'SIGHUP')+ }++ // The child remains alive while another process acquires the exact mutex.+ await fixture.run(+ `python3 -c 'import fcntl,sys;f=open(sys.argv[1],"a");fcntl.flock(f,fcntl.LOCK_EX|fcntl.LOCK_NB)' ${expandRemotePath(`${fixture.marker}.mutex`)}`+ )+ const lock: SpawnLock = { ...fixture.lock, pid: report.pid }++ if (owned) {+ assert.deepEqual(JSON.parse(await readFile(fixture.localPath(lockfilePath(ownershipId)), 'utf8')), lock)+ assert.deepEqual(await readLockfile(fixture.ssh, ownershipId), lock)+ assert.equal((await fixture.run(fixture.command)).stdout, 'EXISTING')+ assert.equal((await reports(fixture)).length, 1)+ assert.ok(+ !(await readdir(path.dirname(fixture.localPath(lockfilePath(ownershipId))))).some((name: string): boolean =>+ name.endsWith('.tmp')+ )+ )+ }++ await assert.rejects(readFile(fixture.localPath(connectReservationPath(ownershipId))), { code: 'ENOENT' })+ await cleanupStale(fixture.ssh, ownershipId, { ...lock, pid: foreign.pid, logPath: '' })+ assert.ok(process.kill(foreign.pid, 0), 'a foreign process is never killed by cleanup')+ await cleanupStale(fixture.ssh, ownershipId, lock)+ assert.ok(process.kill(foreign.pid, 0), 'owned cleanup leaves the unrelated child alive')+ assert.throws((): boolean => process.kill(report.pid, 0), { code: 'ESRCH' })+ await assert.rejects(readFile(fixture.localPath(lockfilePath(ownershipId))), { code: 'ENOENT' })+ } finally {+ foreign.kill('SIGKILL')+ await fixture.dispose()+ }+ },+ 20_000+)++test.skipIf(process.platform === 'win32').each(variants)(+ '$launcher spawn (ownership=$owned) refuses live or malformed update markers without reserving an owner',+ async ({ launcher, owned }: SpawnVariant): Promise<void> => {+ const fixture: SpawnFixture = await spawnFixture(launcher, owned)++ try {+ for (const marker of [`${process.pid}\n0\n`, 'not-a-pid\n']) {+ await writeFile(fixture.marker, marker, 'utf8')+ await assert.rejects(fixture.run(fixture.command), { code: 75, stdout: '' })+ assert.deepEqual(await reports(fixture), [])+ await assert.rejects(readFile(fixture.localPath(connectReservationPath(ownershipId))), { code: 'ENOENT' })+ await assert.rejects(readFile(fixture.localPath(lockfilePath(ownershipId))), { code: 'ENOENT' })+ }+ } finally {+ await fixture.dispose()+ }+ },+ 20_000+)diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.tsindex 0989d435a8f..1fbb6d2e23a 100644--- a/apps/desktop/electron/remote-lifecycle.test.ts+++ b/apps/desktop/electron/remote-lifecycle.test.ts@@ -40,6 +40,7 @@ import {validateRemotePath,writeLockfile} from './remote-lifecycle'+import type { SshConnection } from './ssh-connection'const OWNERSHIP_ID = '0123456789abcdef0123456789abcdef'const SPAWN_NONCE = '0123456789abcdef'@@ -573,20 +574,22 @@ test('pidIsOurDashboard accepts the venv entrypoint an installer wrapper execs itest.skipIf(process.platform === 'win32')('pidIsOurDashboard recognizes an installer wrapper after it execs python + entrypoint',- async () => {- const temp = await mkdtemp(path.join(os.tmpdir(), 'hermes wrapper ownership '))+ async (): Promise<void> => {+ const shell: string = (await exec('command -v bash', { shell: 'bash' })).stdout.trim()+ const temp: string = await mkdtemp(path.join(os.tmpdir(), 'hermes wrapper ownership '))const installDir = path.join(temp, 'install dir')const venvBin = path.join(installDir, 'venv', 'bin')const pythonLink = path.join(venvBin, 'python')const entrypoint = path.join(installDir, 'hermes')const launcher = path.join(temp, 'hermes launcher')- const python = (await exec('command -v python3')).stdout.trim()- const tokenPath = path.join(os.homedir(), spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE).replace(/^~\//, ''))+ const python: string = (await exec('command -v python3', { shell })).stdout.trim()+ const tokenPath: string = path.join(temp, spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE).replace(/^~\//, ''))+ const env: NodeJS.ProcessEnv = { ...process.env, HOME: temp, HERMES_HOME: temp }await mkdir(venvBin, { recursive: true })await symlink(python, pythonLink)await writeFile(entrypoint, 'import time\ntime.sleep(30)\n', 'utf8')- await writeFile(launcher, `#!/usr/bin/env bash\nexec "${pythonLink}" "${entrypoint}" "$@"\n`, 'utf8')+ await writeFile(launcher, `#!${shell}\nexec "${pythonLink}" "${entrypoint}" "$@"\n`, 'utf8')await chmod(launcher, 0o755)const backendFlags = [@@ -602,8 +605,8 @@ test.skipIf(process.platform === 'win32')(const children: ReturnType<typeof spawn>[] = []- const spawnInstaller = (args: string[]) => {- const process = spawn(launcher, args, { stdio: 'ignore' })+ const spawnInstaller = (args: string[]): ReturnType<typeof spawn> => {+ const process: ReturnType<typeof spawn> = spawn(launcher, args, { stdio: 'ignore', env })children.push(process)@@ -612,13 +615,13 @@ test.skipIf(process.platform === 'win32')(const child = spawnInstaller(['--profile', 'ops', 'serve', '--isolated', ...backendFlags])- const ssh = {- exec: async (command: string) => (await exec(command, { shell: '/bin/bash' })).stdout+ const ssh: Pick<SshConnection, 'exec'> = {+ exec: async (command: string): Promise<string> => (await exec(command, { shell, env })).stdout}- const waitForEntrypoint = async (process: ReturnType<typeof spawn>) => {- for (let attempt = 0; attempt < 40; attempt += 1) {- const command = (await exec(`ps -ww -o command= -p ${process.pid}`)).stdout+ const waitForEntrypoint = async (process: ReturnType<typeof spawn>): Promise<boolean> => {+ for (let attempt: number = 0; attempt < 100; attempt += 1) {+ const command: string = (await exec(`ps -ww -o command= -p ${process.pid}`, { shell, env })).stdoutif (command.includes(entrypoint)) {return true@@ -827,42 +830,45 @@ test('buildSpawnCommand atomically reserves the ownership slot through spawn andassert.ok(cmd.indexOf('lock_json') > cmd.indexOf('serve --isolated'))})-test.skipIf(process.platform === 'win32')('detached backend does not inherit the update mutex descriptor', async () => {- const directory = await mkdtemp(path.join(os.tmpdir(), 'hermes-update-mutex-'))- const hermesPath = path.join(directory, 'hermes')- const reportPath = path.join(directory, 'descriptor-report')- const logPath = path.join(directory, 'spawn.log')+test.skipIf(process.platform === 'win32')('detached backend does not inherit the update mutex descriptor', async (): Promise<void> => {+ const shell: string = (await exec('command -v bash', { shell: 'bash' })).stdout.trim()+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-update-mutex-'))+ const hermesPath: string = path.join(directory, 'hermes')+ const reportPath: string = path.join(directory, 'descriptor-report')+ const logPath: string = path.join(directory, 'spawn.log')try {await writeFile(hermesPath,- `#!/bin/sh-: > ${reportPath}+ `#!${shell}+report=${expandRemotePath(reportPath)}+: > "$report.tmp"for fd in /proc/$$/fd/*; dotarget=$(readlink "$fd" 2>/dev/null || true)case "$target" in- *hermes-update-in-progress.mutex) printf '%s\\n' "$target" >> ${reportPath} ;;+ *hermes-update-in-progress.mutex) printf '%s\\n' "$target" >> "$report.tmp" ;;esacdone+mv "$report.tmp" "$report"`,- { mode: 0o700 }+ { encoding: 'utf8', mode: 0o700 })- const command = buildSpawnCommand(hermesPath, '', {+ const command: string = buildSpawnCommand(hermesPath, '', {hermesHome: path.join(directory, 'home'),logPath})- await exec(command, { shell: '/bin/bash' })+ await exec(command, { shell, env: { ...process.env, HOME: directory, HERMES_HOME: directory } })- for (let attempt = 0; attempt < 40; attempt += 1) {+ for (let attempt: number = 0; attempt < 100; attempt += 1) {try {- const report = await readFile(reportPath, 'utf8')+ const report: string = await readFile(reportPath, 'utf8')assert.equal(report, '', 'the backend process must not retain the update mutex descriptor')return- } catch (error: any) {- if (error?.code !== 'ENOENT') {+ } catch (error: unknown) {+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) {throw error}@@ -1497,24 +1503,6 @@ test('buildSpawnCommand payload variables keep $HOME expandable (no double quoti}})-test('buildSpawnCommand lockfile publication is POSIX sh (no bash substitution)', () => {- const cmd = buildSpawnCommand('/x/hermes', 'work', {- hermesHome: '~/.hermes',- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),- ownershipId: OWNERSHIP_ID,- reservationNonce: SPAWN_NONCE,- spawnNonce: SPAWN_NONCE,- tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),- lockMetadata: { ownershipId: OWNERSHIP_ID, pid: '__PID__' }- })-- // ${var//pat/rep} is bash-only; dash aborts the payload on it AFTER the- // serve was spawned, so the client sees an unknown failure, deletes the- // token file, and orphans the backend.- assert.doesNotMatch(cmd, /\$\{lock_json\/\//, 'must not use ${var//} substitution under sh')- assert.ok(cmd.includes('sed "s/__PID__/${child}/"'), 'pid substitution must use sed')-})-test('spawnRemoteDashboard removes a token file when upload reporting fails', async () => {const failure = new Error('channel closed')@@ -1875,7 +1863,8 @@ test.skipIf(process.platform === 'win32')(})// Capture the argv a remote shell would hand to python3, via a shim on PATH.- const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-argv-shim-'))+ const shell: string = (await exec('command -v bash', { shell: 'bash' })).stdout.trim()+ const root: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-argv-shim-'))try {const shimDir = path.join(root, 'shim')@@ -1883,10 +1872,11 @@ test.skipIf(process.platform === 'win32')(await mkdir(shimDir)await mkdir(fakeHome)const argvFile = path.join(shimDir, 'argv')- await writeFile(path.join(shimDir, 'python3'), `#!/bin/sh\nprintf '%s\\0' "$@" > '${argvFile}'\n`, {+ await writeFile(path.join(shimDir, 'python3'), `#!${shell}\nprintf '%s\\0' "$@" > '${argvFile}'\n`, {mode: 0o755})await exec(cmd, {+ shell: 'sh',env: { ...process.env, PATH: `${shimDir}:${process.env.PATH}`, HOME: fakeHome }})const argv = (await readFile(argvFile, 'utf8')).split('\0')@@ -1907,6 +1897,7 @@ test.skipIf(process.platform === 'win32')(const { stdout } = await exec(`${payload.slice(0, loopStart)} printf '%s\\n' "$reservation" "$lock" "$owner_file"`,{+ shell: 'sh',env: { ...process.env, HOME: fakeHome }})diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.tsindex cf38b4752d8..7c4d0647e1b 100644--- a/apps/desktop/electron/remote-lifecycle.ts+++ b/apps/desktop/electron/remote-lifecycle.ts@@ -1067,8 +1067,10 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {`ulimit -n ${REMOTE_NOFILE_SOFT_LIMIT} 2>/dev/null || true; ` +`exec env HERMES_DESKTOP=1${opts.guestOnboarding === true ? ' HERMES_GUEST_ONBOARDING=1' : ''} ${hermes} ${profileArgs}${subCmd}`- const detachedShell = `eval "exec $1>&-"; ${dashCmd} </dev/null >> ${logPath} 2>&1 & echo $!`- const detachedSpawn = `child=$("$(command -v setsid || echo nohup)" sh -c ${shq(detachedShell)} hermes-update-child "$1" & echo $!)`+ const detachedShell: string = `eval "exec $1>&-"; ${dashCmd} </dev/null >> ${logPath} 2>&1 & echo $!`+ // The inner shell backgrounds Hermes and reports its PID; backgrounding the+ // launcher too adds its unrelated PID to the value published in the lock.+ const detachedSpawn: string = `child=$("$(command -v setsid || echo nohup)" sh -c ${shq(detachedShell)} hermes-update-child "$1")`if (!opts.ownershipId || !opts.lockMetadata) {return withRemoteUpdateMutex(@@ -1111,8 +1113,9 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {// ${var//pat/rep} is a bashism — this payload runs under plain sh (dash// on Ubuntu), which aborts the whole script on it with "Bad// substitution" AFTER the child was spawned, orphaning the backend and- // skipping the lockfile publication. Substitute with sed instead.- `lock_json=$(printf '%s' ${shq(metadata)} | sed "s/__PID__/\${child}/"); ` ++ // skipping the lockfile publication. Replace the quoted PID field with+ // a JSON number so readLockfile and concurrent spawns accept the record.+ `lock_json=$(printf '%s' ${shq(metadata)} | sed "s/\\"pid\\":\\"__PID__\\"/\\"pid\\":\${child}/"); ` +`temporary_lock="\${lock}.${reservationNonce}.tmp"; ` +`printf '%s' "$lock_json" > "$temporary_lock" && mv -f "$temporary_lock" "$lock" || { kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 76; }; ` +`echo "$child"`,