Skip to content

Commit df51767

Browse files
committed
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.
1 parent fae04c3 commit df51767

5 files changed

Lines changed: 158 additions & 1 deletion

File tree

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

Lines changed: 17 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,16 @@ 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+
signal?: AbortSignal;
107+
};
92108

93109
export type AgentDeviceIdentifiers = {
94110
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: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import { isRequestCanceledError } from '@agent-device/kernel/errors';
4+
import { createRequestGuard } from './request-guard.ts';
5+
6+
function canceledOutcome(promise: Promise<unknown>): Promise<unknown> {
7+
return promise.then(
8+
() => {
9+
throw new Error('expected rejection');
10+
},
11+
(error: unknown) => error,
12+
);
13+
}
14+
15+
test('a guard without a signal never refuses and never interferes', async () => {
16+
const guard = createRequestGuard({ signal: undefined, requestId: 'req-none' });
17+
guard.refuseIfAborted();
18+
assert.equal(await guard.guard(async () => 'sent'), 'sent');
19+
});
20+
21+
test('refuseIfAborted refuses an already-aborted call with dispatched no', async () => {
22+
const controller = new AbortController();
23+
controller.abort(new Error('caller gave up'));
24+
const guard = createRequestGuard({ signal: controller.signal, requestId: 'req-pre' });
25+
assert.throws(
26+
() => guard.refuseIfAborted(),
27+
(error: unknown) =>
28+
isRequestCanceledError(error) &&
29+
(error as { details?: Record<string, unknown> }).details?.dispatched === 'no' &&
30+
(error as { details?: Record<string, unknown> }).details?.requestId === 'req-pre',
31+
);
32+
});
33+
34+
test('guard settles an in-flight send with the typed canceled error whatever the abort reason', async () => {
35+
const controller = new AbortController();
36+
const guard = createRequestGuard({ signal: controller.signal, requestId: 'req-flight' });
37+
let settleSend: (() => void) | undefined;
38+
const pending = guard.guard(
39+
() => new Promise<string>((resolve) => (settleSend = () => resolve('late'))),
40+
);
41+
controller.abort(new Error('anything'));
42+
const error = await canceledOutcome(pending);
43+
assert.equal(isRequestCanceledError(error), true);
44+
assert.equal((error as { details?: Record<string, unknown> }).details?.dispatched, 'unknown');
45+
assert.equal((error as { details?: Record<string, unknown> }).details?.requestId, 'req-flight');
46+
// A transport that ignores the signal may still resolve later; that must not
47+
// turn the already-rejected caller promise into a second outcome.
48+
settleSend?.();
49+
});
50+
51+
test('guard keeps a send error when no abort ever fires', async () => {
52+
const controller = new AbortController();
53+
const guard = createRequestGuard({ signal: controller.signal });
54+
const failure = new Error('daemon refused');
55+
await assert.rejects(
56+
guard.guard(async () => {
57+
throw failure;
58+
}),
59+
(error: unknown) => error === failure,
60+
);
61+
});
62+
63+
test('guard returns the send value when it settles before any abort', async () => {
64+
const controller = new AbortController();
65+
const guard = createRequestGuard({ signal: controller.signal });
66+
const value = await guard.guard(async () => 'response');
67+
controller.abort();
68+
assert.equal(value, 'response');
69+
});
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { createRequestCanceledError, type AppError } from '@agent-device/kernel/errors';
2+
3+
/**
4+
* The requester-side half of a per-call `AbortSignal`. The transport half closes the request's
5+
* connection so the daemon marks the request canceled (its own cancellation machinery is
6+
* {@link ./request-cancel.ts}); this half answers for the two cases a transport cannot:
7+
*
8+
* - a signal already aborted before anything was sent — nothing may leave the process, so the
9+
* refusal carries `details.dispatched: 'no'`;
10+
* - a custom transport that ignores the signal it was handed — the caller's promise must still
11+
* settle when the abort fires, with `details.dispatched: 'unknown'` because the transport may
12+
* already have written the request.
13+
*
14+
* Both outcomes reject with the typed canceled-request error (`details.reason:
15+
* 'request_canceled'`) whatever reason the caller's own controller aborted with, so every layer
16+
* that lets a cancellation through dispatches on the same reason — and never on the caller's
17+
* arbitrary abort reason or on error text. An abort is never a timeout: nothing here reads or
18+
* extends a request deadline, and no timeout path may produce this rejection.
19+
*/
20+
21+
export type RequestGuard = {
22+
/** Refuses an already-aborted call before anything is sent. No-op without a signal. */
23+
refuseIfAborted(): void;
24+
/** Settles `send`'s outcome against the signal, winning with the typed canceled error on abort. */
25+
guard<T>(send: () => Promise<T>): Promise<T>;
26+
};
27+
28+
const NO_REQUEST_GUARD: RequestGuard = {
29+
refuseIfAborted: () => {},
30+
guard: async <T>(send: () => Promise<T>) => await send(),
31+
};
32+
33+
export function createRequestGuard(params: {
34+
signal: AbortSignal | undefined;
35+
requestId?: string;
36+
}): RequestGuard {
37+
const { signal, requestId } = params;
38+
if (!signal) return NO_REQUEST_GUARD;
39+
const canceled = (dispatched: 'no' | 'unknown'): AppError =>
40+
createRequestCanceledError(
41+
{ requestId, dispatched },
42+
signal.reason instanceof Error ? signal.reason : undefined,
43+
);
44+
return {
45+
refuseIfAborted() {
46+
if (signal.aborted) throw canceled('no');
47+
},
48+
guard: async <T>(send: () => Promise<T>): Promise<T> => {
49+
if (signal.aborted) throw canceled('unknown');
50+
return await new Promise<T>((resolve, reject) => {
51+
const onAbort = (): void => reject(canceled('unknown'));
52+
signal.addEventListener('abort', onAbort, { once: true });
53+
void send().then(
54+
(value) => {
55+
signal.removeEventListener('abort', onAbort);
56+
resolve(value);
57+
},
58+
(error: unknown) => {
59+
signal.removeEventListener('abort', onAbort);
60+
reject(error);
61+
},
62+
);
63+
});
64+
},
65+
};
66+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ export {
99
throwIfRequestCanceled,
1010
} from './internal/request-cancel.ts';
1111
export { emitRequestProgress, withRequestProgressSink } from './internal/request-progress.ts';
12+
export { createRequestGuard, type RequestGuard } from './internal/request-guard.ts';

0 commit comments

Comments
 (0)