Skip to content

Commit b849fd8

Browse files
thymikeeclaude
andauthored
fix(ios): press Open again when the runner watchdog abandons the launch-URL accept (callstack#4017)
* fix(ios): press Open again when the runner watchdog abandons the launch-URL accept On a freshly started runner, the launch confirmation's Open press can time out on the runner's main-thread watchdog (MAIN_THREAD_TIMEOUT) while the "Open in" prompt stays up, and open then failed with launch_confirmation_unanswered with budget to spare. The answer now presses Open again while the same confirmation is still up, within a 25-second accept budget that holds a whole press. Any other accept failure, or a prompt that is gone, ends the answer as before. Fixes callstack#3861 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(ios): state why a second launch-confirmation press cannot answer a later alert Co-Authored-By: Claude Opus 5.5 <[email protected]> * 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 callstack#3861 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(ios): take the open deadline from the admitting transport and keep alert failures typed A request's result deadline is now recorded by the transport that admitted it, from the top-level command's client envelope, and an attempt registered under a parent inherits the parent's. A replay test attempt under an unbounded `test` request therefore has no deadline, instead of one counted from its own registration with the nested open's budget. An accept whose deadline already passed floored its retry window to 1 ms and could skip the loop and throw undefined; the first attempt now always runs. Refs callstack#3861 Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(ios): keep the expired-deadline accept test off real time and name the deadline tests exactly Co-Authored-By: Claude Opus 5.5 <[email protected]> * 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 callstack#3861 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(ios): name the URL-owner lookup cap and pin the unsent press disclosure Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(ios): escape the open help apostrophe Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(ios): pin the exact minTimeoutMs edge and narrow the alert deadline doc Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(ios): say the alert deadline caps the native timeout Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(ios): gate only the launch-confirmation re-press on the open deadline Review of 101a8ce: the per-command deadline also governed the first press, so a first press with less than 10 s of the open budget left was refused unsent where main pressed it. The request deadline now decides only whether to press again, at the one re-press gate (a whole press and its read, 22 s); the first press and every read keep their own runner bounds. This removes the opt-in runner command deadline, its exchange binding and typed refusal, the alert-leg deadline option and the URL-owner lookup cap. A new suite drives the answer through the real alert legs and runner client against a fake runner: an abandoned press is verified through two RUNNER_BUSY resends and pressed again with 49.4 s of a 60 s open left, and a first press with 5 s left is still sent with its full watchdog (refused on 101a8ce). Refs callstack#3861 Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(ios): name the cross-module launch-confirmation runner suite for the runner package index Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent c8772b8 commit b849fd8

21 files changed

Lines changed: 675 additions & 19 deletions

‎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/daemon/src/core/daemon-command-registry.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,12 @@ 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';
19+
import type { DaemonWireRequest } from '@agent-device/contracts/command';
1620
import type { DaemonRequest } from './daemon-request.ts';
1721

1822
export type { DaemonCommandDescriptor, DaemonCommandRoute, SessionCommandKind };
@@ -37,6 +41,19 @@ export function resolveDaemonRequestTimeoutMs(req: DaemonRequest): number | unde
3741
return resolveCommandDaemonTimeoutMs(resolveCommandTimeoutPolicy(req.command), req);
3842
}
3943

44+
/**
45+
* When a request admitted now must have its result: the client envelope starts as the transport
46+
* admits the request, and the daemon keeps the envelope's result margin. `undefined` for a command
47+
* whose client waits without an envelope.
48+
*/
49+
export function resolveDaemonRequestResultDeadlineMs(
50+
req: DaemonWireRequest,
51+
admittedAtMs = Date.now(),
52+
): number | undefined {
53+
const budgetMs = resolveCommandDaemonBudgetMs(resolveCommandTimeoutPolicy(req.command), req);
54+
return budgetMs === undefined ? undefined : admittedAtMs + budgetMs;
55+
}
56+
4057
export function getDaemonCommandRoute(command: string): DaemonCommandRoute {
4158
return getDaemonCommandDescriptor(command)?.route ?? 'generic';
4259
}

‎packages/daemon/src/server/__tests__/http-server-rpc-lifetime.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { test } from 'vitest';
33
import assert from 'node:assert/strict';
44
import { getRequestSignal } from '@agent-device/host-kit/request';
55
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit';
6-
import { postRpcCommand, startRpcServer } from './http-server-rpc.fixtures.ts';
6+
import { postRpcCommand, postRpcRaw, startRpcServer } from './http-server-rpc.fixtures.ts';
7+
import { applicationLifecycleExecutionFromRequest } from '../../sessions/application-lifecycle-execution.ts';
78

89
const TOKEN = 'lifetime-token';
910

@@ -33,3 +34,31 @@ test('an rpc request registers its tracking id while in flight and releases it o
3334
await closeLoopbackServer(server);
3435
}
3536
});
37+
38+
test('an admitted open records a result deadline of its client envelope less the daemon result margin', async (t) => {
39+
if (await skipWhenLoopbackUnavailable(t)) return;
40+
let deadlineAtMs: number | undefined;
41+
const { port, server } = await startRpcServer(TOKEN, async (request) => {
42+
deadlineAtMs = applicationLifecycleExecutionFromRequest(
43+
request,
44+
'/tmp/request.log',
45+
).requestDeadlineAtMs;
46+
return { ok: true, data: {} } satisfies DaemonResponse;
47+
});
48+
try {
49+
const sentAtMs = Date.now();
50+
const requestId = 'req-open-result-deadline';
51+
const body = JSON.stringify({
52+
jsonrpc: '2.0',
53+
id: requestId,
54+
method: 'agent_device.command',
55+
params: { command: 'open', positionals: ['com.example.app'], meta: { requestId } },
56+
});
57+
assert.equal((await postRpcRaw(port, TOKEN, body)).status, 200);
58+
const answeredAtMs = Date.now();
59+
assert.ok(deadlineAtMs !== undefined, 'the open must carry a deadline');
60+
assert.ok(deadlineAtMs >= sentAtMs + 60_000 && deadlineAtMs <= answeredAtMs + 60_000);
61+
} finally {
62+
await closeLoopbackServer(server);
63+
}
64+
});

‎packages/daemon/src/server/http/http-server.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { normalizeError } from '@agent-device/kernel/errors';
1414
import { LEASE_BACKENDS } from '@agent-device/kernel/contracts';
1515
import { isRecord } from '@agent-device/kernel/record';
1616
import type { DaemonInvokeFn, DaemonRequest } from '../../core/daemon-request.ts';
17+
import { resolveDaemonRequestResultDeadlineMs } from '../../core/daemon-command-registry.ts';
1718
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
1819
import {
1920
clearRequestAbortRegistration,
@@ -472,7 +473,9 @@ function beginRpcRequestLifetime(params: {
472473
return {
473474
admit(daemonRequest) {
474475
requestId = resolveRequestTrackingId(daemonRequest.meta?.requestId, rpcId);
475-
abortRegistration = registerRequestAbort(requestId);
476+
abortRegistration = registerRequestAbort(requestId, undefined, {
477+
resultDeadlineMs: resolveDaemonRequestResultDeadlineMs(daemonRequest),
478+
});
476479
return {
477480
...daemonRequest,
478481
meta: { ...daemonRequest.meta, requestId },

‎packages/daemon/src/server/http/transport.test.ts‎

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ import http from 'node:http';
55
import net from 'node:net';
66
import { test } from 'vitest';
77
import { createSocketServer, listenHttpServer, listenNetServer } from './transport.ts';
8-
import { getRequestSignal } from '@agent-device/host-kit/request';
8+
import {
9+
clearRequestAbortRegistration,
10+
getRequestSignal,
11+
registerRequestAbort,
12+
} from '@agent-device/host-kit/request';
13+
import { applicationLifecycleExecutionFromRequest } from '../../sessions/application-lifecycle-execution.ts';
914
import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit';
1015

1116
test('Provider-backed integration daemon socket transport frames requests and normalizes malformed input', async (t) => {
@@ -160,6 +165,90 @@ test('socket disconnect cancels only the disconnected connection in-flight reque
160165
}
161166
});
162167

168+
/** The deadline an `open` running under `requestId` would carry. */
169+
function openDeadlineAtMs(requestId: string | undefined): number | undefined {
170+
return applicationLifecycleExecutionFromRequest(
171+
{
172+
token: 'provider-scenario-token',
173+
session: 'default',
174+
command: 'open',
175+
positionals: ['com.example.app'],
176+
meta: { requestId },
177+
},
178+
'/tmp/request.log',
179+
).requestDeadlineAtMs;
180+
}
181+
182+
test('a socket-admitted open --timeout moves its deadline with the envelope it widens', async (t) => {
183+
if (await skipWhenLoopbackUnavailable(t)) return;
184+
let deadlineAtMs: number | undefined;
185+
const server = createSocketServer(async (req): Promise<DaemonResponse> => {
186+
deadlineAtMs = applicationLifecycleExecutionFromRequest(
187+
req,
188+
'/tmp/request.log',
189+
).requestDeadlineAtMs;
190+
return { ok: true, data: {} };
191+
});
192+
try {
193+
const client = await connectSocket(await listenNetServer(server));
194+
const sentAtMs = Date.now();
195+
await writeSocketRequests(
196+
client,
197+
[
198+
JSON.stringify({
199+
token: 'provider-scenario-token',
200+
session: 'default',
201+
command: 'open',
202+
positionals: ['com.example.app'],
203+
flags: { timeoutMs: 120_000 },
204+
meta: { requestId: 'socket-open-widened-deadline' },
205+
}),
206+
],
207+
1,
208+
);
209+
const answeredAtMs = Date.now();
210+
client.destroy();
211+
assert.ok(deadlineAtMs !== undefined, 'the open must carry a deadline');
212+
assert.ok(deadlineAtMs >= sentAtMs + 120_000 && deadlineAtMs <= answeredAtMs + 120_000);
213+
} finally {
214+
await closeLoopbackServer(server);
215+
}
216+
});
217+
218+
test('an attempt nested under a test request without a client envelope has no deadline', async (t) => {
219+
if (await skipWhenLoopbackUnavailable(t)) return;
220+
let attemptDeadlineAtMs: number | undefined = Number.NaN;
221+
const server = createSocketServer(async (req): Promise<DaemonResponse> => {
222+
const registration = registerRequestAbort('socket-test-attempt', req.meta?.requestId);
223+
try {
224+
attemptDeadlineAtMs = openDeadlineAtMs('socket-test-attempt');
225+
} finally {
226+
clearRequestAbortRegistration(registration);
227+
}
228+
return { ok: true, data: {} };
229+
});
230+
try {
231+
const client = await connectSocket(await listenNetServer(server));
232+
await writeSocketRequests(
233+
client,
234+
[
235+
JSON.stringify({
236+
token: 'provider-scenario-token',
237+
session: 'default',
238+
command: 'test',
239+
positionals: ['flows'],
240+
meta: { requestId: 'socket-test-suite' },
241+
}),
242+
],
243+
1,
244+
);
245+
client.destroy();
246+
assert.equal(attemptDeadlineAtMs, undefined);
247+
} finally {
248+
await closeLoopbackServer(server);
249+
}
250+
});
251+
163252
async function waitForAbort(signal: AbortSignal): Promise<void> {
164253
if (signal.aborted) return;
165254
await new Promise<void>((resolve) => {
@@ -181,6 +270,7 @@ async function connectSocket(port: number): Promise<net.Socket> {
181270
async function writeSocketRequests(
182271
socket: net.Socket,
183272
lines: string[],
273+
expectedResponses = 2,
184274
): Promise<Array<{ ok?: boolean; data?: any; error?: any }>> {
185275
return await new Promise((resolve, reject) => {
186276
const responses: Array<{ ok?: boolean; data?: any; error?: any }> = [];
@@ -195,7 +285,7 @@ async function writeSocketRequests(
195285
if (line) {
196286
responses.push(JSON.parse(line));
197287
}
198-
if (responses.length === 2) {
288+
if (responses.length === expectedResponses) {
199289
resolve(responses);
200290
return;
201291
}

‎packages/daemon/src/server/http/transport.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { AsyncResource } from 'node:async_hooks';
44
import net from 'node:net';
55
import type { Server as HttpServer } from 'node:http';
66
import type { DaemonInvokeFn, DaemonRequest } from '../../core/daemon-request.ts';
7+
import { resolveDaemonRequestResultDeadlineMs } from '../../core/daemon-command-registry.ts';
78
import {
89
clearRequestAbortRegistration,
910
isRequestCanceled,
@@ -76,7 +77,9 @@ export function createSocketServer(handleRequest: DaemonInvokeFn): DaemonServer
7677
...req.meta,
7778
requestId: requestIdForCleanup,
7879
};
79-
requestAbortRegistration = registerRequestAbort(requestIdForCleanup);
80+
requestAbortRegistration = registerRequestAbort(requestIdForCleanup, undefined, {
81+
resultDeadlineMs: resolveDaemonRequestResultDeadlineMs(req),
82+
});
8083
activeRequestIds.add(requestIdForCleanup);
8184
if (isRequestCanceled(requestIdForCleanup)) {
8285
throw createRequestCanceledError();
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { afterEach, expect, test, vi } from 'vitest';
2+
import { withRequestDeadline } from '@agent-device/host-kit/request';
3+
import type { ApplicationLifecycleExecution } from '@agent-device/contracts/application-lifecycle-runtime';
4+
import { applicationLifecycleExecutionFromRequest } from './application-lifecycle-execution.ts';
5+
6+
const NOW_MS = 1_000_000;
7+
8+
afterEach(() => {
9+
vi.useRealTimers();
10+
});
11+
12+
function openExecution(requestId: string | undefined): ApplicationLifecycleExecution {
13+
return applicationLifecycleExecutionFromRequest(
14+
{
15+
token: 'token',
16+
session: 'default',
17+
command: 'open',
18+
positionals: ['com.example.app'],
19+
meta: { requestId },
20+
},
21+
'/tmp/request.log',
22+
);
23+
}
24+
25+
test('an enforced request deadline is the deadline', async () => {
26+
vi.useFakeTimers({ toFake: ['Date'] });
27+
vi.setSystemTime(NOW_MS);
28+
let execution: ApplicationLifecycleExecution | undefined;
29+
await withRequestDeadline('open-in-bounded-batch', 20_000, async () => {
30+
execution = openExecution('open-in-bounded-batch');
31+
return { ok: true, data: {} };
32+
});
33+
expect(execution?.requestDeadlineAtMs).toBe(NOW_MS + 20_000);
34+
});
35+
36+
test('a request no transport admitted has no deadline', () => {
37+
expect(openExecution(undefined).requestDeadlineAtMs).toBeUndefined();
38+
expect(openExecution('never-admitted').requestDeadlineAtMs).toBeUndefined();
39+
});

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import {
2+
getRequestExecutionDeadlineMs,
3+
getRequestResultDeadlineMs,
4+
} from '@agent-device/host-kit/request';
15
import { resolvePlannedOperations } from '../core/execution-plan.ts';
26
import type { ApplicationLifecycleExecution } from '@agent-device/contracts/application-lifecycle-runtime';
37
import { resolveRunnerLogicalLeaseContext } from '../core/lease-context.ts';
@@ -10,6 +14,7 @@ export function applicationLifecycleExecutionFromRequest(
1014
traceLogPath?: string,
1115
): ApplicationLifecycleExecution {
1216
return {
17+
requestDeadlineAtMs: requestDeadlineAtMs(req),
1318
requestId: req.meta?.requestId,
1419
logPath,
1520
traceLogPath,
@@ -25,3 +30,12 @@ export function applicationLifecycleExecutionFromRequest(
2530
plannedOperations: resolvePlannedOperations(req.internal?.executionPlan),
2631
};
2732
}
33+
34+
/**
35+
* An enforced daemon deadline is the request's deadline. Otherwise it is the result deadline the
36+
* transport that admitted the request (or its parent) set, ahead of the client's envelope.
37+
*/
38+
function requestDeadlineAtMs(req: DaemonRequest): number | undefined {
39+
const requestId = req.meta?.requestId;
40+
return getRequestExecutionDeadlineMs(requestId) ?? getRequestResultDeadlineMs(requestId);
41+
}

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

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

15-
type RequestAbortController = AbortController & { executionDeadlineMs?: number };
15+
type RequestAbortController = AbortController & {
16+
executionDeadlineMs?: number;
17+
/**
18+
* The daemon's own result deadline, which the transport that admitted the request set ahead of
19+
* the client's: the end of the client envelope less the daemon's result margin. An attempt
20+
* registered under a parent inherits the parent's, because it runs inside the parent's envelope.
21+
*/
22+
resultDeadlineMs?: number;
23+
};
1624

1725
const REQUEST_CANCEL_SLOT = Symbol('requestCancel');
1826
const requestCancelState = (): RequestCancelState =>
@@ -80,6 +88,7 @@ function evictOldestSetEntries<V>(set: Set<V>): void {
8088
export function registerRequestAbort(
8189
requestId: string | undefined,
8290
parentRequestId?: string,
91+
admission?: Readonly<{ resultDeadlineMs?: number }>,
8392
): RequestAbortRegistration | undefined {
8493
if (!requestId) return undefined;
8594
if (requestAbortControllers().has(requestId)) {
@@ -90,9 +99,11 @@ export function registerRequestAbort(
9099
}
91100
evictOldestEntries(requestAbortControllers());
92101
const controller: RequestAbortController = new AbortController();
93-
controller.executionDeadlineMs = parentRequestId
94-
? requestAbortControllers().get(parentRequestId)?.executionDeadlineMs
95-
: undefined;
102+
const parent = parentRequestId ? requestAbortControllers().get(parentRequestId) : undefined;
103+
controller.executionDeadlineMs = parent?.executionDeadlineMs;
104+
controller.resultDeadlineMs = parentRequestId
105+
? parent?.resultDeadlineMs
106+
: admission?.resultDeadlineMs;
96107
requestAbortControllers().set(requestId, controller);
97108
if (canceledRequestIds().has(requestId)) {
98109
controller.abort(createRequestCanceledError());
@@ -154,6 +165,11 @@ export function getRequestExecutionDeadlineMs(requestId: string | undefined): nu
154165
return requestId ? requestAbortControllers().get(requestId)?.executionDeadlineMs : undefined;
155166
}
156167

168+
/** The daemon's result deadline the admitting transport set for the request, if it set one. */
169+
export function getRequestResultDeadlineMs(requestId: string | undefined): number | undefined {
170+
return requestId ? requestAbortControllers().get(requestId)?.resultDeadlineMs : undefined;
171+
}
172+
157173
export function throwIfRequestCanceled(requestId: string | undefined): void {
158174
getRequestSignal(requestId)?.throwIfAborted();
159175
if (isRequestCanceled(requestId)) {

0 commit comments

Comments
 (0)