fix(browser): retain precise observation termination facts
Distinguish CDP session detachment, observed crashes, and transport loss. Preserve the observed window alongside the original typed coverage-stop failure and unconfirmed cleanup. Validated with 40 focused boundary tests, check:ci, docs:check, and the real Chrome public CLI/MCP verifier on macOS. Browser timing comparison remains incomplete because unchanged-main fixture readiness was intermittent. Fixes #5756
This commit is contained in:
1 parent
d672cc2399
commit
5891bfb302
19 files changed
+414
-73
No files matched your search
@@ -69,7 +69,7 @@ export const observeCdpSession = async (
|
||||
const capture = new TimelineCapture(allowedOrigins, mainFrameId, initialUrl);
|
||||
let removeListener = (): void => {};
|
||||
const removeDisconnectListener = context.connection.onDisconnect(() =>
|
||||
capture.targetTerminated(),
|
||||
capture.transportDisconnected(),
|
||||
);
|
||||
try {
|
||||
await context.connection.send(
|
||||
@@ -236,9 +236,11 @@ class TimelineCapture {
|
||||
this.#lifecycle(params);
|
||||
break;
|
||||
case "Inspector.targetCrashed":
|
||||
case "Target.detachedFromTarget":
|
||||
this.targetTerminated(params);
|
||||
break;
|
||||
case "Target.detachedFromTarget":
|
||||
this.sessionDetached(params);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,6 +308,32 @@ class TimelineCapture {
|
||||
this.end("target_terminated");
|
||||
}
|
||||
|
||||
sessionDetached(params: UnknownRecord = {}): void {
|
||||
if (this.#endReason !== undefined) return;
|
||||
this.#add({
|
||||
type: "session_detached",
|
||||
params,
|
||||
timestamp: null,
|
||||
rawUrl: null,
|
||||
requestId: null,
|
||||
detail: "session_detached",
|
||||
});
|
||||
this.end("session_detached");
|
||||
}
|
||||
|
||||
transportDisconnected(): void {
|
||||
if (this.#endReason !== undefined) return;
|
||||
this.#add({
|
||||
type: "transport_disconnected",
|
||||
params: {},
|
||||
timestamp: null,
|
||||
rawUrl: null,
|
||||
requestId: null,
|
||||
detail: "transport_disconnected",
|
||||
});
|
||||
this.end("transport_disconnected");
|
||||
}
|
||||
|
||||
setFinalUrl(rawUrl: string): void {
|
||||
if (this.#scopeExcluded) return;
|
||||
const destination = scopedUrl(rawUrl, this.allowedOrigins);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { BrowserObservationError } from "../../domain/browserObservationError.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
@@ -37,9 +38,18 @@ export const captureWebExecution = async (
|
||||
sources.check();
|
||||
window.check();
|
||||
if (window.reason !== undefined)
|
||||
throw new BrowserObservationError(session.operation, "target_changed", {
|
||||
detail: `Selected target ${session.target.target_id} ended with ${window.reason} before execution observation could be armed.`,
|
||||
});
|
||||
throw new BrowserObservationError(
|
||||
session.operation,
|
||||
window.reason === "session_detached"
|
||||
? "target_session_detached"
|
||||
: "target_changed",
|
||||
{
|
||||
detail: executionWindowEndDetail(
|
||||
session.target.target_id,
|
||||
window.reason,
|
||||
),
|
||||
},
|
||||
);
|
||||
const waiting = window.start(input.observation_ms);
|
||||
// Cancellation may arrive while asynchronous progress is being delivered.
|
||||
void waiting.catch(() => undefined);
|
||||
@@ -64,7 +74,7 @@ export const captureWebExecution = async (
|
||||
raw = await session.command("Profiler.takePreciseCoverage");
|
||||
}
|
||||
collection.freezeMetadata();
|
||||
await session.command("Profiler.stopPreciseCoverage");
|
||||
await stopPreciseCoverage(session, reason);
|
||||
session.preciseCoverageMayBeActive = false;
|
||||
const requestItems = requests.result();
|
||||
const parsed =
|
||||
@@ -161,3 +171,36 @@ export const captureWebExecution = async (
|
||||
collection.close();
|
||||
}
|
||||
};
|
||||
|
||||
const stopPreciseCoverage = async (
|
||||
session: CdpRuntimeSources["session"],
|
||||
reason: WebExecution["window"]["end_reason"],
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await session.command("Profiler.stopPreciseCoverage");
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
(reason !== "target_terminated" && reason !== "session_detached") ||
|
||||
!(cause instanceof AnalysisError)
|
||||
)
|
||||
throw cause;
|
||||
cause.retainDiagnostics({
|
||||
observed_window: {
|
||||
target_id: session.target.target_id,
|
||||
end_reason: reason,
|
||||
},
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const executionWindowEndDetail = (
|
||||
targetId: string,
|
||||
reason: WebExecution["window"]["end_reason"],
|
||||
): string => {
|
||||
if (reason === "session_detached")
|
||||
return `The debugging session for selected target ${targetId} detached before execution observation could be armed; the target may still exist.`;
|
||||
if (reason === "target_terminated")
|
||||
return `Selected target ${targetId} crashed before execution observation could be armed.`;
|
||||
return `Selected target ${targetId} changed documents before execution observation could be armed.`;
|
||||
};
|
||||
@@ -40,8 +40,8 @@ export class CdpExecutionCollection {
|
||||
}
|
||||
this.window.ingest(event);
|
||||
}),
|
||||
session.transport.connection.onDisconnect(() =>
|
||||
this.window.end("target_terminated"),
|
||||
session.transport.connection.onDisconnect((error) =>
|
||||
this.window.fail(error),
|
||||
),
|
||||
session.transport.connection.onProtocolFailure((error) =>
|
||||
this.window.fail(error),
|
||||
|
||||
@@ -25,10 +25,11 @@ export class CdpExecutionWindow {
|
||||
|
||||
/** Collection ends on a main-document replacement, never follows source URLs into another context. */
|
||||
ingest(event: CdpEvent): void {
|
||||
if (
|
||||
event.method === "Target.detachedFromTarget" ||
|
||||
event.method === "Inspector.targetCrashed"
|
||||
) {
|
||||
if (event.method === "Target.detachedFromTarget") {
|
||||
this.end("session_detached");
|
||||
return;
|
||||
}
|
||||
if (event.method === "Inspector.targetCrashed") {
|
||||
this.end("target_terminated");
|
||||
return;
|
||||
}
|
||||
@@ -101,7 +102,7 @@ export class CdpExecutionWindow {
|
||||
});
|
||||
}
|
||||
|
||||
/** Transport loss ends the window; instrumentation cleanup still requires confirmation. */
|
||||
/** A producer lifecycle fact ends the window; instrumentation cleanup still requires confirmation. */
|
||||
end(reason: EndReason): void {
|
||||
if (this.reason !== undefined || this.#failure !== undefined) return;
|
||||
this.reason = reason;
|
||||
|
||||
@@ -143,17 +143,21 @@ export abstract class AnalysisError extends Error {
|
||||
this.#ownedCleanupResources = [...resources];
|
||||
}
|
||||
|
||||
/** Retain a later lifecycle failure without replacing the original typed error. */
|
||||
/** Retain diagnostic facts without replacing the original typed error. */
|
||||
retainDiagnostics(diagnostics: Readonly<Record<string, JsonValue>>): this {
|
||||
Object.assign(this, {
|
||||
diagnostics: structuredClone({ ...this.diagnostics, ...diagnostics }),
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
retainSecondaryFailure(
|
||||
failure: AnalysisError,
|
||||
diagnostics?: Readonly<Record<string, JsonValue>>,
|
||||
): this {
|
||||
// Secondary resources remain owned by their cleanup lifecycle; preserve
|
||||
// the primary error's live cleanup status and original output.
|
||||
if (diagnostics !== undefined)
|
||||
Object.assign(this, {
|
||||
diagnostics: structuredClone({ ...this.diagnostics, ...diagnostics }),
|
||||
});
|
||||
if (diagnostics !== undefined) this.retainDiagnostics(diagnostics);
|
||||
this.#secondaryFailures.push(failure);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -204,6 +204,7 @@ const browserErrorCategory = (
|
||||
reason === "target_not_allowed" ||
|
||||
reason === "service_worker_blocked" ||
|
||||
reason === "target_changed" ||
|
||||
reason === "target_session_detached" ||
|
||||
reason === "endpoint_unreachable" ||
|
||||
reason === "disconnected"
|
||||
)
|
||||
|
||||
@@ -180,6 +180,7 @@ const BROWSER_ERROR_CODES: Readonly<
|
||||
target_not_allowed: "target_unavailable",
|
||||
service_worker_blocked: "target_unavailable",
|
||||
target_changed: "target_unavailable",
|
||||
target_session_detached: "target_unavailable",
|
||||
protocol_error: "unreadable_output",
|
||||
disconnected: "provider_unavailable",
|
||||
payload_limit: "truncated",
|
||||
|
||||
@@ -51,6 +51,8 @@ const observationFailureMessage = (
|
||||
return `${operation} could not reach the selected loopback debugging endpoint. Verify that the target process is running with debugging enabled and that the endpoint's port matches it, then retry.`;
|
||||
if (reason === "target_not_found")
|
||||
return `${operation} could not find the selected target at the debugging endpoint. Refresh target discovery for that endpoint and retry with a returned target ID.`;
|
||||
if (reason === "target_session_detached")
|
||||
return `${operation} lost its debugging session while the target may still exist. Refresh target discovery and attach to the selected target again.`;
|
||||
if (reason === "service_worker_blocked")
|
||||
return `${operation} refused the selected page because it is controlled by or has a registered service worker while the service-worker policy is block. Set environment.service_workers to allow to permit observation, or remove the service worker registration through the browser.`;
|
||||
if (reason === "disconnected")
|
||||
|
||||
@@ -26,6 +26,7 @@ export type BrowserObservationFailureReason =
|
||||
| "target_not_allowed"
|
||||
| "service_worker_blocked"
|
||||
| "target_changed"
|
||||
| "target_session_detached"
|
||||
| "protocol_error"
|
||||
| "disconnected"
|
||||
| "payload_limit"
|
||||
|
||||
@@ -29,6 +29,8 @@ const timelineEventSchema = z.object({
|
||||
"load_failed",
|
||||
"lifecycle",
|
||||
"target_terminated",
|
||||
"session_detached",
|
||||
"transport_disconnected",
|
||||
]),
|
||||
timestamp: z
|
||||
.number()
|
||||
@@ -63,6 +65,8 @@ export const webObservationSessionSchema = z.object({
|
||||
"window_elapsed",
|
||||
"target_left_scope",
|
||||
"target_terminated",
|
||||
"session_detached",
|
||||
"transport_disconnected",
|
||||
]),
|
||||
}),
|
||||
timeline: z.array(timelineEventSchema),
|
||||
|
||||
@@ -40,6 +40,7 @@ export const webExecutionSchema = z.object({
|
||||
"window_elapsed",
|
||||
"document_changed",
|
||||
"target_terminated",
|
||||
"session_detached",
|
||||
]),
|
||||
producer_started_seconds: z.number().min(0),
|
||||
producer_sampled_seconds: z.number().min(0).nullable(),
|
||||
|
||||
Reference in new issue
Block a user