Skip to content

Commit 9f9cac7

Browse files
committed
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.
1 parent 215826f commit 9f9cac7

2 files changed

Lines changed: 329 additions & 0 deletions

File tree

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
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+
const client = createAgentDeviceClient(
57+
{},
58+
{
59+
transport: (req) =>
60+
new Promise<DaemonResponse>((resolve) => {
61+
// A custom transport that never inspects the context signal: the guard must still settle
62+
// the caller's promise when the abort fires.
63+
setTimeout(() => resolve({ ok: true, data: { ignored: req.command } }), 10_000);
64+
}),
65+
},
66+
);
67+
const controller = new AbortController();
68+
const call = client.interactions.press({ ref: '@e12', signal: controller.signal });
69+
setTimeout(() => controller.abort(), 10);
70+
await assert.rejects(call, (error: unknown) => canceledWith(error, 'unknown'));
71+
});
72+
73+
test('a signal on one call does not cancel another', async () => {
74+
const client = createAgentDeviceClient(
75+
{},
76+
{
77+
transport: async (req: Omit<DaemonRequest, 'token'>) => {
78+
if (req.command === 'wait') {
79+
await new Promise((resolve) => setTimeout(resolve, 50));
80+
}
81+
return { ok: true, data: {} };
82+
},
83+
},
84+
);
85+
const canceled = new AbortController();
86+
const doomed = client.command.wait({ durationMs: 5000, signal: canceled.signal });
87+
const survivor = client.command.wait({ durationMs: 1 });
88+
canceled.abort();
89+
await assert.rejects(doomed, (error: unknown) => isRequestCanceledError(error));
90+
assert.deepEqual(await survivor, {});
91+
});
Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
/**
2+
* #3178: the built-in daemon transports honor a per-call `AbortSignal`.
3+
*
4+
* These run the REAL daemon servers (`createSocketServer`, `createDaemonHttpServer`) against a
5+
* request handler that waits on the daemon's own request-scoped signal, so each mid-flight case
6+
* proves the whole chain: the client aborts → that one connection closes → the daemon marks the
7+
* request canceled (`markRequestCanceled`, reached only through the transport's disconnect path) →
8+
* the client rejects with the typed canceled-request error — and the daemon itself stays alive to
9+
* serve a follow-up request.
10+
*/
11+
import assert from 'node:assert/strict';
12+
import { test } from 'vitest';
13+
import { isRequestCanceledError } from '@agent-device/kernel/errors';
14+
import { getRequestSignal, isRequestCanceled } from '@agent-device/host-kit/request';
15+
import type { DaemonInvokeFn, DaemonRequest, DaemonResponse } from '../../daemon/daemon-request.ts';
16+
import { createDaemonHttpServer } from '../../daemon/server/http-server.ts';
17+
import { createSocketServer, listenNetServer } from '../../daemon/server/transport.ts';
18+
import { sendRequest } from '../daemon-client-transport.ts';
19+
import { resolveDaemonPaths } from '../../daemon-resolution.ts';
20+
import {
21+
closeLoopbackServer,
22+
listenOnLoopback,
23+
skipWhenLoopbackUnavailable,
24+
} from '../../__tests__/test-utils/loopback.ts';
25+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
26+
27+
const TOKEN = 'abort-signal-token';
28+
const STATE_PATHS = resolveDaemonPaths(mkdtempForTestSync('agent-device-client-abort-'));
29+
30+
type SeenRequest = { started: boolean; requestId?: string; canceled: boolean[] };
31+
32+
// `wait` models the long request the caller abandons; every other command answers immediately, so
33+
// the same handler also proves the daemon still serves requests after one was canceled.
34+
function canceledAwareHandler(seen: SeenRequest): DaemonInvokeFn {
35+
return async (req: DaemonRequest): Promise<DaemonResponse> => {
36+
const requestId = req.meta?.requestId;
37+
seen.requestId = requestId;
38+
if (req.command !== 'wait') {
39+
return { ok: true, data: {} };
40+
}
41+
seen.started = true;
42+
const signal = getRequestSignal(requestId);
43+
if (!signal) {
44+
return { ok: true, data: { answeredWithoutSignal: true } };
45+
}
46+
return await new Promise<DaemonResponse>((resolve, reject) => {
47+
signal.addEventListener(
48+
'abort',
49+
() => {
50+
seen.canceled.push(isRequestCanceled(requestId));
51+
reject(signal.reason);
52+
},
53+
{ once: true },
54+
);
55+
});
56+
};
57+
}
58+
59+
function canceledRequestError(error: unknown, dispatched: 'no' | 'unknown'): boolean {
60+
return (
61+
isRequestCanceledError(error) &&
62+
(error as { details?: Record<string, unknown> }).details?.dispatched === dispatched
63+
);
64+
}
65+
66+
test('socket transport: an already-aborted signal sends nothing and refuses with dispatched no', async (t) => {
67+
if (await skipWhenLoopbackUnavailable(t)) return;
68+
const connections: number[] = [];
69+
const server = createSocketServer(async () => {
70+
connections.push(1);
71+
return { ok: true, data: {} };
72+
});
73+
try {
74+
const port = await listenNetServer(server);
75+
const controller = new AbortController();
76+
controller.abort();
77+
await assert.rejects(
78+
sendRequest(
79+
{ port, token: TOKEN, pid: 1 },
80+
{
81+
command: 'devices',
82+
session: 'default',
83+
positionals: [],
84+
flags: {},
85+
meta: { requestId: 'req-socket-pre-abort' },
86+
},
87+
'socket',
88+
STATE_PATHS,
89+
undefined,
90+
{ signal: controller.signal },
91+
),
92+
(error: unknown) => canceledRequestError(error, 'no'),
93+
);
94+
assert.deepEqual(connections, []);
95+
} finally {
96+
await closeLoopbackServer(server);
97+
}
98+
});
99+
100+
test('socket transport: an abort mid-request closes the connection, the daemon marks the request canceled, and the daemon stays alive', async (t) => {
101+
if (await skipWhenLoopbackUnavailable(t)) return;
102+
const seen: SeenRequest = { started: false, canceled: [] };
103+
const server = createSocketServer(canceledAwareHandler(seen));
104+
try {
105+
const port = await listenNetServer(server);
106+
const info = { port, token: TOKEN, pid: 1 };
107+
const controller = new AbortController();
108+
const inFlight = sendRequest(
109+
info,
110+
{
111+
command: 'wait',
112+
session: 'default',
113+
positionals: [],
114+
flags: {},
115+
meta: { requestId: 'req-socket-abort-in-flight' },
116+
},
117+
'socket',
118+
STATE_PATHS,
119+
undefined,
120+
{ signal: controller.signal },
121+
);
122+
// Abort only once the daemon has the request in hand, so this is genuinely a mid-request
123+
// cancel rather than a race against connection setup.
124+
await waitFor(() => seen.started, 'the daemon to start the request');
125+
controller.abort();
126+
await assert.rejects(inFlight, (error: unknown) => canceledRequestError(error, 'unknown'));
127+
// The daemon's disconnect path ran: this request's id is registered-canceled, proven through
128+
// the daemon-side registry rather than off the client's rejection.
129+
await waitFor(() => seen.canceled.length > 0, 'daemon-side cancellation');
130+
assert.deepEqual(seen.canceled, [true]);
131+
assert.equal(seen.requestId, 'req-socket-abort-in-flight');
132+
133+
// Daemon alive and serving: a follow-up request without any cancellation completes.
134+
const followUp = await sendRequest(
135+
info,
136+
{
137+
command: 'devices',
138+
session: 'default',
139+
positionals: [],
140+
flags: {},
141+
meta: { requestId: 'req-socket-follow-up' },
142+
},
143+
'socket',
144+
STATE_PATHS,
145+
5000,
146+
{},
147+
);
148+
assert.equal(followUp.ok, true);
149+
} finally {
150+
await closeLoopbackServer(server);
151+
}
152+
});
153+
154+
test('http transport: an already-aborted signal sends nothing and refuses with dispatched no', async (t) => {
155+
if (await skipWhenLoopbackUnavailable(t)) return;
156+
const received: number[] = [];
157+
const server = await createDaemonHttpServer({
158+
handleRequest: async () => {
159+
received.push(1);
160+
return { ok: true, data: {} };
161+
},
162+
token: TOKEN,
163+
});
164+
try {
165+
const port = await listenOnLoopback(server);
166+
const controller = new AbortController();
167+
controller.abort();
168+
await assert.rejects(
169+
sendRequest(
170+
{ httpPort: port, token: TOKEN, pid: 1 },
171+
{
172+
token: TOKEN,
173+
command: 'devices',
174+
session: 'default',
175+
positionals: [],
176+
flags: {},
177+
meta: { requestId: 'req-http-pre-abort' },
178+
},
179+
'http',
180+
STATE_PATHS,
181+
undefined,
182+
{ signal: controller.signal },
183+
),
184+
(error: unknown) => canceledRequestError(error, 'no'),
185+
);
186+
assert.deepEqual(received, []);
187+
} finally {
188+
await closeLoopbackServer(server);
189+
}
190+
});
191+
192+
test('http transport: an abort mid-request closes that request, the daemon marks it canceled, and the daemon stays alive', async (t) => {
193+
if (await skipWhenLoopbackUnavailable(t)) return;
194+
const seen: SeenRequest = { started: false, canceled: [] };
195+
const server = await createDaemonHttpServer({
196+
handleRequest: canceledAwareHandler(seen),
197+
token: TOKEN,
198+
});
199+
try {
200+
const port = await listenOnLoopback(server);
201+
const info = { httpPort: port, token: TOKEN, pid: 1 };
202+
const controller = new AbortController();
203+
const inFlight = sendRequest(
204+
info,
205+
{
206+
token: TOKEN,
207+
command: 'wait',
208+
session: 'default',
209+
positionals: [],
210+
flags: {},
211+
meta: { requestId: 'req-http-abort-in-flight' },
212+
},
213+
'http',
214+
STATE_PATHS,
215+
undefined,
216+
{ signal: controller.signal },
217+
);
218+
await waitFor(() => seen.started, 'the daemon to start the request');
219+
controller.abort();
220+
await assert.rejects(inFlight, (error: unknown) => canceledRequestError(error, 'unknown'));
221+
await waitFor(() => seen.canceled.length > 0, 'daemon-side cancellation');
222+
assert.deepEqual(seen.canceled, [true]);
223+
assert.equal(seen.requestId, 'req-http-abort-in-flight');
224+
225+
const health = await fetch(`http://127.0.0.1:${port}/health`);
226+
assert.equal(health.ok, true);
227+
} finally {
228+
await closeLoopbackServer(server);
229+
}
230+
});
231+
232+
async function waitFor(condition: () => boolean, what: string): Promise<void> {
233+
const deadline = Date.now() + 3000;
234+
while (!condition()) {
235+
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${what}.`);
236+
await new Promise((resolve) => setTimeout(resolve, 10));
237+
}
238+
}

0 commit comments

Comments
 (0)