Skip to content

Commit 948817a

Browse files
thymikeeclaude
andcommitted
fix(ios): bound the launch-confirmation re-press by the open request's deadline
The re-press after a watchdog-abandoned accept used a fresh 25 s budget from the first press, which ignored the time open had already spent, and reserved only the press watchdog. The daemon now hands the open its request deadline: the enforced daemon deadline when the request has one, otherwise the transport admission time plus what the client envelope leaves the daemon. Another press starts only while that deadline covers the press and its verification read, each with a readiness preflight, and every runner alert command and the URL owner lookup are capped at the time left. A request without a deadline is not re-pressed. Refs #3861 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 097bead commit 948817a

17 files changed

Lines changed: 344 additions & 62 deletions

File tree

‎packages/command-registry/src/timeout-policy.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,19 @@ export function resolveCommandRequestTimeoutMs(
103103
);
104104
}
105105

106+
/**
107+
* How long the daemon may work on a request before its client envelope expires, less the margin
108+
* that lets the daemon's own result win that race. For a command with an enforced daemon deadline
109+
* this is that deadline.
110+
*/
111+
export function resolveCommandDaemonBudgetMs(
112+
policy: CommandTimeoutPolicy,
113+
input: RequestTimeoutInput,
114+
): number | undefined {
115+
const envelopeMs = resolveCommandRequestTimeoutMs(policy, input);
116+
return envelopeMs === undefined ? undefined : envelopeMs - REQUEST_TIMEOUT_BUDGET_MARGIN_MS;
117+
}
118+
106119
/** Resolves an enforced daemon request deadline, when the command declares one. */
107120
export function resolveCommandDaemonTimeoutMs(
108121
policy: CommandTimeoutPolicy,

‎packages/contracts/src/application-lifecycle-runtime.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ export type ApplicationLifecycleExecution = Readonly<{
3333
* means the platform's default boot wait; `prepare` derives its own deadline from `timeoutMs`.
3434
*/
3535
startupDeadlineAtMs?: number;
36+
/**
37+
* Absolute time by which the request must have its result: its enforced daemon deadline, or its
38+
* admission plus what its client envelope leaves the daemon. Absent for a request no transport
39+
* admitted.
40+
*/
41+
requestDeadlineAtMs?: number;
3642
requestId?: string;
3743
logPath?: string;
3844
traceLogPath?: string;

‎packages/contracts/src/interactor-types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,8 @@ export type Interactor = {
541541
*/
542542
export type AlertInteractorOptions = {
543543
timeoutMs?: number;
544+
/** Absolute time no runner alert command may outlast; each leg caps its own budget at it. */
545+
deadlineAtMs?: number;
544546
/** The daemon request's cancellation; owners whose transport can abort thread it into the legs. */
545547
signal?: AbortSignal;
546548
appBundleId?: string;

‎packages/daemon/src/core/daemon-command-registry.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ import {
1111
resolveCommandDeviceClaimPolicy,
1212
resolveCommandTimeoutPolicy,
1313
} from '@agent-device/command-registry/registry';
14-
import { resolveCommandDaemonTimeoutMs } from '@agent-device/command-registry/timeout-policy';
14+
import {
15+
resolveCommandDaemonBudgetMs,
16+
resolveCommandDaemonTimeoutMs,
17+
} from '@agent-device/command-registry/timeout-policy';
1518
import type { RefFrameEffect } from '@agent-device/contracts/replay';
1619
import type { DaemonRequest } from './daemon-request.ts';
1720

@@ -37,6 +40,11 @@ export function resolveDaemonRequestTimeoutMs(req: DaemonRequest): number | unde
3740
return resolveCommandDaemonTimeoutMs(resolveCommandTimeoutPolicy(req.command), req);
3841
}
3942

43+
/** How long the daemon may work on this request before its client gives up on the result. */
44+
export function resolveDaemonRequestBudgetMs(req: DaemonRequest): number | undefined {
45+
return resolveCommandDaemonBudgetMs(resolveCommandTimeoutPolicy(req.command), req);
46+
}
47+
4048
export function getDaemonCommandRoute(command: string): DaemonCommandRoute {
4149
return getDaemonCommandDescriptor(command)?.route ?? 'generic';
4250
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { afterEach, expect, test, vi } from 'vitest';
2+
import {
3+
clearRequestAbortRegistration,
4+
registerRequestAbort,
5+
withRequestDeadline,
6+
} from '@agent-device/host-kit/request';
7+
import type { ApplicationLifecycleExecution } from '@agent-device/contracts/application-lifecycle-runtime';
8+
import type { CommandFlags } from '@agent-device/contracts/command';
9+
import { applicationLifecycleExecutionFromRequest } from './application-lifecycle-execution.ts';
10+
11+
const ADMITTED_AT_MS = 1_000_000;
12+
13+
afterEach(() => {
14+
vi.useRealTimers();
15+
});
16+
17+
function openExecution(
18+
requestId: string | undefined,
19+
flags: CommandFlags = {},
20+
): ApplicationLifecycleExecution {
21+
return applicationLifecycleExecutionFromRequest(
22+
{
23+
token: 'token',
24+
session: 'default',
25+
command: 'open',
26+
positionals: ['com.example.app'],
27+
flags,
28+
meta: { requestId },
29+
},
30+
'/tmp/request.log',
31+
);
32+
}
33+
34+
/** Admits `requestId` at `ADMITTED_AT_MS`, then reads its execution 5 s later. */
35+
function executionAfterAdmission(requestId: string, flags?: CommandFlags) {
36+
vi.useFakeTimers({ toFake: ['Date'] });
37+
vi.setSystemTime(ADMITTED_AT_MS);
38+
const registration = registerRequestAbort(requestId);
39+
try {
40+
vi.setSystemTime(ADMITTED_AT_MS + 5_000);
41+
return openExecution(requestId, flags);
42+
} finally {
43+
clearRequestAbortRegistration(registration);
44+
}
45+
}
46+
47+
test('an open must settle within its client envelope less the daemon result margin', () => {
48+
expect(executionAfterAdmission('open-default-envelope').requestDeadlineAtMs).toBe(
49+
ADMITTED_AT_MS + 60_000,
50+
);
51+
});
52+
53+
test('open --timeout moves the deadline with the envelope it widens', () => {
54+
expect(
55+
executionAfterAdmission('open-widened-envelope', { timeoutMs: 120_000 }).requestDeadlineAtMs,
56+
).toBe(ADMITTED_AT_MS + 120_000);
57+
});
58+
59+
test('an enforced request deadline is the deadline', async () => {
60+
vi.useFakeTimers({ toFake: ['Date'] });
61+
vi.setSystemTime(ADMITTED_AT_MS);
62+
let execution: ApplicationLifecycleExecution | undefined;
63+
await withRequestDeadline('open-in-bounded-batch', 20_000, async () => {
64+
execution = openExecution('open-in-bounded-batch');
65+
return { ok: true, data: {} };
66+
});
67+
expect(execution?.requestDeadlineAtMs).toBe(ADMITTED_AT_MS + 20_000);
68+
});
69+
70+
test('a request no transport admitted has no deadline', () => {
71+
expect(openExecution(undefined).requestDeadlineAtMs).toBeUndefined();
72+
expect(openExecution('never-admitted').requestDeadlineAtMs).toBeUndefined();
73+
});

‎packages/daemon/src/sessions/application-lifecycle-execution.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1+
import {
2+
getRequestAdmittedAtMs,
3+
getRequestExecutionDeadlineMs,
4+
} from '@agent-device/host-kit/request';
15
import { resolvePlannedOperations } from '../core/execution-plan.ts';
6+
import { resolveDaemonRequestBudgetMs } from '../core/daemon-command-registry.ts';
27
import type { ApplicationLifecycleExecution } from '@agent-device/contracts/application-lifecycle-runtime';
38
import { resolveRunnerLogicalLeaseContext } from '../core/lease-context.ts';
49
import type { DaemonRequest } from '../core/daemon-request.ts';
@@ -10,6 +15,7 @@ export function applicationLifecycleExecutionFromRequest(
1015
traceLogPath?: string,
1116
): ApplicationLifecycleExecution {
1217
return {
18+
requestDeadlineAtMs: requestDeadlineAtMs(req),
1319
requestId: req.meta?.requestId,
1420
logPath,
1521
traceLogPath,
@@ -25,3 +31,17 @@ export function applicationLifecycleExecutionFromRequest(
2531
plannedOperations: resolvePlannedOperations(req.internal?.executionPlan),
2632
};
2733
}
34+
35+
/**
36+
* An enforced daemon deadline is the request's deadline. Otherwise the client envelope started when
37+
* the transport admitted the request, so the deadline is that moment plus the envelope's daemon
38+
* budget.
39+
*/
40+
function requestDeadlineAtMs(req: DaemonRequest): number | undefined {
41+
const requestId = req.meta?.requestId;
42+
const enforcedAtMs = getRequestExecutionDeadlineMs(requestId);
43+
if (enforcedAtMs !== undefined) return enforcedAtMs;
44+
const admittedAtMs = getRequestAdmittedAtMs(requestId);
45+
const budgetMs = resolveDaemonRequestBudgetMs(req);
46+
return admittedAtMs === undefined || budgetMs === undefined ? undefined : admittedAtMs + budgetMs;
47+
}

‎packages/host-kit/src/internal/request-cancel.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@ type RequestCancelState = {
1212
requestAbortControllers: Map<string, RequestAbortController>;
1313
};
1414

15-
type RequestAbortController = AbortController & { executionDeadlineMs?: number };
15+
type RequestAbortController = AbortController & {
16+
executionDeadlineMs?: number;
17+
/** When the transport admitted the request; its client envelope started at the same moment. */
18+
admittedAtMs?: number;
19+
};
1620

1721
const REQUEST_CANCEL_SLOT = Symbol('requestCancel');
1822
const requestCancelState = (): RequestCancelState =>
@@ -90,6 +94,7 @@ export function registerRequestAbort(
9094
}
9195
evictOldestEntries(requestAbortControllers());
9296
const controller: RequestAbortController = new AbortController();
97+
controller.admittedAtMs = Date.now();
9398
controller.executionDeadlineMs = parentRequestId
9499
? requestAbortControllers().get(parentRequestId)?.executionDeadlineMs
95100
: undefined;
@@ -154,6 +159,11 @@ export function getRequestExecutionDeadlineMs(requestId: string | undefined): nu
154159
return requestId ? requestAbortControllers().get(requestId)?.executionDeadlineMs : undefined;
155160
}
156161

162+
/** When the transport admitted the request, or `undefined` for a request it never admitted. */
163+
export function getRequestAdmittedAtMs(requestId: string | undefined): number | undefined {
164+
return requestId ? requestAbortControllers().get(requestId)?.admittedAtMs : undefined;
165+
}
166+
157167
export function throwIfRequestCanceled(requestId: string | undefined): void {
158168
getRequestSignal(requestId)?.throwIfAborted();
159169
if (isRequestCanceled(requestId)) {

‎packages/host-kit/src/request.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ export {
22
cancelAllRequests,
33
clearRequestAbortRegistration,
44
clearRequestCanceled,
5+
getRequestAdmittedAtMs,
56
getRequestSignal,
67
getRequestExecutionDeadlineMs,
78
isRequestCanceled,

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

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,12 @@ export async function readAppleAlert(
7575
options: AlertInteractorOptions | undefined,
7676
env: Readonly<EnvMap>,
7777
): Promise<Record<string, unknown>> {
78-
return await runAppleAlert(device, runnerOptions, options, env)('get', DEFAULT_ALERT_TIMEOUT_MS);
78+
return await runAppleAlert(
79+
device,
80+
runnerOptions,
81+
options,
82+
env,
83+
)('get', cappedAtDeadline(DEFAULT_ALERT_TIMEOUT_MS, options));
7984
}
8085

8186
/**
@@ -89,7 +94,7 @@ export async function awaitAppleAlert(
8994
env: Readonly<EnvMap>,
9095
): Promise<Record<string, unknown>> {
9196
const runAlert = runAppleAlert(device, runnerOptions, options, env);
92-
const timeout = options?.timeoutMs ?? DEFAULT_ALERT_TIMEOUT_MS;
97+
const timeout = cappedAtDeadline(options?.timeoutMs ?? DEFAULT_ALERT_TIMEOUT_MS, options);
9398
const start = Date.now();
9499
let firstAttempt = true;
95100
let lastAbsence: AppError | undefined;
@@ -123,15 +128,17 @@ export async function actOnAppleAlert(
123128
env: Readonly<EnvMap>,
124129
): Promise<Record<string, unknown>> {
125130
const runAlert = runAppleAlert(device, runnerOptions, options, env);
126-
const runnerTimeoutMs = isIosFamily(device) ? DEFAULT_ALERT_TIMEOUT_MS : ALERT_ACTION_RETRY_MS;
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);
127136
const start = Date.now();
128137
let lastError: unknown;
129138
let firstAttempt = true;
130-
while (Date.now() - start < ALERT_ACTION_RETRY_MS) {
139+
while (Date.now() - start < retryWindowMs) {
131140
try {
132-
const budgetMs = firstAttempt
133-
? runnerTimeoutMs
134-
: remainingBudgetMs(start, ALERT_ACTION_RETRY_MS);
141+
const budgetMs = firstAttempt ? runnerTimeoutMs : remainingBudgetMs(start, retryWindowMs);
135142
firstAttempt = false;
136143
return await runAlert(action, budgetMs);
137144
} catch (error) {
@@ -143,6 +150,16 @@ export async function actOnAppleAlert(
143150
throw withAlertFallbackHint(lastError);
144151
}
145152

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

0 commit comments

Comments
 (0)