diff --git a/.changeset/bidi-started-response-status.md b/.changeset/bidi-started-response-status.md new file mode 100644 index 00000000..25985127 --- /dev/null +++ b/.changeset/bidi-started-response-status.md @@ -0,0 +1,7 @@ +--- +'@wdio/devtools-service': patch +'@wdio/selenium-devtools': patch +'@wdio/nightwatch-devtools': patch +--- + +A request the browser answered and then gave up on keeps the status it was answered with. Chrome stops loading a script whose response is a 404 and reports the request as `net::ERR_ABORTED`, so a missing script was listed as status 0 with no response headers. It is now listed as 404 with its response headers, with `net::ERR_ABORTED` as the error. A request that fails before any response, such as a blocked beacon, is still listed as status 0 with the error. diff --git a/.claude/rules/network-capture.md b/.claude/rules/network-capture.md index 456a6e0c..cbae9d8c 100644 --- a/.claude/rules/network-capture.md +++ b/.claude/rules/network-capture.md @@ -1,6 +1,6 @@ --- paths: - - "packages/core/src/{bidi,appium-interceptor,request-type,net,network-row-id}.ts" + - "packages/core/src/{bidi,bidi-started-response,appium-interceptor,request-type,net,network-row-id}.ts" - "packages/script/src/{collector,index}.ts" - "packages/script/src/collectors/**" - "packages/trace/src/{trace-network,trace-har}.ts" @@ -27,6 +27,9 @@ Three sources: driver-side (BiDi, Nightwatch's Chrome performance log), the coll - Give each redirect hop a row of its own, its id from `networkRowId` (`core/network-row-id.ts`; Python `frames.network_row_id`, held equal by `mirror-vectors.json`): the request id for the first hop, the id with BiDi's `redirectCount` after it, each on its own clock. Key tracked rows by that id (`MAX_TRACKED_REQUESTS`), match every answer and failure to its hop by its own `redirectCount`, and replace a row only when the same hop is sent again. Why: one row per chain showed a form submit as the `GET` it landed on, losing the `POST` and its 3xx; and matching by the latest hop left the `POST` pending when the next hop was sent before it was answered. The WebdriverIO service has handlers of its own and lists one row per response. - Report a hop's request headers as the browser gives them; nothing copies headers across hops. Why: a hop after a 303 can carry the `POST`'s `content-type` and `origin` in Chrome's BiDi event, which is the browser's report, not ours. - Close a failed BiDi fetch as status 0 with the browser's `errorText`, through the inspector's `fetchError` hook (`subscribeFetchErrors`). Why: otherwise every blocked beacon stays pending for the session. +- Keep each hop's `network.responseStarted` (core `handleBidiResponseStarted`, which the service calls too; Python `response_started_entry`) and close a hop that `fetchError` ends with that status and headers beside the error (`failedRowFields`; mirror section `failedAfterResponse`). Why: Chrome cancels a 404 script's body and sends `fetchError` `net::ERR_ABORTED`, never `responseCompleted`, so a missing bundle read as status 0. Keep it whether or not the hop's row exists: Chrome 158 delivered `responseStarted` before `beforeRequestSent`. +- The WDIO service subscribes `network.responseStarted` itself (`attachBidiListeners`). Why: WDIO's own network manager subscribes `beforeRequestSent`, `responseCompleted` and `fetchError` but not `responseStarted` (only `browser.mock()` does), so a listener alone never fires. +- Read `responseStarted` in core off the inspector's socket by method (`onSocketEvent`). Why: selenium-webdriver's inspector hands it to every callback shaped like a `responseCompleted`, so no shape tells the two apart. The completed handler therefore also closes a row when its headers arrive, and the real completion replaces it. - Write Resource Timing rows with `NETWORK_CAPTURE_SOURCE.RESOURCE_TIMING` (`shared/src/types.ts`), method `''` unless the load is parser-initiated (`GET`), and let the HAR writer add `_source`/`_resourceType`. Why: HAR's required `status` is written as 0, which reads back as a transport failure. - Read native app traffic only through `NativeNetworkCapture` (`core/appium-interceptor.ts`), throttling per-command drains to `NATIVE_NETWORK_DRAIN_INTERVAL_MS`; test-end and session-end drains are never throttled. Why: every read returns the whole history, bodies included. - Read browser-own schemes (`chrome-native:` included) only from `shared/src/browser-schemes.ts`. Why: core's injection gate and the collector's request filter drifted when they kept separate lists. @@ -38,3 +41,4 @@ Three sources: driver-side (BiDi, Nightwatch's Chrome performance log), the coll - Python and selenium-devtools withhold the page batch once BiDi serves (bodies lost); the service keeps patched rows beside BiDi's. - A drain before a page's first BiDi event can pass that page's rows once; Nightwatch clears its flags at session rotation, so loads before re-attach can be listed twice. - Native: no timing (stamped at first read); launch traffic before the listener starts is not listed. +- Python handles each BiDi event on its own thread, so a fetch error handled before its hop's `responseStarted` still closes as status 0. diff --git a/packages/core/src/bidi-headers.ts b/packages/core/src/bidi-headers.ts new file mode 100644 index 00000000..e63d5e73 --- /dev/null +++ b/packages/core/src/bidi-headers.ts @@ -0,0 +1,30 @@ +/** + * Flatten BiDi's `Array<{name, value:{value|type}}>` header shape to a + * lowercased `Record`. Exported so adapter-side helpers can + * reuse it for their own header normalization. + */ +export function arrayHeadersToObject( + headers: unknown +): Record | undefined { + if (!Array.isArray(headers)) { + return undefined + } + const out: Record = {} + for (const h of headers as Array<{ + name?: string + value?: string | { value?: string; type?: string } + }>) { + const name = String(h?.name ?? '').toLowerCase() + if (!name) { + continue + } + const v = h?.value + out[name] = + typeof v === 'string' + ? v + : typeof (v as { value?: string })?.value === 'string' + ? (v as { value: string }).value + : JSON.stringify(v ?? '') + } + return out +} diff --git a/packages/core/src/bidi-started-response.ts b/packages/core/src/bidi-started-response.ts new file mode 100644 index 00000000..34dd7d88 --- /dev/null +++ b/packages/core/src/bidi-started-response.ts @@ -0,0 +1,81 @@ +import type { NetworkRequest } from '@wdio/devtools-shared' +import { arrayHeadersToObject } from './bidi-headers.js' +import { errorMessage } from './error.js' +import { getRequestType } from './net.js' +import { networkRowId } from './network-row-id.js' + +interface ResponseStartedEvent { + redirectCount?: number + request?: { request?: string } + id?: string + response?: { + status?: number + statusText?: string + headers?: unknown + mimeType?: string + } +} + +/** What `network.responseStarted` reported for a hop: kept until a fetch error + * closes that hop, because Chrome cancels a script body once its status is an + * error and BiDi then sends `fetchError`, not `responseCompleted`. */ +export interface StartedResponse { + status: number + statusText?: string + responseHeaders?: Record + mimeType?: string +} + +/** Started responses kept per session: a fetch error follows its response + * within milliseconds, so only the latest few can still be claimed. */ +const MAX_STARTED_RESPONSES = 256 + +/** Keep a hop's started response, whether or not its request row exists yet: + * Chrome can deliver `responseStarted` before `beforeRequestSent`. */ +export function handleBidiResponseStarted( + rawEvent: unknown, + started: Map, + log: (level: 'warn', message: string) => void +): void { + const event = rawEvent as ResponseStartedEvent + try { + const requestId = String(event?.request?.request ?? event?.id ?? '') + const status = Number(event?.response?.status) + if (!requestId || !status) { + return + } + started.set(networkRowId(requestId, event?.redirectCount), { + status, + statusText: event?.response?.statusText, + responseHeaders: arrayHeadersToObject(event?.response?.headers), + mimeType: event?.response?.mimeType + }) + if (started.size > MAX_STARTED_RESPONSES) { + started.delete(started.keys().next().value as string) + } + } catch (err) { + log('warn', `responseStarted threw: ${errorMessage(err)}`) + } +} + +/** The status, headers and type a failed hop closes with: what its started + * response reported, else status 0 with the browser's error text. */ +export function failedRowFields( + url: string, + errorText: string, + answered: StartedResponse | undefined +): Pick & + Partial> { + if (!answered) { + return { status: 0, statusText: errorText, error: errorText } + } + return { + status: answered.status, + statusText: answered.statusText ?? errorText, + error: errorText, + ...(answered.responseHeaders + ? { responseHeaders: answered.responseHeaders } + : {}), + type: getRequestType(url, answered.mimeType) + } +} diff --git a/packages/core/src/bidi-timing.ts b/packages/core/src/bidi-timing.ts new file mode 100644 index 00000000..bde46532 --- /dev/null +++ b/packages/core/src/bidi-timing.ts @@ -0,0 +1,38 @@ +/** Subset of WebDriver BiDi `FetchTimingInfo` (selenium exposes these via + * getters). Values are ms offsets from the request baseline `requestTime` + * (usually 0), so `responseEnd - requestTime` is the request duration. */ +export interface FetchTimings { + requestTime?: number + responseEnd?: number +} + +const isFiniteNumber = (value: unknown): value is number => + typeof value === 'number' && Number.isFinite(value) + +/** Request duration (ms) from the browser's FetchTimingInfo, plus a derived + * endTime anchored to `startTime`. The browser timings are immune to BiDi + * events arriving batched in one tick (which collapses the event-level + * `timestamp`/`Date.now()` to a single value and yields 0-duration requests). + * Falls back to the timestamp diff only when timings are unavailable. */ +export function bidiResponseTiming( + timings: FetchTimings | undefined, + startTime: number, + timestamp?: number +): { endTime: number; time: number } { + if ( + timings && + isFiniteNumber(timings.requestTime) && + isFiniteNumber(timings.responseEnd) && + timings.responseEnd > timings.requestTime + ) { + const time = Math.round(timings.responseEnd - timings.requestTime) + return { endTime: startTime + time, time } + } + const endTime = Number(timestamp ?? Date.now()) + return { endTime, time: Math.max(0, endTime - startTime) } +} + +/** The browser-clock start, only when the event carried one. */ +export function wallTimeOf(value: unknown): { wallTime?: number } { + return isFiniteNumber(value) ? { wallTime: Number(value) } : {} +} diff --git a/packages/core/src/bidi.ts b/packages/core/src/bidi.ts index f503227a..d6e8acff 100644 --- a/packages/core/src/bidi.ts +++ b/packages/core/src/bidi.ts @@ -14,10 +14,23 @@ import { NEVER_ABORTED, type CaptureCallGuard } from './capture-call-guard.js' +import { arrayHeadersToObject } from './bidi-headers.js' +import { + bidiResponseTiming, + wallTimeOf, + type FetchTimings +} from './bidi-timing.js' +import { + failedRowFields, + handleBidiResponseStarted, + type StartedResponse +} from './bidi-started-response.js' import { errorMessage } from './error.js' import { getRequestType } from './net.js' import { networkRowId } from './network-row-id.js' +export { arrayHeadersToObject } + /** Generic sinks the BiDi handlers push into; {@link buildBidiSinks} wires them to a capturer. */ export interface BidiHandlerSinks { pushConsoleLog: (entry: ConsoleLog) => void @@ -208,17 +221,6 @@ async function attachLogInspector( } } -/** Subset of WebDriver BiDi `FetchTimingInfo` (selenium exposes these via - * getters). Values are ms offsets from the request baseline `requestTime` - * (usually 0), so `responseEnd - requestTime` is the request duration. */ -interface FetchTimings { - requestTime?: number - responseEnd?: number -} - -const isFiniteNumber = (value: unknown): value is number => - typeof value === 'number' && Number.isFinite(value) - interface BeforeRequestSentEvent { /** How many redirects led to this hop; 0 or absent for the request itself. */ redirectCount?: number @@ -247,34 +249,6 @@ interface ResponseCompletedEvent { } } -/** Request duration (ms) from the browser's FetchTimingInfo, plus a derived - * endTime anchored to `startTime`. The browser timings are immune to BiDi - * events arriving batched in one tick (which collapses the event-level - * `timestamp`/`Date.now()` to a single value and yields 0-duration requests). - * Falls back to the timestamp diff only when timings are unavailable. */ -function bidiResponseTiming( - timings: FetchTimings | undefined, - startTime: number, - timestamp?: number -): { endTime: number; time: number } { - if ( - timings && - isFiniteNumber(timings.requestTime) && - isFiniteNumber(timings.responseEnd) && - timings.responseEnd > timings.requestTime - ) { - const time = Math.round(timings.responseEnd - timings.requestTime) - return { endTime: startTime + time, time } - } - const endTime = Number(timestamp ?? Date.now()) - return { endTime, time: Math.max(0, endTime - startTime) } -} - -/** The browser-clock start, only when the event carried one. */ -function wallTimeOf(value: unknown): { wallTime?: number } { - return isFiniteNumber(value) ? { wallTime: Number(value) } : {} -} - /** Rows a session has seen, by row id (`networkRowId`): an answer or failure * closes the row of the hop it names, whatever order the hops arrive in. */ const MAX_TRACKED_REQUESTS = 5000 @@ -384,17 +358,20 @@ interface FetchErrorEvent { } /** A request the browser gave up on: closed as a failure, as the WDIO service - * closes its own, so it never sits in the Network tab as pending. */ + * closes its own, so it never sits in the Network tab as pending. A hop the + * browser had already answered keeps that answer's status beside the error. */ export function handleBidiFetchError( rawEvent: unknown, rows: Map, sinks: BidiHandlerSinks, - log: BidiLogger + log: BidiLogger, + started: Map = new Map() ): void { const event = rawEvent as FetchErrorEvent try { const requestId = String(event?.request?.request ?? event?.id ?? '') - const previous = rows.get(networkRowId(requestId, event?.redirectCount)) + const rowId = networkRowId(requestId, event?.redirectCount) + const previous = rows.get(rowId) // The inspector delivers every network event here too; only a failure // carries `errorText`. if (!previous || typeof event?.errorText !== 'string') { @@ -405,12 +382,11 @@ export function handleBidiFetchError( previous.startTime, event?.timestamp ) - const errorText = event?.errorText ?? 'Failed' + const answered = started.get(rowId) + started.delete(rowId) const finalized: NetworkRequest = { ...previous, - status: 0, - statusText: errorText, - error: errorText, + ...failedRowFields(previous.url, event.errorText, answered), endTime, time } @@ -421,36 +397,83 @@ export function handleBidiFetchError( } } -/** A failed fetch closes its row, or it would stay pending forever: through - * the inspector's own hook, or off the socket for an inspector without one. */ -async function subscribeFetchErrors( +/** Subscribe to one BiDi event and read it off the inspector's socket by its + * method; the inspector's own callbacks lose the method, so a `responseStarted` + * reaches them looking like a `responseCompleted`. False when the inspector + * exposes no connection to subscribe on. */ +async function onSocketEvent( inspector: NetworkInspector, - rows: Map, - sinks: BidiHandlerSinks, - log: BidiLogger -): Promise { - if (typeof inspector.fetchError === 'function') { - await inspector.fetchError((e) => handleBidiFetchError(e, rows, sinks, log)) - return - } + method: string, + handle: (params: unknown) => void +): Promise { const bidi = inspector.bidi if (typeof bidi?.subscribe !== 'function' || !bidi.socket?.on) { - return + return false } - await bidi.subscribe('network.fetchError') + await bidi.subscribe(method) bidi.socket.on('message', (raw) => { try { - const { method, params } = JSON.parse(String(raw)) as { + const frame = JSON.parse(String(raw)) as { method?: string params?: unknown } - if (method === 'network.fetchError') { - handleBidiFetchError(params, rows, sinks, log) + if (frame.method === method) { + handle(frame.params) } } catch { /* a frame that is not JSON is not an event */ } }) + return true +} + +/** A failed fetch closes its row, or it would stay pending forever: through + * the inspector's own hook, or off the socket for an inspector without one. */ +async function subscribeFetchErrors( + inspector: NetworkInspector, + rows: Map, + sinks: BidiHandlerSinks, + log: BidiLogger, + started: Map +): Promise { + const handle = (e: unknown) => + handleBidiFetchError(e, rows, sinks, log, started) + if (typeof inspector.fetchError === 'function') { + await inspector.fetchError(handle) + return + } + await onSocketEvent(inspector, 'network.fetchError', handle) +} + +/** The two failure subscriptions, each optional: the inspector is attached + * either way. Without `responseStarted` a request the browser answers and then + * cancels reads as status 0; without `fetchError` it stays pending. */ +async function subscribeFailures( + inspector: NetworkInspector, + rows: Map, + sinks: BidiHandlerSinks, + log: BidiLogger, + signal: AbortSignal +): Promise { + const started = new Map() + try { + await onSocketEvent(inspector, 'network.responseStarted', (e) => + handleBidiResponseStarted(e, started, log) + ) + } catch (err) { + log( + 'warn', + `BiDi network.responseStarted unavailable: ${errorMessage(err)}` + ) + } + if (signal.aborted) { + return + } + try { + await subscribeFetchErrors(inspector, rows, sinks, log, started) + } catch (err) { + log('warn', `BiDi network.fetchError unavailable: ${errorMessage(err)}`) + } } export async function attachNetworkInspector( @@ -488,12 +511,7 @@ export async function attachNetworkInspector( if (signal.aborted) { return false } - try { - await subscribeFetchErrors(inspector, rows, guarded, log) - } catch (err) { - // The inspector is attached either way; only failed requests stay pending. - log('warn', `BiDi network.fetchError unavailable: ${errorMessage(err)}`) - } + await subscribeFailures(inspector, rows, guarded, log, signal) if (signal.aborted) { return false } @@ -569,34 +587,3 @@ export async function attachBidiHandlers( } return attached > 0 } - -/** - * Flatten BiDi's `Array<{name, value:{value|type}}>` header shape to a - * lowercased `Record`. Exported so adapter-side helpers can - * reuse it for their own header normalization. - */ -export function arrayHeadersToObject( - headers: unknown -): Record | undefined { - if (!Array.isArray(headers)) { - return undefined - } - const out: Record = {} - for (const h of headers as Array<{ - name?: string - value?: string | { value?: string; type?: string } - }>) { - const name = String(h?.name ?? '').toLowerCase() - if (!name) { - continue - } - const v = h?.value - out[name] = - typeof v === 'string' - ? v - : typeof (v as { value?: string })?.value === 'string' - ? (v as { value: string }).value - : JSON.stringify(v ?? '') - } - return out -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1cbb0d21..71a38355 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -52,6 +52,7 @@ export * from '@wdio/devtools-trace/trace-mutations' export * from '@wdio/devtools-trace/trace-snapshots' export * from '@wdio/devtools-trace/trace-zip-writer' export * from './bidi.js' +export * from './bidi-started-response.js' export * from './bidi-preload.js' export * from './network-row-id.js' export { diff --git a/packages/core/tests/bidi-started-response.test.ts b/packages/core/tests/bidi-started-response.test.ts new file mode 100644 index 00000000..f90f94b5 --- /dev/null +++ b/packages/core/tests/bidi-started-response.test.ts @@ -0,0 +1,198 @@ +import { describe, it, expect } from 'vitest' +import type { NetworkRequest } from '@wdio/devtools-shared' +import { + attachNetworkInspector, + handleBidiFetchError, + handleBidiRequestSent, + type BidiHandlerSinks +} from '../src/bidi.js' +import { + handleBidiResponseStarted, + type StartedResponse +} from '../src/bidi-started-response.js' + +function makeSinks() { + const pushed: NetworkRequest[] = [] + const replacements: Array<{ id: string; entry: NetworkRequest }> = [] + const sinks: BidiHandlerSinks = { + pushConsoleLog: () => {}, + pushNetworkRequest: (entry) => pushed.push(entry), + replaceNetworkRequest: (id, entry) => replacements.push({ id, entry }) + } + return { sinks, pushed, replacements } +} + +const silentLog = () => {} + +const scriptRequest = { + request: { request: 'S1', url: 'https://x/app.v2.js', method: 'GET' }, + timestamp: 1, + initiator: { type: 'parser' } +} +const scriptNotFound = { + request: { request: 'S1', url: 'https://x/app.v2.js' }, + timestamp: 2, + response: { + status: 404, + statusText: 'Not Found', + mimeType: 'text/plain', + headers: [ + { name: 'Content-Type', value: { type: 'string', value: 'text/plain' } } + ] + } +} +const scriptAborted = { + request: { request: 'S1' }, + timestamp: 3, + errorText: 'net::ERR_ABORTED' +} + +describe('a hop the browser answered and then gave up on', () => { + it('keeps the answer’s status, headers and type beside the error', () => { + const { sinks, replacements } = makeSinks() + const rows = new Map() + const started = new Map() + // Chrome 158 delivered responseStarted before the request's beforeRequestSent. + handleBidiResponseStarted(scriptNotFound, started, silentLog) + handleBidiRequestSent(scriptRequest, rows, sinks, silentLog) + handleBidiFetchError(scriptAborted, rows, sinks, silentLog, started) + expect(replacements.at(-1)?.entry).toMatchObject({ + id: 'S1', + status: 404, + statusText: 'Not Found', + error: 'net::ERR_ABORTED', + responseHeaders: { 'content-type': 'text/plain' } + }) + expect(started.size).toBe(0) + }) + + it('closes a hop with no answer as status 0 with the error text', () => { + const { sinks, replacements } = makeSinks() + const rows = new Map() + const started = new Map() + handleBidiRequestSent(scriptRequest, rows, sinks, silentLog) + handleBidiFetchError( + { ...scriptAborted, errorText: 'net::ERR_BLOCKED_BY_CLIENT' }, + rows, + sinks, + silentLog, + started + ) + expect(replacements.at(-1)?.entry).toMatchObject({ + status: 0, + statusText: 'net::ERR_BLOCKED_BY_CLIENT', + error: 'net::ERR_BLOCKED_BY_CLIENT' + }) + expect(replacements.at(-1)?.entry.responseHeaders).toBeUndefined() + }) + + it('applies an answer only to the hop it names', () => { + const { sinks, replacements } = makeSinks() + const rows = new Map() + const started = new Map() + handleBidiResponseStarted( + { ...scriptNotFound, redirectCount: 1 }, + started, + silentLog + ) + handleBidiRequestSent(scriptRequest, rows, sinks, silentLog) + handleBidiFetchError(scriptAborted, rows, sinks, silentLog, started) + expect(replacements.at(-1)?.entry.status).toBe(0) + }) + + it('keeps no answer without a status, and only the latest 256', () => { + const started = new Map() + handleBidiResponseStarted( + { request: { request: 'R0' }, response: { headers: [] } }, + started, + silentLog + ) + expect(started.size).toBe(0) + for (let i = 0; i < 300; i++) { + handleBidiResponseStarted( + { request: { request: `R${i}` }, response: { status: 200 } }, + started, + silentLog + ) + } + expect(started.size).toBe(256) + expect(started.has('R0')).toBe(false) + expect(started.has('R299')).toBe(true) + }) +}) + +describe('attachNetworkInspector reading responseStarted off the socket', () => { + /** A selenium-webdriver inspector: every frame with params reaches every + * callback, without its method, and the socket carries the frame itself. */ + function fakeInspector({ refuseStarted = false } = {}) { + const callbacks: ((e: unknown) => void)[] = [] + const listeners: ((raw: unknown) => void)[] = [] + const subscribed: string[] = [] + const register = async (cb: (e: unknown) => void) => { + callbacks.push(cb) + } + const inspector = { + beforeRequestSent: register, + responseCompleted: register, + bidi: { + subscribe: async (event: string | string[]) => { + if (refuseStarted && event === 'network.responseStarted') { + throw new Error('unknown event') + } + subscribed.push(...(Array.isArray(event) ? event : [event])) + }, + socket: { + on: (_event: 'message', listener: (raw: unknown) => void) => { + listeners.push(listener) + } + } + } + } + const deliver = (method: string, params: unknown) => { + callbacks.forEach((cb) => cb(params)) + const raw = Buffer.from(JSON.stringify({ method, params })) + listeners.forEach((listener) => listener(raw)) + } + return { inspector, subscribed, deliver } + } + + it('reports a 404 script Chrome stopped loading as 404', async () => { + const { sinks, replacements } = makeSinks() + const { inspector, subscribed, deliver } = fakeInspector() + await attachNetworkInspector({}, async () => inspector, sinks, silentLog) + expect(subscribed).toEqual([ + 'network.responseStarted', + 'network.fetchError' + ]) + deliver('network.responseStarted', scriptNotFound) + deliver('network.beforeRequestSent', scriptRequest) + deliver('network.fetchError', scriptAborted) + expect(replacements.at(-1)?.entry).toMatchObject({ + status: 404, + error: 'net::ERR_ABORTED' + }) + }) + + it('still closes failures as status 0 when responseStarted is refused', async () => { + const warnings: string[] = [] + const { sinks, replacements } = makeSinks() + const { inspector, subscribed, deliver } = fakeInspector({ + refuseStarted: true + }) + const attached = await attachNetworkInspector( + {}, + async () => inspector, + sinks, + (level, message) => level === 'warn' && warnings.push(message) + ) + expect(attached).toBe(true) + expect(subscribed).toEqual(['network.fetchError']) + expect(warnings.join('\n')).toContain('network.responseStarted unavailable') + deliver('network.beforeRequestSent', scriptRequest) + deliver('network.fetchError', scriptAborted) + expect(replacements.at(-1)?.entry).toMatchObject({ + status: 0, + error: 'net::ERR_ABORTED' + }) + }) +}) diff --git a/packages/core/tests/bidi.test.ts b/packages/core/tests/bidi.test.ts index c368683e..c10cf8a2 100644 --- a/packages/core/tests/bidi.test.ts +++ b/packages/core/tests/bidi.test.ts @@ -608,7 +608,10 @@ describe('attachNetworkInspector and the socket it reads failures from', () => { silentLog ) expect(attached).toBe(true) - expect(subscribed).toEqual(['network.fetchError']) + expect(subscribed).toEqual([ + 'network.responseStarted', + 'network.fetchError' + ]) callbacks.request({ request: { request: 'R1', url: 'https://x/beacon', method: 'GET' }, timestamp: 1, @@ -706,7 +709,7 @@ describe('attachNetworkInspector with an inspector that has a fetchError hook', initiator: { type: 'other' } }) - it('subscribes through the hook and reads nothing off the socket', async () => { + it('subscribes failures through the hook, not the socket', async () => { const { sinks, replacements } = makeSinks() const callbacks: Record void> = {} const subscribed: string[] = [] @@ -728,7 +731,7 @@ describe('attachNetworkInspector with an inspector that has a fetchError hook', } } await attachNetworkInspector({}, async () => inspector, sinks, silentLog) - expect(subscribed).toEqual([]) + expect(subscribed).toEqual(['network.responseStarted']) callbacks.request(requestEventFor('R1')) // selenium-webdriver hands every network event to every hook's callback. callbacks.failure(requestEventFor('R1')) diff --git a/packages/selenium-devtools-py/CLAUDE.md b/packages/selenium-devtools-py/CLAUDE.md index f4c21de0..13318795 100644 --- a/packages/selenium-devtools-py/CLAUDE.md +++ b/packages/selenium-devtools-py/CLAUDE.md @@ -35,5 +35,5 @@ Mirrored TypeScript logic and its vectors: `.claude/rules/mirror-vectors.md`. - `packages/selenium-devtools-py/src/selenium_devtools/instrumentation.py` is 1432 lines. The module-level `_state` bag is read by the snapshot capture, its accessors and the element-scripts handoff, so extraction moves state ownership. Per-test frame state already moved to `per_test_capture.py` (`PerTestCapture`); the next change that touches `_state` should split another concern the same way. -- `packages/selenium-devtools-py/src/selenium_devtools/bidi.py` is 855 lines. +- `packages/selenium-devtools-py/src/selenium_devtools/bidi.py` is 913 lines. - `packages/selenium-devtools-py/src/selenium_devtools/pytest_plugin.py` is 899 lines. diff --git a/packages/selenium-devtools-py/changes/bidi-started-response-status.md b/packages/selenium-devtools-py/changes/bidi-started-response-status.md new file mode 100644 index 00000000..de6e5a74 --- /dev/null +++ b/packages/selenium-devtools-py/changes/bidi-started-response-status.md @@ -0,0 +1,5 @@ +--- +patch +--- + +A request the browser answered and then gave up on keeps the status it was answered with. Chrome stops loading a script whose response is a 404 and reports the request as `net::ERR_ABORTED`, so a missing script was listed as status 0 with no response headers. It is now listed as 404 with its response headers, with `net::ERR_ABORTED` as the error. A request that fails before any response, such as a blocked beacon, is still listed as status 0 with the error. diff --git a/packages/selenium-devtools-py/src/selenium_devtools/bidi.py b/packages/selenium-devtools-py/src/selenium_devtools/bidi.py index 1ac55c17..d09a27fd 100644 --- a/packages/selenium-devtools-py/src/selenium_devtools/bidi.py +++ b/packages/selenium-devtools-py/src/selenium_devtools/bidi.py @@ -55,6 +55,8 @@ BIDI_NET_BEFORE_REQUEST, BIDI_NET_FETCH_ERROR, BIDI_NET_RESPONSE_COMPLETED, + BIDI_NET_RESPONSE_STARTED, + BIDI_STARTED_RESPONSE_LIMIT, LOGGER_NAME, PYTHON_MINIMUM_VERSION, SELENIUM_MINIMUM_VERSION, @@ -256,20 +258,42 @@ def response_completed_kwargs( return merged +def response_started_entry(params: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """What ``network.responseStarted`` reported for a hop, kept until a fetch + error closes it: Chrome cancels a script body once its status is an error, + and BiDi then sends ``fetchError``, not ``responseCompleted``. None when the + event carries no status. Mirrors core ``handleBidiResponseStarted``.""" + response = params.get("response") or {} + status = _int_or(response.get("status"), 0) + if not status: + return None + return { + "status": status, + "status_text": response.get("statusText"), + "response_headers": headers_to_object(response.get("headers")), + "mime_type": response.get("mimeType"), + } + + def fetch_error_kwargs( - params: Dict[str, Any], pending: Dict[str, Dict[str, Any]] + params: Dict[str, Any], + pending: Dict[str, Dict[str, Any]], + started: Optional[Dict[str, Dict[str, Any]]] = None, ) -> Optional[Dict[str, Any]]: """kwargs closing a pending request the browser gave up on, as the JS - adapters close theirs: status 0 and the browser's own reason as the error, - so a blocked beacon reads as failed rather than sitting pending for the - rest of the session. + adapters close theirs: the browser's own reason as the error, so a blocked + beacon reads as failed rather than sitting pending for the rest of the + session. A hop whose response had started keeps that response's status and + headers (taken from ``started``); any other closes as status 0. Returns None when the matching request wasn't seen yet. """ request = params.get("request") or {} - prev = pending.get(event_row_id(params)) + row_id = event_row_id(params) + prev = pending.get(row_id) if prev is None: return None + answered = (started if started is not None else {}).pop(row_id, None) start_time = int(prev.get("start_time") or now_ms()) end_time, time = _response_timing( request.get("timings"), start_time, params.get("timestamp") @@ -277,13 +301,19 @@ def fetch_error_kwargs( reason = str(params.get("errorText") or "Failed") merged = dict(prev) merged.update( - status=0, - status_text=reason, + status=answered["status"] if answered else 0, + status_text=(answered and answered["status_text"]) or reason, error=reason, timestamp=now_ms(), end_time=end_time, time=time, ) + if answered: + if answered["response_headers"] is not None: + merged["response_headers"] = answered["response_headers"] + merged["request_type"] = request_type_for( + prev.get("url") or "", answered["mime_type"] + ) return merged @@ -705,11 +735,29 @@ def on_event(event: Any) -> None: on_response_completed = closing_handler( BIDI_NET_RESPONSE_COMPLETED, response_completed_kwargs, [active] ) + started: Dict[str, Dict[str, Any]] = {} + + def on_response_started(event: Any) -> None: + if not active["ok"] or cancelled.is_set(): + return + params = event_params(event) + if _incomplete_event(params, BIDI_NET_RESPONSE_STARTED): + return + with order: + entry = response_started_entry(params) + if entry is None or not event_request_id(params): + return + started[event_row_id(params)] = entry + if len(started) > BIDI_STARTED_RESPONSE_LIMIT: + started.pop(next(iter(started))) + # Subscribed on its own, after the pair: a driver that refuses this one # event should lose only the failure rows, not every network event. failures = {"ok": False} on_fetch_error = closing_handler( - BIDI_NET_FETCH_ERROR, fetch_error_kwargs, [active, failures] + BIDI_NET_FETCH_ERROR, + lambda params, rows: fetch_error_kwargs(params, rows, started), + [active, failures], ) if cancelled.is_set(): @@ -726,6 +774,13 @@ def on_event(event: Any) -> None: if cancelled.is_set(): return False stats["attached"] = attached + if attached and not _subscribe_via_event_manager( + driver, + {BIDI_NET_RESPONSE_STARTED: on_response_started}, + {"ok": False}, + optional=True, + ): + _warn(f"{BIDI_NET_RESPONSE_STARTED} unavailable; a request the browser answers and then cancels reads as status 0") if attached and not _subscribe_via_event_manager( driver, {BIDI_NET_FETCH_ERROR: on_fetch_error}, failures, optional=True ): diff --git a/packages/selenium-devtools-py/src/selenium_devtools/constants.py b/packages/selenium-devtools-py/src/selenium_devtools/constants.py index 333957c7..7ec20463 100644 --- a/packages/selenium-devtools-py/src/selenium_devtools/constants.py +++ b/packages/selenium-devtools-py/src/selenium_devtools/constants.py @@ -218,8 +218,11 @@ BIDI_NET_BEFORE_REQUEST = "network.beforeRequestSent" BIDI_NET_RESPONSE_COMPLETED = "network.responseCompleted" BIDI_NET_FETCH_ERROR = "network.fetchError" +BIDI_NET_RESPONSE_STARTED = "network.responseStarted" # Responses held for a request event not yet delivered; past this the oldest is dropped. BIDI_EARLY_EVENT_LIMIT = 256 +# Started responses kept for a fetch error that may close their hop; past this the oldest is dropped. +BIDI_STARTED_RESPONSE_LIMIT = 256 # The adapter targets the regenerated BiDi layer, which selenium 4.44 shipped — # it is what ``Network.add_event_handler`` and ``EVENT_CONFIGS`` arrived in, and # the pre-4.44 internals network capture used instead were removed in the same diff --git a/packages/selenium-devtools-py/tests/test_bidi.py b/packages/selenium-devtools-py/tests/test_bidi.py index 6b79d282..ebce6c51 100644 --- a/packages/selenium-devtools-py/tests/test_bidi.py +++ b/packages/selenium-devtools-py/tests/test_bidi.py @@ -232,6 +232,38 @@ def test_fetch_error_closes_the_pending_request_as_failed(self): self.assertEqual(failed["time"], 250) self.assertEqual(failed["url"], "https://x/beacon") + def test_fetch_error_keeps_a_started_response_404(self): + pending = {} + req = bidi.request_sent_kwargs( + {"request": {"request": "S1", "url": "https://x/app.v2.js", + "method": "GET"}, "timestamp": 1000} + ) + pending[req["request_id"]] = req + # Chrome 158 sends responseStarted 404, then fetchError, for a 404 script. + started = {"S1": bidi.response_started_entry({ + "request": {"request": "S1"}, + "response": { + "status": 404, "statusText": "Not Found", "mimeType": "text/plain", + "headers": [{"name": "Content-Type", + "value": {"type": "string", "value": "text/plain"}}], + }, + })} + failed = bidi.fetch_error_kwargs( + {"request": {"request": "S1"}, "timestamp": 1010, + "errorText": "net::ERR_ABORTED"}, + pending, started, + ) + self.assertEqual(failed["status"], 404) + self.assertEqual(failed["status_text"], "Not Found") + self.assertEqual(failed["error"], "net::ERR_ABORTED") + self.assertEqual(failed["response_headers"], {"content-type": "text/plain"}) + self.assertEqual(started, {}) + + def test_a_started_response_without_a_status_is_not_kept(self): + self.assertIsNone( + bidi.response_started_entry({"request": {"request": "S1"}, "response": {}}) + ) + def test_fetch_error_none_when_unmatched(self): self.assertIsNone( bidi.fetch_error_kwargs({"request": {"request": "ghost"}}, {}) @@ -691,6 +723,25 @@ def test_a_fetch_error_delivered_before_its_request_is_held_for_it(self): self.assertEqual([f.get("status") for f in frames], [None, 0]) self.assertEqual(frames[1]["error"], "net::ERR_BLOCKED_BY_CLIENT") + def test_a_404_script_the_browser_stopped_loading_reads_as_404(self): + network, capturer = self._attached_capturer() + self._dispatch(network, "network.responseStarted", { + "request": {"request": "S1"}, "timestamp": 1010, + "response": {"status": 404, "statusText": "Not Found", "headers": []}, + }) + self._dispatch(network, "network.beforeRequestSent", { + "request": {"request": "S1", "url": "https://x/app.v2.js", "method": "GET"}, + "timestamp": 1000, + }) + self._dispatch(network, "network.fetchError", { + "request": {"request": "S1"}, "timestamp": 1020, + "errorText": "net::ERR_ABORTED", + }) + + frames = [b[0] for s, b in capturer._tx.sent if s == "networkRequests"] + self.assertEqual([f.get("status") for f in frames], [None, 404]) + self.assertEqual(frames[1]["error"], "net::ERR_ABORTED") + def test_a_held_completion_closes_only_its_own_redirect_hop(self): network, capturer = self._attached_capturer() self._dispatch(network, "network.responseCompleted", { @@ -840,7 +891,11 @@ def failing_subscribe(bidi_event, contexts=None): self.assertTrue(attached) self.assertEqual( sorted(manager.subscribed), - ["network.beforeRequestSent", "network.responseCompleted"], + [ + "network.beforeRequestSent", + "network.responseCompleted", + "network.responseStarted", + ], ) self.assertTrue(any("fetchError" in line for line in logs.output)) self._dispatch(network, "network.beforeRequestSent", { @@ -915,6 +970,7 @@ def test_both_events_are_subscribed_and_counted(self): "network.beforeRequestSent", "network.fetchError", "network.responseCompleted", + "network.responseStarted", ] self.assertEqual(sorted(manager.subscribed), expected) self.assertEqual(sorted(event for event, _ in manager.tracked), expected) diff --git a/packages/selenium-devtools-py/tests/test_mirror_vectors.py b/packages/selenium-devtools-py/tests/test_mirror_vectors.py index 990da9aa..53233660 100644 --- a/packages/selenium-devtools-py/tests/test_mirror_vectors.py +++ b/packages/selenium-devtools-py/tests/test_mirror_vectors.py @@ -19,6 +19,7 @@ from selenium_devtools import ( _contract, + bidi, capture_calls, capture_timing, capturer, @@ -67,6 +68,7 @@ def _vectors_path() -> Path: "typedSecret", "popupBidiHang", "networkRowId", + "failedAfterResponse", } UUID4 = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$") @@ -137,6 +139,32 @@ def test_cases(self): ) +class TestFailedAfterResponse(unittest.TestCase): + def test_cases(self): + for case in _cases("failedAfterResponse"): + with self.subTest(case["name"]): + sent = bidi.request_sent_kwargs({ + "request": {"request": "S1", "url": "https://x/app.v2.js", "method": "GET"}, + "timestamp": 1, + }) + pending = {sent["request_id"]: sent} + started = {} + if case["started"]: + entry = bidi.response_started_entry(case["started"]) + if entry is not None: + started[bidi.event_row_id(case["started"])] = entry + closed = bidi.fetch_error_kwargs(case["failure"], pending, started) + self.assertEqual( + { + "status": closed["status"], + "statusText": closed["status_text"], + "error": closed["error"], + "responseHeaders": closed.get("response_headers"), + }, + case["expect"], + ) + + class TestPopupBidiHang(unittest.TestCase): def test_cases(self): for case in _cases("popupBidiHang"): diff --git a/packages/selenium-devtools/tests/mirror-vectors.test.ts b/packages/selenium-devtools/tests/mirror-vectors.test.ts index 32cc39c1..ad852892 100644 --- a/packages/selenium-devtools/tests/mirror-vectors.test.ts +++ b/packages/selenium-devtools/tests/mirror-vectors.test.ts @@ -9,7 +9,11 @@ import os from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { CaptureTimingRecord, CommandLog } from '@wdio/devtools-shared' +import type { + CaptureTimingRecord, + CommandLog, + NetworkRequest +} from '@wdio/devtools-shared' import { captureMaskPrelude, createSecretRedactor, @@ -31,13 +35,18 @@ import { finalFrameStamp, hasPopupBidiHang, formatCaptureTimingSummary, + handleBidiFetchError, + handleBidiRequestSent, + handleBidiResponseStarted, networkRowId, resolveAdapterOutputDir, resolveRunId, SessionCapturerBase, summarizeCaptureTiming, + type BidiHandlerSinks, type CapturedPerformancePayload, - type CaptureTimingSummary + type CaptureTimingSummary, + type StartedResponse } from '@wdio/devtools-core' import { TestCapture } from '@wdio/devtools-core/test-capture' import { rememberElementLocator } from '../src/helpers/element-locators.js' @@ -103,7 +112,8 @@ const RUNNERS = [ 'secretRedaction', 'typedSecret', 'popupBidiHang', - 'networkRowId' + 'networkRowId', + 'failedAfterResponse' ] it('runs every section the vectors file declares', () => { @@ -184,6 +194,49 @@ describe('nativeSession', () => { } }) +describe('failedAfterResponse', () => { + const request = { + request: { request: 'S1', url: 'https://x/app.v2.js', method: 'GET' }, + timestamp: 1 + } + for (const c of section< + Named & { + started: unknown + failure: unknown + expect: { + status: number + statusText: string + error: string + responseHeaders: Record | null + } + } + >('failedAfterResponse').cases) { + it(c.name, () => { + const closed: NetworkRequest[] = [] + const sinks: BidiHandlerSinks = { + pushConsoleLog: () => {}, + pushNetworkRequest: () => {}, + replaceNetworkRequest: (_id, entry) => closed.push(entry) + } + const rows = new Map() + const started = new Map() + const log = () => {} + if (c.started) { + handleBidiResponseStarted(c.started, started, log) + } + handleBidiRequestSent(request, rows, sinks, log) + handleBidiFetchError(c.failure, rows, sinks, log, started) + const row = closed.at(-1) + expect({ + status: row?.status, + statusText: row?.statusText, + error: row?.error, + responseHeaders: row?.responseHeaders ?? null + }).toEqual(c.expect) + }) + } +}) + describe('networkRowId', () => { for (const c of section< Named & { requestId: string; redirectCount: unknown; expect: string } diff --git a/packages/service/CLAUDE.md b/packages/service/CLAUDE.md index 0e668b6f..91e53650 100644 --- a/packages/service/CLAUDE.md +++ b/packages/service/CLAUDE.md @@ -32,7 +32,7 @@ Accepted residual: a navigation that has not committed when the anchor is read s Caps are eslint `warn`, not a CI gate. - `packages/service/src/index.ts` is over the cap. The command-hook family (`beforeCommand`/`afterCommand`/`#commandStack`/`#drainAfterLiveCommand`) is the next extraction; `before()` is also over the function cap. -- `packages/service/src/session.ts` is over the cap (625 lines by eslint's max-lines, 125 over 500). +- `packages/service/src/session.ts` is over the cap (639 lines by eslint's max-lines, 139 over 500). ## Test coverage gaps diff --git a/packages/service/src/bidi-listeners.ts b/packages/service/src/bidi-listeners.ts index 9ef8f79f..540f598f 100644 --- a/packages/service/src/bidi-listeners.ts +++ b/packages/service/src/bidi-listeners.ts @@ -1,22 +1,25 @@ import logger from '@wdio/logger' +import { errorMessage } from '@wdio/devtools-core' import type { SessionCapturer } from './session.js' const log = logger('@wdio/devtools-service:bidi-listeners') /** * Subscribe a SessionCapturer to the BiDi event stream coming off a - * WebdriverIO browser — network request lifecycle (3 events) + browser + * WebdriverIO browser — network request lifecycle (4 events) + browser * console (`log.entryAdded`). Idempotent only in the sense that the caller * should gate it (e.g. with a one-shot flag); this function will register a * fresh listener on each call. * - * Registration only — WDIO subscribes both the network and log events itself, - * so no session.subscribe is issued here. + * WDIO subscribes the log events and every network event but + * `network.responseStarted` itself (only `browser.mock()` adds that one), so + * that one is subscribed here. Without it a request the browser answers and + * then cancels, such as a 404 script, closes as status 0. */ -export function attachBidiListeners( +export async function attachBidiListeners( browser: WebdriverIO.Browser, capturer: SessionCapturer -): void { +): Promise { log.info('Setting up BiDi network event listeners...') // WDIO's BiDi event types are a broader union than our handlers' @@ -34,6 +37,9 @@ export function attachBidiListeners( browser.on('network.beforeRequestSent', (event) => { capturer.handleNetworkRequestStarted(event as unknown as BidiRequestSent) }) + browser.on('network.responseStarted', (event) => { + capturer.handleNetworkResponseStarted(event) + }) browser.on('network.responseCompleted', (event) => { capturer.handleNetworkResponseCompleted( event as unknown as BidiResponseCompleted @@ -46,5 +52,13 @@ export function attachBidiListeners( capturer.handleLogEntryAdded(event as unknown as BidiLogEntry) }) + try { + await browser.sessionSubscribe({ events: ['network.responseStarted'] }) + } catch (err) { + log.warn( + `BiDi network.responseStarted unavailable; a request the browser answers and then cancels reads as status 0: ${errorMessage(err)}` + ) + } + log.info('✓ BiDi network + log event listeners registered') } diff --git a/packages/service/src/index.ts b/packages/service/src/index.ts index 6cee047e..d25b9043 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -327,10 +327,10 @@ export default class DevToolsHookService implements Services.ServiceInstance { } } - // WDIO has already subscribed the BiDi events by now, so attaching here - // issues no mid-run protocol traffic and misses no early events. + // WDIO has already subscribed most BiDi events by now; attaching here, + // before any test command, misses no early events. if (browser.isBidi && observesPage(this.#options.mode)) { - attachBidiListeners(browser, this.#sessionCapturer) + await attachBidiListeners(browser, this.#sessionCapturer) } await this.#screencast.start(browser) diff --git a/packages/service/src/session.ts b/packages/service/src/session.ts index 0d894444..a9254923 100644 --- a/packages/service/src/session.ts +++ b/packages/service/src/session.ts @@ -25,8 +25,10 @@ import { collectorDrainExpression, drainCollectorWithRecovery, errorMessage, + failedRowFields, foldedStartTime, getRequestType, + handleBidiResponseStarted, isSessionGoneError, loadCollectorSource, loadInjectableScript, @@ -35,7 +37,8 @@ import { rememberReadValue, RetryTracker, SessionCapturerBase, - type SessionCapturerOptions + type SessionCapturerOptions, + type StartedResponse } from '@wdio/devtools-core' import { startsBackend } from '@wdio/devtools-shared' import type { DevToolsMode, TraceMutation } from '@wdio/devtools-shared' @@ -104,6 +107,7 @@ export class SessionCapturer extends SessionCapturerBase { requestHeaders?: Record } >() + #startedResponses = new Map() constructor(devtoolsOptions: SessionCapturerOptions = {}) { super(devtoolsOptions) @@ -796,25 +800,32 @@ export class SessionCapturer extends SessionCapturerBase { } } + handleNetworkResponseStarted(event: unknown) { + handleBidiResponseStarted(event, this.#startedResponses, (level, message) => + log[level](message) + ) + } + handleNetworkFetchError(event: { request: { request: string } redirectCount?: number errorText?: string }) { const requestId = event.request.request + const rowId = networkRowId(requestId, event.redirectCount) + const answered = this.#startedResponses.get(rowId) + this.#startedResponses.delete(rowId) const pending = this.#pendingNetworkRequests.get(requestId) if (pending) { - // Emit a HAR resource-snapshot with status 0 and failure text so the - // trace viewer shows the failed request rather than silently dropping it. + // Closed rather than dropped, so the trace viewer shows the failed request. this.#pendingNetworkRequests.delete(requestId) const endTime = performance.now() const networkRequest: NetworkRequest = { - id: `${Date.now()}-${networkRowId(requestId, event.redirectCount)}`, + id: `${Date.now()}-${rowId}`, url: pending.url, method: pending.method, - status: 0, - statusText: event.errorText ?? 'Failed', type: 'other', + ...failedRowFields(pending.url, event.errorText ?? 'Failed', answered), timestamp: pending.timestamp, startTime: pending.startTime, wallTime: pending.timestamp, diff --git a/packages/service/tests/bidi-listeners.test.ts b/packages/service/tests/bidi-listeners.test.ts new file mode 100644 index 00000000..cf1cd7ca --- /dev/null +++ b/packages/service/tests/bidi-listeners.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, vi } from 'vitest' +import { attachBidiListeners } from '../src/bidi-listeners.js' +import type { SessionCapturer } from '../src/session.js' + +function fakeBrowser(subscribe: () => Promise) { + const listeners = new Map void>() + const browser = { + on: vi.fn((name: string, listener: (event: unknown) => void) => { + listeners.set(name, listener) + }), + sessionSubscribe: vi.fn(subscribe) + } + return { browser: browser as unknown as WebdriverIO.Browser, listeners } +} + +function fakeCapturer() { + return { + handleNetworkRequestStarted: vi.fn(), + handleNetworkResponseStarted: vi.fn(), + handleNetworkResponseCompleted: vi.fn(), + handleNetworkFetchError: vi.fn(), + handleLogEntryAdded: vi.fn() + } as unknown as SessionCapturer +} + +describe('attachBidiListeners', () => { + it('subscribes network.responseStarted, which WDIO leaves unsubscribed', async () => { + const { browser, listeners } = fakeBrowser(async () => {}) + const capturer = fakeCapturer() + await attachBidiListeners(browser, capturer) + expect(browser.sessionSubscribe).toHaveBeenCalledWith({ + events: ['network.responseStarted'] + }) + listeners.get('network.responseStarted')?.({ request: { request: 'S1' } }) + expect(capturer.handleNetworkResponseStarted).toHaveBeenCalledWith({ + request: { request: 'S1' } + }) + }) + + it('keeps every listener when the browser refuses the subscription', async () => { + const { browser, listeners } = fakeBrowser(async () => { + throw new Error('unknown event') + }) + await expect( + attachBidiListeners(browser, fakeCapturer()) + ).resolves.toBeUndefined() + expect([...listeners.keys()]).toEqual([ + 'network.beforeRequestSent', + 'network.responseStarted', + 'network.responseCompleted', + 'network.fetchError', + 'log.entryAdded' + ]) + }) +}) diff --git a/packages/service/tests/network-started-response.test.ts b/packages/service/tests/network-started-response.test.ts new file mode 100644 index 00000000..033d92e7 --- /dev/null +++ b/packages/service/tests/network-started-response.test.ts @@ -0,0 +1,61 @@ +import { describe, it, expect, vi } from 'vitest' +import { SessionCapturer } from '../src/session.js' + +vi.mock('ws') +vi.mock('node:fs/promises') + +const scriptRequest = { + request: { + request: 'S1', + url: 'https://site.test/app.v2.js', + method: 'GET', + headers: [], + timings: { timeOrigin: 1000 } + } +} +const scriptNotFound = { + request: { request: 'S1', url: 'https://site.test/app.v2.js' }, + timestamp: 2, + response: { + status: 404, + statusText: 'Not Found', + mimeType: 'text/plain', + headers: [ + { name: 'Content-Type', value: { type: 'string', value: 'text/plain' } } + ] + } +} + +describe('SessionCapturer: a request answered and then given up on', () => { + it('records a 404 script Chrome stopped loading as 404', () => { + const capturer = new SessionCapturer() + // Chrome 158 delivered responseStarted before the request's beforeRequestSent. + capturer.handleNetworkResponseStarted(scriptNotFound) + capturer.handleNetworkRequestStarted(scriptRequest as any) + capturer.handleNetworkFetchError({ + request: { request: 'S1' }, + errorText: 'net::ERR_ABORTED' + }) + expect(capturer.networkRequests).toHaveLength(1) + expect(capturer.networkRequests[0]).toMatchObject({ + status: 404, + statusText: 'Not Found', + error: 'net::ERR_ABORTED', + responseHeaders: { 'content-type': 'text/plain' } + }) + }) + + it('records a request blocked before any answer as status 0', () => { + const capturer = new SessionCapturer() + capturer.handleNetworkRequestStarted(scriptRequest as any) + capturer.handleNetworkFetchError({ + request: { request: 'S1' }, + errorText: 'net::ERR_BLOCKED_BY_CLIENT' + }) + expect(capturer.networkRequests[0]).toMatchObject({ + status: 0, + statusText: 'net::ERR_BLOCKED_BY_CLIENT', + type: 'other' + }) + }) +}) diff --git a/packages/shared/mirror-vectors.json b/packages/shared/mirror-vectors.json index 01d10a41..32e02f71 100644 --- a/packages/shared/mirror-vectors.json +++ b/packages/shared/mirror-vectors.json @@ -1741,6 +1741,17 @@ {"name": "a count sent as text reads as the first hop", "requestId": "R1", "redirectCount": "2", "expect": "R1"}, {"name": "a boolean reads as the first hop", "requestId": "R1", "redirectCount": true, "expect": "R1"} ] + }, + "failedAfterResponse": { + "mirrors": {"ts": "core/bidi.ts handleBidiResponseStarted, handleBidiFetchError", "py": "bidi.py response_started_entry, fetch_error_kwargs"}, + "notes": "How a request the browser gave up on closes, given what network.responseStarted reported for its hop. Chrome sends responseStarted 404 and then fetchError net::ERR_ABORTED for a 404 script, so the hop keeps the started status and headers beside the error. A hop with no started response closes as status 0 with the error as its text. Each case's request is S1 for https://x/app.v2.js; started is null when no responseStarted arrived. responseHeaders null means the closed row carries none.", + "cases": [ + {"name": "a 404 script the browser stopped loading", "started": {"request": {"request": "S1"}, "response": {"status": 404, "statusText": "Not Found", "mimeType": "text/plain", "headers": [{"name": "Content-Type", "value": {"type": "string", "value": "text/plain"}}]}}, "failure": {"request": {"request": "S1"}, "errorText": "net::ERR_ABORTED"}, "expect": {"status": 404, "statusText": "Not Found", "error": "net::ERR_ABORTED", "responseHeaders": {"content-type": "text/plain"}}}, + {"name": "a request blocked before any answer", "started": null, "failure": {"request": {"request": "S1"}, "errorText": "net::ERR_BLOCKED_BY_CLIENT"}, "expect": {"status": 0, "statusText": "net::ERR_BLOCKED_BY_CLIENT", "error": "net::ERR_BLOCKED_BY_CLIENT", "responseHeaders": null}}, + {"name": "an answer for another redirect hop does not apply", "started": {"request": {"request": "S1"}, "redirectCount": 1, "response": {"status": 404, "statusText": "Not Found"}}, "failure": {"request": {"request": "S1"}, "errorText": "net::ERR_ABORTED"}, "expect": {"status": 0, "statusText": "net::ERR_ABORTED", "error": "net::ERR_ABORTED", "responseHeaders": null}}, + {"name": "an answer with no status text takes the error as its text", "started": {"request": {"request": "S1"}, "response": {"status": 404}}, "failure": {"request": {"request": "S1"}, "errorText": "net::ERR_ABORTED"}, "expect": {"status": 404, "statusText": "net::ERR_ABORTED", "error": "net::ERR_ABORTED", "responseHeaders": null}}, + {"name": "an answer without a status is not kept", "started": {"request": {"request": "S1"}, "response": {"status": 0, "statusText": ""}}, "failure": {"request": {"request": "S1"}, "errorText": "net::ERR_FAILED"}, "expect": {"status": 0, "statusText": "net::ERR_FAILED", "error": "net::ERR_FAILED", "responseHeaders": null}} + ] } } }