Skip to content

Commit e14c9d8

Browse files
thymikeeclaude
andauthored
fix(cloud): unblock iOS snapshot and gate cloud fill on text-entry focus (#1658) (#1666)
* fix(cloud): unblock iOS snapshot and gate cloud fill on text-entry focus (#1658) Two bugs isolated to the cloud-webdriver iOS path. `snapshot`/`diff` refused every capture on a live BrowserStack session with SESSION_NOT_FOUND, instantly and without a driver round trip. The app-session guard they ran belongs to the local XCUITest runner, which must attach to a target app; a cloud capture reads the provider's own driver session and needs no app identity, so it now applies to local Apple targets only. The session was empty in the first place because the provider open path skips local app resolution wholesale — no simctl/devicectl reaches a hosted device — and dropped an explicitly spelled bundle id along with it. A dotted, non-deep-link target is the bundle id under the same convention resolveIosApp applies locally, so a cloud `open com.example.app` now records it. `fill` tapped and sent its keys in back-to-back requests. A WebView input — an OAuth page in a Safari view controller — takes first responder asynchronously, so the keys landed with nothing focused while the command still answered "Filled N chars"; tapping and filling as two separate commands worked only because the round trip between them gave the field time to focus. The cloud interactor now waits on the same signal the Apple runner uses, the software keyboard going from hidden to shown after its tap, and discloses what it observed as `textEntryReadiness` so a fill with no witness cannot pass for a filled field. Where keyboard visibility cannot witness the focus move — back-to-back fills into one form, the shape that failed most often — it spends the runner's full readiness budget rather than racing the app with a short settle. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015Zjbzf7HdziX9SzFpNP7WW * fix(cloud): let a new bundle-id open replace the tracked cloud iOS app Adopting an explicitly spelled bundle id on a provider-backed open (the fix that makes snapshot/diff work at all) also made a previously dead precedence rule live: the provider branch returned currentAppBundleId first, so once a first open had populated it, `open com.a` followed by `open com.b` left the session still reporting com.a to every appBundleId-gated command. The local path does the opposite, and is the convention this branch is meant to mirror: resolveIosApp returns a dotted target unchanged and never consults the session's current app. Only its deep-link branches prefer the tracked id. Flip the provider branch to match — an explicit bundle-id target wins, and everything the branch cannot name (deep links, display names, bare open) still falls back to the tracked id. * fix(cloud): fail a witness-less cloud fill instead of reporting it filled Review follow-ups on #1658. `not-observed` was still a success: it sent the keys and answered "Filled N chars", and nothing renders `textEntryReadiness` in default CLI output — so the exact silent success this branch exists to remove survived whenever focus never happened. A tap that raises no keyboard now fails with `text_entry_focus_not_observed` and sends no keys, leaving the field untouched rather than half-written, and the readiness vocabulary keeps only outcomes that describe a fill that did type. The readiness budget was advertised but not enforced at the request boundary: each keyboard probe inherited the client's 30s default, so one hung probe could hold a 2s wait for far longer. Probes now carry their own bound, threaded through the client as a per-request timeout override. The probe also swallowed every error as "this driver cannot answer", which degraded a dead session, an auth rejection, or a grid outage into a blind text entry. Only a positively classified unimplemented route counts as unsupported now — classified on the W3C error code rather than the status, since `unknown command` and `invalid session id` share HTTP 404 — and everything else propagates. The provider scenario proved request ordering against a stub that always accepted keys. Its fake now models the device: focus lands a beat after the tap, and keys arriving while the keyboard is down are accepted and dropped, exactly as an unfocused field does. The tests assert the field's own value, and both go red against the pre-fix `fill`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015Zjbzf7HdziX9SzFpNP7WW * fix(cloud): witness the tapped field's focus before a cloud fill types Review of cc23f2b found two ways a fill could still report success without evidence that OUR tap focused the field it was aimed at. P1. `settled-keyboard-up` and `settled-unknown` both typed and returned normal success. Keyboard visibility can only witness that *a* field took focus, never *which*: filling a second field in an already-open form reads the same before and after, so a missed tap left the first field focused and `POST /keys` — which the driver routes to whatever holds first responder — appended to it while every request returned 200. Failing those closed outright would have broken ordinary multi-field form fills, which do work: a live AWS Device Farm run types both fields of a WebView login correctly. So witness focus properly instead. W3C `GET /element/active` answers the question keyboard visibility cannot — is the thing focused now the thing I tapped — and answers it whether or not the keyboard was already up. That becomes the primary signal (`focused-element`); the keyboard transition stays as the fallback for drivers without the route, and a keyboard already up on such a driver now refuses rather than typing. The test is identity, not geometry. Containment of the tap point looks like the obvious rule and is wrong: focusing a field can re-lay it out. On a live iPhone 16, tapping Safari's collapsed address bar expands it into a taller field that no longer covers the tapped point, and a containment-only rule refused a fill that plainly worked. So a tap that MOVES focus counts, with containment as the second half of the test — re-filling the already-focused field moves nothing, and only geometry tells that from a tap that missed. Both readings are taken before the tap, since each is evidence only as a change. P2. The 2s budget bounded the loop but not the calls inside it: every probe got a fixed 1500ms, so one begun near the deadline finished well past it. Both the probe timeout and the sleep are now capped by the remaining budget. Also fixes a related escape the review did not name: the poll loop had no catch, so one transient grid error aborted a fill the next poll would have satisfied. Probe failures are now tolerated within the budget, but a budget that expires without a single answered probe rethrows, so a dead session surfaces as itself rather than as "the tap missed". The provider scenario gains the two-field case the review asked for: it begins keyboard-up with the email field focused, misses the password tap, and asserts no keys reach the email field. Verified on AWS Device Farm iPhone 16 / iOS 18.0 at this exact tree: address bar (the re-layout case) and both WebView login fields all report `focused-element`, the second with the keyboard already up, and the device reads back `tomsmith` and a 20-character password. * fix(cloud): refuse a cloud fill no focus probe can witness, and bound the composite probe Two blockers from the review of 3a9aceb. P1. `settled-unknown` was the last path that typed without evidence: when both the active-element and keyboard routes are positively unsupported, `fill` settled 350ms, typed, and returned ordinary success. Nothing renders `textEntryReadiness`, so that reached a caller looking exactly like a fill that worked — the same silent false success #1658 is about, just narrowed to one branch. It now refuses with a distinct reason, `text_entry_focus_unobservable`: nothing is wrong with the target, the driver simply cannot answer, so the caller's next move differs from a missed tap and the hint names it — `press` then `type` stays the deliberate way to enter text unwitnessed. `CLOUD_TEXT_ENTRY_READINESS` is now `focused-element` and `keyboard-shown` only. Every value describes a fill that witnessed focus before sending a key; there is deliberately no value for typing blind. P2. `activeElement(timeoutMs)` bounded each of its two sequential requests by the full timeout rather than bounding the operation, so a probe handed the 1.5s left of a 2s readiness deadline could spend ~3s across `/element/active` and `/element/{id}/rect` and overrun the deadline it was derived from. It now derives one deadline at entry and gives the second request only what the first left, floored at zero so an already-spent budget aborts immediately instead of falling back to the client default. The regression pins elapsed transport time across both calls, which is what the defect is made of: the rect request answers only its own abort, so the time it was allowed to run IS the budget it was handed. It measures ~202ms of a shared 200ms budget before the fix and ~120ms after. Also updates the generic Cloud WebDriver facade scenario, whose stub answered `{value: null}` to everything and so read as a driver with neither route. It now answers the two focus probes, since that scenario exercises facade wiring rather than text-entry semantics — those live in cloud-webdriver-ios-text-entry.test.ts, which models focus properly. --------- Co-authored-by: Claude <[email protected]>
1 parent 9b4239b commit e14c9d8

15 files changed

Lines changed: 1651 additions & 12 deletions

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
## Unreleased
44

55
- `agent-device help workflow` is now a compact ~8KB card instead of a ~41KB dump; the same depth still exists, split into `help scripting` (save-script, secret-safe fills, batch JSON, replay divergence/repair, recording) and `help gestures` (multi-touch shapes and platform quirks), plus a few paragraphs folded into the topics that already owned the subject (`help debugging`, `help physical-device`, `help validate`). Every `help <topic>` first line is now `agent-device <version> — <topic>` so an agent can read the installed version from its mandatory first help read instead of a separate `agent-device --version` call.
6-
6+
- Cloud iOS (BrowserStack, AWS Device Farm): `snapshot` and `diff` no longer fail with `SESSION_NOT_FOUND` on a live provider session (#1658). The app-session guard they ran belongs to the local XCUITest runner, which must attach to a target app; a cloud capture reads the provider's own driver session and needs no app identity, so the guard now applies to local Apple targets only. Relatedly, a cloud iOS `open com.example.app` now records that bundle id on the session — the provider path skips local app resolution (no simctl/devicectl reaches a hosted device), and used to drop an explicitly spelled bundle id along with it, leaving the session with no app identity at all. Opening a second bundle id replaces the first, matching the local path, where an explicitly spelled target always wins over the session's current app; deep links, display names, and bare `open` still keep the app already tracked.
7+
- Cloud `fill` (BrowserStack, AWS Device Farm) now witnesses that the field it tapped actually holds text-entry focus before sending its keys, instead of dispatching tap and keys in back-to-back requests (#1658). A WebView input — an OAuth/SSO page in a Safari view controller, for example — takes first responder asynchronously, so the keys used to land with nothing focused while `fill` still answered "Filled N chars"; tapping and filling as two separate commands worked only because the round trip between them gave the field time to focus. The witness is the focused element's own geometry: `fill` polls the active element and proceeds only once it contains the point it tapped, which is the one signal that identifies *which* field took focus. Keyboard visibility cannot — it reads the same before and after a second fill into an already-open form, so it could not tell a focused password field from the email field the previous fill left focused. The response discloses `textEntryReadiness`: `focused-element`, or `keyboard-shown` when the driver has no active-element route but the keyboard rose from hidden after the tap. Both describe a fill that witnessed focus before typing; there is deliberately no value for typing without evidence, because nothing renders this field and such a value would reach a caller as an ordinary success. Breaking: when focus cannot be witnessed, cloud `fill` now FAILS with `COMMAND_FAILED` / `text_entry_focus_not_observed` and sends no keys, instead of typing into whatever holds first responder and answering "Filled N chars" — a fill with no witness must not read as a filled field. That covers a tap that focused nothing, a keyboard already up on a driver that cannot name the focused field, and a driver that reports neither (`text_entry_focus_unobservable`, which points at `press` + `type` as the deliberate way to enter text unwitnessed). Only a positively classified unimplemented route counts as unsupported, so a dead session, an auth rejection, or a grid outage surfaces instead of degrading into a blind text entry.
78
- `scroll` and `back` now accept `--settle` (with `--settle-quiet` and `--timeout`), collapsing scroll-then-observe and back-then-observe into one call (#1638). The response carries the same settled payload the touch commands return — verdict, changed-lines diff with fresh refs on added lines, the unchanged-interactive tail, and `refsGeneration` when the settled tree was stored — and is best-effort: it never fails the action. One difference is deliberate: `scroll`/`back` resolve no element, so the diff baseline is the session's stored pre-action tree ("the last tree you observed") rather than a freshly resolved pre-action capture. Both commands now also preserve the daemon on timeout, like the other settle-capable commands.
89
- Security: repository `./agent-device.json` now accepts only project-safe automation defaults. It rejects daemon endpoint/auth/transport/server settings, tenant/run/lease selectors, provider/cloud and Metro connection fields, headers, executable reporter modules, local write destinations, and other operator-controlled values before local module loading or any daemon health/RPC request. Put remote endpoint and token together in protected CI environment variables, user config, an explicit `--config` file, or the existing `connect`/`--remote-config` workflow. Daemon auth tokens no longer travel in serialized command flags.
910
- `viewport` is now rejected during capability admission on Apple targets instead of reaching the device and failing inside dispatch. No Apple backend can resize a screen — simulator and device geometry is fixed by the selected device type — so `viewport` on iOS/iPadOS/tvOS/macOS now fails with `UNSUPPORTED_OPERATION`, `viewport is not supported on this device`, and a hint pointing at `--platform web` and at picking a different simulator. `capabilities` no longer advertises `viewport` on Apple targets. Web viewport resizing (`agent-device viewport 1280 900 --platform web`) is unchanged, and Android was already denied.

‎packages/contracts/src/facades/interaction.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,16 @@ export type {
106106
SettleParams,
107107
SettleTailEntry,
108108
} from '../interaction.ts';
109-
export { MAESTRO_NON_HITTABLE_FALLBACK_MESSAGE, TEXT_ENTRY_ROUTES } from '../interactor-types.ts';
109+
export {
110+
CLOUD_TEXT_ENTRY_READINESS,
111+
MAESTRO_NON_HITTABLE_FALLBACK_MESSAGE,
112+
TEXT_ENTRY_ROUTES,
113+
} from '../interactor-types.ts';
110114
export type {
115+
CloudTextEntryReadiness,
111116
ElementSelectorKey,
112117
ElementSelectorTapOptions,
118+
FillBackendResult,
113119
Interactor,
114120
RunnerCallOptions,
115121
RunnerContext,

‎packages/contracts/src/interactor-types.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,49 @@ export type TypeTextBackendResult = {
9898
textEntryRoute?: TextEntryRoute;
9999
};
100100

101+
/**
102+
* What a cloud-WebDriver `fill` could establish about its target taking text
103+
* entry focus before it sent the keys (#1658). The local Apple runner owns this
104+
* discipline in Swift and reports it as a `textEntryRoute`; the cloud path has
105+
* no runner, only what the driver will tell it, so it names what it observed
106+
* instead of which channel it typed through. Listed strongest evidence first:
107+
*
108+
* - `focused-element`: the element holding text-entry focus after the tap
109+
* contains the tapped point — positive evidence that THIS field, not merely
110+
* some field, took focus.
111+
* - `keyboard-shown`: no active-element route, but the software keyboard went
112+
* from hidden to shown after our tap. Witnesses that focus arrived somewhere,
113+
* which only means our field when the keyboard was down beforehand.
114+
* Every value describes a fill that sent its keys AND witnessed focus first.
115+
* There is deliberately no value for "typed without evidence": nothing renders
116+
* this field, so such a value would reach a caller as an ordinary success and
117+
* recreate the #1658 silent false success it exists to remove. Every
118+
* unwitnessed case throws without typing instead —
119+
*
120+
* - `text_entry_focus_not_observed`: the tap focused nothing, or a keyboard
121+
* already up on a driver that cannot say which field owns it (keys would have
122+
* landed in the PREVIOUS field).
123+
* - `text_entry_focus_unobservable`: the driver implements neither route, so no
124+
* wait could establish anything. `press` + `type` remains the deliberate way
125+
* to enter text unwitnessed.
126+
*
127+
* Closed set: the cloud interactor is its only producer and the boundary that
128+
* narrows it (readFillBackendResult, src/core/dispatch-interactions.ts) drops a
129+
* value it cannot name.
130+
*/
131+
export const CLOUD_TEXT_ENTRY_READINESS = ['focused-element', 'keyboard-shown'] as const;
132+
133+
export type CloudTextEntryReadiness = (typeof CLOUD_TEXT_ENTRY_READINESS)[number];
134+
135+
/**
136+
* What `Interactor.fill` reports back about the entry it performed. Only the
137+
* cloud-WebDriver interactor populates `textEntryReadiness`; the Apple runner
138+
* carries its own equivalent in Swift and every other platform fills blind.
139+
*/
140+
export type FillBackendResult = {
141+
textEntryReadiness?: CloudTextEntryReadiness;
142+
};
143+
101144
export type SnapshotOptions = BaseSnapshotOptions & {
102145
appBundleId?: string;
103146
signal?: AbortSignal;
Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
import assert from 'node:assert/strict';
2+
import { afterEach, test } from 'vitest';
3+
import { AppError } from '@agent-device/kernel/errors';
4+
import { WebDriverClient } from './webdriver-client.ts';
5+
6+
const realFetch = globalThis.fetch;
7+
8+
afterEach(() => {
9+
globalThis.fetch = realFetch;
10+
});
11+
12+
// #1658: `fill` blind-settles and types when the keyboard route is unsupported.
13+
// Anything else reaching that branch would degrade a real provider failure into
14+
// a blind text entry, so the split is pinned against the actual wire shapes.
15+
test('is_keyboard_shown reports an unimplemented route as unsupported', async () => {
16+
// Appium's own answer for a route the driver does not have.
17+
const client = await connectedClient(
18+
webDriverResponse(404, { value: { error: 'unknown command', message: 'Unknown command' } }),
19+
);
20+
21+
assert.equal(await client.isKeyboardShown(), 'unsupported');
22+
});
23+
24+
test('is_keyboard_shown reports a non-boolean answer as unsupported', async () => {
25+
const client = await connectedClient(webDriverResponse(200, { value: null }));
26+
27+
assert.equal(await client.isKeyboardShown(), 'unsupported');
28+
});
29+
30+
// The status is identical to an unimplemented route's, so a status-only test
31+
// would read a dead session as a missing feature and keep typing into it.
32+
test('is_keyboard_shown propagates a dead session, which shares the 404', async () => {
33+
const client = await connectedClient(
34+
webDriverResponse(404, {
35+
value: {
36+
error: 'invalid session id',
37+
message: 'A session is either terminated or not started',
38+
},
39+
}),
40+
);
41+
42+
await assert.rejects(client.isKeyboardShown(), (error: AppError) => {
43+
assert.match(error.message, /terminated or not started/);
44+
return true;
45+
});
46+
});
47+
48+
test('is_keyboard_shown propagates a grid failure', async () => {
49+
const client = await connectedClient(
50+
webDriverResponse(503, { value: { message: 'provider backend unavailable' } }),
51+
);
52+
53+
await assert.rejects(client.isKeyboardShown(), (error: AppError) => {
54+
assert.match(error.message, /provider backend unavailable/);
55+
return true;
56+
});
57+
});
58+
59+
// The readiness poll advertises a 2s budget; without the override each probe
60+
// would inherit the client's 30s default and one hung request could hold it
61+
// there. A stub that answers only the abort proves the caller's bound is the
62+
// one in force — were it ignored, this test would hang to its own timeout.
63+
test('is_keyboard_shown honors a caller timeout shorter than the client default', async () => {
64+
const client = await connectedClient(
65+
async (_input, init) =>
66+
await new Promise<Response>((_resolve, reject) => {
67+
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason as Error));
68+
}),
69+
);
70+
71+
await assert.rejects(client.isKeyboardShown(50), (error: Error) => {
72+
assert.match(`${error.name} ${error.message}`, /timeout|abort/i);
73+
return true;
74+
});
75+
});
76+
77+
// The focused element is the only signal that can say WHICH field took focus,
78+
// so `fill` fails closed when it is unavailable. Each wire shape it
79+
// distinguishes is pinned here.
80+
test('activeElement returns the focused element id and rect', async () => {
81+
const client = await connectedClient(
82+
webDriverRoutes({
83+
'/element/active': { body: { value: { [W3C_ELEMENT_KEY]: 'el-1' } } },
84+
'/rect': { body: { value: { x: 20, y: 300, width: 350, height: 44 } } },
85+
}),
86+
);
87+
88+
assert.deepEqual(await client.activeElement(), {
89+
id: 'el-1',
90+
rect: { x: 20, y: 300, width: 350, height: 44 },
91+
});
92+
});
93+
94+
// A form with nothing focused yet is an expected state, not a broken driver —
95+
// the caller must keep polling rather than give up.
96+
test('activeElement reports nothing focused as none', async () => {
97+
const client = await connectedClient(
98+
webDriverRoutes({
99+
'/element/active': {
100+
status: 404,
101+
body: { value: { error: 'no such element', message: 'nothing focused' } },
102+
},
103+
}),
104+
);
105+
106+
assert.equal(await client.activeElement(), 'none');
107+
});
108+
109+
// Focus moved between the two round trips. A race the caller can simply retry
110+
// out of, not a failure worth ending the fill on.
111+
test('activeElement reports an element that vanished before its rect as none', async () => {
112+
const client = await connectedClient(
113+
webDriverRoutes({
114+
'/element/active': { body: { value: { [W3C_ELEMENT_KEY]: 'el-1' } } },
115+
'/rect': {
116+
status: 404,
117+
body: { value: { error: 'no such element', message: 'stale element' } },
118+
},
119+
}),
120+
);
121+
122+
assert.equal(await client.activeElement(), 'none');
123+
});
124+
125+
// A grid that answers 200/null is not implementing the route: the spec reports
126+
// "nothing focused" as a `no such element` error. Reading null as "nothing
127+
// focused" would fail every fill on such a grid instead of falling back.
128+
test('activeElement reports a non-element answer as unsupported', async () => {
129+
const client = await connectedClient(
130+
webDriverRoutes({ '/element/active': { body: { value: null } } }),
131+
);
132+
133+
assert.equal(await client.activeElement(), 'unsupported');
134+
});
135+
136+
test('activeElement reports an unimplemented route as unsupported', async () => {
137+
const client = await connectedClient(
138+
webDriverRoutes({
139+
'/element/active': {
140+
status: 404,
141+
body: { value: { error: 'unknown command', message: 'Unknown command' } },
142+
},
143+
}),
144+
);
145+
146+
assert.equal(await client.activeElement(), 'unsupported');
147+
});
148+
149+
// Same discipline as the keyboard route: a dead session shares the 404 and must
150+
// never be mistaken for a driver that simply lacks the feature.
151+
test('activeElement propagates a dead session, which shares the 404', async () => {
152+
const client = await connectedClient(
153+
webDriverRoutes({
154+
'/element/active': {
155+
status: 404,
156+
body: {
157+
value: { error: 'invalid session id', message: 'A session is either terminated' },
158+
},
159+
},
160+
}),
161+
);
162+
163+
await assert.rejects(client.activeElement(), (error: AppError) => {
164+
assert.match(error.message, /terminated/);
165+
return true;
166+
});
167+
});
168+
169+
// `timeoutMs` bounds the OPERATION, not each request in it. Given the full
170+
// budget twice, these two sequential round trips would together take double it
171+
// — a probe handed the 1.5s left of a 2s readiness deadline would run 3s and
172+
// overrun the deadline it came from. Real time is unavoidable here: the defect
173+
// IS elapsed transport time across two calls.
174+
test('activeElement bounds its two sequential requests by one shared budget', async () => {
175+
const firstCallMs = 80;
176+
const budgetMs = 200;
177+
let rectRequestBudgetMs: number | undefined;
178+
const client = await connectedClient(async (input, init) => {
179+
const url = String(input instanceof Request ? input.url : input);
180+
if (url.includes('/rect')) {
181+
// Never answers; only its own abort ends it, so how long it was allowed
182+
// to run is exactly the budget it was handed.
183+
const startedAt = Date.now();
184+
return await new Promise<Response>((_resolve, reject) => {
185+
init?.signal?.addEventListener('abort', () => {
186+
rectRequestBudgetMs = Date.now() - startedAt;
187+
reject(init.signal?.reason as Error);
188+
});
189+
});
190+
}
191+
await new Promise((resolve) => setTimeout(resolve, firstCallMs));
192+
return new Response(JSON.stringify({ value: { [W3C_ELEMENT_KEY]: 'el-1' } }), {
193+
status: 200,
194+
headers: { 'Content-Type': 'application/json' },
195+
});
196+
});
197+
198+
await assert.rejects(client.activeElement(budgetMs));
199+
200+
assert.ok(rectRequestBudgetMs !== undefined, 'the rect request should have been made');
201+
// It must get what the first call left (~120ms), never a fresh 200ms.
202+
assert.ok(
203+
rectRequestBudgetMs < budgetMs - firstCallMs / 2,
204+
`rect request was allowed ${rectRequestBudgetMs}ms of a shared ${budgetMs}ms budget already ${firstCallMs}ms spent`,
205+
);
206+
});
207+
208+
const W3C_ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
209+
210+
/** Dispatches by URL suffix, since `activeElement` makes two round trips. */
211+
function webDriverRoutes(
212+
routes: Record<string, { status?: number; body: unknown }>,
213+
): typeof globalThis.fetch {
214+
const keys = Object.keys(routes).sort((a, b) => b.length - a.length);
215+
return async (input) => {
216+
const url = String(input instanceof Request ? input.url : input);
217+
const key = keys.find((candidate) => url.includes(candidate));
218+
const route = key
219+
? routes[key]!
220+
: { status: 500, body: { value: { message: `unrouted ${url}` } } };
221+
return new Response(JSON.stringify(route.body), {
222+
status: route.status ?? 200,
223+
headers: { 'Content-Type': 'application/json' },
224+
});
225+
};
226+
}
227+
228+
/** A client with a live session id, so the probes reach the session routes. */
229+
async function connectedClient(respond: typeof globalThis.fetch): Promise<WebDriverClient> {
230+
globalThis.fetch = webDriverResponse(200, {
231+
value: { sessionId: 'wd-1', capabilities: {} },
232+
});
233+
const client = new WebDriverClient({
234+
clientVersion: '0.0.0-test',
235+
endpoint: 'http://cloud-webdriver.test/wd/hub/',
236+
requestPolicy: { timeoutMs: 30_000, retryAttempts: 0 },
237+
});
238+
await client.createSession({ platformName: 'iOS' });
239+
globalThis.fetch = respond;
240+
return client;
241+
}
242+
243+
function webDriverResponse(status: number, body: unknown): typeof globalThis.fetch {
244+
return async () =>
245+
new Response(JSON.stringify(body), {
246+
status,
247+
headers: { 'Content-Type': 'application/json' },
248+
});
249+
}

0 commit comments

Comments
 (0)