Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -17,7 +17,9 @@ export type FakeRunnerResponse =
/** Hangs up on this request and every later one for the command: the entry is never consumed. */
| { kind: 'hangUpAlways' }
/** Hangs up and stops listening, as a runner process that died mid-command. */
| { kind: 'exit' };
| { kind: 'exit' }
/** Never answers, as a runner still executing the command when its caller gives up. */
| { kind: 'hold' };

export type FakeRunnerRequest = {
command: string;
Expand Down Expand Up @@ -79,9 +81,10 @@ export async function startFakeRunnerServer(
requests,
close: () =>
stopped ??
new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
),
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
server.closeAllConnections();
}),
};
}

Expand All @@ -101,6 +104,7 @@ function writeFakeRunnerResponse(
res.end(JSON.stringify({ ok: false, error: { message: 'fake runner script exhausted' } }));
return;
}
if (next.kind === 'hold') return;
if (next.kind === 'hangUp' || next.kind === 'hangUpAlways') {
res.destroy();
return;
Expand Down
207 changes: 206 additions & 1 deletion packages/platform-apple/src/runner/__tests__/runner-exchange.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import assert from 'node:assert/strict';
import type { ExecResult } from '@agent-device/host-kit/command';
import { createRequestCanceledError, isRequestCanceledError } from '@agent-device/kernel/errors';
import { withKeyedLock } from '@agent-device/kernel/keyed-lock';
import { afterEach, test } from 'vitest';
import { executeRunnerExchange } from '../runner-exchange.ts';
import { RunnerCommandAccounting, type RunnerSession } from '../runner-session-types.ts';
import { IOS_SIMULATOR } from './device-fixtures.ts';
import { startFakeRunnerServer, type FakeRunnerServer } from './fake-runner-server.ts';
import {
startFakeRunnerServer,
type FakeRunnerResponse,
type FakeRunnerServer,
} from './fake-runner-server.ts';

let server: FakeRunnerServer | undefined;

Expand Down Expand Up @@ -184,3 +190,202 @@ test('the exchange awaits owner invalidation before throwing a fatal runner erro
}
await assert.rejects(exchange);
});

const LONG_PRESS = {
command: 'longPress',
x: 10,
y: 10,
durationMs: 5_000,
appBundleId: 'com.example.app',
} as const;

function journalState(lifecycleState: string): FakeRunnerResponse {
return { kind: 'ok', data: { lifecycleState } };
}

async function abortOnceReceived(
runner: FakeRunnerServer,
command: string,
controller: AbortController,
reason: unknown = createRequestCanceledError(),
): Promise<void> {
while (!runner.requests.some((request) => request.command === command)) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
await new Promise<void>((resolve) => setTimeout(resolve, 1));
}
controller.abort(reason);
}

function statusPolls(runner: FakeRunnerServer): unknown[] {
return runner.requests
.filter((request) => request.command === 'status')
.map((request) => request.body.statusCommandId);
}

function sentCommandId(runner: FakeRunnerServer, command: string): unknown {
return runner.requests.find((request) => request.command === command)?.body.commandId;
}

test('a canceled exchange whose command reached the runner settles only once its journal entry is terminal', async () => {
server = await startFakeRunnerServer({
longPress: [{ kind: 'hold' }],
status: [journalState('started'), journalState('completed')],
});
const runner = server;
const session = sessionFor(runner.port);
const controller = new AbortController();
let requestsWhenSettled = -1;

const exchange = executeRunnerExchange(
IOS_SIMULATOR,
session,
LONG_PRESS,
undefined,
10_000,
async () => {},
controller.signal,
).finally(() => {
requestsWhenSettled = runner.requests.length;
});
await abortOnceReceived(runner, 'longPress', controller);

await assert.rejects(exchange, isRequestCanceledError);
const commandId = sentCommandId(runner, 'longPress');
assert.deepEqual(statusPolls(runner), [commandId, commandId]);
assert.equal(requestsWhenSettled, runner.requests.length);
assert.equal(session.commandCharges.hasOutstandingCharges, false);
});

test('a request on the same session lock starts only after the canceled command is terminal', async () => {
server = await startFakeRunnerServer({
longPress: [{ kind: 'hold' }],
status: [journalState('accepted'), journalState('started'), journalState('failed')],
});
const runner = server;
const session = sessionFor(runner.port);
const locks = new Map<string, Promise<unknown>>();
const controller = new AbortController();

const canceled = withKeyedLock(locks, 'session:default', async () => {
await executeRunnerExchange(
IOS_SIMULATOR,
session,
LONG_PRESS,
undefined,
10_000,
async () => {},
controller.signal,
);
});
await abortOnceReceived(runner, 'longPress', controller);
const nextRequestSawPolls = withKeyedLock(locks, 'session:default', async () =>
statusPolls(runner),
);

await assert.rejects(canceled, isRequestCanceledError);
assert.equal((await nextRequestSawPolls).length, 3);
assert.equal(session.commandCharges.hasOutstandingCharges, false);
});

test('a request canceled before its command is sent releases without reading the journal', async () => {
server = await startFakeRunnerServer({});
const session = sessionFor(server.port);
session.lastHealthyMutation = { atMs: Date.now(), appBundleId: LONG_PRESS.appBundleId };
const controller = new AbortController();
controller.abort(createRequestCanceledError());

await assert.rejects(
executeRunnerExchange(
IOS_SIMULATOR,
session,
LONG_PRESS,
undefined,
10_000,
async () => {},
controller.signal,
),
isRequestCanceledError,
);

assert.deepEqual(server.requests, []);
assert.equal(session.commandCharges.hasOutstandingCharges, false);
});

test('a canceled command the journal never accepted releases after one read and stays abandoned', async () => {
server = await startFakeRunnerServer({
longPress: [{ kind: 'hold' }],
status: [journalState('notAccepted')],
});
const session = sessionFor(server.port);
const controller = new AbortController();

const exchange = executeRunnerExchange(
IOS_SIMULATOR,
session,
LONG_PRESS,
undefined,
10_000,
async () => {},
controller.signal,
);
await abortOnceReceived(server, 'longPress', controller);

await assert.rejects(exchange, isRequestCanceledError);
assert.equal(statusPolls(server).length, 1);
assert.equal(session.commandCharges.hasAbandonedCharges, true);
});

test('a drain that outlives the command deadline settles and leaves the charge abandoned', async () => {
server = await startFakeRunnerServer({
longPress: [{ kind: 'hold' }],
status: Array.from({ length: 50 }, () => journalState('started')),
});
const session = sessionFor(server.port);
const controller = new AbortController();
const timeoutMs = 300;
const startedAtMs = Date.now();

const exchange = executeRunnerExchange(
IOS_SIMULATOR,
session,
LONG_PRESS,
undefined,
timeoutMs,
async () => {},
controller.signal,
);
await abortOnceReceived(server, 'longPress', controller);

await assert.rejects(exchange, isRequestCanceledError);
assert.ok(statusPolls(server).length >= 1);
assert.ok(Date.now() - startedAtMs < timeoutMs + 1_000);
assert.equal(session.commandCharges.hasAbandonedCharges, true);
});

test("a caller's own deadline abort does not wait on the runner journal", async () => {
server = await startFakeRunnerServer({
longPress: [{ kind: 'hold' }],
status: [journalState('started'), journalState('completed')],
});
const session = sessionFor(server.port);
const controller = new AbortController();

const exchange = executeRunnerExchange(
IOS_SIMULATOR,
session,
LONG_PRESS,
undefined,
10_000,
async () => {},
controller.signal,
);
await abortOnceReceived(
server,
'longPress',
controller,
new DOMException('Wait deadline exceeded', 'TimeoutError'),
);

await assert.rejects(exchange);
assert.deepEqual(statusPolls(server), []);
assert.equal(session.commandCharges.hasAbandonedCharges, true);
});
36 changes: 36 additions & 0 deletions packages/platform-apple/src/runner/runner-command-journal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { RunnerCommand } from './runner-contract.ts';
import type { RunnerCommandAccounting } from './runner-session-types.ts';

/**
* The runner journal vocabulary, so charge settlement, status recovery, and the drain of a canceled
* command cannot disagree about what a state means. `runner-swift-settlement-fixtures.ts` pins these
* names to `RunnerCommandLifecycleState`, and the recovery wiring rows are derived from that same
* declaration, so a state the runner gains has to be ruled here before it can decide a handoff.
*
* `completed` and `failed` close an entry — from the response's `ok` in `finish`, or a thrown error in
* `fail` — so execution ended. `accepted` and `started` are written as execution opens, so they share
* one in-flight verdict. `notAccepted` is what `status` reports for an id the journal never held,
* which this daemon cannot read as terminal.
*/
const RUNNER_TERMINAL_LIFECYCLE_STATES: ReadonlySet<string> = new Set(['completed', 'failed']);
export const RUNNER_IN_FLIGHT_LIFECYCLE_STATES: ReadonlySet<string> = new Set([
'accepted',
'started',
]);

/**
* Discharges the abandoned charge terminal status proves landed (#2965). A status reply is served
* inline, so it is no evidence that queued work finished; this is the only place a status answer may
* settle a charge, and only the one its `statusCommandId` names.
*
* @returns whether the evidence paid a debt, or `undefined` when the state is not terminal and no
* settlement was attempted.
*/
export function settleRunnerChargeForTerminalStatus(
session: { commandCharges: RunnerCommandAccounting },
command: Pick<RunnerCommand, 'commandId'>,
lifecycleState: string,
): boolean | undefined {
if (!RUNNER_TERMINAL_LIFECYCLE_STATES.has(lifecycleState)) return undefined;
return session.commandCharges.settleTerminalEvidence(command.commandId);
}
36 changes: 4 additions & 32 deletions packages/platform-apple/src/runner/runner-command-recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import {
} from './runner-contract.ts';
import { isReadOnlyRunnerCommand } from './runner-command-traits.ts';
import { RUNNER_REPLY_LOST_REASON } from './runner-error-classification.ts';
import {
RUNNER_IN_FLIGHT_LIFECYCLE_STATES,
settleRunnerChargeForTerminalStatus,
} from './runner-command-journal.ts';
import type { AppleRunnerCommandOptions } from './runner-provider.ts';
import { executeRunnerCommandWithSession, type RunnerSession } from './runner-session.ts';

Expand Down Expand Up @@ -277,38 +281,6 @@ async function tryRecoverRunnerCommandAfterTransportError(
);
}

/**
* The runner journal vocabulary, so the charge settlement below and the recovery verdict in
* {@link handleRunnerCommandStatusRecovery} cannot disagree about what a state means.
* `runner-swift-settlement-fixtures.ts` pins these names to `RunnerCommandLifecycleState`, and the
* recovery wiring rows are derived from that same declaration, so a state the runner gains has to be
* ruled here before it can decide a handoff.
*
* `completed` and `failed` close an entry — from the response's `ok` in `finish`, or a thrown error in
* `fail` — so execution ended, and each gets its own recovery verdict below. `accepted` and `started`
* are written as execution opens, so they share one in-flight verdict. `notAccepted` is what `status`
* reports for an id the journal never held, which this daemon cannot read as terminal.
*/
const RUNNER_TERMINAL_LIFECYCLE_STATES: ReadonlySet<string> = new Set(['completed', 'failed']);
const RUNNER_IN_FLIGHT_LIFECYCLE_STATES: ReadonlySet<string> = new Set(['accepted', 'started']);

/**
* Discharges the abandoned charge terminal status proves landed (#2965). A status reply is served
* inline, so it is no evidence that queued work finished; this is the only place a status answer may
* settle a charge, and only the one its `statusCommandId` names.
*
* @returns whether the evidence paid a debt, or `undefined` when the state is not terminal and no
* settlement was attempted.
*/
function settleRunnerChargeForTerminalStatus(
session: RunnerSession,
command: RunnerCommand,
lifecycleState: string,
): boolean | undefined {
if (!RUNNER_TERMINAL_LIFECYCLE_STATES.has(lifecycleState)) return undefined;
return session.commandCharges.settleTerminalEvidence(command.commandId);
}

function handleRunnerCommandStatusRecovery(
status: Record<string, unknown>,
lifecycleState: string,
Expand Down
Loading
Loading