Skip to content

Commit 0c1d01f

Browse files
committed
refactor(ios-runner): give the response decoder a home the runner closure already loads
The Coverage job caught the new module: runner-session.ts sits in the eager closure of the app-lifecycle, doctor and runner-operations facades, so runner-response.ts made those closures evaluate one module more than the merge-base did. The envelope belongs beside the rest of the runner wire contract, which every one of those entries already evaluates and every reader already imports, so the decode helpers move into runner-contract.ts and the separate file goes away. No behavior moves. The two command-path refusal tests leave runner-session.test.ts, which is past the test-file tripwire and may not grow, and call parseRunnerResponse from the response suite instead.
1 parent 81d6408 commit 0c1d01f

7 files changed

Lines changed: 118 additions & 137 deletions

File tree

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

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,13 @@ import {
66
decodeRunnerResponseBody,
77
isRunnerResponseOk,
88
readRunnerResponseData,
9-
} from '../runner-response.ts';
9+
} from '../runner-contract.ts';
10+
import { parseRunnerResponse } from '../runner-session.ts';
1011

11-
// A body cut off mid-write, the shape a runner that died while answering leaves behind.
12+
// A body cut off mid-write: the shape a runner that died while answering leaves behind.
1213
const TRUNCATED_BODY = '{"ok":true,"data":{"nodes":[{"label":"Sign In"';
14+
// `ok` is a Swift `Bool`, so this is what a private truthiness rule used to accept as an answer.
15+
const STRINGLY_TYPED_BODY = '{"ok":"true","data":{"tapped":true}}';
1316

1417
describe('decodeRunnerResponseBody', () => {
1518
test('decodes the runner envelope', () => {
@@ -98,3 +101,39 @@ describe('buildRunnerResponseError', () => {
98101
assert.equal(error.details?.hint, undefined);
99102
});
100103
});
104+
105+
describe('parseRunnerResponse', () => {
106+
test('refuses a body whose ok is not the boolean true', async () => {
107+
const session = { ready: false };
108+
109+
await assert.rejects(
110+
() => parseRunnerResponse(new Response(STRINGLY_TYPED_BODY), session),
111+
(error: unknown) => {
112+
assert.ok(error instanceof AppError);
113+
assert.equal(error.code, 'COMMAND_FAILED');
114+
assert.deepEqual(error.details?.runner, { ok: 'true', data: { tapped: true } });
115+
return true;
116+
},
117+
);
118+
119+
assert.equal(session.ready, false);
120+
});
121+
122+
test('refuses a body that is not readable JSON', async () => {
123+
const session = { ready: false };
124+
125+
await assert.rejects(
126+
() => parseRunnerResponse(new Response(TRUNCATED_BODY), session),
127+
(error: unknown) => {
128+
assert.ok(error instanceof AppError);
129+
assert.equal(error.code, 'COMMAND_FAILED');
130+
assert.equal(error.details?.text, TRUNCATED_BODY);
131+
// Transport-shaped: no `runner` detail, so the session keeps its recency bets (#2552).
132+
assert.equal(error.details?.runner, undefined);
133+
return true;
134+
},
135+
);
136+
137+
assert.equal(session.ready, false);
138+
});
139+
});

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

Lines changed: 0 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -340,64 +340,6 @@ 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-
401343
test('runner session emits reason diagnostics when readiness preflight is used', async () => {
402344
const session = makeRunnerSession({ ready: false });
403345
mockWaitForRunner.mockResolvedValueOnce(runnerResponse({ uptimeMs: 42 }));

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ import {
99
import type { DeviceInfo } from '@agent-device/kernel/device';
1010
import { isRequestCanceledError } from '@agent-device/kernel/errors';
1111
import { sendRunnerCommandOnce } from './runner-transport.ts';
12-
import { withRunnerCommandId } from './runner-contract.ts';
12+
import {
13+
decodeRunnerResponseBody,
14+
isRunnerResponseOk,
15+
withRunnerCommandId,
16+
} from './runner-contract.ts';
1317
import {
1418
buildRunnerLease,
1519
readStaleRunnerLease,
@@ -29,7 +33,6 @@ import {
2933
type RunnerProcessHandle,
3034
type RunnerSession,
3135
} from './runner-session-types.ts';
32-
import { decodeRunnerResponseBody, isRunnerResponseOk } from './runner-response.ts';
3336

3437
// A healthy localhost runner answers uptime in tens of milliseconds and a dead
3538
// port refuses immediately; the timeout only bounds the wedged-runner case,

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { AppError } from '@agent-device/kernel/errors';
22
import type { DeviceInfo } from '@agent-device/kernel/device';
33
import { emitDiagnostic } from './host.ts';
4-
import { classifyRunnerReportedError, type RunnerCommand } from './runner-contract.ts';
5-
import { isReadOnlyRunnerCommand } from './runner-command-traits.ts';
64
import {
5+
classifyRunnerReportedError,
76
decodeRunnerResponseBody,
87
isRunnerResponseOk,
98
readRunnerResponseData,
10-
} from './runner-response.ts';
9+
type RunnerCommand,
10+
type RunnerResponsePayload,
11+
} from './runner-contract.ts';
12+
import { isReadOnlyRunnerCommand } from './runner-command-traits.ts';
1113
import type { AppleRunnerCommandOptions } from './runner-provider.ts';
1214
import { executeRunnerCommandWithSession, type RunnerSession } from './runner-session.ts';
1315

@@ -340,15 +342,16 @@ function runnerStatusInFlightError(
340342

341343
function parseLifecycleResponseJson(value: unknown): Record<string, unknown> | undefined {
342344
if (typeof value !== 'string' || value.trim().length === 0) return undefined;
345+
let payload: RunnerResponsePayload;
343346
try {
344-
const payload = decodeRunnerResponseBody(value);
345-
return isRunnerResponseOk(payload) ? readRunnerResponseData(payload) : undefined;
347+
payload = decodeRunnerResponseBody(value);
346348
} catch {
347349
// A retained body the one decoder refuses is not a recoverable result; the
348350
// caller keeps the session and reports the retained response as unreadable
349351
// instead of returning a truncated command result (#2662).
350352
return undefined;
351353
}
354+
return isRunnerResponseOk(payload) ? readRunnerResponseData(payload) : undefined;
352355
}
353356

354357
function completedWithoutRetainedResponseHint(

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

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,66 @@ export function classifyRunnerReportedError(
468468
});
469469
}
470470

471+
export type RunnerResponsePayload = {
472+
ok?: unknown;
473+
error?: { code?: unknown; message?: unknown; hint?: unknown };
474+
data?: unknown;
475+
};
476+
477+
/**
478+
* The one decoding of a runner response body (#2662). The envelope arrives at three readers — a
479+
* command's own response, the lifecycle journal a status probe reads back after the transport
480+
* response was lost, and the adoption `uptime` probe — and all three must agree on what is
481+
* readable, or a body one of them refuses becomes an answer for another. A body that is not JSON
482+
* at all is transport-shaped failure: a runner that died mid-write must not be read as having
483+
* answered.
484+
*/
485+
export function decodeRunnerResponseBody(text: string): RunnerResponsePayload {
486+
let parsed: unknown;
487+
try {
488+
parsed = JSON.parse(text);
489+
} catch {
490+
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
491+
}
492+
return parsed && typeof parsed === 'object' ? (parsed as RunnerResponsePayload) : {};
493+
}
494+
495+
/** The runner's `ok` is a Swift `Bool`, so only the literal `true` is an answer. */
496+
export function isRunnerResponseOk(payload: RunnerResponsePayload): boolean {
497+
return payload.ok === true;
498+
}
499+
500+
export function readRunnerResponseData(payload: RunnerResponsePayload): Record<string, unknown> {
501+
if (!payload.data || typeof payload.data !== 'object' || Array.isArray(payload.data)) return {};
502+
return payload.data as Record<string, unknown>;
503+
}
504+
505+
export function buildRunnerResponseError(
506+
payload: RunnerResponsePayload,
507+
logPath?: string,
508+
): AppError {
509+
const runnerErrorCode = readRunnerErrorCode(payload.error?.code);
510+
const errorMessage =
511+
typeof payload.error?.message === 'string' ? payload.error.message : undefined;
512+
const hint = typeof payload.error?.hint === 'string' ? payload.error.hint : undefined;
513+
const classification = classifyRunnerReportedError(runnerErrorCode);
514+
return new AppError(classification.code, errorMessage ?? 'Runner error', {
515+
runner: payload,
516+
...classification.details,
517+
xcodebuild: {
518+
exitCode: 1,
519+
stdout: '',
520+
stderr: '',
521+
},
522+
hint,
523+
logPath,
524+
});
525+
}
526+
527+
function readRunnerErrorCode(rawCode: unknown): string | undefined {
528+
return typeof rawCode === 'string' && rawCode.trim().length > 0 ? rawCode.trim() : undefined;
529+
}
530+
471531
export function resolveRunnerEarlyExitHint(
472532
message: string,
473533
stdout: string,

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

Lines changed: 0 additions & 64 deletions
This file was deleted.

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ import {
2828
type RunnerPhaseBudget,
2929
} from './runner-xctestrun.ts';
3030
import {
31+
buildRunnerResponseError,
32+
decodeRunnerResponseBody,
33+
isRunnerResponseOk,
34+
readRunnerResponseData,
3135
resolveRunnerRequestSignal,
3236
withRunnerCommandId,
3337
type RunnerCommand,
@@ -60,12 +64,6 @@ import {
6064
type RunnerDisposalOptions,
6165
} from './runner-disposal.ts';
6266
import { enrichRunnerFailureFromLog } from './runner-failure-diagnostics.ts';
63-
import {
64-
buildRunnerResponseError,
65-
decodeRunnerResponseBody,
66-
isRunnerResponseOk,
67-
readRunnerResponseData,
68-
} from './runner-response.ts';
6967
import {
7068
buildRunnerSessionId,
7169
normalizeRunnerStartupTimeoutMs,

0 commit comments

Comments
 (0)