Skip to content

Commit 3ac4047

Browse files
committed
refactor: one canceled-request error, and tighten the #1774 shapes
Review pass over the session-create fix: - The canceled-request error had nine hand-rolled copies (src/request/cancel, maestro shared, exec, retry, install-source x2, and the new provider one). It now has one definition in @agent-device/kernel/errors: createRequestCanceledError(details?, cause?) + isRequestCanceledError + REQUEST_CANCELED_REASON. Callers add evidence or a sharper hint; the reason itself is not overridable, so nothing can build one the predicate misses. - lease_allocate's timeout bundle moves beside INSTALL_TIMEOUT_POLICY in the registry (same {...DEFAULT, envelopeMs, onTimeout} shape); the request timeout constant stays exported from timeout-policy like its siblings. - Transport: fetch helper returns Response's own ok/status; the timeout reason const is private behind isWebDriverRequestTimeout. - Client: one-use options type inlined; the two deadline helpers share one floor. - Session-manager tests: shared makeRuntime/jsonResponse/afterEach restore. Net -29 lines with the feature in.
1 parent 6b6a33e commit 3ac4047

32 files changed

Lines changed: 194 additions & 223 deletions

‎packages/kernel/src/errors.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,40 @@ export function throwDaemonError(error: DaemonError): never {
128128
});
129129
}
130130

131+
/**
132+
* `details.reason` of a request its requester abandoned — an explicit cancel or
133+
* a client disconnect. One definition, so every layer that must let a
134+
* cancellation through untouched (retry loops, provider adapters, runner
135+
* transports) dispatches on the same typed reason.
136+
*/
137+
export const REQUEST_CANCELED_REASON = 'request_canceled';
138+
const REQUEST_CANCELED_MESSAGE = 'request canceled';
139+
const REQUEST_CANCELED_HINT =
140+
'The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.';
141+
142+
/**
143+
* The canceled-request error. `details` may add evidence (what was released,
144+
* which command was interrupted) or override the hint; the reason itself is
145+
* not overridable, so a caller cannot build one this predicate misses.
146+
*/
147+
export function createRequestCanceledError(details?: AppErrorDetails, cause?: unknown): AppError {
148+
return new AppError(
149+
'COMMAND_FAILED',
150+
REQUEST_CANCELED_MESSAGE,
151+
{ hint: REQUEST_CANCELED_HINT, ...details, reason: REQUEST_CANCELED_REASON },
152+
cause,
153+
);
154+
}
155+
156+
export function isRequestCanceledError(error: unknown): boolean {
157+
if (!(error instanceof AppError)) return false;
158+
if (error.code !== 'COMMAND_FAILED') return false;
159+
if (error.details?.reason === REQUEST_CANCELED_REASON) return true;
160+
// Owned debt: canceled errors that crossed a wire without their details keep
161+
// the message; do not add new message sniffs beside it.
162+
return error.message === REQUEST_CANCELED_MESSAGE;
163+
}
164+
131165
export function asAppError(err: unknown, fallbackCode: AppErrorCode = 'UNKNOWN'): AppError {
132166
if (err instanceof AppError) return err;
133167
if (err instanceof Error) {

‎packages/maestro/src/internal/engine-flow.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import path from 'node:path';
2-
import { AppError } from '@agent-device/kernel/errors';
3-
import { createRequestCanceledError } from './shared.ts';
2+
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
43
import {
54
MAESTRO_NUMERIC_FIELD_CONSTRAINTS,
65
numericDescription,

‎packages/maestro/src/internal/program-loader.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
3-
import { createRequestCanceledError } from './shared.ts';
3+
import { createRequestCanceledError } from '@agent-device/kernel/errors';
44
import type { MaestroProgram } from './program-ir.ts';
55
import { parseMaestroProgram } from './program-ir-parser.ts';
66

‎packages/maestro/src/internal/shared.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AppError } from '@agent-device/kernel/errors';
1+
import {} from '@agent-device/kernel/errors';
22
import type { Point, Rect, SnapshotNode } from '@agent-device/kernel/snapshot';
33

44
export function stripUndefined<T extends Record<string, unknown>>(value: T): T {
@@ -45,10 +45,3 @@ export function extractNodeText(node: SnapshotNode): string {
4545
?.trim() ?? ''
4646
);
4747
}
48-
49-
export function createRequestCanceledError(): AppError {
50-
return new AppError('COMMAND_FAILED', 'request canceled', {
51-
reason: 'request_canceled',
52-
hint: 'The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.',
53-
});
54-
}

‎packages/provider-webdriver/src/runtime-session.test.ts‎

Lines changed: 49 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
11
import assert from 'node:assert/strict';
2-
import { test } from 'vitest';
2+
import { afterEach, test } from 'vitest';
33
import type { DeviceLease } from '@agent-device/contracts/device';
44
import { deviceFieldsFromPublicPlatform, type DeviceInfo } from '@agent-device/kernel/device';
55
import { AppError } from '@agent-device/kernel/errors';
6-
import { createCloudWebDriverRuntime } from './runtime.ts';
6+
import { createCloudWebDriverRuntime, type CloudWebDriverRuntimeOptions } from './runtime.ts';
7+
8+
const realFetch = globalThis.fetch;
9+
10+
afterEach(() => {
11+
globalThis.fetch = realFetch;
12+
});
713

814
test('session allocation preserves its primary failure when provider cleanup also fails', async () => {
9-
const previousFetch = globalThis.fetch;
1015
let cleanupCalled = false;
11-
globalThis.fetch = async () =>
12-
new Response(JSON.stringify({ value: { message: 'create session failed' } }), {
13-
status: 500,
14-
headers: { 'Content-Type': 'application/json' },
15-
});
16-
const runtime = createCloudWebDriverRuntime({
17-
clientVersion: 'test',
18-
provider: 'webdriver-test',
19-
endpoint: 'https://webdriver.test/wd/hub/',
20-
platform: 'android',
21-
deviceName: 'Test device',
22-
requestPolicy: { retryAttempts: 0 },
16+
globalThis.fetch = async () => jsonResponse({ value: { message: 'create session failed' } }, 500);
17+
const runtime = makeRuntime({
2318
prepareSession: async ({ base }) => ({
2419
...base,
2520
cleanup: async () => {
@@ -30,10 +25,8 @@ test('session allocation preserves its primary failure when provider cleanup als
3025
});
3126

3227
try {
33-
const allocate = runtime.leaseLifecycle.allocate;
34-
assert.ok(allocate);
3528
await assert.rejects(
36-
() => allocate(makeLease()),
29+
() => runtime.leaseLifecycle.allocate!(makeLease()),
3730
(error: unknown) => {
3831
assert.ok(error instanceof AppError);
3932
assert.match(error.message, /create session failed/);
@@ -44,33 +37,20 @@ test('session allocation preserves its primary failure when provider cleanup als
4437
assert.equal(cleanupCalled, true);
4538
} finally {
4639
await runtime.shutdown();
47-
globalThis.fetch = previousFetch;
4840
}
4941
});
5042

5143
// #1774: a request already gone before the create is issued must create
5244
// NOTHING. Prepared provider resources are cleaned up and no `POST /session`
5345
// goes out, so there is no billed device session to leak.
5446
test('allocation canceled before create issues no session and cleans up prepared work', async () => {
55-
const previousFetch = globalThis.fetch;
5647
let sessionRequests = 0;
5748
let cleanupCalled = false;
5849
globalThis.fetch = async (input) => {
59-
if (String(input instanceof Request ? input.url : input).endsWith('/session')) {
60-
sessionRequests += 1;
61-
}
62-
return new Response(JSON.stringify({ value: { sessionId: 'wd-1', capabilities: {} } }), {
63-
status: 200,
64-
headers: { 'Content-Type': 'application/json' },
65-
});
50+
if (requestUrl(input).endsWith('/session')) sessionRequests += 1;
51+
return jsonResponse({ value: { sessionId: 'wd-1', capabilities: {} } });
6652
};
67-
const runtime = createCloudWebDriverRuntime({
68-
clientVersion: 'test',
69-
provider: 'webdriver-test',
70-
endpoint: 'https://webdriver.test/wd/hub/',
71-
platform: 'android',
72-
deviceName: 'Test device',
73-
requestPolicy: { retryAttempts: 0 },
53+
const runtime = makeRuntime({
7454
prepareSession: async ({ base }) => ({
7555
...base,
7656
cleanup: async () => {
@@ -83,10 +63,8 @@ test('allocation canceled before create issues no session and cleans up prepared
8363
controller.abort();
8464

8565
try {
86-
const allocate = runtime.leaseLifecycle.allocate;
87-
assert.ok(allocate);
8866
await assert.rejects(
89-
() => allocate(makeLease(), { signal: controller.signal }),
67+
() => runtime.leaseLifecycle.allocate!(makeLease(), { signal: controller.signal }),
9068
(error: unknown) => {
9169
assert.ok(error instanceof AppError);
9270
assert.equal(error.details?.reason, 'request_canceled');
@@ -97,7 +75,6 @@ test('allocation canceled before create issues no session and cleans up prepared
9775
assert.equal(cleanupCalled, true);
9876
} finally {
9977
await runtime.shutdown();
100-
globalThis.fetch = previousFetch;
10178
}
10279
});
10380

@@ -106,44 +83,28 @@ test('allocation canceled before create issues no session and cleans up prepared
10683
// register that session (nobody is waiting on it) — it deletes it, holding the
10784
// id it just learned, so the billed session is released instead of orphaned.
10885
test('a session that completes after cancellation is released, not registered', async () => {
109-
const previousFetch = globalThis.fetch;
11086
const controller = new AbortController();
11187
let deletedSessionId: string | undefined;
11288
globalThis.fetch = async (input, init) => {
113-
const url = String(input instanceof Request ? input.url : input);
89+
const url = requestUrl(input);
11490
const method = init?.method ?? 'GET';
11591
if (url.endsWith('/session') && method === 'POST') {
11692
// The client disconnects mid-create; the provider finishes anyway.
11793
controller.abort();
118-
return new Response(JSON.stringify({ value: { sessionId: 'wd-live', capabilities: {} } }), {
119-
status: 200,
120-
headers: { 'Content-Type': 'application/json' },
121-
});
94+
return jsonResponse({ value: { sessionId: 'wd-live', capabilities: {} } });
12295
}
12396
if (url.endsWith('/session/wd-live') && method === 'DELETE') {
12497
deletedSessionId = 'wd-live';
125-
return new Response(JSON.stringify({ value: null }), {
126-
status: 200,
127-
headers: { 'Content-Type': 'application/json' },
128-
});
98+
return jsonResponse({ value: null });
12999
}
130100
throw new Error(`unexpected ${method} ${url}`);
131101
};
132-
const runtime = createCloudWebDriverRuntime({
133-
clientVersion: 'test',
134-
provider: 'webdriver-test',
135-
endpoint: 'https://webdriver.test/wd/hub/',
136-
platform: 'android',
137-
deviceName: 'Test device',
138-
requestPolicy: { retryAttempts: 0 },
139-
});
102+
const runtime = makeRuntime();
140103
const lease = makeLease();
141104

142105
try {
143-
const allocate = runtime.leaseLifecycle.allocate;
144-
assert.ok(allocate);
145106
await assert.rejects(
146-
() => allocate(lease, { signal: controller.signal }),
107+
() => runtime.leaseLifecycle.allocate!(lease, { signal: controller.signal }),
147108
(error: unknown) => {
148109
assert.ok(error instanceof AppError);
149110
assert.equal(error.details?.reason, 'request_canceled');
@@ -156,7 +117,6 @@ test('a session that completes after cancellation is released, not registered',
156117
assert.equal(runtime.getInteractor(makeDevice(lease)), undefined);
157118
} finally {
158119
await runtime.shutdown();
159-
globalThis.fetch = previousFetch;
160120
}
161121
});
162122

@@ -165,30 +125,20 @@ test('a session that completes after cancellation is released, not registered',
165125
// an operator can find and stop the maybe-orphaned billed session, rather than
166126
// this process guessing at REST cleanup of a session it never owned.
167127
test('a create-timeout surfaces provider evidence for the maybe-leaked session', async () => {
168-
const previousFetch = globalThis.fetch;
169-
globalThis.fetch = async (input, init) => {
170-
if (String(input instanceof Request ? input.url : input).endsWith('/session')) {
171-
return await new Promise<Response>((_resolve, reject) => {
172-
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason as Error));
173-
});
174-
}
175-
throw new Error('unexpected request');
176-
};
177-
const runtime = createCloudWebDriverRuntime({
178-
clientVersion: 'test',
128+
globalThis.fetch = async (_input, init) =>
129+
await new Promise<Response>((_resolve, reject) => {
130+
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason as Error));
131+
});
132+
const runtime = makeRuntime({
179133
provider: 'browserstack',
180-
endpoint: 'https://webdriver.test/wd/hub/',
181134
platform: 'ios',
182-
deviceName: 'iPhone 17',
183135
requestPolicy: { retryAttempts: 0, sessionCreateTimeoutMs: 40 },
184136
});
185137
const lease = { ...makeLease(), leaseProvider: 'browserstack' };
186138

187139
try {
188-
const allocate = runtime.leaseLifecycle.allocate;
189-
assert.ok(allocate);
190140
await assert.rejects(
191-
() => allocate(lease),
141+
() => runtime.leaseLifecycle.allocate!(lease),
192142
(error: unknown) => {
193143
assert.ok(error instanceof AppError);
194144
assert.equal(error.details?.reason, 'provider_session_create_timeout');
@@ -200,10 +150,32 @@ test('a create-timeout surfaces provider evidence for the maybe-leaked session',
200150
);
201151
} finally {
202152
await runtime.shutdown();
203-
globalThis.fetch = previousFetch;
204153
}
205154
});
206155

156+
function makeRuntime(overrides: Partial<CloudWebDriverRuntimeOptions> = {}) {
157+
return createCloudWebDriverRuntime({
158+
clientVersion: 'test',
159+
provider: 'webdriver-test',
160+
endpoint: 'https://webdriver.test/wd/hub/',
161+
platform: 'android',
162+
deviceName: 'Test device',
163+
requestPolicy: { retryAttempts: 0 },
164+
...overrides,
165+
});
166+
}
167+
168+
function jsonResponse(body: unknown, status = 200): Response {
169+
return new Response(JSON.stringify(body), {
170+
status,
171+
headers: { 'Content-Type': 'application/json' },
172+
});
173+
}
174+
175+
function requestUrl(input: RequestInfo | URL): string {
176+
return String(input instanceof Request ? input.url : input);
177+
}
178+
207179
function makeDevice(lease: DeviceLease): DeviceInfo {
208180
return {
209181
...deviceFieldsFromPublicPlatform('android'),

‎packages/provider-webdriver/src/runtime-session.ts‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import type {
44
} from '@agent-device/contracts/observability';
55
import type { DeviceLease, LeaseLifecycleContext } from '@agent-device/contracts/device';
66
import { deviceFieldsFromPublicPlatform, type DeviceInfo } from '@agent-device/kernel/device';
7-
import { AppError } from '@agent-device/kernel/errors';
7+
import {
8+
AppError,
9+
createRequestCanceledError,
10+
type AppErrorDetails,
11+
} from '@agent-device/kernel/errors';
812
import { unavailableCloudArtifactsResult } from './artifact-results.ts';
913
import {
1014
createCloudWebDriverCapabilities,
@@ -182,7 +186,9 @@ export class WebDriverSessionManager {
182186
req: LeaseLifecycleContext | undefined,
183187
): Promise<WebDriverSession> {
184188
if (req?.signal?.aborted) {
185-
const canceled = requestCanceledError(this.options.provider, lease, {});
189+
const canceled = createRequestCanceledError(
190+
canceledAllocationEvidence(this.options.provider, lease),
191+
);
186192
await cleanupAfterCreateSessionFailure(handle.prepared, canceled);
187193
throw canceled;
188194
}
@@ -217,7 +223,8 @@ export class WebDriverSessionManager {
217223
session: WebDriverSession,
218224
): Promise<AppError> {
219225
const close = await this.closeSession(handle);
220-
return requestCanceledError(this.options.provider, lease, {
226+
return createRequestCanceledError({
227+
...canceledAllocationEvidence(this.options.provider, lease),
221228
releasedWebDriverSessionId: session.sessionId,
222229
...(handle.prepared.providerSessionId
223230
? { releasedProviderSessionId: handle.prepared.providerSessionId }
@@ -375,16 +382,10 @@ function sessionCreateTimeoutError(
375382
);
376383
}
377384

378-
function requestCanceledError(
379-
provider: string,
380-
lease: DeviceLease,
381-
released: Record<string, unknown>,
382-
): AppError {
383-
return new AppError('COMMAND_FAILED', 'request canceled', {
384-
reason: 'request_canceled',
385+
function canceledAllocationEvidence(provider: string, lease: DeviceLease): AppErrorDetails {
386+
return {
385387
provider,
386388
leaseId: lease.leaseId,
387-
...released,
388389
hint: 'The lease request was canceled (explicit cancel or client disconnect) while the provider session was being created; the session it produced, if any, was released instead of registered.',
389-
});
390+
};
390391
}

0 commit comments

Comments
 (0)