Skip to content

Commit 37a5ad4

Browse files
thymikeeclaude
andauthored
fix(ios): disclose whether a canceled read-only runner send was written (#3409)
* fix(ios): disclose whether a canceled read-only runner send was written Follow-up to #3385. The read-only route (waitForRunner) threw a bare canceled error, so a cancellation that landed before any connect attempt was charged and drained with one status poll instead of withdrawn. It now discloses `dispatched: no` when no attempt could have written the command, and `unknown` once an attempt was interrupted mid-flight or an earlier attempt may have written it. Pins two exchange behaviors with tests: a refused connection withdraws its charge whether or not the request was canceled (the runner never received the command), and a drain whose status read fails stops at once with the charge left abandoned. Refs #3383 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(ios): keep dispatched no when a canceled runner route proves nothing was written Each route of the read-only connect loop replaced its failure with a bare canceled error, so a cancellation whose own failure proved nothing was written (a usbmux connect still in progress, a refused fetch, a simulator curl that could not connect) reported `dispatched: unknown`. Routes now keep `no` when that failure is the proof, and the final simulator post combines the loop's write evidence with its own failure the same way. An abort that interrupts a POST, or the request's shared abort reason, still reads as possibly written. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent ab33587 commit 37a5ad4

5 files changed

Lines changed: 248 additions & 8 deletions

File tree

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import assert from 'node:assert/strict';
2+
import net from 'node:net';
23
import type { ExecResult } from '@agent-device/host-kit/command';
34
import { createRequestCanceledError, isRequestCanceledError } from '@agent-device/kernel/errors';
45
import { withKeyedLock } from '@agent-device/kernel/keyed-lock';
@@ -15,6 +16,7 @@ vi.mock('../runner-transport.ts', async (importOriginal) => {
1516
import { executeRunnerExchange } from '../runner-exchange.ts';
1617
import { RunnerCommandAccounting, type RunnerSession } from '../runner-session-types.ts';
1718
import { IOS_SIMULATOR } from './device-fixtures.ts';
19+
import { captureDiagnostics } from './runner-session-fixtures.ts';
1820
import {
1921
startFakeRunnerServer,
2022
type FakeRunnerResponse,
@@ -374,6 +376,59 @@ test('a canceled command the journal never accepted releases after one read and
374376
assert.equal(session.commandCharges.hasAbandonedCharges, true);
375377
});
376378

379+
test('a drain whose status read fails stops at once and leaves the charge abandoned', async () => {
380+
server = await startFakeRunnerServer({
381+
longPress: [{ kind: 'hold' }],
382+
status: [journalState('started'), { kind: 'exit' }],
383+
});
384+
const runner = server;
385+
const session = sessionFor(runner.port);
386+
const controller = new AbortController();
387+
const startedAtMs = Date.now();
388+
let settledAfterMs = -1;
389+
390+
const diagnostics = await captureDiagnostics(async () => {
391+
const exchange = executeRunnerExchange(
392+
IOS_SIMULATOR,
393+
session,
394+
LONG_PRESS,
395+
undefined,
396+
10_000,
397+
async () => {},
398+
controller.signal,
399+
);
400+
await abortOnceReceived(runner, 'longPress', controller);
401+
await assert.rejects(exchange, isRequestCanceledError);
402+
settledAfterMs = Date.now() - startedAtMs;
403+
});
404+
405+
assert.ok(diagnostics.includes('"outcome":"status_unavailable"'), diagnostics);
406+
assert.equal(statusPolls(runner).length, 2);
407+
assert.ok(settledAfterMs < 2_000, `the drain held for ${settledAfterMs}ms`);
408+
assert.equal(session.commandCharges.hasAbandonedCharges, true);
409+
});
410+
411+
test('a refused connection withdraws its charge although nothing canceled it', async () => {
412+
const port = await closedLocalPort();
413+
const session = sessionFor(port);
414+
session.lastHealthyMutation = { atMs: Date.now(), appBundleId: LONG_PRESS.appBundleId };
415+
416+
await assert.rejects(
417+
executeRunnerExchange(IOS_SIMULATOR, session, LONG_PRESS, undefined, 10_000, async () => {}),
418+
(error: unknown) => !isRequestCanceledError(error),
419+
);
420+
421+
assert.equal(session.commandCharges.hasOutstandingCharges, false);
422+
});
423+
424+
async function closedLocalPort(): Promise<number> {
425+
const listener = net.createServer();
426+
await new Promise<void>((resolve) => listener.listen(0, '127.0.0.1', resolve));
427+
const { port } = listener.address() as net.AddressInfo;
428+
await new Promise<void>((resolve) => listener.close(() => resolve()));
429+
return port;
430+
}
431+
377432
test('a drain that outlives the command deadline settles and leaves the charge abandoned', async () => {
378433
server = await startFakeRunnerServer({
379434
longPress: [{ kind: 'hold' }],

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

Lines changed: 152 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ import { afterEach, beforeEach, test, vi } from 'vitest';
22
import assert from 'node:assert/strict';
33
import type { ExecBackgroundResult } from '@agent-device/host-kit/command';
44
import { appleRunnerTestHost } from '../test-host.ts';
5-
import { AppError } from '@agent-device/kernel/errors';
5+
import {
6+
AppError,
7+
createRequestCanceledError,
8+
isRequestCanceledError,
9+
} from '@agent-device/kernel/errors';
610
import { RunnerCommandAccounting, type RunnerSession } from '../runner-session-types.ts';
711
import {
812
iosDevice,
@@ -83,6 +87,153 @@ test('waitForRunner propagates request cancellation without fallback', async ()
8387
);
8488
});
8589

90+
test('waitForRunner discloses whether a canceled command could have been written', async () => {
91+
const canceledBeforeAnyAttempt = AbortSignal.abort(createRequestCanceledError());
92+
await assert.rejects(
93+
() =>
94+
waitForRunner(
95+
iosSimulator,
96+
8100,
97+
{ command: 'snapshot' },
98+
undefined,
99+
5_000,
100+
undefined,
101+
canceledBeforeAnyAttempt,
102+
),
103+
(error: unknown) =>
104+
isRequestCanceledError(error) && (error as AppError).details?.dispatched === 'no',
105+
);
106+
107+
const controller = new AbortController();
108+
vi.stubGlobal(
109+
'fetch',
110+
vi.fn(
111+
(_url: string, init: RequestInit) =>
112+
new Promise((_resolve, reject) => {
113+
init.signal?.addEventListener('abort', () => reject(init.signal?.reason));
114+
controller.abort(createRequestCanceledError());
115+
}),
116+
),
117+
);
118+
await assert.rejects(
119+
() =>
120+
waitForRunner(
121+
iosSimulator,
122+
8100,
123+
{ command: 'snapshot' },
124+
undefined,
125+
5_000,
126+
undefined,
127+
controller.signal,
128+
),
129+
(error: unknown) =>
130+
isRequestCanceledError(error) && (error as AppError).details?.dispatched === 'unknown',
131+
);
132+
});
133+
134+
function refusedConnect(): Error {
135+
return Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:8100'), { code: 'ECONNREFUSED' });
136+
}
137+
138+
function canceledWithDispatch(dispatched: string) {
139+
return (error: unknown) =>
140+
isRequestCanceledError(error) && (error as AppError).details?.dispatched === dispatched;
141+
}
142+
143+
test('waitForRunner keeps no when usbmux is canceled while it is still connecting', async () => {
144+
const controller = new AbortController();
145+
mockUsbmuxPostCommand.mockImplementation(async () => {
146+
controller.abort(createRequestCanceledError());
147+
throw createRequestCanceledError({ dispatched: 'no' });
148+
});
149+
150+
await assert.rejects(
151+
() =>
152+
waitForRunner(
153+
xctestIosDevice,
154+
8100,
155+
{ command: 'snapshot' },
156+
undefined,
157+
5_000,
158+
undefined,
159+
controller.signal,
160+
),
161+
canceledWithDispatch('no'),
162+
);
163+
});
164+
165+
test('waitForRunner keeps no when a canceled network attempt was refused', async () => {
166+
const controller = new AbortController();
167+
vi.stubGlobal(
168+
'fetch',
169+
vi.fn(async () => {
170+
controller.abort(createRequestCanceledError());
171+
throw refusedConnect();
172+
}),
173+
);
174+
175+
await assert.rejects(
176+
() =>
177+
waitForRunner(
178+
iosSimulator,
179+
8100,
180+
{ command: 'snapshot' },
181+
undefined,
182+
5_000,
183+
undefined,
184+
controller.signal,
185+
),
186+
canceledWithDispatch('no'),
187+
);
188+
});
189+
190+
test('waitForRunner keeps no when a canceled simulator fallback could not connect', async () => {
191+
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(refusedConnect()));
192+
const controller = new AbortController();
193+
mockRunCmd.mockImplementation(async () => {
194+
controller.abort(createRequestCanceledError());
195+
return { exitCode: 7, stdout: '', stderr: 'curl: (7) Failed to connect' };
196+
});
197+
198+
await assert.rejects(
199+
() =>
200+
waitForRunner(
201+
iosSimulator,
202+
8100,
203+
{ command: 'snapshot' },
204+
undefined,
205+
5_000,
206+
makeReadyRunnerSession(),
207+
controller.signal,
208+
),
209+
canceledWithDispatch('no'),
210+
);
211+
});
212+
213+
test('waitForRunner keeps no when the final simulator post is canceled after a refused connect', async () => {
214+
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(refusedConnect()));
215+
const controller = new AbortController();
216+
mockRunCmd.mockImplementation(async () => {
217+
controller.abort(createRequestCanceledError());
218+
return { exitCode: 7, stdout: '', stderr: 'curl: (7) Failed to connect' };
219+
});
220+
221+
await assert.rejects(
222+
() =>
223+
waitForRunner(
224+
iosSimulator,
225+
8100,
226+
{ command: 'snapshot' },
227+
undefined,
228+
100,
229+
undefined,
230+
controller.signal,
231+
),
232+
canceledWithDispatch('no'),
233+
);
234+
assert.equal(mockRunCmd.mock.calls.length, 1);
235+
});
236+
86237
test('waitForRunner reuses cached physical-device tunnel IP across commands', async () => {
87238
mockUsbmuxPostCommand.mockRejectedValue(usbmuxDeviceUnattachedError());
88239
stubSuccessfulFetch();

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,8 @@ async function sendRunnerCommandAfterPreflight(params: {
302302
}
303303

304304
/**
305-
* A send that provably wrote nothing withdraws its charge. Otherwise this process stopped waiting on
305+
* A send that provably wrote nothing withdraws its charge, whether or not it was canceled: a refused
306+
* connection, or a cancellation the transport saw before its POST. Otherwise this process stopped waiting on
306307
* a command the runner may hold, so the charge stays as abandoned, and a canceled request also waits
307308
* out the command's execution before it settles (#3383).
308309
*/

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,10 @@ export class RunnerCommandAccounting {
260260
if (index !== -1) this.charges[index]!.abandoned = true;
261261
}
262262

263-
/** Withdraw the charge of a send that provably wrote nothing: the runner holds no such command. */
263+
/**
264+
* Withdraw the charge of a send that provably wrote nothing — a refused connection, or a cancellation
265+
* seen before the POST (`dispatched: no`). The runner holds no such command, canceled or not.
266+
*/
264267
withdrawUnsent(commandId: string | undefined): void {
265268
const index = this.findChargeIndex(commandId);
266269
if (index !== -1) this.charges.splice(index, 1);

‎packages/platform-apple/src/runner/runner-startup-transport.ts‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@ export async function waitForRunner(
102102
lastError = err;
103103
if (!isRunnerCommandProvablyUnwritten(err)) commandMayHaveBeenWritten = true;
104104
},
105+
}).catch((error: unknown) => {
106+
if (isRequestCanceledError(error) && !isRunnerCommandProvablyUnwritten(error)) {
107+
commandMayHaveBeenWritten = true;
108+
}
109+
throw error;
105110
});
106111
if (response) return response;
107112
throw buildRunnerEndpointProbeError({
@@ -127,7 +132,7 @@ export async function waitForRunner(
127132
);
128133
} catch (error) {
129134
if (signal?.aborted || isRequestCanceledError(error)) {
130-
throw createRequestCanceledError();
135+
throw canceledRunnerConnect(commandMayHaveBeenWritten);
131136
}
132137
if (isUsbmuxDeviceUnattachedError(error)) throw error;
133138
if (!lastError) {
@@ -136,7 +141,7 @@ export async function waitForRunner(
136141
}
137142

138143
if (signal?.aborted) {
139-
throw createRequestCanceledError();
144+
throw canceledRunnerConnect(commandMayHaveBeenWritten);
140145
}
141146

142147
if (device.kind === 'simulator') {
@@ -154,6 +159,11 @@ export async function waitForRunner(
154159
remainingMs,
155160
signal,
156161
).catch((error: unknown) => {
162+
if (signal?.aborted || isRequestCanceledError(error)) {
163+
throw canceledRunnerConnect(
164+
commandMayHaveBeenWritten || !isProvablyUnwrittenBeforeCancel(error, signal),
165+
);
166+
}
157167
throw withRunnerWriteEvidence(error, commandMayHaveBeenWritten);
158168
});
159169
return new Response(simResponse.body, { status: simResponse.status });
@@ -177,6 +187,26 @@ export async function waitForRunner(
177187
);
178188
}
179189

190+
function canceledRunnerConnect(commandMayHaveBeenWritten: boolean): AppError {
191+
return createRequestCanceledError({ dispatched: commandMayHaveBeenWritten ? 'unknown' : 'no' });
192+
}
193+
194+
/**
195+
* The cancellation one route reports. It keeps `dispatched: no` only when the failure it replaces
196+
* proves nothing was written (a refused connect, or a cancel seen before the POST); an abort that
197+
* interrupted the POST itself proves nothing, so the loop reads it as possibly written.
198+
*/
199+
function canceledRunnerAttempt(error: unknown, signal: AbortSignal | undefined): AppError {
200+
return createRequestCanceledError(
201+
isProvablyUnwrittenBeforeCancel(error, signal) ? { dispatched: 'no' } : {},
202+
);
203+
}
204+
205+
/** The request's shared abort reason is never evidence about one send. */
206+
function isProvablyUnwrittenBeforeCancel(error: unknown, signal: AbortSignal | undefined): boolean {
207+
return error !== signal?.reason && isRunnerCommandProvablyUnwritten(error);
208+
}
209+
180210
/**
181211
* An earlier attempt that may have written the command may also have executed it, so the loop's
182212
* failure is `unknown` whatever a later refused attempt stamped.
@@ -391,7 +421,7 @@ async function tryRunnerRoute(
391421
);
392422
} catch (error) {
393423
if (params.signal?.aborted || isRequestCanceledError(error)) {
394-
throw createRequestCanceledError();
424+
throw canceledRunnerAttempt(error, params.signal);
395425
}
396426
if (isUsbmuxDeviceUnattachedError(error)) {
397427
if (!canFallBackFromUsbmux(device, error)) {
@@ -444,7 +474,7 @@ async function tryRunnerEndpoints(
444474
);
445475
} catch (error) {
446476
if (signal?.aborted || isRequestCanceledError(error)) {
447-
throw createRequestCanceledError();
477+
throw canceledRunnerAttempt(error, signal);
448478
}
449479
onError(endpoint, error);
450480
}
@@ -470,7 +500,7 @@ async function tryRunnerSimulatorEndpoint(
470500
return new Response(simResponse.body, { status: simResponse.status });
471501
} catch (error) {
472502
if (signal?.aborted || isRequestCanceledError(error)) {
473-
throw createRequestCanceledError();
503+
throw canceledRunnerAttempt(error, signal);
474504
}
475505
onError(error);
476506
return null;

0 commit comments

Comments
 (0)