Skip to content

Chrome DevTools for coding agents

feat: add logpoints built on the DevTools BreakpointManager (#3211)

Johan Gorter0877ee00d2e4
diff --git a/docs/tool-reference.md b/docs/tool-reference.md
index 276a0587..72837b92 100644
--- a/docs/tool-reference.md
+++ b/docs/tool-reference.md
@@ -30,7 +30,7 @@
- **[Network](#network)** (2 tools)
- [`get_network_request`](#get_network_request)
- [`list_network_requests`](#list_network_requests)
-- **[Debugging](#debugging)** (9 tools)
+- **[Debugging](#debugging)** (10 tools)
- [`evaluate_script`](#evaluate_script)
- [`get_console_message`](#get_console_message)
- [`get_css_styles`](#get_css_styles)
@@ -38,6 +38,7 @@
- [`list_console_messages`](#list_console_messages)
- [`screencast_start`](#screencast_start)
- [`screencast_stop`](#screencast_stop)
+ - [`set_logpoints`](#set_logpoints)
- [`take_screenshot`](#take_screenshot)
- [`take_snapshot`](#take_snapshot)
- **[Memory](#memory)** (14 tools)
@@ -478,6 +479,17 @@ Results are paginated (10 rules per page by default); use pageIdx to page throug
---
+### `set_logpoints`
+
+**Description:** Set the complete set of logpoints of the selected page: logpoints not in the list are removed, new ones are added, and an empty list removes all. A logpoint logs expressions to the console every time a line executes, without pausing or changing the source, like logpoints in the DevTools Sources panel. Locations are script URLs or original source files resolved through source maps (not available with --no-source-maps; scripts in workers and out-of-process iframes are not supported). A location in a generated script moves to its original source line when a source map covers it, and locations on the same line become one logpoint with the last expression. Output appears in [`list_console_messages`](#list_console_messages); an expression that throws produces an error message without text. Logpoints survive reloads and navigations until removed or the page is closed. The response lists the resulting logpoints and where they are bound.
+
+**Parameters:**
+
+- **logpoints** (array) **(required)**: Logpoints formatted as <url>:<lineNumber>[:<columnNumber>] <expression>. The url is a script URL or the path of an original source file from a source map, exact or as a path suffix (e.g. "src/app.ts"). Line and column numbers are 1-based in the coordinates of the url; a line without executable code moves to the next possible location. The expression is evaluated like console.log() arguments in the scope of the location, where local variables are accessible by their original names, and runs before the line executes, so a variable declared on that line is not set yet. [`list_console_messages`](#list_console_messages) shows objects as [object Object]: read them with [`get_console_message`](#get_console_message), or log JSON.stringify(value) for plain data. Example: "src/cart.ts:42 'cart total:', cart.total, cart.items.length". Pass an empty array to remove all logpoints.
+- **pageId** (number) **(required)**: Targets a specific page by ID.
+
+---
+
### `take_screenshot`
**Description:** Take a screenshot of the page or element.
diff --git a/skills/chrome-devtools/SKILL.md b/skills/chrome-devtools/SKILL.md
index ab71579f..873949cf 100644
--- a/skills/chrome-devtools/SKILL.md
+++ b/skills/chrome-devtools/SKILL.md
@@ -36,6 +36,7 @@ Note: For `evaluate_script`, `pageId` is required when targeting pages. However,
- **Visual inspection**: `take_screenshot` (when user needs to see visual state)
- **CSS & Styling inspection**: Use `get_css_styles` to inspect matched rules, cascade, and CSS variables. Treat the output as authoritative and complete.
- **Additional details**: Use `evaluate_script` for runtime DOM/JS data not available via `get_css_styles` or `take_snapshot`.
+- **Runtime values**: Use `set_logpoints` to log expressions at script or source-file lines (source maps supported) instead of editing code; read the output with `list_console_messages`.
### Parallel execution
diff --git a/src/LogpointManager.ts b/src/LogpointManager.ts
new file mode 100644
index 00000000..47e5ef21
--- /dev/null
+++ b/src/LogpointManager.ts
@@ -0,0 +1,433 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import {Script} from 'node:vm';
+
+import {
+ type TargetUniverse,
+ waitForSourceMaps,
+} from './devtools/DevtoolsUtils.js';
+import {DevTools} from './third_party/index.js';
+
+export interface LogpointOptions {
+ /**
+ * The URL of a script as served to the browser, or the URL of an original
+ * source file from a source map. Matched exactly or as a path suffix.
+ */
+ url: string;
+ /** 1-based line number in the coordinates of `url`. */
+ lineNumber: number;
+ /** Optional 1-based column number. */
+ columnNumber?: number;
+ /** Logged like the arguments of `console.log()`. */
+ expression: string;
+}
+
+/**
+ * A location in a script as served to the browser, 1-based like the
+ * locations reported by the tools.
+ */
+export interface GeneratedLocation {
+ url: string;
+ lineNumber: number;
+ columnNumber: number;
+}
+
+export interface Logpoint {
+ /**
+ * The full URL of the script or original source the logpoint was set in.
+ * DevTools normalizes locations, so this can be the original source file
+ * of a location that was given in a generated script.
+ */
+ url: string;
+ lineNumber: number;
+ columnNumber?: number;
+ expression: string;
+ /**
+ * Whether `url` is an original source file from a source map rather than
+ * a script as served to the browser.
+ */
+ sourceMapped: boolean;
+ /**
+ * The locations in the scripts served to the browser the logpoint is
+ * currently set at. Empty while no parsed script contains the location,
+ * for example right after a reload before the script was parsed again.
+ */
+ generatedLocations: GeneratedLocation[];
+}
+
+/**
+ * Thrown by {@link LogpointManager.setLogpoints} when some locations could
+ * not be bound. The other logpoints were applied; `logpoints` holds the
+ * resulting state.
+ */
+export class LogpointError extends Error {
+ readonly logpoints: Logpoint[];
+
+ constructor(message: string, logpoints: Logpoint[]) {
+ super(message);
+ this.name = 'LogpointError';
+ this.logpoints = logpoints;
+ }
+}
+
+type Universe = DevTools.Foundation.Universe.Universe;
+type Breakpoint = DevTools.BreakpointManager.Breakpoint;
+type UserCondition = DevTools.BreakpointManager.UserCondition;
+type UISourceCode = DevTools.Workspace.UISourceCode.UISourceCode;
+
+interface ResolvedLogpoint {
+ options: LogpointOptions;
+ uiSourceCode: UISourceCode;
+ key: string;
+}
+
+export const LOGPOINT_FORMAT =
+ '<url>:<lineNumber>[:<columnNumber>] <expression>';
+
+/**
+ * Parses a logpoint given as `<url>:<lineNumber>[:<columnNumber>] <expression>`.
+ * The url may itself contain colons (for example a port), so the location is
+ * the shortest prefix that ends in one or two numbers followed by whitespace.
+ */
+export function parseLogpoint(text: string): LogpointOptions {
+ const match = /^(\S+?):(\d+)(?::(\d+))?\s+(\S.*)$/s.exec(text.trim());
+ if (!match) {
+ throw new Error(
+ `Invalid logpoint "${text}". Expected the format ${LOGPOINT_FORMAT}, for example "src/app.ts:42 'total', cart.total".`,
+ );
+ }
+ const [, url, lineNumber, columnNumber, expression] = match;
+ const logpoint: LogpointOptions = {
+ url,
+ lineNumber: Number(lineNumber),
+ expression,
+ };
+ if (columnNumber !== undefined) {
+ logpoint.columnNumber = Number(columnNumber);
+ }
+ if (logpoint.lineNumber < 1 || logpoint.columnNumber === 0) {
+ throw new Error(
+ `Invalid logpoint "${text}": line and column numbers are 1-based.`,
+ );
+ }
+ return logpoint;
+}
+
+/**
+ * Checks that the expression parses as `console.log()` arguments. V8 is used
+ * for parsing both here and in the browser, so an expression that is rejected
+ * here would also be rejected as a breakpoint condition. The script is only
+ * compiled, never run.
+ */
+export function validateExpression(expression: string): void {
+ try {
+ new Script(`console.log(${expression})`);
+ } catch (error) {
+ throw new Error(
+ `The logpoint expression \`${expression}\` does not compile: ${error instanceof Error ? error.message : String(error)}. Provide the expression like arguments to console.log(...).`,
+ );
+ }
+}
+
+/**
+ * DevTools brands breakpoint conditions nominally; any string is a valid
+ * user condition.
+ */
+function toUserCondition(expression: string): UserCondition;
+function toUserCondition(expression: string): string {
+ return expression;
+}
+
+function isFromSourceMap(uiSourceCode: UISourceCode): boolean {
+ return uiSourceCode.contentType().isFromSourceMap();
+}
+
+function locationKey(
+ url: string,
+ lineNumber: number,
+ columnNumber: number | undefined,
+): string {
+ return `${url}:${lineNumber}${columnNumber === undefined ? '' : `:${columnNumber}`}`;
+}
+
+function baseName(url: string): string {
+ return url.slice(url.lastIndexOf('/') + 1).toLowerCase();
+}
+
+/**
+ * How long to wait for the source maps of the page to load before an original
+ * source URL is reported as unknown. Loads still pending then continue in the
+ * background, so a retry finds the source.
+ */
+const SOURCE_MAP_LOAD_TIMEOUT_MS = 5_000;
+
+/**
+ * Manages logpoints for a single page on top of the `BreakpointManager` of
+ * the page's DevTools universe.
+ *
+ * A logpoint is a DevTools breakpoint with `isLogpoint` set: its condition
+ * logs the expression and never pauses. The breakpoint manager resolves the
+ * location through source maps, substitutes minified variable names in the
+ * expression and keeps the breakpoint bound across reloads and rebuilt
+ * bundles. This class only maps the tool API (URLs and 1-based positions)
+ * onto workspace source codes.
+ */
+export class LogpointManager {
+ readonly #universe: Universe;
+ readonly #target: DevTools.Target;
+ /**
+ * The breakpoints that are logpoints of this page. The breakpoint manager
+ * keeps one `Breakpoint` per normalized location, so two requested
+ * locations can share one entry.
+ */
+ readonly #records = new Set<Breakpoint>();
+
+ constructor(devTools: TargetUniverse) {
+ this.#universe = devTools.universe;
+ this.#target = devTools.target;
+ }
+
+ get #debuggerModel(): DevTools.DebuggerModel {
+ const model = this.#target.model(DevTools.DebuggerModel);
+ if (!model) {
+ throw new Error('The DevTools debugger model is not available.');
+ }
+ return model;
+ }
+
+ /**
+ * Makes the given logpoints the complete set of logpoints on the page:
+ * logpoints not in the list are removed, new ones are added and the
+ * expression of an existing logpoint at the same location is replaced.
+ * Expressions and locations are validated before anything is changed.
+ * Throws a {@link LogpointError} when a location has no executable code;
+ * the other logpoints are applied regardless.
+ */
+ async setLogpoints(desired: LogpointOptions[]): Promise<Logpoint[]> {
+ for (const options of desired) {
+ validateExpression(options.expression);
+ }
+ const resolved = new Map<string, ResolvedLogpoint>();
+ for (const options of desired) {
+ const uiSourceCode = await this.#findUISourceCode(options.url);
+ const key = locationKey(
+ uiSourceCode.url(),
+ options.lineNumber,
+ options.columnNumber,
+ );
+ // The last entry for a location wins, like setting it twice would.
+ resolved.set(key, {options, uiSourceCode, key});
+ }
+
+ const kept = new Set<Breakpoint>();
+ const unbound: string[] = [];
+ for (const {options, uiSourceCode, key} of resolved.values()) {
+ const breakpoint = await this.#universe.breakpointManager.setBreakpoint(
+ uiSourceCode,
+ // The tool API is 1-based like the DevTools UI; the model is 0-based.
+ options.lineNumber - 1,
+ options.columnNumber === undefined
+ ? undefined
+ : options.columnNumber - 1,
+ toUserCondition(options.expression),
+ /* enabled */ true,
+ /* isLogpoint */ true,
+ DevTools.BreakpointManager.BreakpointOrigin.USER_ACTION,
+ );
+ if (!breakpoint) {
+ unbound.push(key);
+ continue;
+ }
+ // Wait for the breakpoint to be set in the backend so that the result
+ // reports whether the location resolved.
+ await breakpoint.updateBreakpoint();
+
+ if (!this.#records.has(breakpoint) && !breakpoint.bound()) {
+ await breakpoint.remove(/* keepInStorage */ false);
+ unbound.push(key);
+ continue;
+ }
+ this.#records.add(breakpoint);
+ kept.add(breakpoint);
+ }
+
+ for (const breakpoint of [...this.#records]) {
+ if (!kept.has(breakpoint)) {
+ this.#records.delete(breakpoint);
+ await breakpoint.remove(/* keepInStorage */ false);
+ }
+ }
+
+ this.#setLazySourceMapLoading(this.#records.size === 0);
+
+ const logpoints = this.#currentLogpoints();
+ if (unbound.length) {
+ throw new LogpointError(
+ `No executable code at ${unbound.join(', ')} (for example a comment, type annotation or empty line, or a line not mapped to the generated script). Pick lines containing executable code. The other logpoints were applied.`,
+ logpoints,
+ );
+ }
+ return logpoints;
+ }
+
+ /**
+ * Releases the records. The breakpoints are not removed from the backend:
+ * the universe is being disposed and its session detaches, which removes
+ * them along with the page.
+ */
+ dispose(): void {
+ this.#records.clear();
+ }
+
+ #currentLogpoints(): Logpoint[] {
+ return [...this.#records].map(breakpoint => this.#snapshot(breakpoint));
+ }
+
+ /**
+ * Reads the current state of a breakpoint, so that the result reflects
+ * the normalized location and the re-binding done by the breakpoint
+ * manager after reloads. The breakpoint manager may have moved a
+ * generated location to its original source, so whether the logpoint is
+ * source-mapped follows from the breakpoint, not from the request.
+ */
+ #snapshot(breakpoint: Breakpoint): Logpoint {
+ const sourceMapped = [...breakpoint.getUiSourceCodes()].some(
+ isFromSourceMap,
+ );
+ const modelBreakpoint = breakpoint.modelBreakpoint(this.#debuggerModel);
+ const generatedLocations: GeneratedLocation[] = [];
+ if (breakpoint.bound()) {
+ for (const position of modelBreakpoint?.currentState ?? []) {
+ generatedLocations.push({
+ url: position.url,
+ lineNumber: position.lineNumber + 1,
+ columnNumber: (position.columnNumber ?? 0) + 1,
+ });
+ }
+ }
+ const columnNumber = breakpoint.columnNumber();
+ return {
+ url: breakpoint.url(),
+ lineNumber: breakpoint.lineNumber() + 1,
+ columnNumber: columnNumber === undefined ? undefined : columnNumber + 1,
+ expression: breakpoint.condition(),
+ sourceMapped,
+ generatedLocations,
+ };
+ }
+
+ /**
+ * Source maps load lazily by default, so after a reload the original
+ * sources of a rebuilt bundle would not re-appear in the workspace and a
+ * logpoint on an original source file could not be re-bound to the new
+ * generated location. While logpoints exist, source maps are loaded
+ * eagerly instead, like DevTools does with the Sources panel open.
+ */
+ #setLazySourceMapLoading(lazy: boolean): void {
+ this.#universe.settings
+ .resolve(DevTools.SourceMapManager.lazyLoadingSettingDescriptor)
+ .set(lazy);
+ }
+
+ /**
+ * Finds the workspace source code for a script or original source URL,
+ * loading source maps if needed. Throws a descriptive error, including
+ * sources with the same file name, when nothing matches.
+ */
+ async #findUISourceCode(url: string): Promise<UISourceCode> {
+ // Source maps are loaded lazily in the DevTools universe and original
+ // sources only appear in the workspace once their source map has loaded.
+ let match = this.#matchUISourceCode(url);
+ let timedOut = false;
+ if (match && !isFromSourceMap(match)) {
+ // The script may be a transpiled file served at the URL of its original
+ // source (see #matchUISourceCode); its source map decides.
+ const matchedUrl = match.url();
+ const scripts = this.#debuggerModel
+ .scripts()
+ .filter(script => script.sourceURL === matchedUrl);
+ if (scripts.some(script => script.sourceMapURL)) {
+ const signal = AbortSignal.timeout(SOURCE_MAP_LOAD_TIMEOUT_MS);
+ await waitForSourceMaps(this.#debuggerModel, scripts, signal);
+ match = this.#matchUISourceCode(url);
+ if (signal.aborted && (!match || !isFromSourceMap(match))) {
+ // Setting the logpoint on the served script would use its line
+ // numbers instead of those of the original source.
+ throw new Error(
+ `The source map of ${matchedUrl} was still loading after ${SOURCE_MAP_LOAD_TIMEOUT_MS / 1000} seconds; retry.`,
+ );
+ }
+ }
+ } else if (!match) {
+ const signal = AbortSignal.timeout(SOURCE_MAP_LOAD_TIMEOUT_MS);
+ await waitForSourceMaps(
+ this.#debuggerModel,
+ this.#debuggerModel.scripts(),
+ signal,
+ );
+ timedOut = signal.aborted;
+ match = this.#matchUISourceCode(url);
+ }
+ if (match) {
+ return match;
+ }
+ const name = baseName(url);
+ const similar = [...this.#pageSourceCodes()]
+ .map(uiSourceCode => uiSourceCode.url())
+ .filter(candidate => baseName(candidate) === name)
+ .slice(0, 5);
+ throw new Error(
+ `No parsed script or original source file matches "${url}". The url must match the URL of a script as served to the browser or an original source file from a source map, exactly or as a path suffix.${timedOut ? ` Some source maps were still loading after ${SOURCE_MAP_LOAD_TIMEOUT_MS / 1000} seconds; retry if the file comes from a source map.` : ''}${similar.length ? ` Sources with the same file name: ${similar.join(', ')}.` : ''}`,
+ );
+ }
+
+ /** The scripts and source-map sources of the page in the workspace. */
+ *#pageSourceCodes(): Iterable<UISourceCode> {
+ for (const uiSourceCode of this.#universe.workspace.uiSourceCodes()) {
+ const projectType = uiSourceCode.project().type();
+ // Content scripts of extensions are left out: they are not part of the
+ // page under development and would make path-suffix matches ambiguous.
+ if (projectType === DevTools.Workspace.Workspace.projectTypes.Network) {
+ yield uiSourceCode;
+ }
+ }
+ }
+
+ /**
+ * Finds the workspace source code for a script or original source URL.
+ * An exact URL match wins; otherwise the URL is matched as a path suffix so
+ * that users can pass "src/app.ts" without knowing the bundler's URL
+ * scheme. An ambiguous suffix match is reported as an error.
+ */
+ #matchUISourceCode(url: string): UISourceCode | null {
+ const candidates = new Map<string, UISourceCode>();
+ for (const uiSourceCode of this.#pageSourceCodes()) {
+ const candidateUrl = uiSourceCode.url();
+ if (candidateUrl !== url && !candidateUrl.endsWith('/' + url)) {
+ continue;
+ }
+ // Dev servers like Vite serve a transpiled file at the URL of its
+ // original source, with a source map pointing back at that same URL.
+ // The original source then has the line numbers of the file on disk,
+ // so it wins over the script served at the same URL.
+ const existing = candidates.get(candidateUrl);
+ if (!existing || isFromSourceMap(uiSourceCode)) {
+ candidates.set(candidateUrl, uiSourceCode);
+ }
+ }
+ const exact = candidates.get(url);
+ if (exact) {
+ return exact;
+ }
+ if (candidates.size > 1) {
+ throw new Error(
+ `"${url}" matches multiple sources: ${[...candidates.keys()].join(', ')}. Specify a longer path.`,
+ );
+ }
+ return candidates.values().next().value ?? null;
+ }
+}
diff --git a/src/McpPage.ts b/src/McpPage.ts
index 0e1cabde..b40eab91 100644
--- a/src/McpPage.ts
+++ b/src/McpPage.ts
@@ -16,6 +16,8 @@ import {
type ListenerMap,
type UncaughtError,
} from './collectors/PageCollector.js';
+import type {Logpoint, LogpointOptions} from './LogpointManager.js';
+import {LogpointManager} from './LogpointManager.js';
import {TextSnapshot} from './TextSnapshot.js';
import {
type Locator,
@@ -204,6 +206,9 @@ export class McpPage implements ContextPage {
#webAuthnEnabled = false;
#webAuthnAuthenticator?: WebAuthnAuthenticator;
+ // Logpoints, created on first use.
+ #logpointManager?: LogpointManager;
+
// Dialog
#dialog?: Dialog;
#dialogHandler: (dialog: Dialog) => void;
@@ -431,6 +436,27 @@ export class McpPage implements ContextPage {
return this.#devtoolsUniverse;
}
+ /**
+ * Makes the given logpoints the complete set of logpoints on the page, see
+ * {@link LogpointManager.setLogpoints}. The manager is created on first
+ * use, so an empty list on a page without logpoints is a no-op.
+ */
+ setLogpoints(logpoints: LogpointOptions[]): Promise<Logpoint[]> {
+ if (!this.#logpointManager) {
+ if (logpoints.length === 0) {
+ return Promise.resolve([]);
+ }
+ const devtoolsUniverse = this.devtoolsUniverse;
+ if (!devtoolsUniverse) {
+ throw new Error(
+ `DevTools universe is not available for page ${this.id ?? '?'}.`,
+ );
+ }
+ this.#logpointManager = new LogpointManager(devtoolsUniverse);
+ }
+ return this.#logpointManager.setLogpoints(logpoints);
+ }
+
getWebAuthnAuthenticator():
Omit<WebAuthnAuthenticatorState, 'credentials'> | undefined {
return (
@@ -885,6 +911,8 @@ export class McpPage implements ContextPage {
this.#pptrPage?.off('dialog', this.#dialogHandler);
this.#networkCollector?.dispose();
this.#consoleCollector?.dispose();
+ this.#logpointManager?.dispose();
+ this.#logpointManager = undefined;
const devtoolsUniverse = this.#devtoolsUniverse;
this.#devtoolsUniverse = undefined;
this.#webAuthnAuthenticator = undefined;
diff --git a/src/config/cli-options.ts b/src/config/cli-options.ts
index ecf71112..dfd98861 100644
--- a/src/config/cli-options.ts
+++ b/src/config/cli-options.ts
@@ -1898,6 +1898,28 @@ export const commands: Commands = {
},
},
},
+ set_logpoints: {
+ description:
+ 'Set the complete set of logpoints of the selected page: logpoints not in the list are removed, new ones are added, and an empty list removes all. A logpoint logs expressions to the console every time a line executes, without pausing or changing the source, like logpoints in the DevTools Sources panel. Locations are script URLs or original source files resolved through source maps (not available with --no-source-maps; scripts in workers and out-of-process iframes are not supported). A location in a generated script moves to its original source line when a source map covers it, and locations on the same line become one logpoint with the last expression. Output appears in list_console_messages; an expression that throws produces an error message without text. Logpoints survive reloads and navigations until removed or the page is closed. The response lists the resulting logpoints and where they are bound.',
+ category: 'Debugging',
+ args: {
+ pageId: {
+ name: 'pageId',
+ type: 'number',
+ description: 'Targets a specific page by ID.',
+ required: true,
+ positional: true,
+ },
+ logpoints: {
+ name: 'logpoints',
+ type: 'array',
+ description:
+ 'Logpoints formatted as <url>:<lineNumber>[:<columnNumber>] <expression>. The url is a script URL or the path of an original source file from a source map, exact or as a path suffix (e.g. "src/app.ts"). Line and column numbers are 1-based in the coordinates of the url; a line without executable code moves to the next possible location. The expression is evaluated like console.log() arguments in the scope of the location, where local variables are accessible by their original names, and runs before the line executes, so a variable declared on that line is not set yet. list_console_messages shows objects as [object Object]: read them with get_console_message, or log JSON.stringify(value) for plain data. Example: "src/cart.ts:42 \'cart total:\', cart.total, cart.items.length". Pass an empty array to remove all logpoints.',
+ required: true,
+ positional: true,
+ },
+ },
+ },
take_heapsnapshot: {
description:
'Capture a heap snapshot of the target page. Use to analyze the memory distribution of JavaScript objects and debug memory leaks.',
diff --git a/src/devtools/DevtoolsUtils.ts b/src/devtools/DevtoolsUtils.ts
index cd88c6e3..a09f0eec 100644
--- a/src/devtools/DevtoolsUtils.ts
+++ b/src/devtools/DevtoolsUtils.ts
@@ -532,15 +532,10 @@ export async function createStackTrace(
}
const signal = AbortSignal.timeout(1_000);
- await Promise.all(
- [...scriptIds].map(id =>
- waitForScript(model, id, signal)
- .then(script =>
- model.sourceMapManager().sourceMapForClientPromise(script),
- )
- .catch(),
- ),
+ const scripts = await Promise.all(
+ [...scriptIds].map(id => waitForScript(model, id, signal)),
);
+ await waitForSourceMaps(model, scripts, signal);
const binding = devTools.universe.context.get(
DevTools.DebuggerWorkspaceBinding,
@@ -554,12 +549,49 @@ export async function createStackTrace(
);
}
+/**
+ * Waits for the source maps of `scripts` to load, so that their original
+ * sources are in the workspace. Scripts without a source map are skipped.
+ * Non-trivial pages have hundreds of source maps, so the wait ends when
+ * `signal` aborts; loads still pending then continue in the background and
+ * resolve later.
+ */
+export async function waitForSourceMaps(
+ model: DevTools.DebuggerModel,
+ scripts: Iterable<DevToolsScript>,
+ signal: AbortSignal,
+): Promise<void> {
+ const manager = model.sourceMapManager();
+ const aborted = new Promise<void>(resolve => {
+ if (signal.aborted) {
+ resolve();
+ return;
+ }
+ signal.addEventListener('abort', () => resolve(), {once: true});
+ });
+ await Promise.all(
+ [...scripts].map(script => {
+ if (!script.sourceMapURL) {
+ return undefined;
+ }
+ return Promise.race([
+ manager.sourceMapForClientPromise(script).then(() => undefined),
+ aborted,
+ ]);
+ }),
+ );
+}
+
+type DevToolsScript = NonNullable<
+ ReturnType<DevTools.DebuggerModel['scriptForId']>
+>;
+
// Waits indefinitely for the script so pair it with Promise.race.
async function waitForScript(
model: DevTools.DebuggerModel,
scriptId: string,
signal: AbortSignal,
-): Promise<NonNullable<ReturnType<DevTools.DebuggerModel['scriptForId']>>> {
+): Promise<DevToolsScript> {
while (true) {
if (signal.aborted) {
throw signal.reason;
diff --git a/src/formatters/LogpointFormatter.ts b/src/formatters/LogpointFormatter.ts
new file mode 100644
index 00000000..b0da32a4
--- /dev/null
+++ b/src/formatters/LogpointFormatter.ts
@@ -0,0 +1,89 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import type {GeneratedLocation, Logpoint} from '../LogpointManager.js';
+
+export interface StructuredLogpoint {
+ url: string;
+ lineNumber: number;
+ columnNumber?: number;
+ expression: string;
+ sourceMapped: boolean;
+ generatedLocations: GeneratedLocation[];
+}
+
+function formatLocation(
+ url: string,
+ lineNumber: number,
+ columnNumber?: number,
+): string {
+ return `${url}:${lineNumber}${columnNumber === undefined ? '' : `:${columnNumber}`}`;
+}
+
+function formatLogpoint(logpoint: StructuredLogpoint): string {
+ const location = formatLocation(
+ logpoint.url,
+ logpoint.lineNumber,
+ logpoint.columnNumber,
+ );
+ let status: string;
+ if (logpoint.generatedLocations.length === 0) {
+ status = 'not bound (no parsed script contains the location)';
+ } else if (logpoint.sourceMapped) {
+ status = `bound via source map at ${logpoint.generatedLocations
+ .map(generated => {
+ return formatLocation(
+ generated.url,
+ generated.lineNumber,
+ generated.columnNumber,
+ );
+ })
+ .join(', ')}`;
+ } else {
+ status = 'bound';
+ }
+ return `- ${location} logging \`${logpoint.expression}\` [${status}]`;
+}
+
+function formatLogpoints(logpoints: readonly StructuredLogpoint[]): string {
+ if (logpoints.length === 0) {
+ return 'No logpoints are set on the page.';
+ }
+ const lines = [`${logpoints.length} logpoint(s) set on the page:`];
+ for (const logpoint of logpoints) {
+ lines.push(formatLogpoint(logpoint));
+ }
+ return lines.join('\n');
+}
+
+export class LogpointFormatter {
+ readonly #logpoints: readonly StructuredLogpoint[];
+
+ constructor(logpoints: readonly Logpoint[]) {
+ this.#logpoints = logpoints.map(logpoint => {
+ return {
+ url: logpoint.url,
+ lineNumber: logpoint.lineNumber,
+ ...(logpoint.columnNumber === undefined
+ ? {}
+ : {columnNumber: logpoint.columnNumber}),
+ expression: logpoint.expression,
+ sourceMapped: logpoint.sourceMapped,
+ generatedLocations: logpoint.generatedLocations.map(generated => {
+ return {...generated};
+ }),
+ };
+ });
+ }
+
+ toJSON(): StructuredLogpoint[] {
+ return [...this.#logpoints];
+ }
+
+ toString(): string {
+ return formatLogpoints(this.toJSON());
+ }
+}
diff --git a/src/telemetry/tool_call_metrics.json b/src/telemetry/tool_call_metrics.json
index 7a936753..4cb14248 100644
--- a/src/telemetry/tool_call_metrics.json
+++ b/src/telemetry/tool_call_metrics.json
@@ -1396,5 +1396,18 @@
"argType": "boolean"
}
]
+ },
+ {
+ "name": "set_logpoints",
+ "args": [
+ {
+ "name": "page_id",
+ "argType": "number"
+ },
+ {
+ "name": "logpoints_count",
+ "argType": "number"
+ }
+ ]
}
]
diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.ts
index a5f74ecf..85286788 100644
--- a/src/tools/ToolDefinition.ts
+++ b/src/tools/ToolDefinition.ts
@@ -15,6 +15,7 @@ import type {
HeapQueryOptions,
} from '../processors/HeapSnapshotManager.js';
import type {McpPage} from '../McpPage.js';
+import type {Logpoint, LogpointOptions} from '../LogpointManager.js';
import type {DevToolsCommentBridge} from '../devtools/DevToolsCommentBridge.js';
import type {CssFormatterOptions} from '../formatters/CssFormatter.js';
import type {
@@ -524,6 +525,7 @@ export type ContextPage = Readonly<{
getDialog(): Dialog | undefined;
clearDialog(): void;
throwIfDialogOpen(): void;
+ setLogpoints(logpoints: LogpointOptions[]): Promise<Logpoint[]>;
isClosed(): boolean;
getScreenRecorder(): ScreenRecorderData | null;
setScreenRecorder(data: ScreenRecorderData | null): void;
diff --git a/src/tools/console.ts b/src/tools/console.ts
index 3239f27b..ef1488cb 100644
--- a/src/tools/console.ts
+++ b/src/tools/console.ts
@@ -9,6 +9,10 @@ import {zod, type ConsoleMessageType} from '../third_party/index.js';
import {ToolCategory} from './categories.js';
import {definePageTool, type PageToolFactory} from './ToolDefinition.js';
+import {
+ GET_CONSOLE_MESSAGE_TOOL_NAME,
+ LIST_CONSOLE_MESSAGES_TOOL_NAME,
+} from './toolNames.js';
type ConsoleResponseType = ConsoleMessageType | 'issue';
const FILTERABLE_MESSAGE_TYPES: [
@@ -37,8 +41,6 @@ const FILTERABLE_MESSAGE_TYPES: [
'issue',
];
-const LIST_CONSOLE_MESSAGES_TOOL_NAME = 'list_console_messages';
-
export const listConsoleMessages: PageToolFactory = definePageTool(
(cliArgs: ParsedArguments) => {
return {
@@ -110,7 +112,7 @@ export const listConsoleMessages: PageToolFactory = definePageTool(
);
export const getConsoleMessage: PageToolFactory = definePageTool(() => ({
- name: 'get_console_message',
+ name: GET_CONSOLE_MESSAGE_TOOL_NAME,
description: `Gets a console message by its ID. You can get all messages by calling ${LIST_CONSOLE_MESSAGES_TOOL_NAME}.`,
annotations: {
category: ToolCategory.DEBUGGING,
diff --git a/src/tools/logpoints.ts b/src/tools/logpoints.ts
new file mode 100644
index 00000000..4e03c829
--- /dev/null
+++ b/src/tools/logpoints.ts
@@ -0,0 +1,69 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import {LogpointFormatter} from '../formatters/LogpointFormatter.js';
+import {
+ LOGPOINT_FORMAT,
+ LogpointError,
+ parseLogpoint,
+} from '../LogpointManager.js';
+import {zod} from '../third_party/index.js';
+
+import {ToolCategory} from './categories.js';
+import {definePageTool, type PageToolFactory} from './ToolDefinition.js';
+import {
+ GET_CONSOLE_MESSAGE_TOOL_NAME,
+ LIST_CONSOLE_MESSAGES_TOOL_NAME,
+} from './toolNames.js';
+
+const SET_LOGPOINTS_TOOL_NAME = 'set_logpoints';
+
+export const setLogpoints: PageToolFactory = definePageTool(() => ({
+ name: SET_LOGPOINTS_TOOL_NAME,
+ description: `Set the complete set of logpoints of the selected page: logpoints not in the list are removed, new ones are added, and an empty list removes all. A logpoint logs expressions to the console every time a line executes, without pausing or changing the source, like logpoints in the DevTools Sources panel. Locations are script URLs or original source files resolved through source maps (not available with --no-source-maps; scripts in workers and out-of-process iframes are not supported). A location in a generated script moves to its original source line when a source map covers it, and locations on the same line become one logpoint with the last expression. Output appears in ${LIST_CONSOLE_MESSAGES_TOOL_NAME}; an expression that throws produces an error message without text. Logpoints survive reloads and navigations until removed or the page is closed. The response lists the resulting logpoints and where they are bound.`,
+ annotations: {
+ category: ToolCategory.DEBUGGING,
+ readOnlyHint: false,
+ },
+ schema: {
+ logpoints: zod
+ .array(zod.string())
+ .describe(
+ `Logpoints formatted as ${LOGPOINT_FORMAT}. The url is a script URL or the path of an original source file from a source map, exact or as a path suffix (e.g. "src/app.ts"). Line and column numbers are 1-based in the coordinates of the url; a line without executable code moves to the next possible location. The expression is evaluated like console.log() arguments in the scope of the location, where local variables are accessible by their original names, and runs before the line executes, so a variable declared on that line is not set yet. ${LIST_CONSOLE_MESSAGES_TOOL_NAME} shows objects as [object Object]: read them with ${GET_CONSOLE_MESSAGE_TOOL_NAME}, or log JSON.stringify(value) for plain data. Example: "src/cart.ts:42 'cart total:', cart.total, cart.items.length". Pass an empty array to remove all logpoints.`,
+ ),
+ },
+ blockedByDialog: false,
+ concurrency: 'page',
+ verifyFilesSchema: {},
+ handler: async (request, response) => {
+ let logpoints;
+ try {
+ logpoints = await request.page.setLogpoints(
+ request.params.logpoints.map(parseLogpoint),
+ );
+ } catch (error) {
+ if (error instanceof LogpointError) {
+ // The other logpoints were applied; report the resulting state.
+ response.appendResponseLine(
+ new LogpointFormatter(error.logpoints).toString(),
+ );
+ }
+ throw error;
+ }
+ response.appendResponseLine(new LogpointFormatter(logpoints).toString());
+ if (logpoints.length === 0) {
+ return;
+ }
+ if (logpoints.some(logpoint => logpoint.sourceMapped)) {
+ response.appendResponseLine(
+ 'Source-mapped locations are re-resolved automatically when a matching source map loads again (for example after a reload with a regenerated bundle). Note: on the first page load after a rebuild, code that runs during the load itself is not logged yet; if a load-time logpoint stays silent right after a rebuild, reload once more before concluding that the line does not run.',
+ );
+ }
+ response.appendResponseLine(
+ `Logged output appears in ${LIST_CONSOLE_MESSAGES_TOOL_NAME} once a line executes; objects show as [object Object] there, ${GET_CONSOLE_MESSAGE_TOOL_NAME} shows them as JSON.`,
+ );
+ },
+}));
diff --git a/src/tools/toolNames.ts b/src/tools/toolNames.ts
new file mode 100644
index 00000000..5e2cc443
--- /dev/null
+++ b/src/tools/toolNames.ts
@@ -0,0 +1,10 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+// Tool names referenced from other tools' descriptions. Kept out of the tool
+// modules because `createTools()` instantiates every export of those.
+export const LIST_CONSOLE_MESSAGES_TOOL_NAME = 'list_console_messages';
+export const GET_CONSOLE_MESSAGE_TOOL_NAME = 'get_console_message';
diff --git a/src/tools/tools.ts b/src/tools/tools.ts
index 9bd86ee9..5885433c 100644
--- a/src/tools/tools.ts
+++ b/src/tools/tools.ts
@@ -14,6 +14,7 @@ import * as emulationTools from './emulation.js';
import * as extensionTools from './extensions.js';
import * as inputTools from './input.js';
import * as lighthouseTools from './lighthouse.js';
+import * as logpointTools from './logpoints.js';
import * as memoryTools from './memory.js';
import * as networkTools from './network.js';
import * as pagesTools from './pages.js';
@@ -38,6 +39,7 @@ export const createTools = (args: ParsedArguments): AnyToolDefinition[] => {
...Object.values(extensionTools),
...Object.values(inputTools),
...Object.values(lighthouseTools),
+ ...Object.values(logpointTools),
...Object.values(memoryTools),
...Object.values(networkTools),
...Object.values(pagesTools),
diff --git a/tests/LogpointManager.test.ts b/tests/LogpointManager.test.ts
new file mode 100644
index 00000000..c03299c4
--- /dev/null
+++ b/tests/LogpointManager.test.ts
@@ -0,0 +1,672 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import assert from 'node:assert';
+import type {IncomingMessage, ServerResponse} from 'node:http';
+import {describe, it} from 'node:test';
+
+import ts from 'typescript';
+
+import type {Logpoint, LogpointOptions} from '../src/LogpointManager.js';
+import {
+ LogpointError,
+ parseLogpoint,
+ validateExpression,
+} from '../src/LogpointManager.js';
+import type {McpPage} from '../src/McpPage.js';
+import {serverHooks} from './server.js';
+import {html, waitExecutionFor, withMcpContext} from './utils.js';
+
+const APP_SCRIPT = `function greet(name) {
+ const message = 'Hello, ' + name;
+ return message;
+}
+function withDebuggerStatement() {
+ debugger;
+ return 42;
+}
+`;
+
+function serveAppScript(req: IncomingMessage, res: ServerResponse) {
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
+ res.statusCode = 200;
+ res.end(APP_SCRIPT);
+}
+
+// A "bundle" transpiled from TypeScript with a real source map, like a
+// bundler would produce. Line 2 of the TypeScript source is the logpoint
+// target used in tests.
+const TS_SOURCE = [
+ `function tsGreet(name: string): string {`,
+ ` const tsMessage: string = 'Hello, ' + name;`,
+ ` return tsMessage;`,
+ `}`,
+ `(globalThis as {tsGreet?: unknown}).tsGreet = tsGreet;`,
+].join('\n');
+
+function transpileTsBundle(): {js: string; map: string} {
+ const result = ts.transpileModule(TS_SOURCE, {
+ fileName: 'app.ts',
+ compilerOptions: {
+ sourceMap: true,
+ module: ts.ModuleKind.None,
+ target: ts.ScriptTarget.ES2020,
+ },
+ });
+ assert.ok(result.sourceMapText, 'transpilation should produce a source map');
+ return {js: result.outputText, map: result.sourceMapText};
+}
+
+// Simulates a rebuilt bundle: the same code shifted down by extra leading
+// statements. Prepending a semicolon per line to the mappings shifts all
+// generated positions accordingly. The banner lines are executable so that
+// a logpoint left at the old generated position no longer hits tsGreet.
+function shiftBundle(
+ bundle: {js: string; map: string},
+ extraLines: number,
+): {js: string; map: string} {
+ const banner =
+ Array.from(
+ {length: extraLines},
+ (_, i) => `globalThis.banner${i} = ${i};`,
+ ).join('\n') + '\n';
+ const map = JSON.parse(bundle.map);
+ map.mappings = ';'.repeat(extraLines) + map.mappings;
+ return {js: banner + bundle.js, map: JSON.stringify(map)};
+}
+
+// A TypeScript file served the way a dev server like Vite does: transpiled
+// in place at the URL of the original file, with an inline source map that
+// points back at that same URL. The interface shifts the TypeScript lines
+// against the generated ones: tsDevGreet's message is on line 5 of the
+// TypeScript source and on line 3 of the served JavaScript.
+const DEV_TS_SOURCE = [
+ `interface Greeting {`,
+ ` text: string;`,
+ `}`,
+ `function tsDevGreet(name: string): string {`,
+ ` const devMessage: string = 'Hello, ' + name;`,
+ ` return devMessage;`,
+ `}`,
+ `(globalThis as {tsDevGreet?: unknown}).tsDevGreet = tsDevGreet;`,
+].join('\n');
+
+function transpileDevTs(): string {
+ const result = ts.transpileModule(DEV_TS_SOURCE, {
+ fileName: 'dev.ts',
+ compilerOptions: {
+ inlineSourceMap: true,
+ inlineSources: true,
+ module: ts.ModuleKind.None,
+ target: ts.ScriptTarget.ES2020,
+ },
+ });
+ return result.outputText;
+}
+
+// A "minified" script whose variable names differ from the original source,
+// as a minifier produces them, with a hand-written source map (there is no
+// minifier among the dev dependencies). Every identifier is mapped, which
+// DevTools needs to substitute original names in logpoint expressions.
+const MIN_TS_SOURCE = [
+ `function minGreet(name: string): string {`,
+ ` const minMessage: string = 'Hello, ' + name;`,
+ ` return minMessage;`,
+ `}`,
+ `(globalThis as {minGreet?: unknown}).minGreet = minGreet;`,
+].join('\n');
+
+const MIN_JS = [
+ `function minGreet(n){`,
+ `const m='Hello, '+n;`,
+ `return m;`,
+ `}`,
+ `globalThis.minGreet=minGreet;`,
+ `//# sourceMappingURL=min.js.map`,
+].join('\n');
+
+// Per generated line, the tokens of the generated text in order and the
+// original token each one comes from (same line of the original source).
+// Tokens are found in order, so repeated tokens map to their next occurrence.
+const MIN_NAMES = ['minGreet', 'name', 'minMessage'];
+const MIN_TOKENS: Array<Array<[string, string]>> = [
+ [
+ ['function', 'function'],
+ ['minGreet', 'minGreet'],
+ ['(', '('],
+ ['n', 'name'],
+ [')', ')'],
+ ['{', '{'],
+ ],
+ [
+ ['const', 'const'],
+ ['m', 'minMessage'],
+ ['=', '='],
+ [`'Hello, '`, `'Hello, '`],
+ ['+', '+'],
+ ['n', 'name'],
+ [';', ';'],
+ ],
+ [
+ ['return', 'return'],
+ ['m', 'minMessage'],
+ [';', ';'],
+ ],
+ [['}', '}']],
+ [
+ ['globalThis', 'globalThis'],
+ ['minGreet', 'minGreet'],
+ ['=', '='],
+ ['minGreet', 'minGreet'],
+ [';', ';'],
+ ],
+];
+
+// [generated column, original line, original column, name index] segments.
+function minSegments(): Array<Array<[number, number, number, number?]>> {
+ const originalLines = MIN_TS_SOURCE.split('\n');
+ const generatedLines = MIN_JS.split('\n');
+ return MIN_TOKENS.map((tokens, line) => {
+ let generatedFrom = 0;
+ let originalFrom = 0;
+ return tokens.map(([generatedToken, originalToken]) => {
+ const generatedColumn = generatedLines[line].indexOf(
+ generatedToken,
+ generatedFrom,
+ );
+ const originalColumn = originalLines[line].indexOf(
+ originalToken,
+ originalFrom,
+ );
+ assert.ok(generatedColumn >= 0 && originalColumn >= 0, generatedToken);
+ generatedFrom = generatedColumn + generatedToken.length;
+ originalFrom = originalColumn + originalToken.length;
+ const name = MIN_NAMES.indexOf(originalToken);
+ return name >= 0
+ ? [generatedColumn, line, originalColumn, name]
+ : [generatedColumn, line, originalColumn];
+ });
+ });
+}
+
+const BASE64 =
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+function encodeVlq(value: number): string {
+ let vlq = value < 0 ? (-value << 1) | 1 : value << 1;
+ let encoded = '';
+ do {
+ let digit = vlq & 31;
+ vlq >>>= 5;
+ if (vlq > 0) {
+ digit |= 32;
+ }
+ encoded += BASE64[digit];
+ } while (vlq > 0);
+ return encoded;
+}
+
+function encodeMappings(): string {
+ let previousSourceLine = 0;
+ let previousSourceColumn = 0;
+ let previousName = 0;
+ return minSegments()
+ .map(line => {
+ let previousGeneratedColumn = 0;
+ return line
+ .map(([generatedColumn, sourceLine, sourceColumn, name]) => {
+ const fields = [
+ generatedColumn - previousGeneratedColumn,
+ 0,
+ sourceLine - previousSourceLine,
+ sourceColumn - previousSourceColumn,
+ ];
+ previousGeneratedColumn = generatedColumn;
+ previousSourceLine = sourceLine;
+ previousSourceColumn = sourceColumn;
+ if (name !== undefined) {
+ fields.push(name - previousName);
+ previousName = name;
+ }
+ return fields.map(encodeVlq).join('');
+ })
+ .join(',');
+ })
+ .join(';');
+}
+
+function minifiedSourceMap(): string {
+ return JSON.stringify({
+ version: 3,
+ file: 'min.js',
+ sources: ['min.ts'],
+ sourcesContent: [MIN_TS_SOURCE],
+ names: MIN_NAMES,
+ mappings: encodeMappings(),
+ });
+}
+
+/** Collects console messages of the page from now on. */
+function collectConsole(page: McpPage): string[] {
+ const messages: string[] = [];
+ page.pptrPage.on('console', message => {
+ messages.push(message.text());
+ });
+ return messages;
+}
+
+async function waitForMessage(
+ messages: string[],
+ expected: string | RegExp,
+): Promise<void> {
+ const matches = (message: string) =>
+ typeof expected === 'string'
+ ? message === expected
+ : expected.test(message);
+ await waitExecutionFor(async () => {
+ if (!messages.some(matches)) {
+ throw new Error(
+ `Console messages do not include ${expected} yet: ${JSON.stringify(messages)}`,
+ );
+ }
+ }, 5000);
+}
+
+function evaluateWithTimeout(
+ page: McpPage,
+ expression: string,
+): Promise<unknown> {
+ return Promise.race([
+ page.pptrPage.evaluate(expression),
+ new Promise((_resolve, reject) => {
+ setTimeout(() => {
+ reject(new Error('Evaluation timed out: the debugger paused the page'));
+ }, 10_000);
+ }),
+ ]);
+}
+
+function assertLogpoint(
+ actual: Logpoint,
+ expected: Omit<Logpoint, 'generatedLocations'> & {
+ generatedUrl: string;
+ generatedLineNumber: number;
+ },
+): void {
+ const {generatedUrl, generatedLineNumber, ...rest} = expected;
+ const {generatedLocations, ...actualRest} = actual;
+ assert.deepStrictEqual(actualRest, rest);
+ assert.strictEqual(generatedLocations.length, 1);
+ assert.strictEqual(generatedLocations[0].url, generatedUrl);
+ assert.strictEqual(generatedLocations[0].lineNumber, generatedLineNumber);
+}
+
+describe('parseLogpoint', () => {
+ it('parses locations with ports, columns and expressions', () => {
+ assert.deepStrictEqual(
+ parseLogpoint(`http://127.0.0.1:16552/app.js:2 'greeting for', name`),
+ {
+ url: 'http://127.0.0.1:16552/app.js',
+ lineNumber: 2,
+ expression: `'greeting for', name`,
+ },
+ );
+ assert.deepStrictEqual(parseLogpoint('src/app.ts:42:7 cart.total'), {
+ url: 'src/app.ts',
+ lineNumber: 42,
+ columnNumber: 7,
+ expression: 'cart.total',
+ });
+ });
+
+ it('rejects a missing location or 0-based numbers', () => {
+ assert.throws(() => parseLogpoint('src/app.ts cart.total'), /format/);
+ assert.throws(() => parseLogpoint('src/app.ts:0 x'), /1-based/);
+ assert.throws(() => parseLogpoint('src/app.ts:4:0 x'), /1-based/);
+ });
+});
+
+describe('validateExpression', () => {
+ it('accepts console.log style arguments and rejects syntax errors', () => {
+ assert.doesNotThrow(() => validateExpression(`'total:', cart.total`));
+ assert.throws(
+ () => validateExpression(`'unbalanced', (`),
+ /does not compile/,
+ );
+ });
+});
+
+describe('LogpointManager', () => {
+ const server = serverHooks();
+
+ function setupRoutes() {
+ server.addRoute('/app.js', serveAppScript);
+ server.addHtmlRoute('/', html`<script src="/app.js"></script>`);
+ }
+
+ // Serves an html page with a transpiled TypeScript "bundle" whose content
+ // can be swapped between navigations via the returned holder.
+ function setupBundleRoutes(): {current: {js: string; map: string}} {
+ const holder = {current: transpileTsBundle()};
+ server.addHtmlRoute('/sm', html`<script src="/bundle.js"></script>`);
+ server.addRoute('/bundle.js', (req, res) => {
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
+ res.setHeader('Cache-Control', 'no-store');
+ res.end(holder.current.js);
+ });
+ server.addRoute('/app.js.map', (req, res) => {
+ res.setHeader('Content-Type', 'application/json');
+ res.setHeader('Cache-Control', 'no-store');
+ res.end(holder.current.map);
+ });
+ return holder;
+ }
+
+ it('logs without pausing, matches path suffixes and survives reloads', async () => {
+ await withMcpContext(async (response, context) => {
+ setupRoutes();
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/'));
+ const messages = collectConsole(page);
+ const url = server.getRoute('/app.js');
+
+ const logpoints = await page.setLogpoints([
+ {url: 'app.js', lineNumber: 2, expression: `'greeting for', name`},
+ ]);
+
+ assert.strictEqual(logpoints.length, 1);
+ assertLogpoint(logpoints[0], {
+ url,
+ lineNumber: 2,
+ // DevTools normalizes a missing column to the first column.
+ columnNumber: 1,
+ expression: `'greeting for', name`,
+ sourceMapped: false,
+ generatedUrl: url,
+ generatedLineNumber: 2,
+ });
+
+ await page.pptrPage.evaluate(`greet('World')`);
+ await waitForMessage(messages, 'greeting for World');
+
+ // Breakpoint conditions must not turn `debugger;` into a pause.
+ assert.strictEqual(
+ await evaluateWithTimeout(page, `withDebuggerStatement()`),
+ 42,
+ );
+
+ await page.pptrPage.reload();
+ await page.pptrPage.evaluate(`greet('Again')`);
+ await waitForMessage(messages, 'greeting for Again');
+ assert.strictEqual(
+ await evaluateWithTimeout(page, `withDebuggerStatement()`),
+ 42,
+ );
+ });
+ });
+
+ it('replaces, removes and clears logpoints with the complete list', async () => {
+ await withMcpContext(async (response, context) => {
+ setupRoutes();
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/'));
+ const messages = collectConsole(page);
+ const url = server.getRoute('/app.js');
+ const line2: LogpointOptions = {url, lineNumber: 2, expression: `'two'`};
+ const line3: LogpointOptions = {
+ url,
+ lineNumber: 3,
+ expression: `'three'`,
+ };
+
+ assert.strictEqual((await page.setLogpoints([line2, line3])).length, 2);
+
+ // Keep line 3 with a new expression; line 2 must stop logging.
+ const replaced = await page.setLogpoints([
+ {...line3, expression: `'three replaced'`},
+ ]);
+ assert.strictEqual(replaced.length, 1);
+ assert.strictEqual(replaced[0].lineNumber, 3);
+ assert.strictEqual(replaced[0].expression, `'three replaced'`);
+
+ await page.pptrPage.evaluate(`greet('World')`);
+ await waitForMessage(messages, 'three replaced');
+ assert.ok(!messages.includes('two'), `Line 2 still logged: ${messages}`);
+ assert.ok(
+ !messages.includes('three'),
+ `Old expression logged: ${messages}`,
+ );
+
+ assert.deepStrictEqual(await page.setLogpoints([]), []);
+ await page.pptrPage.evaluate(`greet('World')`);
+ await page.pptrPage.evaluate(`console.log('sentinel')`);
+ await waitForMessage(messages, 'sentinel');
+ assert.strictEqual(
+ messages.filter(message => message === 'three replaced').length,
+ 1,
+ );
+ });
+ });
+
+ it('resolves original sources and re-binds after a rebuilt bundle', async () => {
+ await withMcpContext(async (response, context) => {
+ const holder = setupBundleRoutes();
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/sm'));
+ const messages = collectConsole(page);
+ const options: LogpointOptions = {
+ url: 'app.ts',
+ lineNumber: 2,
+ expression: `'ts greeting', name`,
+ };
+
+ const [logpoint] = await page.setLogpoints([options]);
+ assert.strictEqual(logpoint.sourceMapped, true);
+ assert.ok(
+ logpoint.url.endsWith('/app.ts'),
+ `Expected the source map URL, got ${logpoint.url}`,
+ );
+ assert.strictEqual(logpoint.generatedLocations.length, 1);
+ const generated = logpoint.generatedLocations[0];
+ assert.strictEqual(generated.url, server.getRoute('/bundle.js'));
+
+ await page.pptrPage.evaluate(`tsGreet('One')`);
+ await waitForMessage(messages, 'ts greeting One');
+
+ // "Rebuild" the bundle: same source, shifted generated locations.
+ const extraLines = 5;
+ holder.current = shiftBundle(holder.current, extraLines);
+ await page.pptrPage.reload();
+
+ // The breakpoint manager re-binds once the new source map attaches.
+ await waitExecutionFor(async () => {
+ const [current] = await page.setLogpoints([options]);
+ const location = current.generatedLocations[0];
+ if (location?.lineNumber !== generated.lineNumber + extraLines) {
+ throw new Error(
+ `Not rebound yet: ${JSON.stringify(current.generatedLocations)}`,
+ );
+ }
+ }, 5000);
+
+ await page.pptrPage.evaluate(`tsGreet('Two')`);
+ await waitForMessage(messages, 'ts greeting Two');
+ });
+ });
+
+ it('substitutes original variable names at minified locations', async () => {
+ await withMcpContext(async (response, context) => {
+ server.addHtmlRoute('/min', html`<script src="/min.js"></script>`);
+ server.addRoute('/min.js', (req, res) => {
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
+ res.end(MIN_JS);
+ });
+ server.addRoute('/min.js.map', (req, res) => {
+ res.setHeader('Content-Type', 'application/json');
+ res.end(minifiedSourceMap());
+ });
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/min'));
+ const messages = collectConsole(page);
+
+ const logpoints = await page.setLogpoints([
+ {
+ url: 'min.ts',
+ lineNumber: 3,
+ expression: `'min greeting', name, minMessage`,
+ },
+ ]);
+
+ // The original source is only served through the source map.
+ assertLogpoint(logpoints[0], {
+ url: server.getRoute('/min.js').replace(/min\.js$/, 'min.ts'),
+ lineNumber: 3,
+ columnNumber: 3,
+ expression: `'min greeting', name, minMessage`,
+ sourceMapped: true,
+ generatedUrl: server.getRoute('/min.js'),
+ generatedLineNumber: 3,
+ });
+
+ // `name` and `minMessage` only exist as `n` and `m` in the script.
+ await page.pptrPage.evaluate(`minGreet('World')`);
+ await waitForMessage(messages, 'min greeting World Hello, World');
+ });
+ });
+
+ it('prefers the original source over a script served at the same URL', async () => {
+ await withMcpContext(async (response, context) => {
+ server.addHtmlRoute('/dev', html`<script src="/src/dev.ts"></script>`);
+ server.addRoute('/src/dev.ts', (req, res) => {
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
+ res.end(transpileDevTs());
+ });
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/dev'));
+ const messages = collectConsole(page);
+ const url = server.getRoute('/src/dev.ts');
+
+ const logpoints = await page.setLogpoints([
+ {url: 'src/dev.ts', lineNumber: 5, expression: `'dev greeting', name`},
+ ]);
+
+ // Line 5 of the TypeScript file, not line 5 of the served JavaScript;
+ // the column is that of the indented statement.
+ assertLogpoint(logpoints[0], {
+ url,
+ lineNumber: 5,
+ columnNumber: 3,
+ expression: `'dev greeting', name`,
+ sourceMapped: true,
+ generatedUrl: url,
+ generatedLineNumber: 3,
+ });
+
+ await page.pptrPage.evaluate(`tsDevGreet('Dev')`);
+ await waitForMessage(messages, 'dev greeting Dev');
+ });
+ });
+
+ it('reports unknown, ambiguous and non-executable locations', async () => {
+ await withMcpContext(async (response, context) => {
+ setupBundleRoutes();
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/sm'));
+ const bundleUrl = server.getRoute('/bundle.js');
+
+ await assert.rejects(
+ page.setLogpoints([
+ {url: 'nonexistent.js', lineNumber: 2, expression: `'never'`},
+ ]),
+ new RegExp(
+ `^Error: No parsed script or original source file matches "nonexistent.js"`,
+ ),
+ );
+ await assert.rejects(
+ page.setLogpoints([
+ {url: 'other/bundle.js', lineNumber: 2, expression: `'never'`},
+ ]),
+ new RegExp(`Sources with the same file name: ${bundleUrl}\\.$`),
+ );
+
+ // A valid logpoint is applied even when another one has no code.
+ await assert.rejects(
+ page.setLogpoints([
+ {url: 'app.ts', lineNumber: 2, expression: `'ok'`},
+ {url: 'app.ts', lineNumber: 999, expression: `'never'`},
+ ]),
+ (error: unknown) => {
+ assert.ok(error instanceof LogpointError);
+ assert.match(error.message, /No executable code at .*app\.ts:999 /);
+ assert.strictEqual(error.logpoints.length, 1);
+ assert.strictEqual(error.logpoints[0].lineNumber, 2);
+ return true;
+ },
+ );
+ assert.strictEqual(
+ (
+ await page.setLogpoints([
+ {url: 'app.ts', lineNumber: 2, expression: `'ok'`},
+ ])
+ ).length,
+ 1,
+ );
+ });
+ });
+
+ it('merges locations that normalize to the same breakpoint', async () => {
+ await withMcpContext(async (response, context) => {
+ setupBundleRoutes();
+ const page = context.getSelectedMcpPage();
+ await page.pptrPage.goto(server.getRoute('/sm'));
+ const messages = collectConsole(page);
+ const authored: LogpointOptions = {
+ url: 'app.ts',
+ lineNumber: 2,
+ expression: `'authored', name`,
+ };
+
+ const [first] = await page.setLogpoints([authored]);
+ const [generated] = first.generatedLocations;
+
+ // The generated location normalizes to the authored one, so both
+ // requests end up as one breakpoint whose expression is the last one.
+ const merged = await page.setLogpoints([
+ authored,
+ {
+ url: generated.url,
+ lineNumber: generated.lineNumber,
+ columnNumber: generated.columnNumber,
+ expression: `'generated', name`,
+ },
+ ]);
+ assert.strictEqual(merged.length, 1);
+ assert.strictEqual(merged[0].url, first.url);
+ assert.strictEqual(merged[0].sourceMapped, true);
+ assert.strictEqual(merged[0].expression, `'generated', name`);
+
+ await page.pptrPage.evaluate(`tsGreet('One')`);
+ await waitForMessage(messages, 'generated One');
+ assert.ok(
+ !messages.includes('authored One'),
+ `Logged twice: ${messages}`,
+ );
+
+ // Keeping only one of the two locations keeps the shared breakpoint.
+ const [kept] = await page.setLogpoints([authored]);
+ assert.strictEqual(kept.expression, `'authored', name`);
+ await page.pptrPage.evaluate(`tsGreet('Kept')`);
+ await waitForMessage(messages, 'authored Kept');
+
+ // Dropping the last key removes the shared breakpoint.
+ assert.deepStrictEqual(await page.setLogpoints([]), []);
+ await page.pptrPage.evaluate(`tsGreet('Two')`);
+ await page.pptrPage.evaluate(`console.log('sentinel')`);
+ await waitForMessage(messages, 'sentinel');
+ assert.ok(!messages.includes('generated Two'), `Still logs: ${messages}`);
+ });
+ });
+});
diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.ts
index b8a7b8ef..fdac2a28 100644
--- a/tests/McpPage.test.ts
+++ b/tests/McpPage.test.ts
@@ -12,6 +12,7 @@ import sinon from 'sinon';
import {UncaughtError} from '../src/collectors/PageCollector.js';
import type {ReadonlyServerConfig} from '../src/config/ServerConfig.js';
import type {TargetUniverse} from '../src/devtools/DevtoolsUtils.js';
+import {LogpointManager} from '../src/LogpointManager.js';
import {McpPage, replaceHtmlElementsWithUids} from '../src/McpPage.js';
import {
DevTools,
@@ -2641,3 +2642,66 @@ describe('McpPage', () => {
});
});
});
+
+describe('McpPage logpoints', () => {
+ async function createMcpPageWithUniverse() {
+ const pptrPage = createMockPuppeteerPage();
+ pptrPage.emulateFocusedPage.resolves();
+ const target = createMockPuppeteerTarget({page: pptrPage});
+ const mcpPage = new McpPage(target, 1, {
+ config: createMockServerConfig(),
+ locatorClass: Locator,
+ });
+ const universe = sinon.createStubInstance(
+ DevTools.Foundation.Universe.Universe,
+ );
+ sinon.stub(mcpPage, 'devtoolsUniverse').get((): TargetUniverse => ({
+ universe,
+ target: sinon.createStubInstance(DevTools.Target),
+ session: createMockCDPSession(),
+ }));
+ await mcpPage.init();
+ return mcpPage;
+ }
+
+ it('setLogpoints with an empty list creates no LogpointManager', async () => {
+ const setLogpoints = sinon.stub(LogpointManager.prototype, 'setLogpoints');
+ const mcpPage = await createMcpPageWithUniverse();
+
+ assert.deepStrictEqual(await mcpPage.setLogpoints([]), []);
+
+ sinon.assert.notCalled(setLogpoints);
+ });
+
+ it('setLogpoints creates one LogpointManager and forwards the list', async () => {
+ const setLogpoints = sinon
+ .stub(LogpointManager.prototype, 'setLogpoints')
+ .resolves([]);
+ const mcpPage = await createMcpPageWithUniverse();
+ const logpoints = [{url: 'app.js', lineNumber: 2, expression: `'x'`}];
+
+ await mcpPage.setLogpoints(logpoints);
+ await mcpPage.setLogpoints([]);
+
+ sinon.assert.calledTwice(setLogpoints);
+ sinon.assert.calledWithExactly(setLogpoints.firstCall, logpoints);
+ sinon.assert.calledWithExactly(setLogpoints.secondCall, []);
+ assert.strictEqual(
+ setLogpoints.firstCall.thisValue,
+ setLogpoints.secondCall.thisValue,
+ );
+ });
+
+ it('dispose releases the LogpointManager', async () => {
+ sinon.stub(LogpointManager.prototype, 'setLogpoints').resolves([]);
+ const dispose = sinon.stub(LogpointManager.prototype, 'dispose');
+ const mcpPage = await createMcpPageWithUniverse();
+ await mcpPage.setLogpoints([
+ {url: 'app.js', lineNumber: 2, expression: `'x'`},
+ ]);
+
+ mcpPage.dispose();
+
+ sinon.assert.calledOnce(dispose);
+ });
+});
diff --git a/tests/formatters/LogpointFormatter.test.js.snapshot b/tests/formatters/LogpointFormatter.test.js.snapshot
new file mode 100644
index 00000000..077c7dbc
--- /dev/null
+++ b/tests/formatters/LogpointFormatter.test.js.snapshot
@@ -0,0 +1,58 @@
+exports[`LogpointFormatter > formats an empty logpoint list toJSON 1`] = `
+[]
+`;
+
+exports[`LogpointFormatter > formats an empty logpoint list toString 1`] = `
+No logpoints are set on the page.
+`;
+
+exports[`LogpointFormatter > formats bound, source-mapped and unbound logpoints toJSON 1`] = `
+[
+ {
+ "url": "http://example.com/app.js",
+ "lineNumber": 4,
+ "expression": "'greeting for', name",
+ "sourceMapped": false,
+ "generatedLocations": [
+ {
+ "url": "http://example.com/app.js",
+ "lineNumber": 4,
+ "columnNumber": 3
+ }
+ ]
+ },
+ {
+ "url": "webpack:///src/cart.ts",
+ "lineNumber": 42,
+ "columnNumber": 7,
+ "expression": "'cart total:', cart.total, cart.items.length",
+ "sourceMapped": true,
+ "generatedLocations": [
+ {
+ "url": "http://example.com/bundle.js",
+ "lineNumber": 17,
+ "columnNumber": 25
+ },
+ {
+ "url": "http://example.com/bundle.js",
+ "lineNumber": 90,
+ "columnNumber": 1
+ }
+ ]
+ },
+ {
+ "url": "http://example.com/late.js",
+ "lineNumber": 1,
+ "expression": "'not parsed yet'",
+ "sourceMapped": false,
+ "generatedLocations": []
+ }
+]
+`;
+
+exports[`LogpointFormatter > formats bound, source-mapped and unbound logpoints toString 1`] = `
+3 logpoint(s) set on the page:
+- http://example.com/app.js:4 logging \`'greeting for', name\` [bound]
+- webpack:///src/cart.ts:42:7 logging \`'cart total:', cart.total, cart.items.length\` [bound via source map at http://example.com/bundle.js:17:25, http://example.com/bundle.js:90:1]
+- http://example.com/late.js:1 logging \`'not parsed yet'\` [not bound (no parsed script contains the location)]
+`;
diff --git a/tests/formatters/LogpointFormatter.test.ts b/tests/formatters/LogpointFormatter.test.ts
new file mode 100644
index 00000000..5319d35a
--- /dev/null
+++ b/tests/formatters/LogpointFormatter.test.ts
@@ -0,0 +1,55 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import {describe, it} from 'node:test';
+
+import {LogpointFormatter} from '../../src/formatters/LogpointFormatter.js';
+import type {Logpoint} from '../../src/LogpointManager.js';
+
+describe('LogpointFormatter', () => {
+ function formatterTest(label: string, logpoints: Logpoint[]) {
+ it(label + ' toString', t => {
+ const formatter = new LogpointFormatter(logpoints);
+ t.assert.snapshot(formatter.toString());
+ });
+ it(label + ' toJSON', t => {
+ const formatter = new LogpointFormatter(logpoints);
+ t.assert.snapshot(JSON.stringify(formatter.toJSON(), null, 2));
+ });
+ }
+
+ formatterTest('formats an empty logpoint list', []);
+
+ formatterTest('formats bound, source-mapped and unbound logpoints', [
+ {
+ url: 'http://example.com/app.js',
+ lineNumber: 4,
+ expression: `'greeting for', name`,
+ sourceMapped: false,
+ generatedLocations: [
+ {url: 'http://example.com/app.js', lineNumber: 4, columnNumber: 3},
+ ],
+ },
+ {
+ url: 'webpack:///src/cart.ts',
+ lineNumber: 42,
+ columnNumber: 7,
+ expression: `'cart total:', cart.total, cart.items.length`,
+ sourceMapped: true,
+ generatedLocations: [
+ {url: 'http://example.com/bundle.js', lineNumber: 17, columnNumber: 25},
+ {url: 'http://example.com/bundle.js', lineNumber: 90, columnNumber: 1},
+ ],
+ },
+ {
+ url: 'http://example.com/late.js',
+ lineNumber: 1,
+ expression: `'not parsed yet'`,
+ sourceMapped: false,
+ generatedLocations: [],
+ },
+ ]);
+});
diff --git a/tests/tools/logpoints.test.ts b/tests/tools/logpoints.test.ts
new file mode 100644
index 00000000..218ec3c2
--- /dev/null
+++ b/tests/tools/logpoints.test.ts
@@ -0,0 +1,171 @@
+/**
+ * @license
+ * Copyright 2026 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import assert from 'node:assert';
+import {describe, it} from 'node:test';
+
+import sinon from 'sinon';
+
+import type {Logpoint} from '../../src/LogpointManager.js';
+import {LogpointError} from '../../src/LogpointManager.js';
+import {setLogpoints} from '../../src/tools/logpoints.js';
+import {createHandlerMocks} from '../mocks.js';
+
+const BOUND_LOGPOINT: Logpoint = {
+ url: 'http://127.0.0.1:16552/app.js',
+ lineNumber: 2,
+ expression: `'greeting for', name`,
+ sourceMapped: false,
+ generatedLocations: [
+ {url: 'http://127.0.0.1:16552/app.js', lineNumber: 2, columnNumber: 3},
+ ],
+};
+
+const SOURCE_MAPPED_LOGPOINT: Logpoint = {
+ url: 'webpack:///src/cart.ts',
+ lineNumber: 42,
+ columnNumber: 7,
+ expression: 'cart.total',
+ sourceMapped: true,
+ generatedLocations: [
+ {url: 'http://127.0.0.1:16552/bundle.js', lineNumber: 17, columnNumber: 25},
+ ],
+};
+
+describe('set_logpoints', () => {
+ it('parses the logpoint strings and passes them to the page', async () => {
+ const {page, context, response, args} = createHandlerMocks();
+ page.setLogpoints.resolves([BOUND_LOGPOINT]);
+
+ await setLogpoints(args).handler(
+ {
+ params: {
+ logpoints: [`http://127.0.0.1:16552/app.js:2 'greeting for', name`],
+ },
+ page,
+ },
+ response,
+ context,
+ );
+
+ sinon.assert.calledOnceWithExactly(page.setLogpoints, [
+ {
+ url: 'http://127.0.0.1:16552/app.js',
+ lineNumber: 2,
+ expression: `'greeting for', name`,
+ },
+ ]);
+ sinon.assert.calledTwice(response.appendResponseLine);
+ sinon.assert.calledWithExactly(
+ response.appendResponseLine.firstCall,
+ [
+ '1 logpoint(s) set on the page:',
+ "- http://127.0.0.1:16552/app.js:2 logging `'greeting for', name` [bound]",
+ ].join('\n'),
+ );
+ sinon.assert.calledWithExactly(
+ response.appendResponseLine.secondCall,
+ 'Logged output appears in list_console_messages once a line executes; objects show as [object Object] there, get_console_message shows them as JSON.',
+ );
+ });
+
+ it('passes column numbers and adds the source map note', async () => {
+ const {page, context, response, args} = createHandlerMocks();
+ page.setLogpoints.resolves([SOURCE_MAPPED_LOGPOINT]);
+
+ await setLogpoints(args).handler(
+ {params: {logpoints: ['src/cart.ts:42:7 cart.total']}, page},
+ response,
+ context,
+ );
+
+ sinon.assert.calledOnceWithExactly(page.setLogpoints, [
+ {
+ url: 'src/cart.ts',
+ lineNumber: 42,
+ columnNumber: 7,
+ expression: 'cart.total',
+ },
+ ]);
+ sinon.assert.calledThrice(response.appendResponseLine);
+ sinon.assert.calledWithExactly(
+ response.appendResponseLine.firstCall,
+ [
+ '1 logpoint(s) set on the page:',
+ '- webpack:///src/cart.ts:42:7 logging `cart.total` [bound via source map at http://127.0.0.1:16552/bundle.js:17:25]',
+ ].join('\n'),
+ );
+ sinon.assert.calledWithExactly(
+ response.appendResponseLine.secondCall,
+ 'Source-mapped locations are re-resolved automatically when a matching source map loads again (for example after a reload with a regenerated bundle). Note: on the first page load after a rebuild, code that runs during the load itself is not logged yet; if a load-time logpoint stays silent right after a rebuild, reload once more before concluding that the line does not run.',
+ );
+ });
+
+ it('removes all logpoints with an empty list', async () => {
+ const {page, context, response, args} = createHandlerMocks();
+ page.setLogpoints.resolves([]);
+
+ await setLogpoints(args).handler(
+ {params: {logpoints: []}, page},
+ response,
+ context,
+ );
+
+ sinon.assert.calledOnceWithExactly(page.setLogpoints, []);
+ sinon.assert.calledOnceWithExactly(
+ response.appendResponseLine,
+ 'No logpoints are set on the page.',
+ );
+ });
+
+ it('rejects malformed logpoints before touching the page', async () => {
+ const {page, context, response, args} = createHandlerMocks();
+
+ await assert.rejects(
+ setLogpoints(args).handler(
+ {params: {logpoints: ['src/app.ts cart.total']}, page},
+ response,
+ context,
+ ),
+ /Expected the format <url>:<lineNumber>\[:<columnNumber>\] <expression>/,
+ );
+
+ sinon.assert.notCalled(page.setLogpoints);
+ sinon.assert.notCalled(response.appendResponseLine);
+ });
+
+ it('reports the applied logpoints when a location has no code', async () => {
+ const {page, context, response, args} = createHandlerMocks();
+ page.setLogpoints.rejects(
+ new LogpointError('No executable code at app.ts:999', [BOUND_LOGPOINT]),
+ );
+
+ await assert.rejects(
+ setLogpoints(args).handler(
+ {
+ params: {
+ logpoints: [
+ `http://127.0.0.1:16552/app.js:2 'greeting for', name`,
+ `app.ts:999 'never'`,
+ ],
+ },
+ page,
+ },
+ response,
+ context,
+ ),
+ /No executable code at app\.ts:999/,
+ );
+
+ sinon.assert.calledOnceWithExactly(
+ response.appendResponseLine,
+ [
+ '1 logpoint(s) set on the page:',
+ "- http://127.0.0.1:16552/app.js:2 logging `'greeting for', name` [bound]",
+ ].join('\n'),
+ );
+ });
+});