Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,23 @@ test('an unproven registration exit reports startup-exited even under a short en
assert.equal(failure.details?.startupTimeoutMs, 2_000);
});

test('a listen-denied exit fails once with startup-listen-denied and a host-access hint', async () => {
const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-listen-denied-'));
spawn.mockImplementation(
planRegisteredDaemonLaunches([
{ kind: 'exit', exit: { pid: 998_555, exitCode: DAEMON_STARTUP_EXIT_CODES.listenDenied } },
{ kind: 'exit', exit: { pid: 998_556, exitCode: DAEMON_STARTUP_EXIT_CODES.listenDenied } },
]),
);
pause.mockImplementation(async () => {
await realPause();
});
const failure = await expectStartupFailure(sendToDaemon(request(paths)));
assert.equal(failure.details?.reason, 'startup-listen-denied');
assert.match(String(failure.details?.hint), /listen EPERM or EACCES\). A sandbox/);
assert.equal(spawn.mock.calls.length, 1, 'a denied listen is not retried');
});

test('a startup ceiling that is not a positive integer is rejected before any daemon spawns', async () => {
const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-bad-ceiling-'));
for (const raw of ['0', '-5', 'abc', '12.5']) {
Expand Down
41 changes: 34 additions & 7 deletions packages/daemon-client/src/daemon-client-startup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,16 @@ const MINIMUM_DAEMON_TAKEOVER_BUDGET_MS = 5_000;

const DAEMON_STARTUP_TIMEOUT_ENV = 'AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS';

/** Agent directive: a sandboxed agent reads it to ask for host access instead of giving up. */
const DAEMON_LISTEN_DENIED_HINT =
'The host denied the daemon a loopback port on 127.0.0.1 (listen EPERM or EACCES). A sandbox ' +
'around this command likely blocks local ports and simulator access. Run agent-device ' +
"outside the sandbox: allow the agent-device command in the agent's sandbox rules, or rerun it " +
'with host access (escalated permissions).';

type DaemonStartupFailureReason =
| typeof DAEMON_UNAVAILABLE_REASONS.startupExited.reason
| typeof DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason
| typeof DAEMON_UNAVAILABLE_REASONS.startupStalled.reason
| typeof DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason;

Expand Down Expand Up @@ -340,14 +348,28 @@ export async function startLocalDaemon(settings: DaemonClientSettings): Promise<
...(phases ? { phases: describeStartupPhaseTimings(phases) } : {}),
...(daemonLogTail ? { daemonLogTail } : {}),
metadataState: state,
hint:
reason === DAEMON_UNAVAILABLE_REASONS.startupStalled.reason ||
reason === DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason
? resolveStartupProgressHint(reason, startupTimeoutMs)
: resolveDaemonStartupHint(state, settings.paths),
hint: resolveStartupFailureHint(effectiveReason, startupTimeoutMs, () =>
resolveDaemonStartupHint(state, settings.paths),
),
});
}

function resolveStartupFailureHint(
reason: DaemonStartupFailureReason,
ceilingMs: number,
exitedHint: () => string,
): string {
switch (reason) {
case DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason:
return DAEMON_LISTEN_DENIED_HINT;
case DAEMON_UNAVAILABLE_REASONS.startupStalled.reason:
case DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason:
return resolveStartupProgressHint(reason, ceilingMs);
case DAEMON_UNAVAILABLE_REASONS.startupExited.reason:
return exitedHint();
}
}

async function attemptLocalDaemonStartup(
settings: DaemonClientSettings,
deadline: number,
Expand Down Expand Up @@ -385,16 +407,21 @@ async function attemptLocalDaemonStartup(
};
}
const { cleanup, joined } = await retireStartupAttempt(settings, launch, deadline);
const listenDenied =
startup.kind === 'early_exit' &&
startup.exit.exitCode === DAEMON_STARTUP_EXIT_CODES.listenDenied;
const reason: DaemonStartupFailureReason =
startup.kind === 'stalled'
? DAEMON_UNAVAILABLE_REASONS.startupStalled.reason
: startup.kind === 'ceiling'
? DAEMON_UNAVAILABLE_REASONS.startupCeiling.reason
: DAEMON_UNAVAILABLE_REASONS.startupExited.reason;
: listenDenied
? DAEMON_UNAVAILABLE_REASONS.startupListenDenied.reason
: DAEMON_UNAVAILABLE_REASONS.startupExited.reason;
const available = isRegistrationAvailable(inspectProcessLock(settings.paths.lockPath));
return {
cleanup,
retry: joined && startup.kind === 'early_exit' && available,
retry: joined && startup.kind === 'early_exit' && !listenDenied && available,
reason,
startError: startup.kind === 'early_exit' ? describeDaemonEarlyExit(startup.exit) : undefined,
daemonProcess: startup.kind === 'early_exit' ? startup.exit : { pid: launch.pid },
Expand Down
6 changes: 5 additions & 1 deletion packages/daemon-client/src/daemon-lifecycle-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,12 @@ export const DAEMON_UNAVAILABLE_REASONS = {
bindingMismatch: { reason: 'daemon-binding-mismatch' },
// The running daemon enforces a different daemon policy than `AGENT_DEVICE_DAEMON_POLICY` names.
policyMismatch: { reason: 'DAEMON_POLICY_MISMATCH' },
// The daemon process ended before it registered a reachable endpoint.
// The daemon process ended before it registered a reachable endpoint, for a cause other than a
// denied loopback listen.
startupExited: { reason: 'startup-exited' },
// The daemon process ended because the host refused its loopback listen, as a sandbox around the
// launching command does.
startupListenDenied: { reason: 'startup-listen-denied' },
// The daemon stayed registered and reachable but never reported the startup phase that follows.
startupStalled: { reason: 'startup-stalled' },
// Startup passed the ceiling its own startup budget allows, so this client stopped waiting.
Expand Down
10 changes: 9 additions & 1 deletion packages/daemon-contracts/src/daemon-registration-owner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,15 @@ const DAEMON_OWNERSHIP_REFUSAL_REASONS = {
privateStartupUnowned: { reason: 'daemon_private_startup_unowned' },
} as const satisfies ReasonTable<'daemon lifecycle'>;

export const DAEMON_STARTUP_EXIT_CODES = Object.freeze({ busy: 75, unproven: 78 });
/**
* The exit codes of a daemon startup that must not run. `listenDenied`: the host refused the
* loopback listen (EPERM or EACCES), as a sandbox around the launching command does.
*/
export const DAEMON_STARTUP_EXIT_CODES = Object.freeze({
busy: 75,
listenDenied: 77,
unproven: 78,
});
export type DaemonRegistrationFields = Readonly<{
socketPort?: number;
httpPort?: number;
Expand Down
5 changes: 3 additions & 2 deletions packages/daemon/src/server/http/daemon-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ export type DaemonRuntimeController = {
};

/**
* Thrown by {@link startDaemonRuntime} when the daemon must not run: its policy is unusable or
* another daemon owns the state dir. `details.exitCode` is the code the executable exits with.
* Thrown by {@link startDaemonRuntime} when the daemon must not run: its policy is unusable,
* another daemon owns the state dir, or the host denied its loopback listen. `details.exitCode` is
* the code the executable exits with.
*/
export function daemonStartupExitCode(error: unknown): number {
const exitCode = asAppError(error).details?.exitCode;
Expand Down
35 changes: 35 additions & 0 deletions packages/daemon/src/server/http/transport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import http from 'node:http';
import net from 'node:net';
import { test } from 'vitest';
import { createSocketServer, listenHttpServer, listenNetServer } from './transport.ts';
import { daemonStartupExitCode } from './daemon-runtime.ts';
import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http';
import {
clearRequestAbortRegistration,
Expand All @@ -13,6 +14,8 @@ import {
} from '@agent-device/host-kit/request';
import { applicationLifecycleExecutionFromRequest } from '../../sessions/application-lifecycle-execution.ts';
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit';
import { AppError } from '@agent-device/kernel/errors';
import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner';

test('Provider-backed integration daemon socket transport frames requests and normalizes malformed input', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) {
Expand Down Expand Up @@ -490,3 +493,35 @@ test('Provider-backed integration socket rejects malformed device pins before in
await closeLoopbackServer(server);
}
});

function serverWhoseListenFails(code: string): net.Server {
const server = net.createServer();
server.listen = (() => {
process.nextTick(() =>
server.emit('error', Object.assign(new Error(`listen ${code}: 127.0.0.1`), { code })),
);
return server;
}) as typeof server.listen;
return server;
}

test.for(['EPERM', 'EACCES'])(
'a %s loopback listen fails with daemon_listen_denied and the listen-denied exit code',
async (code) => {
await assert.rejects(listenNetServer(serverWhoseListenFails(code)), (error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.details?.reason, 'daemon_listen_denied');
assert.equal(error.details?.code, code);
assert.equal(daemonStartupExitCode(error), DAEMON_STARTUP_EXIT_CODES.listenDenied);
return true;
});
},
);

test('an EADDRINUSE loopback listen keeps its own error and no listen-denied exit code', async () => {
await assert.rejects(listenNetServer(serverWhoseListenFails('EADDRINUSE')), (error: unknown) => {
assert.ok(!(error instanceof AppError));
assert.equal((error as NodeJS.ErrnoException).code, 'EADDRINUSE');
return true;
});
});
27 changes: 25 additions & 2 deletions packages/daemon/src/server/http/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
createRequestCanceledError,
malformedRequestDetails,
normalizeError,
type ReasonTable,
} from '@agent-device/kernel/errors';
import { AsyncResource } from 'node:async_hooks';
import net from 'node:net';
Expand All @@ -26,6 +27,7 @@ import {
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { consumeTextLines } from '@agent-device/host-kit/transport';
import { DAEMON_REQUEST_MAX_BYTES } from '@agent-device/contracts/daemon-http';
import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner';

import {
serializeDaemonProgressEnvelope,
Expand Down Expand Up @@ -230,14 +232,35 @@ export function listenHttpServer(server: HttpServer): Promise<number> {
return listenLoopbackServer(server, 'Failed to bind HTTP server');
}

const DAEMON_LISTEN_REASONS = {
// The host refused the daemon's loopback listen with EPERM or EACCES, as a sandbox around the
// launching command does; `details.code` holds the errno code.
denied: { reason: 'daemon_listen_denied' },
} as const satisfies ReasonTable<'daemon lifecycle'>;

const LISTEN_DENIED_CODES: ReadonlySet<string> = new Set(['EPERM', 'EACCES']);

function listenLoopbackServer(
server: net.Server | HttpServer,
errorMessage: string,
): Promise<number> {
return new Promise((resolve, reject) => {
server.once('error', reject);
const onError = (error: NodeJS.ErrnoException) => {
if (!error.code || !LISTEN_DENIED_CODES.has(error.code)) {
reject(error);
return;
}
reject(
new AppError('COMMAND_FAILED', `${errorMessage}: listen ${error.code} on 127.0.0.1`, {
reason: DAEMON_LISTEN_REASONS.denied.reason,
code: error.code,
exitCode: DAEMON_STARTUP_EXIT_CODES.listenDenied,
}),
);
};
server.once('error', onError);
server.listen(0, '127.0.0.1', () => {
server.off('error', reject);
server.off('error', onError);
const address = server.address();
if (typeof address === 'object' && address?.port) {
resolve(address.port);
Expand Down
2 changes: 1 addition & 1 deletion src/commands/schema/cli-help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ Runner and daemon lifecycle (applies to simulators too):
No runner read launches a session app that is not running: snapshot, wait, is, get, a reading find, and an interaction's leading reads (a gesture's viewport read, the capture that resolves a selector click/fill) answer the retriable APP_NOT_RUNNING instead of bare-launching over a launch SpringBoard still holds behind its deep-link confirmation. Only open, activate, and a command that mutates without a leading read bring a stopped app up.
close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless --shutdown was requested, the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision.
Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap.
A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-exited (the process ended before registering), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it.
A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-listen-denied (the host refused the daemon's loopback listen, as a sandbox does; rerun agent-device with host access), startup-exited (the process ended before registering for another cause), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it.
On iOS simulators, open prepares app accessibility before launching an app or URL. If a running app has an empty accessibility tree after an earlier XCTest session, use open <app> --relaunch, then snapshot -i. A preparation failure is logged and does not block launch.
A command that needs the shared local daemon starts it for its state dir when none runs (device status and device release --stale never contact one). When the running daemon comes from another version or build, the command replaces it only if the daemon reports no work: no in-flight request, session, repair session, or live lease (a streaming resumable upload and a host human-control hold that names no lease are not counted); otherwise it fails with details.reason daemon-busy and leaves the daemon alone. A daemon that agreed to leave is waited for up to 60 s and never signaled while it drains; one still running then fails with details.reason daemon-drain-timeout unless it answers nothing and is provably a daemon process, which is force-retired. A daemon from a release that predates this check is never replaced and fails with daemon-incompatible. End a busy or older daemon deliberately with agent-device daemon stop --state-dir <path>. Node clients pick daemonLifecycle 'attach' (never starts or replaces a daemon; fails with daemon-not-running or daemon-incompatible) or 'managed' (the default until 0.22), and ensureDaemon() starts or replaces one explicitly.
daemon stop --state-dir <path> stops a detached daemon with process signals after verifying its identity; on non-Windows hosts it waits up to 75 s for the daemon to finish its own teardown before it forces the exit, while on Windows the stop signal force-terminates the daemon (mode forced, cleanupConfidence unknown). For a live embedded runtime, stop refuses with details.reason daemon-owner-embedded and a hint naming the host PID. Close that runtime in its host process with the handle returned by startAgentDevice(). Stop refuses live unrecognized ownership with daemon-owner-unrecognized and sends no request or signal. Stop retires an embedded or unrecognized registration when its recorded host lifetime has provably exited. Without --clean, an unreadable daemon.json fails with daemon-record-unreadable. daemon status shows host-owned or owner-not-recognized. Managed clients reuse a matching embedded runtime. Takeover, drain, and timeout recovery refuse a live embedded or unrecognized owner without a signal; a provably exited owner is retired so the state directory stays usable. Detached stop and cleanup use the lifetime and ownership from one registration read. --clean requires proven detached ownership; embedded, unrecognized and unreadable records fail with daemon-clean-not-detached because that cleanup walks the owner's whole process tree.
Expand Down
Loading
Loading