Skip to content

Commit 81d6408

Browse files
committed
refactor(ios-runner): decode every runner response body in one module
The runner answers one HTTP envelope, but three places decoded it: the command path in runner-session.ts, the `status` recovery read in runner-command-recovery.ts, and the adoption `uptime` probe in runner-adoption.ts. Each had its own rule for what an unreadable body means, so a body one path refused could be read as an answer by another. `decodeRunnerResponseBody` in runner-response.ts is now the only place that turns a runner response body into a payload, and `isRunnerResponseOk` is the one acceptance rule: the runner's `ok` is a Swift `Bool`, so only the literal true answers. The command path and the recovery read accepted any truthy `ok`, so a retained body reading `ok: "true"` came back as a completed command's own result; both now refuse it, as the adoption probe already did. Each reader keeps its own failure handling — a truncated retained body is still an unrecoverable command, a truncated probe answer is still a failed probe — but none can disagree with the command path about what is readable.
1 parent 91652a8 commit 81d6408

8 files changed

Lines changed: 320 additions & 67 deletions

File tree

‎packages/platform-apple/src/runner/__tests__/runner-adoption.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,27 @@ test('adoption is skipped when the probe fails', async () => {
289289
expect(await tryAdoptRunnerSessionFromLease(simulator, {})).toBeNull();
290290
});
291291

292+
// #2662: the probe decodes through the command path's decoder, so a body that
293+
// path would refuse cannot be read as an answer here either. Adoption must not
294+
// re-stamp the lease for a runner it cannot read.
295+
test('adoption is skipped when the uptime probe answers a truncated body', async () => {
296+
const lease = writeStaleLease();
297+
mockIsProcessAlive.mockReturnValue(true);
298+
mockSendRunnerCommandOnce.mockResolvedValue(new Response('{"ok":true,"data":{"uptime":'));
299+
300+
expect(await tryAdoptRunnerSessionFromLease(simulator, {})).toBeNull();
301+
expect(readStaleRunnerLease(simulator.id)?.ownerToken).toBe(lease.ownerToken);
302+
});
303+
304+
test('adoption is skipped when the uptime probe answers an ok that is not the boolean true', async () => {
305+
const lease = writeStaleLease();
306+
mockIsProcessAlive.mockReturnValue(true);
307+
mockSendRunnerCommandOnce.mockResolvedValue(new Response('{"ok":"true"}'));
308+
309+
expect(await tryAdoptRunnerSessionFromLease(simulator, {})).toBeNull();
310+
expect(readStaleRunnerLease(simulator.id)?.ownerToken).toBe(lease.ownerToken);
311+
});
312+
292313
test('adoption is disabled by the kill switch', async () => {
293314
writeStaleLease();
294315
mockIsProcessAlive.mockReturnValue(true);

‎packages/platform-apple/src/runner/__tests__/runner-command-recovery.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,55 @@ test('a journaled RUNNER_WEDGED keeps its fatal code and stays unretriable', asy
204204
return true;
205205
});
206206
});
207+
208+
/**
209+
* #2662: the `status` read has no decoder of its own, so it accepts what the one
210+
* decoder accepts. A stringly-typed `ok` used to be the seam: a private truthiness
211+
* rule read this retained body as the command's own result.
212+
*/
213+
test('a retained response whose ok is not the boolean true is not recovered', async () => {
214+
const { result, invalidate } = await runRecovery({
215+
script: [
216+
{
217+
kind: 'ok',
218+
data: {
219+
lifecycleState: 'completed',
220+
lifecycleResponseJson: '{"ok":"true","data":{"tapped":true}}',
221+
},
222+
},
223+
],
224+
});
225+
226+
await assert.rejects(result, (error: unknown) => {
227+
assert.ok(error instanceof AppError);
228+
assert.equal(error.details?.recovery, 'completed_without_retained_response');
229+
return true;
230+
});
231+
assert.equal(invalidate.mock.calls.length, 0);
232+
});
233+
234+
/**
235+
* A retained body cut off mid-write answers nothing. The session is kept — the
236+
* runner is reachable, it proved that by serving `status` — but the truncated
237+
* command result is not handed back.
238+
*/
239+
test('a truncated retained response is not recovered', async () => {
240+
const { result, invalidate } = await runRecovery({
241+
script: [
242+
{
243+
kind: 'ok',
244+
data: {
245+
lifecycleState: 'completed',
246+
lifecycleResponseJson: '{"ok":true,"data":{"nodes":[{"label":"Sign In"',
247+
},
248+
},
249+
],
250+
});
251+
252+
await assert.rejects(result, (error: unknown) => {
253+
assert.ok(error instanceof AppError);
254+
assert.equal(error.details?.recovery, 'completed_without_retained_response');
255+
return true;
256+
});
257+
assert.equal(invalidate.mock.calls.length, 0);
258+
});
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import assert from 'node:assert/strict';
2+
import { describe, test } from 'vitest';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import {
5+
buildRunnerResponseError,
6+
decodeRunnerResponseBody,
7+
isRunnerResponseOk,
8+
readRunnerResponseData,
9+
} from '../runner-response.ts';
10+
11+
// A body cut off mid-write, the shape a runner that died while answering leaves behind.
12+
const TRUNCATED_BODY = '{"ok":true,"data":{"nodes":[{"label":"Sign In"';
13+
14+
describe('decodeRunnerResponseBody', () => {
15+
test('decodes the runner envelope', () => {
16+
assert.deepEqual(decodeRunnerResponseBody('{"ok":true,"data":{"tapped":true}}'), {
17+
ok: true,
18+
data: { tapped: true },
19+
});
20+
});
21+
22+
test('rejects a truncated body instead of reading a reply out of it', () => {
23+
assert.throws(
24+
() => decodeRunnerResponseBody(TRUNCATED_BODY),
25+
(error: unknown) =>
26+
error instanceof AppError &&
27+
error.code === 'COMMAND_FAILED' &&
28+
error.message === 'Invalid runner response' &&
29+
error.details?.text === TRUNCATED_BODY,
30+
);
31+
});
32+
33+
test('never reads a JSON body that is not an envelope as an answer', () => {
34+
for (const body of ['null', '42', '"ok"']) {
35+
assert.equal(isRunnerResponseOk(decodeRunnerResponseBody(body)), false, body);
36+
}
37+
});
38+
39+
test('carries a bare-array body through unread rather than inventing an envelope', () => {
40+
const payload = decodeRunnerResponseBody('[]');
41+
assert.equal(isRunnerResponseOk(payload), false);
42+
assert.deepEqual(readRunnerResponseData(payload), {});
43+
});
44+
});
45+
46+
describe('isRunnerResponseOk', () => {
47+
test('accepts only the boolean true the runner sends', () => {
48+
assert.equal(isRunnerResponseOk({ ok: true }), true);
49+
assert.equal(isRunnerResponseOk({ ok: false }), false);
50+
assert.equal(isRunnerResponseOk({}), false);
51+
// Stringly-typed truthiness would let a proxy or a wedged socket answer for the runner.
52+
assert.equal(isRunnerResponseOk({ ok: 'true' }), false);
53+
assert.equal(isRunnerResponseOk({ ok: 1 }), false);
54+
});
55+
});
56+
57+
describe('readRunnerResponseData', () => {
58+
test('reads only an object data payload', () => {
59+
assert.deepEqual(readRunnerResponseData({ ok: true, data: { tapped: true } }), {
60+
tapped: true,
61+
});
62+
assert.deepEqual(readRunnerResponseData({ ok: true }), {});
63+
assert.deepEqual(readRunnerResponseData({ ok: true, data: null }), {});
64+
assert.deepEqual(readRunnerResponseData({ ok: true, data: [] }), {});
65+
assert.deepEqual(readRunnerResponseData({ ok: true, data: 'tapped' }), {});
66+
});
67+
});
68+
69+
describe('buildRunnerResponseError', () => {
70+
test('carries the payload, the runner hint, and the classified code', () => {
71+
const error = buildRunnerResponseError(
72+
{
73+
ok: false,
74+
error: {
75+
code: 'RUNNER_BUSY',
76+
message: 'Main thread is busy',
77+
hint: 'Retry after it drains',
78+
},
79+
},
80+
'/tmp/runner.log',
81+
);
82+
83+
assert.ok(error instanceof AppError);
84+
assert.equal(error.code, 'COMMAND_FAILED');
85+
assert.equal(error.message, 'Main thread is busy');
86+
assert.equal(error.details?.hint, 'Retry after it drains');
87+
assert.equal(error.details?.logPath, '/tmp/runner.log');
88+
assert.equal(error.details?.retriable, true);
89+
assert.deepEqual((error.details as { runner?: unknown }).runner, {
90+
ok: false,
91+
error: { code: 'RUNNER_BUSY', message: 'Main thread is busy', hint: 'Retry after it drains' },
92+
});
93+
});
94+
95+
test('keeps a missing runner message as a generic runner error', () => {
96+
const error = buildRunnerResponseError({ ok: false, error: {} });
97+
assert.equal(error.message, 'Runner error');
98+
assert.equal(error.details?.hint, undefined);
99+
});
100+
});

‎packages/platform-apple/src/runner/__tests__/runner-session.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,64 @@ test('runner session probes readiness before mutating commands', async () => {
340340
});
341341
});
342342

343+
test('runner session refuses a command response whose ok is not the boolean true', async () => {
344+
// The runner's `ok` is a Swift `Bool`, so a stringly-typed one is not an answer
345+
// the session may mark itself ready on (#2662).
346+
const session = makeRunnerSession({ ready: false });
347+
mockWaitForRunner.mockResolvedValueOnce(runnerResponse({ uptimeMs: 42 }));
348+
mockSendRunnerCommandOnce.mockResolvedValueOnce(
349+
new Response('{"ok":"true","data":{"tapped":true}}'),
350+
);
351+
352+
await assert.rejects(
353+
() =>
354+
executeRunnerCommandWithSession(
355+
IOS_SIMULATOR,
356+
session,
357+
{ command: 'tap', x: 120, y: 240, appBundleId: 'com.example.demo' },
358+
'/tmp/runner.log',
359+
30_000,
360+
),
361+
(error: unknown) => {
362+
assert.ok(error instanceof AppError);
363+
assert.equal(error.code, 'COMMAND_FAILED');
364+
assert.deepEqual(error.details?.runner, { ok: 'true', data: { tapped: true } });
365+
return true;
366+
},
367+
);
368+
369+
// Refused is not the same as served: a body that is not an answer cannot be
370+
// recorded as the healthy mutation that lets the next command skip preflight.
371+
assert.equal(session.lastHealthyMutation, undefined);
372+
});
373+
374+
test('runner session refuses a command response body that is not readable JSON', async () => {
375+
const truncatedBody = '{"ok":true,"data":{"nodes":[{"label":"Sign In"';
376+
const session = makeRunnerSession({ ready: false });
377+
mockWaitForRunner.mockResolvedValueOnce(runnerResponse({ uptimeMs: 42 }));
378+
mockSendRunnerCommandOnce.mockResolvedValueOnce(new Response(truncatedBody));
379+
380+
await assert.rejects(
381+
() =>
382+
executeRunnerCommandWithSession(
383+
IOS_SIMULATOR,
384+
session,
385+
{ command: 'tap', x: 120, y: 240, appBundleId: 'com.example.demo' },
386+
'/tmp/runner.log',
387+
30_000,
388+
),
389+
(error: unknown) => {
390+
assert.ok(error instanceof AppError);
391+
assert.equal(error.code, 'COMMAND_FAILED');
392+
assert.equal(error.details?.text, truncatedBody);
393+
assert.equal(error.details?.runner, undefined);
394+
return true;
395+
},
396+
);
397+
398+
assert.equal(session.lastHealthyMutation, undefined);
399+
});
400+
343401
test('runner session emits reason diagnostics when readiness preflight is used', async () => {
344402
const session = makeRunnerSession({ ready: false });
345403
mockWaitForRunner.mockResolvedValueOnce(runnerResponse({ uptimeMs: 42 }));

‎packages/platform-apple/src/runner/runner-adoption.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
type RunnerProcessHandle,
3030
type RunnerSession,
3131
} from './runner-session-types.ts';
32+
import { decodeRunnerResponseBody, isRunnerResponseOk } from './runner-response.ts';
3233

3334
// A healthy localhost runner answers uptime in tens of milliseconds and a dead
3435
// port refuses immediately; the timeout only bounds the wedged-runner case,
@@ -137,8 +138,7 @@ async function probeRunnerAnswersUptime(device: DeviceInfo, port: number): Promi
137138
withRunnerCommandId({ command: 'uptime' }),
138139
RUNNER_ADOPTION_PROBE_TIMEOUT_MS,
139140
);
140-
const payload = JSON.parse(await response.text()) as { ok?: unknown };
141-
return payload?.ok === true;
141+
return isRunnerResponseOk(decodeRunnerResponseBody(await response.text()));
142142
} catch {
143143
return false;
144144
}

‎packages/platform-apple/src/runner/runner-command-recovery.ts‎

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@ import type { DeviceInfo } from '@agent-device/kernel/device';
33
import { emitDiagnostic } from './host.ts';
44
import { classifyRunnerReportedError, type RunnerCommand } from './runner-contract.ts';
55
import { isReadOnlyRunnerCommand } from './runner-command-traits.ts';
6+
import {
7+
decodeRunnerResponseBody,
8+
isRunnerResponseOk,
9+
readRunnerResponseData,
10+
} from './runner-response.ts';
611
import type { AppleRunnerCommandOptions } from './runner-provider.ts';
712
import { executeRunnerCommandWithSession, type RunnerSession } from './runner-session.ts';
813

9-
type LifecycleResponsePayload = {
10-
ok?: unknown;
11-
data?: unknown;
12-
};
13-
1414
type RunnerTransportRecovery =
1515
| { type: 'recovered'; data: Record<string, unknown>; reason: string; lifecycleState?: string }
1616
| { type: 'skipInvalidation'; error: AppError; reason: string; lifecycleState?: string }
@@ -340,20 +340,15 @@ function runnerStatusInFlightError(
340340

341341
function parseLifecycleResponseJson(value: unknown): Record<string, unknown> | undefined {
342342
if (typeof value !== 'string' || value.trim().length === 0) return undefined;
343-
const parsed = parseLifecycleResponsePayload(value);
344-
if (!parsed.ok) return undefined;
345-
if (parsed.data && typeof parsed.data === 'object' && !Array.isArray(parsed.data)) {
346-
return parsed.data as Record<string, unknown>;
347-
}
348-
return {};
349-
}
350-
351-
function parseLifecycleResponsePayload(value: string): LifecycleResponsePayload {
352343
try {
353-
const raw: unknown = JSON.parse(value);
354-
if (raw && typeof raw === 'object') return raw as LifecycleResponsePayload;
355-
} catch {}
356-
return {};
344+
const payload = decodeRunnerResponseBody(value);
345+
return isRunnerResponseOk(payload) ? readRunnerResponseData(payload) : undefined;
346+
} catch {
347+
// A retained body the one decoder refuses is not a recoverable result; the
348+
// caller keeps the session and reports the retained response as unreadable
349+
// instead of returning a truncated command result (#2662).
350+
return undefined;
351+
}
357352
}
358353

359354
function completedWithoutRetainedResponseHint(
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* The one decoding of an Apple runner response body. Every reader of the
3+
* runner's HTTP envelope — command responses, the lifecycle `status` read, and
4+
* the adoption `uptime` probe — decodes here, so no caller can keep a private
5+
* rule about what is readable and what is an answer (#2662).
6+
*/
7+
import { AppError } from '@agent-device/kernel/errors';
8+
import { classifyRunnerReportedError } from './runner-contract.ts';
9+
10+
export type RunnerResponsePayload = {
11+
ok?: unknown;
12+
error?: { code?: unknown; message?: unknown; hint?: unknown };
13+
data?: unknown;
14+
};
15+
16+
/**
17+
* A body that is not JSON at all is transport-shaped failure, not an empty
18+
* response: a runner that died mid-write must not be read as having answered.
19+
*/
20+
export function decodeRunnerResponseBody(text: string): RunnerResponsePayload {
21+
let parsed: unknown;
22+
try {
23+
parsed = JSON.parse(text);
24+
} catch {
25+
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
26+
}
27+
return parsed && typeof parsed === 'object' ? (parsed as RunnerResponsePayload) : {};
28+
}
29+
30+
/** The runner's `ok` is a Swift `Bool`, so only the literal `true` is an answer. */
31+
export function isRunnerResponseOk(payload: RunnerResponsePayload): boolean {
32+
return payload.ok === true;
33+
}
34+
35+
export function readRunnerResponseData(payload: RunnerResponsePayload): Record<string, unknown> {
36+
if (!payload.data || typeof payload.data !== 'object' || Array.isArray(payload.data)) return {};
37+
return payload.data as Record<string, unknown>;
38+
}
39+
40+
export function buildRunnerResponseError(
41+
payload: RunnerResponsePayload,
42+
logPath?: string,
43+
): AppError {
44+
const runnerErrorCode = readRunnerErrorCode(payload.error?.code);
45+
const errorMessage =
46+
typeof payload.error?.message === 'string' ? payload.error.message : undefined;
47+
const hint = typeof payload.error?.hint === 'string' ? payload.error.hint : undefined;
48+
const classification = classifyRunnerReportedError(runnerErrorCode);
49+
return new AppError(classification.code, errorMessage ?? 'Runner error', {
50+
runner: payload,
51+
...classification.details,
52+
xcodebuild: {
53+
exitCode: 1,
54+
stdout: '',
55+
stderr: '',
56+
},
57+
hint,
58+
logPath,
59+
});
60+
}
61+
62+
function readRunnerErrorCode(rawCode: unknown): string | undefined {
63+
return typeof rawCode === 'string' && rawCode.trim().length > 0 ? rawCode.trim() : undefined;
64+
}

0 commit comments

Comments
 (0)