diff --git a/cli/README.md b/cli/README.md index 460288fb..0a53aafd 100644 --- a/cli/README.md +++ b/cli/README.md @@ -332,6 +332,20 @@ bun scripts/tooling/hapi-display-image.mjs /absolute/path/to/image.png "optional completes the same session. Wait for that row or explicitly stop it rather than creating duplicates. Process exit and explicit stop still clean up the child. The Hub gives Codex spawn RPCs 60 seconds for preflight plus startup. +- On macOS, when the spawner's responsible process goes away with it (a runner + started by launchd, directly or through the npm launcher `bin/hapi.cjs`, + which passes `HAPI_LAUNCHER_PID`), every detached `spawnHappyCLI` child + (sessions, runner handoff, runner start) is started with + `HAPI_DISCLAIM_RESPONSIBILITY=`. In a direct child of that pid, + the entry hook clears the variable and re-executes the same executable in + place so the child becomes its own responsible process; the pid, stdio and + cwd are unchanged. Without this, a session kept alive across a runner restart + loses LAN access for every new process in its tree (macOS Local Network + check, `EHOSTUNREACH`) once the old runner is gone. Spawners started from + Terminal or SSH keep the inherited responsibility (and its implicit LAN + allowance). Binaries without the hook ignore the variable; any failure in the + hook falls back to a plain exec or to continuing in-process, and is logged. + Implementation: `src/runtime/disclaimExec.ts`, `src/runtime/responsibility.ts`. When changing agent bootstrap, handoff, or shared-session plumbing: diff --git a/cli/bin/hapi.cjs b/cli/bin/hapi.cjs index 777a2bdb..6bfdddd7 100755 --- a/cli/bin/hapi.cjs +++ b/cli/bin/hapi.cjs @@ -154,7 +154,12 @@ function main() { const args = process.argv.slice(2); try { - execFileSync(binPath, args, { stdio: 'inherit' }); + // The binary may hand this launcher's macOS responsibility on to the + // processes it detaches (see cli/src/runtime/responsibility.ts). + execFileSync(binPath, args, { + stdio: 'inherit', + env: { ...process.env, HAPI_LAUNCHER_PID: String(process.pid) }, + }); } catch (error) { const { status, signal } = reportExecutionFailure(error, binPath, args); diff --git a/cli/src/bin/hapiBin.test.ts b/cli/src/bin/hapiBin.test.ts index 30dd423e..58157e17 100644 --- a/cli/src/bin/hapiBin.test.ts +++ b/cli/src/bin/hapiBin.test.ts @@ -83,6 +83,23 @@ describe('hapi binary launcher package versions', () => { expect(result.stderr).not.toContain('Failed to execute:'); }); + it.skipIf(process.platform === 'win32')('passes its own pid to the platform binary as HAPI_LAUNCHER_PID', () => { + const binaryPath = installPlatformPackage(version); + mkdirSync(path.dirname(binaryPath), { recursive: true }); + writeFileSync(binaryPath, '#!/bin/sh\necho "$HAPI_LAUNCHER_PID $PPID $*"\n', { mode: 0o755 }); + + const result = spawnSync(process.execPath, [launcherPath, 'runner', 'start-sync'], { + encoding: 'utf-8', + env: { ...process.env, HAPI_LAUNCHER_PID: 'stale' }, + }); + + expect(result.status, result.stderr).toBe(0); + const [launcherPid, parentPid, ...args] = result.stdout.trim().split(' '); + expect(launcherPid).toMatch(/^\d+$/); + expect(launcherPid).toBe(parentPid); + expect(args).toEqual(['runner', 'start-sync']); + }); + it('still diagnoses a missing optional dependency', () => { expect(require(launcherPath).getBinaryPath()).toBeNull(); diff --git a/cli/src/index.test.ts b/cli/src/index.test.ts new file mode 100644 index 00000000..91ceced2 --- /dev/null +++ b/cli/src/index.test.ts @@ -0,0 +1,43 @@ +import { spawnSync } from 'node:child_process' +import { chmodSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const entry = path.resolve(import.meta.dirname, 'index.ts') +// chmod does not restrict writes on Windows or for root. +const canMakeReadOnly = process.platform !== 'win32' && process.getuid?.() !== 0 + +describe.skipIf(!canMakeReadOnly)('CLI entry point with an unwritable HAPI_HOME', () => { + let root: string + let env: NodeJS.ProcessEnv + + beforeEach(() => { + root = mkdtempSync(path.join(tmpdir(), 'hapi-entry-')) + const readOnly = path.join(root, 'read-only') + mkdirSync(readOnly) + chmodSync(readOnly, 0o555) + env = { ...process.env, HAPI_HOME: path.join(readOnly, 'home') } + delete env.HAPI_DISCLAIM_RESPONSIBILITY + delete env.HAPI_LAUNCHER_PID + }) + + afterEach(() => { + try { + chmodSync(path.join(root, 'read-only'), 0o755) + } catch { + // beforeEach failed before the directory existed. + } + rmSync(root, { recursive: true, force: true }) + }) + + it.each(['--version', '--help'])('prints %s without creating HAPI_HOME', (flag) => { + const result = spawnSync('bun', [entry, flag], { env, encoding: 'utf8', timeout: 30_000 }) + + expect(result.error).toBeUndefined() + expect(result.stderr).not.toMatch(/EACCES/) + expect(result.status).toBe(0) + expect(result.stdout.length).toBeGreaterThan(0) + }, 30_000) +}) diff --git a/cli/src/index.ts b/cli/src/index.ts index 44a1e6a7..4b5762ff 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -1,5 +1,26 @@ #!/usr/bin/env bun -import { runCli } from './commands/runCli' +import { handleDisclaimExecEntry, takeDisclaimFallbackNote } from './runtime/disclaimExec' -void runCli() +async function main(): Promise { + // Before the CLI module graph loads: the macOS responsibility re-exec must + // happen before any module side effects. + await handleDisclaimExecEntry() + const fallbackNote = takeDisclaimFallbackNote() + // Dependency-free, so `--help` and `--version` work even when HAPI_HOME cannot be created. + const { captureLauncherPid } = await import('./runtime/launcherPid') + captureLauncherPid() + const { runCli } = await import('./commands/runCli') + if (fallbackNote) { + try { + // The logger creates HAPI_HOME; the note is best effort. + const { logger } = await import('./ui/logger') + logger.debug(`[WARN] [DISCLAIM] ${fallbackNote}`) + } catch { + // The note already went to stderr when the disclaim failed. + } + } + await runCli() +} + +void main() diff --git a/cli/src/runtime/__fixtures__/reexecEntry.ts b/cli/src/runtime/__fixtures__/reexecEntry.ts new file mode 100644 index 00000000..133a2809 --- /dev/null +++ b/cli/src/runtime/__fixtures__/reexecEntry.ts @@ -0,0 +1,11 @@ +// Runs the real entry hook, then reports. With `--missing-symbol` the disclaim +// symbol lookup is pointed at a name that does not exist (fail-open check). +import { handleDisclaimExecEntry, takeDisclaimFallbackNote } from '../disclaimExec' +import { loadDarwinSpawnExec } from '../darwinSpawnExec' +import { report } from './report' + +const missingSymbol = process.argv.includes('--missing-symbol') +await handleDisclaimExecEntry(missingSymbol + ? { loadNative: async () => () => loadDarwinSpawnExec({ disclaimSymbol: 'hapi_missing_symbol_for_test' }) } + : {}) +report({ fallbackNote: takeDisclaimFallbackNote() }) diff --git a/cli/src/runtime/__fixtures__/report.ts b/cli/src/runtime/__fixtures__/report.ts new file mode 100644 index 00000000..c45e49d5 --- /dev/null +++ b/cli/src/runtime/__fixtures__/report.ts @@ -0,0 +1,23 @@ +// Prints this process's identity for the darwin re-exec tests. +import { dlopen, FFIType } from 'bun:ffi' +import { canDisclaimForChildren } from '../responsibility' +import { DISCLAIM_RESPONSIBILITY_ENV } from '../disclaimExec' + +const { symbols } = dlopen('/usr/lib/libSystem.B.dylib', { + responsibility_get_pid_responsible_for_pid: { args: [FFIType.i32], returns: FFIType.i32 }, + getpgrp: { args: [], returns: FFIType.i32 } +}) + +export function report(extra: Record = {}): void { + console.log(JSON.stringify({ + pid: process.pid, + responsible: symbols.responsibility_get_pid_responsible_for_pid(process.pid), + ownResponsible: canDisclaimForChildren(), + pgid: symbols.getpgrp(), + cwd: process.cwd(), + probe: process.env.HAPI_DISCLAIM_TEST_PROBE ?? null, + request: process.env[DISCLAIM_RESPONSIBILITY_ENV] ?? null, + args: process.argv.slice(2), + ...extra + })) +} diff --git a/cli/src/runtime/__fixtures__/reportResponsibility.ts b/cli/src/runtime/__fixtures__/reportResponsibility.ts new file mode 100644 index 00000000..f8b19730 --- /dev/null +++ b/cli/src/runtime/__fixtures__/reportResponsibility.ts @@ -0,0 +1,4 @@ +// Stand-in for a binary without the entry hook (e.g. an older release). +import { report } from './report' + +report() diff --git a/cli/src/runtime/darwinSpawnExec.ts b/cli/src/runtime/darwinSpawnExec.ts new file mode 100644 index 00000000..2a67d7b2 --- /dev/null +++ b/cli/src/runtime/darwinSpawnExec.ts @@ -0,0 +1,117 @@ +/** + * bun:ffi binding for an in-place `posix_spawn(POSIX_SPAWN_SETEXEC)` on macOS. + * + * Kept separate from disclaimExec.ts so `bun:ffi` is only loaded when a disclaim + * was actually requested (and never under Node/vitest). + */ +import { dlopen, FFIType, ptr, read, type Pointer } from 'bun:ffi' +import type { SpawnExecNative } from './disclaimExec' + +const LIBSYSTEM = '/usr/lib/libSystem.B.dylib' +export const DISCLAIM_SYMBOL = 'responsibility_spawnattrs_setdisclaim' + +const POSIX_SPAWN_SETSIGDEF = 0x04 +const POSIX_SPAWN_SETSIGMASK = 0x08 +const POSIX_SPAWN_SETEXEC = 0x40 +const SIGKILL = 9 +const SIGSTOP = 17 + +// Buffers whose addresses are handed to native code. Bun's FFI requires them to +// stay reachable while native code may read them; exec only returns on failure. +let pinned: unknown[] = [] + +function cString(value: string): Buffer { + return Buffer.from(`${value}\0`, 'utf8') +} + +export function loadDarwinSpawnExec(options: { disclaimSymbol?: string } = {}): SpawnExecNative { + const core = dlopen(LIBSYSTEM, { + posix_spawnattr_init: { args: [FFIType.ptr], returns: FFIType.i32 }, + posix_spawnattr_destroy: { args: [FFIType.ptr], returns: FFIType.i32 }, + posix_spawnattr_setflags: { args: [FFIType.ptr, FFIType.i16], returns: FFIType.i32 }, + posix_spawnattr_setsigmask: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, + posix_spawnattr_setsigdefault: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, + posix_spawn: { + args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], + returns: FFIType.i32 + }, + _NSGetEnviron: { args: [], returns: FFIType.ptr }, + getenv: { args: [FFIType.ptr], returns: FFIType.ptr }, + setenv: { args: [FFIType.ptr, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }, + unsetenv: { args: [FFIType.ptr], returns: FFIType.i32 } + }).symbols + + // Private libSystem symbol: resolve it on its own so its absence only disables + // the disclaim, not the exec. + const disclaimSymbol = options.disclaimSymbol ?? DISCLAIM_SYMBOL + let setDisclaim: ((attr: BigUint64Array, disclaim: number) => number) | null = null + try { + const optional = dlopen(LIBSYSTEM, { + [disclaimSymbol]: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.i32 } + }).symbols as Record number> + setDisclaim = optional[disclaimSymbol] ?? null + } catch { + setDisclaim = null + } + + return { + canDisclaim: setDisclaim !== null, + // The libc environment is what the exec passes on; process.env writes do not reach it. + unsetenv(name: string): boolean { + const key = cString(name) + core.unsetenv(key) + return core.getenv(key) === null + }, + setenv(name: string, value: string): void { + core.setenv(cString(name), cString(value), 1) + }, + exec(path: string, argv: readonly string[], disclaim: boolean): number { + // posix_spawnattr_t is an opaque pointer on Darwin. + const attr = new BigUint64Array(1) + let rc = core.posix_spawnattr_init(attr) + if (rc !== 0) { + return rc + } + try { + if (disclaim) { + if (!setDisclaim) { + return -1 + } + rc = setDisclaim(attr, 1) + if (rc !== 0) { + return rc + } + } + // Reset every catchable signal to its default action and clear the + // mask, so the new image does not inherit the dispositions this Bun + // runtime installed for itself. + const emptyMask = new Uint32Array([0]) + const allCatchable = new Uint32Array([0xffffffff & ~((1 << (SIGKILL - 1)) | (1 << (SIGSTOP - 1)))]) + rc = core.posix_spawnattr_setsigmask(attr, emptyMask) + || core.posix_spawnattr_setsigdefault(attr, allCatchable) + || core.posix_spawnattr_setflags(attr, POSIX_SPAWN_SETEXEC | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK) + if (rc !== 0) { + return rc + } + + const pathBuffer = cString(path) + const strings = argv.map(cString) + const argvArray = new BigUint64Array(strings.length + 1) + strings.forEach((value, index) => { + argvArray[index] = BigInt(ptr(value)) + }) + const environPointer = core._NSGetEnviron() + if (!environPointer) { + return -1 + } + const environ = read.ptr(environPointer, 0) as Pointer + pinned = [pathBuffer, strings, argvArray, attr, emptyMask, allCatchable] + // Returns only on failure; on success this process image is replaced. + return core.posix_spawn(null, pathBuffer, null, attr, argvArray, environ) + } finally { + pinned = [] + core.posix_spawnattr_destroy(attr) + } + } + } +} diff --git a/cli/src/runtime/disclaimExec.darwin.test.ts b/cli/src/runtime/disclaimExec.darwin.test.ts new file mode 100644 index 00000000..35617ee4 --- /dev/null +++ b/cli/src/runtime/disclaimExec.darwin.test.ts @@ -0,0 +1,115 @@ +/** + * Real re-exec through bun:ffi on macOS, in dev mode (bun runs the fixtures): + * same pid, own responsible process, stdio pipe, process group, env and cwd + * preserved, fail-open without the private symbol, a request addressed to + * another process ignored, and a binary without the hook ignoring the request. + * The compiled binary needs a separate smoke test on a Mac. LAN access itself + * needs a LAN peer and is not exercised here. Needs HAPI_BUN_EXEC from the test + * setup. + */ +import { spawn } from 'node:child_process' +import { mkdtempSync, realpathSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { afterAll, describe, expect, it } from 'vitest' +import { DISCLAIM_RESPONSIBILITY_ENV } from './disclaimExec' + +const reexecEntry = resolve(__dirname, '__fixtures__/reexecEntry.ts') +const withoutHook = resolve(__dirname, '__fixtures__/reportResponsibility.ts') + +interface RunResult { + spawnedPid: number | undefined + code: number | null + stdout: string + stderr: string +} + +// The spawned bun process is a direct child of this test process. +function run(args: string[], cwd: string, request: boolean | string): Promise { + const env: NodeJS.ProcessEnv = { ...process.env, HAPI_DISCLAIM_TEST_PROBE: 'kept as is' } + if (request !== false) { + env[DISCLAIM_RESPONSIBILITY_ENV] = request === true ? String(process.pid) : request + } else { + delete env[DISCLAIM_RESPONSIBILITY_ENV] + } + return new Promise((resolvePromise, reject) => { + const child = spawn(process.env.HAPI_BUN_EXEC!, args, { + cwd, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + env + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk) => { stdout += chunk }) + child.stderr.on('data', (chunk) => { stderr += chunk }) + child.on('error', reject) + child.on('exit', (code) => resolvePromise({ spawnedPid: child.pid, code, stdout, stderr })) + }) +} + +describe.runIf(process.platform === 'darwin')('macOS responsibility re-exec', () => { + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'hapi-disclaim-'))) + afterAll(() => rmSync(cwd, { recursive: true, force: true })) + + it('re-executes in place as its own responsible process, keeping pid, pipe, group, env and cwd', async () => { + const result = await run([reexecEntry, 'a b', 'c'], cwd, true) + + expect(result.code, result.stderr).toBe(0) + expect(result.stderr).toBe('') + const report = JSON.parse(result.stdout) + expect(report.pid).toBe(result.spawnedPid) + expect(report.responsible).toBe(report.pid) + expect(report.ownResponsible).toBe(true) + expect(report.pgid).toBe(report.pid) + expect(report.cwd).toBe(cwd) + expect(report.probe).toBe('kept as is') + expect(report.request).toBeNull() + expect(report.fallbackNote).toBeNull() + expect(report.args).toEqual(['a b', 'c']) + }) + + it('without a request the child keeps the spawner as responsible process', async () => { + const result = await run([reexecEntry], cwd, false) + + expect(result.code, result.stderr).toBe(0) + const report = JSON.parse(result.stdout) + expect(report.responsible).not.toBe(report.pid) + expect(report.ownResponsible).toBe(false) + }) + + it('ignores a request addressed to another process', async () => { + const result = await run([reexecEntry], cwd, String(process.pid + 1)) + + expect(result.code, result.stderr).toBe(0) + expect(result.stderr).toBe('') + const report = JSON.parse(result.stdout) + expect(report.responsible).not.toBe(report.pid) + expect(report.request).toBeNull() + }) + + it('fails open to a plain exec when the disclaim symbol is missing, and leaves a note for the log', async () => { + const result = await run([reexecEntry, '--missing-symbol'], cwd, true) + + expect(result.code, result.stderr).toBe(0) + expect(result.stderr.trim().split('\n')).toEqual([ + '[hapi] macOS responsibility disclaim: disclaim symbol not found; executing without it' + ]) + const report = JSON.parse(result.stdout) + expect(report.pid).toBe(result.spawnedPid) + expect(report.responsible).not.toBe(report.pid) + expect(report.request).toBeNull() + expect(report.fallbackNote).toBe('disclaim symbol not found') + expect(report.probe).toBe('kept as is') + }) + + it('a binary without the hook ignores the request and runs normally (rollback)', async () => { + const result = await run([withoutHook, 'x'], cwd, true) + + expect(result.code, result.stderr).toBe(0) + const report = JSON.parse(result.stdout) + expect(report.pid).toBe(result.spawnedPid) + expect(report.responsible).not.toBe(report.pid) + expect(report.args).toEqual(['x']) + }) +}) diff --git a/cli/src/runtime/disclaimExec.test.ts b/cli/src/runtime/disclaimExec.test.ts new file mode 100644 index 00000000..182450e5 --- /dev/null +++ b/cli/src/runtime/disclaimExec.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, it, vi } from 'vitest' +import { + DISCLAIM_FALLBACK_ENV, + DISCLAIM_RESPONSIBILITY_ENV, + handleDisclaimExecEntry, + isRequestForThisProcess, + reexecArgv, + runDisclaimExec, + shouldDisclaimResponsibility, + takeDisclaimFallbackNote, + type SpawnExecNative +} from './disclaimExec' + +const EXE = '/Users/me/.local/bin/hapi-local' + +type FakeNative = SpawnExecNative & { exec: ReturnType; setenv: ReturnType } + +function fakeNative(options: { canDisclaim?: boolean; unsetOk?: boolean; execResults?: Array } = {}): FakeNative { + const results = [...(options.execResults ?? [])] + return { + canDisclaim: options.canDisclaim ?? true, + unsetenv: vi.fn((_name: string) => options.unsetOk ?? true), + setenv: vi.fn((_name: string, _value: string) => {}), + // A real exec never returns on success; 'replaced' stands for that by throwing. + exec: vi.fn((_path: string, _argv: readonly string[], _disclaim: boolean) => { + const next = results.shift() ?? 1 + if (next === 'replaced') { + throw new Error('replaced') + } + return next + }) + } +} + +describe('shouldDisclaimResponsibility', () => { + const own = () => true + const notOwn = () => false + + it('applies only to detached darwin spawns from a process that may hand its responsibility on', () => { + expect(shouldDisclaimResponsibility('darwin', true, own)).toBe(true) + expect(shouldDisclaimResponsibility('darwin', true, notOwn)).toBe(false) + expect(shouldDisclaimResponsibility('darwin', false, own)).toBe(false) + expect(shouldDisclaimResponsibility('darwin', undefined, own)).toBe(false) + expect(shouldDisclaimResponsibility('linux', true, own)).toBe(false) + expect(shouldDisclaimResponsibility('win32', true, own)).toBe(false) + }) + + it('does not consult the responsibility lookup off darwin or for attached spawns', () => { + const lookup = vi.fn(() => true) + shouldDisclaimResponsibility('linux', true, lookup) + shouldDisclaimResponsibility('darwin', false, lookup) + expect(lookup).not.toHaveBeenCalled() + }) +}) + +describe('reexecArgv', () => { + it('drops the virtual bunfs entry of a compiled binary', () => { + expect(reexecArgv(['bun', '/$bunfs/root/hapi', 'runner', 'start-sync'], EXE)).toEqual([EXE, 'runner', 'start-sync']) + }) + + it('keeps the real entry script in dev mode', () => { + expect(reexecArgv(['/opt/bun', '/repo/cli/src/index.ts', 'claude', 'a b'], '/opt/bun')) + .toEqual(['/opt/bun', '/repo/cli/src/index.ts', 'claude', 'a b']) + }) +}) + +describe('runDisclaimExec', () => { + const argv = [EXE, 'claude'] + + it('clears the request and execs with the disclaim, without logging', () => { + const native = fakeNative({ execResults: ['replaced'] }) + const log = vi.fn() + + expect(() => runDisclaimExec(EXE, argv, () => native, log)).toThrow('replaced') + expect(native.unsetenv).toHaveBeenCalledWith(DISCLAIM_RESPONSIBILITY_ENV) + expect(native.exec).toHaveBeenCalledWith(EXE, argv, true) + expect(log).not.toHaveBeenCalled() + }) + + it('fails open to a plain exec when the disclaim symbol is missing, with one log line and a note', () => { + const native = fakeNative({ canDisclaim: false, execResults: ['replaced'] }) + const log = vi.fn() + + expect(() => runDisclaimExec(EXE, argv, () => native, log)).toThrow('replaced') + expect(native.exec.mock.calls).toEqual([[EXE, argv, false]]) + expect(log).toHaveBeenCalledTimes(1) + expect(log.mock.calls[0][0]).toContain('disclaim symbol not found') + expect(native.setenv).toHaveBeenCalledWith(DISCLAIM_FALLBACK_ENV, 'disclaim symbol not found') + }) + + it('fails open to a plain exec when the disclaimed exec returns an error', () => { + const native = fakeNative({ execResults: [22, 'replaced'] }) + const log = vi.fn() + + expect(() => runDisclaimExec(EXE, argv, () => native, log)).toThrow('replaced') + expect(native.exec.mock.calls.map((call) => call[2])).toEqual([true, false]) + expect(log).toHaveBeenCalledTimes(1) + expect(log.mock.calls[0][0]).toContain('code 22') + }) + + it('does not exec when the request cannot be cleared, so the new image cannot loop', () => { + const native = fakeNative({ unsetOk: false }) + const log = vi.fn() + + runDisclaimExec(EXE, argv, () => native, log) + + expect(native.exec).not.toHaveBeenCalled() + expect(log).toHaveBeenCalledTimes(1) + }) + + it('returns when the native binding cannot load', () => { + const log = vi.fn() + + runDisclaimExec(EXE, argv, () => { + throw new Error('dlopen failed') + }, log) + + expect(log).toHaveBeenCalledTimes(1) + expect(log.mock.calls[0][0]).toContain('dlopen failed') + }) + + it('returns when every exec fails', () => { + const native = fakeNative({ execResults: [1, 2] }) + const log = vi.fn() + + runDisclaimExec(EXE, argv, () => native, log) + + expect(native.exec).toHaveBeenCalledTimes(2) + expect(log).toHaveBeenCalledTimes(2) + expect(log.mock.calls[1][0]).toContain('continuing in-process') + }) +}) + +describe('isRequestForThisProcess', () => { + it('accepts only the pid of the direct parent', () => { + expect(isRequestForThisProcess('4242', 4242)).toBe(true) + expect(isRequestForThisProcess('4242', 4243)).toBe(false) + expect(isRequestForThisProcess('1', 1)).toBe(false) + expect(isRequestForThisProcess('', 4242)).toBe(false) + expect(isRequestForThisProcess('4242x', 4242)).toBe(false) + }) +}) + +describe('handleDisclaimExecEntry', () => { + const argv = ['bun', '/$bunfs/root/hapi', 'runner', 'start-sync'] + const PARENT = 4242 + + it('does nothing without a request', async () => { + const loadNative = vi.fn() + const env: NodeJS.ProcessEnv = { KEEP: 'x' } + + await handleDisclaimExecEntry({ env, argv, platform: 'darwin', ppid: PARENT, loadNative }) + + expect(loadNative).not.toHaveBeenCalled() + expect(env).toEqual({ KEEP: 'x' }) + }) + + it('drops a request off darwin without exec', async () => { + const loadNative = vi.fn() + const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) } + + await handleDisclaimExecEntry({ env, argv, platform: 'linux', ppid: PARENT, loadNative }) + + expect(loadNative).not.toHaveBeenCalled() + expect(env).toEqual({}) + }) + + it.each(['1', '9999'])('drops a request addressed to another process (%s), e.g. one leaked through an older binary', async (value) => { + const loadNative = vi.fn() + const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: value } + + await handleDisclaimExecEntry({ env, argv, platform: 'darwin', ppid: PARENT, loadNative }) + + expect(loadNative).not.toHaveBeenCalled() + expect(env).toEqual({}) + }) + + it('re-executes its own executable with its own arguments', async () => { + // A real exec does not return; the fake fails both attempts so the call can be inspected. + const native = fakeNative({ execResults: [5, 6] }) + const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) } + + await handleDisclaimExecEntry({ + env, argv, argv0: '/usr/local/bin/hapi', execPath: EXE, platform: 'darwin', ppid: PARENT, + loadNative: async () => () => native, writeStderr: vi.fn() + }) + + expect(native.exec.mock.calls[0]).toEqual([EXE, ['/usr/local/bin/hapi', 'runner', 'start-sync'], true]) + expect(env[DISCLAIM_RESPONSIBILITY_ENV]).toBeUndefined() + }) + + it('continues in-process with the request cleared and a fallback note for the log', async () => { + const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) } + const writeStderr = vi.fn() + + await handleDisclaimExecEntry({ + env, argv, execPath: EXE, platform: 'darwin', ppid: PARENT, writeStderr, + loadNative: async () => { + throw new Error('no bun:ffi') + } + }) + + expect(env[DISCLAIM_RESPONSIBILITY_ENV]).toBeUndefined() + expect(writeStderr).toHaveBeenCalledTimes(1) + const note = takeDisclaimFallbackNote(env) + expect(note).toContain('no bun:ffi') + expect(env[DISCLAIM_FALLBACK_ENV]).toBeUndefined() + }) + + it('continues in-process when the native binding throws mid-way', async () => { + const native = fakeNative() + native.unsetenv = vi.fn(() => { + throw new TypeError('ffi call failed') + }) + const env: NodeJS.ProcessEnv = { [DISCLAIM_RESPONSIBILITY_ENV]: String(PARENT) } + const writeStderr = vi.fn() + + await expect(handleDisclaimExecEntry({ + env, argv, execPath: EXE, platform: 'darwin', ppid: PARENT, writeStderr, + loadNative: async () => () => native + })).resolves.toBeUndefined() + + expect(native.exec).not.toHaveBeenCalled() + expect(writeStderr).toHaveBeenCalledTimes(1) + expect(takeDisclaimFallbackNote(env)).toContain('ffi call failed') + }) +}) diff --git a/cli/src/runtime/disclaimExec.ts b/cli/src/runtime/disclaimExec.ts new file mode 100644 index 00000000..c66dee04 --- /dev/null +++ b/cli/src/runtime/disclaimExec.ts @@ -0,0 +1,167 @@ +/** + * macOS responsibility disclaim for detached HAPI processes. + * + * macOS attributes a process's privacy decisions (Local Network, TCC) to its + * "responsible process", inherited from the spawner. A session spawned by a + * launchd-managed runner therefore stays tied to that runner's pid. Once the + * runner is replaced (upgrade, handoff) and that pid is gone, macOS can no + * longer resolve the responsible app, and every new process in the session tree + * that connects to a LAN address fails with EHOSTUNREACH. + * + * When the spawner may hand its responsibility on (see responsibility.ts), a + * detached child is started with `HAPI_DISCLAIM_RESPONSIBILITY=`. + * The entry hook below honours it only in a direct child of that pid, removes + * the variable, and re-executes `process.execPath` in place (same pid, stdio, + * cwd, and otherwise the same environment) with + * `responsibility_spawnattrs_setdisclaim`, so the child becomes its own + * responsible process. A binary that predates this hook ignores the variable and + * starts normally, which keeps rollbacks working; a copy of the variable that + * leaks further down such a tree is ignored by later binaries because their + * parent is not the spawner. + */ +export const DISCLAIM_RESPONSIBILITY_ENV = 'HAPI_DISCLAIM_RESPONSIBILITY' +/** Set for the re-executed image when the disclaim degraded, so it can log why. */ +export const DISCLAIM_FALLBACK_ENV = 'HAPI_DISCLAIM_FALLBACK' + +export interface SpawnExecNative { + /** Whether the private disclaim symbol was found. */ + canDisclaim: boolean + /** Removes a variable from the libc environment; true when it is gone. */ + unsetenv(name: string): boolean + setenv(name: string, value: string): void + /** Replaces the current process image; returns only on failure (non-zero code). */ + exec(path: string, argv: readonly string[], disclaim: boolean): number +} + +export function shouldDisclaimResponsibility( + platform: NodeJS.Platform, + detached: boolean | undefined, + canDisclaimForChildren: () => boolean +): boolean { + return platform === 'darwin' && detached === true && canDisclaimForChildren() +} + +/** The request is addressed to direct children of the spawner only. */ +export function isRequestForThisProcess(value: string, ppid: number): boolean { + return /^\d+$/.test(value) && Number(value) > 1 && Number(value) === ppid +} + +/** + * argv for re-executing this same invocation. Compiled binaries report a virtual + * `/$bunfs/...` entry as argv[1] that the executable supplies itself; in dev mode + * argv[1] is the real entry script (Bun has already applied `--cwd`, so the + * current directory is the one it needs). + */ +export function reexecArgv(argv: readonly string[], argv0: string): string[] { + const compiled = (argv[1] ?? '').startsWith('/$bunfs/') + return compiled ? [argv0, ...argv.slice(2)] : [argv0, ...argv.slice(1)] +} + +/** + * Fails open: without the disclaim it execs the same command plainly, and if no + * exec is possible it returns so the caller continues in-process. Each fallback + * step writes one line through `log`. + */ +export function runDisclaimExec( + execPath: string, + argv: readonly string[], + loadNative: () => SpawnExecNative, + log: (line: string) => void +): void { + let native: SpawnExecNative + try { + native = loadNative() + } catch (error) { + log(`macOS responsibility disclaim unavailable (${error instanceof Error ? error.message : String(error)}); continuing without it`) + return + } + // The exec'd image must not see the request again, or it would re-exec forever. + if (!native.unsetenv(DISCLAIM_RESPONSIBILITY_ENV)) { + log(`macOS responsibility disclaim: could not clear ${DISCLAIM_RESPONSIBILITY_ENV}; continuing without it`) + return + } + + let reason: string + if (native.canDisclaim) { + const rc = native.exec(execPath, argv, true) + reason = `disclaimed exec failed (code ${rc})` + } else { + reason = 'disclaim symbol not found' + } + log(`macOS responsibility disclaim: ${reason}; executing without it`) + native.setenv(DISCLAIM_FALLBACK_ENV, reason) + const rc = native.exec(execPath, argv, false) + log(`macOS responsibility disclaim: exec failed (code ${rc}); continuing in-process without it`) +} + +export interface DisclaimEntryOptions { + env?: NodeJS.ProcessEnv + argv?: readonly string[] + argv0?: string + execPath?: string + platform?: NodeJS.Platform + ppid?: number + loadNative?: () => Promise<() => SpawnExecNative> + writeStderr?: (line: string) => void +} + +async function loadDarwinNative(): Promise<() => SpawnExecNative> { + const { loadDarwinSpawnExec } = await import('./darwinSpawnExec') + return loadDarwinSpawnExec +} + +/** + * Entry hook; runs before the CLI module graph loads so the re-exec happens + * before any side effects (log files, sockets, timers). Returns when this process + * should continue as the CLI; it never throws. + */ +export async function handleDisclaimExecEntry(options: DisclaimEntryOptions = {}): Promise { + const env = options.env ?? process.env + const requested = env[DISCLAIM_RESPONSIBILITY_ENV] + if (requested === undefined) { + return + } + // Never hand the request on to this process's own children. + delete env[DISCLAIM_RESPONSIBILITY_ENV] + if ((options.platform ?? process.platform) !== 'darwin' + || !isRequestForThisProcess(requested, options.ppid ?? process.ppid)) { + return + } + + const writeStderr = options.writeStderr ?? ((line: string) => process.stderr.write(`[hapi] ${line}\n`)) + const notes: string[] = [] + const log = (line: string) => { + notes.push(line) + writeStderr(line) + } + // Fail open: whatever goes wrong, this process continues as the CLI. + try { + let loadNative: () => SpawnExecNative + try { + loadNative = await (options.loadNative ?? loadDarwinNative)() + } catch (error) { + loadNative = () => { + throw error + } + } + runDisclaimExec( + options.execPath ?? process.execPath, + reexecArgv(options.argv ?? process.argv, options.argv0 ?? process.argv0), + loadNative, + log + ) + } catch (error) { + log(`macOS responsibility disclaim failed (${error instanceof Error ? error.message : String(error)}); continuing in-process without it`) + } + env[DISCLAIM_FALLBACK_ENV] = notes.join('; ') +} + +/** Reads and clears the fallback note left by the entry hook, if any. */ +export function takeDisclaimFallbackNote(env: NodeJS.ProcessEnv = process.env): string | null { + const note = env[DISCLAIM_FALLBACK_ENV] + if (note === undefined) { + return null + } + delete env[DISCLAIM_FALLBACK_ENV] + return note +} diff --git a/cli/src/runtime/launcherPid.ts b/cli/src/runtime/launcherPid.ts new file mode 100644 index 00000000..28dc4eb3 --- /dev/null +++ b/cli/src/runtime/launcherPid.ts @@ -0,0 +1,31 @@ +/** + * The npm launcher (`bin/hapi.cjs`) passes its own pid so the binary can tell + * whether launchd started it through the launcher (see responsibility.ts). + * + * This module imports nothing: the CLI entry reads the value before any module + * with side effects loads, so `hapi --help` still works when HAPI_HOME cannot be + * created. + */ + +/** Set by the npm launcher to its own pid; read once at startup and never passed on. */ +export const LAUNCHER_PID_ENV = 'HAPI_LAUNCHER_PID' + +let launcherPid: number | null = null + +function parsePid(value: string | undefined): number | null { + if (!value || !/^\d+$/.test(value)) { + return null + } + const pid = Number(value) + return pid > 1 ? pid : null +} + +/** Reads and removes the launcher pid, so no child of this process inherits it. */ +export function captureLauncherPid(env: NodeJS.ProcessEnv = process.env): void { + launcherPid = parsePid(env[LAUNCHER_PID_ENV]) + delete env[LAUNCHER_PID_ENV] +} + +export function getLauncherPid(): number | null { + return launcherPid +} diff --git a/cli/src/runtime/responsibility.test.ts b/cli/src/runtime/responsibility.test.ts new file mode 100644 index 00000000..508b6502 --- /dev/null +++ b/cli/src/runtime/responsibility.test.ts @@ -0,0 +1,93 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { captureLauncherPid, getLauncherPid, LAUNCHER_PID_ENV } from './launcherPid' +import { ownsResponsibility } from './responsibility' + +// pid -> responsible pid +function table(entries: Record): (pid: number) => number { + return (pid) => entries[pid] ?? pid +} + +describe('ownsResponsibility', () => { + it('is true for a process that is its own responsible process (started by launchd)', () => { + expect(ownsResponsibility({ pid: 100, ppid: 1, launcherPid: null, responsibleFor: table({ 100: 100 }) })).toBe(true) + }) + + it('is true under the npm launcher when that launcher is the parent and its own responsible process', () => { + expect(ownsResponsibility({ pid: 100, ppid: 50, launcherPid: 50, responsibleFor: table({ 100: 50, 50: 50 }) })).toBe(true) + }) + + it('is false under the npm launcher started from Terminal or SSH', () => { + // Terminal (10) is responsible for both the launcher (50) and the binary (100). + expect(ownsResponsibility({ pid: 100, ppid: 50, launcherPid: 50, responsibleFor: table({ 100: 10, 50: 10 }) })).toBe(false) + }) + + it('is false when the responsible process is not the declared launcher or not the parent', () => { + const facts = { pid: 100, responsibleFor: table({ 100: 50, 50: 50 }) } + expect(ownsResponsibility({ ...facts, ppid: 50, launcherPid: null })).toBe(false) + expect(ownsResponsibility({ ...facts, ppid: 50, launcherPid: 51 })).toBe(false) + expect(ownsResponsibility({ ...facts, ppid: 60, launcherPid: 50 })).toBe(false) + }) + + it('is false for a process under a supervisor such as pm2', () => { + // pm2 (20) -> launcher (50) -> binary (100); pm2 is responsible for both. + expect(ownsResponsibility({ pid: 100, ppid: 50, launcherPid: 50, responsibleFor: table({ 100: 20, 50: 20 }) })).toBe(false) + }) +}) + +describe('captureLauncherPid', () => { + afterEach(() => captureLauncherPid({})) + + it('removes the launcher pid from the environment so children never inherit it', () => { + const env: NodeJS.ProcessEnv = { [LAUNCHER_PID_ENV]: '50', KEEP: 'x' } + + captureLauncherPid(env) + + expect(env).toEqual({ KEEP: 'x' }) + }) + + it.each([ + ['50', 50], + ['1', null], + ['stale', null], + [undefined, null], + ])('reads %s as launcher pid %s', (value, expected) => { + captureLauncherPid(value === undefined ? {} : { [LAUNCHER_PID_ENV]: value }) + + expect(getLauncherPid()).toBe(expected) + }) +}) + +describe('canDisclaimForChildren', () => { + const platform = Object.getOwnPropertyDescriptor(process, 'platform')! + + afterEach(() => { + Object.defineProperty(process, 'platform', platform) + vi.resetModules() + vi.doUnmock('@/ui/logger') + }) + + it('fails open and logs once when the lookup is unavailable on darwin', async () => { + const debug = vi.fn() + vi.doMock('@/ui/logger', () => ({ logger: { debug } })) + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) + vi.resetModules() + const { canDisclaimForChildren } = await import('./responsibility') + + // Vitest runs under Node, where bun:ffi is not available. + expect(canDisclaimForChildren()).toBe(false) + expect(canDisclaimForChildren()).toBe(false) + expect(debug).toHaveBeenCalledTimes(1) + expect(debug.mock.calls[0][0]).toMatch(/^\[WARN\] \[DISCLAIM\] macOS responsibility lookup unavailable/) + }) + + it('stays silent off darwin', async () => { + const debug = vi.fn() + vi.doMock('@/ui/logger', () => ({ logger: { debug } })) + Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }) + vi.resetModules() + const { canDisclaimForChildren } = await import('./responsibility') + + expect(canDisclaimForChildren()).toBe(false) + expect(debug).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/runtime/responsibility.ts b/cli/src/runtime/responsibility.ts new file mode 100644 index 00000000..9597b145 --- /dev/null +++ b/cli/src/runtime/responsibility.ts @@ -0,0 +1,84 @@ +/** + * Whether this process may hand its macOS responsibility to the detached + * processes it spawns (see disclaimExec.ts). + * + * That is the case when this process is its own responsible process, as a + * runner started directly by launchd is, or when its responsible process is the + * npm launcher (`bin/hapi.cjs`) that launchd started and that started this + * process. In both cases the inherited responsible pid goes away when the runner + * or its launcher exits. A process started from Terminal or over SSH has + * Terminal or sshd-session as its responsible process, and macOS grants their + * descendants LAN access implicitly; those keep the inherited responsibility. + * + * Observed on macOS 27: once a process's responsible process has exited, + * `responsibility_get_pid_responsible_for_pid` reports the process itself. Such a + * spawner then counts as its own responsible process. Its tree has already lost + * LAN access for new processes, so disclaiming its children is no worse. + */ +import { logger } from '@/ui/logger' +import { getLauncherPid } from './launcherPid' + +type ResponsibleFor = (pid: number) => number + +let lookup: ResponsibleFor | null | undefined + +export interface ResponsibilityFacts { + pid: number + ppid: number + launcherPid: number | null + responsibleFor: ResponsibleFor +} + +export function ownsResponsibility(facts: ResponsibilityFacts): boolean { + const responsible = facts.responsibleFor(facts.pid) + if (responsible === facts.pid) { + return true + } + return facts.launcherPid !== null + && responsible === facts.launcherPid + && responsible === facts.ppid + && facts.responsibleFor(responsible) === responsible +} + +function warnOnce(reason: string): void { + logger.debug(`[WARN] [DISCLAIM] macOS responsibility lookup unavailable (${reason}); detached children keep the inherited responsible process`) +} + +function loadLookup(): ResponsibleFor | null { + if (process.platform !== 'darwin') { + return null + } + if (!process.versions.bun) { + warnOnce('not running under Bun') + return null + } + try { + // Loaded lazily: this module is also imported under Node (tests), where + // bun:ffi does not exist. + const { dlopen, FFIType } = require('bun:ffi') as typeof import('bun:ffi') + const { symbols } = dlopen('/usr/lib/libSystem.B.dylib', { + responsibility_get_pid_responsible_for_pid: { args: [FFIType.i32], returns: FFIType.i32 } + }) + return (pid) => symbols.responsibility_get_pid_responsible_for_pid(pid) + } catch (error) { + warnOnce(error instanceof Error ? error.message : String(error)) + return null + } +} + +/** False whenever the answer is unknown, so callers fail open to no disclaim. */ +export function canDisclaimForChildren(): boolean { + if (lookup === undefined) { + lookup = loadLookup() + } + if (!lookup) { + return false + } + try { + return ownsResponsibility({ pid: process.pid, ppid: process.ppid, launcherPid: getLauncherPid(), responsibleFor: lookup }) + } catch (error) { + warnOnce(error instanceof Error ? error.message : String(error)) + lookup = null + return false + } +} diff --git a/cli/src/utils/spawnHappyCLI.test.ts b/cli/src/utils/spawnHappyCLI.test.ts index 18cddb06..ba4658eb 100644 --- a/cli/src/utils/spawnHappyCLI.test.ts +++ b/cli/src/utils/spawnHappyCLI.test.ts @@ -1,16 +1,22 @@ -import { beforeAll, afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { beforeAll, afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { SpawnOptions } from 'child_process'; const { spawnMock, existsSyncMock, isBunCompiledMock, - projectPathMock + projectPathMock, + canDisclaimForChildrenMock } = vi.hoisted(() => ({ spawnMock: vi.fn((..._args: any[]) => ({ pid: 12345 }) as any), existsSyncMock: vi.fn((path: string) => !path.includes('missing-hapi.exe')), isBunCompiledMock: vi.fn(() => false), - projectPathMock: vi.fn(() => process.cwd()) + projectPathMock: vi.fn(() => process.cwd()), + canDisclaimForChildrenMock: vi.fn(() => false) +})); + +vi.mock('@/runtime/responsibility', () => ({ + canDisclaimForChildren: canDisclaimForChildrenMock })); vi.mock('child_process', async () => { @@ -69,6 +75,7 @@ describe('spawnHappyCLI windowsHide behavior', () => { existsSyncMock.mockImplementation((path: string) => !path.includes('missing-hapi.exe')); isBunCompiledMock.mockReturnValue(false); projectPathMock.mockReturnValue(process.cwd()); + canDisclaimForChildrenMock.mockReturnValue(false); if (originalInvokedCwd === undefined) { delete process.env.HAPI_INVOKED_CWD; } else { @@ -134,6 +141,75 @@ describe('spawnHappyCLI windowsHide behavior', () => { expect('windowsHide' in options).toBe(false); }); + describe('macOS responsibility disclaim', () => { + const exe = '/Users/me/.local/bin/hapi-local'; + + function spawnCall(): { command: string; args: string[]; env: NodeJS.ProcessEnv | undefined } { + expect(spawnMock).toHaveBeenCalledTimes(1); + const [command, args, options] = spawnMock.mock.calls[0] as [string, string[], SpawnOptions]; + return { command, args, env: options.env }; + } + + beforeEach(() => { + isBunCompiledMock.mockReturnValue(true); + process.env.HAPI_CLI_EXECUTABLE = exe; + existsSyncMock.mockImplementation(() => true); + canDisclaimForChildrenMock.mockReturnValue(true); + }); + + afterEach(() => { + delete process.env.HAPI_DISCLAIM_RESPONSIBILITY; + }); + + it('requests the disclaim for this spawner through the environment, leaving the command unchanged', async () => { + setPlatform('darwin'); + const { spawnHappyCLI } = await import('./spawnHappyCLI'); + + spawnHappyCLI(['claude', '--started-by', 'runner'], { detached: true, stdio: 'ignore' }); + + const call = spawnCall(); + expect(call.command).toBe(exe); + expect(call.args).toEqual(['claude', '--started-by', 'runner']); + expect(call.env?.HAPI_DISCLAIM_RESPONSIBILITY).toBe(String(process.pid)); + expect(getSpawnOptionsOrThrow().detached).toBe(true); + }); + + it('does not request it when the spawner cannot hand its responsibility on (Terminal, SSH)', async () => { + setPlatform('darwin'); + canDisclaimForChildrenMock.mockReturnValue(false); + process.env.HAPI_DISCLAIM_RESPONSIBILITY = '1'; + const { spawnHappyCLI } = await import('./spawnHappyCLI'); + + spawnHappyCLI(['runner', 'start-sync'], { detached: true, stdio: 'ignore' }); + + const call = spawnCall(); + expect(call.args).toEqual(['runner', 'start-sync']); + expect(call.env && 'HAPI_DISCLAIM_RESPONSIBILITY' in call.env).toBe(false); + }); + + it('does not request it for a non-detached darwin spawn', async () => { + setPlatform('darwin'); + const { spawnHappyCLI } = await import('./spawnHappyCLI'); + + spawnHappyCLI(['hub'], { detached: false, stdio: 'ignore' }); + + const call = spawnCall(); + expect(call.args).toEqual(['hub']); + expect(call.env && 'HAPI_DISCLAIM_RESPONSIBILITY' in call.env).toBe(false); + }); + + it.each(['linux', 'win32'])('does not request it for a detached %s spawn', async (platform) => { + setPlatform(platform); + const { spawnHappyCLI } = await import('./spawnHappyCLI'); + + spawnHappyCLI(['runner', 'start-sync'], { detached: true, stdio: 'ignore' }); + + const call = spawnCall(); + expect(call.args).toEqual(['runner', 'start-sync']); + expect(call.env && 'HAPI_DISCLAIM_RESPONSIBILITY' in call.env).toBe(false); + }); + }); + it('forces Bun child processes to run with the cli project root as cwd', async () => { // Clear the test-isolation override so we test the pure runtime behaviour delete process.env.HAPI_BUN_EXEC; diff --git a/cli/src/utils/spawnHappyCLI.ts b/cli/src/utils/spawnHappyCLI.ts index ccf34b82..dd2b8dfe 100644 --- a/cli/src/utils/spawnHappyCLI.ts +++ b/cli/src/utils/spawnHappyCLI.ts @@ -31,6 +31,8 @@ import { fileURLToPath } from 'node:url'; import { isBunCompiled, projectPath } from '@/projectPath'; import { logger } from '@/ui/logger'; import { existsSync } from 'node:fs'; +import { DISCLAIM_RESPONSIBILITY_ENV, shouldDisclaimResponsibility } from '@/runtime/disclaimExec'; +import { canDisclaimForChildren } from '@/runtime/responsibility'; const HAPI_CLI_EXECUTABLE_ENV = 'HAPI_CLI_EXECUTABLE'; @@ -147,8 +149,12 @@ export function spawnHappyCLI(args: string[], options: SpawnOptions = {}): Child // for when "hapi" was started and don't care about the underlying node process // details and flags we use to achieve the same result. const fullCommand = `hapi ${args.join(' ')}`; - logger.debug(`[SPAWN HAPI CLI] Spawning: ${fullCommand} in ${directory}`); - + // A detached process outlives its spawner. On macOS, when the spawner's + // responsible process goes away with it (launchd-managed runner, or its npm + // launcher), the child must not keep it (see runtime/disclaimExec.ts). + const disclaimResponsibility = shouldDisclaimResponsibility(process.platform, options.detached, canDisclaimForChildren); + logger.debug(`[SPAWN HAPI CLI] Spawning: ${fullCommand} in ${directory}${disclaimResponsibility ? ' (macOS responsibility disclaim requested)' : ''}`); + const compiledMode = isBunCompiled(); const { command: spawnCommand, args: spawnArgs } = getHappyCliCommand(args); @@ -180,6 +186,12 @@ export function spawnHappyCLI(args: string[], options: SpawnOptions = {}): Child : resolveInvokedCwd(options.cwd); shouldSetEnv = true; } + // Set or cleared explicitly so an inherited request never leaks to a child. + if (disclaimResponsibility) { + finalEnv[DISCLAIM_RESPONSIBILITY_ENV] = String(process.pid); + } else { + delete finalEnv[DISCLAIM_RESPONSIBILITY_ENV]; + } if (shouldSetEnv) { finalOptions.env = finalEnv; }