Skip to content

Chrome DevTools for coding agents

2.7 KB
Raw Blame
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type {CD4ACommentThread} from '../types.js';

export interface CommentFormatterOptions {
  resolveBackendNodeId?: (backendNodeId: number) => Promise<string | undefined>;
  resolveCdpRequestId?: (cdpRequestId: string) => number | undefined;
}

export interface StructuredCommentThread {
  id: string;
  text: string;
  elementUid?: string;
  reqid?: number;
}

function formatCommentThread(thread: StructuredCommentThread): string {
  const lines: string[] = [
    `### Thread: ${thread.id}`,
    `- Comment: ${thread.text}`,
  ];
  if (thread.elementUid) {
    lines.push(`- Related element uid: ${thread.elementUid}`);
  }
  if (thread.reqid !== undefined) {
    lines.push(`- Related network reqid: ${thread.reqid}`);
  }
  return lines.join('\n');
}

function formatComments(threads: readonly StructuredCommentThread[]): string {
  if (threads.length === 0) {
    return 'No open DevTools comments found.';
  }
  const lines: string[] = [
    `Found ${threads.length} DevTools comment thread(s):`,
  ];
  for (const thread of threads) {
    lines.push(`\n${formatCommentThread(thread)}`);
  }
  return lines.join('\n');
}

export class CommentFormatter {
  readonly #threads: readonly StructuredCommentThread[];

  constructor(threads: readonly StructuredCommentThread[]) {
    this.#threads = threads;
  }

  static async from(
    threads: readonly CD4ACommentThread[],
    options?: CommentFormatterOptions,
  ): Promise<CommentFormatter> {
    const structuredThreads: StructuredCommentThread[] = [];
    for (const thread of threads) {
      let elementUid: string | undefined;
      const resolveBackendNodeId = options?.resolveBackendNodeId;
      if (thread.node?.backendNodeId !== undefined && resolveBackendNodeId) {
        elementUid = await resolveBackendNodeId(thread.node.backendNodeId);
      }

      let reqid: number | undefined;
      const resolveCdpRequestId = options?.resolveCdpRequestId;
      if (thread.networkRequestId !== undefined && resolveCdpRequestId) {
        reqid = resolveCdpRequestId(thread.networkRequestId);
      }

      const item: StructuredCommentThread = {
        id: thread.id,
        text: thread.text,
      };
      if (elementUid) {
        item.elementUid = elementUid;
      }
      if (reqid !== undefined) {
        item.reqid = reqid;
      }
      structuredThreads.push(item);
    }
    return new CommentFormatter(structuredThreads);
  }

  static formatThread(thread: StructuredCommentThread): string {
    return formatCommentThread(thread);
  }

  toJSON(): StructuredCommentThread[] {
    return [...this.#threads];
  }

  toString(): string {
    return formatComments(this.toJSON());
  }
}