Skip to content

Commit 7743291

Browse files
thymikeeclaude
andcommitted
fix(ios): refuse launch-confirmation runner steps the deadline cannot hold
The deadline only shrank the alert payload's timeout before the readiness preflight, and a spent deadline still dispatched with a 1 ms floor. An alert runner command now carries a host-side deadline that the exchange turns into the runner timeout right before the payload, after the preflight; a press left less than its whole watchdog, or any command left no time, is refused unsent with the typed `runner_command_deadline_spent`. Once the deadline has passed, the launch confirmation sends nothing, and a press refused unsent leaves the confirmation unanswered. Runner startup and transport overhead stay outside this bound. Refs #3861 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 80a53b5 commit 7743291

9 files changed

Lines changed: 256 additions & 98 deletions

File tree

‎packages/platform-apple/src/__tests__/alert.test.ts‎

Lines changed: 0 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -281,34 +281,3 @@ test('a macOS app session forwards the bundle its surface is scoped to', async (
281281
{ bundleId: 'com.example.app', surface: 'app', env: process.env },
282282
]);
283283
});
284-
285-
test('an accept whose deadline already passed still asks once and reports the typed failure', async () => {
286-
vi.useFakeTimers();
287-
// Every clock read lands 5 ms later, so the retry window a past deadline floors to 1 ms is
288-
// already spent by the time the loop could first check it.
289-
let nowMs = 1_000_000;
290-
const clock = vi.spyOn(Date, 'now').mockImplementation(() => (nowMs += 5));
291-
mockRunner.mockRejectedValue(runnerAbsence());
292-
293-
const outcome = actOnAppleAlert(
294-
IOS_SIMULATOR,
295-
runnerOptions,
296-
'accept',
297-
{ deadlineAtMs: 1_000_000 - 60_000 },
298-
process.env,
299-
)
300-
.catch((error: unknown) => error)
301-
.finally(() => clock.mockRestore());
302-
await vi.advanceTimersByTimeAsync(3_500);
303-
const failure = await outcome;
304-
305-
assert.ok(failure instanceof AppError, 'an expired deadline must reject with an AppError');
306-
assert.equal(failure.details?.runnerErrorCode, ALERT_NOT_FOUND_RUNNER_CODE);
307-
assert.equal(mockRunner.mock.calls.length, 1);
308-
assert.deepEqual(mockRunner.mock.calls[0]?.[1], {
309-
command: 'alert',
310-
action: 'accept',
311-
appBundleId: undefined,
312-
timeoutMs: 1,
313-
});
314-
});

‎packages/platform-apple/src/alert.ts‎

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,26 @@ function runAppleAlert(
5151
return async (action) =>
5252
(await runMacOsAlertAction(action, { ...target, env })) as Record<string, unknown>;
5353
}
54+
// A press needs its whole watchdog; a read is worth sending while any time is left.
55+
const deadline = (action: NativeAlertAction, timeoutMs: number) =>
56+
options?.deadlineAtMs === undefined
57+
? {}
58+
: {
59+
deadline: {
60+
atMs: options.deadlineAtMs,
61+
minTimeoutMs: action === 'get' ? 1 : timeoutMs,
62+
},
63+
};
5464
return async (action, timeoutMs) =>
5565
(await runAppleRunnerCommand(
5666
device,
57-
{ command: 'alert', action, appBundleId: options?.appBundleId, timeoutMs },
67+
{
68+
command: 'alert',
69+
action,
70+
appBundleId: options?.appBundleId,
71+
timeoutMs,
72+
...deadline(action, timeoutMs),
73+
},
5874
runnerOptions,
5975
)) as Record<string, unknown>;
6076
}
@@ -75,12 +91,7 @@ export async function readAppleAlert(
7591
options: AlertInteractorOptions | undefined,
7692
env: Readonly<EnvMap>,
7793
): Promise<Record<string, unknown>> {
78-
return await runAppleAlert(
79-
device,
80-
runnerOptions,
81-
options,
82-
env,
83-
)('get', cappedAtDeadline(DEFAULT_ALERT_TIMEOUT_MS, options));
94+
return await runAppleAlert(device, runnerOptions, options, env)('get', DEFAULT_ALERT_TIMEOUT_MS);
8495
}
8596

8697
/**
@@ -94,7 +105,7 @@ export async function awaitAppleAlert(
94105
env: Readonly<EnvMap>,
95106
): Promise<Record<string, unknown>> {
96107
const runAlert = runAppleAlert(device, runnerOptions, options, env);
97-
const timeout = cappedAtDeadline(options?.timeoutMs ?? DEFAULT_ALERT_TIMEOUT_MS, options);
108+
const timeout = options?.timeoutMs ?? DEFAULT_ALERT_TIMEOUT_MS;
98109
const start = Date.now();
99110
let firstAttempt = true;
100111
let lastAbsence: AppError | undefined;
@@ -128,40 +139,26 @@ export async function actOnAppleAlert(
128139
env: Readonly<EnvMap>,
129140
): Promise<Record<string, unknown>> {
130141
const runAlert = runAppleAlert(device, runnerOptions, options, env);
131-
const runnerTimeoutMs = cappedAtDeadline(
132-
isIosFamily(device) ? DEFAULT_ALERT_TIMEOUT_MS : ALERT_ACTION_RETRY_MS,
133-
options,
134-
);
135-
const retryWindowMs = cappedAtDeadline(ALERT_ACTION_RETRY_MS, options);
142+
const runnerTimeoutMs = isIosFamily(device) ? DEFAULT_ALERT_TIMEOUT_MS : ALERT_ACTION_RETRY_MS;
136143
const start = Date.now();
137144
let lastError: unknown;
138145
let firstAttempt = true;
139-
// The first attempt always runs, so a window a spent deadline floored to 1 ms still ends with the
140-
// backend's own answer rather than with no error at all.
141-
do {
146+
while (Date.now() - start < ALERT_ACTION_RETRY_MS) {
142147
try {
143-
const budgetMs = firstAttempt ? runnerTimeoutMs : remainingBudgetMs(start, retryWindowMs);
148+
const budgetMs = firstAttempt
149+
? runnerTimeoutMs
150+
: remainingBudgetMs(start, ALERT_ACTION_RETRY_MS);
144151
firstAttempt = false;
145152
return await runAlert(action, budgetMs);
146153
} catch (error) {
147154
lastError = error;
148155
if (!isAlertNotFoundError(error)) break;
149156
}
150157
await sleep(ALERT_POLL_INTERVAL_MS);
151-
} while (Date.now() - start < retryWindowMs);
158+
}
152159
throw withAlertFallbackHint(lastError);
153160
}
154161

155-
function cappedAtDeadline(budgetMs: number, options: AlertInteractorOptions | undefined): number {
156-
return capAtDeadline(budgetMs, options?.deadlineAtMs);
157-
}
158-
159-
/** A step's own budget, capped at the time the caller's deadline still leaves (at least 1 ms). */
160-
export function capAtDeadline(budgetMs: number, deadlineAtMs: number | undefined): number {
161-
if (deadlineAtMs === undefined) return budgetMs;
162-
return Math.max(1, Math.min(budgetMs, deadlineAtMs - Date.now()));
163-
}
164-
165162
function remainingBudgetMs(start: number, timeoutMs: number): number {
166163
return Math.max(1, timeoutMs - (Date.now() - start));
167164
}

‎packages/platform-apple/src/launch-confirmation.test.ts‎

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -741,37 +741,65 @@ test('abandoned accepts stop once the request cannot hold another press', async
741741
});
742742
});
743743

744-
test('every runner alert command of the answer is capped at the request time left', async () => {
744+
/** The Apple alert legs over the mocked runner client, as the session interactor binds them. */
745+
function runnerAlertLegs() {
746+
return {
747+
awaitAlert: async (options) => await awaitAppleAlert(simulator, {}, options, {}),
748+
readAlert: async (options) => await readAppleAlert(simulator, {}, options, {}),
749+
acceptAlert: async (options) => await actOnAppleAlert(simulator, {}, 'accept', options, {}),
750+
} satisfies Pick<Interactor, 'awaitAlert' | 'readAlert' | 'acceptAlert'>;
751+
}
752+
753+
test('a deadline spent by the press sends no verification read and keeps its unknown effect', async () => {
745754
const runner = vi.mocked(runAppleRunnerCommand);
746755
await onFakeClock(async () => {
747-
const sent: Array<Readonly<{ action: unknown; timeoutMs: unknown }>> = [];
756+
const deadlineAtMs = Date.now() + 12_000;
757+
const sent: unknown[] = [];
748758
runner.mockImplementation(async (_device, command) => {
749-
const { action, timeoutMs } = command as { action?: string; timeoutMs?: number };
750-
sent.push({ action, timeoutMs });
751-
if (action !== 'accept') return CONFIRMATION;
752-
vi.advanceTimersByTime(timeoutMs ?? 0);
759+
sent.push(command);
760+
if ((command as { action?: string }).action !== 'accept') return CONFIRMATION;
761+
vi.advanceTimersByTime(12_000);
753762
throw runnerMainThreadTimeout();
754763
});
755764
vi.mocked(resolveIosSimulatorDeepLinkBundleId).mockResolvedValueOnce('com.example.app');
756-
const interactor = {
757-
awaitAlert: async (options) => await awaitAppleAlert(simulator, {}, options, {}),
758-
readAlert: async (options) => await readAppleAlert(simulator, {}, options, {}),
759-
acceptAlert: async (options) => await actOnAppleAlert(simulator, {}, 'accept', options, {}),
760-
} satisfies Pick<Interactor, 'awaitAlert' | 'readAlert' | 'acceptAlert'>;
761765

762766
await expect(
763767
answerSimulatorLaunchConfirmation(
764768
simulator,
765769
{ url: 'example://automation', appBundleId: 'com.example.app' },
766-
Promise.resolve(interactor as Interactor),
770+
Promise.resolve(runnerAlertLegs() as Interactor),
767771
new AbortController().signal,
768-
Date.now() + 6_000,
772+
deadlineAtMs,
769773
),
770-
).resolves.toEqual(STILL_PRESENT);
774+
).resolves.toEqual({ outcome: 'unreadable', step: 'alert-accept' });
771775
expect(sent).toEqual([
772-
{ action: 'get', timeoutMs: 3_000 },
773-
{ action: 'accept', timeoutMs: 6_000 },
774-
{ action: 'get', timeoutMs: 1 },
776+
expect.objectContaining({
777+
action: 'get',
778+
timeoutMs: 3_000,
779+
deadline: { atMs: deadlineAtMs, minTimeoutMs: 1 },
780+
}),
781+
expect.objectContaining({
782+
action: 'accept',
783+
timeoutMs: DEFAULT_ALERT_TIMEOUT_MS,
784+
deadline: { atMs: deadlineAtMs, minTimeoutMs: DEFAULT_ALERT_TIMEOUT_MS },
785+
}),
775786
]);
776787
}).finally(() => runner.mockReset());
777788
});
789+
790+
test('a press the runner client refused unsent leaves the confirmation unanswered unread', async () => {
791+
const acceptAlert = vi.fn(async () => {
792+
throw new AppError('COMMAND_FAILED', 'The deadline left no time to send this runner command.', {
793+
reason: 'runner_command_deadline_spent',
794+
dispatched: 'no',
795+
});
796+
});
797+
const { port: device } = port(async () => CONFIRMATION, {
798+
acceptAlert,
799+
deadlineAtMs: Date.now() + 60_000,
800+
});
801+
802+
await expect(answerLaunchConfirmation(device)).resolves.toEqual(STILL_PRESENT);
803+
expect(acceptAlert).toHaveBeenCalledOnce();
804+
expect(device.readAlert).not.toHaveBeenCalled();
805+
});

‎packages/platform-apple/src/launch-confirmation.ts‎

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,13 @@ import { invalidRuntimeContract } from '@agent-device/contracts/runtime-contract
44
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
55
import type { DeviceInfo } from '@agent-device/kernel/device';
66
import { AppError } from '@agent-device/kernel/errors';
7-
import { alertIfPresent, capAtDeadline } from './alert.ts';
7+
import { alertIfPresent } from './alert.ts';
88
import { resolveIosSimulatorDeepLinkBundleId } from './core/app-resolution.ts';
9-
import { RUNNER_READY_PREFLIGHT_TIMEOUT_MS } from './runner/runner-contract.ts';
9+
import {
10+
isRunnerCommandDeadlineSpentError,
11+
RUNNER_READY_PREFLIGHT_TIMEOUT_MS,
12+
runnerCommandDeadlineSpentError,
13+
} from './runner/runner-contract.ts';
1014
import { isRunnerMainThreadTimeoutError } from './runner/runner-error-classification.ts';
1115

1216
export const LAUNCH_CONFIRMATION_FOREIGN_APP_REASON = 'launch_confirmation_foreign_app';
@@ -62,8 +66,8 @@ export type LaunchConfirmationTarget = Readonly<{ url: string; appBundleId: stri
6266
export type LaunchConfirmationPort = Readonly<{
6367
appBundleId: string;
6468
/**
65-
* When the enclosing request must have its result. Every step is capped at it, and only a request
66-
* with one has time to press `Open` again.
69+
* When the enclosing request must have its result. Once it passes, no step is sent; runner
70+
* timeouts are capped at it; and only a request with one has time to press `Open` again.
6771
*/
6872
deadlineAtMs: number | undefined;
6973
/** Initial presentation wait, or `undefined` when no alert appears within its window. */
@@ -136,6 +140,11 @@ async function acceptConfirmation(
136140
(error: unknown) => ({ error }),
137141
);
138142
if (!failure) return accepted();
143+
if (isRunnerCommandDeadlineSpentError(failure.error)) {
144+
// Refused unsent: nothing was pressed, so the confirmation just seen is still up.
145+
reportUnanswered('alert-still-present', { pressSent: false });
146+
return { outcome: 'unanswered', reason: 'alert-still-present' };
147+
}
139148
const attempt = await verifyFailedAcceptance(port, original, failure.error);
140149
if (attempt.outcome !== 'unanswered') return attempt;
141150
const remainingMs = timeLeft(port.deadlineAtMs);
@@ -253,19 +262,36 @@ export function createLaunchConfirmationPort(
253262
throw invalidRuntimeContract('Apple interactor has no alert wait, read or accept leg');
254263
}
255264
const target = { appBundleId, surface: 'app', deadlineAtMs } as const;
265+
// Once the deadline has passed, a step is refused before anything is sent.
266+
const beforeDeadline = async <T>(step: () => Promise<T>): Promise<T> => {
267+
if (deadlineAtMs !== undefined && Date.now() >= deadlineAtMs) {
268+
throw runnerCommandDeadlineSpentError();
269+
}
270+
return await step();
271+
};
256272
return Object.freeze({
257273
appBundleId,
258274
deadlineAtMs,
259275
awaitAlert: async () =>
260-
await alertIfPresent(
261-
awaitAlert({ ...target, timeoutMs: LAUNCH_CONFIRMATION_PRESENTATION_TIMEOUT_MS }),
276+
await beforeDeadline(
277+
async () =>
278+
await alertIfPresent(
279+
awaitAlert({ ...target, timeoutMs: LAUNCH_CONFIRMATION_PRESENTATION_TIMEOUT_MS }),
280+
),
262281
),
263-
readAlert: async () => await alertIfPresent(readAlert(target)),
264-
acceptAlert: async () => await acceptAlert(target),
282+
readAlert: async () =>
283+
await beforeDeadline(async () => await alertIfPresent(readAlert(target))),
284+
acceptAlert: async () => await beforeDeadline(async () => await acceptAlert(target)),
265285
resolveUrlOwner: async () =>
266-
await resolveIosSimulatorDeepLinkBundleId(device, url, {
267-
timeoutMs: capAtDeadline(URL_OWNER_LOOKUP_TIMEOUT_MS, deadlineAtMs),
268-
signal,
269-
}),
286+
await beforeDeadline(
287+
async () =>
288+
await resolveIosSimulatorDeepLinkBundleId(device, url, {
289+
timeoutMs:
290+
deadlineAtMs === undefined
291+
? URL_OWNER_LOOKUP_TIMEOUT_MS
292+
: Math.min(URL_OWNER_LOOKUP_TIMEOUT_MS, deadlineAtMs - Date.now()),
293+
signal,
294+
}),
295+
),
270296
});
271297
}

0 commit comments

Comments
 (0)