Skip to content

Commit 11a395e

Browse files
authored
feat(client): accept an AbortSignal per call and close the request on abort (#3200)
* feat(contracts,host-kit): declare the per-call AbortSignal and its requester-side guard Declare `signal?: AbortSignal` once at the owning contract types — the per-call overrides, the transport context, and the internal request envelope — so no per-site guard repeats it (#3178). Add `createRequestGuard` to @agent-device/host-kit/request beside the daemon-side cancellation machinery it answers for: an already-aborted call is refused with `dispatched: 'no'`, and an abort racing an in-flight send wins with the typed canceled-request error so a custom transport that ignores the signal cannot outlive the caller's promise. * feat(client): thread the per-call signal through the daemon client and both transports Wire the declared signal from the client's execute seam down to the transport context and the request guard, and from the built-in transport into both daemon wires (#3178): - `sendToDaemon` refuses an already-aborted call before daemon startup and guards each client-side phase; an abort during the artifact upload now combines with the lease beat's own signal so the upload stops for either owner. - The socket transport destroys its connection on abort, and the HTTP transport destroys its request; either way the daemon sees a client disconnect and marks the request canceled. Every settle path detaches the abort listener, and the timeout timer is cleared on abort so an abort never triggers the timeout path's runner sweep or daemon reset. - Retries and fallback attempts start behind a refusal check, so nothing is sent after an abort. * refactor(host-kit): own the transport-facing canceled-request helpers in the guard module `abortedRequestError` and `refuseAbortedRequest` complete the request-cancel seam the daemon request transports consume, so every rejection a caller's abort produces is built by the module that declares the cancellation contract rather than restated per transport. * test(client): cover the per-call AbortSignal on the client surface and both transports #3178 acceptance: an abort before send sends nothing (`dispatched: 'no'`); an abort mid-request closes that one request so the daemon marks it canceled (`dispatched: 'unknown'`, proven daemon-side through the request-cancel registry), and the daemon keeps serving follow-up requests. Client-level cases pin the guard half: the signal rides the transport context, and a custom transport that ignores it cannot outlive the caller's promise. Regression evidence: all eight wiring cases fail on the pre-fix sources (verified by running these files against fc7df6c's client/daemon-client/ transport) and pass with the fix. * docs(client): document the per-call signal on every client method #3178's Done-when: the public client docs list `signal`, including the already-aborted refusal (`dispatched: 'no'`), the mid-flight cancel (`reason: 'request_canceled'`), and the promise that an abort never takes the timeout path's runner cleanup or daemon reset. * test(daemon-client): carry the wire token in the abort fixtures' daemon requests * test(daemon-client): prove an abort is never a timeout at the transport seam Add the paired regression cases for #3178's never-a-timeout promise: with the timeout seam mocked, an abort with an armed budget leaves the seam never called, while the same budget without a signal reaches it. Counterfactual verified: deleting the abort path's `clearTimeout` fails only the abort case. Clear the ignoring-transport test's late resolve so it keeps no timer alive. * fix(client): own the per-call guard beside its transport and answer the review - Move the requester-side AbortSignal guard out of @agent-device/host-kit/request into daemon-client-transport.ts, the module the CLI eager closure already loads, so the caller-side half and the transport half share one owner and the ADR-0019 loading-shape probe stops counting 9 extra modules against cli.ts and the replay-port facade. - Generate the request id in execute before guarding, so a canceled call names itself in request.meta and matches the daemon's diagnostic for the same request. - Report dispatched 'no' when a guard is entered already aborted: the refusal proves send never ran, so 'unknown' would suppress a safe retry. - Keep a non-Error abort reason as the cause unchanged. - Return before handleTransportError once a request is settled, so the error an intentional destroy emits cannot log daemon_request_socket_error. - Cut the remote-retry health probe on the caller's signal and recheck the signal before timeout and retry handling, so a canceled call never reads as timed out. - Forward the caller's abort into the lease beat, which owns its own connection. - Prove the signal reaches the daemon through the DEFAULT transport: one loopback test per transport drives createAgentDeviceClient with no injected transport and asserts the daemon saw the cancel. - Prove the RPC handler still serves after an HTTP cancellation, not just /health. - Qualify the signal contract and the docs with the two phases the guarantee does not cover: a response-artifact download already underway, and a canceled one-shot replay's existing daemon cleanup. * refactor(daemon-client): keep the guard's helpers module-local and name the beat's outcomes The code-quality audit found two exports with no consumer outside the transport module and two functions whose new branches pushed them over the complexity threshold. Nothing imported the helpers, so the guard's error factory and its send-attempt refusal stay module-private beside the two callers that use them. The lease beat now says what a failed beat means — one path ends the protection, one reports a transient miss — and the retry path names the budget a deadline-capped probe proves, instead of inlining both decisions. * test(provider-scenarios): resolve alert interactors per call from the request's execution metadata The scenario gateway built its Apple interactor once at bind time with an empty runner context, so an alert leg asked the runner for a request id it never had. While the client sent no meta.requestId the unkeyed provider scope still matched, but every call now carries one: the request-scoped scripted provider is keyed by (deviceId, requestId), the empty lookup missed it, and the leg fell through to the local XCTest runner — which spawns real tooling and hangs the in-process harness. Per-call resolution mirrors the production alert binding, which projects the input's execution metadata into the interactor context. * refactor(test): one per-call alert-leg resolver for the iOS scenario gateway * test(daemon-client): destroy tracked sockets when a loopback abort case fails net.Server.close() waits for accepted connections, and a hanging-handler request keeps its connection open until the client's abort destroys it. When an assertion before that fails, the daemon-side handler waits forever and close() hangs the lane, turning the regression signal the abort tests exist to provide into a test timeout. Track the accepted sockets and destroy them in teardown at the three socket suites whose handlers never answer. http.Server already has closeAllConnections(); net.Server has no equivalent. * chore(gates): ack the caller-signal digest on the HTTP health probe The compatibleChanges entry must carry the post-change digest; the declaration moved when the probe began composing the #3178 caller signal with its own timeout budget. The /health request and accepted payload are untouched, so protocol 2 peers parse it exactly as before. * docs(agents): name both request-cancellation seams The caller's per-call abort guard moved beside the transports it serves, while `@agent-device/host-kit/request` kept the daemon-side cancel registry and progress. The declaration-site line still credited the whole seam to host-kit, pointing the next reader at a module that no longer exports the guard.
1 parent f2f3afa commit 11a395e

17 files changed

Lines changed: 1212 additions & 88 deletions

‎AGENTS.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,11 @@ Read the declaration rather than maintaining a prose copy:
5656
- common command input fields, and which surface may write an input key (model, operator, retired):
5757
`src/commands/common-input-fields.ts` and `src/commands/input-audience.ts`
5858

59-
Shared selector parsing and matching belongs in `@agent-device/selectors`; request cancellation
60-
and progress in `@agent-device/host-kit/request`; cross-layer contracts in `packages/contracts/src`;
61-
CLI flags in `src/commands/cli-grammar`; cross-surface schema composition in `src/commands/schema`.
59+
Shared selector parsing and matching belongs in `@agent-device/selectors`; daemon-side request
60+
cancellation and progress in `@agent-device/host-kit/request`, and the caller's per-call abort guard
61+
beside the transports it serves in `src/daemon-client/daemon-client-transport.ts`; cross-layer
62+
contracts in `packages/contracts/src`; CLI flags in `src/commands/cli-grammar`; cross-surface schema
63+
composition in `src/commands/schema`.
6264

6365
Resolve registry completeness failures at the missing declaration. Diagnose other gate failures
6466
at their reported invariant; do not suppress them or add an allowlist to get a pass. Build interaction

‎packages/contracts/src/client-connection.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@ import type {
1717

1818
export type AgentDeviceDaemonTransportContext = {
1919
authToken?: string;
20+
/**
21+
* Cancels this one in-flight request. A built-in transport that sees an abort destroys the
22+
* request's connection, which makes the daemon mark the request canceled; the promise rejects
23+
* with the typed canceled-request error. A custom transport that ignores the signal keeps its
24+
* own cancellation contract, and the client still rejects the caller's promise on abort.
25+
*/
26+
signal?: AbortSignal;
2027
};
2128

2229
export type AgentDeviceDaemonTransport = (
@@ -88,7 +95,22 @@ export type AgentDeviceRequestOverrides = Pick<
8895
| 'iosXctestrunFile'
8996
| 'iosXctestDerivedDataPath'
9097
| 'iosXctestEnvDir'
91-
>;
98+
> & {
99+
/**
100+
* Cancels this one call. Already aborted: the call rejects without sending anything
101+
* (`details.dispatched: 'no'`). Aborted in flight: the request's connection closes, the daemon
102+
* marks the request canceled, and the promise rejects with the typed canceled-request error
103+
* (`details.reason: 'request_canceled'`). An abort is never a timeout: no runner sweep, no
104+
* daemon reset.
105+
*
106+
* The guarantee covers the daemon request, and the built-in transports enforce it; a custom
107+
* transport receives the signal on its context and may implement cancellation differently. Two
108+
* phases run outside it: a response-artifact download started after the response begins is not
109+
* canceled, and a canceled one-shot replay still runs the existing cleanup that may tear down a
110+
* daemon this client started.
111+
*/
112+
signal?: AbortSignal;
113+
};
92114

93115
export type AgentDeviceIdentifiers = {
94116
session?: string;

‎packages/contracts/src/request-envelope.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,9 @@ export type InternalRequestOptions = AgentDeviceClientConfig &
9898
leaseTtlMs?: number;
9999
provider?: string;
100100
providerSessionId?: string;
101+
/**
102+
* Cancels this one call in flight; never crosses the wire. The client hands it to the transport
103+
* context and rejects its own promise on abort even when a custom transport ignores it.
104+
*/
105+
signal?: AbortSignal;
101106
};
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/**
2+
* #3178: every client call accepts `signal?: AbortSignal`.
3+
*
4+
* These pin the client's own half of the contract against a scripted transport: an already-aborted
5+
* call never reaches the transport (`details.dispatched: 'no'`), the signal rides the transport
6+
* context for a transport that honors it, and a custom transport that ignores the signal still
7+
* loses the race — the caller's promise rejects with the typed canceled-request error
8+
* (`details.dispatched: 'unknown'`). The transport-into-daemon half is covered by
9+
* `src/daemon-client/__tests__/daemon-client-abort.test.ts`.
10+
*/
11+
import assert from 'node:assert/strict';
12+
import { test } from 'vitest';
13+
import { isRequestCanceledError } from '@agent-device/kernel/errors';
14+
import { createAgentDeviceClient } from '../agent-device-client.ts';
15+
import type { AgentDeviceDaemonTransportContext } from '@agent-device/contracts/client';
16+
import type { DaemonRequest, DaemonResponse } from '@agent-device/kernel/contracts';
17+
import { createTransport } from './client-transport-fixture.ts';
18+
19+
function canceledWith(error: unknown, dispatched: 'no' | 'unknown'): boolean {
20+
return (
21+
isRequestCanceledError(error) &&
22+
(error as { details?: Record<string, unknown> }).details?.dispatched === dispatched
23+
);
24+
}
25+
26+
test('a client call with an already-aborted signal never reaches the transport', async () => {
27+
const { config, calls, transport } = createTransport(() => ({ ok: true, data: {} }));
28+
const client = createAgentDeviceClient(config, { transport });
29+
const controller = new AbortController();
30+
controller.abort();
31+
await assert.rejects(
32+
client.interactions.press({ ref: '@e12', signal: controller.signal }),
33+
(error: unknown) => canceledWith(error, 'no'),
34+
);
35+
assert.deepEqual(calls, []);
36+
});
37+
38+
test('the signal rides the transport context so a built-in-style transport can close the request', async () => {
39+
const contexts: Array<AgentDeviceDaemonTransportContext | undefined> = [];
40+
const client = createAgentDeviceClient(
41+
{},
42+
{
43+
transport: async (_req, context) => {
44+
contexts.push(context);
45+
return { ok: true, data: {} } satisfies DaemonResponse;
46+
},
47+
},
48+
);
49+
const controller = new AbortController();
50+
await client.command.wait({ durationMs: 1, signal: controller.signal });
51+
assert.equal(contexts.length, 1);
52+
assert.equal(contexts[0]?.signal, controller.signal);
53+
});
54+
55+
test('aborting a call whose transport ignores the signal still rejects the caller with the typed canceled error', async () => {
56+
let lingering: ReturnType<typeof setTimeout> | undefined;
57+
const client = createAgentDeviceClient(
58+
{},
59+
{
60+
transport: (req) =>
61+
new Promise<DaemonResponse>((resolve) => {
62+
// A custom transport that never inspects the context signal: the guard must still settle
63+
// the caller's promise when the abort fires. The late resolve is cleared once the caller
64+
// has been rejected, so the worker keeps no timer alive for its own promise.
65+
lingering = setTimeout(
66+
() => resolve({ ok: true, data: { ignored: req.command } }),
67+
10_000,
68+
);
69+
lingering.unref?.();
70+
}),
71+
},
72+
);
73+
const controller = new AbortController();
74+
const call = client.interactions.press({ ref: '@e12', signal: controller.signal });
75+
setTimeout(() => controller.abort(), 10);
76+
await assert.rejects(call, (error: unknown) => canceledWith(error, 'unknown'));
77+
if (lingering) clearTimeout(lingering);
78+
});
79+
80+
test('a signal on one call does not cancel another', async () => {
81+
const client = createAgentDeviceClient(
82+
{},
83+
{
84+
transport: async (req: Omit<DaemonRequest, 'token'>) => {
85+
if (req.command === 'wait') {
86+
await new Promise((resolve) => setTimeout(resolve, 50));
87+
}
88+
return { ok: true, data: {} };
89+
},
90+
},
91+
);
92+
const canceled = new AbortController();
93+
const doomed = client.command.wait({ durationMs: 5000, signal: canceled.signal });
94+
const survivor = client.command.wait({ durationMs: 1 });
95+
// Deferred so the doomed call is genuinely in flight when the abort fires: a synchronous abort
96+
// would land before `execute` installs the guard and reject through the pre-abort `no` path that
97+
// the first test already covers. The guard answers for a transport that ignores the signal, so
98+
// this exercises the in-flight `unknown` rejection while the survivor runs untouched.
99+
await new Promise((resolve) => setTimeout(resolve, 10));
100+
canceled.abort();
101+
await assert.rejects(doomed, (error: unknown) => canceledWith(error, 'unknown'));
102+
assert.deepEqual(await survivor, {});
103+
});

‎src/__tests__/test-utils/loopback.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,29 @@ function closeHttpConnections(server: LoopbackServer): void {
7979
maybeHttpServer.closeIdleConnections?.();
8080
}
8181

82+
/**
83+
* `net.Server.close()` waits for every accepted connection to finish, and a request handler that
84+
* never answers keeps its connection open forever — `http.Server` has `closeAllConnections()` and
85+
* `net.Server` has no equivalent. Track the accepted sockets so a test whose assertion already
86+
* failed can destroy them instead of hanging in teardown: a regression in cancellation wiring must
87+
* surface as the failed assertion, not as the test timeout swallowing it.
88+
*/
89+
export function trackLoopbackSockets(server: net.Server): () => void {
90+
const sockets = new Set<net.Socket>();
91+
server.on('connection', (socket) => {
92+
sockets.add(socket);
93+
socket.on('close', () => {
94+
sockets.delete(socket);
95+
});
96+
});
97+
return () => {
98+
for (const socket of sockets) {
99+
socket.destroy();
100+
}
101+
sockets.clear();
102+
};
103+
}
104+
82105
export function waitForHttpOk(url: string, timeoutMs: number): Promise<void> {
83106
const deadline = Date.now() + timeoutMs;
84107
return new Promise((resolve, reject) => {

‎src/agent-device-client.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
type SessionRuntimeHints,
3636
} from '@agent-device/kernel/contracts';
3737
import { AppError, throwDaemonError } from '@agent-device/kernel/errors';
38+
import { createRequestId } from '@agent-device/host-kit/diagnostics';
3839
import {
3940
buildMeta,
4041
normalizeDeployResult,
@@ -74,6 +75,7 @@ import { isRecord, readSnapshotKeyboardBandFact } from '@agent-device/kernel/rec
7475
import { readResponseWarnings } from '@agent-device/kernel/success-text';
7576
import { createLeaseClient } from './client/lease-client.ts';
7677
import { normalizeScreenshotCaptureResult } from './client/screenshot-result.ts';
78+
import { createRequestGuard } from './daemon-client/daemon-client-transport.ts';
7779

7880
export function createAgentDeviceClient(
7981
config: AgentDeviceClientConfig = {},
@@ -95,16 +97,29 @@ export function createAgentDeviceClient(
9597
input?: Record<string, unknown>,
9698
): Promise<Record<string, unknown>> => {
9799
const merged = mergeClientOptions(config, options);
100+
// The id is generated before the guard so a canceled call names itself in `request.meta`, and
101+
// the daemon's diagnostics for the request the transport goes on to cancel carry the same id
102+
// the caller's rejection carries.
103+
const requestId = merged.requestId ?? createRequestId();
104+
const cancellation = createRequestGuard({ signal: merged.signal, requestId });
105+
cancellation.refuseIfAborted();
98106
const request = {
99107
session: resolveSessionName(merged.session),
100108
command,
101109
positionals,
102110
...(input ? { input } : {}),
103111
flags: buildRequestFlags(merged, metadataFlags),
104112
runtime: merged.runtime,
105-
meta: buildMeta(merged),
113+
meta: { ...buildMeta(merged), requestId },
106114
};
107-
const response = await transport(request, { authToken: merged.daemonAuthToken });
115+
// `signal` rides the transport context (it is a live object, never wire data), and the guard
116+
// answers for a custom transport that ignores it: the caller's promise settles on abort either
117+
// way. The built-in transport closes the request's connection, which is what makes the daemon
118+
// mark the request canceled.
119+
const response = await cancellation.guard(
120+
async () =>
121+
await transport(request, { authToken: merged.daemonAuthToken, signal: merged.signal }),
122+
);
108123
if (!response.ok) {
109124
throwDaemonError(response.error);
110125
}

0 commit comments

Comments
 (0)