fix(cli): keep LAN access for sessions that outlive their runner on macOS (#2328)

* fix(cli): keep LAN access for sessions that outlive their runner on macOS

macOS attributes Local Network decisions to a process's responsible
process, which a child inherits from its spawner. Sessions spawned by a
runner that launchd started (directly, or through the npm launcher
bin/hapi.cjs) inherit the runner's or the launcher's pid. Once that
process exits (upgrade, version handoff) while the sessions are kept,
every new process in their trees that connects to a LAN address fails
with EHOSTUNREACH.

When the spawner may hand its responsibility on, detached spawnHappyCLI
children (sessions, runner handoff, runner start) are started with
HAPI_DISCLAIM_RESPONSIBILITY=<spawner pid>. In a direct child of that
pid, the entry hook removes the variable from the libc environment and
re-executes process.execPath in place via posix_spawn(POSIX_SPAWN_SETEXEC)
with responsibility_spawnattrs_setdisclaim, so the child becomes its own
responsible process. The pid, stdio, process group, cwd and the rest of
the environment are unchanged, so the runner's ChildProcess tracking keeps
working.

The spawner may hand its responsibility on when it is its own responsible
process, or when its responsible process is its direct parent, is the npm
launcher (which now passes HAPI_LAUNCHER_PID) and is itself its own
responsible process. A spawner started from Terminal or over SSH keeps the
inherited responsibility and with it the implicit LAN allowance macOS
grants there. The lookup uses responsibility_get_pid_responsible_for_pid
through bun:ffi; when it is unavailable the spawn is not disclaimed and
this is logged once.

Binaries without the hook ignore the variable, and a copy that leaks into
a rolled-back tree is ignored because its parent is not the spawner. The
private disclaim symbol may disappear: the hook then execs without it, and
any other failure continues in-process; the reason is written to the hapi
log.

* fix(cli): print --help and --version when HAPI_HOME cannot be created

The entry point imported runtime/responsibility to read the npm launcher's
pid. That module imports the logger, whose configuration creates HAPI_HOME,
so `hapi --help` and `hapi --version` failed before printing when that
directory could not be created.

Move the launcher pid into a dependency-free module, read it from there, and
make the optional disclaim fallback note best effort. Add an entry point test
that runs both flags with an unwritable HAPI_HOME.
This commit is contained in:
Junmo Kim
2026-11-09 12:03:22 +08:00
committed by GitHub
parent 2524f81615
commit f75109ce07
17 changed files with 1068 additions and 8 deletions
+79 -3
View File
@@ -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;
+14 -2
View File
@@ -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;
}