Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/bidi-started-response-status.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 5 additions & 1 deletion .claude/rules/network-capture.md
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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.
Expand All @@ -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.
30 changes: 30 additions & 0 deletions packages/core/src/bidi-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Flatten BiDi's `Array<{name, value:{value|type}}>` header shape to a
* lowercased `Record<string, string>`. Exported so adapter-side helpers can
* reuse it for their own header normalization.
*/
export function arrayHeadersToObject(
headers: unknown
): Record<string, string> | undefined {
if (!Array.isArray(headers)) {
return undefined
}
const out: Record<string, string> = {}
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
}
81 changes: 81 additions & 0 deletions packages/core/src/bidi-started-response.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>
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<string, StartedResponse>,
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<NetworkRequest, 'status' | 'statusText' | 'error' | 'responseHeaders'> &
Partial<Pick<NetworkRequest, 'type'>> {
if (!answered) {
return { status: 0, statusText: errorText, error: errorText }
}
return {
status: answered.status,
statusText: answered.statusText ?? errorText,
error: errorText,
Comment on lines +73 to +75

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Saved traces lose cancellations

Keeping the response status now hides browser cancellations after trace export. networkRequestToHar drops error, and harToNetworkRequest does not restore it. A cancelled 404 script loses its net::ERR_ABORTED reason. A response answered with 200 and then cancelled looks successful and no longer produces an OpenTelemetry request.failed event.

Preserve error through trace export and import, and make the telemetry check honor it.

...(answered.responseHeaders
? { responseHeaders: answered.responseHeaders }
: {}),
type: getRequestType(url, answered.mimeType)
}
}
38 changes: 38 additions & 0 deletions packages/core/src/bidi-timing.ts
Original file line number Diff line number Diff line change
@@ -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) } : {}
}
Loading