{
  "canonical_name": "microsoft/playwright",
  "compilation_id": "pack_4417925051ba4a278053e0739cd39250",
  "created_at": "2026-05-19T12:51:07.067694+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npm i -g @playwright/cli@latest` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npm i -g @playwright/cli@latest",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_6b09d51fae974d9cb4352a8923aa3655"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_f19adc1eb9f725c19fa056fd702a3716",
    "canonical_name": "microsoft/playwright",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/microsoft/playwright",
    "slug": "playwright",
    "source_packet_id": "phit_e2daea04d0f040e387844ad8b71ee041",
    "source_validation_id": "dval_92cb4f86971644e48c9c64d546891493"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 local_cli的用户",
    "github_forks": 5698,
    "github_stars": 88785,
    "one_liner_en": "Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.",
    "one_liner_zh": "Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "high",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:test, git, cli"
    },
    "target_user": "使用 local_cli 等宿主 AI 的用户",
    "title_en": "playwright",
    "title_zh": "playwright 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Browser Automation",
        "label_zh": "浏览器自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-browser-automation",
        "type": "core_capability"
      },
      {
        "label_en": "Page Observation and Action Planning",
        "label_zh": "页面观察与动作规划",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-page-observation-and-action-planning",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_e2daea04d0f040e387844ad8b71ee041",
  "page_model": {
    "artifacts": {
      "artifact_slug": "playwright",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npm i -g @playwright/cli@latest",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/microsoft/playwright#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API."
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "local_cli",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Fail tests on page errors",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_347cf8732e73437a9699e4d8bc55d958 | https://github.com/microsoft/playwright/issues/40880 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature]: Fail tests on page errors",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Ubuntu 26.04 LTS support",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_764e9005d6a94f41b4a8d9f52decca99 | https://github.com/microsoft/playwright/issues/40117 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature]: Ubuntu 26.04 LTS support",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: trace correlation hooks for external observability/replay systems",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_3c11bc1bf38e448f82e5b70d9f909037 | https://github.com/microsoft/playwright/issues/40887 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature]: trace correlation hooks for external observability/replay systems",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Feature]: support signal in waitFor* APIs",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_500f564d44534739b16e93ed0b6a86eb | https://github.com/microsoft/playwright/issues/40578 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature]: support signal in waitFor* APIs",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] \"NS_BINDING_ABORTED\" error in Firefox",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_16f48d22960444cfa514e3e08d959d45 | https://github.com/microsoft/playwright/issues/20749 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[BUG] \"NS_BINDING_ABORTED\" error in Firefox",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "Developers should check this security_permissions risk before relying on the project: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only",
            "category": "安全/权限坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_32d5131674a6cea46a3dd9fea57edcee | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only",
              "failure_mode_cluster:github_issue | fmev_5eb5ff7b9134ac254ca127feb48992d6 | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only"
            ],
            "severity": "high",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only. Context: Observed when using node, docker, playwright, linux",
            "title": "失败模式：security_permissions: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path...",
            "user_impact": "Developers may expose sensitive permissions or credentials: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_641150bc817a45af974903e3c724aa41 | https://github.com/microsoft/playwright/issues/40681 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Bug]: In VS Code, tests are not displayed in the Testing section.",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_429f2bbd1fa3334bca8aae5ee7df68b8 | https://github.com/microsoft/playwright/issues/40481 | [Bug]: In VS Code, tests are not displayed in the Testing section."
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: In VS Code, tests are not displayed in the Testing section.. Context: Observed when using node, playwright, windows, macos",
            "title": "失败模式：installation: [Bug]: In VS Code, tests are not displayed in the Testing section.",
            "user_impact": "Developers may fail before the first successful local run: [Bug]: In VS Code, tests are not displayed in the Testing section."
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_09c75aac9731971717426ccfbe72651b | https://github.com/microsoft/playwright/issues/40904 | [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1. Context: Observed when using node, playwright",
            "title": "失败模式：installation: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1",
            "user_impact": "Developers may fail before the first successful local run: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_bd2b1ca9bdfc4104afb98768ab5f87d4 | https://github.com/microsoft/playwright/issues/40889 | [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite. Context: Observed when using node, playwright, windows",
            "title": "失败模式：installation: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests nev...",
            "user_impact": "Developers may fail before the first successful local run: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_f50999f1a6066b929ea1a2971fefc95a | https://github.com/microsoft/playwright/issues/40768 | [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials. Context: Observed when using node, playwright, windows, linux",
            "title": "失败模式：installation: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect w...",
            "user_impact": "Developers may fail before the first successful local run: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_0f40df2fb212e08cdc02306a91f914c1 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length",
              "failure_mode_cluster:github_issue | fmev_a8ab1c8959a949b8aee2604c9969fcc4 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length. Context: Observed when using node, playwright, macos",
            "title": "失败模式：installation: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix s...",
            "user_impact": "Developers may fail before the first successful local run: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Feature] Configure web servers per project",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_4722870d2dbf6cec9abf1c0c8bcde960 | https://github.com/microsoft/playwright/issues/22496 | [Feature] Configure web servers per project"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Feature] Configure web servers per project. Context: Observed when using node, python, playwright",
            "title": "失败模式：installation: [Feature] Configure web servers per project",
            "user_impact": "Developers may fail before the first successful local run: [Feature] Configure web servers per project"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: [Regression]: install-deps --dry-run can no longer be used to generate install script",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_issue | fmev_c8dd7be64694731b0c1d899e67c604ae | https://github.com/microsoft/playwright/issues/40885 | [Regression]: install-deps --dry-run can no longer be used to generate install script"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: [Regression]: install-deps --dry-run can no longer be used to generate install script. Context: Observed when using node, docker, playwright, linux",
            "title": "失败模式：installation: [Regression]: install-deps --dry-run can no longer be used to generate install script",
            "user_impact": "Developers may fail before the first successful local run: [Regression]: install-deps --dry-run can no longer be used to generate install script"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_2c207034cca249f7b5c12ac82005f46f | https://github.com/microsoft/playwright/issues/13027 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_1099381b0b074addae62105e5328e211 | https://github.com/microsoft/playwright/issues/40826 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 38 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：[Feature]: Fail tests on page errors。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 744,
        "forks": 5698,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 88785
      },
      "source_url": "https://github.com/microsoft/playwright",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.",
      "title": "playwright 能力包",
      "trial_prompt": "# playwright - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for microsoft/playwright.\n\nProject:\n- Name: playwright\n- Repository: https://github.com/microsoft/playwright\n- Summary: Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. page-1: Playwright Introduction and Project Overview. Produce one small intermediate artifact and wait for confirmation.\n2. page-2: Package Ecosystem and Monorepo Structure. Produce one small intermediate artifact and wait for confirmation.\n3. page-3: Client-Server Communication Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. page-4: Browser Launch and Process Management. Produce one small intermediate artifact and wait for confirmation.\n5. page-5: Test Runner and Execution Engine. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/microsoft/playwright\n- https://github.com/microsoft/playwright#readme\n- .claude/skills/playwright-dev/SKILL.md\n- .claude/skills/playwright-devops/SKILL.md\n- packages/playwright-core/src/tools/cli-client/skill/SKILL.md\n- packages/playwright-core/src/tools/trace/SKILL.md\n- README.md\n- packages/playwright/package.json\n- packages/playwright-core/package.json\n- package.json\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: [Feature]: Expose securityDetails() on APIResponse for HTTPS monitoring （https://github.com/microsoft/playwright/issues/40905）；github/github_issue: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted（https://github.com/microsoft/playwright/issues/40904）；github/github_issue: [Bug]: Unable to Listen to Download Event While Using window.showSaveFil（https://github.com/microsoft/playwright/issues/31162）；github/github_issue: [Feature]: Fail tests on page errors（https://github.com/microsoft/playwright/issues/40880）；github/github_issue: [Feature]: trace correlation hooks for external observability/replay sys（https://github.com/microsoft/playwright/issues/40887）；github/github_issue: [Bug]: Trace viewer does not capture some dynamically added CSS classes（https://github.com/microsoft/playwright/issues/40895）；github/github_issue: [Regression]: install-deps --dry-run can no longer be used to generate i（https://github.com/microsoft/playwright/issues/40885）；github/github_issue: [Feature]: Fail tests on page errors（https://github.com/microsoft/playwright/issues/40880）；github/github_issue: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Pl（https://github.com/microsoft/playwright/issues/40681）；github/github_issue: [Bug]: In VS Code, tests are not displayed in the Testing section.（https://github.com/microsoft/playwright/issues/40481）；github/github_issue: [Bug]: playwright-cli open fails with EINVAL when session name is long o（https://github.com/microsoft/playwright/issues/40878）；github/github_issue: [BUG] \"NS_BINDING_ABORTED\" error in Firefox（https://github.com/microsoft/playwright/issues/20749）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature]: Expose securityDetails() on APIResponse for HTTPS monitoring ",
              "url": "https://github.com/microsoft/playwright/issues/40905"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted",
              "url": "https://github.com/microsoft/playwright/issues/40904"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug]: Unable to Listen to Download Event While Using window.showSaveFil",
              "url": "https://github.com/microsoft/playwright/issues/31162"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature]: Fail tests on page errors",
              "url": "https://github.com/microsoft/playwright/issues/40880"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature]: trace correlation hooks for external observability/replay sys",
              "url": "https://github.com/microsoft/playwright/issues/40887"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug]: Trace viewer does not capture some dynamically added CSS classes",
              "url": "https://github.com/microsoft/playwright/issues/40895"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Regression]: install-deps --dry-run can no longer be used to generate i",
              "url": "https://github.com/microsoft/playwright/issues/40885"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature]: Fail tests on page errors",
              "url": "https://github.com/microsoft/playwright/issues/40880"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Pl",
              "url": "https://github.com/microsoft/playwright/issues/40681"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug]: In VS Code, tests are not displayed in the Testing section.",
              "url": "https://github.com/microsoft/playwright/issues/40481"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug]: playwright-cli open fails with EINVAL when session name is long o",
              "url": "https://github.com/microsoft/playwright/issues/40878"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG] \"NS_BINDING_ABORTED\" error in Firefox",
              "url": "https://github.com/microsoft/playwright/issues/20749"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.",
      "effort": "安装已验证",
      "forks": 5698,
      "icon": "code",
      "name": "playwright 能力包",
      "risk": "可发布",
      "slug": "playwright",
      "stars": 88785,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/microsoft/playwright 项目说明书\n\n生成时间：2026-05-16 07:17:40 UTC\n\n## 目录\n\n- [Playwright Introduction and Project Overview](#page-1)\n- [Package Ecosystem and Monorepo Structure](#page-2)\n- [Client-Server Communication Architecture](#page-3)\n- [Browser Launch and Process Management](#page-4)\n- [Test Runner and Execution Engine](#page-5)\n- [Locators, Selectors, and Element Interaction](#page-6)\n- [Assertions, Matchers, and Expect API](#page-7)\n- [Browser Implementations and Protocol Support](#page-8)\n- [Trace Viewer and Debugging Tools](#page-9)\n- [CLI, MCP Server, and Agent Integration](#page-10)\n\n<a id='page-1'></a>\n\n## Playwright Introduction and Project Overview\n\n### 相关页面\n\n相关主题：[Package Ecosystem and Monorepo Structure](#page-2), [Test Runner and Execution Engine](#page-5)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n- [packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n- [packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n- [packages/playwright-core/src/tools/cli-client/skill/references/session-management.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md)\n- [packages/injected/src/consoleApi.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/consoleApi.ts)\n- [packages/injected/src/roleUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleUtils.ts)\n- [packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n- [packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n</details>\n\n# Playwright Introduction and Project Overview\n\n## 1. Overview\n\nPlaywright is a powerful end-to-end testing framework developed by Microsoft that enables reliable browser automation. It supports testing across multiple browsers (Chromium, Firefox, WebKit) with a single unified API, making it ideal for modern web application testing.\n\nThe project provides comprehensive tools for browser automation, test execution, debugging, and trace inspection. Playwright is designed to handle complex web scenarios including single-page applications, modern JavaScript frameworks, and sophisticated user interactions.\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n## 2. Project Architecture\n\n### 2.1 Core Packages\n\nThe Playwright project is organized as a monorepo with several key packages:\n\n| Package | Purpose |\n|---------|---------|\n| `playwright` | Main package with full test runner and all browser support |\n| `playwright-core` | Core browser automation library without bundled browsers |\n| `trace-viewer` | Web-based trace analysis and visualization tool |\n| `html-reporter` | Test report generation and visualization |\n| `injected` | In-browser script injection utilities |\n\n### 2.2 High-Level Architecture\n\n```mermaid\ngraph TD\n    A[Playwright Test Runner] --> B[playwright-core]\n    B --> C[Browser Drivers]\n    C --> D[Chromium]\n    C --> E[Firefox]\n    C --> F[WebKit]\n    B --> G[Connection Layer]\n    G --> H[Channel Owners]\n    H --> I[Page]\n    H --> J[Request/Response]\n    H --> K[Route]\n    H --> L[Tracing]\n    H --> M[WebSocket]\n    A --> N[HTML Reporter]\n    A --> O[Trace Viewer]\n```\n\n资料来源：[packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n\n### 2.3 Channel Owner System\n\nPlaywright uses a channel-based communication system where various browser objects are managed through factory functions:\n\n```mermaid\ngraph LR\n    A[Local Utils] --> B[Page]\n    A --> C[Playwright]\n    A --> D[Request]\n    A --> E[Response]\n    A --> F[Route]\n    A --> G[Tracing]\n    A --> H[WebSocket]\n```\n\nThe connection layer registers object factories for different types:\n\n```typescript\nPage: (parent, type, guid, init) => new Page(parent, type, guid, init),\nRequest: (parent, type, guid, init) => new Request(parent, type, guid, init),\nResponse: (parent, type, guid, init) => new Response(parent, type, guid, init),\nRoute: (parent, type, guid, init) => new Route(parent, type, guid, init),\nTracing: (parent, type, guid, init) => new Tracing(parent, type, guid, init),\n```\n\n资料来源：[packages/playwright-core/src/client/connection.ts:1-20](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n\n## 3. Browser Automation Capabilities\n\n### 3.1 CLI Client (playwright-cli)\n\nThe CLI client provides an interactive shell for browser automation tasks:\n\n| Command Category | Features |\n|-----------------|----------|\n| Navigation | `goto`, `back`, `forward`, `reload` |\n| Interaction | `click`, `fill`, `type`, `check`, `select` |\n| Capture | `screenshot`, `pdf`, `snapshot` |\n| Tabs | `tab-list`, `tab-new`, `tab-close`, `tab-select` |\n| Storage | `state-save`, `state-load`, `cookie-*`, `localstorage-*` |\n| Network | `route`, `unroute`, `route-list` |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n### 3.2 Injected Script API\n\nWhen Playwright injects scripts into web pages, a dedicated API becomes available:\n\n```typescript\nwindow.playwright = {\n  $: (selector: string, strict?: boolean) => this._querySelector(selector, !!strict),\n  $$: (selector: string) => this._querySelectorAll(selector),\n  inspect: (selector: string) => this._inspect(selector),\n  selector: (element: Element) => this._selector(element),\n  generateLocator: (element: Element, language?: Language) => this._generateLocator(element, language),\n  ariaSnapshot: (element?: Element, options?: AriaTreeOptions) => this._ariaSnapshot(element, options),\n  resume: () => this._resume(),\n  ...new Locator(this._injectedScript, ''),\n};\n```\n\nThe injected script is automatically installed on page load and provides DOM querying, locator generation, and ARIA snapshot capabilities.\n\n资料来源：[packages/injected/src/consoleApi.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/consoleApi.ts)\n\n### 3.3 ARIA Role Utilities\n\nPlaywright automatically maps HTML elements to ARIA roles for accessibility testing:\n\n| Element | Role Mapping |\n|---------|--------------|\n| `<H1>` - `<H6>` | `heading` |\n| `<BUTTON>` | `button` |\n| `<A>` | `link` |\n| `<INPUT type=\"search\">` | `searchbox` / `combobox` (with list) |\n| `<DIALOG>` | `dialog` |\n| `<NAV>` | `navigation` |\n| `<HEADER>` | `banner` (unless landmark prevented) |\n| `<FOOTER>` | `contentinfo` (unless landmark prevented) |\n| `<IMG alt=\"\">` | `presentation` (empty alt, no title) |\n\n```typescript\n'INPUT': (e: Element) => {\n  const type = (e as HTMLInputElement).type.toLowerCase();\n  if (type === 'search')\n    return e.hasAttribute('list') ? 'combobox' : 'searchbox';\n  // ...\n}\n```\n\n资料来源：[packages/injected/src/roleUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleUtils.ts)\n\n## 4. Test Execution Framework\n\n### 4.1 Running Tests\n\nPlaywright tests are executed using the standard Playwright test runner:\n\n```bash\n# Run all tests\nPLAYWRIGHT_HTML_OPEN=never npx playwright test\n\n# Run with custom npm script\nPLAYWRIGHT_HTML_OPEN=never npm run special-test-command\n```\n\nThe environment variable `PLAYWRIGHT_HTML_OPEN=never` prevents the interactive HTML report from opening automatically.\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n\n### 4.2 Debug Mode\n\nDebugging tests uses the CLI debug mode which pauses execution and provides debugging instructions:\n\n```bash\nPLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli\n```\n\nWhen debugging instructions appear with a session name (e.g., `tw-abcdef`), attach using:\n\n```bash\nplaywright-cli attach tw-abcdef\n```\n\nAvailable debugging commands:\n\n| Command | Purpose |\n|---------|---------|\n| `playwright-cli resume` | Resume test execution |\n| `playwright-cli snapshot` | Get inventory of interactive elements |\n| `playwright-cli click e5` | Interact with element by ref |\n| `playwright-cli eval` | Read URL/state |\n| `playwright-cli show --annotate` | Request user annotation |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n\n## 5. Browser Session Management\n\n### 5.1 Named Sessions\n\nPlaywright CLI supports multiple named browser sessions:\n\n```bash\n# Create new browser session named \"mysession\" with persistent profile\nplaywright-cli -s=mysession open example.com --persistent\n\n# Use specific session\nplaywright-cli -s=mysession click e6\n\n# Close named browser\nplaywright-cli -s=mysession close\n\n# Delete user data for persistent session\nplaywright-cli -s=mysession delete-data\n```\n\n### 5.2 Global Session Management\n\n```bash\n# List all browser sessions\nplaywright-cli list\n\n# Close all browsers\nplaywright-cli close-all\n\n# Forcefully kill all browser processes\nplaywright-cli kill-all\n```\n\n### 5.3 Environment Variable\n\nSet a default session via environment variable:\n\n```bash\nexport PLAYWRIGHT_CLI_SESSION=\"mysession\"\nplaywright-cli open example.com  # Uses \"mysession\" automatically\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/session-management.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md)\n\n## 6. Trace Viewer\n\n### 6.1 Overview\n\nThe Trace Viewer is a Progressive Web App for analyzing Playwright traces locally without sending data elsewhere:\n\n```mermaid\ngraph LR\n    A[Playwright Test] --> B[Trace.zip]\n    B --> C[Trace Viewer]\n    C --> D[Actions View]\n    C --> E[Requests View]\n    C --> F[Console View]\n    C --> G[Snapshots]\n```\n\n### 6.2 CLI Trace Commands\n\n```bash\n# Open and inspect trace\nnpx playwright trace open <trace.zip>\n\n# List all actions\nnpx playwright trace actions\n\n# Filter actions by pattern\nnpx playwright trace actions --grep \"click\"\n\n# Show only failed actions\nnpx playwright trace actions --errors-only\n\n# View specific action details\nnpx playwright trace action <action-id>\n\n# View DOM snapshot for action\nnpx playwright trace snapshot <action-id>\n\n# Evaluate JavaScript on snapshot\nnpx playwright trace snapshot <action-id> -- eval \"document.body.outerHTML\"\n\n# Export attachments\nnpx playwright trace attachments\nnpx playwright trace attachment 1 -o out.png\n```\n\n### 6.3 Typical Investigation Workflow\n\n```bash\n# 1. Open the trace\nnpx playwright trace open test-results/my-test/trace.zip\n\n# 2. View all actions\nnpx playwright trace actions\n\n# 3. Find failed actions\nnpx playwright trace actions --errors-only\n\n# 4. Inspect specific action\nnpx playwright trace action 12\n\n# 5. View page state at that moment\nnpx playwright trace snapshot 12\n\n# 6. Query DOM for details\nnpx playwright trace snapshot 12 -- eval \"document.querySelector('.error-message').textContent\"\n\n# 7. Check network failures\nnpx playwright trace requests --failed\n\n# 8. Check console errors\nnpx playwright trace console --errors-only\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n\n### 6.4 Trace Viewer UI Components\n\nThe trace viewer web application includes:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| WorkbenchLoader | `workbenchLoader.tsx` | Main application entry, handles file uploads and drag-drop |\n| BrowserFrame | `browserFrame.tsx` | Renders browser chrome with address bar |\n| MetadataView | `metadataView.tsx` | Displays test metadata (viewport, user agent, baseURL) |\n| TestCaseView | `testCaseView.tsx` | Shows individual test case details and results |\n\nThe workbench loader provides a progressive web app experience with local-only processing:\n\n```typescript\n<div className='info'>Playwright Trace Viewer is a Progressive Web App, it does not send your trace anywhere,\n  it opens it locally.</div>\n```\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n\n## 7. Key Features Summary\n\n| Feature | Description |\n|---------|-------------|\n| **Cross-browser** | Chromium, Firefox, WebKit support with single API |\n| **Auto-waiting** | Actions wait for elements to be actionable |\n| **Web-first assertions** | Built-in assertion library |\n| **Tracing** | Comprehensive action tracing and debugging |\n| **Locators** | Multiple strategies: CSS, ARIA, text, role |\n| **Network interception** | Mock and modify network requests |\n| **Storage state** | Save/restore authentication and cookies |\n| **CLI tools** | Interactive browser automation shell |\n\n## 8. Architecture Diagram: End-to-End Test Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Test\n    participant R as Playwright Runner\n    participant C as CLI Client\n    participant P as Browser\n    participant TV as Trace Viewer\n\n    T->>R: npx playwright test\n    R->>P: Launch browser\n    R->>P: Inject script\n    T->>C: playwright-cli attach\n    Note over C,P: Interactive debugging\n    P->>TV: Generate trace.zip\n    TV->>T: Analyze failures\n```\n\n## 9. Resources and Further Reading\n\n- Main Documentation: Playwright CLI capabilities and commands\n- Test Debugging: Debug mode and CLI attachment workflow\n- Trace Analysis: Using trace viewer for post-mortem analysis\n- Session Management: Multi-browser concurrent testing patterns\n- Storage State: Authentication and state persistence patterns\n\n---\n\n<a id='page-2'></a>\n\n## Package Ecosystem and Monorepo Structure\n\n### 相关页面\n\n相关主题：[Playwright Introduction and Project Overview](#page-1), [Client-Server Communication Architecture](#page-3)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [package.json](https://github.com/microsoft/playwright/blob/main/package.json)\n- [packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n- [packages/injected/src/roleUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleUtils.ts)\n- [packages/injected/src/consoleApi.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/consoleApi.ts)\n- [packages/playwright-browser-webkit/package.json](https://github.com/microsoft/playwright/blob/main/packages/playwright-browser-webkit/package.json)\n- [packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n- [examples/todomvc/package.json](https://github.com/microsoft/playwright/blob/main/examples/todomvc/package.json)\n</details>\n\n# Package Ecosystem and Monorepo Structure\n\nPlaywright is organized as a monorepo using npm workspaces, enabling centralized version management and shared tooling across multiple specialized packages. The repository contains the main `playwright` package alongside browser-specific packages, core libraries, and supporting tools.\n\n## Repository Overview\n\nThe Playwright monorepo follows a multi-package architecture where:\n\n- The root `package.json` defines shared scripts, build tooling, and workspace configuration\n- Individual packages under `packages/` contain focused, modular functionality\n- Examples under `examples/` demonstrate real-world usage patterns\n\n```mermaid\ngraph TD\n    Root[Root package.json<br/>v1.61.0-next] --> Core[playwright-core]\n    Root --> Main[playwright]\n    Root --> Chromium[playwright-browser-chromium]\n    Root --> Firefox[playwright-browser-firefox]\n    Root --> Webkit[playwright-browser-webkit]\n    Root --> Injected[injected]\n    Root --> TraceViewer[trace-viewer]\n    Root --> HtmlReporter[html-reporter]\n    \n    Core --> Injected\n    Main --> Core\n    Chromium --> Core\n    Firefox --> Core\n    Webkit --> Core\n```\n\n## Core Packages\n\n### playwright\n\nThe main public package that provides the high-level API for browser automation. It re-exports types and utilities from `playwright-core` while bundling browser automation capabilities.\n\n### playwright-core\n\nThe foundational package containing all browser automation logic. This package:\n\n- Defines client-side abstractions (`Page`, `Request`, `Response`, `Route`, `WebSocket`, `Worker`)\n- Manages channel-based communication between client and server\n- Implements the `LocalUtils` factory for shared utilities\n\nThe connection layer registers object factories for all domain objects:\n\n```typescript\nregisterObjectFactories({\n  LocalUtils: (parent, type, guid, init) => {\n    const result = new LocalUtils(parent, type, guid, init);\n    if (!this._localUtils)\n      this._localUtils = result;\n    return result;\n  },\n  Page: (parent, type, guid, init) => new Page(parent, type, guid, init),\n  Request: (parent, type, guid, init) => new Request(parent, type, guid, init),\n  Response: (parent, type, guid, init) => new Response(parent, type, guid, init),\n  Route: (parent, type, guid, init) => new Route(parent, type, guid, init),\n  Tracing: (parent, type, guid, init) => new Tracing(parent, type, guid, init),\n  WebSocket: (parent, type, guid, init) => new WebSocket(parent, type, guid, init),\n  Worker: (parent, type, guid, init) => new Worker(parent, type, guid, init),\n});\n```\n\n资料来源：[packages/playwright-core/src/client/connection.ts:10-35]()\n\n## Browser Packages\n\nBrowser-specific packages provide automatic browser installation and management. Each package depends on `playwright-core`.\n\n| Package | Purpose | Dependencies |\n|---------|---------|--------------|\n| `playwright-browser-chromium` | Chromium browser support | playwright-core |\n| `playwright-browser-firefox` | Firefox browser support | playwright-core |\n| `playwright-browser-webkit` | WebKit browser support | playwright-core |\n\nThe browser packages expose a standard interface:\n\n```json\n{\n  \"name\": \"@playwright/browser-webkit\",\n  \"version\": \"1.61.0-next\",\n  \"exports\": {\n    \".\": {\n      \"types\": \"./index.d.ts\",\n      \"import\": \"./index.mjs\",\n      \"require\": \"./index.js\",\n      \"default\": \"./index.js\"\n    }\n  },\n  \"dependencies\": {\n    \"playwright-core\": \"1.61.0-next\"\n  }\n}\n```\n\n资料来源：[packages/playwright-browser-webkit/package.json]()\n\n## Injected Scripts Package\n\nThe `injected` package contains scripts that run within the browser context, providing accessibility utilities and developer inspection capabilities.\n\n### Console API Installation\n\nThe injected script installs a `playwright` object onto `window` when `install()` is called:\n\n```typescript\ninstall() {\n  if (this._injectedScript.window.playwright)\n    return;\n  this._injectedScript.window.playwright = {\n    $: (selector: string, strict?: boolean) => this._querySelector(selector, !!strict),\n    $$: (selector: string) => this._querySelectorAll(selector),\n    inspect: (selector: string) => this._inspect(selector),\n    selector: (element: Element) => this._selector(element),\n    generateLocator: (element: Element, language?: Language) => this._generateLocator(element, language),\n    ariaSnapshot: (element?: Element, options?: AriaTreeOptions) => {\n      return this._injectedScript.ariaSnapshot(element || this._injectedScript.document.body, options || { mode: 'default' });\n    },\n    resume: () => this._resume(),\n    ...new Locator(this._injectedScript, ''),\n  };\n}\n```\n\n资料来源：[packages/injected/src/consoleApi.ts:10-30]()\n\n### Role Utilities\n\nThe `roleUtils.ts` file maps HTML elements to their ARIA roles for accessibility testing:\n\n```typescript\n'DIALOG': () => 'dialog',\n'FORM': (e: Element) => hasExplicitAccessibleName(e) ? 'form' : null,\n'HEADER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'banner',\n'IMG': (e: Element) => (e.getAttribute('alt') === '') && !e.getAttribute('title') && !hasGlobalAriaAttribute(e) && !hasTabIndex(e) ? 'presentation' : 'img',\n```\n\n资料来源：[packages/injected/src/roleUtils.ts:1-50]()\n\n## Tooling Packages\n\n### trace-viewer\n\nA React-based Progressive Web Application for inspecting Playwright trace files. The trace viewer provides:\n\n- Drop-zone interface for loading trace files locally\n- Progress dialogs for trace processing\n- Version display showing the Playwright version\n- No data transmission—opens files locally\n\n```tsx\n<div className='info'>Playwright Trace Viewer is a Progressive Web App, it does not send your trace anywhere,\n  it opens it locally.</div>\n<div className='version'>Playwright v{__APP_VERSION__}</div>\n```\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx:1-30]()\n\n### html-reporter\n\nGenerates HTML test reports with:\n\n- Test case location linking\n- Duration tracking\n- Project and tag labeling\n- Annotation display\n- Retry labeling for failed tests\n\n```tsx\n<CopyToClipboardContainer value={`${test.location.file}:${test.location.line}`}>\n  {test.location.file}:{test.location.line}\n</CopyToClipboardContainer>\n<TraceLink test={test} trailingSeparator={true} />\n<div className='test-case-duration'>{msToString(test.duration)}</div>\n```\n\n资料来源：[packages/html-reporter/src/testCaseView.tsx:1-30]()\n\n## CLI Tools\n\n### playwright-cli\n\nA command-line tool for browser automation and page interaction. Available commands include:\n\n```bash\n# Core commands\nplaywright-cli open                          # Open browser\nplaywright-cli goto <url>                    # Navigate\nplaywright-cli click <element>               # Click element\nplaywright-cli type <text>                   # Type text\n\n# Snapshot and evaluation\nplaywright-cli snapshot                      # Get page snapshot\nplaywright-cli eval \"code\"                   # Execute JS\n\n# Tab management\nplaywright-cli tab-list                      # List tabs\nplaywright-cli tab-new <url>                 # New tab\n\n# State management\nplaywright-cli state-save <file>             # Save state\nplaywright-cli state-load <file>            # Load state\n\n# Network interception\nplaywright-cli route \"<pattern>\"             # Intercept routes\n```\n\n### playwright-trace\n\nInspect trace files from the command line:\n\n```bash\nnpx playwright trace open <trace.zip>       # Open and extract trace\nnpx playwright trace actions                 # List all actions\nnpx playwright trace action <action-id>      # View action details\nnpx playwright trace console                 # View console messages\nnpx playwright trace errors                  # View errors\nnpx playwright trace snapshot <action-id>    # View DOM snapshot\nnpx playwright trace close                   # Close trace\n```\n\n## Build and Test Scripts\n\nThe root `package.json` defines comprehensive test and lint scripts:\n\n| Script | Purpose |\n|--------|---------|\n| `ctest` | Chromium tests |\n| `ftest` | Firefox tests |\n| `wtest` | WebKit tests |\n| `atest` | Android tests |\n| `etest` | Electron tests |\n| `itest` | Installation tests |\n| `stest` | Stress tests |\n| `biditest` | BiDi protocol tests |\n| `ttest` | Playwright Test runner tests |\n| `lint` | Full linting suite |\n| `tsc` | TypeScript compilation |\n\n```json\n{\n  \"scripts\": {\n    \"ctest\": \"playwright test --config=tests/library/playwright.config.ts --project=chromium-*\",\n    \"ftest\": \"playwright test --config=tests/library/playwright.config.ts --project=firefox-*\",\n    \"wtest\": \"playwright test --config=tests/library/playwright.config.ts --project=webkit-*\",\n    \"test\": \"playwright test --config=tests/library/playwright.config.ts\",\n    \"eslint\": \"eslint --cache\",\n    \"tsc\": \"tsc -p .\"\n  }\n}\n```\n\n资料来源：[package.json:1-50]()\n\n## Monorepo Structure Summary\n\n```mermaid\ngraph TD\n    subgraph \"Root\"\n        RootPkg[package.json<br/>v1.61.0-next]\n    end\n    \n    subgraph \"Core Packages\"\n        Core[playwright-core<br/>Automation core]\n        Injected[injected<br/>Browser scripts]\n    end\n    \n    subgraph \"Public Packages\"\n        Main[playwright<br/>Main API]\n        Chromium[playwright-browser-chromium]\n        Firefox[playwright-browser-firefox]\n        Webkit[playwright-browser-webkit]\n    end\n    \n    subgraph \"Tooling\"\n        CLI[playwright-cli<br/>CLI tool]\n        Trace[playwright-trace<br/>Trace CLI]\n        Viewer[trace-viewer<br/>Trace PWA]\n        Reporter[html-reporter<br/>Test reports]\n    end\n    \n    subgraph \"Examples\"\n        Todo[todomvc]\n        Svgomg[svgomg]\n    end\n    \n    Main --> Core\n    Chromium --> Core\n    Firefox --> Core\n    Webkit --> Core\n    CLI --> Core\n    Trace --> Core\n    Viewer --> Core\n    Reporter --> Core\n    Core --> Injected\n```\n\n## Package Versioning\n\nAll packages in the monorepo share the same version number for consistency:\n\n```json\n{\n  \"version\": \"1.61.0-next\",\n  \"engines\": {\n    \"node\": \">=18\"\n  }\n}\n```\n\nBrowser packages declare explicit dependencies on `playwright-core`:\n\n```json\n\"dependencies\": {\n  \"playwright-core\": \"1.61.0-next\"\n}\n```\n\nThis ensures version alignment across the ecosystem while allowing independent releases when necessary.\n\n---\n\n<a id='page-3'></a>\n\n## Client-Server Communication Architecture\n\n### 相关页面\n\n相关主题：[Package Ecosystem and Monorepo Structure](#page-2), [Browser Launch and Process Management](#page-4)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/client/channelOwner.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/channelOwner.ts)\n- [packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n- [packages/playwright-core/src/server/dispatchers/dispatcher.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/dispatchers/dispatcher.ts)\n- [packages/playwright-core/src/remote/playwrightConnection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/remote/playwrightConnection.ts)\n- [packages/protocol/src/channels.d.ts](https://github.com/microsoft/playwright/blob/main/packages/protocol/src/channels.d.ts)\n- [packages/playwright-core/src/client/playwright.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/playwright.ts)\n- [packages/playwright-core/src/client/page.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/page.ts)\n</details>\n\n# Client-Server Communication Architecture\n\n## Overview\n\nPlaywright's Client-Server Communication Architecture enables the automation of web browsers through a well-defined message-passing system. The architecture separates the client API (used by test developers) from the server-side browser automation engine, allowing tests to control Chromium, Firefox, and WebKit browsers running either locally or in remote environments.\n\n## High-Level Architecture\n\n```mermaid\ngraph TD\n    subgraph Client[\"Client Side (Node.js)\"]\n        API[Test API<br/>playwright.click()]\n        CO[ChannelOwner<br/>Base Class]\n        CONN[Connection]\n    end\n    \n    subgraph Server[\"Server Side (Node.js + Browser)\"]\n        DIS[Dispatcher]\n        CH[Channel Handlers]\n        BR[Browser<br/>Chromium/Firefox/WebKit]\n    end\n    \n    API --> CO\n    CO --> CONN\n    CONN -->|Protocol Messages| DIS\n    DIS --> CH\n    CH --> BR\n    \n    style Client fill:#e1f5fe\n    style Server fill:#fff3e0\n```\n\nThe architecture follows a factory pattern where the `Connection` class registers object factories for all protocol-defined objects. When the client creates a `Page` or `BrowserContext`, the corresponding factory is invoked to create a client-side proxy object.\n\n## Core Components\n\n### ChannelOwner (Client-Side Base Class)\n\nThe `ChannelOwner` class serves as the base for all client-side objects that communicate with the server. It provides:\n\n- **Message routing**: Sends commands to the server and receives responses\n- **Event handling**: Subscribes to server-side events\n- **Lifecycle management**: Tracks object disposal and cleanup\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `channel` | `Channel` | The communication channel to the server |\n| `connection` | `Connection` | Reference to the parent connection |\n| `guid` | `string` | Unique identifier for this object |\n| `parent` | `ChannelOwner \\| null` | Parent object in the hierarchy |\n\n资料来源：[packages/playwright-core/src/client/channelOwner.ts]()\n\n### Connection (Client-Side Hub)\n\nThe `Connection` class manages all client-server communication and object lifecycle.\n\n```typescript\n// Connection registers factories for all protocol objects\nregisterObjectFactories(factories: Record<string, ChannelFactory>) {\n  // Creates appropriate client-side objects for each type\n}\n```\n\n**Registered Object Factories:**\n\n| Object Type | Factory Creates | Purpose |\n|-------------|-----------------|---------|\n| `Browser` | Browser instance | Main browser process |\n| `BrowserContext` | Context instance | Isolated browsing sessions |\n| `Page` | Page instance | Single tab/page |\n| `Request` | Request instance | HTTP request tracking |\n| `Response` | Response instance | HTTP response data |\n| `Route` | Route instance | Network request interception |\n| `Tracing` | Tracing instance | Trace collection |\n| `WebSocket` | WebSocket instance | WebSocket communication |\n| `Worker` | Worker instance | Web Workers |\n| `LocalUtils` | Utility instance | Local utility functions |\n\n资料来源：[packages/playwright-core/src/client/connection.ts:1-50]()\n\n### Dispatcher (Server-Side Handler)\n\nThe `Dispatcher` class is the server-side counterpart that handles messages from clients.\n\n```mermaid\ngraph LR\n    MSG[Incoming<br/>Message] --> DIS[Dispatcher]\n    DIS -->|Route| HAND[Channel Handler]\n    HAND -->|Execute| BR[Browser API]\n    BR -->|Result| RES[Response<br/>to Client]\n```\n\nKey responsibilities:\n- Deserialize incoming messages\n- Route to appropriate channel handler\n- Execute browser automation commands\n- Send responses back to client\n\n资料来源：[packages/playwright-core/src/server/dispatchers/dispatcher.ts]()\n\n### Protocol Channels\n\nThe protocol defines typed channels for all communication between client and server.\n\n```typescript\n// Generated from protocol definitions\ninterface Channels {\n  Browser: {\n    // Methods\n    newContext(options?: BrowserNewContextOptions): Promise<BrowserContext>;\n    close(): Promise<void>;\n    // Events\n    on('disconnected', callback: () => void): void;\n  };\n  Page: {\n    click(selector: string, options?: PageClickOptions): Promise<void>;\n    fill(selector: string, value: string): Promise<void>;\n    // ...\n  };\n}\n```\n\n资料来源：[packages/protocol/src/channels.d.ts]()\n\n## Communication Flow\n\n### Method Invocation Flow\n\n```mermaid\nsequenceDiagram\n    participant Client as Test Code\n    participant CO as ChannelOwner\n    participant CONN as Connection\n    participant Wire as Wire Protocol\n    participant DIS as Dispatcher\n    participant Impl as Implementation\n    \n    Client->>CO: page.click('#button')\n    CO->>CONN: sendMessage('click', args)\n    CONN->>Wire: serialize & send\n    Wire->>DIS: deliver message\n    DIS->>Impl: invoke method\n    Impl-->>DIS: return result\n    DIS-->>Wire: send response\n    Wire-->>CONN: receive response\n    CONN-->>CO: deserialize result\n    CO-->>Client: Promise resolves\n```\n\n### Object Creation Flow\n\nWhen a client requests a new object (e.g., `browser.newContext()`):\n\n1. Server creates the implementation object\n2. Server creates a dispatcher wrapper\n3. Server returns the new object's channel reference to client\n4. Client's connection factory creates appropriate `ChannelOwner` subclass\n5. Client receives a proxy object to interact with the new object\n\n```mermaid\ngraph TD\n    subgraph Server[\"Server\"]\n        IMPL[Implementation]\n        DISP[Dispatcher]\n    end\n    \n    subgraph Client[\"Client\"]\n        FACT[Factory]\n        PROXY[ChannelOwner Proxy]\n    end\n    \n    IMPL -->|creates| DISP\n    DISP -->|returns guid| FACT\n    FACT -->|creates| PROXY\n```\n\n## Remote Connections\n\nPlaywright supports remote browser connections through `PlaywrightConnection`.\n\n```mermaid\ngraph TD\n    subgraph Local[\"Test Machine\"]\n        TEST[Test Code]\n        CLIENT[Local Client]\n    end\n    \n    subgraph Remote[\"Remote Machine\"]\n        SERVER[Playwright Server]\n        BROWSER[Browser]\n    end\n    \n    TEST --> CLIENT\n    CLIENT -->|WebSocket| SERVER\n    SERVER --> BROWSER\n```\n\nThe remote connection maintains the same channel-based communication but uses WebSocket transport instead of in-process communication.\n\n资料来源：[packages/playwright-core/src/remote/playwrightConnection.ts]()\n\n## Message Protocol\n\n### Message Structure\n\n```typescript\ninterface ProtocolMessage {\n  id: string;           // Unique message ID\n  guid: string;         // Target object GUID\n  method: string;       // Method name\n  params?: object;     // Method parameters\n  type: 'request' | 'response' | 'event';\n}\n```\n\n### Event Subscription\n\nClients subscribe to server-side events through the channel system:\n\n```typescript\n// Server emits event\ndispatcher.dispatchEvent('eventName', payload);\n\n// Client receives via callback\npage.on('close', () => {\n  console.log('Page closed');\n});\n```\n\n## Object Hierarchy\n\n```mermaid\ngraph TD\n    P[Playwright] --> BC[Browser]\n    BC --> BCT[BrowserContext]\n    BCT --> PGE[Page]\n    \n    PGE --> W[Worker]\n    PGE --> R[Route]\n    \n    BCT --> RS[Request]\n    BCT --> RS2[Response]\n    \n    style P fill:#c8e6c9\n    style BC fill:#fff9c4\n    style BCT fill:#bbdefb\n    style PGE fill:#ffccbc\n```\n\nAll objects inherit from `ChannelOwner` and maintain references to their parent connection.\n\n## Error Handling\n\nThe architecture handles errors through:\n\n1. **Sync errors**: Caught and returned as rejected promises\n2. **Async errors**: Propagated through the message response\n3. **Disconnection**: Server sends 'disconnected' event to notify clients\n\n```typescript\ntry {\n  await page.click('#missing');\n} catch (e) {\n  // Error contains reason and stack\n  console.log(e.message); // Target closed, did you mean to close the browser?\n}\n```\n\n## Key Design Patterns\n\n### Factory Pattern\n\nObject factories in `Connection` create the appropriate `ChannelOwner` subclass based on protocol type.\n\n### Proxy Pattern\n\n`ChannelOwner` instances are proxies that forward method calls to the server.\n\n### Observer Pattern\n\nEvent subscriptions allow clients to react to server-side state changes.\n\n### Promise-based Async\n\nAll operations return Promises, enabling async/await usage in tests.\n\n## Summary\n\nPlaywright's Client-Server Communication Architecture provides:\n\n- **Type safety**: Protocol definitions ensure consistent interfaces\n- **Location transparency**: Local and remote execution use the same API\n- **Extensibility**: New object types can be added to the protocol\n- **Performance**: Optimized message serialization and batching\n- **Debuggability**: Clear message flow between components\n\n---\n\n<a id='page-4'></a>\n\n## Browser Launch and Process Management\n\n### 相关页面\n\n相关主题：[Client-Server Communication Architecture](#page-3), [Browser Implementations and Protocol Support](#page-8)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/outofprocess.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/outofprocess.ts)\n- [packages/playwright-core/src/inprocess.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/inprocess.ts)\n- [packages/playwright-core/src/server/browserType.ts](https://github.com/microsoft/playicrosoft/playwright/blob/main/packages/playwright-core/src/server/browserType.ts)\n- [packages/playwright-core/src/server/browser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/browser.ts)\n- [packages/utils/processLauncher.ts](https://github.com/microsoft/playwright/blob/main/packages/utils/processLauncher.ts)\n- [packages/playwright-core/src/server/transport.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/transport.ts)\n</details>\n\n# Browser Launch and Process Management\n\n## Overview\n\nBrowser Launch and Process Management is a core subsystem in Playwright responsible for spawning, communicating with, and lifecycle-managing browser processes. This subsystem abstracts the complexity of launching different browser types (Chromium, Firefox, WebKit) across different environments, handling both in-process and out-of-process execution models while maintaining reliable communication channels.\n\nThe system provides:\n\n- **Cross-browser abstraction** - Unified API for launching Chromium, Firefox, and WebKit\n- **Process lifecycle management** - Spawning, health monitoring, graceful termination\n- **Dual execution modes** - In-process and out-of-process browser execution\n- **Transport layer abstraction** - Message-based IPC between Node.js and browser processes\n- **Resource cleanup** - Proper disposal of browser instances and associated resources\n\n资料来源：[packages/playwright-core/src/server/browserType.ts:1-50]()\n\n## Architecture\n\n### High-Level Components\n\n```mermaid\ngraph TD\n    A[Playwright Client API] --> B[BrowserType]\n    B --> C{Launch Mode}\n    C -->|Out-of-Process| D[OutOfProcess]\n    C -->|In-Process| E[InProcess]\n    D --> F[ProcessLauncher]\n    D --> G[Transport Layer]\n    E --> H[BrowserProcess]\n    F --> I[Browser Executable]\n    G --> J[Browser Server]\n    H --> I\n```\n\n### Core Component Roles\n\n| Component | Package | Responsibility |\n|-----------|---------|----------------|\n| `BrowserType` | `playwright-core` | Entry point for browser launching, delegates to appropriate implementation |\n| `OutOfProcess` | `playwright-core` | Manages out-of-process browser execution with separate server process |\n| `InProcess` | `playwright-core` | Manages in-process browser execution within Node.js |\n| `ProcessLauncher` | `utils` | Core process spawning and management utilities |\n| `Transport` | `playwright-core` | Message-based IPC communication layer |\n| `Browser` | `playwright-core` | Abstract browser base class with lifecycle management |\n\n资料来源：[packages/playwright-core/src/server/browserType.ts:1-100]()\n\n## Launch Modes\n\nPlaywright supports two distinct browser launch modes, each suited for different use cases.\n\n### Out-of-Process Mode\n\nThe out-of-process (OOP) mode spawns browser processes as separate OS processes, with communication handled via WebSocket or pipe-based transport layers.\n\n**Characteristics:**\n\n- Process isolation - Browser crashes do not affect the Node.js process\n- Cross-language support - Enables Playwright bindings in languages other than Node.js\n- Resource efficiency - Better for running multiple browser instances\n- Security - Browser runs in separate sandboxed process\n\n```mermaid\ngraph LR\n    A[Node.js Process] <-->|WebSocket/Pipes| B[Browser Server Process]\n    B --> C[Browser Executable]\n```\n\nThe `OutOfProcess` class handles:\n\n1. Spawning the browser server executable\n2. Establishing transport connection\n3. Handshake and version negotiation\n4. Proxying API calls to the browser\n\n资料来源：[packages/playwright-core/src/outofprocess.ts:1-80]()\n\n### In-Process Mode\n\nThe in-process mode runs browser execution within the Node.js process itself, useful for scenarios requiring tighter integration.\n\n**Characteristics:**\n\n- Direct execution - No inter-process communication overhead\n- Debugging simplicity - Easier to debug browser and client code together\n- Shared memory - Direct access to browser resources\n- Limited isolation - Browser crashes may affect Node.js process\n\nThe `InProcess` class provides a simplified launch path that instantiates browser internals directly without spawning separate processes.\n\n资料来源：[packages/playwright-core/src/inprocess.ts:1-60]()\n\n### Mode Selection\n\n```typescript\n// Out-of-process (default)\nconst browser = await chromium.launch({ headless: true });\n\n// In-process via browser type's `launchServer`\nconst server = await chromium.launchServer({ headless: true });\n```\n\n## Process Lifecycle\n\n### Launch Sequence\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant BrowserType\n    participant Launcher\n    participant Browser\n    participant Transport\n\n    Client->>BrowserType: launch(options)\n    BrowserType->>Launcher: spawn(executable, args)\n    Launcher->>Browser: new Browser(transport)\n    Browser->>Transport: connect()\n    Transport-->>Browser: connection established\n    Browser->>Browser: initialize()\n    Browser-->>BrowserType: ready\n    BrowserType-->>Client: Browser instance\n```\n\n### Lifecycle States\n\n| State | Description | Transitions |\n|-------|-------------|-------------|\n| `Launching` | Process is being spawned | → `Connected` or `Failed` |\n| `Connected` | Transport layer established | → `Initialized` or `Closed` |\n| `Initialized` | Browser fully ready | → `Closed` |\n| `Failed` | Launch or initialization failed | Terminal state |\n| `Closed` | Browser process terminated | Terminal state |\n\n资料来源：[packages/playwright-core/src/server/browser.ts:1-150]()\n\n### Termination\n\nBrowser termination follows a controlled shutdown sequence:\n\n1. **Graceful close request** - Send close command to browser\n2. **Resource cleanup** - Dispose contexts, pages, and handlers\n3. **Process termination** - Kill the browser executable if still running\n4. **Transport cleanup** - Close connections and cleanup pipes\n\n```mermaid\ngraph TD\n    A[Browser.close called] --> B{Force kill?}\n    B -->|No| C[Graceful shutdown]\n    B -->|Yes| D[Kill process]\n    C --> E[Wait for exit]\n    E --> F[Force kill if timeout]\n    D --> G[Cleanup resources]\n    F --> G\n    G --> H[Done]\n```\n\n## Transport Layer\n\nThe transport layer enables message-based communication between the Node.js client and browser process.\n\n### Message Protocol\n\nMessages follow a structured format with JSON-serialized headers and binary payloads:\n\n```\n┌─────────────────────────────────────────┐\n│ Message Header (JSON)                   │\n│ { id, method, params, binaryLength }    │\n├─────────────────────────────────────────┤\n│ Binary Payload (if binaryLength > 0)    │\n└─────────────────────────────────────────┘\n```\n\n### Transport Implementations\n\n| Type | Use Case | Package |\n|------|----------|---------|\n| `PipeTransport` | Local Windows processes | `playwright-core` |\n| `StdioTransport` | Unix domain sockets | `playwright-core` |\n| `WebSocketTransport` | Remote/cloud browsers | `playwright-core` |\n\n资料来源：[packages/playwright-core/src/server/transport.ts:1-100]()\n\n### Connection Establishment\n\n```typescript\nclass Transport {\n  constructor(connection: Connection) {\n    this._connection = connection;\n  }\n\n  async connect(pipe: Pipe): Promise<void> {\n    // Establish connection to browser process\n  }\n\n  send(message: ProtocolMessage): void {\n    // Serialize and send message\n  }\n\n  async close(): Promise<void> {\n    // Graceful transport shutdown\n  }\n}\n```\n\n## Process Launcher\n\nThe `ProcessLauncher` utility provides cross-platform process spawning and management.\n\n### Launch Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `executablePath` | `string` | Path to browser executable |\n| `args` | `string[]` | Command-line arguments |\n| `env` | `Record<string,string>` | Environment variables |\n| `cwd` | `string` | Working directory |\n| `stdio` | `'pipe' \\| 'inherit'` | Standard IO mode |\n| `detach` | `boolean` | Run in detached mode |\n| `timeout` | `number` | Launch timeout in ms |\n\n资料来源：[packages/utils/processLauncher.ts:1-120]()\n\n### Process Monitoring\n\nThe launcher maintains process health through:\n\n1. **Exit detection** - Monitoring for unexpected process termination\n2. **Output capture** - Collecting stdout/stderr for debugging\n3. **Resource limits** - Optional memory and CPU limits\n4. **Cleanup hooks** - Automatic resource disposal on exit\n\n### Error Handling\n\n```typescript\ninterface LaunchError {\n  reason: 'executable-not-found' | 'timeout' | 'crash' | 'protocol-error';\n  message: string;\n  stack?: string;\n}\n```\n\n## Browser Type Registry\n\nEach browser type (Chromium, Firefox, WebKit) extends the base `BrowserType` class with browser-specific logic.\n\n### Browser Executable Resolution\n\n```mermaid\ngraph TD\n    A[launch called] --> B{Find browser?}\n    B -->|User path| C[Validate executable]\n    B -->|Default| D[Check installed browsers]\n    C -->|Valid| E[Launch browser]\n    C -->|Invalid| F[Throw error]\n    D -->|Found| E\n    D -->|Not found| G[Prompt installation]\n```\n\n### BrowserType Interface\n\n```typescript\ninterface BrowserType {\n  name(): string;\n  executablePath(): string;\n  launch(options?: LaunchOptions): Promise<Browser>;\n  launchServer(options?: LaunchOptions): Promise<BrowserServer>;\n  launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>;\n  executable(): string;\n  defaultArgs(options?: LaunchOptions): string[];\n}\n```\n\n资料来源：[packages/playwright-core/src/server/browserType.ts:100-200]()\n\n## Configuration Options\n\n### Common Launch Options\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `headless` | `true` | Run browser in headless mode |\n| `args` | `[]` | Additional browser arguments |\n| `channel` | `undefined` | Browser channel (e.g., 'chrome', 'msedge') |\n| `chromiumSandbox` | `true` | Enable Chromium sandbox (Linux) |\n| `devtools` | `false` | Open DevTools on launch |\n| `downloadPath` | `undefined` | Custom download directory |\n| `env` | `process.env` | Environment variables |\n| `executablePath` | `undefined` | Custom browser executable path |\n| `firefoxUserPrefs` | `{}` | Firefox-specific preferences |\n| `proxy` | `undefined` | Proxy configuration |\n| `timeout` | `30000` | Launch timeout in milliseconds |\n| `viewport` | `{ width: 1280, height: 720 }` | Default viewport size |\n\n### Browser-Specific Options\n\n#### Chromium\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `chromiumSandbox` | `boolean` | Enable Linux sandbox |\n| `proxy` | `ProxySettings` | HTTP/SOCKS proxy |\n| `downloadContentTypes` | `string[]` | Content types to download |\n\n#### Firefox\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `firefoxUserPrefs` | `Record<string, string \\| number \\| boolean>` | Gecko preferences |\n| `firefoxExtensionPaths` | `string[]` | Extension directories |\n\n#### WebKit\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `wkWebKitExperimentalSimulateSaturation` | `boolean` | Simulate saturation |\n| `wkWebKitExperimentalLayoutMetrics` | `boolean` | Enable layout metrics |\n\n## Integration with CLI Tools\n\nThe browser launch system integrates with Playwright's CLI tooling for interactive browser automation.\n\n### CLI Session Management\n\n```bash\n# Open browser with named session\nplaywright-cli -s=mysession open https://example.com\n\n# Create persistent profile\nplaywright-cli open https://example.com --persistent\n\n# Browser selection\nplaywright-cli open https://example.com --browser=firefox\n```\n\nThe CLI layer uses the same `BrowserType` APIs to establish browser sessions, with session state managed through the browser's context persistence mechanisms.\n\n## Best Practices\n\n### Resource Management\n\n1. **Always close browsers** - Use `browser.close()` in try/finally blocks\n2. **Handle launch failures** - Wrap launch calls in try/catch for graceful error handling\n3. **Use context isolation** - Launch separate contexts instead of separate browsers when possible\n4. **Set appropriate timeouts** - Adjust timeouts for slow environments\n\n### Launch Example\n\n```typescript\nimport { chromium } from 'playwright';\n\nasync function run() {\n  let browser;\n  try {\n    browser = await chromium.launch({\n      headless: true,\n      timeout: 30000,\n      args: ['--disable-gpu', '--no-sandbox'],\n    });\n    \n    const context = await browser.newContext();\n    const page = await context.newPage();\n    \n    // Perform actions...\n    \n  } catch (error) {\n    console.error('Browser launch failed:', error);\n  } finally {\n    if (browser) {\n      await browser.close();\n    }\n  }\n}\n```\n\n## Summary\n\nThe Browser Launch and Process Management system provides a robust foundation for browser automation in Playwright. By abstracting the complexities of process spawning, inter-process communication, and lifecycle management, it enables developers to work with browsers through a clean, consistent API regardless of the underlying browser type or execution environment.\n\nKey takeaways:\n\n- **Dual execution modes** support both isolated (OOP) and integrated (in-process) browser execution\n- **Transport abstraction** enables reliable message passing across different IPC mechanisms\n- **Lifecycle management** ensures proper resource cleanup and graceful degradation\n- **Browser type registry** provides consistent APIs across Chromium, Firefox, and WebKit\n\n---\n\n<a id='page-5'></a>\n\n## Test Runner and Execution Engine\n\n### 相关页面\n\n相关主题：[Playwright Introduction and Project Overview](#page-1), [Locators, Selectors, and Element Interaction](#page-6), [Assertions, Matchers, and Expect API](#page-7)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright/src/runner/testRunner.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/runner/testRunner.ts)\n- [packages/playwright/src/runner/dispatcher.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/runner/dispatcher.ts)\n- [packages/playwright/src/common/testLoader.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/common/testLoader.ts)\n- [packages/playwright/src/common/fixtures.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/common/fixtures.ts)\n- [packages/playwright/src/common/poolBuilder.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/common/poolBuilder.ts)\n- [packages/playwright/src/runner/workerHost.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/runner/workerHost.ts)\n- [packages/playwright/src/worker/workerMain.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/worker/workerMain.ts)\n</details>\n\n# Test Runner and Execution Engine\n\nThe Playwright Test Runner is the core execution engine responsible for discovering, scheduling, and running end-to-end tests across multiple browsers and processes. It provides a complete test isolation model, automatic retry logic, parallel execution, and seamless integration with fixtures for test setup and teardown.\n\n## Architecture Overview\n\nThe test runner follows a multi-process architecture designed for scalability and isolation. At a high level, it consists of a central **TestRunner** process that coordinates test execution, multiple **Worker** processes that execute tests in isolated browser contexts, and a **Dispatcher** that manages the assignment of tests to available workers.\n\n```mermaid\ngraph TD\n    A[TestRunner<br/>Main Process] --> B[Dispatcher<br/>Test Assignment]\n    B --> C[Worker Host 1<br/>Process]\n    B --> D[Worker Host 2<br/>Process]\n    B --> E[Worker Host N<br/>Process]\n    C --> F[Browser Context 1]\n    D --> G[Browser Context 2]\n    E --> H[Browser Context N]\n    F --> I[Page 1]\n    G --> J[Page 2]\n    H --> K[Page N]\n```\n\n### Core Components\n\n| Component | File Location | Responsibility |\n|-----------|---------------|----------------|\n| TestRunner | `packages/playwright/src/runner/testRunner.ts` | Entry point; orchestrates the full test run lifecycle |\n| Dispatcher | `packages/playwright/src/runner/dispatcher.ts` | Distributes tests to workers and tracks completion |\n| TestLoader | `packages/playwright/src/common/testLoader.ts` | Discovers and parses test files |\n| Fixtures | `packages/playwright/src/common/fixtures.ts` | Manages test fixtures and dependencies |\n| PoolBuilder | `packages/playwright/src/common/poolBuilder.ts` | Creates and manages browser context pools |\n| WorkerHost | `packages/playwright/src/runner/workerHost.ts` | Manages worker process lifecycle |\n| WorkerMain | `packages/playwright/src/worker/workerMain.ts` | Worker process entry point; runs actual tests |\n\n资料来源：[packages/playwright/src/runner/testRunner.ts:1-50]()\n资料来源：[packages/playwright/src/runner/dispatcher.ts:1-60]()\n\n## Test Discovery and Loading\n\nThe test discovery process begins with the **TestLoader**, which recursively scans the project for test files matching the configured patterns. Playwright supports both `.spec.ts` and `.spec.js` file extensions by default, though these patterns are fully configurable through `playwright.config.ts`.\n\n### Loading Pipeline\n\n```mermaid\ngraph LR\n    A[Test Files<br/>*.spec.ts] --> B[TestLoader]\n    B --> C[Parse Test Cases]\n    C --> D[Extract Fixtures]\n    D --> E[Build Test Tree]\n    E --> F[Dispatcher]\n```\n\nThe TestLoader performs the following operations:\n\n1. **File Discovery** — Scans the specified test directory for files matching the glob patterns defined in the configuration.\n2. **Syntax Parsing** — Parses each test file to extract `test`, `test.describe`, and `test.beforeEach` declarations.\n3. **Fixture Extraction** — Identifies fixture dependencies declared via `test.use()` or fixture function signatures.\n4. **Test Tree Construction** — Builds a hierarchical structure representing test suites and individual test cases.\n\n资料来源：[packages/playwright/src/common/testLoader.ts:1-80]()\n\n### Configuration Files\n\nPlaywright recognizes two primary configuration file formats:\n\n| File | Format | Priority |\n|------|--------|----------|\n| `playwright.config.ts` | TypeScript | Highest |\n| `playwright.config.js` | JavaScript | Lower |\n| `playwright.config.mjs` | ES Module | Lower |\n\nThe configuration defines critical execution parameters including:\n\n```typescript\n// Example playwright.config.ts structure\nexport default defineConfig({\n  timeout: 30000,           // Per-test timeout in milliseconds\n  retries: 0,               // Number of retries on failure\n  workers: process.env.CI ? 1 : undefined,  // Parallel workers\n  reporter: 'html',         // Output format\n  use: {\n    baseURL: 'http://localhost',\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: false,\n  },\n  projects: [\n    { name: 'chromium', use: { browserName: 'chromium' } },\n    { name: 'firefox', use: { browserName: 'firefox' } },\n    { name: 'webkit', use: { browserName: 'webkit' } },\n  ],\n});\n```\n\n资料来源：[package.json:test-scripts]()\n资料来源：[README.md:test-configuration]()\n\n## Worker Process Model\n\nEach worker process operates as an independent execution unit, running in a separate Node.js process for complete isolation. The **WorkerHost** manages the lifecycle of these processes, handling creation, communication, and graceful termination.\n\n### Worker Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Spawning: Start Worker\n    Spawning --> Initializing: Worker PID obtained\n    Initializing --> Ready: Fixtures initialized\n    Ready --> Running: Test assigned\n    Running --> Ready: Test complete\n    Running --> Retrying: Test failed, retries remaining\n    Retrying --> Running: Retry attempt\n    Retrying --> Failed: No retries left\n    Running --> Failed: Test failed, no retries\n    Ready --> Shutdown: All tests complete\n    Failed --> [*]: Worker terminated\n    Shutdown --> [*]: Cleanup complete\n```\n\n### Worker Communication\n\nWorkers communicate with the main process through an IPC (Inter-Process Communication) channel. The protocol supports the following message types:\n\n| Message Type | Direction | Purpose |\n|--------------|-----------|---------|\n| `init` | Main → Worker | Initialize worker with config |\n| `run` | Main → Worker | Execute a specific test |\n| `stop` | Main → Worker | Cancel running test |\n| `done` | Worker → Main | Report test result |\n| `error` | Worker → Main | Report runtime error |\n| `teardown` | Main → Worker | Graceful shutdown |\n\n资料来源：[packages/playwright/src/runner/workerHost.ts:1-100]()\n资料来源：[packages/playwright/src/worker/workerMain.ts:1-50]()\n\n## Dispatcher and Test Assignment\n\nThe **Dispatcher** is the central coordinator responsible for assigning tests to available workers while respecting configured parallelism limits. It maintains a queue of pending tests and dynamically allocates them based on worker availability.\n\n### Test Assignment Algorithm\n\n```mermaid\ngraph TD\n    A[Test Queue] --> B{Workers Available?}\n    B -->|Yes| C[Pop Next Test]\n    C --> D{Test has deps?}\n    D -->|No| E[Assign to available worker]\n    D -->|Yes| F[Wait for deps]\n    F --> D\n    E --> G[Execute Test]\n    G --> H[Test Result]\n    H --> I{Success?}\n    I -->|Yes| J[Mark complete]\n    I -->|No| K{Retries left?}\n    K -->|Yes| L[Re-queue for retry]\n    K -->|No| M[Mark failed]\n    J --> A\n    L --> A\n    M --> A\n```\n\nThe dispatcher implements the following strategies:\n\n- **Load Balancing** — Tests are distributed evenly across workers to maximize throughput.\n- **Retry Logic** — Failed tests are automatically re-queued up to the configured retry count.\n- **Serial Execution per Worker** — Each worker processes one test at a time to maintain isolation.\n- **Sharding** — Tests can be sharded across multiple machines using `--shard` flag.\n\n资料来源：[packages/playwright/src/runner/dispatcher.ts:50-200]()\n\n### Parallelism Configuration\n\n| Config Option | CLI Flag | Description |\n|---------------|----------|-------------|\n| `workers` | `--workers` | Number of parallel worker processes |\n| `retries` | `--retries` | Number of retry attempts per failed test |\n| `timeout` | `--timeout` | Per-test timeout in milliseconds |\n| `shard` | `--shard=N/M` | Shard tests across M machines, run shard N |\n\n```bash\n# Run with 4 workers\nnpx playwright test --workers=4\n\n# Run with retries and extended timeout\nnpx playwright test --retries=2 --timeout=60000\n\n# Run shard 1 of 3\nnpx playwright test --shard=1/3\n```\n\n## Fixture System\n\nFixtures provide a dependency injection mechanism for test setup and teardown. They ensure that resources are properly initialized before tests run and cleaned up afterward.\n\n### Fixture Types\n\n| Type | Scope | Usage |\n|------|-------|-------|\n| `static` | Across all tests | Global configuration |\n| `worker` | Per worker process | Shared within one worker |\n| `test` | Per test execution | Fresh for each test |\n| `session` | Across all workers | Shared global state |\n\n```typescript\nimport { test as baseTest, expect } from '@playwright/test';\n\n// Define a fixture with automatic cleanup\nexport const test = baseTest.extend({\n  // Auto-cleanup database for each test\n  database: async ({}, use) => {\n    const db = await createTestDatabase();\n    await use(db);\n    await db.cleanup();\n  },\n  \n  // Reuse authenticated page across all tests in a worker\n  authenticatedPage: async ({ browser }, use) => {\n    const context = await browser.newContext();\n    const page = await context.newPage();\n    await page.goto('/login');\n    await page.fill('#username', 'testuser');\n    await page.fill('#password', 'testpass');\n    await page.click('#submit');\n    await use(page);\n    await context.close();\n  },\n});\n```\n\n资料来源：[packages/playwright/src/common/fixtures.ts:1-100]()\n\n### Built-in Fixtures\n\nPlaywright provides several built-in fixtures that are automatically available to all tests:\n\n| Fixture | Type | Description |\n|---------|------|-------------|\n| `page` | `test` | Fresh page for each test |\n| `context` | `test` | Fresh browser context |\n| `browser` | `worker` | Browser instance shared in worker |\n| `request` | `test` | APIRequestContext for REST testing |\n| `火` | `test` | Playwright test object |\n\n## Browser Context Pooling\n\nThe **PoolBuilder** manages a pool of browser contexts to optimize resource usage. Rather than creating a new context for each test (which can be expensive), the pool maintains a set of reusable contexts.\n\n### Pooling Strategy\n\n```mermaid\ngraph TD\n    A[Test Request] --> B{Idle Context Available?}\n    B -->|Yes| C[Use Pooled Context]\n    B -->|No| D{Max Pool Size Reached?}\n    D -->|No| E[Create New Context]\n    D -->|Yes| F[Wait for Available]\n    E --> C\n    F --> C\n    C --> G[Test Execution]\n    G --> H{Context Satisfies Test?}\n    H -->|Yes| I[Return to Pool]\n    H -->|No| J[Destroy Context]\n    J --> K[Create Fresh Context]\n    K --> I\n```\n\n### Context Configuration\n\nEach project can define its own context configuration:\n\n```typescript\nexport default defineConfig({\n  projects: [\n    {\n      name: 'chromium',\n      use: {\n        browserName: 'chromium',\n        viewport: { width: 1920, height: 1080 },\n        permissions: ['geolocation'],\n        storageState: './auth.json',\n        launchOptions: {\n          args: ['--disable-dev-shm-usage'],\n        },\n      },\n    },\n  ],\n});\n```\n\n资料来源：[packages/playwright/src/common/poolBuilder.ts:1-80]()\n\n## Debug Mode and CLI Integration\n\nPlaywright provides a CLI-based debugging mode that allows interactive inspection of test execution. When running with `--debug=cli`, the test runner pauses at the start and exposes a debug session.\n\n### Debug Workflow\n\n```mermaid\ngraph TD\n    A[npx playwright test --debug=cli] --> B[Test Paused at Start]\n    B --> C[Debugging Instructions<br/>Session: tw-XXXX]\n    C --> D[playwright-cli attach tw-XXXX]\n    D --> E[Interactive Commands]\n    E --> F[snapshot, click, fill, etc.]\n    F --> G[Test Continues]\n    G --> H[Capture Results]\n    H --> I[Generate Report]\n```\n\n### Debug Commands\n\n| Command | Purpose |\n|---------|---------|\n| `playwright-cli snapshot` | Get current page snapshot with element refs |\n| `playwright-cli click <ref>` | Click an element by its reference |\n| `playwright-cli fill <ref> <text>` | Fill input field |\n| `playwright-cli eval <expression>` | Execute JavaScript in page context |\n| `playwright-cli resume` | Continue test execution |\n| `playwright-cli screenshot` | Capture current page state |\n\n```bash\n# Start test in debug mode\nPLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli\n\n# In another terminal, attach to the debug session\nplaywright-cli attach tw-abcdef\n\n# Explore the page\nplaywright-cli snapshot\nplaywright-cli click e15\nplaywright-cli eval \"document.title\"\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md:1-50]()\n\n## Tracing and Debugging\n\nPlaywright includes a comprehensive tracing system that captures detailed execution information for post-mortem analysis.\n\n### Trace Contents\n\n| Category | Captured Data |\n|----------|---------------|\n| **Actions** | Clicks, fills, navigations with timestamps |\n| **DOM Snapshots** | Before/after state for each action |\n| **Screenshots** | Visual state at key moments |\n| **Network** | All HTTP requests/responses |\n| **Console** | Console.log output and errors |\n| **Errors** | Stack traces for failures |\n\n### Trace Commands\n\n```bash\n# Open a trace file\nnpx playwright trace open trace.zip\n\n# List all actions\nnpx playwright trace actions\n\n# View specific action details\nnpx playwright trace action <action-id>\n\n# Get DOM snapshot at an action\nnpx playwright trace snapshot <action-id>\n\n# View console errors\nnpx playwright trace console --errors-only\n```\n\n```mermaid\ngraph LR\n    A[Test Execution] --> B[trace-{timestamp}.trace]\n    A --> C[trace-{timestamp}.network]\n    A --> D[resources/]\n    B --> E[Action Log]\n    C --> F[Network Activity]\n    D --> G[Cached Assets]\n    E --> H[Trace Viewer]\n    F --> H\n    G --> H\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md:1-80]()\n\n## Execution Flow Summary\n\nThe complete test execution flow follows these stages:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant TestRunner\n    participant TestLoader\n    participant Dispatcher\n    participant WorkerHost\n    participant Worker\n\n    User->>TestRunner: npx playwright test\n    TestRunner->>TestLoader: Load tests\n    TestLoader-->>TestRunner: Test tree\n    TestRunner->>Dispatcher: Initialize\n    TestRunner->>WorkerHost: Spawn workers\n    WorkerHost->>Worker: Start process\n    \n    loop For each test\n        Dispatcher->>WorkerHost: Assign test\n        WorkerHost->>Worker: Run test\n        Worker->>PoolBuilder: Request context\n        PoolBuilder-->>Worker: Context\n        Worker->>Fixtures: Setup fixtures\n        Fixtures-->>Worker: Fixture values\n        Worker->>Worker: Execute test body\n        Worker->>Fixtures: Teardown fixtures\n        Worker-->>WorkerHost: Test result\n        WorkerHost-->>Dispatcher: Result\n    end\n    \n    Dispatcher-->>TestRunner: All complete\n    TestRunner->>User: Report\n```\n\n## Command-Line Interface\n\n### Common Commands\n\n| Command | Description |\n|---------|-------------|\n| `npx playwright test` | Run all tests |\n| `npx playwright test <file>` | Run specific file |\n| `npx playwright test --debug` | Run in debug mode |\n| `npx playwright test --list` | List all tests without running |\n| `npx playwright show-report` | Open HTML report |\n\n### Configuration via CLI\n\n```bash\n# Override config values\nnpx playwright test --project=chromium --timeout=30000\n\n# Run only matching tests\nnpx playwright test --grep=\"login\"\n\n# Run only failed tests from last run\nnpx playwright test --last-failed\n\n# Update snapshots\nnpx playwright test --update-snapshots\n```\n\n## Integration with Trace Viewer\n\nThe trace viewer is a Progressive Web App that opens trace files locally without sending data anywhere. It provides visual debugging capabilities.\n\n```mermaid\ngraph TD\n    A[Trace.zip] --> B[WorkbenchLoader]\n    B --> C[TraceModel]\n    C --> D[Actions Panel]\n    C --> E[Screenshots Panel]\n    C --> F[Network Panel]\n    C --> G[Console Panel]\n    D --> H[Unified Timeline]\n    E --> H\n    F --> H\n    G --> H\n```\n\nTo use the trace viewer:\n\n1. Run a test that generates a trace (using `trace: 'on'` in config)\n2. Locate the trace file in `test-results/<test-name>/trace.zip`\n3. Open at [trace.playwright.dev](https://trace.playwright.dev) or via CLI\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx:1-60]()\n\n## Summary\n\nThe Playwright Test Runner provides a production-grade testing infrastructure with:\n\n- **Multi-process isolation** ensuring test independence\n- **Automatic resource management** through fixture cleanup\n- **Flexible parallelism** configurable per project and CI environment\n- **Rich debugging** via CLI integration and trace playback\n- **Cross-browser support** executing tests on Chromium, Firefox, and WebKit\n- **Comprehensive reporting** with built-in HTML reports and trace viewer\n\nThe architecture cleanly separates concerns between test discovery (TestLoader), orchestration (Dispatcher), execution (Workers), and resource management (Fixtures, PoolBuilder), making it both maintainable and extensible.\n\n---\n\n<a id='page-6'></a>\n\n## Locators, Selectors, and Element Interaction\n\n### 相关页面\n\n相关主题：[Test Runner and Execution Engine](#page-5), [Assertions, Matchers, and Expect API](#page-7)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/client/locator.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/locator.ts)\n- [packages/injected/src/selectorEngine.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/selectorEngine.ts)\n- [packages/injected/src/selectorGenerator.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/selectorGenerator.ts)\n- [packages/injected/src/roleSelectorEngine.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleSelectorEngine.ts)\n- [packages/injected/src/selectorEvaluator.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/selectorEvaluator.ts)\n- [packages/injected/src/injectedScript.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/injectedScript.ts)\n- [packages/playwright-core/src/server/selectors.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/selectors.ts)\n</details>\n\n# Locators, Selectors, and Element Interaction\n\nThis page describes how Playwright locates DOM elements and interacts with them programmatically. The system consists of client-side Locator APIs, an in-browser Injected Script that evaluates selectors, and a server-side Selector Manager that registers and manages selector engines.\n\n## Architecture Overview\n\nPlaywright uses a layered architecture for element location:\n\n| Layer | Package | Responsibility |\n|-------|---------|----------------|\n| **Client API** | `playwright-core/src/client/locator.ts` | Fluent locator interface exposed to test authors |\n| **Server Manager** | `playwright-core/src/server/selectors.ts` | Registers selector engines, manages context |\n| **Injected Script** | `packages/injected/src/` | Runs in browser context, evaluates selectors |\n\n```mermaid\ngraph TD\n    A[Test Author Code] --> B[Locator API]\n    B --> C[Selector Manager]\n    C --> D[Registered Selector Engines]\n    D --> E[Injected Script]\n    E --> F[Browser DOM]\n    \n    B -->|locator.click/hover/fill| G[Action Commands]\n    E -->|querySelector, querySelectorAll| F\n```\n\n资料来源：[packages/playwright-core/src/client/locator.ts](packages/playwright-core/src/client/locator.ts)  \n资料来源：[packages/playwright-core/src/server/selectors.ts](packages/playwright-core/src/server/selectors.ts)\n\n## Locator API\n\nThe `Locator` class provides a fluent API for finding and interacting with elements. It differs from `ElementHandle` by using *strict* mode by default and automatically retrying until elements are actionable.\n\n### Core Locator Methods\n\n| Method | Description |\n|--------|-------------|\n| `click()` | Click the element |\n| `fill()` | Fill input field with text |\n| `hover()` | Hover over element |\n| `dblclick()` | Double-click element |\n| `check()` / `uncheck()` | Toggle checkbox/radio |\n| `selectOption()` | Select option(s) from dropdown |\n| `scrollIntoViewIfNeeded()` | Scroll element into view |\n| `tap()` | Perform tap gesture |\n| `dragAndDrop()` | Drag and drop operations |\n\n### Locator vs ElementHandle\n\n| Aspect | Locator | ElementHandle |\n|--------|---------|---------------|\n| Evaluation | Re-evaluated on each action | Captured once |\n| Strict mode | Enabled by default | Must be manually enforced |\n| Retries | Auto-retries until actionable | Single attempt |\n| Shadow DOM | Traverses automatically | Manual shadow traversal |\n\nThe injected script exposes locator helpers via `window.playwright`:\n\n```typescript\nthis._injectedScript.window.playwright = {\n  $: (selector: string, strict?: boolean) => this._querySelector(selector, !!strict),\n  $$: (selector: string) => this._querySelectorAll(selector),\n  inspect: (selector: string) => this._inspect(selector),\n  selector: (element: Element) => this._selector(element),\n  generateLocator: (element: Element, language?: Language) => this._generateLocator(element, language),\n  ariaSnapshot: (element?: Element, options?: AriaTreeOptions) => { ... },\n  resume: () => this._resume(),\n  ...new Locator(this._injectedScript, ''),\n};\n```\n\n资料来源：[packages/injected/src/consoleApi.ts:1-30](packages/injected/src/consoleApi.ts)\n\n## Selector Engine Architecture\n\nPlaywright supports multiple built-in selector engines that can be combined using the `>>` combinator.\n\n### Selector Engine Types\n\n| Engine | Prefix | Example | Description |\n|--------|--------|---------|-------------|\n| **CSS** | (default) | `div.button` | Standard CSS selectors |\n| **Role** | `role/` | `role=button[name=\"Submit\"]` | ARIA role matching |\n| **Text** | `text/` | `text=\"Log In\"` | Text content matching |\n| **Test ID** | `testId=` | `testId=submit-btn` | `data-testid` attribute |\n| **Label** | `label=` | `label=Username` | Form label association |\n| **Alt Text** | `alt=` | `alt=Profile Photo` | Image alt attributes |\n| **Title** | `title=` | `title=Settings` | Title attribute |\n| **XPath** | `xpath=` | `xpath=//button[1]` | XPath expressions |\n| **Regex** | `/regex/` | `/^submit.*$/i` | Pattern matching |\n\n### Selector Evaluation Flow\n\n```mermaid\ngraph LR\n    A[Selector String] --> B[Parse & Split by >>]\n    B --> C[Engine Registry Lookup]\n    C --> D{Engine Type?}\n    D -->|CSS| E[query/queryAll]\n    D -->|Role| F[Role Selector Engine]\n    D -->|Text| G[Text Selector Engine]\n    D -->|Other| H[Custom Engine]\n    E --> I[Evaluate in DOM]\n    F --> I\n    G --> I\n    H --> I\n    I --> J[Match Results]\n```\n\n### Engine Registration\n\nSelector engines are registered with the `SelectorEngine` class:\n\n```typescript\ntype SelectorEngine = {\n  name: string;\n  create?(root: Preview<Element>, target: Element, context: SelectorInjectedContext): Selector;\n  query(root: Element, selector: Selector): Element | null;\n  queryAll?(root: Element, selector: Selector): Element[];\n};\n```\n\n资料来源：[packages/injected/src/selectorEngine.ts](packages/injected/src/selectorEngine.ts)\n\n## Role Selector Engine\n\nThe role selector engine matches elements by their ARIA role with optional name and properties filters.\n\n### Supported ARIA Roles\n\nThe engine recognizes all standard ARIA roles including: `button`, `link`, `checkbox`, `radio`, `textbox`, `searchbox`, `combobox`, `listbox`, `menu`, `menuitem`, `tab`, `tablist`, `dialog`, `alertdialog`, and many more.\n\n### Role Selector Syntax\n\n```bash\nrole=button[name=\"Submit\"]\nrole=link[name=\"Documentation\"]\nrole=textbox[name=\"Email\"][include-hidden]\nrole=menuitemcheckbox[name=\"Bold\"][checked]\n```\n\n### Role Matching Logic\n\n```mermaid\ngraph TD\n    A[Input: role=button] --> B[Get all elements with role=button]\n    B --> C{has name filter?}\n    C -->|Yes| D[Filter by accessible name]\n    C -->|No| E[Return all matches]\n    D --> F{Matches found?}\n    F -->|Yes| E\n    F -->|No| G[Return empty]\n    E --> H[Apply other filters]\n```\n\n资料来源：[packages/injected/src/roleSelectorEngine.ts](packages/injected/src/roleSelectorEngine.ts)\n\n## Selector Evaluator\n\nThe `SelectorEvaluator` class performs actual DOM matching using registered engines.\n\n### Key Methods\n\n| Method | Signature | Purpose |\n|--------|-----------|---------|\n| `query` | `(selector: ParsedSelector, root: Element, strict: boolean)` | Find single element |\n| `queryAll` | `(selector: ParsedSelector, root: Element)` | Find all matches |\n| `parseSelector` | `(selector: string)` | Parse selector string |\n| `preusable` | `()` | Create context for reuse |\n\n### Selector Parsing\n\nSelectors are parsed into a structured format:\n\n```typescript\ntype ParsedSelector = {\n  parsed: {\n    engineName: string;\n    strict: boolean;\n    chain: {\n      engine: string;\n      selector: string;\n      distance: number;\n      shadow: ShadowRootLevel[];\n    }[];\n  };\n};\n```\n\n资料来源：[packages/injected/src/selectorEvaluator.ts](packages/injected/src/selectorEvaluator.ts)\n\n## Selector Generator\n\nThe selector generator suggests optimal selectors for elements during codegen and when using `playwright codegen`.\n\n### Generation Strategy\n\n| Priority | Selector Type | Example |\n|----------|---------------|---------|\n| 1 | Test ID | `[data-testid=\"submit\"]` |\n| 2 | Accessible | `role=button[name=\"Submit\"]` |\n| 3 | Text | `text=\"Submit\"` |\n| 4 | CSS | `#submit-btn` |\n| 5 | Relative | `nth=5` |\n\n### Generator Implementation\n\nThe generator analyzes elements and ranks candidate selectors by:\n\n1. **Uniqueness** - Does this selector match exactly one element?\n2. **Stability** - Will this selector survive UI changes?\n3. **Readability** - Is this selector meaningful to humans?\n4. **Brevity** - Shorter selectors preferred when equivalent\n\n资料来源：[packages/injected/src/selectorGenerator.ts](packages/injected/src/selectorGenerator.ts)\n\n## Injected Script Integration\n\nThe `InjectedScript` class provides the bridge between Node.js and browser contexts.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[Playwright Node.js] -->|Evaluate| B[InjectedScript]\n    B --> C[Query Selector Engines]\n    B --> D[Locator Generation]\n    B --> E[ARIA Snapshot]\n    B --> F[Console API]\n    \n    C --> G[DOM Manipulation]\n    D --> H[Selector Suggestions]\n    E --> I[Accessibility Tree]\n    \n    G --> J[User Actions]\n    J -->|click, hover, type| K[Event Dispatch]\n```\n\n### Console API Methods\n\n| Method | Description |\n|--------|-------------|\n| `playwright.$()` | Query single element |\n| `playwright.$$()` | Query all elements |\n| `playwright.inspect()` | Highlight element |\n| `playwright.selector()` | Generate selector for element |\n| `playwright.generateLocator()` | Generate in specific language |\n| `playwright.ariaSnapshot()` | Get accessibility snapshot |\n\n资料来源：[packages/injected/src/injectedScript.ts](packages/injected/src/injectedScript.ts)\n\n## Using Locators with playwright-cli\n\nThe CLI tool supports all selector types for element interaction:\n\n### Element Targeting Methods\n\n```bash\n# Using snapshot refs (from playwright-cli snapshot)\nplaywright-cli click e15\n\n# CSS selectors\nplaywright-cli click \"#main > button.submit\"\n\n# Role locators\nplaywright-cli click \"getByRole('button', { name: 'Submit' })\"\n\n# Test IDs\nplaywright-cli click \"getByTestId('submit-button')\"\n```\n\n### Interaction Commands\n\n| Command | Description | Example |\n|---------|-------------|---------|\n| `click` | Click element | `playwright-cli click e5` |\n| `fill` | Type into input | `playwright-cli fill e4 \"hello world\"` |\n| `hover` | Hover over element | `playwright-cli hover e4` |\n| `select` | Select dropdown option | `playwright-cli select e9 \"option-value\"` |\n| `check/uncheck` | Toggle checkbox | `playwright-cli check e12` |\n| `drag` | Drag and drop | `playwright-cli drop e4 --data=\"text/plain=hello\"` |\n| `upload` | Upload file | `playwright-cli upload ./document.pdf` |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n## Selector Manager\n\nThe server-side `SelectorManager` handles registration and lifecycle of selector engines across browser contexts.\n\n### Manager Responsibilities\n\n| Responsibility | Description |\n|----------------|-------------|\n| Engine Registration | Register built-in and custom engines |\n| Context Management | Create/destroy selector contexts |\n| Session Handling | Maintain state across browser sessions |\n| Channel Communication | Bridge between server and injected script |\n\n### Custom Selector Registration\n\n```typescript\n// Register a custom selector engine\nawait test.selectors.register({\n  name: 'my-selector',\n  query: async (root, selector) => {\n    return root.querySelector(selector);\n  },\n  queryAll: async (root, selector) => {\n    return [...root.querySelectorAll(selector)];\n  }\n});\n```\n\n资料来源：[packages/playwright-core/src/server/selectors.ts](packages/playwright-core/src/server/selectors.ts)\n\n## Element Interaction Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Test Code\n    participant L as Locator API\n    participant S as Selector Manager\n    participant I as Injected Script\n    participant B as Browser DOM\n\n    T->>L: locator.click(\"button\")\n    L->>S: query(\"button\")\n    S->>I: evaluate querySelector\n    I->>B: query DOM\n    B->>I: return Element\n    I->>S: return Element\n    S->>L: return Element\n    L->>L: waitForElement\n    L->>T: click complete\n```\n\n## Best Practices\n\n### Preferred Selector Order\n\n1. **Test IDs** (`data-testid`) — Most stable and explicit\n2. **Role + Name** — Semantically meaningful and accessible\n3. **Text Content** — Human-readable but may change\n4. **CSS Classes/IDs** — Fast but brittle\n5. **XPath** — Last resort; hard to maintain\n\n### Anti-Patterns to Avoid\n\n| Anti-Pattern | Problem | Alternative |\n|--------------|---------|-------------|\n| Index-based `nth=` | Breaks with layout changes | Use role/name filtering |\n| Deep CSS paths | Fragile to DOM changes | Use semantic selectors |\n| Dynamic attributes | Unstable in CI | Use stable test IDs |\n| Coordinates | Resolution-dependent | Use element targets |\n\n## Summary\n\nPlaywright's locator and selector system provides a flexible, multi-engine approach to DOM element identification:\n\n- **Locator API** offers a fluent, retry-based interface for test authors\n- **Multiple selector engines** handle CSS, ARIA roles, text, and custom selectors\n- **Injected Script** enables browser-side evaluation without round-trips\n- **Selector Generator** helps discover optimal selectors during development\n\nThe architecture prioritizes accessibility (role selectors), stability (test IDs), and developer experience (fluent API) while maintaining performance through optimized DOM queries.\n\n---\n\n<a id='page-7'></a>\n\n## Assertions, Matchers, and Expect API\n\n### 相关页面\n\n相关主题：[Test Runner and Execution Engine](#page-5), [Locators, Selectors, and Element Interaction](#page-6)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright/src/matchers/expect.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/expect.ts)\n- [packages/playwright/src/matchers/matchers.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/matchers.ts)\n- [packages/playwright/src/matchers/toMatchSnapshot.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/toMatchSnapshot.ts)\n- [packages/playwright/src/matchers/toMatchAriaSnapshot.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/toMatchAriaSnapshot.ts)\n- [packages/isomorphic/expectUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/expectUtils.ts)\n- [packages/isomorphic/assert.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/assert.ts)\n</details>\n\n# Assertions, Matchers, and Expect API\n\nPlaywright's assertion system provides a powerful, auto-retrying mechanism for validating application state during end-to-end testing. The `expect` API combined with matchers enables test authors to write expressive, readable assertions that automatically wait for conditions to be met rather than requiring manual polling or arbitrary timeouts.\n\n## Overview\n\nPlaywright's assertion framework is built on three core concepts that work together to provide reliable test assertions:\n\n| Component | Purpose |\n|-----------|---------|\n| **Expect API** | Core assertion function that wraps values and provides matcher methods |\n| **Matchers** | Individual comparison functions that validate specific conditions |\n| **Expect Utils** | Shared utility functions for handling timeouts, polling, and error messages |\n\nThe architecture follows a layered approach where the `expect` function creates an expectation object that chains matcher methods. Each matcher returns either a pass result or throws an error with detailed context about what failed.\n\n```mermaid\ngraph TD\n    A[Test Code] --> B[expect value]\n    B --> C[Expectation Object]\n    C --> D[Matcher Methods]\n    D --> E{Auto-retry Loop}\n    E -->|condition met| F[Pass - Continue]\n    E -->|condition not met| G[Wait and Retry]\n    G --> E\n    E -->|timeout exceeded| H[Throw ExpectationError]\n    F --> I[Test Continues]\n    H --> J[Test Fails]\n```\n\n## Core Files and Structure\n\n### Expect Implementation\n\nThe main `expect` function is defined in `packages/playwright/src/matchers/expect.ts`. This file exports the `expect` function and the `Expect` class that handles the retry logic and matcher invocation.\n\nKey responsibilities:\n- Creating expectation objects from actual values\n- Managing auto-retry mechanisms with configurable timeouts\n- Formatting error messages with expected vs. actual values\n- Supporting both synchronous and asynchronous expectations\n\n### Matchers Module\n\nThe matchers are defined in `packages/playwright/src/matchers/matchers.ts`. This file contains all built-in matcher functions that can be chained off the `expect` call.\n\n### Isomorphic Utilities\n\nShared assertion utilities in `packages/isomorphic/expectUtils.ts` and `packages/isomorphic/assert.ts` provide platform-agnostic functionality used across different Playwright packages.\n\n## Expect API Reference\n\n### Basic Usage\n\n```typescript\nimport { test, expect } from '@playwright/test';\n\ntest('login page', async ({ page }) => {\n  await page.goto('/login');\n  \n  // Basic equality assertion\n  await expect(page).toHaveTitle('Login');\n  \n  // Locator assertion with auto-wait\n  await expect(page.getByRole('button', { name: 'Submit' })).toBeVisible();\n  \n  // Text content assertion\n  await expect(page.locator('.error')).toHaveText('Invalid credentials');\n});\n```\n\n### Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `timeout` | `number` | Matcher's default | Maximum time to retry the assertion |\n| `message` | `string \\| function` | auto-generated | Custom error message on failure |\n| `containsText` | `string \\| RegExp` | - | Pattern that should appear in error |\n\n## Built-in Matchers\n\n### Web-First Assertions\n\nPlaywright provides specialized \"web-first\" assertions optimized for UI testing. These assertions automatically wait for the expected state before failing.\n\n#### Visibility and Presence\n\n| Matcher | Description |\n|---------|-------------|\n| `toBeVisible()` | Element is visible and not obscured |\n| `toBeHidden()` | Element is not visible |\n| `toBeAttached()` | Element is present in DOM |\n| `toBeEnabled()` | Element is enabled (not disabled) |\n| `toBeDisabled()` | Element is disabled |\n| `toBeEditable()` | Element is editable |\n| `toBeFocused()` | Element has focus |\n\n#### Content Assertions\n\n| Matcher | Description |\n|---------|-------------|\n| `toHaveText(expected, options?)` | Element contains exact or partial text |\n| `toContainText(expected)` | Element contains text (partial match) |\n| `toHaveValue(value)` | Input element has specific value |\n| `toHaveValues(values)` | Multiple select or checkbox group values |\n| `toHaveTitle(title)` | Page has specific title |\n| `toHaveURL(url)` | Page has specific URL |\n| `toHaveScreenshot(name, options?)` | Element/page matches screenshot |\n\n#### Form and Input Assertions\n\n| Matcher | Description |\n|---------|-------------|\n| `toBeChecked()` | Checkbox or radio is checked |\n| `toHaveChecked()` | Checkbox with specific state |\n| `toBeSelected()` | Option is selected in select element |\n| `toBeRequired()` | Input is marked as required |\n| `toBeValid()` | Input passes validation constraints |\n\n### Negation\n\nAll matchers support negation using `.not`:\n\n```typescript\nawait expect(page.getByRole('button')).not.toBeDisabled();\nawait expect(page.locator('.loading')).not.toBeVisible();\n```\n\n## Snapshot Testing\n\nPlaywright supports snapshot testing through dedicated matchers that compare rendered output against stored baselines.\n\n### Visual Snapshots\n\nThe `toMatchSnapshot` matcher captures and compares images:\n\n```typescript\ntest('screenshot comparison', async ({ page }) => {\n  await page.goto('/dashboard');\n  await expect(page).toMatchScreenshot('dashboard.png', {\n    fullPage: true,\n    animations: 'disabled'\n  });\n});\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | Snapshot file name |\n| `options?.fullPage` | `boolean` | Capture entire scrollable page |\n| `options?.animations` | `'disabled' \\| 'allow'` | Animation handling |\n| `options?.mask` | `locator[]` | Elements to mask in screenshot |\n| `options?.threshold` | `number` | Pixel matching threshold 0-1 |\n\n### Aria Snapshots\n\nThe `toMatchAriaSnapshot` matcher compares the semantic structure of the page:\n\n```typescript\ntest('page structure', async ({ page }) => {\n  await page.goto('/form');\n  await expect(page).toMatchAriaSnapshot(`\n    - heading \"Create Account\"\n    - textbox \"Email\"\n    - textbox \"Password\"\n    - button \"Submit\"\n  `);\n});\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `snapshot` | `string` | Expected ARIA tree structure |\n| `options?.timeout` | `number` | Retry timeout in ms |\n| `options?.matcher` | `string \\| RegExp` | Custom snapshot matcher |\n\n### Updating Snapshots\n\nWhen UI changes are intentional, update snapshots using the CLI:\n\n```bash\nnpx playwright test --update-snapshots\n# or\nnpx playwright test -u\n```\n\n## Custom Matchers\n\n### Defining Custom Matchers\n\nExtend the `expect` object with custom matchers for project-specific assertions:\n\n```typescript\n// expect.d.ts or custom expect file\nimport { expect as baseExpect } from '@playwright/test';\n\nexport { test } from '@playwright/test';\n\nexport const expect = baseExpect.extend({\n  async toHaveAnalyticsEvent(\n    locator: Locator,\n    eventName: string,\n    options?: { timeout?: number }\n  ) {\n    const timeout = options?.timeout ?? 1000;\n    const analyticsData: string[] = [];\n    \n    const listener = (event: ConsoleMessage) => {\n      if (event.type() === 'log') {\n        analyticsData.push(event.text());\n      }\n    };\n    \n    locator.page().on('console', listener);\n    \n    try {\n      await page.waitForFunction(\n        (name) => window.analytics?.events?.includes(name),\n        eventName,\n        { timeout }\n      );\n      return { pass: true };\n    } catch {\n      return {\n        pass: false,\n        message: () => `Expected analytics event \"${eventName}\" was not fired`,\n      };\n    } finally {\n      locator.page().off('console', listener);\n    }\n  },\n});\n```\n\n### Using Custom Matchers\n\n```typescript\nimport { expect } from './expect';\n\ntest('analytics tracking', async ({ page }) => {\n  await page.goto('/products');\n  await page.click('.buy-button');\n  \n  // Uses custom matcher\n  await expect(page).toHaveAnalyticsEvent('purchase_initiated');\n});\n```\n\n## Auto-Retry Behavior\n\nPlaywright assertions automatically retry until the condition is met or timeout expires. This eliminates flaky tests caused by timing issues.\n\n### Retry Loop Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Test\n    participant E as Expect\n    participant M as Matcher\n    participant P as Page\n\n    T->>E: expect(locator).toBeVisible()\n    Note over E: Create Expectation\n    loop Retry until timeout\n        E->>M: Compare current state\n        M->>P: Query element state\n        alt Condition met\n            M-->>E: Pass\n            E-->>T: Continue\n        else Condition not met\n            M-->>E: Fail\n            E->>E: Wait (default: 100ms)\n        end\n    end\n    Note over E: Timeout exceeded\n    E-->>T: Throw ExpectationError\n```\n\n### Timeout Configuration\n\n```typescript\n// Per-assertion timeout\nawait expect(page.locator('.loading')).toBeHidden({ timeout: 5000 });\n\n// Global default timeout\n// In playwright.config.ts:\nexport default {\n  expect: {\n    timeout: 5000,\n  },\n};\n```\n\n### Timeout Inheritance\n\n| Configuration Location | Value |\n|------------------------|-------|\n| Assertion option | `{ timeout: 3000 }` |\n| `expect` config section | `5000` |\n| Test fixture | Inherited |\n| Default | `1000` (1 second) |\n\n## Error Messages\n\nPlaywright generates detailed, actionable error messages when assertions fail.\n\n### Error Message Structure\n\n```\nexpect(received).toHaveText(expected)\n\nExpected string: \"Welcome, John\"\nReceived string: \"Welcome, Guest\"\n```\n\n### Custom Messages\n\n```typescript\nawait expect(page.locator('.balance')).toHaveText(\n  '$100.00',\n  { message: 'Balance should reflect completed transaction' }\n);\n\n// Or use a function for dynamic messages\nawait expect(page.locator('.status')).toHaveText(\n  'Active',\n  { message: () => `Expected status for user ${userId} to be Active` }\n);\n```\n\n## TypeScript Integration\n\n### Type Safety\n\nAll matchers are fully typed and provide autocomplete support:\n\n```typescript\n// TypeScript infers expected type\nawait expect(page.locator('input')).toHaveValue('hello');\n\n// For complex matchers, types are enforced\nawait expect(page).toHaveScreenshot('button.png', {\n  // options type is inferred\n  fullPage: true,\n  animations: 'disabled'\n});\n```\n\n### Generic Assertions\n\nFor custom assertion types, use generics:\n\n```typescript\nexpect.extend({\n  async toHaveData属性<T>(\n    this: jest.MatcherContext,\n    received: T,\n    key: string,\n    value: unknown\n  ) {\n    const data = (received as any)[key];\n    return {\n      pass: data === value,\n      message: () => `Expected ${key} to be ${value}, got ${data}`,\n    };\n  },\n});\n```\n\n## Best Practices\n\n### Prefer Web-First Assertions\n\nAlways use Playwright's built-in web-first assertions over raw comparisons:\n\n```typescript\n// ❌ Fragile - no auto-wait\nexpect(await page.textContent('button')).toBe('Submit');\n\n// ✅ Reliable - auto-waits and handles timing\nawait expect(page.getByRole('button')).toHaveText('Submit');\n```\n\n### Combine Matchers\n\nChain multiple matchers for comprehensive checks:\n\n```typescript\nawait expect(page.getByRole('textbox', { name: 'Email' }))\n  .toBeVisible()\n  .toBeEnabled()\n  .toBeFocused()\n  .toHaveAttribute('type', 'email');\n```\n\n### Use Descriptive Names\n\nName expectations clearly for better test output:\n\n```typescript\n// ❌ Unclear\nawait expect(page.locator('.main')).toHaveScreenshot('shot.png');\n\n// ✅ Clear intent\nawait expect(page).toMatchScreenshot('checkout-page-cart-items.png');\n```\n\n## Summary\n\nThe Assertions, Matchers, and Expect API form the foundation of Playwright's verification capabilities. Key takeaways:\n\n| Aspect | Key Point |\n|--------|-----------|\n| **Auto-retry** | Assertions automatically wait for conditions, reducing flakiness |\n| **Web-first** | Built specifically for dynamic web applications |\n| **Rich matchers** | Comprehensive set of UI-specific assertions |\n| **Snapshot support** | Visual and semantic snapshot testing built-in |\n| **Extensibility** | Custom matchers via `expect.extend` |\n| **TypeScript** | Full type safety and autocomplete support |\n\nThe system is designed to make tests reliable by default, allowing developers to focus on test logic rather than timing and synchronization concerns.\n\n---\n\n<a id='page-8'></a>\n\n## Browser Implementations and Protocol Support\n\n### 相关页面\n\n相关主题：[Browser Launch and Process Management](#page-4), [CLI, MCP Server, and Agent Integration](#page-10)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/server/chromium/chromium.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/chromium/chromium.ts)\n- [packages/playwright-core/src/server/chromium/crBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/chromium/crBrowser.ts)\n- [packages/playwright-core/src/server/firefox/firefox.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/firefox/firefox.ts)\n- [packages/playwright-core/src/server/firefox/ffBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/firefox/ffBrowser.ts)\n- [packages/playwright-core/src/server/webkit/webkit.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/webkit/webkit.ts)\n- [packages/playwright-core/src/server/webkit/wkBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/webkit/wkBrowser.ts)\n- [packages/playwright-core/src/server/bidi/bidiBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/bidi/bidiBrowser.ts)\n- [browser_patches/firefox/juggler](https://github.com/microsoft/playwright/blob/main/browser_patches/firefox/juggler)\n</details>\n\n# Browser Implementations and Protocol Support\n\n## Overview\n\nPlaywright's browser implementation architecture provides a unified automation API across three major browser engines: Chromium, Firefox, and WebKit. The architecture abstracts browser-specific differences through a common interface while supporting multiple protocols for communication between the Node.js process and browser instances. This design enables developers to write browser automation code once and execute it across different browsers without modification.\n\nThe browser implementations are organized in the `packages/playwright-core/src/server/` directory, with each browser type having its own subdirectory containing browser-specific initialization, connection, and protocol handling code. This modular structure allows for independent development and maintenance of each browser's implementation while sharing common infrastructure through the core playwright-core package.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"Playwright Core API\"\n        A[chromium.launch()] --> B[BrowserType]\n        C[firefox.launch()] --> B\n        D[webkit.launch()] --> B\n    end\n    \n    subgraph \"Protocol Layer\"\n        B --> E[CDP Connection]\n        B --> F[BiDi Protocol]\n    end\n    \n    subgraph \"Browser Implementations\"\n        E --> G[Chromium Browser]\n        E --> H[WebKit Browser]\n        F --> I[Firefox Browser]\n        F --> J[Chromium via BiDi]\n        F --> K[WebKit via BiDi]\n    end\n    \n    subgraph \"Browser Processes\"\n        G --> L[Chromium Process]\n        H --> M[WebKit Process]\n        I --> N[Firefox + Juggler]\n    end\n```\n\n## Browser Package Structure\n\nPlaywright provides separate packages for each browser to optimize installation and distribution. The packages enable automatic installation of browser binaries when imported.\n\n| Package Name | Description | Auto-Install | Main Export |\n|--------------|-------------|--------------|-------------|\n| `playwright-chromium` | Chromium browser support | Yes | `chromium` |\n| `@playwright/browser-chromium` | Chromium browser support | Yes | `chromium` |\n| `playwright` | All browsers | Yes | `chromium`, `firefox`, `webkit` |\n| `playwright-core` | All browsers | No | `chromium`, `firefox`, `webkit` |\n| `@playwright/browser-webkit` | WebKit browser support | Yes | `webkit` |\n| `playwright-browser-webkit` | WebKit browser support | Yes | `webkit` |\n\nEach package exports a `chromium`, `firefox`, or `webkit` object that provides the `BrowserType` interface for launching browser instances. The packages share common dependencies through `playwright-core`, which contains the actual implementation logic.\n\n## Chromium Implementation\n\nThe Chromium implementation consists of two main components: the browser type definition and the actual browser instance management.\n\n### Chromium Architecture\n\n```mermaid\ngraph TD\n    A[chromium.launch()] --> B[Chromium#44;BrowserType]\n    B --> C[ChromiumBrowser#44;ConnectedBrowser]\n    C --> D[CDP Session]\n    C --> E[ChromiumBrowserContext]\n    D --> F[Chrome DevTools Protocol]\n    E --> G[ChromiumPage]\n    G --> F\n```\n\n### Browser Type (`chromium.ts`)\n\nThe Chromium browser type class extends the base `BrowserType` interface and provides the specific configuration for launching Chromium instances. This file contains:\n\n- **Launch options**: Configuration for headless mode, viewport, user agent, and other browser settings\n- **Browser binary path**: Resolution logic for finding the Chromium executable\n- **Connection establishment**: Code for establishing CDP connections to the browser\n- **Feature detection**: Capabilities and features specific to Chromium\n\n### Browser Instance (`crBrowser.ts`)\n\nThe Chromium browser instance class manages the lifecycle of a connected Chromium browser. Key responsibilities include:\n\n- **Page management**: Creating and tracking page instances\n- **Context management**: Handling browser contexts for isolation\n- **CDP session handling**: Managing DevTools protocol sessions\n- **Process management**: Monitoring and terminating the browser process\n\n## Firefox Implementation\n\nFirefox requires special handling due to its architecture. Unlike Chromium and WebKit which support CDP directly, Firefox uses a patched version called Juggler.\n\n### Firefox Architecture with Juggler\n\n```mermaid\ngraph TD\n    A[firefox.launch()] --> B[Firefox#44;BrowserType]\n    B --> C[FFBrowser#44;ConnectedBrowser]\n    C --> D[Juggler Bridge]\n    D --> E[CDP to Juggler Translation]\n    E --> F[Firefox Browser Process]\n    \n    subgraph \"Browser Patches\"\n        G[Juggler Protocol]\n        H[CDP Emulator]\n        I[Automation Hooks]\n    end\n    \n    D --> G\n    G --> H\n    G --> I\n```\n\n### Juggler Protocol Handler\n\nThe Firefox implementation uses Juggler, a custom protocol handler that bridges Playwright's CDP-based API with Firefox's automation capabilities. The Juggler component:\n\n- **Patches Firefox**: Modifies Firefox behavior to enable automation\n- **Protocol translation**: Converts CDP commands to Firefox-specific commands\n- **Event forwarding**: Streams events from Firefox back to Playwright\n\nThis architecture allows Playwright to provide a consistent API across all browsers while accommodating Firefox's different internal architecture.\n\n### Browser Type (`firefox.ts`)\n\nThe Firefox browser type handles:\n\n- **Binary detection**: Locating the Firefox executable\n- **Profile management**: Creating temporary profiles for isolation\n- **Launch configuration**: Setting up Firefox-specific options\n- **Juggler injection**: Ensuring Juggler is properly initialized\n\n### Browser Instance (`ffBrowser.ts`)\n\nThe Firefox browser instance provides:\n\n- **Page tracking**: Managing page instances within Firefox\n- **Context handling**: Isolating browsing contexts\n- **Protocol communication**: Managing Juggler-based communication\n\n## WebKit Implementation\n\nWebKit powers Safari and other browsers. Playwright's WebKit implementation provides support for this browser engine through a combination of native CDP support and custom protocol handling.\n\n### WebKit Architecture\n\n```mermaid\ngraph TD\n    A[webkit.launch()] --> B[WebKit#44;BrowserType]\n    B --> C[WKBrowser#44;ConnectedBrowser]\n    C --> D[WebKit Protocol Handler]\n    D --> E[CDP Compatible Layer]\n    E --> F[WebKit Browser Process]\n    \n    C --> G[WebKitBrowserContext]\n    G --> H[WKPage]\n    H --> D\n```\n\n### Browser Type (`webkit.ts`)\n\nThe WebKit browser type includes:\n\n- **Executable resolution**: Finding WebKit-based browsers\n- **Launch parameters**: Configuring WebKit-specific options\n- **Connection setup**: Establishing protocol communication\n\n### Browser Instance (`wkBrowser.ts`)\n\nThe WebKit browser instance manages:\n\n- **Page lifecycle**: Creating and managing page instances\n- **Protocol sessions**: Handling WebKit's protocol communication\n- **Feature compatibility**: Ensuring WebKit-specific features work correctly\n\n## BiDi Protocol Support\n\nThe WebDriver BiDi (Bidirectional) protocol is a standardized web automation protocol that provides bidirectional communication between automation tools and browsers. Playwright's support for BiDi enables:\n\n- **Standardization**: Using the W3C-standardized protocol\n- **Cross-browser compatibility**: A single protocol approach\n- **Reduced complexity**: Simpler protocol handling compared to CDP\n\n### BiDi Architecture\n\n```mermaid\ngraph TD\n    A[BiDi Browser Connection] --> B[BidiBrowser#44;ConnectedBrowser]\n    B --> C[BiDi Session]\n    C --> D[Command Handler]\n    C --> E[Event Handler]\n    \n    D --> F[Browser Commands]\n    E --> G[Browser Events]\n    \n    B --> H[BrowserContext]\n    H --> I[Page]\n    \n    subgraph \"BiDi Protocol Messages\"\n        J[JSON-RPC 2.0]\n        K[WebSocket Transport]\n    end\n    \n    C --> J\n    J --> K\n```\n\n### BiDi Browser (`bidiBrowser.ts`)\n\nThe BiDi browser implementation provides:\n\n- **Session management**: Creating and maintaining BiDi sessions\n- **Command routing**: Dispatching commands to appropriate handlers\n- **Event subscription**: Managing browser event subscriptions\n- **Context isolation**: Supporting multiple browser contexts\n\n## Protocol Communication\n\nPlaywright supports multiple communication protocols for interacting with browsers. Understanding these protocols helps in debugging and extending Playwright's capabilities.\n\n### Chrome DevTools Protocol (CDP)\n\nCDP is the primary protocol used by Chromium and partially by WebKit. It provides:\n\n- **Complete browser control**: Full access to browser features\n- **Rich debugging**: Detailed debugging capabilities\n- **Real-time events**: Immediate event notifications\n\n### WebDriver BiDi\n\nBiDi is the W3C-standardized protocol for browser automation:\n\n- **Cross-browser support**: Standard protocol across all browsers\n- **Bidirectional communication**: Events flow both directions\n- **Simpler model**: Less complex than CDP for basic operations\n\n### Protocol Selection\n\n| Feature | CDP | BiDi |\n|---------|-----|------|\n| Browser support | Chromium, WebKit | All browsers |\n| Event subscription | Full | Full |\n| Performance | Optimized | Standard |\n| Standardization | Google-specific | W3C standard |\n\n## Launch Configuration\n\nEach browser type accepts launch options that configure how the browser instance is created.\n\n### Common Launch Options\n\n| Option | Type | Description | Chromium | Firefox | WebKit |\n|--------|------|-------------|----------|---------|--------|\n| `headless` | boolean | Run without visible UI | ✓ | ✓ | ✓ |\n| `args` | string[] | Additional browser arguments | ✓ | ✓ | ✓ |\n| `executablePath` | string | Custom browser executable | ✓ | ✓ | ✓ |\n| `timeout` | number | Launch timeout in ms | ✓ | ✓ | ✓ |\n| `viewport` | Viewport | Default page viewport | ✓ | ✓ | ✓ |\n| `userAgent` | string | Custom user agent | ✓ | ✓ | ✓ |\n| `locale` | string | Browser locale | ✓ | ✓ | ✓ |\n| `proxy` | ProxyConfig | Proxy settings | ✓ | ✓ | ✓ |\n\n### Headless Mode\n\nHeadless mode runs the browser without visible UI, essential for CI/CD environments and server-side automation. All three browsers support headless execution with identical behavior.\n\n### Persistent Contexts\n\nPlaywright supports persistent browser contexts that maintain state across sessions:\n\n```mermaid\ngraph LR\n    A[User Data Directory] --> B[Browser Profile]\n    B --> C[Cookies]\n    B --> D[Local Storage]\n    B --> E[Session Storage]\n    B --> F[Cache]\n```\n\n## Browser Contexts and Pages\n\n### Architecture\n\n```mermaid\ngraph TD\n    Browser --> Context1[BrowserContext]\n    Browser --> Context2[BrowserContext]\n    \n    Context1 --> Page1[Page]\n    Context1 --> Page2[Page]\n    Context2 --> Page3[Page]\n    \n    Page1 --> CDPSession[CDP Session]\n    Page2 --> CDPSession\n```\n\n### BrowserContext\n\nBrowser contexts provide isolation between different automation sessions:\n\n- **Separate storage**: Each context has its own cookies, cache, and storage\n- **Independent state**: Actions in one context don't affect others\n- **Parallel execution**: Contexts can run simultaneously\n- **Resource isolation**: Memory and process isolation\n\n### Page\n\nPages represent individual browser tabs or windows:\n\n- **Navigation**: Loading URLs and managing history\n- **Interaction**: Clicking, typing, and other user actions\n- **Evaluation**: Running JavaScript in the page context\n- **Capture**: Taking screenshots and generating PDFs\n\n## Process Architecture\n\n### Browser Process Model\n\n```mermaid\ngraph TD\n    subgraph \"Node.js Process\"\n        A[Playwright API]\n        B[Connection]\n    end\n    \n    subgraph \"Browser Process\"\n        C[Browser Main Process]\n        D[Renderer Process 1]\n        E[Renderer Process 2]\n        F[Renderer Process N]\n    end\n    \n    B --> C\n    C --> D\n    C --> E\n    C --> F\n```\n\n### Process Communication\n\nThe communication between Node.js and browser processes varies by browser:\n\n- **Chromium**: Direct CDP over WebSocket or pipe\n- **Firefox**: Juggler bridge acting as intermediary\n- **WebKit**: CDP-compatible protocol over WebSocket\n\n## Version Compatibility\n\nPlaywright maintains compatibility matrices for browser versions to ensure stable automation:\n\n| Playwright Version | Chromium | Firefox | WebKit |\n|-------------------|----------|---------|--------|\n| 1.61.0-next | Latest | Latest | Latest |\n| Stable releases | Bundled | Bundled | Bundled |\n\nBrowser binaries are downloaded and managed by Playwright's installer, ensuring version compatibility between the library and browser binaries.\n\n## Extension Points\n\nThe browser implementation architecture supports extension through:\n\n### Custom Browser Executables\n\n```typescript\nconst browser = await chromium.launch({\n  executablePath: '/path/to/custom/chromium'\n});\n```\n\n### Protocol Interceptors\n\nExtensions can intercept and modify protocol messages for debugging or custom behavior.\n\n### Custom Context Options\n\nBrowser contexts accept custom options specific to each browser implementation.\n\n## Troubleshooting\n\n### Browser Installation Issues\n\n```bash\n# Install all browsers\nnpx playwright install\n\n# Install specific browser\nnpx playwright install chromium\nnpx playwright install firefox\nnpx playwright install webkit\n```\n\n### Connection Issues\n\nConnection problems typically manifest as timeout errors during launch or operation. The trace viewer tool (`npx playwright trace`) helps diagnose these issues by capturing detailed protocol communication.\n\n### Platform-Specific Considerations\n\nEach browser may have platform-specific requirements:\n\n- **Chromium**: Generally has few platform-specific issues\n- **Firefox**: Requires Juggler patches for all platforms\n- **WebKit**: May require platform-specific dependencies\n\n## Summary\n\nPlaywright's browser implementation architecture provides a robust, extensible foundation for cross-browser automation. By abstracting browser-specific details through a common interface while supporting multiple communication protocols, Playwright enables developers to write reliable browser automation code that works consistently across Chromium, Firefox, and WebKit.\n\nThe architecture's modular design allows for independent browser implementations while sharing common infrastructure, making it possible to add new browser support or extend existing capabilities without affecting the overall system.\n\n---\n\n<a id='page-9'></a>\n\n## Trace Viewer and Debugging Tools\n\n### 相关页面\n\n相关主题：[Test Runner and Execution Engine](#page-5), [CLI, MCP Server, and Agent Integration](#page-10)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/server/trace/recorder/tracing.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/trace/recorder/tracing.ts)\n- [packages/playwright-core/src/server/trace/recorder/snapshotter.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/trace/recorder/snapshotter.ts)\n- [packages/trace-viewer/src/index.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/index.tsx)\n- [packages/trace-viewer/src/ui/workbench.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbench.tsx)\n- [packages/isomorphic/trace/traceLoader.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/trace/traceLoader.ts)\n- [packages/isomorphic/trace/traceModel.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/trace/traceModel.ts)\n- [packages/trace/src/trace.ts](https://github.com/microsoft/playwright/blob/main/packages/trace/src/trace.ts)\n</details>\n\n# Trace Viewer and Debugging Tools\n\n## Overview\n\nPlaywright's Trace Viewer and Debugging Tools provide comprehensive execution tracing capabilities for debugging and analyzing browser automation tests. The tracing system captures detailed execution traces including DOM snapshots, screenshots, network activity, and console logs, enabling developers to reconstruct and analyze exactly what happened during test execution.\n\nThe trace infrastructure consists of three main components:\n\n| Component | Purpose | Location |\n|-----------|---------|----------|\n| Trace Recorder | Captures actions, snapshots, and metadata during test execution | `packages/playwright-core/src/server/trace/recorder/` |\n| Trace Viewer | Progressive Web App for visual trace inspection | `packages/trace-viewer/` |\n| Trace Model | Data structures and loading logic for trace files | `packages/isomorphic/trace/` |\n\n资料来源：[packages/trace-viewer/src/index.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/index.tsx)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Test Execution] --> B[Tracing Recorder]\n    B --> C[Snapshotter]\n    B --> D[Action Logger]\n    B --> E[Network Monitor]\n    \n    C --> F[DOM Snapshots]\n    D --> G[Action Log]\n    E --> H[Network Events]\n    \n    F --> I[trace-{timestamp}.trace]\n    G --> I\n    H --> J[trace-{timestamp}.network]\n    \n    I --> K[Trace ZIP Archive]\n    J --> K\n    K --> L[Trace Viewer PWA]\n    K --> M[playwright trace CLI]\n```\n\n### Core Components\n\n#### Trace Recorder (`packages/playwright-core/src/server/trace/recorder/tracing.ts`)\n\nThe `Tracing` class manages the recording process for browser contexts. It initializes snapshot capture, action logging, and network monitoring.\n\n| Method | Description |\n|--------|-------------|\n| `start()` | Initializes trace recording with snapshotter and action collectors |\n| `stop()` | Finalizes and writes trace files |\n| `snapshot()` | Captures current DOM state |\n\n#### Snapshotter (`packages/playwright-core/src/server/trace/recorder/snapshotter.ts`)\n\nCaptures DOM snapshots before and after each action, enabling reconstruction of page state at any point during test execution.\n\n资料来源：[packages/playwright-core/src/server/trace/recorder/snapshotter.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/trace/recorder/snapshotter.ts)\n\n#### Trace Model (`packages/isomorphic/trace/traceModel.ts`)\n\nThe `TraceModel` class represents the in-memory structure of a trace file, containing:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `actions` | `ActionTrace[]` | All recorded actions |\n| `events` | `TraceEvent[]` | Network, console, and other events |\n| `snapshots` | `Snapshot[]` | DOM snapshots |\n\n#### Trace Loader (`packages/isomorphic/trace/traceLoader.ts`)\n\nHandles parsing and loading of trace files from disk or network.\n\n资料来源：[packages/isomorphic/trace/traceLoader.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/trace/traceLoader.ts)\n\n## Trace File Format\n\nWhen tracing starts, Playwright creates a `traces/` directory containing several files:\n\n### File Structure\n\n| File | Format | Contents |\n|------|--------|----------|\n| `trace-{timestamp}.trace` | Binary/JSON | Action log with DOM snapshots, screenshots, timing |\n| `trace-{timestamp}.network` | Binary/JSON | Complete network activity including headers, bodies, timing |\n| `resources/` | Directory | Cached resources (images, fonts, scripts) |\n\n### Trace Archive\n\nAll trace files are packaged into a `.zip` archive for easy sharing and analysis:\n\n```bash\n# Default location\ntest-results/{test-name}/trace.zip\n```\n\n### Captured Data Categories\n\n| Category | Details |\n|----------|---------|\n| **Actions** | Clicks, fills, hovers, keyboard input, navigations |\n| **DOM** | Full DOM snapshot before/after each action |\n| **Screenshots** | Visual state at each step |\n| **Network** | All requests, responses, headers, bodies, timing |\n| **Console** | Browser console messages and stdout/stderr |\n| **Errors** | Error messages with stack traces |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/tracing.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/tracing.md)\n\n## Trace Viewer UI\n\nThe Trace Viewer is a Progressive Web App that runs locally in the browser without sending trace data anywhere.\n\n```mermaid\ngraph LR\n    A[Open trace.zip] --> B[Extract & Parse]\n    B --> C[Action Timeline]\n    B --> D[Snapshot View]\n    B --> E[Network Log]\n    B --> F[Console Output]\n```\n\n### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Action Timeline** | Visual representation of all actions with timing |\n| **DOM Snapshots** | Interactive DOM inspection at any action point |\n| **Network Log** | Filterable view of all HTTP requests/responses |\n| **Console View** | Console messages with filtering by type |\n| **Error Tracking** | Consolidated view of all errors with stack traces |\n\n### Loading Traces\n\nTraces can be loaded in multiple ways:\n\n1. **Local File**: Drop `.zip` file directly into the viewer\n2. **URL Parameter**: Pass `?trace=` with trace URL\n3. **Upload Button**: Select file via browser dialog\n\nThe viewer displays a progress indicator during trace loading:\n\n```tsx\n<Dialog open={showProgressDialog} isModal={true}>\n  <div className='progress-content'>\n    <div className='title'>Loading Playwright Trace...</div>\n    <div className='progress-wrapper'>\n      <div className='inner-progress' \n        style={{ width: progress.total ? (100 * progress.done / progress.total) + '%' : 0 }}>\n      </div>\n    </div>\n  </div>\n</Dialog>\n```\n\n资料来源：[packages/trace-viewer/src/ui/workbench.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbench.tsx)\n\n## CLI Commands\n\n### Trace Recording Commands\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli tracing-start` | Start trace recording |\n| `playwright-cli tracing-stop` | Stop trace recording and save |\n\n### Trace Inspection Commands\n\n| Command | Description |\n|---------|-------------|\n| `npx playwright trace open <trace.zip>` | Open and extract trace |\n| `npx playwright trace close` | Remove extracted trace data |\n| `npx playwright trace actions` | List all actions |\n| `npx playwright trace actions --grep \"click\"` | Filter actions by pattern |\n| `npx playwright trace actions --errors-only` | Show only failed actions |\n| `npx playwright trace action <id>` | Show details for one action |\n| `npx playwright trace requests` | List all network requests |\n| `npx playwright trace requests --failed` | Show only failed requests |\n| `npx playwright trace request <id>` | Show request details |\n| `npx playwright trace console` | Show console messages |\n| `npx playwright trace console --errors-only` | Show only errors |\n| `npx playwright trace errors` | Show all errors with stack traces |\n| `npx playwright trace snapshot <id>` | Get DOM snapshot |\n| `npx playwright trace attachments` | List trace attachments |\n\n### Example Workflow\n\n```bash\n# 1. Open trace and view metadata\nnpx playwright trace open test-results/my-test/trace.zip\n\n# 2. List all actions\nnpx playwright trace actions\n\n# 3. Show only failed actions\nnpx playwright trace actions --errors-only\n\n# 4. Get details for specific action\nnpx playwright trace action 12\n\n# 5. View DOM at that point\nnpx playwright trace snapshot 12\n\n# 6. Check for network failures\nnpx playwright trace requests --failed\n\n# 7. View console errors\nnpx playwright trace console --errors-only\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n\n## Integration with Test Debugging\n\n### Debug Mode\n\nRun tests in debug mode with CLI integration:\n\n```bash\nPLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli\n```\n\nThis command:\n1. Pauses test execution at start\n2. Prints debugging instructions with session name\n3. Allows attaching via `playwright-cli` to explore the page\n\n### Attaching to Test Session\n\n```bash\n# After starting debug mode, attach to the printed session\nplaywright-cli attach tw-abcdef\n```\n\nAvailable exploration commands while attached:\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli snapshot` | Get current DOM snapshot |\n| `playwright-cli click <ref>` | Interact with elements |\n| `playwright-cli eval <js>` | Execute JavaScript |\n| `playwright-cli show --annotate` | Launch annotation dashboard |\n| `playwright-cli resume` | Resume test execution |\n\n### Spec-Driven Testing Workflow\n\nThe debugging tools integrate with Playwright's spec-driven testing approach:\n\n1. **Create seed test** that navigates to the application\n2. **Run seed in debug mode** and attach via CLI\n3. **Explore the app** to understand interactive surfaces\n4. **Write spec file** documenting expected behavior\n5. **Generate tests** from the spec\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n\n## API Reference\n\n### JavaScript Execution in CLI\n\nExecute arbitrary JavaScript in the browser context:\n\n```bash\n# Basic evaluation\nplaywright-cli eval \"document.title\"\n\n# With return value\nplaywright-cli run-code \"async page => await page.title()\"\n\n# Read from clipboard\nplaywright-cli run-code \"async page => {\n  await page.context().grantPermissions(['clipboard-read']);\n  return await page.evaluate(() => navigator.clipboard.readText());\n}\"\n```\n\n### Page Information\n\n```bash\n# Get page title\nplaywright-cli run-code \"async page => await page.title()\"\n\n# Get current URL\nplaywright-cli run-code \"async page => page.url()\"\n\n# Get viewport size\nplaywright-cli run-code \"async page => page.viewportSize()\"\n```\n\n### Snapshot with Custom Depth\n\n```bash\n# Default snapshot\nplaywright-cli snapshot\n\n# Snapshot with element bounding boxes\nplaywright-cli snapshot --boxes\n\n# Limited depth for performance\nplaywright-cli snapshot --depth=4\n\n# Snapshot specific element\nplaywright-cli snapshot \"#main\"\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/running-code.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/running-code.md)\n\n## Storage State Management\n\n### Saving Authentication State\n\n```bash\n# Step 1: Login and save state\nplaywright-cli open https://app.example.com/login\nplaywright-cli snapshot\nplaywright-cli fill e1 \"user@example.com\"\nplaywright-cli fill e2 \"password123\"\nplaywright-cli click e3\nplaywright-cli state-save auth.json\n\n# Step 2: Later, restore state\nplaywright-cli state-load auth.json\nplaywright-cli open https://app.example.com/dashboard\n# Already authenticated\n```\n\n### Cookie Management\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli cookie-list` | List all cookies |\n| `playwright-cli cookie-get <name>` | Get specific cookie |\n| `playwright-cli cookie-set <name> <value>` | Set a cookie |\n| `playwright-cli cookie-delete <name>` | Delete a cookie |\n| `playwright-cli cookie-clear` | Clear all cookies |\n\n### Local/Session Storage\n\n```bash\n# List storage items\nplaywright-cli localstorage-list\nplaywright-cli sessionstorage-list\n\n# Get specific value\nplaywright-cli localstorage-get theme\nplaywright-cli sessionstorage-get step\n\n# Set value\nplaywright-cli localstorage-set theme dark\nplaywright-cli sessionstorage-set step 3\n\n# Delete/Clear\nplaywright-cli localstorage-delete theme\nplaywright-cli localstorage-clear\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/storage-state.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/storage-state.md)\n\n## Advanced Features\n\n### Persistent Profiles\n\nBrowser profiles can be persisted to disk for testing scenarios requiring persistent state:\n\n```bash\n# Auto-generated profile location\nplaywright-cli open https://example.com --persistent\n\n# Custom profile directory\nplaywright-cli open https://example.com --profile=/path/to/profile\n\n# Create named session with persistent profile\nplaywright-cli -s=mysession open example.com --persistent\n```\n\n### Network Interception\n\n```bash\n# Mock responses\nplaywright-cli route \"**/*.jpg\" --status=404\nplaywright-cli route \"https://api.example.com/**\" --body='{\"mock\": true}'\n\n# List and remove routes\nplaywright-cli route-list\nplaywright-cli unroute \"**/*.jpg\"\n```\n\n### Highlighting Elements\n\n```bash\n# Highlight an element\nplaywright-cli highlight e5\n\n# Highlight with custom style\nplaywright-cli highlight e5 --style=\"outline: 3px dashed red\"\n\n# Hide highlights\nplaywright-cli highlight --hide\n```\n\n### Video Recording\n\n```bash\n# Start video recording\nplaywright-cli video-start video.webm\n\n# Add chapter markers\nplaywright-cli video-chapter \"Chapter Title\" --description=\"Details\" --duration=2000\n\n# Stop recording\nplaywright-cli video-stop\n```\n\n## Best Practices\n\n| Practice | Description |\n|----------|-------------|\n| **Use `--debug=cli`** | Always debug through test execution, not direct URL opening |\n| **Capture specific actions** | Use `--grep` flags to narrow focus during investigation |\n| **Save authentication state** | Reuse authenticated sessions instead of repeating login |\n| **Use raw output** | Pipe CLI output to tools like `jq` for scripting |\n| **Clean up traces** | Run `playwright-cli trace close` after investigation |\n\n### Raw Output for Scripting\n\n```bash\n# Get JSON output for processing\nplaywright-cli list --json\n\n# Pipe to jq for data extraction\nplaywright-cli --raw eval \"JSON.stringify(performance.timing)\" | jq '.loadEventEnd - .navigationStart'\n\n# Save to file\nplaywright-cli --raw snapshot > before.yml\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n---\n\n<a id='page-10'></a>\n\n## CLI, MCP Server, and Agent Integration\n\n### 相关页面\n\n相关主题：[Trace Viewer and Debugging Tools](#page-9)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/tools/cli-client/cli.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/cli.ts)\n- [packages/playwright-core/src/tools/mcp/index.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/index.ts)\n- [packages/playwright-core/src/tools/mcp/browserFactory.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserFactory.ts)\n- [packages/playwright-core/src/tools/mcp/browserModel.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserModel.ts)\n- [packages/playwright-core/src/tools/dashboard/dashboardApp.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/dashboard/dashboardApp.ts)\n- [packages/dashboard/src/dashboard.tsx](https://github.com/microsoft/playwright/blob/main/packages/dashboard/src/dashboard.tsx)\n- [packages/playwright-core/src/tools/backend/tools.ts](https://github.com/microsoft/microsoft/playwright/blob/main/packages/playwright-core/src/tools/backend/tools.ts)\n</details>\n\n# CLI, MCP Server, and Agent Integration\n\n## Overview\n\nPlaywright provides a comprehensive command-line interface (CLI), MCP (Model Context Protocol) server, and agent integration system that enables automated browser control, testing, and inspection workflows. These three interconnected components form the foundation of Playwright's external interaction layer, allowing developers and AI agents to programmatically control browsers, execute tests, and analyze application behavior.\n\nThe CLI layer (`playwright-cli`) provides a human-readable command interface for browser automation, while the MCP server exposes these capabilities to AI agents and automated systems. The agent integration system coordinates between tools, manages browser sessions, and maintains state across operations.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User / AI Agent] --> B[CLI Interface<br/>playwright-cli]\n    A --> C[MCP Server<br/>Model Context Protocol]\n    B --> D[Tool Backend<br/>packages/playwright-core/src/tools/backend/tools.ts]\n    C --> D\n    D --> E[Browser Factory<br/>browserFactory.ts]\n    E --> F[Browser Pool<br/>Chromium, Firefox, WebKit]\n    D --> G[Session Manager]\n    G --> H[State: Cookies, LocalStorage,<br/>SessionStorage]\n    D --> I[Trace Viewer<br/>trace viewer package]\n```\n\n## CLI (`playwright-cli`)\n\n### Purpose and Scope\n\nThe `playwright-cli` tool provides a command-line interface for browser automation and testing. It is defined in `packages/playwright-core/src/tools/cli-client/cli.ts` and offers a comprehensive set of commands for interacting with browsers without writing code directly.\n\nThe CLI accepts commands like `open`, `goto`, `click`, `fill`, `snapshot`, and many others, making browser automation accessible through a simple shell interface.\n\n### Core Commands\n\n#### Browser Lifecycle\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli open [url]` | Opens a new browser and optionally navigates to URL |\n| `playwright-cli close` | Closes the current browser session |\n| `playwright-cli close-all` | Closes all browser sessions |\n| `playwright-cli kill-all` | Forcefully terminates all browser processes |\n\n#### Navigation\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli goto <url>` | Navigate to the specified URL |\n| `playwright-cli go-back` | Navigate back in browser history |\n| `playwright-cli go-forward` | Navigate forward in browser history |\n| `playwright-cli reload` | Reload the current page |\n\n#### Element Interaction\n\n| Command | Description | Example |\n|---------|-------------|---------|\n| `playwright-cli click <ref>` | Click an element by ref | `playwright-cli click e15` |\n| `playwright-cli dblclick <ref>` | Double-click an element | `playwright-cli dblclick e7` |\n| `playwright-cli fill <ref> <text>` | Fill input field | `playwright-cli fill e5 \"text\"` |\n| `playwright-cli type <text>` | Type text into focused element | `playwright-cli type \"search\"` |\n| `playwright-cli press <key>` | Press a keyboard key | `playwright-cli press Enter` |\n| `playwright-cli select <ref> <value>` | Select dropdown option | `playwright-cli select e9 \"value\"` |\n| `playwright-cli check <ref>` | Check a checkbox | `playwright-cli check e12` |\n| `playwright-cli uncheck <ref>` | Uncheck a checkbox | `playwright-cli uncheck e12` |\n| `playwright-cli hover <ref>` | Hover over an element | `playwright-cli hover e4` |\n| `playwright-cli drag <src> <target>` | Drag element to target | `playwright-cli drag e2 e8` |\n\n#### Data Input\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli upload <path>` | Upload file to element |\n| `playwright-cli drop <ref> --path=<file>` | Drop file onto element |\n| `playwright-cli drop <ref> --data=<type>=<data>` | Drop data onto element |\n\n### Snapshot and Inspection\n\nThe snapshot command captures the current page state, including interactive elements with their refs:\n\n```bash\nplaywright-cli snapshot\nplaywright-cli snapshot --filename=state.yaml\nplaywright-cli snapshot \"#main\"\nplaywright-cli snapshot --depth=4\nplaywright-cli snapshot --boxes\n```\n\nElements can be targeted using refs from snapshots, CSS selectors, or Playwright locators:\n\n```bash\n# Using ref\nplaywright-cli click e15\n\n# Using CSS selector\nplaywright-cli click \"#main > button.submit\"\n\n# Using role locator\nplaywright-cli click \"getByRole('button', { name: 'Submit' })\"\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n### Storage Management\n\n```bash\n# State persistence\nplaywright-cli state-save [filename]\nplaywright-cli state-load [filename]\n\n# Cookies\nplaywright-cli cookie-list [--domain=<domain>]\nplaywright-cli cookie-get <name>\nplaywright-cli cookie-set <name> <value> [--domain=<domain>] [--httpOnly] [--secure]\nplaywright-cli cookie-delete <name>\nplaywright-cli cookie-clear\n\n# LocalStorage\nplaywright-cli localstorage-list\nplaywright-cli localstorage-get <key>\nplaywright-cli localstorage-set <key> <value>\nplaywright-cli localstorage-delete <key>\nplaywright-cli localstorage-clear\n\n# SessionStorage\nplaywright-cli sessionstorage-list\nplaywright-cli sessionstorage-get <key>\nplaywright-cli sessionstorage-set <key> <value>\nplaywright-cli sessionstorage-delete <key>\nplaywright-cli sessionstorage-clear\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/session-management.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md)\n\n### Network Interception\n\n```bash\n# Mock network responses\nplaywright-cli route \"**/*.jpg\" --status=404\nplaywright-cli route \"https://api.example.com/**\" --body='{\"mock\": true}'\nplaywright-cli route-list\nplaywright-cli unroute \"**/*.jpg\"\nplaywright-cli unroute\n```\n\n### Tracing\n\n```bash\n# Start/stop trace recording\nplaywright-cli tracing-start\nplaywright-cli tracing-stop\n\n# Video chapters\nplaywright-cli video-start <file.webm>\nplaywright-cli video-chapter \"Title\" --description=\"Details\" --duration=2000\nplaywright-cli video-stop\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/tracing.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/tracing.md)\n\n### Tab Management\n\n```bash\nplaywright-cli tab-list\nplaywright-cli tab-new [url]\nplaywright-cli tab-close [index]\nplaywright-cli tab-select <index>\n```\n\n### Dialog Handling\n\n```bash\nplaywright-cli dialog-accept [text]\nplaywright-cli dialog-dismiss\n```\n\n### Advanced: JavaScript Execution\n\n```bash\nplaywright-cli run-code \"async page => await page.title()\"\nplaywright-cli eval \"document.title\"\nplaywright-cli eval \"el => el.textContent\" <ref>\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/running-code.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/running-code.md)\n\n### Browser Sessions\n\nSessions allow multiple independent browser instances with optional persistence:\n\n```bash\n# Named session with persistent profile\nplaywright-cli -s=mysession open https://example.com --persistent\n\n# With custom profile directory\nplaywright-cli -s=mysession open https://example.com --profile=/path/to/profile\n\n# Session management\nplaywright-cli -s=mysession click e6\nplaywright-cli -s=mysession close\nplaywright-cli -s=mysession delete-data\n\n# List and cleanup\nplaywright-cli list\nplaywright-cli close-all\nplaywright-cli kill-all\n```\n\nSession name can be set via environment variable:\n\n```bash\nexport PLAYWRIGHT_CLI_SESSION=\"mysession\"\n```\n\n## MCP Server Integration\n\n### Purpose and Architecture\n\nThe MCP (Model Context Protocol) server provides programmatic access to Playwright's browser automation capabilities for AI agents. The server is defined in `packages/playwright-core/src/tools/mcp/index.ts` and exposes a standardized interface for browser control operations.\n\n```mermaid\ngraph LR\n    A[AI Agent] -->|MCP Protocol| B[MCP Server<br/>index.ts]\n    B --> C[Browser Factory<br/>browserFactory.ts]\n    B --> D[Browser Model<br/>browserModel.ts]\n    C --> E[Chromium]\n    C --> F[Firefox]\n    C --> G[WebKit]\n    D --> H[Browser State<br/>and Context]\n```\n\n### Browser Factory (`browserFactory.ts`)\n\nThe `BrowserFactory` class is responsible for creating and managing browser instances. It provides methods for launching browsers with various configurations:\n\n```typescript\nclass BrowserFactory {\n  async launch(options?: BrowserLaunchOptions): Promise<Browser>;\n  async connect(browserWSEndpoint: string): Promise<Browser>;\n  async close(): Promise<void>;\n}\n```\n\nThe factory handles:\n- Browser type selection (Chromium, Firefox, WebKit)\n- Launch option configuration\n- Browser connection management\n- Resource cleanup\n\n资料来源：[packages/playwright-core/src/tools/mcp/browserFactory.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserFactory.ts)\n\n### Browser Model (`browserModel.ts`)\n\nThe `BrowserModel` maintains state and context for browser instances:\n\n```typescript\nclass BrowserModel {\n  id: string;\n  browser: Browser;\n  context: BrowserContext;\n  pages: Page[];\n  sessionName?: string;\n  createdAt: Date;\n}\n```\n\nKey responsibilities:\n- Tracking active pages and contexts\n- Managing browser lifecycle\n- Providing access to current state\n- Handling browser events\n\n资料来源：[packages/playwright-core/src/tools/mcp/browserModel.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserModel.ts)\n\n### MCP Tool Interface\n\nThe MCP server exposes tools through the `tools.ts` backend:\n\n```typescript\n// Defined in packages/playwright-core/src/tools/backend/tools.ts\nexport interface Tool {\n  name: string;\n  description: string;\n  execute(params: ToolParams): Promise<ToolResult>;\n}\n```\n\nAvailable tool categories include:\n- Navigation tools (goto, back, forward, reload)\n- Interaction tools (click, fill, select, hover)\n- Inspection tools (snapshot, screenshot, content)\n- Storage tools (cookies, localStorage, sessionStorage)\n\n## Dashboard and Visualization\n\n### Dashboard Application (`dashboardApp.ts`)\n\nThe Playwright dashboard provides a visual interface for analyzing test results and traces:\n\n```mermaid\ngraph TD\n    A[Test Execution] --> B[Trace Files<br/>.zip format]\n    B --> C[Trace Viewer]\n    C --> D[Dashboard App<br/>dashboardApp.ts]\n    D --> E[Action Timeline]\n    D --> F[Network Log]\n    D --> G[Console Output]\n    D --> H[Screenshots]\n```\n\nThe dashboard displays:\n- Test action timeline with timing information\n- Network request/response logs\n- Console messages and errors\n- DOM snapshots at each step\n- Screenshots for visual verification\n\n资料来源：[packages/playwright-core/src/tools/dashboard/dashboardApp.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/dashboard/dashboardApp.ts)\n\n### Trace Viewer (`workbenchLoader.tsx`)\n\nThe trace viewer is a Progressive Web App that loads locally without sending data externally:\n\n```typescript\n// Loading states\ninterface LoadState {\n  showFileUploadDropArea: boolean;\n  showProgressDialog: boolean;\n  processingErrorMessage?: string;\n  traceURL?: string;\n}\n```\n\nKey features:\n- Drag-and-drop trace file loading\n- File browser selection\n- Progress indication during trace parsing\n- Local-only processing for privacy\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n\n### Dashboard React Component\n\nThe main dashboard component renders the UI:\n\n```typescript\n// packages/dashboard/src/dashboard.tsx\nexport const Dashboard: React.FC<DashboardProps> = ({ traceData }) => {\n  // Renders action tree, network log, console output, snapshots\n};\n```\n\n## Spec-Driven Testing Workflow\n\nThe CLI supports a specification-driven testing workflow documented in `spec-driven-testing.md`:\n\n```mermaid\ngraph LR\n    A[Write Spec File<br/>specs/feature.plan.md] --> B[Generate Tests]\n    B --> C[Execute Tests]\n    C --> D[Generate Traces]\n    D --> E[Analyze Results]\n    E --> F[Annotate & Feedback]\n```\n\n### Spec File Structure\n\n```markdown\n# <Feature> Test Plan\n\n## Application Overview\n<Description>\n\n## Test Scenarios\n\n### 1. <Group Name>\n**Seed:** `tests/seed.spec.ts`\n\n#### 1.1. <scenario-name>\n**File:** `tests/<group>/<scenario>.spec.ts`\n**Steps:**\n  1. <User step>\n     - expect: <outcome>\n  2. <Next step>\n     - expect: <outcome>\n```\n\n### Test Generation Flow\n\n1. Create seed test that navigates to the app\n2. Explore app using `playwright-cli attach` and `snapshot`\n3. Write spec file with test scenarios\n4. Generate actual test code from spec\n5. Execute and capture traces\n6. Review results in trace viewer\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/spec-driven-testing.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/spec-driven-testing.md)\n\n## Trace CLI Tool\n\n### Command Reference\n\n```bash\n# Open and analyze traces\nnpx playwright trace open <trace.zip>\nnpx playwright trace close\n\n# List actions\nnpx playwright trace actions\nnpx playwright trace actions --grep \"click\"\nnpx playwright trace actions --errors-only\n\n# View specific action\nnpx playwright trace action <action-id>\n\n# View requests, console, errors\nnpx playwright trace requests\nnpx playwright trace console\nnpx playwright trace errors\n\n# Get DOM snapshot\nnpx playwright trace snapshot <action-id>\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n\n### Trace File Structure\n\nWhen tracing is enabled, Playwright creates:\n\n| File/Directory | Content |\n|---------------|---------|\n| `trace-{timestamp}.trace` | Action log with DOM snapshots, screenshots, timing |\n| `trace-{timestamp}.network` | Complete network activity log |\n| `resources/` | Cached resources for replay |\n\n## Tool Backend Architecture\n\nThe tool backend (`packages/playwright-core/src/tools/backend/tools.ts`) serves as the coordination layer:\n\n```mermaid\ngraph TD\n    A[CLI / MCP Server] --> B[Tool Backend<br/>tools.ts]\n    B --> C[Browser Tool]\n    B --> D[Page Tool]\n    B --> E[Storage Tool]\n    B --> F[Trace Tool]\n    C --> G[Playwright Core API]\n    D --> G\n    E --> G\n    F --> G\n```\n\n### Tool Categories\n\n| Category | Tools |\n|----------|-------|\n| Browser | launch, connect, close, context |\n| Navigation | goto, back, forward, reload |\n| Interaction | click, fill, select, hover, drag, type, press |\n| Snapshot | snapshot, screenshot, pdf |\n| Storage | cookies, localStorage, sessionStorage |\n| Network | route, unroute, route-list |\n\n## Package Structure\n\n| Package | Purpose |\n|---------|---------|\n| `playwright` | Main package with all browser support |\n| `@playwright/test` | Testing framework with reporters |\n| `playwright-core` | Core API without browser binaries |\n| `@playwright/browser-chromium` | Chromium browser support |\n| `@playwright/browser-firefox` | Firefox browser support |\n| `@playwright/browser-webkit` | WebKit browser support |\n\n资料来源：[package.json](https://github.com/microsoft/playwright/blob/main/package.json), [packages/playwright-test/package.json](https://github.com/microsoft/playwright/blob/main/packages/playwright-test/package.json), [packages/playwright-webkit/package.json](https://github.com/microsoft/playwright/blob/main/packages/playwright-webkit/package.json)\n\n## Environment Variables\n\n| Variable | Purpose |\n|----------|---------|\n| `PLAYWRIGHT_CLI_SESSION` | Default session name for CLI |\n| `PLAYWRIGHT_HTML_OPEN` | Controls browser launch behavior in tests |\n| `PLAYWRIGHT_BROWSERS_PATH` | Custom browser installation directory |\n\n## Error Handling Patterns\n\n```bash\n# Try-catch in run-code\nplaywright-cli run-code \"async page => {\n  try {\n    await page.getByRole('button', { name: 'Submit' }).click({ timeout: 1000 });\n    return 'clicked';\n  } catch (e) {\n    return 'element not found';\n  }\n}\"\n```\n\n## Installation and Usage\n\n### CLI Installation\n\n```bash\n# Use via npx (no installation required)\nnpx --no-install playwright-cli --version\n\n# Or install globally\nnpm install -g playwright-cli\n```\n\n### Testing Commands\n\nFrom the root `package.json`:\n\n| Script | Purpose |\n|--------|---------|\n| `npm run test` | Run library tests |\n| `npm run ctest` | Chromium tests only |\n| `npm run ftest` | Firefox tests only |\n| `npm run wtest` | WebKit tests only |\n| `npm run biditest` | Bidi protocol tests |\n\n## Summary\n\nThe Playwright CLI, MCP Server, and Agent Integration system provides a layered approach to browser automation:\n\n1. **CLI Layer**: Human-friendly command interface for browser automation tasks\n2. **MCP Layer**: Programmatic interface for AI agents and automated systems\n3. **Tool Backend**: Coordination layer that manages browser factories and models\n4. **Dashboard/Trace Viewer**: Visualization tools for analyzing test results\n\nThese components work together to enable comprehensive browser testing and automation workflows, from simple interactive sessions to complex AI-driven testing scenarios.\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：microsoft/playwright\n\n摘要：发现 38 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：[Feature]: Fail tests on page errors。\n\n## 1. 安装坑 · 来源证据：[Feature]: Fail tests on page errors\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Fail tests on page errors\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_347cf8732e73437a9699e4d8bc55d958 | https://github.com/microsoft/playwright/issues/40880 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：[Feature]: Ubuntu 26.04 LTS support\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Ubuntu 26.04 LTS support\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_764e9005d6a94f41b4a8d9f52decca99 | https://github.com/microsoft/playwright/issues/40117 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：[Feature]: trace correlation hooks for external observability/replay systems\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: trace correlation hooks for external observability/replay systems\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3c11bc1bf38e448f82e5b70d9f909037 | https://github.com/microsoft/playwright/issues/40887 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 运行坑 · 来源证据：[Feature]: support signal in waitFor* APIs\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Feature]: support signal in waitFor* APIs\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_500f564d44534739b16e93ed0b6a86eb | https://github.com/microsoft/playwright/issues/40578 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 5. 维护坑 · 来源证据：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_16f48d22960444cfa514e3e08d959d45 | https://github.com/microsoft/playwright/issues/20749 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 失败模式：security_permissions: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path...\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- 对用户的影响：Developers may expose sensitive permissions or credentials: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only. Context: Observed when using node, docker, playwright, linux\n- 防护动作：Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/microsoft/playwright/issues/40892\n- 证据：failure_mode_cluster:github_issue | fmev_32d5131674a6cea46a3dd9fea57edcee | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only, failure_mode_cluster:github_issue | fmev_5eb5ff7b9134ac254ca127feb48992d6 | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n\n## 7. 安全/权限坑 · 来源证据：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_641150bc817a45af974903e3c724aa41 | https://github.com/microsoft/playwright/issues/40681 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 安装坑 · 失败模式：installation: [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: In VS Code, tests are not displayed in the Testing section.. Context: Observed when using node, playwright, windows, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_429f2bbd1fa3334bca8aae5ee7df68b8 | https://github.com/microsoft/playwright/issues/40481 | [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n## 9. 安装坑 · 失败模式：installation: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1. Context: Observed when using node, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_09c75aac9731971717426ccfbe72651b | https://github.com/microsoft/playwright/issues/40904 | [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n## 10. 安装坑 · 失败模式：installation: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests nev...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite. Context: Observed when using node, playwright, windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_bd2b1ca9bdfc4104afb98768ab5f87d4 | https://github.com/microsoft/playwright/issues/40889 | [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n\n## 11. 安装坑 · 失败模式：installation: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect w...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials. Context: Observed when using node, playwright, windows, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_f50999f1a6066b929ea1a2971fefc95a | https://github.com/microsoft/playwright/issues/40768 | [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n\n## 12. 安装坑 · 失败模式：installation: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix s...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length. Context: Observed when using node, playwright, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_0f40df2fb212e08cdc02306a91f914c1 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length, failure_mode_cluster:github_issue | fmev_a8ab1c8959a949b8aee2604c9969fcc4 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n\n## 13. 安装坑 · 失败模式：installation: [Feature] Configure web servers per project\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Feature] Configure web servers per project\n- 对用户的影响：Developers may fail before the first successful local run: [Feature] Configure web servers per project\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature] Configure web servers per project. Context: Observed when using node, python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_4722870d2dbf6cec9abf1c0c8bcde960 | https://github.com/microsoft/playwright/issues/22496 | [Feature] Configure web servers per project\n\n## 14. 安装坑 · 失败模式：installation: [Regression]: install-deps --dry-run can no longer be used to generate install script\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Regression]: install-deps --dry-run can no longer be used to generate install script\n- 对用户的影响：Developers may fail before the first successful local run: [Regression]: install-deps --dry-run can no longer be used to generate install script\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Regression]: install-deps --dry-run can no longer be used to generate install script. Context: Observed when using node, docker, playwright, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_c8dd7be64694731b0c1d899e67c604ae | https://github.com/microsoft/playwright/issues/40885 | [Regression]: install-deps --dry-run can no longer be used to generate install script\n\n## 15. 安装坑 · 来源证据：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2c207034cca249f7b5c12ac82005f46f | https://github.com/microsoft/playwright/issues/13027 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 16. 安装坑 · 来源证据：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_1099381b0b074addae62105e5328e211 | https://github.com/microsoft/playwright/issues/40826 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 17. 安装坑 · 来源证据：[Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: In VS Code, tests are not displayed in the Testing section.\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_37a2f26303c64848818cc2f7865f7426 | https://github.com/microsoft/playwright/issues/40481 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 18. 安装坑 · 来源证据：[Feature] Configure web servers per project\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Configure web servers per project\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_528a2b31f563446684290d7dc62c0b9f | https://github.com/microsoft/playwright/issues/22496 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 19. 安装坑 · 来源证据：[Feature]: Configurable last-run file location for improved CI shard use\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Configurable last-run file location for improved CI shard use\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_0e5ae6ed54b0470dad14f33379cd267a | https://github.com/microsoft/playwright/issues/40805 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 20. 安装坑 · 来源证据：[Feature]: keyboard.pressSequence() for batched named key presses\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: keyboard.pressSequence() for batched named key presses\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_0ea0c22b305a43d48f3cd020cb99d222 | https://github.com/microsoft/playwright/issues/40740 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 21. 安装坑 · 来源证据：[Regression]: install-deps --dry-run can no longer be used to generate install script\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Regression]: install-deps --dry-run can no longer be used to generate install script\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f01d9cdd9bf0431b887c561d41e500d4 | https://github.com/microsoft/playwright/issues/40885 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 22. 配置坑 · 失败模式：configuration: [Bug]: newPage sometimes hangs indefinitely on Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Bug]: newPage sometimes hangs indefinitely on Firefox\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug]: newPage sometimes hangs indefinitely on Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: newPage sometimes hangs indefinitely on Firefox. Context: Observed when using windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_e47d5fda2471b4288d1427ec676e3942 | https://github.com/microsoft/playwright/issues/40882 | [Bug]: newPage sometimes hangs indefinitely on Firefox\n\n## 23. 配置坑 · 失败模式：configuration: [Feature]: Configurable last-run file location for improved CI shard use\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Configurable last-run file location for improved CI shard use\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Configurable last-run file location for improved CI shard use\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Configurable last-run file location for improved CI shard use. Context: Observed when using python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7cbc84a1a300e023acd52c21ad246467 | https://github.com/microsoft/playwright/issues/40805 | [Feature]: Configurable last-run file location for improved CI shard use\n\n## 24. 配置坑 · 失败模式：configuration: [Feature]: Fail tests on page errors\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Fail tests on page errors\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Fail tests on page errors\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Fail tests on page errors. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_face5b21f87e009618730d0ba96565c5 | https://github.com/microsoft/playwright/issues/40880 | [Feature]: Fail tests on page errors\n\n## 25. 配置坑 · 失败模式：configuration: [Feature]: Hierarchal Projects\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Hierarchal Projects\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Hierarchal Projects\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Hierarchal Projects. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_4c57d49ac0e7f3d85ed34fcff015d2c1 | https://github.com/microsoft/playwright/issues/40890 | [Feature]: Hierarchal Projects\n\n## 26. 配置坑 · 失败模式：configuration: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces. Context: Observed when using python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_8ef6929f8ee894946dadbc5a2e818841 | https://github.com/microsoft/playwright/issues/40681 | [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n## 27. 配置坑 · 来源证据：[Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_eefd168ed7194785a44744e0d489dc34 | https://github.com/microsoft/playwright/issues/31162 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 28. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:221981891 | https://github.com/microsoft/playwright | README/documentation is current enough for a first validation pass.\n\n## 29. 运行坑 · 失败模式：runtime: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [BUG] \"NS_BINDING_ABORTED\" error in Firefox. Context: Observed when using node, playwright, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_21f0858060c2b2d6c7f5f8f26ec42f3e | https://github.com/microsoft/playwright/issues/20749 | [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n## 30. 运行坑 · 失败模式：runtime: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox. Context: Observed when using node, docker, playwright, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_fb1936317ab9129c8d5d5dc060c212ee | https://github.com/microsoft/playwright/issues/13027 | [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n## 31. 运行坑 · 失败模式：runtime: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_18f4dc6435817d05134a997d1ad7134e | https://github.com/microsoft/playwright/issues/31162 | [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n## 32. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | last_activity_observed missing\n\n## 33. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:221981891 | https://github.com/microsoft/playwright | no_demo; severity=medium\n\n## 34. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:221981891 | https://github.com/microsoft/playwright | no_demo; severity=medium\n\n## 35. 安全/权限坑 · 来源证据：[Feature] support WebAuthn\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature] support WebAuthn\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_874db657219c4a63a90b030fed024459 | https://github.com/microsoft/playwright/issues/7276 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 36. 安全/权限坑 · 来源证据：[Feature]: Multi-Tab and Multi-Browser Recording Support\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Multi-Tab and Multi-Browser Recording Support\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dcba5ea273d149518992b7a0beaa9868 | https://github.com/microsoft/playwright/issues/40769 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 37. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | issue_or_pr_quality=unknown\n\n## 38. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | release_recency=unknown\n\n<!-- canonical_name: microsoft/playwright; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "playwright",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:221981891",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/microsoft/playwright"
        },
        {
          "evidence_id": "art_b2213d06a04743089bd0d2db345084dd",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/microsoft/playwright#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "playwright 说明书",
      "toc": [
        "https://github.com/microsoft/playwright 项目说明书",
        "目录",
        "Playwright Introduction and Project Overview",
        "1. Overview",
        "2. Project Architecture",
        "3. Browser Automation Capabilities",
        "4. Test Execution Framework",
        "Run all tests",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "474d3c1ec8739f94c6e227a44b6d62d6b0ce6d94",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "package.json",
      "README.md",
      "docs/src/emulation.md",
      "docs/src/other-locators.md",
      "docs/src/codegen.md",
      "docs/src/library-csharp.md",
      "docs/src/test-retries-js.md",
      "docs/src/test-runners-python.md",
      "docs/src/test-cli-js.md",
      "docs/src/test-webserver-js.md",
      "docs/src/intro-python.md",
      "docs/src/test-reporters-js.md",
      "docs/src/api-testing-js.md",
      "docs/src/writing-tests-js.md",
      "docs/src/locators.md",
      "docs/src/running-tests-java.md",
      "docs/src/protractor-js.md",
      "docs/src/dialogs.md",
      "docs/src/running-tests-csharp.md",
      "docs/src/frames.md",
      "docs/src/junit-java.md",
      "docs/src/api-testing-python.md",
      "docs/src/getting-started-mcp.md",
      "docs/src/accessibility-testing-java.md",
      "docs/src/events.md",
      "docs/src/trace-viewer.md",
      "docs/src/screenshots.md",
      "docs/src/test-parameterize-js.md",
      "docs/src/service-workers-js-python.md",
      "docs/src/threading-java.md",
      "docs/src/api-testing-java.md",
      "docs/src/test-projects-js.md",
      "docs/src/test-timeouts-js.md",
      "docs/src/running-tests-js.md",
      "docs/src/trace-viewer-intro-csharp.md",
      "docs/src/release-notes-js.md",
      "docs/src/browser-contexts.md",
      "docs/src/intro-js.md",
      "docs/src/mock.md",
      "docs/src/library-js.md"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# playwright-internal - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 playwright-internal 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md`, `packages/playwright-core/src/tools/trace/SKILL.md` Claim：`clm_0004` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md`, `packages/playwright-core/src/tools/trace/SKILL.md` Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 怎么开始\n\n- `npm i -D @playwright/test` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `npx playwright install` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `npx playwright test` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `npx playwright show-trace trace.zip` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `npm install -g @playwright/cli@latest` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `claude mcp add playwright npx @playwright/mcp@latest` 证据：`README.md` Claim：`clm_0010` supported 0.86\n- `npm i playwright` 证据：`README.md` Claim：`clm_0011` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做权限沙盒试用\n- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。\n\n### 30 秒判断\n\n- **现在怎么做**：先做权限沙盒试用\n- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md`, `packages/playwright-core/src/tools/trace/SKILL.md` Claim：`clm_0004` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md`, `packages/playwright-core/src/tools/trace/SKILL.md` Claim：`clm_0001` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `CLAUDE.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `CLAUDE.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0012` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0013` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`.claude/skills/playwright-dev/SKILL.md`, `.claude/skills/playwright-devops/SKILL.md`, `packages/playwright-core/src/tools/cli-client/skill/SKILL.md`, `packages/playwright-core/src/tools/trace/SKILL.md` Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n### 上下文规模\n\n- 文件总数：2742\n- 重要文件覆盖：40/2742\n- 证据索引条目：80\n- 角色 / Skill 条目：4\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 playwright-internal 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 playwright-internal 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 playwright-internal 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 4 个角色 / Skill / 项目文档条目。\n\n- **playwright-dev**（skill）：Explains how to develop Playwright - add APIs, MCP tools, CLI commands, and vendor dependencies. 激活提示：当用户任务与“playwright-dev”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.claude/skills/playwright-dev/SKILL.md`\n- **playwright-devops**（skill）：DevOps workflows for Playwright - CI failure analysis, workflow debugging, and release operations. 激活提示：当用户任务与“playwright-devops”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.claude/skills/playwright-devops/SKILL.md`\n- **playwright-cli**（skill）：Automate browser interactions, test web pages and work with Playwright tests. 激活提示：当用户任务与“playwright-cli”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/playwright-core/src/tools/cli-client/skill/SKILL.md`\n- **playwright-trace**（skill）：Inspect Playwright trace files from the command line — list actions, view requests, console, errors, snapshots and screenshots. 激活提示：当用户任务与“playwright-trace”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`packages/playwright-core/src/tools/trace/SKILL.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **Monorepo Packages**（documentation）：Package npm name Purpose --------- ---------- --------- playwright-core playwright-core Browser automation engine: client, server, dispatchers, protocol playwright playwright Test runner + browser automation public package playwright-test @playwright/test Test runner entry point playwright-client @playwright/client Standalone client package protocol internal RPC protocol definitions protocol.yml → generated channels.d.ts 证据：`CLAUDE.md`\n- **🎭 Playwright**（documentation）：! npm version https://img.shields.io/npm/v/playwright.svg https://www.npmjs.com/package/playwright ! Chromium version https://img.shields.io/badge/chromium-149.0.7827.3-blue.svg?logo=google-chrome https://www.chromium.org/Home ! Firefox version https://img.shields.io/badge/firefox-150.0.2-blue.svg?logo=firefoxbrowser https://www.mozilla.org/en-US/firefox/new/ ! WebKit version https://img.shields.io/badge/webkit-26.4-blue.svg?logo=safari https://webkit.org/ ! Join Discord https://img.shields.io/badge/join-discord-informational https://aka.ms/playwright/discord 证据：`README.md`\n- **Tool for printing .exe and .dll dependencies on Windows**（documentation）：Tool for printing .exe and .dll dependencies on Windows 证据：`browser_patches/winldd/README.md`\n- **Battery Status API**（documentation）：Demo http://pazguille.github.io/demo-battery-api/ 证据：`examples/mock-battery/demo-battery-api/README.md`\n- **Playwright Chrome Extension**（documentation）：The Playwright Chrome Extension allows you to connect to pages in your existing browser and leverage the state of your default user profile. This means the AI assistant can interact with websites where you're already logged in, using your existing cookies, sessions, and browser state, providing a seamless experience without requiring separate authentication or setup. 证据：`packages/extension/README.md`\n- **Injected**（documentation）：This directory contains helper sources which are injected into the page. 证据：`packages/injected/src/README.md`\n- **@playwright/browser-chromium**（documentation）：This package automatically installs Chromium https://www.chromium.org/ browser for Playwright http://github.com/microsoft/playwright library. If you want to write end-to-end tests, we recommend @playwright/test https://playwright.dev/docs/intro . 证据：`packages/playwright-browser-chromium/README.md`\n- **@playwright/browser-firefox**（documentation）：This package automatically installs Firefox https://www.mozilla.org/firefox/ browser for Playwright http://github.com/microsoft/playwright library. If you want to write end-to-end tests, we recommend @playwright/test https://playwright.dev/docs/intro . 证据：`packages/playwright-browser-firefox/README.md`\n- **@playwright/browser-webkit**（documentation）：This package automatically installs WebKit https://www.webkit.org/ browser for Playwright http://github.com/microsoft/playwright library. If you want to write end-to-end tests, we recommend @playwright/test https://playwright.dev/docs/intro . 证据：`packages/playwright-browser-webkit/README.md`\n- **playwright-chromium**（documentation）：This package contains the Chromium https://www.chromium.org/ flavor of the Playwright http://github.com/microsoft/playwright library. If you want to write end-to-end tests, we recommend @playwright/test https://playwright.dev/docs/intro . 证据：`packages/playwright-chromium/README.md`\n- **playwright-core**（documentation）：This package contains the no-browser flavor of Playwright http://github.com/microsoft/playwright . 证据：`packages/playwright-core/README.md`\n- **Readme**（documentation）：BEWARE This package is EXPERIMENTAL and does not respect semver. 证据：`packages/playwright-ct-core/README.md`\n- **Readme**（documentation）：BEWARE This package is EXPERIMENTAL and does not respect semver. 证据：`packages/playwright-ct-react/README.md`\n- **Readme**（documentation）：BEWARE This package is EXPERIMENTAL and does not respect semver. 证据：`packages/playwright-ct-react17/README.md`\n- **Readme**（documentation）：BEWARE This package is EXPERIMENTAL and does not respect semver. 证据：`packages/playwright-ct-vue/README.md`\n- **playwright-firefox**（documentation）：This package contains the Firefox https://www.mozilla.org/firefox/ flavor of the Playwright http://github.com/microsoft/playwright library. If you want to write end-to-end tests, we recommend @playwright/test https://playwright.dev/docs/intro . 证据：`packages/playwright-firefox/README.md`\n- **playwright-webkit**（documentation）：This package contains the WebKit https://www.webkit.org/ flavor of the Playwright http://github.com/microsoft/playwright library. If you want to write end-to-end tests, we recommend @playwright/test https://playwright.dev/docs/intro . 证据：`packages/playwright-webkit/README.md`\n- **Readme**（documentation）：Tests derived from axe-core test suite: https://github.com/dequelabs/axe-core/tree/develop/test. 证据：`tests/assets/axe-core/README.md`\n- **Client Certificate test-certificates**（documentation）：Client Certificate test-certificates 证据：`tests/assets/client-certificates/README.md`\n- **Playwright Modernizr tests**（documentation）：- modernizr.com modernizr.com isn't getting updated anymore, see here https://github.com/Modernizr/Modernizr/issues/2490 and here https://github.com/Modernizr/Modernizr/commit/db96bdaff995a1d4abccb0dc69c77db7b47ad614 . It only contains version 3.6. - This is why we build it from source ourselves, using roll.sh they recommend it . 证据：`tests/assets/modernizr/README.md`\n- **Readme**（documentation）：Source: https://github.com/mdn/dom-examples/tree/main/to-do-notifications 证据：`tests/assets/to-do-notifications/README.md`\n- **Regenerating**（documentation）：This font contains two glyphs — + U+2B and - U+2D — each rendered as a simple filled black rectangle. The simplicity makes screenshot tests insensitive to font-rendering/antialiasing differences across platforms. 证据：`tests/assets/webfont/README.md`\n- **Readme**（documentation）：Web platform tests are copied from https://github.com/web-platform-tests/wpt at revision 5adfe4e8cd223729aa2942915e8a515c079ed0ef . 证据：`tests/assets/wpt/README.md`\n- **Running Bidi tests**（documentation）：To install beta channel of Firefox, run the following command in the project root: After that you need to pass custom firefox binary path to the test runner via BIDI FFPATH : 证据：`tests/bidi/README.md`\n- **Getting Started with Create React App**（documentation）：Getting Started with Create React App 证据：`tests/components/ct-react17/README.md`\n- **ct-vue-cli**（documentation）：Compiles and hot-reloads for development 证据：`tests/components/ct-vue-cli/README.md`\n- **ct1**（documentation）：This template should help get you started developing with Vue 3 in Vite. 证据：`tests/components/ct-vue-vite/README.md`\n- **Julia SSIM trap**（documentation）：SSIM https://en.wikipedia.org/wiki/Structural similarity is a metric used to compare image similarity. 证据：`tests/image_tools/fixtures/should-fail/julia-ssim-trap/README.md`\n- **Readme**（documentation）：These tests are coming from the looks-same library: - https://github.com/gemini-testing/looks-same/blob/b9399bce8fd980e6e59cf740bee3cd3fe66c3eae/test/test.js 证据：`tests/image_tools/fixtures/should-fail/looks-same-tests/README.md`\n- **Original SSIM trap**（documentation）：SSIM https://en.wikipedia.org/wiki/Structural similarity is a metric used to compare image similarity. 证据：`tests/image_tools/fixtures/should-fail/original-ssim-trap/README.md`\n- **Trivial failing examples**（documentation）：Trivial failing examples Some trivial failing examples 证据：`tests/image_tools/fixtures/should-fail/trivial/README.md`\n- **Chrome non-deterministic rendering**（documentation）：Reported by: https://bugs.chromium.org/p/chromium/issues/detail?id=919955 证据：`tests/image_tools/fixtures/should-match/crbug-919955/README.md`\n- **Readme**（documentation）：These tests are coming from the looks-same library: - https://github.com/gemini-testing/looks-same/blob/b9399bce8fd980e6e59cf740bee3cd3fe66c3eae/test/test.js 证据：`tests/image_tools/fixtures/should-match/looks-same-tests/README.md`\n- **Tiny anti-aliasing sample**（documentation）：This is a 10x10 image sample with a 3 anti-aliased pixels in-between. This is actually a cropped down snapshot of one of the ubuntu-x86-vs-ubuntu-arm samples ../ubuntu-x86-vs-ubuntu-arm/samples/stylings stories-Stylings-stories-Texture-bar-should-use-custom-path-chrome/stylings-stories/texture/bar/should-use-custom-path-actual.png handy for debugging purposes. 证据：`tests/image_tools/fixtures/should-match/tiny-antialiasing-sample/README.md`\n- **Equal small images**（documentation）：Equal small images Simple equal images. 证据：`tests/image_tools/fixtures/should-match/trivial/README.md`\n- **Readme**（documentation）：A set of examples with rendering artifacts that happen when running Playwright screenshot tests on WebKit linux. 证据：`tests/image_tools/fixtures/should-match/webkit-rendering-artifacts/README.md`\n- **Readme**（documentation）：This directory holds a stable test runner: - It is possible to test broken test runner with a stable working one. - Dependencies between ToT and stable test runner do not clash. 证据：`tests/playwright-test/stable-test-runner/README.md`\n- **Readme**（documentation）：This folder contains the proxy https://github.com/TooTallNate/proxy-agents library vendored at commit c881a1804197b89580320b87082971c3c6a61746 with the following modifications: 证据：`tests/third_party/proxy/README.md`\n- **Flakiness Dashboard Backend**（documentation）：This directory contains source code for the Azure function that we use to aggregate test reports. The data is consumed by https://devops.playwright.dev/flakiness.html 证据：`utils/flakiness-dashboard/README.md`\n- **Mapping distribution libraries to package names**（documentation）：Mapping distribution libraries to package names 证据：`utils/linux-browser-dependencies/README.md`\n- **Package**（package_manifest）：{ \"name\": \"playwright-internal\", \"private\": true, \"version\": \"1.61.0-next\", \"description\": \"A high-level API to automate web browsers\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"scripts\": { \"ctest\": \"playwright test --config=tests/library/playwright.config.ts --project=chromium- \", \"ftest\": \"playwright test --config=tests/library/playwright.config.ts --project=firefox- \", \"wtest\": \"playwright test --config=tests/library/playwright.config.ts --project=webkit- \", \"atest\": \"playwright test --config=tests/a… 证据：`package.json`\n- **Contributing**（documentation）：To maintain project quality and focus, Playwright requires a corresponding issue for every contribution, with the exception of minor documentation fixes. 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"github-api\", \"version\": \"0.0.1\", \"scripts\": { \"test\": \"playwright test\" }, \"keywords\": , \"author\": \"\", \"license\": \"ISC\", \"devDependencies\": { \"@playwright/test\": \"^1.17.1\" } } 证据：`examples/github-api/package.json`\n- **Package**（package_manifest）：{ \"name\": \"mock-battery\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"scripts\": { \"test\": \"playwright test\", \"start\": \"http-server -c-1 -p 9900 demo-battery-api\" }, \"keywords\": , \"author\": \"\", \"license\": \"ISC\", \"devDependencies\": { \"@playwright/test\": \"^1.19.1\", \"http-server\": \"^14.1.0\" } } 证据：`examples/mock-battery/package.json`\n- **Package**（package_manifest）：{ \"name\": \"mock-filesystem\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"scripts\": { \"test\": \"playwright test\", \"start\": \"http-server -c-1 -p 9900 src/\" }, \"keywords\": , \"author\": \"\", \"license\": \"ISC\", \"devDependencies\": { \"@playwright/test\": \"^1.19.1\", \"http-server\": \"^14.1.0\" } } 证据：`examples/mock-filesystem/package.json`\n- **Package**（package_manifest）：{ \"name\": \"svgomg-tests\", \"version\": \"0.0.1\", \"scripts\": { \"test\": \"playwright test\", \"ctest\": \"playwright test --project=chromium\", \"ftest\": \"playwright test --project=firefox\", \"wtest\": \"playwright test --project=webkit\" }, \"keywords\": , \"author\": \"\", \"license\": \"ISC\", \"devDependencies\": { \"@playwright/test\": \"^1.17.1\" } } 证据：`examples/svgomg/package.json`\n- **Package**（package_manifest）：{ \"name\": \"todomvc-test\", \"version\": \"0.0.1\", \"scripts\": { \"test\": \"playwright test\", \"ctest\": \"playwright test --project=chromium\", \"ftest\": \"playwright test --project=firefox\", \"wtest\": \"playwright test --project=webkit\" }, \"keywords\": , \"author\": \"\", \"license\": \"ISC\", \"devDependencies\": { \"@playwright/test\": \"^1.38.0\", \"dotenv\": \"^17.2.3\" } } 证据：`examples/todomvc/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/dashboard\", \"private\": true, \"version\": \"0.0.0\", \"type\": \"module\", \"dependencies\": { \"@browser-logos/chrome\": \"2.0.0\", \"@browser-logos/chrome-beta\": \"3.0.0\", \"@browser-logos/chrome-canary\": \"2.0.0\", \"@browser-logos/chrome-dev\": \"3.0.0\", \"@browser-logos/chromium\": \"2.0.1\", \"@browser-logos/edge\": \"2.0.7\", \"@browser-logos/firefox\": \"3.0.10\", \"@browser-logos/firefox-beta\": \"4.1.4\", \"@browser-logos/firefox-nightly\": \"3.0.6\", \"@browser-logos/safari\": \"2.1.0\" } } 证据：`packages/dashboard/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/extension\", \"version\": \"0.2.1\", \"description\": \"Playwright Browser Extension\", \"private\": true, \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\" } 证据：`packages/extension/package.json`\n- **Package**（package_manifest）：{ \"name\": \"html-reporter\", \"private\": true, \"version\": \"0.0.0\", \"type\": \"module\" } 证据：`packages/html-reporter/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/browser-chromium\", \"version\": \"1.61.0-next\", \"description\": \"Playwright package that automatically installs Chromium\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"import\": \"./index.mjs\", \"require\": \"./index.js\", \"default\": \"./index.js\" }, \"./package.json\": \"./package.json\" }, \"scripts\": { \"install\": \"node install.js\" }, \"dependencies\": { \"playwright-core\": \"1.61.0-next\" } } 证据：`packages/playwright-browser-chromium/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/browser-firefox\", \"version\": \"1.61.0-next\", \"description\": \"Playwright package that automatically installs Firefox\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"import\": \"./index.mjs\", \"require\": \"./index.js\", \"default\": \"./index.js\" }, \"./package.json\": \"./package.json\" }, \"scripts\": { \"install\": \"node install.js\" }, \"dependencies\": { \"playwright-core\": \"1.61.0-next\" } } 证据：`packages/playwright-browser-firefox/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/browser-webkit\", \"version\": \"1.61.0-next\", \"description\": \"Playwright package that automatically installs WebKit\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"import\": \"./index.mjs\", \"require\": \"./index.js\", \"default\": \"./index.js\" }, \"./package.json\": \"./package.json\" }, \"scripts\": { \"install\": \"node install.js\" }, \"dependencies\": { \"playwright-core\": \"1.61.0-next\" } } 证据：`packages/playwright-browser-webkit/package.json`\n- **Package**（package_manifest）：{ \"name\": \"playwright-chromium\", \"version\": \"1.61.0-next\", \"description\": \"A high-level API to automate Chromium\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"import\": \"./index.mjs\", \"require\": \"./index.js\", \"default\": \"./index.js\" }, \"./package.json\": \"./package.json\" }, \"bin\": { \"playwright\": \"cli.js\" }, \"scripts\": { \"install\": \"node install.js\" }, \"dependencies\": { \"playwright-core\": \"1.61.0-next\" } } 证据：`packages/playwright-chromium/package.json`\n- **Package**（package_manifest）：{ \"name\": \"playwright-cli-stub\", \"version\": \"0.0.0\", \"private\": true, \"bin\": { \"playwright-cli\": \"playwright-cli-stub.js\" } } 证据：`packages/playwright-cli-stub/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/client\", \"private\": true, \"version\": \"0.0.0\", \"description\": \"A thin client for Playwright\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"import\": \"./index.mjs\", \"require\": \"./index.js\", \"default\": \"./index.js\" }, \"./package.json\": \"./package.json\" }, \"scripts\": { \"esbuild\": \"node build.js\", \"build\": \"npm run esbuild\", \"watch\": \"npm run esbuild -- --watch\" }, \"dependencies\": { \"playwright-core\": \"1.61.0-next\" } } 证据：`packages/playwright-client/package.json`\n- **Package**（package_manifest）：{ \"name\": \"playwright-core\", \"version\": \"1.61.0-next\", \"description\": \"A high-level API to automate web browsers\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"import\": \"./index.mjs\", \"require\": \"./index.js\", \"default\": \"./index.js\" }, \"./package.json\": \"./package.json\", \"./lib/bootstrap\": \"./lib/bootstrap.js\", \"./lib/coreBundle\": \"./lib/coreBundle.js\", \"./lib/utilsBundle\": \"./lib/utilsBundle.js\", \"./lib/tools/cli-client/program\": \"./lib/tools/cli-client/program… 证据：`packages/playwright-core/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/experimental-ct-core\", \"version\": \"1.61.0-next\", \"description\": \"Playwright Component Testing Helpers\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"default\": \"./index.js\" }, \"./lib/mount\": \"./lib/mount.js\", \"./lib/program\": \"./lib/program.js\", \"./types/component\": { \"types\": \"./types/component.d.ts\" } }, \"dependencies\": { \"playwright-core\": \"1.61.0-next\", \"vite\": \"^6.4.1\", \"playwright\": \"1.61.0-next\" } } 证据：`packages/playwright-ct-core/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/experimental-ct-react\", \"version\": \"1.61.0-next\", \"description\": \"Playwright Component Testing for React\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"default\": \"./index.js\" }, \"./register\": { \"types\": \"./register.d.ts\", \"default\": \"./register.mjs\" }, \"./hooks\": { \"types\": \"./hooks.d.ts\", \"default\": \"./hooks.mjs\" }, \"./package.json\": \"./package.json\" }, \"dependencies\": { \"@playwright/experimental-ct-core\": \"1.61.0-next\", \"@vitejs/plugin-r… 证据：`packages/playwright-ct-react/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@playwright/experimental-ct-react17\", \"version\": \"1.61.0-next\", \"description\": \"Playwright Component Testing for React\", \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/microsoft/playwright.git\" }, \"homepage\": \"https://playwright.dev\", \"engines\": { \"node\": \" =18\" }, \"author\": { \"name\": \"Microsoft Corporation\" }, \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./index.d.ts\", \"default\": \"./index.js\" }, \"./register\": { \"types\": \"./register.d.ts\", \"default\": \"./register.mjs\" }, \"./hooks\": { \"types\": \"./hooks.d.ts\", \"default\": \"./hooks.mjs\" }, \"./package.json\": \"./package.json\" }, \"dependencies\": { \"@playwright/experimental-ct-core\": \"1.61.0-next\", \"@vitejs/plugin… 证据：`packages/playwright-ct-react17/package.json`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`CLAUDE.md`, `README.md`, `browser_patches/winldd/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`CLAUDE.md`, `README.md`, `browser_patches/winldd/README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Playwright Introduction and Project Overview**：importance `high`\n  - source_paths: README.md, packages/playwright/package.json, packages/playwright-core/package.json, package.json\n- **Package Ecosystem and Monorepo Structure**：importance `high`\n  - source_paths: packages/playwright/src/index.ts, packages/playwright-core/src/index.ts, packages/playwright-core/src/server/index.ts, package.json\n- **Client-Server Communication Architecture**：importance `high`\n  - source_paths: packages/playwright-core/src/client/channelOwner.ts, packages/playwright-core/src/client/connection.ts, packages/playwright-core/src/server/dispatchers/dispatcher.ts, packages/playwright-core/src/remote/playwrightConnection.ts, packages/protocol/src/channels.d.ts\n- **Browser Launch and Process Management**：importance `high`\n  - source_paths: packages/playwright-core/src/outofprocess.ts, packages/playwright-core/src/inprocess.ts, packages/playwright-core/src/server/browserType.ts, packages/playwright-core/src/server/browser.ts, packages/utils/processLauncher.ts\n- **Test Runner and Execution Engine**：importance `high`\n  - source_paths: packages/playwright/src/runner/testRunner.ts, packages/playwright/src/runner/dispatcher.ts, packages/playwright/src/common/testLoader.ts, packages/playwright/src/common/fixtures.ts, packages/playwright/src/common/poolBuilder.ts\n- **Locators, Selectors, and Element Interaction**：importance `high`\n  - source_paths: packages/playwright-core/src/client/locator.ts, packages/injected/src/selectorEngine.ts, packages/injected/src/selectorGenerator.ts, packages/injected/src/roleSelectorEngine.ts, packages/injected/src/selectorEvaluator.ts\n- **Assertions, Matchers, and Expect API**：importance `high`\n  - source_paths: packages/playwright/src/matchers/expect.ts, packages/playwright/src/matchers/matchers.ts, packages/playwright/src/matchers/toMatchSnapshot.ts, packages/playwright/src/matchers/toMatchAriaSnapshot.ts, packages/isomorphic/expectUtils.ts\n- **Browser Implementations and Protocol Support**：importance `high`\n  - source_paths: packages/playwright-core/src/server/chromium/chromium.ts, packages/playwright-core/src/server/chromium/crBrowser.ts, packages/playwright-core/src/server/firefox/firefox.ts, packages/playwright-core/src/server/firefox/ffBrowser.ts, packages/playwright-core/src/server/webkit/webkit.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `474d3c1ec8739f94c6e227a44b6d62d6b0ce6d94`\n- inspected_files: `package.json`, `README.md`, `docs/src/emulation.md`, `docs/src/other-locators.md`, `docs/src/codegen.md`, `docs/src/library-csharp.md`, `docs/src/test-retries-js.md`, `docs/src/test-runners-python.md`, `docs/src/test-cli-js.md`, `docs/src/test-webserver-js.md`, `docs/src/intro-python.md`, `docs/src/test-reporters-js.md`, `docs/src/api-testing-js.md`, `docs/src/writing-tests-js.md`, `docs/src/locators.md`, `docs/src/running-tests-java.md`, `docs/src/protractor-js.md`, `docs/src/dialogs.md`, `docs/src/running-tests-csharp.md`, `docs/src/frames.md`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 来源证据：[Feature]: Fail tests on page errors\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Fail tests on page errors\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_347cf8732e73437a9699e4d8bc55d958 | https://github.com/microsoft/playwright/issues/40880 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：[Feature]: Ubuntu 26.04 LTS support\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Ubuntu 26.04 LTS support\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_764e9005d6a94f41b4a8d9f52decca99 | https://github.com/microsoft/playwright/issues/40117 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：[Feature]: trace correlation hooks for external observability/replay systems\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: trace correlation hooks for external observability/replay systems\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_3c11bc1bf38e448f82e5b70d9f909037 | https://github.com/microsoft/playwright/issues/40887 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：[Feature]: support signal in waitFor* APIs\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Feature]: support signal in waitFor* APIs\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_500f564d44534739b16e93ed0b6a86eb | https://github.com/microsoft/playwright/issues/40578 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_16f48d22960444cfa514e3e08d959d45 | https://github.com/microsoft/playwright/issues/20749 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 失败模式：security_permissions: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path...\n\n- Trigger: Developers should check this security_permissions risk before relying on the project: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only. Context: Observed when using node, docker, playwright, linux\n- Why it matters: Developers may expose sensitive permissions or credentials: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- Evidence: failure_mode_cluster:github_issue | fmev_32d5131674a6cea46a3dd9fea57edcee | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only, failure_mode_cluster:github_issue | fmev_5eb5ff7b9134ac254ca127feb48992d6 | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 来源证据：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_641150bc817a45af974903e3c724aa41 | https://github.com/microsoft/playwright/issues/40681 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 失败模式：installation: [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- Trigger: Developers should check this installation risk before relying on the project: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: In VS Code, tests are not displayed in the Testing section.. Context: Observed when using node, playwright, windows, macos\n- Why it matters: Developers may fail before the first successful local run: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- Evidence: failure_mode_cluster:github_issue | fmev_429f2bbd1fa3334bca8aae5ee7df68b8 | https://github.com/microsoft/playwright/issues/40481 | [Bug]: In VS Code, tests are not displayed in the Testing section.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 失败模式：installation: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n- Trigger: Developers should check this installation risk before relying on the project: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1. Context: Observed when using node, playwright\n- Why it matters: Developers may fail before the first successful local run: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- Evidence: failure_mode_cluster:github_issue | fmev_09c75aac9731971717426ccfbe72651b | https://github.com/microsoft/playwright/issues/40904 | [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 失败模式：installation: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests nev...\n\n- Trigger: Developers should check this installation risk before relying on the project: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite. Context: Observed when using node, playwright, windows\n- Why it matters: Developers may fail before the first successful local run: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- Evidence: failure_mode_cluster:github_issue | fmev_bd2b1ca9bdfc4104afb98768ab5f87d4 | https://github.com/microsoft/playwright/issues/40889 | [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：microsoft/playwright\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：local_cli\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：[Feature]: Fail tests on page errors（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：[Feature]: Ubuntu 26.04 LTS support（high）：可能阻塞安装或首次运行。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：[Feature]: trace correlation hooks for external observability/replay systems（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：[Feature]: support signal in waitFor* APIs（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：[BUG] \"NS_BINDING_ABORTED\" error in Firefox（high）：可能阻塞安装或首次运行。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/microsoft/playwright 项目说明书\n\n生成时间：2026-05-16 07:17:40 UTC\n\n## 目录\n\n- [Playwright Introduction and Project Overview](#page-1)\n- [Package Ecosystem and Monorepo Structure](#page-2)\n- [Client-Server Communication Architecture](#page-3)\n- [Browser Launch and Process Management](#page-4)\n- [Test Runner and Execution Engine](#page-5)\n- [Locators, Selectors, and Element Interaction](#page-6)\n- [Assertions, Matchers, and Expect API](#page-7)\n- [Browser Implementations and Protocol Support](#page-8)\n- [Trace Viewer and Debugging Tools](#page-9)\n- [CLI, MCP Server, and Agent Integration](#page-10)\n\n<a id='page-1'></a>\n\n## Playwright Introduction and Project Overview\n\n### 相关页面\n\n相关主题：[Package Ecosystem and Monorepo Structure](#page-2), [Test Runner and Execution Engine](#page-5)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n- [packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n- [packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n- [packages/playwright-core/src/tools/cli-client/skill/references/session-management.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md)\n- [packages/injected/src/consoleApi.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/consoleApi.ts)\n- [packages/injected/src/roleUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleUtils.ts)\n- [packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n- [packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n</details>\n\n# Playwright Introduction and Project Overview\n\n## 1. Overview\n\nPlaywright is a powerful end-to-end testing framework developed by Microsoft that enables reliable browser automation. It supports testing across multiple browsers (Chromium, Firefox, WebKit) with a single unified API, making it ideal for modern web application testing.\n\nThe project provides comprehensive tools for browser automation, test execution, debugging, and trace inspection. Playwright is designed to handle complex web scenarios including single-page applications, modern JavaScript frameworks, and sophisticated user interactions.\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n## 2. Project Architecture\n\n### 2.1 Core Packages\n\nThe Playwright project is organized as a monorepo with several key packages:\n\n| Package | Purpose |\n|---------|---------|\n| `playwright` | Main package with full test runner and all browser support |\n| `playwright-core` | Core browser automation library without bundled browsers |\n| `trace-viewer` | Web-based trace analysis and visualization tool |\n| `html-reporter` | Test report generation and visualization |\n| `injected` | In-browser script injection utilities |\n\n### 2.2 High-Level Architecture\n\n```mermaid\ngraph TD\n    A[Playwright Test Runner] --> B[playwright-core]\n    B --> C[Browser Drivers]\n    C --> D[Chromium]\n    C --> E[Firefox]\n    C --> F[WebKit]\n    B --> G[Connection Layer]\n    G --> H[Channel Owners]\n    H --> I[Page]\n    H --> J[Request/Response]\n    H --> K[Route]\n    H --> L[Tracing]\n    H --> M[WebSocket]\n    A --> N[HTML Reporter]\n    A --> O[Trace Viewer]\n```\n\n资料来源：[packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n\n### 2.3 Channel Owner System\n\nPlaywright uses a channel-based communication system where various browser objects are managed through factory functions:\n\n```mermaid\ngraph LR\n    A[Local Utils] --> B[Page]\n    A --> C[Playwright]\n    A --> D[Request]\n    A --> E[Response]\n    A --> F[Route]\n    A --> G[Tracing]\n    A --> H[WebSocket]\n```\n\nThe connection layer registers object factories for different types:\n\n```typescript\nPage: (parent, type, guid, init) => new Page(parent, type, guid, init),\nRequest: (parent, type, guid, init) => new Request(parent, type, guid, init),\nResponse: (parent, type, guid, init) => new Response(parent, type, guid, init),\nRoute: (parent, type, guid, init) => new Route(parent, type, guid, init),\nTracing: (parent, type, guid, init) => new Tracing(parent, type, guid, init),\n```\n\n资料来源：[packages/playwright-core/src/client/connection.ts:1-20](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n\n## 3. Browser Automation Capabilities\n\n### 3.1 CLI Client (playwright-cli)\n\nThe CLI client provides an interactive shell for browser automation tasks:\n\n| Command Category | Features |\n|-----------------|----------|\n| Navigation | `goto`, `back`, `forward`, `reload` |\n| Interaction | `click`, `fill`, `type`, `check`, `select` |\n| Capture | `screenshot`, `pdf`, `snapshot` |\n| Tabs | `tab-list`, `tab-new`, `tab-close`, `tab-select` |\n| Storage | `state-save`, `state-load`, `cookie-*`, `localstorage-*` |\n| Network | `route`, `unroute`, `route-list` |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n### 3.2 Injected Script API\n\nWhen Playwright injects scripts into web pages, a dedicated API becomes available:\n\n```typescript\nwindow.playwright = {\n  $: (selector: string, strict?: boolean) => this._querySelector(selector, !!strict),\n  $$: (selector: string) => this._querySelectorAll(selector),\n  inspect: (selector: string) => this._inspect(selector),\n  selector: (element: Element) => this._selector(element),\n  generateLocator: (element: Element, language?: Language) => this._generateLocator(element, language),\n  ariaSnapshot: (element?: Element, options?: AriaTreeOptions) => this._ariaSnapshot(element, options),\n  resume: () => this._resume(),\n  ...new Locator(this._injectedScript, ''),\n};\n```\n\nThe injected script is automatically installed on page load and provides DOM querying, locator generation, and ARIA snapshot capabilities.\n\n资料来源：[packages/injected/src/consoleApi.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/consoleApi.ts)\n\n### 3.3 ARIA Role Utilities\n\nPlaywright automatically maps HTML elements to ARIA roles for accessibility testing:\n\n| Element | Role Mapping |\n|---------|--------------|\n| `<H1>` - `<H6>` | `heading` |\n| `<BUTTON>` | `button` |\n| `<A>` | `link` |\n| `<INPUT type=\"search\">` | `searchbox` / `combobox` (with list) |\n| `<DIALOG>` | `dialog` |\n| `<NAV>` | `navigation` |\n| `<HEADER>` | `banner` (unless landmark prevented) |\n| `<FOOTER>` | `contentinfo` (unless landmark prevented) |\n| `<IMG alt=\"\">` | `presentation` (empty alt, no title) |\n\n```typescript\n'INPUT': (e: Element) => {\n  const type = (e as HTMLInputElement).type.toLowerCase();\n  if (type === 'search')\n    return e.hasAttribute('list') ? 'combobox' : 'searchbox';\n  // ...\n}\n```\n\n资料来源：[packages/injected/src/roleUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleUtils.ts)\n\n## 4. Test Execution Framework\n\n### 4.1 Running Tests\n\nPlaywright tests are executed using the standard Playwright test runner:\n\n```bash\n# Run all tests\nPLAYWRIGHT_HTML_OPEN=never npx playwright test\n\n# Run with custom npm script\nPLAYWRIGHT_HTML_OPEN=never npm run special-test-command\n```\n\nThe environment variable `PLAYWRIGHT_HTML_OPEN=never` prevents the interactive HTML report from opening automatically.\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n\n### 4.2 Debug Mode\n\nDebugging tests uses the CLI debug mode which pauses execution and provides debugging instructions:\n\n```bash\nPLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli\n```\n\nWhen debugging instructions appear with a session name (e.g., `tw-abcdef`), attach using:\n\n```bash\nplaywright-cli attach tw-abcdef\n```\n\nAvailable debugging commands:\n\n| Command | Purpose |\n|---------|---------|\n| `playwright-cli resume` | Resume test execution |\n| `playwright-cli snapshot` | Get inventory of interactive elements |\n| `playwright-cli click e5` | Interact with element by ref |\n| `playwright-cli eval` | Read URL/state |\n| `playwright-cli show --annotate` | Request user annotation |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n\n## 5. Browser Session Management\n\n### 5.1 Named Sessions\n\nPlaywright CLI supports multiple named browser sessions:\n\n```bash\n# Create new browser session named \"mysession\" with persistent profile\nplaywright-cli -s=mysession open example.com --persistent\n\n# Use specific session\nplaywright-cli -s=mysession click e6\n\n# Close named browser\nplaywright-cli -s=mysession close\n\n# Delete user data for persistent session\nplaywright-cli -s=mysession delete-data\n```\n\n### 5.2 Global Session Management\n\n```bash\n# List all browser sessions\nplaywright-cli list\n\n# Close all browsers\nplaywright-cli close-all\n\n# Forcefully kill all browser processes\nplaywright-cli kill-all\n```\n\n### 5.3 Environment Variable\n\nSet a default session via environment variable:\n\n```bash\nexport PLAYWRIGHT_CLI_SESSION=\"mysession\"\nplaywright-cli open example.com  # Uses \"mysession\" automatically\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/session-management.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md)\n\n## 6. Trace Viewer\n\n### 6.1 Overview\n\nThe Trace Viewer is a Progressive Web App for analyzing Playwright traces locally without sending data elsewhere:\n\n```mermaid\ngraph LR\n    A[Playwright Test] --> B[Trace.zip]\n    B --> C[Trace Viewer]\n    C --> D[Actions View]\n    C --> E[Requests View]\n    C --> F[Console View]\n    C --> G[Snapshots]\n```\n\n### 6.2 CLI Trace Commands\n\n```bash\n# Open and inspect trace\nnpx playwright trace open <trace.zip>\n\n# List all actions\nnpx playwright trace actions\n\n# Filter actions by pattern\nnpx playwright trace actions --grep \"click\"\n\n# Show only failed actions\nnpx playwright trace actions --errors-only\n\n# View specific action details\nnpx playwright trace action <action-id>\n\n# View DOM snapshot for action\nnpx playwright trace snapshot <action-id>\n\n# Evaluate JavaScript on snapshot\nnpx playwright trace snapshot <action-id> -- eval \"document.body.outerHTML\"\n\n# Export attachments\nnpx playwright trace attachments\nnpx playwright trace attachment 1 -o out.png\n```\n\n### 6.3 Typical Investigation Workflow\n\n```bash\n# 1. Open the trace\nnpx playwright trace open test-results/my-test/trace.zip\n\n# 2. View all actions\nnpx playwright trace actions\n\n# 3. Find failed actions\nnpx playwright trace actions --errors-only\n\n# 4. Inspect specific action\nnpx playwright trace action 12\n\n# 5. View page state at that moment\nnpx playwright trace snapshot 12\n\n# 6. Query DOM for details\nnpx playwright trace snapshot 12 -- eval \"document.querySelector('.error-message').textContent\"\n\n# 7. Check network failures\nnpx playwright trace requests --failed\n\n# 8. Check console errors\nnpx playwright trace console --errors-only\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n\n### 6.4 Trace Viewer UI Components\n\nThe trace viewer web application includes:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| WorkbenchLoader | `workbenchLoader.tsx` | Main application entry, handles file uploads and drag-drop |\n| BrowserFrame | `browserFrame.tsx` | Renders browser chrome with address bar |\n| MetadataView | `metadataView.tsx` | Displays test metadata (viewport, user agent, baseURL) |\n| TestCaseView | `testCaseView.tsx` | Shows individual test case details and results |\n\nThe workbench loader provides a progressive web app experience with local-only processing:\n\n```typescript\n<div className='info'>Playwright Trace Viewer is a Progressive Web App, it does not send your trace anywhere,\n  it opens it locally.</div>\n```\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n\n## 7. Key Features Summary\n\n| Feature | Description |\n|---------|-------------|\n| **Cross-browser** | Chromium, Firefox, WebKit support with single API |\n| **Auto-waiting** | Actions wait for elements to be actionable |\n| **Web-first assertions** | Built-in assertion library |\n| **Tracing** | Comprehensive action tracing and debugging |\n| **Locators** | Multiple strategies: CSS, ARIA, text, role |\n| **Network interception** | Mock and modify network requests |\n| **Storage state** | Save/restore authentication and cookies |\n| **CLI tools** | Interactive browser automation shell |\n\n## 8. Architecture Diagram: End-to-End Test Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Test\n    participant R as Playwright Runner\n    participant C as CLI Client\n    participant P as Browser\n    participant TV as Trace Viewer\n\n    T->>R: npx playwright test\n    R->>P: Launch browser\n    R->>P: Inject script\n    T->>C: playwright-cli attach\n    Note over C,P: Interactive debugging\n    P->>TV: Generate trace.zip\n    TV->>T: Analyze failures\n```\n\n## 9. Resources and Further Reading\n\n- Main Documentation: Playwright CLI capabilities and commands\n- Test Debugging: Debug mode and CLI attachment workflow\n- Trace Analysis: Using trace viewer for post-mortem analysis\n- Session Management: Multi-browser concurrent testing patterns\n- Storage State: Authentication and state persistence patterns\n\n---\n\n<a id='page-2'></a>\n\n## Package Ecosystem and Monorepo Structure\n\n### 相关页面\n\n相关主题：[Playwright Introduction and Project Overview](#page-1), [Client-Server Communication Architecture](#page-3)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [package.json](https://github.com/microsoft/playwright/blob/main/package.json)\n- [packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n- [packages/injected/src/roleUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleUtils.ts)\n- [packages/injected/src/consoleApi.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/consoleApi.ts)\n- [packages/playwright-browser-webkit/package.json](https://github.com/microsoft/playwright/blob/main/packages/playwright-browser-webkit/package.json)\n- [packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n- [examples/todomvc/package.json](https://github.com/microsoft/playwright/blob/main/examples/todomvc/package.json)\n</details>\n\n# Package Ecosystem and Monorepo Structure\n\nPlaywright is organized as a monorepo using npm workspaces, enabling centralized version management and shared tooling across multiple specialized packages. The repository contains the main `playwright` package alongside browser-specific packages, core libraries, and supporting tools.\n\n## Repository Overview\n\nThe Playwright monorepo follows a multi-package architecture where:\n\n- The root `package.json` defines shared scripts, build tooling, and workspace configuration\n- Individual packages under `packages/` contain focused, modular functionality\n- Examples under `examples/` demonstrate real-world usage patterns\n\n```mermaid\ngraph TD\n    Root[Root package.json<br/>v1.61.0-next] --> Core[playwright-core]\n    Root --> Main[playwright]\n    Root --> Chromium[playwright-browser-chromium]\n    Root --> Firefox[playwright-browser-firefox]\n    Root --> Webkit[playwright-browser-webkit]\n    Root --> Injected[injected]\n    Root --> TraceViewer[trace-viewer]\n    Root --> HtmlReporter[html-reporter]\n    \n    Core --> Injected\n    Main --> Core\n    Chromium --> Core\n    Firefox --> Core\n    Webkit --> Core\n```\n\n## Core Packages\n\n### playwright\n\nThe main public package that provides the high-level API for browser automation. It re-exports types and utilities from `playwright-core` while bundling browser automation capabilities.\n\n### playwright-core\n\nThe foundational package containing all browser automation logic. This package:\n\n- Defines client-side abstractions (`Page`, `Request`, `Response`, `Route`, `WebSocket`, `Worker`)\n- Manages channel-based communication between client and server\n- Implements the `LocalUtils` factory for shared utilities\n\nThe connection layer registers object factories for all domain objects:\n\n```typescript\nregisterObjectFactories({\n  LocalUtils: (parent, type, guid, init) => {\n    const result = new LocalUtils(parent, type, guid, init);\n    if (!this._localUtils)\n      this._localUtils = result;\n    return result;\n  },\n  Page: (parent, type, guid, init) => new Page(parent, type, guid, init),\n  Request: (parent, type, guid, init) => new Request(parent, type, guid, init),\n  Response: (parent, type, guid, init) => new Response(parent, type, guid, init),\n  Route: (parent, type, guid, init) => new Route(parent, type, guid, init),\n  Tracing: (parent, type, guid, init) => new Tracing(parent, type, guid, init),\n  WebSocket: (parent, type, guid, init) => new WebSocket(parent, type, guid, init),\n  Worker: (parent, type, guid, init) => new Worker(parent, type, guid, init),\n});\n```\n\n资料来源：[packages/playwright-core/src/client/connection.ts:10-35]()\n\n## Browser Packages\n\nBrowser-specific packages provide automatic browser installation and management. Each package depends on `playwright-core`.\n\n| Package | Purpose | Dependencies |\n|---------|---------|--------------|\n| `playwright-browser-chromium` | Chromium browser support | playwright-core |\n| `playwright-browser-firefox` | Firefox browser support | playwright-core |\n| `playwright-browser-webkit` | WebKit browser support | playwright-core |\n\nThe browser packages expose a standard interface:\n\n```json\n{\n  \"name\": \"@playwright/browser-webkit\",\n  \"version\": \"1.61.0-next\",\n  \"exports\": {\n    \".\": {\n      \"types\": \"./index.d.ts\",\n      \"import\": \"./index.mjs\",\n      \"require\": \"./index.js\",\n      \"default\": \"./index.js\"\n    }\n  },\n  \"dependencies\": {\n    \"playwright-core\": \"1.61.0-next\"\n  }\n}\n```\n\n资料来源：[packages/playwright-browser-webkit/package.json]()\n\n## Injected Scripts Package\n\nThe `injected` package contains scripts that run within the browser context, providing accessibility utilities and developer inspection capabilities.\n\n### Console API Installation\n\nThe injected script installs a `playwright` object onto `window` when `install()` is called:\n\n```typescript\ninstall() {\n  if (this._injectedScript.window.playwright)\n    return;\n  this._injectedScript.window.playwright = {\n    $: (selector: string, strict?: boolean) => this._querySelector(selector, !!strict),\n    $$: (selector: string) => this._querySelectorAll(selector),\n    inspect: (selector: string) => this._inspect(selector),\n    selector: (element: Element) => this._selector(element),\n    generateLocator: (element: Element, language?: Language) => this._generateLocator(element, language),\n    ariaSnapshot: (element?: Element, options?: AriaTreeOptions) => {\n      return this._injectedScript.ariaSnapshot(element || this._injectedScript.document.body, options || { mode: 'default' });\n    },\n    resume: () => this._resume(),\n    ...new Locator(this._injectedScript, ''),\n  };\n}\n```\n\n资料来源：[packages/injected/src/consoleApi.ts:10-30]()\n\n### Role Utilities\n\nThe `roleUtils.ts` file maps HTML elements to their ARIA roles for accessibility testing:\n\n```typescript\n'DIALOG': () => 'dialog',\n'FORM': (e: Element) => hasExplicitAccessibleName(e) ? 'form' : null,\n'HEADER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'banner',\n'IMG': (e: Element) => (e.getAttribute('alt') === '') && !e.getAttribute('title') && !hasGlobalAriaAttribute(e) && !hasTabIndex(e) ? 'presentation' : 'img',\n```\n\n资料来源：[packages/injected/src/roleUtils.ts:1-50]()\n\n## Tooling Packages\n\n### trace-viewer\n\nA React-based Progressive Web Application for inspecting Playwright trace files. The trace viewer provides:\n\n- Drop-zone interface for loading trace files locally\n- Progress dialogs for trace processing\n- Version display showing the Playwright version\n- No data transmission—opens files locally\n\n```tsx\n<div className='info'>Playwright Trace Viewer is a Progressive Web App, it does not send your trace anywhere,\n  it opens it locally.</div>\n<div className='version'>Playwright v{__APP_VERSION__}</div>\n```\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx:1-30]()\n\n### html-reporter\n\nGenerates HTML test reports with:\n\n- Test case location linking\n- Duration tracking\n- Project and tag labeling\n- Annotation display\n- Retry labeling for failed tests\n\n```tsx\n<CopyToClipboardContainer value={`${test.location.file}:${test.location.line}`}>\n  {test.location.file}:{test.location.line}\n</CopyToClipboardContainer>\n<TraceLink test={test} trailingSeparator={true} />\n<div className='test-case-duration'>{msToString(test.duration)}</div>\n```\n\n资料来源：[packages/html-reporter/src/testCaseView.tsx:1-30]()\n\n## CLI Tools\n\n### playwright-cli\n\nA command-line tool for browser automation and page interaction. Available commands include:\n\n```bash\n# Core commands\nplaywright-cli open                          # Open browser\nplaywright-cli goto <url>                    # Navigate\nplaywright-cli click <element>               # Click element\nplaywright-cli type <text>                   # Type text\n\n# Snapshot and evaluation\nplaywright-cli snapshot                      # Get page snapshot\nplaywright-cli eval \"code\"                   # Execute JS\n\n# Tab management\nplaywright-cli tab-list                      # List tabs\nplaywright-cli tab-new <url>                 # New tab\n\n# State management\nplaywright-cli state-save <file>             # Save state\nplaywright-cli state-load <file>            # Load state\n\n# Network interception\nplaywright-cli route \"<pattern>\"             # Intercept routes\n```\n\n### playwright-trace\n\nInspect trace files from the command line:\n\n```bash\nnpx playwright trace open <trace.zip>       # Open and extract trace\nnpx playwright trace actions                 # List all actions\nnpx playwright trace action <action-id>      # View action details\nnpx playwright trace console                 # View console messages\nnpx playwright trace errors                  # View errors\nnpx playwright trace snapshot <action-id>    # View DOM snapshot\nnpx playwright trace close                   # Close trace\n```\n\n## Build and Test Scripts\n\nThe root `package.json` defines comprehensive test and lint scripts:\n\n| Script | Purpose |\n|--------|---------|\n| `ctest` | Chromium tests |\n| `ftest` | Firefox tests |\n| `wtest` | WebKit tests |\n| `atest` | Android tests |\n| `etest` | Electron tests |\n| `itest` | Installation tests |\n| `stest` | Stress tests |\n| `biditest` | BiDi protocol tests |\n| `ttest` | Playwright Test runner tests |\n| `lint` | Full linting suite |\n| `tsc` | TypeScript compilation |\n\n```json\n{\n  \"scripts\": {\n    \"ctest\": \"playwright test --config=tests/library/playwright.config.ts --project=chromium-*\",\n    \"ftest\": \"playwright test --config=tests/library/playwright.config.ts --project=firefox-*\",\n    \"wtest\": \"playwright test --config=tests/library/playwright.config.ts --project=webkit-*\",\n    \"test\": \"playwright test --config=tests/library/playwright.config.ts\",\n    \"eslint\": \"eslint --cache\",\n    \"tsc\": \"tsc -p .\"\n  }\n}\n```\n\n资料来源：[package.json:1-50]()\n\n## Monorepo Structure Summary\n\n```mermaid\ngraph TD\n    subgraph \"Root\"\n        RootPkg[package.json<br/>v1.61.0-next]\n    end\n    \n    subgraph \"Core Packages\"\n        Core[playwright-core<br/>Automation core]\n        Injected[injected<br/>Browser scripts]\n    end\n    \n    subgraph \"Public Packages\"\n        Main[playwright<br/>Main API]\n        Chromium[playwright-browser-chromium]\n        Firefox[playwright-browser-firefox]\n        Webkit[playwright-browser-webkit]\n    end\n    \n    subgraph \"Tooling\"\n        CLI[playwright-cli<br/>CLI tool]\n        Trace[playwright-trace<br/>Trace CLI]\n        Viewer[trace-viewer<br/>Trace PWA]\n        Reporter[html-reporter<br/>Test reports]\n    end\n    \n    subgraph \"Examples\"\n        Todo[todomvc]\n        Svgomg[svgomg]\n    end\n    \n    Main --> Core\n    Chromium --> Core\n    Firefox --> Core\n    Webkit --> Core\n    CLI --> Core\n    Trace --> Core\n    Viewer --> Core\n    Reporter --> Core\n    Core --> Injected\n```\n\n## Package Versioning\n\nAll packages in the monorepo share the same version number for consistency:\n\n```json\n{\n  \"version\": \"1.61.0-next\",\n  \"engines\": {\n    \"node\": \">=18\"\n  }\n}\n```\n\nBrowser packages declare explicit dependencies on `playwright-core`:\n\n```json\n\"dependencies\": {\n  \"playwright-core\": \"1.61.0-next\"\n}\n```\n\nThis ensures version alignment across the ecosystem while allowing independent releases when necessary.\n\n---\n\n<a id='page-3'></a>\n\n## Client-Server Communication Architecture\n\n### 相关页面\n\n相关主题：[Package Ecosystem and Monorepo Structure](#page-2), [Browser Launch and Process Management](#page-4)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/client/channelOwner.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/channelOwner.ts)\n- [packages/playwright-core/src/client/connection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/connection.ts)\n- [packages/playwright-core/src/server/dispatchers/dispatcher.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/dispatchers/dispatcher.ts)\n- [packages/playwright-core/src/remote/playwrightConnection.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/remote/playwrightConnection.ts)\n- [packages/protocol/src/channels.d.ts](https://github.com/microsoft/playwright/blob/main/packages/protocol/src/channels.d.ts)\n- [packages/playwright-core/src/client/playwright.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/playwright.ts)\n- [packages/playwright-core/src/client/page.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/page.ts)\n</details>\n\n# Client-Server Communication Architecture\n\n## Overview\n\nPlaywright's Client-Server Communication Architecture enables the automation of web browsers through a well-defined message-passing system. The architecture separates the client API (used by test developers) from the server-side browser automation engine, allowing tests to control Chromium, Firefox, and WebKit browsers running either locally or in remote environments.\n\n## High-Level Architecture\n\n```mermaid\ngraph TD\n    subgraph Client[\"Client Side (Node.js)\"]\n        API[Test API<br/>playwright.click()]\n        CO[ChannelOwner<br/>Base Class]\n        CONN[Connection]\n    end\n    \n    subgraph Server[\"Server Side (Node.js + Browser)\"]\n        DIS[Dispatcher]\n        CH[Channel Handlers]\n        BR[Browser<br/>Chromium/Firefox/WebKit]\n    end\n    \n    API --> CO\n    CO --> CONN\n    CONN -->|Protocol Messages| DIS\n    DIS --> CH\n    CH --> BR\n    \n    style Client fill:#e1f5fe\n    style Server fill:#fff3e0\n```\n\nThe architecture follows a factory pattern where the `Connection` class registers object factories for all protocol-defined objects. When the client creates a `Page` or `BrowserContext`, the corresponding factory is invoked to create a client-side proxy object.\n\n## Core Components\n\n### ChannelOwner (Client-Side Base Class)\n\nThe `ChannelOwner` class serves as the base for all client-side objects that communicate with the server. It provides:\n\n- **Message routing**: Sends commands to the server and receives responses\n- **Event handling**: Subscribes to server-side events\n- **Lifecycle management**: Tracks object disposal and cleanup\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `channel` | `Channel` | The communication channel to the server |\n| `connection` | `Connection` | Reference to the parent connection |\n| `guid` | `string` | Unique identifier for this object |\n| `parent` | `ChannelOwner \\| null` | Parent object in the hierarchy |\n\n资料来源：[packages/playwright-core/src/client/channelOwner.ts]()\n\n### Connection (Client-Side Hub)\n\nThe `Connection` class manages all client-server communication and object lifecycle.\n\n```typescript\n// Connection registers factories for all protocol objects\nregisterObjectFactories(factories: Record<string, ChannelFactory>) {\n  // Creates appropriate client-side objects for each type\n}\n```\n\n**Registered Object Factories:**\n\n| Object Type | Factory Creates | Purpose |\n|-------------|-----------------|---------|\n| `Browser` | Browser instance | Main browser process |\n| `BrowserContext` | Context instance | Isolated browsing sessions |\n| `Page` | Page instance | Single tab/page |\n| `Request` | Request instance | HTTP request tracking |\n| `Response` | Response instance | HTTP response data |\n| `Route` | Route instance | Network request interception |\n| `Tracing` | Tracing instance | Trace collection |\n| `WebSocket` | WebSocket instance | WebSocket communication |\n| `Worker` | Worker instance | Web Workers |\n| `LocalUtils` | Utility instance | Local utility functions |\n\n资料来源：[packages/playwright-core/src/client/connection.ts:1-50]()\n\n### Dispatcher (Server-Side Handler)\n\nThe `Dispatcher` class is the server-side counterpart that handles messages from clients.\n\n```mermaid\ngraph LR\n    MSG[Incoming<br/>Message] --> DIS[Dispatcher]\n    DIS -->|Route| HAND[Channel Handler]\n    HAND -->|Execute| BR[Browser API]\n    BR -->|Result| RES[Response<br/>to Client]\n```\n\nKey responsibilities:\n- Deserialize incoming messages\n- Route to appropriate channel handler\n- Execute browser automation commands\n- Send responses back to client\n\n资料来源：[packages/playwright-core/src/server/dispatchers/dispatcher.ts]()\n\n### Protocol Channels\n\nThe protocol defines typed channels for all communication between client and server.\n\n```typescript\n// Generated from protocol definitions\ninterface Channels {\n  Browser: {\n    // Methods\n    newContext(options?: BrowserNewContextOptions): Promise<BrowserContext>;\n    close(): Promise<void>;\n    // Events\n    on('disconnected', callback: () => void): void;\n  };\n  Page: {\n    click(selector: string, options?: PageClickOptions): Promise<void>;\n    fill(selector: string, value: string): Promise<void>;\n    // ...\n  };\n}\n```\n\n资料来源：[packages/protocol/src/channels.d.ts]()\n\n## Communication Flow\n\n### Method Invocation Flow\n\n```mermaid\nsequenceDiagram\n    participant Client as Test Code\n    participant CO as ChannelOwner\n    participant CONN as Connection\n    participant Wire as Wire Protocol\n    participant DIS as Dispatcher\n    participant Impl as Implementation\n    \n    Client->>CO: page.click('#button')\n    CO->>CONN: sendMessage('click', args)\n    CONN->>Wire: serialize & send\n    Wire->>DIS: deliver message\n    DIS->>Impl: invoke method\n    Impl-->>DIS: return result\n    DIS-->>Wire: send response\n    Wire-->>CONN: receive response\n    CONN-->>CO: deserialize result\n    CO-->>Client: Promise resolves\n```\n\n### Object Creation Flow\n\nWhen a client requests a new object (e.g., `browser.newContext()`):\n\n1. Server creates the implementation object\n2. Server creates a dispatcher wrapper\n3. Server returns the new object's channel reference to client\n4. Client's connection factory creates appropriate `ChannelOwner` subclass\n5. Client receives a proxy object to interact with the new object\n\n```mermaid\ngraph TD\n    subgraph Server[\"Server\"]\n        IMPL[Implementation]\n        DISP[Dispatcher]\n    end\n    \n    subgraph Client[\"Client\"]\n        FACT[Factory]\n        PROXY[ChannelOwner Proxy]\n    end\n    \n    IMPL -->|creates| DISP\n    DISP -->|returns guid| FACT\n    FACT -->|creates| PROXY\n```\n\n## Remote Connections\n\nPlaywright supports remote browser connections through `PlaywrightConnection`.\n\n```mermaid\ngraph TD\n    subgraph Local[\"Test Machine\"]\n        TEST[Test Code]\n        CLIENT[Local Client]\n    end\n    \n    subgraph Remote[\"Remote Machine\"]\n        SERVER[Playwright Server]\n        BROWSER[Browser]\n    end\n    \n    TEST --> CLIENT\n    CLIENT -->|WebSocket| SERVER\n    SERVER --> BROWSER\n```\n\nThe remote connection maintains the same channel-based communication but uses WebSocket transport instead of in-process communication.\n\n资料来源：[packages/playwright-core/src/remote/playwrightConnection.ts]()\n\n## Message Protocol\n\n### Message Structure\n\n```typescript\ninterface ProtocolMessage {\n  id: string;           // Unique message ID\n  guid: string;         // Target object GUID\n  method: string;       // Method name\n  params?: object;     // Method parameters\n  type: 'request' | 'response' | 'event';\n}\n```\n\n### Event Subscription\n\nClients subscribe to server-side events through the channel system:\n\n```typescript\n// Server emits event\ndispatcher.dispatchEvent('eventName', payload);\n\n// Client receives via callback\npage.on('close', () => {\n  console.log('Page closed');\n});\n```\n\n## Object Hierarchy\n\n```mermaid\ngraph TD\n    P[Playwright] --> BC[Browser]\n    BC --> BCT[BrowserContext]\n    BCT --> PGE[Page]\n    \n    PGE --> W[Worker]\n    PGE --> R[Route]\n    \n    BCT --> RS[Request]\n    BCT --> RS2[Response]\n    \n    style P fill:#c8e6c9\n    style BC fill:#fff9c4\n    style BCT fill:#bbdefb\n    style PGE fill:#ffccbc\n```\n\nAll objects inherit from `ChannelOwner` and maintain references to their parent connection.\n\n## Error Handling\n\nThe architecture handles errors through:\n\n1. **Sync errors**: Caught and returned as rejected promises\n2. **Async errors**: Propagated through the message response\n3. **Disconnection**: Server sends 'disconnected' event to notify clients\n\n```typescript\ntry {\n  await page.click('#missing');\n} catch (e) {\n  // Error contains reason and stack\n  console.log(e.message); // Target closed, did you mean to close the browser?\n}\n```\n\n## Key Design Patterns\n\n### Factory Pattern\n\nObject factories in `Connection` create the appropriate `ChannelOwner` subclass based on protocol type.\n\n### Proxy Pattern\n\n`ChannelOwner` instances are proxies that forward method calls to the server.\n\n### Observer Pattern\n\nEvent subscriptions allow clients to react to server-side state changes.\n\n### Promise-based Async\n\nAll operations return Promises, enabling async/await usage in tests.\n\n## Summary\n\nPlaywright's Client-Server Communication Architecture provides:\n\n- **Type safety**: Protocol definitions ensure consistent interfaces\n- **Location transparency**: Local and remote execution use the same API\n- **Extensibility**: New object types can be added to the protocol\n- **Performance**: Optimized message serialization and batching\n- **Debuggability**: Clear message flow between components\n\n---\n\n<a id='page-4'></a>\n\n## Browser Launch and Process Management\n\n### 相关页面\n\n相关主题：[Client-Server Communication Architecture](#page-3), [Browser Implementations and Protocol Support](#page-8)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/outofprocess.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/outofprocess.ts)\n- [packages/playwright-core/src/inprocess.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/inprocess.ts)\n- [packages/playwright-core/src/server/browserType.ts](https://github.com/microsoft/playicrosoft/playwright/blob/main/packages/playwright-core/src/server/browserType.ts)\n- [packages/playwright-core/src/server/browser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/browser.ts)\n- [packages/utils/processLauncher.ts](https://github.com/microsoft/playwright/blob/main/packages/utils/processLauncher.ts)\n- [packages/playwright-core/src/server/transport.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/transport.ts)\n</details>\n\n# Browser Launch and Process Management\n\n## Overview\n\nBrowser Launch and Process Management is a core subsystem in Playwright responsible for spawning, communicating with, and lifecycle-managing browser processes. This subsystem abstracts the complexity of launching different browser types (Chromium, Firefox, WebKit) across different environments, handling both in-process and out-of-process execution models while maintaining reliable communication channels.\n\nThe system provides:\n\n- **Cross-browser abstraction** - Unified API for launching Chromium, Firefox, and WebKit\n- **Process lifecycle management** - Spawning, health monitoring, graceful termination\n- **Dual execution modes** - In-process and out-of-process browser execution\n- **Transport layer abstraction** - Message-based IPC between Node.js and browser processes\n- **Resource cleanup** - Proper disposal of browser instances and associated resources\n\n资料来源：[packages/playwright-core/src/server/browserType.ts:1-50]()\n\n## Architecture\n\n### High-Level Components\n\n```mermaid\ngraph TD\n    A[Playwright Client API] --> B[BrowserType]\n    B --> C{Launch Mode}\n    C -->|Out-of-Process| D[OutOfProcess]\n    C -->|In-Process| E[InProcess]\n    D --> F[ProcessLauncher]\n    D --> G[Transport Layer]\n    E --> H[BrowserProcess]\n    F --> I[Browser Executable]\n    G --> J[Browser Server]\n    H --> I\n```\n\n### Core Component Roles\n\n| Component | Package | Responsibility |\n|-----------|---------|----------------|\n| `BrowserType` | `playwright-core` | Entry point for browser launching, delegates to appropriate implementation |\n| `OutOfProcess` | `playwright-core` | Manages out-of-process browser execution with separate server process |\n| `InProcess` | `playwright-core` | Manages in-process browser execution within Node.js |\n| `ProcessLauncher` | `utils` | Core process spawning and management utilities |\n| `Transport` | `playwright-core` | Message-based IPC communication layer |\n| `Browser` | `playwright-core` | Abstract browser base class with lifecycle management |\n\n资料来源：[packages/playwright-core/src/server/browserType.ts:1-100]()\n\n## Launch Modes\n\nPlaywright supports two distinct browser launch modes, each suited for different use cases.\n\n### Out-of-Process Mode\n\nThe out-of-process (OOP) mode spawns browser processes as separate OS processes, with communication handled via WebSocket or pipe-based transport layers.\n\n**Characteristics:**\n\n- Process isolation - Browser crashes do not affect the Node.js process\n- Cross-language support - Enables Playwright bindings in languages other than Node.js\n- Resource efficiency - Better for running multiple browser instances\n- Security - Browser runs in separate sandboxed process\n\n```mermaid\ngraph LR\n    A[Node.js Process] <-->|WebSocket/Pipes| B[Browser Server Process]\n    B --> C[Browser Executable]\n```\n\nThe `OutOfProcess` class handles:\n\n1. Spawning the browser server executable\n2. Establishing transport connection\n3. Handshake and version negotiation\n4. Proxying API calls to the browser\n\n资料来源：[packages/playwright-core/src/outofprocess.ts:1-80]()\n\n### In-Process Mode\n\nThe in-process mode runs browser execution within the Node.js process itself, useful for scenarios requiring tighter integration.\n\n**Characteristics:**\n\n- Direct execution - No inter-process communication overhead\n- Debugging simplicity - Easier to debug browser and client code together\n- Shared memory - Direct access to browser resources\n- Limited isolation - Browser crashes may affect Node.js process\n\nThe `InProcess` class provides a simplified launch path that instantiates browser internals directly without spawning separate processes.\n\n资料来源：[packages/playwright-core/src/inprocess.ts:1-60]()\n\n### Mode Selection\n\n```typescript\n// Out-of-process (default)\nconst browser = await chromium.launch({ headless: true });\n\n// In-process via browser type's `launchServer`\nconst server = await chromium.launchServer({ headless: true });\n```\n\n## Process Lifecycle\n\n### Launch Sequence\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant BrowserType\n    participant Launcher\n    participant Browser\n    participant Transport\n\n    Client->>BrowserType: launch(options)\n    BrowserType->>Launcher: spawn(executable, args)\n    Launcher->>Browser: new Browser(transport)\n    Browser->>Transport: connect()\n    Transport-->>Browser: connection established\n    Browser->>Browser: initialize()\n    Browser-->>BrowserType: ready\n    BrowserType-->>Client: Browser instance\n```\n\n### Lifecycle States\n\n| State | Description | Transitions |\n|-------|-------------|-------------|\n| `Launching` | Process is being spawned | → `Connected` or `Failed` |\n| `Connected` | Transport layer established | → `Initialized` or `Closed` |\n| `Initialized` | Browser fully ready | → `Closed` |\n| `Failed` | Launch or initialization failed | Terminal state |\n| `Closed` | Browser process terminated | Terminal state |\n\n资料来源：[packages/playwright-core/src/server/browser.ts:1-150]()\n\n### Termination\n\nBrowser termination follows a controlled shutdown sequence:\n\n1. **Graceful close request** - Send close command to browser\n2. **Resource cleanup** - Dispose contexts, pages, and handlers\n3. **Process termination** - Kill the browser executable if still running\n4. **Transport cleanup** - Close connections and cleanup pipes\n\n```mermaid\ngraph TD\n    A[Browser.close called] --> B{Force kill?}\n    B -->|No| C[Graceful shutdown]\n    B -->|Yes| D[Kill process]\n    C --> E[Wait for exit]\n    E --> F[Force kill if timeout]\n    D --> G[Cleanup resources]\n    F --> G\n    G --> H[Done]\n```\n\n## Transport Layer\n\nThe transport layer enables message-based communication between the Node.js client and browser process.\n\n### Message Protocol\n\nMessages follow a structured format with JSON-serialized headers and binary payloads:\n\n```\n┌─────────────────────────────────────────┐\n│ Message Header (JSON)                   │\n│ { id, method, params, binaryLength }    │\n├─────────────────────────────────────────┤\n│ Binary Payload (if binaryLength > 0)    │\n└─────────────────────────────────────────┘\n```\n\n### Transport Implementations\n\n| Type | Use Case | Package |\n|------|----------|---------|\n| `PipeTransport` | Local Windows processes | `playwright-core` |\n| `StdioTransport` | Unix domain sockets | `playwright-core` |\n| `WebSocketTransport` | Remote/cloud browsers | `playwright-core` |\n\n资料来源：[packages/playwright-core/src/server/transport.ts:1-100]()\n\n### Connection Establishment\n\n```typescript\nclass Transport {\n  constructor(connection: Connection) {\n    this._connection = connection;\n  }\n\n  async connect(pipe: Pipe): Promise<void> {\n    // Establish connection to browser process\n  }\n\n  send(message: ProtocolMessage): void {\n    // Serialize and send message\n  }\n\n  async close(): Promise<void> {\n    // Graceful transport shutdown\n  }\n}\n```\n\n## Process Launcher\n\nThe `ProcessLauncher` utility provides cross-platform process spawning and management.\n\n### Launch Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `executablePath` | `string` | Path to browser executable |\n| `args` | `string[]` | Command-line arguments |\n| `env` | `Record<string,string>` | Environment variables |\n| `cwd` | `string` | Working directory |\n| `stdio` | `'pipe' \\| 'inherit'` | Standard IO mode |\n| `detach` | `boolean` | Run in detached mode |\n| `timeout` | `number` | Launch timeout in ms |\n\n资料来源：[packages/utils/processLauncher.ts:1-120]()\n\n### Process Monitoring\n\nThe launcher maintains process health through:\n\n1. **Exit detection** - Monitoring for unexpected process termination\n2. **Output capture** - Collecting stdout/stderr for debugging\n3. **Resource limits** - Optional memory and CPU limits\n4. **Cleanup hooks** - Automatic resource disposal on exit\n\n### Error Handling\n\n```typescript\ninterface LaunchError {\n  reason: 'executable-not-found' | 'timeout' | 'crash' | 'protocol-error';\n  message: string;\n  stack?: string;\n}\n```\n\n## Browser Type Registry\n\nEach browser type (Chromium, Firefox, WebKit) extends the base `BrowserType` class with browser-specific logic.\n\n### Browser Executable Resolution\n\n```mermaid\ngraph TD\n    A[launch called] --> B{Find browser?}\n    B -->|User path| C[Validate executable]\n    B -->|Default| D[Check installed browsers]\n    C -->|Valid| E[Launch browser]\n    C -->|Invalid| F[Throw error]\n    D -->|Found| E\n    D -->|Not found| G[Prompt installation]\n```\n\n### BrowserType Interface\n\n```typescript\ninterface BrowserType {\n  name(): string;\n  executablePath(): string;\n  launch(options?: LaunchOptions): Promise<Browser>;\n  launchServer(options?: LaunchOptions): Promise<BrowserServer>;\n  launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>;\n  executable(): string;\n  defaultArgs(options?: LaunchOptions): string[];\n}\n```\n\n资料来源：[packages/playwright-core/src/server/browserType.ts:100-200]()\n\n## Configuration Options\n\n### Common Launch Options\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `headless` | `true` | Run browser in headless mode |\n| `args` | `[]` | Additional browser arguments |\n| `channel` | `undefined` | Browser channel (e.g., 'chrome', 'msedge') |\n| `chromiumSandbox` | `true` | Enable Chromium sandbox (Linux) |\n| `devtools` | `false` | Open DevTools on launch |\n| `downloadPath` | `undefined` | Custom download directory |\n| `env` | `process.env` | Environment variables |\n| `executablePath` | `undefined` | Custom browser executable path |\n| `firefoxUserPrefs` | `{}` | Firefox-specific preferences |\n| `proxy` | `undefined` | Proxy configuration |\n| `timeout` | `30000` | Launch timeout in milliseconds |\n| `viewport` | `{ width: 1280, height: 720 }` | Default viewport size |\n\n### Browser-Specific Options\n\n#### Chromium\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `chromiumSandbox` | `boolean` | Enable Linux sandbox |\n| `proxy` | `ProxySettings` | HTTP/SOCKS proxy |\n| `downloadContentTypes` | `string[]` | Content types to download |\n\n#### Firefox\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `firefoxUserPrefs` | `Record<string, string \\| number \\| boolean>` | Gecko preferences |\n| `firefoxExtensionPaths` | `string[]` | Extension directories |\n\n#### WebKit\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `wkWebKitExperimentalSimulateSaturation` | `boolean` | Simulate saturation |\n| `wkWebKitExperimentalLayoutMetrics` | `boolean` | Enable layout metrics |\n\n## Integration with CLI Tools\n\nThe browser launch system integrates with Playwright's CLI tooling for interactive browser automation.\n\n### CLI Session Management\n\n```bash\n# Open browser with named session\nplaywright-cli -s=mysession open https://example.com\n\n# Create persistent profile\nplaywright-cli open https://example.com --persistent\n\n# Browser selection\nplaywright-cli open https://example.com --browser=firefox\n```\n\nThe CLI layer uses the same `BrowserType` APIs to establish browser sessions, with session state managed through the browser's context persistence mechanisms.\n\n## Best Practices\n\n### Resource Management\n\n1. **Always close browsers** - Use `browser.close()` in try/finally blocks\n2. **Handle launch failures** - Wrap launch calls in try/catch for graceful error handling\n3. **Use context isolation** - Launch separate contexts instead of separate browsers when possible\n4. **Set appropriate timeouts** - Adjust timeouts for slow environments\n\n### Launch Example\n\n```typescript\nimport { chromium } from 'playwright';\n\nasync function run() {\n  let browser;\n  try {\n    browser = await chromium.launch({\n      headless: true,\n      timeout: 30000,\n      args: ['--disable-gpu', '--no-sandbox'],\n    });\n    \n    const context = await browser.newContext();\n    const page = await context.newPage();\n    \n    // Perform actions...\n    \n  } catch (error) {\n    console.error('Browser launch failed:', error);\n  } finally {\n    if (browser) {\n      await browser.close();\n    }\n  }\n}\n```\n\n## Summary\n\nThe Browser Launch and Process Management system provides a robust foundation for browser automation in Playwright. By abstracting the complexities of process spawning, inter-process communication, and lifecycle management, it enables developers to work with browsers through a clean, consistent API regardless of the underlying browser type or execution environment.\n\nKey takeaways:\n\n- **Dual execution modes** support both isolated (OOP) and integrated (in-process) browser execution\n- **Transport abstraction** enables reliable message passing across different IPC mechanisms\n- **Lifecycle management** ensures proper resource cleanup and graceful degradation\n- **Browser type registry** provides consistent APIs across Chromium, Firefox, and WebKit\n\n---\n\n<a id='page-5'></a>\n\n## Test Runner and Execution Engine\n\n### 相关页面\n\n相关主题：[Playwright Introduction and Project Overview](#page-1), [Locators, Selectors, and Element Interaction](#page-6), [Assertions, Matchers, and Expect API](#page-7)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright/src/runner/testRunner.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/runner/testRunner.ts)\n- [packages/playwright/src/runner/dispatcher.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/runner/dispatcher.ts)\n- [packages/playwright/src/common/testLoader.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/common/testLoader.ts)\n- [packages/playwright/src/common/fixtures.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/common/fixtures.ts)\n- [packages/playwright/src/common/poolBuilder.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/common/poolBuilder.ts)\n- [packages/playwright/src/runner/workerHost.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/runner/workerHost.ts)\n- [packages/playwright/src/worker/workerMain.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/worker/workerMain.ts)\n</details>\n\n# Test Runner and Execution Engine\n\nThe Playwright Test Runner is the core execution engine responsible for discovering, scheduling, and running end-to-end tests across multiple browsers and processes. It provides a complete test isolation model, automatic retry logic, parallel execution, and seamless integration with fixtures for test setup and teardown.\n\n## Architecture Overview\n\nThe test runner follows a multi-process architecture designed for scalability and isolation. At a high level, it consists of a central **TestRunner** process that coordinates test execution, multiple **Worker** processes that execute tests in isolated browser contexts, and a **Dispatcher** that manages the assignment of tests to available workers.\n\n```mermaid\ngraph TD\n    A[TestRunner<br/>Main Process] --> B[Dispatcher<br/>Test Assignment]\n    B --> C[Worker Host 1<br/>Process]\n    B --> D[Worker Host 2<br/>Process]\n    B --> E[Worker Host N<br/>Process]\n    C --> F[Browser Context 1]\n    D --> G[Browser Context 2]\n    E --> H[Browser Context N]\n    F --> I[Page 1]\n    G --> J[Page 2]\n    H --> K[Page N]\n```\n\n### Core Components\n\n| Component | File Location | Responsibility |\n|-----------|---------------|----------------|\n| TestRunner | `packages/playwright/src/runner/testRunner.ts` | Entry point; orchestrates the full test run lifecycle |\n| Dispatcher | `packages/playwright/src/runner/dispatcher.ts` | Distributes tests to workers and tracks completion |\n| TestLoader | `packages/playwright/src/common/testLoader.ts` | Discovers and parses test files |\n| Fixtures | `packages/playwright/src/common/fixtures.ts` | Manages test fixtures and dependencies |\n| PoolBuilder | `packages/playwright/src/common/poolBuilder.ts` | Creates and manages browser context pools |\n| WorkerHost | `packages/playwright/src/runner/workerHost.ts` | Manages worker process lifecycle |\n| WorkerMain | `packages/playwright/src/worker/workerMain.ts` | Worker process entry point; runs actual tests |\n\n资料来源：[packages/playwright/src/runner/testRunner.ts:1-50]()\n资料来源：[packages/playwright/src/runner/dispatcher.ts:1-60]()\n\n## Test Discovery and Loading\n\nThe test discovery process begins with the **TestLoader**, which recursively scans the project for test files matching the configured patterns. Playwright supports both `.spec.ts` and `.spec.js` file extensions by default, though these patterns are fully configurable through `playwright.config.ts`.\n\n### Loading Pipeline\n\n```mermaid\ngraph LR\n    A[Test Files<br/>*.spec.ts] --> B[TestLoader]\n    B --> C[Parse Test Cases]\n    C --> D[Extract Fixtures]\n    D --> E[Build Test Tree]\n    E --> F[Dispatcher]\n```\n\nThe TestLoader performs the following operations:\n\n1. **File Discovery** — Scans the specified test directory for files matching the glob patterns defined in the configuration.\n2. **Syntax Parsing** — Parses each test file to extract `test`, `test.describe`, and `test.beforeEach` declarations.\n3. **Fixture Extraction** — Identifies fixture dependencies declared via `test.use()` or fixture function signatures.\n4. **Test Tree Construction** — Builds a hierarchical structure representing test suites and individual test cases.\n\n资料来源：[packages/playwright/src/common/testLoader.ts:1-80]()\n\n### Configuration Files\n\nPlaywright recognizes two primary configuration file formats:\n\n| File | Format | Priority |\n|------|--------|----------|\n| `playwright.config.ts` | TypeScript | Highest |\n| `playwright.config.js` | JavaScript | Lower |\n| `playwright.config.mjs` | ES Module | Lower |\n\nThe configuration defines critical execution parameters including:\n\n```typescript\n// Example playwright.config.ts structure\nexport default defineConfig({\n  timeout: 30000,           // Per-test timeout in milliseconds\n  retries: 0,               // Number of retries on failure\n  workers: process.env.CI ? 1 : undefined,  // Parallel workers\n  reporter: 'html',         // Output format\n  use: {\n    baseURL: 'http://localhost',\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: false,\n  },\n  projects: [\n    { name: 'chromium', use: { browserName: 'chromium' } },\n    { name: 'firefox', use: { browserName: 'firefox' } },\n    { name: 'webkit', use: { browserName: 'webkit' } },\n  ],\n});\n```\n\n资料来源：[package.json:test-scripts]()\n资料来源：[README.md:test-configuration]()\n\n## Worker Process Model\n\nEach worker process operates as an independent execution unit, running in a separate Node.js process for complete isolation. The **WorkerHost** manages the lifecycle of these processes, handling creation, communication, and graceful termination.\n\n### Worker Lifecycle\n\n```mermaid\nstateDiagram-v2\n    [*] --> Spawning: Start Worker\n    Spawning --> Initializing: Worker PID obtained\n    Initializing --> Ready: Fixtures initialized\n    Ready --> Running: Test assigned\n    Running --> Ready: Test complete\n    Running --> Retrying: Test failed, retries remaining\n    Retrying --> Running: Retry attempt\n    Retrying --> Failed: No retries left\n    Running --> Failed: Test failed, no retries\n    Ready --> Shutdown: All tests complete\n    Failed --> [*]: Worker terminated\n    Shutdown --> [*]: Cleanup complete\n```\n\n### Worker Communication\n\nWorkers communicate with the main process through an IPC (Inter-Process Communication) channel. The protocol supports the following message types:\n\n| Message Type | Direction | Purpose |\n|--------------|-----------|---------|\n| `init` | Main → Worker | Initialize worker with config |\n| `run` | Main → Worker | Execute a specific test |\n| `stop` | Main → Worker | Cancel running test |\n| `done` | Worker → Main | Report test result |\n| `error` | Worker → Main | Report runtime error |\n| `teardown` | Main → Worker | Graceful shutdown |\n\n资料来源：[packages/playwright/src/runner/workerHost.ts:1-100]()\n资料来源：[packages/playwright/src/worker/workerMain.ts:1-50]()\n\n## Dispatcher and Test Assignment\n\nThe **Dispatcher** is the central coordinator responsible for assigning tests to available workers while respecting configured parallelism limits. It maintains a queue of pending tests and dynamically allocates them based on worker availability.\n\n### Test Assignment Algorithm\n\n```mermaid\ngraph TD\n    A[Test Queue] --> B{Workers Available?}\n    B -->|Yes| C[Pop Next Test]\n    C --> D{Test has deps?}\n    D -->|No| E[Assign to available worker]\n    D -->|Yes| F[Wait for deps]\n    F --> D\n    E --> G[Execute Test]\n    G --> H[Test Result]\n    H --> I{Success?}\n    I -->|Yes| J[Mark complete]\n    I -->|No| K{Retries left?}\n    K -->|Yes| L[Re-queue for retry]\n    K -->|No| M[Mark failed]\n    J --> A\n    L --> A\n    M --> A\n```\n\nThe dispatcher implements the following strategies:\n\n- **Load Balancing** — Tests are distributed evenly across workers to maximize throughput.\n- **Retry Logic** — Failed tests are automatically re-queued up to the configured retry count.\n- **Serial Execution per Worker** — Each worker processes one test at a time to maintain isolation.\n- **Sharding** — Tests can be sharded across multiple machines using `--shard` flag.\n\n资料来源：[packages/playwright/src/runner/dispatcher.ts:50-200]()\n\n### Parallelism Configuration\n\n| Config Option | CLI Flag | Description |\n|---------------|----------|-------------|\n| `workers` | `--workers` | Number of parallel worker processes |\n| `retries` | `--retries` | Number of retry attempts per failed test |\n| `timeout` | `--timeout` | Per-test timeout in milliseconds |\n| `shard` | `--shard=N/M` | Shard tests across M machines, run shard N |\n\n```bash\n# Run with 4 workers\nnpx playwright test --workers=4\n\n# Run with retries and extended timeout\nnpx playwright test --retries=2 --timeout=60000\n\n# Run shard 1 of 3\nnpx playwright test --shard=1/3\n```\n\n## Fixture System\n\nFixtures provide a dependency injection mechanism for test setup and teardown. They ensure that resources are properly initialized before tests run and cleaned up afterward.\n\n### Fixture Types\n\n| Type | Scope | Usage |\n|------|-------|-------|\n| `static` | Across all tests | Global configuration |\n| `worker` | Per worker process | Shared within one worker |\n| `test` | Per test execution | Fresh for each test |\n| `session` | Across all workers | Shared global state |\n\n```typescript\nimport { test as baseTest, expect } from '@playwright/test';\n\n// Define a fixture with automatic cleanup\nexport const test = baseTest.extend({\n  // Auto-cleanup database for each test\n  database: async ({}, use) => {\n    const db = await createTestDatabase();\n    await use(db);\n    await db.cleanup();\n  },\n  \n  // Reuse authenticated page across all tests in a worker\n  authenticatedPage: async ({ browser }, use) => {\n    const context = await browser.newContext();\n    const page = await context.newPage();\n    await page.goto('/login');\n    await page.fill('#username', 'testuser');\n    await page.fill('#password', 'testpass');\n    await page.click('#submit');\n    await use(page);\n    await context.close();\n  },\n});\n```\n\n资料来源：[packages/playwright/src/common/fixtures.ts:1-100]()\n\n### Built-in Fixtures\n\nPlaywright provides several built-in fixtures that are automatically available to all tests:\n\n| Fixture | Type | Description |\n|---------|------|-------------|\n| `page` | `test` | Fresh page for each test |\n| `context` | `test` | Fresh browser context |\n| `browser` | `worker` | Browser instance shared in worker |\n| `request` | `test` | APIRequestContext for REST testing |\n| `火` | `test` | Playwright test object |\n\n## Browser Context Pooling\n\nThe **PoolBuilder** manages a pool of browser contexts to optimize resource usage. Rather than creating a new context for each test (which can be expensive), the pool maintains a set of reusable contexts.\n\n### Pooling Strategy\n\n```mermaid\ngraph TD\n    A[Test Request] --> B{Idle Context Available?}\n    B -->|Yes| C[Use Pooled Context]\n    B -->|No| D{Max Pool Size Reached?}\n    D -->|No| E[Create New Context]\n    D -->|Yes| F[Wait for Available]\n    E --> C\n    F --> C\n    C --> G[Test Execution]\n    G --> H{Context Satisfies Test?}\n    H -->|Yes| I[Return to Pool]\n    H -->|No| J[Destroy Context]\n    J --> K[Create Fresh Context]\n    K --> I\n```\n\n### Context Configuration\n\nEach project can define its own context configuration:\n\n```typescript\nexport default defineConfig({\n  projects: [\n    {\n      name: 'chromium',\n      use: {\n        browserName: 'chromium',\n        viewport: { width: 1920, height: 1080 },\n        permissions: ['geolocation'],\n        storageState: './auth.json',\n        launchOptions: {\n          args: ['--disable-dev-shm-usage'],\n        },\n      },\n    },\n  ],\n});\n```\n\n资料来源：[packages/playwright/src/common/poolBuilder.ts:1-80]()\n\n## Debug Mode and CLI Integration\n\nPlaywright provides a CLI-based debugging mode that allows interactive inspection of test execution. When running with `--debug=cli`, the test runner pauses at the start and exposes a debug session.\n\n### Debug Workflow\n\n```mermaid\ngraph TD\n    A[npx playwright test --debug=cli] --> B[Test Paused at Start]\n    B --> C[Debugging Instructions<br/>Session: tw-XXXX]\n    C --> D[playwright-cli attach tw-XXXX]\n    D --> E[Interactive Commands]\n    E --> F[snapshot, click, fill, etc.]\n    F --> G[Test Continues]\n    G --> H[Capture Results]\n    H --> I[Generate Report]\n```\n\n### Debug Commands\n\n| Command | Purpose |\n|---------|---------|\n| `playwright-cli snapshot` | Get current page snapshot with element refs |\n| `playwright-cli click <ref>` | Click an element by its reference |\n| `playwright-cli fill <ref> <text>` | Fill input field |\n| `playwright-cli eval <expression>` | Execute JavaScript in page context |\n| `playwright-cli resume` | Continue test execution |\n| `playwright-cli screenshot` | Capture current page state |\n\n```bash\n# Start test in debug mode\nPLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli\n\n# In another terminal, attach to the debug session\nplaywright-cli attach tw-abcdef\n\n# Explore the page\nplaywright-cli snapshot\nplaywright-cli click e15\nplaywright-cli eval \"document.title\"\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md:1-50]()\n\n## Tracing and Debugging\n\nPlaywright includes a comprehensive tracing system that captures detailed execution information for post-mortem analysis.\n\n### Trace Contents\n\n| Category | Captured Data |\n|----------|---------------|\n| **Actions** | Clicks, fills, navigations with timestamps |\n| **DOM Snapshots** | Before/after state for each action |\n| **Screenshots** | Visual state at key moments |\n| **Network** | All HTTP requests/responses |\n| **Console** | Console.log output and errors |\n| **Errors** | Stack traces for failures |\n\n### Trace Commands\n\n```bash\n# Open a trace file\nnpx playwright trace open trace.zip\n\n# List all actions\nnpx playwright trace actions\n\n# View specific action details\nnpx playwright trace action <action-id>\n\n# Get DOM snapshot at an action\nnpx playwright trace snapshot <action-id>\n\n# View console errors\nnpx playwright trace console --errors-only\n```\n\n```mermaid\ngraph LR\n    A[Test Execution] --> B[trace-{timestamp}.trace]\n    A --> C[trace-{timestamp}.network]\n    A --> D[resources/]\n    B --> E[Action Log]\n    C --> F[Network Activity]\n    D --> G[Cached Assets]\n    E --> H[Trace Viewer]\n    F --> H\n    G --> H\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md:1-80]()\n\n## Execution Flow Summary\n\nThe complete test execution flow follows these stages:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant TestRunner\n    participant TestLoader\n    participant Dispatcher\n    participant WorkerHost\n    participant Worker\n\n    User->>TestRunner: npx playwright test\n    TestRunner->>TestLoader: Load tests\n    TestLoader-->>TestRunner: Test tree\n    TestRunner->>Dispatcher: Initialize\n    TestRunner->>WorkerHost: Spawn workers\n    WorkerHost->>Worker: Start process\n    \n    loop For each test\n        Dispatcher->>WorkerHost: Assign test\n        WorkerHost->>Worker: Run test\n        Worker->>PoolBuilder: Request context\n        PoolBuilder-->>Worker: Context\n        Worker->>Fixtures: Setup fixtures\n        Fixtures-->>Worker: Fixture values\n        Worker->>Worker: Execute test body\n        Worker->>Fixtures: Teardown fixtures\n        Worker-->>WorkerHost: Test result\n        WorkerHost-->>Dispatcher: Result\n    end\n    \n    Dispatcher-->>TestRunner: All complete\n    TestRunner->>User: Report\n```\n\n## Command-Line Interface\n\n### Common Commands\n\n| Command | Description |\n|---------|-------------|\n| `npx playwright test` | Run all tests |\n| `npx playwright test <file>` | Run specific file |\n| `npx playwright test --debug` | Run in debug mode |\n| `npx playwright test --list` | List all tests without running |\n| `npx playwright show-report` | Open HTML report |\n\n### Configuration via CLI\n\n```bash\n# Override config values\nnpx playwright test --project=chromium --timeout=30000\n\n# Run only matching tests\nnpx playwright test --grep=\"login\"\n\n# Run only failed tests from last run\nnpx playwright test --last-failed\n\n# Update snapshots\nnpx playwright test --update-snapshots\n```\n\n## Integration with Trace Viewer\n\nThe trace viewer is a Progressive Web App that opens trace files locally without sending data anywhere. It provides visual debugging capabilities.\n\n```mermaid\ngraph TD\n    A[Trace.zip] --> B[WorkbenchLoader]\n    B --> C[TraceModel]\n    C --> D[Actions Panel]\n    C --> E[Screenshots Panel]\n    C --> F[Network Panel]\n    C --> G[Console Panel]\n    D --> H[Unified Timeline]\n    E --> H\n    F --> H\n    G --> H\n```\n\nTo use the trace viewer:\n\n1. Run a test that generates a trace (using `trace: 'on'` in config)\n2. Locate the trace file in `test-results/<test-name>/trace.zip`\n3. Open at [trace.playwright.dev](https://trace.playwright.dev) or via CLI\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx:1-60]()\n\n## Summary\n\nThe Playwright Test Runner provides a production-grade testing infrastructure with:\n\n- **Multi-process isolation** ensuring test independence\n- **Automatic resource management** through fixture cleanup\n- **Flexible parallelism** configurable per project and CI environment\n- **Rich debugging** via CLI integration and trace playback\n- **Cross-browser support** executing tests on Chromium, Firefox, and WebKit\n- **Comprehensive reporting** with built-in HTML reports and trace viewer\n\nThe architecture cleanly separates concerns between test discovery (TestLoader), orchestration (Dispatcher), execution (Workers), and resource management (Fixtures, PoolBuilder), making it both maintainable and extensible.\n\n---\n\n<a id='page-6'></a>\n\n## Locators, Selectors, and Element Interaction\n\n### 相关页面\n\n相关主题：[Test Runner and Execution Engine](#page-5), [Assertions, Matchers, and Expect API](#page-7)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/client/locator.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/client/locator.ts)\n- [packages/injected/src/selectorEngine.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/selectorEngine.ts)\n- [packages/injected/src/selectorGenerator.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/selectorGenerator.ts)\n- [packages/injected/src/roleSelectorEngine.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/roleSelectorEngine.ts)\n- [packages/injected/src/selectorEvaluator.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/selectorEvaluator.ts)\n- [packages/injected/src/injectedScript.ts](https://github.com/microsoft/playwright/blob/main/packages/injected/src/injectedScript.ts)\n- [packages/playwright-core/src/server/selectors.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/selectors.ts)\n</details>\n\n# Locators, Selectors, and Element Interaction\n\nThis page describes how Playwright locates DOM elements and interacts with them programmatically. The system consists of client-side Locator APIs, an in-browser Injected Script that evaluates selectors, and a server-side Selector Manager that registers and manages selector engines.\n\n## Architecture Overview\n\nPlaywright uses a layered architecture for element location:\n\n| Layer | Package | Responsibility |\n|-------|---------|----------------|\n| **Client API** | `playwright-core/src/client/locator.ts` | Fluent locator interface exposed to test authors |\n| **Server Manager** | `playwright-core/src/server/selectors.ts` | Registers selector engines, manages context |\n| **Injected Script** | `packages/injected/src/` | Runs in browser context, evaluates selectors |\n\n```mermaid\ngraph TD\n    A[Test Author Code] --> B[Locator API]\n    B --> C[Selector Manager]\n    C --> D[Registered Selector Engines]\n    D --> E[Injected Script]\n    E --> F[Browser DOM]\n    \n    B -->|locator.click/hover/fill| G[Action Commands]\n    E -->|querySelector, querySelectorAll| F\n```\n\n资料来源：[packages/playwright-core/src/client/locator.ts](packages/playwright-core/src/client/locator.ts)  \n资料来源：[packages/playwright-core/src/server/selectors.ts](packages/playwright-core/src/server/selectors.ts)\n\n## Locator API\n\nThe `Locator` class provides a fluent API for finding and interacting with elements. It differs from `ElementHandle` by using *strict* mode by default and automatically retrying until elements are actionable.\n\n### Core Locator Methods\n\n| Method | Description |\n|--------|-------------|\n| `click()` | Click the element |\n| `fill()` | Fill input field with text |\n| `hover()` | Hover over element |\n| `dblclick()` | Double-click element |\n| `check()` / `uncheck()` | Toggle checkbox/radio |\n| `selectOption()` | Select option(s) from dropdown |\n| `scrollIntoViewIfNeeded()` | Scroll element into view |\n| `tap()` | Perform tap gesture |\n| `dragAndDrop()` | Drag and drop operations |\n\n### Locator vs ElementHandle\n\n| Aspect | Locator | ElementHandle |\n|--------|---------|---------------|\n| Evaluation | Re-evaluated on each action | Captured once |\n| Strict mode | Enabled by default | Must be manually enforced |\n| Retries | Auto-retries until actionable | Single attempt |\n| Shadow DOM | Traverses automatically | Manual shadow traversal |\n\nThe injected script exposes locator helpers via `window.playwright`:\n\n```typescript\nthis._injectedScript.window.playwright = {\n  $: (selector: string, strict?: boolean) => this._querySelector(selector, !!strict),\n  $$: (selector: string) => this._querySelectorAll(selector),\n  inspect: (selector: string) => this._inspect(selector),\n  selector: (element: Element) => this._selector(element),\n  generateLocator: (element: Element, language?: Language) => this._generateLocator(element, language),\n  ariaSnapshot: (element?: Element, options?: AriaTreeOptions) => { ... },\n  resume: () => this._resume(),\n  ...new Locator(this._injectedScript, ''),\n};\n```\n\n资料来源：[packages/injected/src/consoleApi.ts:1-30](packages/injected/src/consoleApi.ts)\n\n## Selector Engine Architecture\n\nPlaywright supports multiple built-in selector engines that can be combined using the `>>` combinator.\n\n### Selector Engine Types\n\n| Engine | Prefix | Example | Description |\n|--------|--------|---------|-------------|\n| **CSS** | (default) | `div.button` | Standard CSS selectors |\n| **Role** | `role/` | `role=button[name=\"Submit\"]` | ARIA role matching |\n| **Text** | `text/` | `text=\"Log In\"` | Text content matching |\n| **Test ID** | `testId=` | `testId=submit-btn` | `data-testid` attribute |\n| **Label** | `label=` | `label=Username` | Form label association |\n| **Alt Text** | `alt=` | `alt=Profile Photo` | Image alt attributes |\n| **Title** | `title=` | `title=Settings` | Title attribute |\n| **XPath** | `xpath=` | `xpath=//button[1]` | XPath expressions |\n| **Regex** | `/regex/` | `/^submit.*$/i` | Pattern matching |\n\n### Selector Evaluation Flow\n\n```mermaid\ngraph LR\n    A[Selector String] --> B[Parse & Split by >>]\n    B --> C[Engine Registry Lookup]\n    C --> D{Engine Type?}\n    D -->|CSS| E[query/queryAll]\n    D -->|Role| F[Role Selector Engine]\n    D -->|Text| G[Text Selector Engine]\n    D -->|Other| H[Custom Engine]\n    E --> I[Evaluate in DOM]\n    F --> I\n    G --> I\n    H --> I\n    I --> J[Match Results]\n```\n\n### Engine Registration\n\nSelector engines are registered with the `SelectorEngine` class:\n\n```typescript\ntype SelectorEngine = {\n  name: string;\n  create?(root: Preview<Element>, target: Element, context: SelectorInjectedContext): Selector;\n  query(root: Element, selector: Selector): Element | null;\n  queryAll?(root: Element, selector: Selector): Element[];\n};\n```\n\n资料来源：[packages/injected/src/selectorEngine.ts](packages/injected/src/selectorEngine.ts)\n\n## Role Selector Engine\n\nThe role selector engine matches elements by their ARIA role with optional name and properties filters.\n\n### Supported ARIA Roles\n\nThe engine recognizes all standard ARIA roles including: `button`, `link`, `checkbox`, `radio`, `textbox`, `searchbox`, `combobox`, `listbox`, `menu`, `menuitem`, `tab`, `tablist`, `dialog`, `alertdialog`, and many more.\n\n### Role Selector Syntax\n\n```bash\nrole=button[name=\"Submit\"]\nrole=link[name=\"Documentation\"]\nrole=textbox[name=\"Email\"][include-hidden]\nrole=menuitemcheckbox[name=\"Bold\"][checked]\n```\n\n### Role Matching Logic\n\n```mermaid\ngraph TD\n    A[Input: role=button] --> B[Get all elements with role=button]\n    B --> C{has name filter?}\n    C -->|Yes| D[Filter by accessible name]\n    C -->|No| E[Return all matches]\n    D --> F{Matches found?}\n    F -->|Yes| E\n    F -->|No| G[Return empty]\n    E --> H[Apply other filters]\n```\n\n资料来源：[packages/injected/src/roleSelectorEngine.ts](packages/injected/src/roleSelectorEngine.ts)\n\n## Selector Evaluator\n\nThe `SelectorEvaluator` class performs actual DOM matching using registered engines.\n\n### Key Methods\n\n| Method | Signature | Purpose |\n|--------|-----------|---------|\n| `query` | `(selector: ParsedSelector, root: Element, strict: boolean)` | Find single element |\n| `queryAll` | `(selector: ParsedSelector, root: Element)` | Find all matches |\n| `parseSelector` | `(selector: string)` | Parse selector string |\n| `preusable` | `()` | Create context for reuse |\n\n### Selector Parsing\n\nSelectors are parsed into a structured format:\n\n```typescript\ntype ParsedSelector = {\n  parsed: {\n    engineName: string;\n    strict: boolean;\n    chain: {\n      engine: string;\n      selector: string;\n      distance: number;\n      shadow: ShadowRootLevel[];\n    }[];\n  };\n};\n```\n\n资料来源：[packages/injected/src/selectorEvaluator.ts](packages/injected/src/selectorEvaluator.ts)\n\n## Selector Generator\n\nThe selector generator suggests optimal selectors for elements during codegen and when using `playwright codegen`.\n\n### Generation Strategy\n\n| Priority | Selector Type | Example |\n|----------|---------------|---------|\n| 1 | Test ID | `[data-testid=\"submit\"]` |\n| 2 | Accessible | `role=button[name=\"Submit\"]` |\n| 3 | Text | `text=\"Submit\"` |\n| 4 | CSS | `#submit-btn` |\n| 5 | Relative | `nth=5` |\n\n### Generator Implementation\n\nThe generator analyzes elements and ranks candidate selectors by:\n\n1. **Uniqueness** - Does this selector match exactly one element?\n2. **Stability** - Will this selector survive UI changes?\n3. **Readability** - Is this selector meaningful to humans?\n4. **Brevity** - Shorter selectors preferred when equivalent\n\n资料来源：[packages/injected/src/selectorGenerator.ts](packages/injected/src/selectorGenerator.ts)\n\n## Injected Script Integration\n\nThe `InjectedScript` class provides the bridge between Node.js and browser contexts.\n\n### Architecture\n\n```mermaid\ngraph TD\n    A[Playwright Node.js] -->|Evaluate| B[InjectedScript]\n    B --> C[Query Selector Engines]\n    B --> D[Locator Generation]\n    B --> E[ARIA Snapshot]\n    B --> F[Console API]\n    \n    C --> G[DOM Manipulation]\n    D --> H[Selector Suggestions]\n    E --> I[Accessibility Tree]\n    \n    G --> J[User Actions]\n    J -->|click, hover, type| K[Event Dispatch]\n```\n\n### Console API Methods\n\n| Method | Description |\n|--------|-------------|\n| `playwright.$()` | Query single element |\n| `playwright.$$()` | Query all elements |\n| `playwright.inspect()` | Highlight element |\n| `playwright.selector()` | Generate selector for element |\n| `playwright.generateLocator()` | Generate in specific language |\n| `playwright.ariaSnapshot()` | Get accessibility snapshot |\n\n资料来源：[packages/injected/src/injectedScript.ts](packages/injected/src/injectedScript.ts)\n\n## Using Locators with playwright-cli\n\nThe CLI tool supports all selector types for element interaction:\n\n### Element Targeting Methods\n\n```bash\n# Using snapshot refs (from playwright-cli snapshot)\nplaywright-cli click e15\n\n# CSS selectors\nplaywright-cli click \"#main > button.submit\"\n\n# Role locators\nplaywright-cli click \"getByRole('button', { name: 'Submit' })\"\n\n# Test IDs\nplaywright-cli click \"getByTestId('submit-button')\"\n```\n\n### Interaction Commands\n\n| Command | Description | Example |\n|---------|-------------|---------|\n| `click` | Click element | `playwright-cli click e5` |\n| `fill` | Type into input | `playwright-cli fill e4 \"hello world\"` |\n| `hover` | Hover over element | `playwright-cli hover e4` |\n| `select` | Select dropdown option | `playwright-cli select e9 \"option-value\"` |\n| `check/uncheck` | Toggle checkbox | `playwright-cli check e12` |\n| `drag` | Drag and drop | `playwright-cli drop e4 --data=\"text/plain=hello\"` |\n| `upload` | Upload file | `playwright-cli upload ./document.pdf` |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n## Selector Manager\n\nThe server-side `SelectorManager` handles registration and lifecycle of selector engines across browser contexts.\n\n### Manager Responsibilities\n\n| Responsibility | Description |\n|----------------|-------------|\n| Engine Registration | Register built-in and custom engines |\n| Context Management | Create/destroy selector contexts |\n| Session Handling | Maintain state across browser sessions |\n| Channel Communication | Bridge between server and injected script |\n\n### Custom Selector Registration\n\n```typescript\n// Register a custom selector engine\nawait test.selectors.register({\n  name: 'my-selector',\n  query: async (root, selector) => {\n    return root.querySelector(selector);\n  },\n  queryAll: async (root, selector) => {\n    return [...root.querySelectorAll(selector)];\n  }\n});\n```\n\n资料来源：[packages/playwright-core/src/server/selectors.ts](packages/playwright-core/src/server/selectors.ts)\n\n## Element Interaction Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Test Code\n    participant L as Locator API\n    participant S as Selector Manager\n    participant I as Injected Script\n    participant B as Browser DOM\n\n    T->>L: locator.click(\"button\")\n    L->>S: query(\"button\")\n    S->>I: evaluate querySelector\n    I->>B: query DOM\n    B->>I: return Element\n    I->>S: return Element\n    S->>L: return Element\n    L->>L: waitForElement\n    L->>T: click complete\n```\n\n## Best Practices\n\n### Preferred Selector Order\n\n1. **Test IDs** (`data-testid`) — Most stable and explicit\n2. **Role + Name** — Semantically meaningful and accessible\n3. **Text Content** — Human-readable but may change\n4. **CSS Classes/IDs** — Fast but brittle\n5. **XPath** — Last resort; hard to maintain\n\n### Anti-Patterns to Avoid\n\n| Anti-Pattern | Problem | Alternative |\n|--------------|---------|-------------|\n| Index-based `nth=` | Breaks with layout changes | Use role/name filtering |\n| Deep CSS paths | Fragile to DOM changes | Use semantic selectors |\n| Dynamic attributes | Unstable in CI | Use stable test IDs |\n| Coordinates | Resolution-dependent | Use element targets |\n\n## Summary\n\nPlaywright's locator and selector system provides a flexible, multi-engine approach to DOM element identification:\n\n- **Locator API** offers a fluent, retry-based interface for test authors\n- **Multiple selector engines** handle CSS, ARIA roles, text, and custom selectors\n- **Injected Script** enables browser-side evaluation without round-trips\n- **Selector Generator** helps discover optimal selectors during development\n\nThe architecture prioritizes accessibility (role selectors), stability (test IDs), and developer experience (fluent API) while maintaining performance through optimized DOM queries.\n\n---\n\n<a id='page-7'></a>\n\n## Assertions, Matchers, and Expect API\n\n### 相关页面\n\n相关主题：[Test Runner and Execution Engine](#page-5), [Locators, Selectors, and Element Interaction](#page-6)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright/src/matchers/expect.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/expect.ts)\n- [packages/playwright/src/matchers/matchers.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/matchers.ts)\n- [packages/playwright/src/matchers/toMatchSnapshot.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/toMatchSnapshot.ts)\n- [packages/playwright/src/matchers/toMatchAriaSnapshot.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright/src/matchers/toMatchAriaSnapshot.ts)\n- [packages/isomorphic/expectUtils.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/expectUtils.ts)\n- [packages/isomorphic/assert.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/assert.ts)\n</details>\n\n# Assertions, Matchers, and Expect API\n\nPlaywright's assertion system provides a powerful, auto-retrying mechanism for validating application state during end-to-end testing. The `expect` API combined with matchers enables test authors to write expressive, readable assertions that automatically wait for conditions to be met rather than requiring manual polling or arbitrary timeouts.\n\n## Overview\n\nPlaywright's assertion framework is built on three core concepts that work together to provide reliable test assertions:\n\n| Component | Purpose |\n|-----------|---------|\n| **Expect API** | Core assertion function that wraps values and provides matcher methods |\n| **Matchers** | Individual comparison functions that validate specific conditions |\n| **Expect Utils** | Shared utility functions for handling timeouts, polling, and error messages |\n\nThe architecture follows a layered approach where the `expect` function creates an expectation object that chains matcher methods. Each matcher returns either a pass result or throws an error with detailed context about what failed.\n\n```mermaid\ngraph TD\n    A[Test Code] --> B[expect value]\n    B --> C[Expectation Object]\n    C --> D[Matcher Methods]\n    D --> E{Auto-retry Loop}\n    E -->|condition met| F[Pass - Continue]\n    E -->|condition not met| G[Wait and Retry]\n    G --> E\n    E -->|timeout exceeded| H[Throw ExpectationError]\n    F --> I[Test Continues]\n    H --> J[Test Fails]\n```\n\n## Core Files and Structure\n\n### Expect Implementation\n\nThe main `expect` function is defined in `packages/playwright/src/matchers/expect.ts`. This file exports the `expect` function and the `Expect` class that handles the retry logic and matcher invocation.\n\nKey responsibilities:\n- Creating expectation objects from actual values\n- Managing auto-retry mechanisms with configurable timeouts\n- Formatting error messages with expected vs. actual values\n- Supporting both synchronous and asynchronous expectations\n\n### Matchers Module\n\nThe matchers are defined in `packages/playwright/src/matchers/matchers.ts`. This file contains all built-in matcher functions that can be chained off the `expect` call.\n\n### Isomorphic Utilities\n\nShared assertion utilities in `packages/isomorphic/expectUtils.ts` and `packages/isomorphic/assert.ts` provide platform-agnostic functionality used across different Playwright packages.\n\n## Expect API Reference\n\n### Basic Usage\n\n```typescript\nimport { test, expect } from '@playwright/test';\n\ntest('login page', async ({ page }) => {\n  await page.goto('/login');\n  \n  // Basic equality assertion\n  await expect(page).toHaveTitle('Login');\n  \n  // Locator assertion with auto-wait\n  await expect(page.getByRole('button', { name: 'Submit' })).toBeVisible();\n  \n  // Text content assertion\n  await expect(page.locator('.error')).toHaveText('Invalid credentials');\n});\n```\n\n### Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `timeout` | `number` | Matcher's default | Maximum time to retry the assertion |\n| `message` | `string \\| function` | auto-generated | Custom error message on failure |\n| `containsText` | `string \\| RegExp` | - | Pattern that should appear in error |\n\n## Built-in Matchers\n\n### Web-First Assertions\n\nPlaywright provides specialized \"web-first\" assertions optimized for UI testing. These assertions automatically wait for the expected state before failing.\n\n#### Visibility and Presence\n\n| Matcher | Description |\n|---------|-------------|\n| `toBeVisible()` | Element is visible and not obscured |\n| `toBeHidden()` | Element is not visible |\n| `toBeAttached()` | Element is present in DOM |\n| `toBeEnabled()` | Element is enabled (not disabled) |\n| `toBeDisabled()` | Element is disabled |\n| `toBeEditable()` | Element is editable |\n| `toBeFocused()` | Element has focus |\n\n#### Content Assertions\n\n| Matcher | Description |\n|---------|-------------|\n| `toHaveText(expected, options?)` | Element contains exact or partial text |\n| `toContainText(expected)` | Element contains text (partial match) |\n| `toHaveValue(value)` | Input element has specific value |\n| `toHaveValues(values)` | Multiple select or checkbox group values |\n| `toHaveTitle(title)` | Page has specific title |\n| `toHaveURL(url)` | Page has specific URL |\n| `toHaveScreenshot(name, options?)` | Element/page matches screenshot |\n\n#### Form and Input Assertions\n\n| Matcher | Description |\n|---------|-------------|\n| `toBeChecked()` | Checkbox or radio is checked |\n| `toHaveChecked()` | Checkbox with specific state |\n| `toBeSelected()` | Option is selected in select element |\n| `toBeRequired()` | Input is marked as required |\n| `toBeValid()` | Input passes validation constraints |\n\n### Negation\n\nAll matchers support negation using `.not`:\n\n```typescript\nawait expect(page.getByRole('button')).not.toBeDisabled();\nawait expect(page.locator('.loading')).not.toBeVisible();\n```\n\n## Snapshot Testing\n\nPlaywright supports snapshot testing through dedicated matchers that compare rendered output against stored baselines.\n\n### Visual Snapshots\n\nThe `toMatchSnapshot` matcher captures and compares images:\n\n```typescript\ntest('screenshot comparison', async ({ page }) => {\n  await page.goto('/dashboard');\n  await expect(page).toMatchScreenshot('dashboard.png', {\n    fullPage: true,\n    animations: 'disabled'\n  });\n});\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | Snapshot file name |\n| `options?.fullPage` | `boolean` | Capture entire scrollable page |\n| `options?.animations` | `'disabled' \\| 'allow'` | Animation handling |\n| `options?.mask` | `locator[]` | Elements to mask in screenshot |\n| `options?.threshold` | `number` | Pixel matching threshold 0-1 |\n\n### Aria Snapshots\n\nThe `toMatchAriaSnapshot` matcher compares the semantic structure of the page:\n\n```typescript\ntest('page structure', async ({ page }) => {\n  await page.goto('/form');\n  await expect(page).toMatchAriaSnapshot(`\n    - heading \"Create Account\"\n    - textbox \"Email\"\n    - textbox \"Password\"\n    - button \"Submit\"\n  `);\n});\n```\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `snapshot` | `string` | Expected ARIA tree structure |\n| `options?.timeout` | `number` | Retry timeout in ms |\n| `options?.matcher` | `string \\| RegExp` | Custom snapshot matcher |\n\n### Updating Snapshots\n\nWhen UI changes are intentional, update snapshots using the CLI:\n\n```bash\nnpx playwright test --update-snapshots\n# or\nnpx playwright test -u\n```\n\n## Custom Matchers\n\n### Defining Custom Matchers\n\nExtend the `expect` object with custom matchers for project-specific assertions:\n\n```typescript\n// expect.d.ts or custom expect file\nimport { expect as baseExpect } from '@playwright/test';\n\nexport { test } from '@playwright/test';\n\nexport const expect = baseExpect.extend({\n  async toHaveAnalyticsEvent(\n    locator: Locator,\n    eventName: string,\n    options?: { timeout?: number }\n  ) {\n    const timeout = options?.timeout ?? 1000;\n    const analyticsData: string[] = [];\n    \n    const listener = (event: ConsoleMessage) => {\n      if (event.type() === 'log') {\n        analyticsData.push(event.text());\n      }\n    };\n    \n    locator.page().on('console', listener);\n    \n    try {\n      await page.waitForFunction(\n        (name) => window.analytics?.events?.includes(name),\n        eventName,\n        { timeout }\n      );\n      return { pass: true };\n    } catch {\n      return {\n        pass: false,\n        message: () => `Expected analytics event \"${eventName}\" was not fired`,\n      };\n    } finally {\n      locator.page().off('console', listener);\n    }\n  },\n});\n```\n\n### Using Custom Matchers\n\n```typescript\nimport { expect } from './expect';\n\ntest('analytics tracking', async ({ page }) => {\n  await page.goto('/products');\n  await page.click('.buy-button');\n  \n  // Uses custom matcher\n  await expect(page).toHaveAnalyticsEvent('purchase_initiated');\n});\n```\n\n## Auto-Retry Behavior\n\nPlaywright assertions automatically retry until the condition is met or timeout expires. This eliminates flaky tests caused by timing issues.\n\n### Retry Loop Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Test\n    participant E as Expect\n    participant M as Matcher\n    participant P as Page\n\n    T->>E: expect(locator).toBeVisible()\n    Note over E: Create Expectation\n    loop Retry until timeout\n        E->>M: Compare current state\n        M->>P: Query element state\n        alt Condition met\n            M-->>E: Pass\n            E-->>T: Continue\n        else Condition not met\n            M-->>E: Fail\n            E->>E: Wait (default: 100ms)\n        end\n    end\n    Note over E: Timeout exceeded\n    E-->>T: Throw ExpectationError\n```\n\n### Timeout Configuration\n\n```typescript\n// Per-assertion timeout\nawait expect(page.locator('.loading')).toBeHidden({ timeout: 5000 });\n\n// Global default timeout\n// In playwright.config.ts:\nexport default {\n  expect: {\n    timeout: 5000,\n  },\n};\n```\n\n### Timeout Inheritance\n\n| Configuration Location | Value |\n|------------------------|-------|\n| Assertion option | `{ timeout: 3000 }` |\n| `expect` config section | `5000` |\n| Test fixture | Inherited |\n| Default | `1000` (1 second) |\n\n## Error Messages\n\nPlaywright generates detailed, actionable error messages when assertions fail.\n\n### Error Message Structure\n\n```\nexpect(received).toHaveText(expected)\n\nExpected string: \"Welcome, John\"\nReceived string: \"Welcome, Guest\"\n```\n\n### Custom Messages\n\n```typescript\nawait expect(page.locator('.balance')).toHaveText(\n  '$100.00',\n  { message: 'Balance should reflect completed transaction' }\n);\n\n// Or use a function for dynamic messages\nawait expect(page.locator('.status')).toHaveText(\n  'Active',\n  { message: () => `Expected status for user ${userId} to be Active` }\n);\n```\n\n## TypeScript Integration\n\n### Type Safety\n\nAll matchers are fully typed and provide autocomplete support:\n\n```typescript\n// TypeScript infers expected type\nawait expect(page.locator('input')).toHaveValue('hello');\n\n// For complex matchers, types are enforced\nawait expect(page).toHaveScreenshot('button.png', {\n  // options type is inferred\n  fullPage: true,\n  animations: 'disabled'\n});\n```\n\n### Generic Assertions\n\nFor custom assertion types, use generics:\n\n```typescript\nexpect.extend({\n  async toHaveData属性<T>(\n    this: jest.MatcherContext,\n    received: T,\n    key: string,\n    value: unknown\n  ) {\n    const data = (received as any)[key];\n    return {\n      pass: data === value,\n      message: () => `Expected ${key} to be ${value}, got ${data}`,\n    };\n  },\n});\n```\n\n## Best Practices\n\n### Prefer Web-First Assertions\n\nAlways use Playwright's built-in web-first assertions over raw comparisons:\n\n```typescript\n// ❌ Fragile - no auto-wait\nexpect(await page.textContent('button')).toBe('Submit');\n\n// ✅ Reliable - auto-waits and handles timing\nawait expect(page.getByRole('button')).toHaveText('Submit');\n```\n\n### Combine Matchers\n\nChain multiple matchers for comprehensive checks:\n\n```typescript\nawait expect(page.getByRole('textbox', { name: 'Email' }))\n  .toBeVisible()\n  .toBeEnabled()\n  .toBeFocused()\n  .toHaveAttribute('type', 'email');\n```\n\n### Use Descriptive Names\n\nName expectations clearly for better test output:\n\n```typescript\n// ❌ Unclear\nawait expect(page.locator('.main')).toHaveScreenshot('shot.png');\n\n// ✅ Clear intent\nawait expect(page).toMatchScreenshot('checkout-page-cart-items.png');\n```\n\n## Summary\n\nThe Assertions, Matchers, and Expect API form the foundation of Playwright's verification capabilities. Key takeaways:\n\n| Aspect | Key Point |\n|--------|-----------|\n| **Auto-retry** | Assertions automatically wait for conditions, reducing flakiness |\n| **Web-first** | Built specifically for dynamic web applications |\n| **Rich matchers** | Comprehensive set of UI-specific assertions |\n| **Snapshot support** | Visual and semantic snapshot testing built-in |\n| **Extensibility** | Custom matchers via `expect.extend` |\n| **TypeScript** | Full type safety and autocomplete support |\n\nThe system is designed to make tests reliable by default, allowing developers to focus on test logic rather than timing and synchronization concerns.\n\n---\n\n<a id='page-8'></a>\n\n## Browser Implementations and Protocol Support\n\n### 相关页面\n\n相关主题：[Browser Launch and Process Management](#page-4), [CLI, MCP Server, and Agent Integration](#page-10)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/server/chromium/chromium.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/chromium/chromium.ts)\n- [packages/playwright-core/src/server/chromium/crBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/chromium/crBrowser.ts)\n- [packages/playwright-core/src/server/firefox/firefox.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/firefox/firefox.ts)\n- [packages/playwright-core/src/server/firefox/ffBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/firefox/ffBrowser.ts)\n- [packages/playwright-core/src/server/webkit/webkit.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/webkit/webkit.ts)\n- [packages/playwright-core/src/server/webkit/wkBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/webkit/wkBrowser.ts)\n- [packages/playwright-core/src/server/bidi/bidiBrowser.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/bidi/bidiBrowser.ts)\n- [browser_patches/firefox/juggler](https://github.com/microsoft/playwright/blob/main/browser_patches/firefox/juggler)\n</details>\n\n# Browser Implementations and Protocol Support\n\n## Overview\n\nPlaywright's browser implementation architecture provides a unified automation API across three major browser engines: Chromium, Firefox, and WebKit. The architecture abstracts browser-specific differences through a common interface while supporting multiple protocols for communication between the Node.js process and browser instances. This design enables developers to write browser automation code once and execute it across different browsers without modification.\n\nThe browser implementations are organized in the `packages/playwright-core/src/server/` directory, with each browser type having its own subdirectory containing browser-specific initialization, connection, and protocol handling code. This modular structure allows for independent development and maintenance of each browser's implementation while sharing common infrastructure through the core playwright-core package.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"Playwright Core API\"\n        A[chromium.launch()] --> B[BrowserType]\n        C[firefox.launch()] --> B\n        D[webkit.launch()] --> B\n    end\n    \n    subgraph \"Protocol Layer\"\n        B --> E[CDP Connection]\n        B --> F[BiDi Protocol]\n    end\n    \n    subgraph \"Browser Implementations\"\n        E --> G[Chromium Browser]\n        E --> H[WebKit Browser]\n        F --> I[Firefox Browser]\n        F --> J[Chromium via BiDi]\n        F --> K[WebKit via BiDi]\n    end\n    \n    subgraph \"Browser Processes\"\n        G --> L[Chromium Process]\n        H --> M[WebKit Process]\n        I --> N[Firefox + Juggler]\n    end\n```\n\n## Browser Package Structure\n\nPlaywright provides separate packages for each browser to optimize installation and distribution. The packages enable automatic installation of browser binaries when imported.\n\n| Package Name | Description | Auto-Install | Main Export |\n|--------------|-------------|--------------|-------------|\n| `playwright-chromium` | Chromium browser support | Yes | `chromium` |\n| `@playwright/browser-chromium` | Chromium browser support | Yes | `chromium` |\n| `playwright` | All browsers | Yes | `chromium`, `firefox`, `webkit` |\n| `playwright-core` | All browsers | No | `chromium`, `firefox`, `webkit` |\n| `@playwright/browser-webkit` | WebKit browser support | Yes | `webkit` |\n| `playwright-browser-webkit` | WebKit browser support | Yes | `webkit` |\n\nEach package exports a `chromium`, `firefox`, or `webkit` object that provides the `BrowserType` interface for launching browser instances. The packages share common dependencies through `playwright-core`, which contains the actual implementation logic.\n\n## Chromium Implementation\n\nThe Chromium implementation consists of two main components: the browser type definition and the actual browser instance management.\n\n### Chromium Architecture\n\n```mermaid\ngraph TD\n    A[chromium.launch()] --> B[Chromium#44;BrowserType]\n    B --> C[ChromiumBrowser#44;ConnectedBrowser]\n    C --> D[CDP Session]\n    C --> E[ChromiumBrowserContext]\n    D --> F[Chrome DevTools Protocol]\n    E --> G[ChromiumPage]\n    G --> F\n```\n\n### Browser Type (`chromium.ts`)\n\nThe Chromium browser type class extends the base `BrowserType` interface and provides the specific configuration for launching Chromium instances. This file contains:\n\n- **Launch options**: Configuration for headless mode, viewport, user agent, and other browser settings\n- **Browser binary path**: Resolution logic for finding the Chromium executable\n- **Connection establishment**: Code for establishing CDP connections to the browser\n- **Feature detection**: Capabilities and features specific to Chromium\n\n### Browser Instance (`crBrowser.ts`)\n\nThe Chromium browser instance class manages the lifecycle of a connected Chromium browser. Key responsibilities include:\n\n- **Page management**: Creating and tracking page instances\n- **Context management**: Handling browser contexts for isolation\n- **CDP session handling**: Managing DevTools protocol sessions\n- **Process management**: Monitoring and terminating the browser process\n\n## Firefox Implementation\n\nFirefox requires special handling due to its architecture. Unlike Chromium and WebKit which support CDP directly, Firefox uses a patched version called Juggler.\n\n### Firefox Architecture with Juggler\n\n```mermaid\ngraph TD\n    A[firefox.launch()] --> B[Firefox#44;BrowserType]\n    B --> C[FFBrowser#44;ConnectedBrowser]\n    C --> D[Juggler Bridge]\n    D --> E[CDP to Juggler Translation]\n    E --> F[Firefox Browser Process]\n    \n    subgraph \"Browser Patches\"\n        G[Juggler Protocol]\n        H[CDP Emulator]\n        I[Automation Hooks]\n    end\n    \n    D --> G\n    G --> H\n    G --> I\n```\n\n### Juggler Protocol Handler\n\nThe Firefox implementation uses Juggler, a custom protocol handler that bridges Playwright's CDP-based API with Firefox's automation capabilities. The Juggler component:\n\n- **Patches Firefox**: Modifies Firefox behavior to enable automation\n- **Protocol translation**: Converts CDP commands to Firefox-specific commands\n- **Event forwarding**: Streams events from Firefox back to Playwright\n\nThis architecture allows Playwright to provide a consistent API across all browsers while accommodating Firefox's different internal architecture.\n\n### Browser Type (`firefox.ts`)\n\nThe Firefox browser type handles:\n\n- **Binary detection**: Locating the Firefox executable\n- **Profile management**: Creating temporary profiles for isolation\n- **Launch configuration**: Setting up Firefox-specific options\n- **Juggler injection**: Ensuring Juggler is properly initialized\n\n### Browser Instance (`ffBrowser.ts`)\n\nThe Firefox browser instance provides:\n\n- **Page tracking**: Managing page instances within Firefox\n- **Context handling**: Isolating browsing contexts\n- **Protocol communication**: Managing Juggler-based communication\n\n## WebKit Implementation\n\nWebKit powers Safari and other browsers. Playwright's WebKit implementation provides support for this browser engine through a combination of native CDP support and custom protocol handling.\n\n### WebKit Architecture\n\n```mermaid\ngraph TD\n    A[webkit.launch()] --> B[WebKit#44;BrowserType]\n    B --> C[WKBrowser#44;ConnectedBrowser]\n    C --> D[WebKit Protocol Handler]\n    D --> E[CDP Compatible Layer]\n    E --> F[WebKit Browser Process]\n    \n    C --> G[WebKitBrowserContext]\n    G --> H[WKPage]\n    H --> D\n```\n\n### Browser Type (`webkit.ts`)\n\nThe WebKit browser type includes:\n\n- **Executable resolution**: Finding WebKit-based browsers\n- **Launch parameters**: Configuring WebKit-specific options\n- **Connection setup**: Establishing protocol communication\n\n### Browser Instance (`wkBrowser.ts`)\n\nThe WebKit browser instance manages:\n\n- **Page lifecycle**: Creating and managing page instances\n- **Protocol sessions**: Handling WebKit's protocol communication\n- **Feature compatibility**: Ensuring WebKit-specific features work correctly\n\n## BiDi Protocol Support\n\nThe WebDriver BiDi (Bidirectional) protocol is a standardized web automation protocol that provides bidirectional communication between automation tools and browsers. Playwright's support for BiDi enables:\n\n- **Standardization**: Using the W3C-standardized protocol\n- **Cross-browser compatibility**: A single protocol approach\n- **Reduced complexity**: Simpler protocol handling compared to CDP\n\n### BiDi Architecture\n\n```mermaid\ngraph TD\n    A[BiDi Browser Connection] --> B[BidiBrowser#44;ConnectedBrowser]\n    B --> C[BiDi Session]\n    C --> D[Command Handler]\n    C --> E[Event Handler]\n    \n    D --> F[Browser Commands]\n    E --> G[Browser Events]\n    \n    B --> H[BrowserContext]\n    H --> I[Page]\n    \n    subgraph \"BiDi Protocol Messages\"\n        J[JSON-RPC 2.0]\n        K[WebSocket Transport]\n    end\n    \n    C --> J\n    J --> K\n```\n\n### BiDi Browser (`bidiBrowser.ts`)\n\nThe BiDi browser implementation provides:\n\n- **Session management**: Creating and maintaining BiDi sessions\n- **Command routing**: Dispatching commands to appropriate handlers\n- **Event subscription**: Managing browser event subscriptions\n- **Context isolation**: Supporting multiple browser contexts\n\n## Protocol Communication\n\nPlaywright supports multiple communication protocols for interacting with browsers. Understanding these protocols helps in debugging and extending Playwright's capabilities.\n\n### Chrome DevTools Protocol (CDP)\n\nCDP is the primary protocol used by Chromium and partially by WebKit. It provides:\n\n- **Complete browser control**: Full access to browser features\n- **Rich debugging**: Detailed debugging capabilities\n- **Real-time events**: Immediate event notifications\n\n### WebDriver BiDi\n\nBiDi is the W3C-standardized protocol for browser automation:\n\n- **Cross-browser support**: Standard protocol across all browsers\n- **Bidirectional communication**: Events flow both directions\n- **Simpler model**: Less complex than CDP for basic operations\n\n### Protocol Selection\n\n| Feature | CDP | BiDi |\n|---------|-----|------|\n| Browser support | Chromium, WebKit | All browsers |\n| Event subscription | Full | Full |\n| Performance | Optimized | Standard |\n| Standardization | Google-specific | W3C standard |\n\n## Launch Configuration\n\nEach browser type accepts launch options that configure how the browser instance is created.\n\n### Common Launch Options\n\n| Option | Type | Description | Chromium | Firefox | WebKit |\n|--------|------|-------------|----------|---------|--------|\n| `headless` | boolean | Run without visible UI | ✓ | ✓ | ✓ |\n| `args` | string[] | Additional browser arguments | ✓ | ✓ | ✓ |\n| `executablePath` | string | Custom browser executable | ✓ | ✓ | ✓ |\n| `timeout` | number | Launch timeout in ms | ✓ | ✓ | ✓ |\n| `viewport` | Viewport | Default page viewport | ✓ | ✓ | ✓ |\n| `userAgent` | string | Custom user agent | ✓ | ✓ | ✓ |\n| `locale` | string | Browser locale | ✓ | ✓ | ✓ |\n| `proxy` | ProxyConfig | Proxy settings | ✓ | ✓ | ✓ |\n\n### Headless Mode\n\nHeadless mode runs the browser without visible UI, essential for CI/CD environments and server-side automation. All three browsers support headless execution with identical behavior.\n\n### Persistent Contexts\n\nPlaywright supports persistent browser contexts that maintain state across sessions:\n\n```mermaid\ngraph LR\n    A[User Data Directory] --> B[Browser Profile]\n    B --> C[Cookies]\n    B --> D[Local Storage]\n    B --> E[Session Storage]\n    B --> F[Cache]\n```\n\n## Browser Contexts and Pages\n\n### Architecture\n\n```mermaid\ngraph TD\n    Browser --> Context1[BrowserContext]\n    Browser --> Context2[BrowserContext]\n    \n    Context1 --> Page1[Page]\n    Context1 --> Page2[Page]\n    Context2 --> Page3[Page]\n    \n    Page1 --> CDPSession[CDP Session]\n    Page2 --> CDPSession\n```\n\n### BrowserContext\n\nBrowser contexts provide isolation between different automation sessions:\n\n- **Separate storage**: Each context has its own cookies, cache, and storage\n- **Independent state**: Actions in one context don't affect others\n- **Parallel execution**: Contexts can run simultaneously\n- **Resource isolation**: Memory and process isolation\n\n### Page\n\nPages represent individual browser tabs or windows:\n\n- **Navigation**: Loading URLs and managing history\n- **Interaction**: Clicking, typing, and other user actions\n- **Evaluation**: Running JavaScript in the page context\n- **Capture**: Taking screenshots and generating PDFs\n\n## Process Architecture\n\n### Browser Process Model\n\n```mermaid\ngraph TD\n    subgraph \"Node.js Process\"\n        A[Playwright API]\n        B[Connection]\n    end\n    \n    subgraph \"Browser Process\"\n        C[Browser Main Process]\n        D[Renderer Process 1]\n        E[Renderer Process 2]\n        F[Renderer Process N]\n    end\n    \n    B --> C\n    C --> D\n    C --> E\n    C --> F\n```\n\n### Process Communication\n\nThe communication between Node.js and browser processes varies by browser:\n\n- **Chromium**: Direct CDP over WebSocket or pipe\n- **Firefox**: Juggler bridge acting as intermediary\n- **WebKit**: CDP-compatible protocol over WebSocket\n\n## Version Compatibility\n\nPlaywright maintains compatibility matrices for browser versions to ensure stable automation:\n\n| Playwright Version | Chromium | Firefox | WebKit |\n|-------------------|----------|---------|--------|\n| 1.61.0-next | Latest | Latest | Latest |\n| Stable releases | Bundled | Bundled | Bundled |\n\nBrowser binaries are downloaded and managed by Playwright's installer, ensuring version compatibility between the library and browser binaries.\n\n## Extension Points\n\nThe browser implementation architecture supports extension through:\n\n### Custom Browser Executables\n\n```typescript\nconst browser = await chromium.launch({\n  executablePath: '/path/to/custom/chromium'\n});\n```\n\n### Protocol Interceptors\n\nExtensions can intercept and modify protocol messages for debugging or custom behavior.\n\n### Custom Context Options\n\nBrowser contexts accept custom options specific to each browser implementation.\n\n## Troubleshooting\n\n### Browser Installation Issues\n\n```bash\n# Install all browsers\nnpx playwright install\n\n# Install specific browser\nnpx playwright install chromium\nnpx playwright install firefox\nnpx playwright install webkit\n```\n\n### Connection Issues\n\nConnection problems typically manifest as timeout errors during launch or operation. The trace viewer tool (`npx playwright trace`) helps diagnose these issues by capturing detailed protocol communication.\n\n### Platform-Specific Considerations\n\nEach browser may have platform-specific requirements:\n\n- **Chromium**: Generally has few platform-specific issues\n- **Firefox**: Requires Juggler patches for all platforms\n- **WebKit**: May require platform-specific dependencies\n\n## Summary\n\nPlaywright's browser implementation architecture provides a robust, extensible foundation for cross-browser automation. By abstracting browser-specific details through a common interface while supporting multiple communication protocols, Playwright enables developers to write reliable browser automation code that works consistently across Chromium, Firefox, and WebKit.\n\nThe architecture's modular design allows for independent browser implementations while sharing common infrastructure, making it possible to add new browser support or extend existing capabilities without affecting the overall system.\n\n---\n\n<a id='page-9'></a>\n\n## Trace Viewer and Debugging Tools\n\n### 相关页面\n\n相关主题：[Test Runner and Execution Engine](#page-5), [CLI, MCP Server, and Agent Integration](#page-10)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/server/trace/recorder/tracing.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/trace/recorder/tracing.ts)\n- [packages/playwright-core/src/server/trace/recorder/snapshotter.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/trace/recorder/snapshotter.ts)\n- [packages/trace-viewer/src/index.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/index.tsx)\n- [packages/trace-viewer/src/ui/workbench.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbench.tsx)\n- [packages/isomorphic/trace/traceLoader.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/trace/traceLoader.ts)\n- [packages/isomorphic/trace/traceModel.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/trace/traceModel.ts)\n- [packages/trace/src/trace.ts](https://github.com/microsoft/playwright/blob/main/packages/trace/src/trace.ts)\n</details>\n\n# Trace Viewer and Debugging Tools\n\n## Overview\n\nPlaywright's Trace Viewer and Debugging Tools provide comprehensive execution tracing capabilities for debugging and analyzing browser automation tests. The tracing system captures detailed execution traces including DOM snapshots, screenshots, network activity, and console logs, enabling developers to reconstruct and analyze exactly what happened during test execution.\n\nThe trace infrastructure consists of three main components:\n\n| Component | Purpose | Location |\n|-----------|---------|----------|\n| Trace Recorder | Captures actions, snapshots, and metadata during test execution | `packages/playwright-core/src/server/trace/recorder/` |\n| Trace Viewer | Progressive Web App for visual trace inspection | `packages/trace-viewer/` |\n| Trace Model | Data structures and loading logic for trace files | `packages/isomorphic/trace/` |\n\n资料来源：[packages/trace-viewer/src/index.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/index.tsx)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Test Execution] --> B[Tracing Recorder]\n    B --> C[Snapshotter]\n    B --> D[Action Logger]\n    B --> E[Network Monitor]\n    \n    C --> F[DOM Snapshots]\n    D --> G[Action Log]\n    E --> H[Network Events]\n    \n    F --> I[trace-{timestamp}.trace]\n    G --> I\n    H --> J[trace-{timestamp}.network]\n    \n    I --> K[Trace ZIP Archive]\n    J --> K\n    K --> L[Trace Viewer PWA]\n    K --> M[playwright trace CLI]\n```\n\n### Core Components\n\n#### Trace Recorder (`packages/playwright-core/src/server/trace/recorder/tracing.ts`)\n\nThe `Tracing` class manages the recording process for browser contexts. It initializes snapshot capture, action logging, and network monitoring.\n\n| Method | Description |\n|--------|-------------|\n| `start()` | Initializes trace recording with snapshotter and action collectors |\n| `stop()` | Finalizes and writes trace files |\n| `snapshot()` | Captures current DOM state |\n\n#### Snapshotter (`packages/playwright-core/src/server/trace/recorder/snapshotter.ts`)\n\nCaptures DOM snapshots before and after each action, enabling reconstruction of page state at any point during test execution.\n\n资料来源：[packages/playwright-core/src/server/trace/recorder/snapshotter.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/trace/recorder/snapshotter.ts)\n\n#### Trace Model (`packages/isomorphic/trace/traceModel.ts`)\n\nThe `TraceModel` class represents the in-memory structure of a trace file, containing:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `actions` | `ActionTrace[]` | All recorded actions |\n| `events` | `TraceEvent[]` | Network, console, and other events |\n| `snapshots` | `Snapshot[]` | DOM snapshots |\n\n#### Trace Loader (`packages/isomorphic/trace/traceLoader.ts`)\n\nHandles parsing and loading of trace files from disk or network.\n\n资料来源：[packages/isomorphic/trace/traceLoader.ts](https://github.com/microsoft/playwright/blob/main/packages/isomorphic/trace/traceLoader.ts)\n\n## Trace File Format\n\nWhen tracing starts, Playwright creates a `traces/` directory containing several files:\n\n### File Structure\n\n| File | Format | Contents |\n|------|--------|----------|\n| `trace-{timestamp}.trace` | Binary/JSON | Action log with DOM snapshots, screenshots, timing |\n| `trace-{timestamp}.network` | Binary/JSON | Complete network activity including headers, bodies, timing |\n| `resources/` | Directory | Cached resources (images, fonts, scripts) |\n\n### Trace Archive\n\nAll trace files are packaged into a `.zip` archive for easy sharing and analysis:\n\n```bash\n# Default location\ntest-results/{test-name}/trace.zip\n```\n\n### Captured Data Categories\n\n| Category | Details |\n|----------|---------|\n| **Actions** | Clicks, fills, hovers, keyboard input, navigations |\n| **DOM** | Full DOM snapshot before/after each action |\n| **Screenshots** | Visual state at each step |\n| **Network** | All requests, responses, headers, bodies, timing |\n| **Console** | Browser console messages and stdout/stderr |\n| **Errors** | Error messages with stack traces |\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/tracing.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/tracing.md)\n\n## Trace Viewer UI\n\nThe Trace Viewer is a Progressive Web App that runs locally in the browser without sending trace data anywhere.\n\n```mermaid\ngraph LR\n    A[Open trace.zip] --> B[Extract & Parse]\n    B --> C[Action Timeline]\n    B --> D[Snapshot View]\n    B --> E[Network Log]\n    B --> F[Console Output]\n```\n\n### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| **Action Timeline** | Visual representation of all actions with timing |\n| **DOM Snapshots** | Interactive DOM inspection at any action point |\n| **Network Log** | Filterable view of all HTTP requests/responses |\n| **Console View** | Console messages with filtering by type |\n| **Error Tracking** | Consolidated view of all errors with stack traces |\n\n### Loading Traces\n\nTraces can be loaded in multiple ways:\n\n1. **Local File**: Drop `.zip` file directly into the viewer\n2. **URL Parameter**: Pass `?trace=` with trace URL\n3. **Upload Button**: Select file via browser dialog\n\nThe viewer displays a progress indicator during trace loading:\n\n```tsx\n<Dialog open={showProgressDialog} isModal={true}>\n  <div className='progress-content'>\n    <div className='title'>Loading Playwright Trace...</div>\n    <div className='progress-wrapper'>\n      <div className='inner-progress' \n        style={{ width: progress.total ? (100 * progress.done / progress.total) + '%' : 0 }}>\n      </div>\n    </div>\n  </div>\n</Dialog>\n```\n\n资料来源：[packages/trace-viewer/src/ui/workbench.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbench.tsx)\n\n## CLI Commands\n\n### Trace Recording Commands\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli tracing-start` | Start trace recording |\n| `playwright-cli tracing-stop` | Stop trace recording and save |\n\n### Trace Inspection Commands\n\n| Command | Description |\n|---------|-------------|\n| `npx playwright trace open <trace.zip>` | Open and extract trace |\n| `npx playwright trace close` | Remove extracted trace data |\n| `npx playwright trace actions` | List all actions |\n| `npx playwright trace actions --grep \"click\"` | Filter actions by pattern |\n| `npx playwright trace actions --errors-only` | Show only failed actions |\n| `npx playwright trace action <id>` | Show details for one action |\n| `npx playwright trace requests` | List all network requests |\n| `npx playwright trace requests --failed` | Show only failed requests |\n| `npx playwright trace request <id>` | Show request details |\n| `npx playwright trace console` | Show console messages |\n| `npx playwright trace console --errors-only` | Show only errors |\n| `npx playwright trace errors` | Show all errors with stack traces |\n| `npx playwright trace snapshot <id>` | Get DOM snapshot |\n| `npx playwright trace attachments` | List trace attachments |\n\n### Example Workflow\n\n```bash\n# 1. Open trace and view metadata\nnpx playwright trace open test-results/my-test/trace.zip\n\n# 2. List all actions\nnpx playwright trace actions\n\n# 3. Show only failed actions\nnpx playwright trace actions --errors-only\n\n# 4. Get details for specific action\nnpx playwright trace action 12\n\n# 5. View DOM at that point\nnpx playwright trace snapshot 12\n\n# 6. Check for network failures\nnpx playwright trace requests --failed\n\n# 7. View console errors\nnpx playwright trace console --errors-only\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n\n## Integration with Test Debugging\n\n### Debug Mode\n\nRun tests in debug mode with CLI integration:\n\n```bash\nPLAYWRIGHT_HTML_OPEN=never npx playwright test --debug=cli\n```\n\nThis command:\n1. Pauses test execution at start\n2. Prints debugging instructions with session name\n3. Allows attaching via `playwright-cli` to explore the page\n\n### Attaching to Test Session\n\n```bash\n# After starting debug mode, attach to the printed session\nplaywright-cli attach tw-abcdef\n```\n\nAvailable exploration commands while attached:\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli snapshot` | Get current DOM snapshot |\n| `playwright-cli click <ref>` | Interact with elements |\n| `playwright-cli eval <js>` | Execute JavaScript |\n| `playwright-cli show --annotate` | Launch annotation dashboard |\n| `playwright-cli resume` | Resume test execution |\n\n### Spec-Driven Testing Workflow\n\nThe debugging tools integrate with Playwright's spec-driven testing approach:\n\n1. **Create seed test** that navigates to the application\n2. **Run seed in debug mode** and attach via CLI\n3. **Explore the app** to understand interactive surfaces\n4. **Write spec file** documenting expected behavior\n5. **Generate tests** from the spec\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/playwright-tests.md)\n\n## API Reference\n\n### JavaScript Execution in CLI\n\nExecute arbitrary JavaScript in the browser context:\n\n```bash\n# Basic evaluation\nplaywright-cli eval \"document.title\"\n\n# With return value\nplaywright-cli run-code \"async page => await page.title()\"\n\n# Read from clipboard\nplaywright-cli run-code \"async page => {\n  await page.context().grantPermissions(['clipboard-read']);\n  return await page.evaluate(() => navigator.clipboard.readText());\n}\"\n```\n\n### Page Information\n\n```bash\n# Get page title\nplaywright-cli run-code \"async page => await page.title()\"\n\n# Get current URL\nplaywright-cli run-code \"async page => page.url()\"\n\n# Get viewport size\nplaywright-cli run-code \"async page => page.viewportSize()\"\n```\n\n### Snapshot with Custom Depth\n\n```bash\n# Default snapshot\nplaywright-cli snapshot\n\n# Snapshot with element bounding boxes\nplaywright-cli snapshot --boxes\n\n# Limited depth for performance\nplaywright-cli snapshot --depth=4\n\n# Snapshot specific element\nplaywright-cli snapshot \"#main\"\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/running-code.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/running-code.md)\n\n## Storage State Management\n\n### Saving Authentication State\n\n```bash\n# Step 1: Login and save state\nplaywright-cli open https://app.example.com/login\nplaywright-cli snapshot\nplaywright-cli fill e1 \"user@example.com\"\nplaywright-cli fill e2 \"password123\"\nplaywright-cli click e3\nplaywright-cli state-save auth.json\n\n# Step 2: Later, restore state\nplaywright-cli state-load auth.json\nplaywright-cli open https://app.example.com/dashboard\n# Already authenticated\n```\n\n### Cookie Management\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli cookie-list` | List all cookies |\n| `playwright-cli cookie-get <name>` | Get specific cookie |\n| `playwright-cli cookie-set <name> <value>` | Set a cookie |\n| `playwright-cli cookie-delete <name>` | Delete a cookie |\n| `playwright-cli cookie-clear` | Clear all cookies |\n\n### Local/Session Storage\n\n```bash\n# List storage items\nplaywright-cli localstorage-list\nplaywright-cli sessionstorage-list\n\n# Get specific value\nplaywright-cli localstorage-get theme\nplaywright-cli sessionstorage-get step\n\n# Set value\nplaywright-cli localstorage-set theme dark\nplaywright-cli sessionstorage-set step 3\n\n# Delete/Clear\nplaywright-cli localstorage-delete theme\nplaywright-cli localstorage-clear\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/storage-state.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/storage-state.md)\n\n## Advanced Features\n\n### Persistent Profiles\n\nBrowser profiles can be persisted to disk for testing scenarios requiring persistent state:\n\n```bash\n# Auto-generated profile location\nplaywright-cli open https://example.com --persistent\n\n# Custom profile directory\nplaywright-cli open https://example.com --profile=/path/to/profile\n\n# Create named session with persistent profile\nplaywright-cli -s=mysession open example.com --persistent\n```\n\n### Network Interception\n\n```bash\n# Mock responses\nplaywright-cli route \"**/*.jpg\" --status=404\nplaywright-cli route \"https://api.example.com/**\" --body='{\"mock\": true}'\n\n# List and remove routes\nplaywright-cli route-list\nplaywright-cli unroute \"**/*.jpg\"\n```\n\n### Highlighting Elements\n\n```bash\n# Highlight an element\nplaywright-cli highlight e5\n\n# Highlight with custom style\nplaywright-cli highlight e5 --style=\"outline: 3px dashed red\"\n\n# Hide highlights\nplaywright-cli highlight --hide\n```\n\n### Video Recording\n\n```bash\n# Start video recording\nplaywright-cli video-start video.webm\n\n# Add chapter markers\nplaywright-cli video-chapter \"Chapter Title\" --description=\"Details\" --duration=2000\n\n# Stop recording\nplaywright-cli video-stop\n```\n\n## Best Practices\n\n| Practice | Description |\n|----------|-------------|\n| **Use `--debug=cli`** | Always debug through test execution, not direct URL opening |\n| **Capture specific actions** | Use `--grep` flags to narrow focus during investigation |\n| **Save authentication state** | Reuse authenticated sessions instead of repeating login |\n| **Use raw output** | Pipe CLI output to tools like `jq` for scripting |\n| **Clean up traces** | Run `playwright-cli trace close` after investigation |\n\n### Raw Output for Scripting\n\n```bash\n# Get JSON output for processing\nplaywright-cli list --json\n\n# Pipe to jq for data extraction\nplaywright-cli --raw eval \"JSON.stringify(performance.timing)\" | jq '.loadEventEnd - .navigationStart'\n\n# Save to file\nplaywright-cli --raw snapshot > before.yml\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n---\n\n<a id='page-10'></a>\n\n## CLI, MCP Server, and Agent Integration\n\n### 相关页面\n\n相关主题：[Trace Viewer and Debugging Tools](#page-9)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/playwright-core/src/tools/cli-client/cli.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/cli.ts)\n- [packages/playwright-core/src/tools/mcp/index.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/index.ts)\n- [packages/playwright-core/src/tools/mcp/browserFactory.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserFactory.ts)\n- [packages/playwright-core/src/tools/mcp/browserModel.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserModel.ts)\n- [packages/playwright-core/src/tools/dashboard/dashboardApp.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/dashboard/dashboardApp.ts)\n- [packages/dashboard/src/dashboard.tsx](https://github.com/microsoft/playwright/blob/main/packages/dashboard/src/dashboard.tsx)\n- [packages/playwright-core/src/tools/backend/tools.ts](https://github.com/microsoft/microsoft/playwright/blob/main/packages/playwright-core/src/tools/backend/tools.ts)\n</details>\n\n# CLI, MCP Server, and Agent Integration\n\n## Overview\n\nPlaywright provides a comprehensive command-line interface (CLI), MCP (Model Context Protocol) server, and agent integration system that enables automated browser control, testing, and inspection workflows. These three interconnected components form the foundation of Playwright's external interaction layer, allowing developers and AI agents to programmatically control browsers, execute tests, and analyze application behavior.\n\nThe CLI layer (`playwright-cli`) provides a human-readable command interface for browser automation, while the MCP server exposes these capabilities to AI agents and automated systems. The agent integration system coordinates between tools, manages browser sessions, and maintains state across operations.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User / AI Agent] --> B[CLI Interface<br/>playwright-cli]\n    A --> C[MCP Server<br/>Model Context Protocol]\n    B --> D[Tool Backend<br/>packages/playwright-core/src/tools/backend/tools.ts]\n    C --> D\n    D --> E[Browser Factory<br/>browserFactory.ts]\n    E --> F[Browser Pool<br/>Chromium, Firefox, WebKit]\n    D --> G[Session Manager]\n    G --> H[State: Cookies, LocalStorage,<br/>SessionStorage]\n    D --> I[Trace Viewer<br/>trace viewer package]\n```\n\n## CLI (`playwright-cli`)\n\n### Purpose and Scope\n\nThe `playwright-cli` tool provides a command-line interface for browser automation and testing. It is defined in `packages/playwright-core/src/tools/cli-client/cli.ts` and offers a comprehensive set of commands for interacting with browsers without writing code directly.\n\nThe CLI accepts commands like `open`, `goto`, `click`, `fill`, `snapshot`, and many others, making browser automation accessible through a simple shell interface.\n\n### Core Commands\n\n#### Browser Lifecycle\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli open [url]` | Opens a new browser and optionally navigates to URL |\n| `playwright-cli close` | Closes the current browser session |\n| `playwright-cli close-all` | Closes all browser sessions |\n| `playwright-cli kill-all` | Forcefully terminates all browser processes |\n\n#### Navigation\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli goto <url>` | Navigate to the specified URL |\n| `playwright-cli go-back` | Navigate back in browser history |\n| `playwright-cli go-forward` | Navigate forward in browser history |\n| `playwright-cli reload` | Reload the current page |\n\n#### Element Interaction\n\n| Command | Description | Example |\n|---------|-------------|---------|\n| `playwright-cli click <ref>` | Click an element by ref | `playwright-cli click e15` |\n| `playwright-cli dblclick <ref>` | Double-click an element | `playwright-cli dblclick e7` |\n| `playwright-cli fill <ref> <text>` | Fill input field | `playwright-cli fill e5 \"text\"` |\n| `playwright-cli type <text>` | Type text into focused element | `playwright-cli type \"search\"` |\n| `playwright-cli press <key>` | Press a keyboard key | `playwright-cli press Enter` |\n| `playwright-cli select <ref> <value>` | Select dropdown option | `playwright-cli select e9 \"value\"` |\n| `playwright-cli check <ref>` | Check a checkbox | `playwright-cli check e12` |\n| `playwright-cli uncheck <ref>` | Uncheck a checkbox | `playwright-cli uncheck e12` |\n| `playwright-cli hover <ref>` | Hover over an element | `playwright-cli hover e4` |\n| `playwright-cli drag <src> <target>` | Drag element to target | `playwright-cli drag e2 e8` |\n\n#### Data Input\n\n| Command | Description |\n|---------|-------------|\n| `playwright-cli upload <path>` | Upload file to element |\n| `playwright-cli drop <ref> --path=<file>` | Drop file onto element |\n| `playwright-cli drop <ref> --data=<type>=<data>` | Drop data onto element |\n\n### Snapshot and Inspection\n\nThe snapshot command captures the current page state, including interactive elements with their refs:\n\n```bash\nplaywright-cli snapshot\nplaywright-cli snapshot --filename=state.yaml\nplaywright-cli snapshot \"#main\"\nplaywright-cli snapshot --depth=4\nplaywright-cli snapshot --boxes\n```\n\nElements can be targeted using refs from snapshots, CSS selectors, or Playwright locators:\n\n```bash\n# Using ref\nplaywright-cli click e15\n\n# Using CSS selector\nplaywright-cli click \"#main > button.submit\"\n\n# Using role locator\nplaywright-cli click \"getByRole('button', { name: 'Submit' })\"\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/SKILL.md)\n\n### Storage Management\n\n```bash\n# State persistence\nplaywright-cli state-save [filename]\nplaywright-cli state-load [filename]\n\n# Cookies\nplaywright-cli cookie-list [--domain=<domain>]\nplaywright-cli cookie-get <name>\nplaywright-cli cookie-set <name> <value> [--domain=<domain>] [--httpOnly] [--secure]\nplaywright-cli cookie-delete <name>\nplaywright-cli cookie-clear\n\n# LocalStorage\nplaywright-cli localstorage-list\nplaywright-cli localstorage-get <key>\nplaywright-cli localstorage-set <key> <value>\nplaywright-cli localstorage-delete <key>\nplaywright-cli localstorage-clear\n\n# SessionStorage\nplaywright-cli sessionstorage-list\nplaywright-cli sessionstorage-get <key>\nplaywright-cli sessionstorage-set <key> <value>\nplaywright-cli sessionstorage-delete <key>\nplaywright-cli sessionstorage-clear\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/session-management.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/session-management.md)\n\n### Network Interception\n\n```bash\n# Mock network responses\nplaywright-cli route \"**/*.jpg\" --status=404\nplaywright-cli route \"https://api.example.com/**\" --body='{\"mock\": true}'\nplaywright-cli route-list\nplaywright-cli unroute \"**/*.jpg\"\nplaywright-cli unroute\n```\n\n### Tracing\n\n```bash\n# Start/stop trace recording\nplaywright-cli tracing-start\nplaywright-cli tracing-stop\n\n# Video chapters\nplaywright-cli video-start <file.webm>\nplaywright-cli video-chapter \"Title\" --description=\"Details\" --duration=2000\nplaywright-cli video-stop\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/tracing.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/tracing.md)\n\n### Tab Management\n\n```bash\nplaywright-cli tab-list\nplaywright-cli tab-new [url]\nplaywright-cli tab-close [index]\nplaywright-cli tab-select <index>\n```\n\n### Dialog Handling\n\n```bash\nplaywright-cli dialog-accept [text]\nplaywright-cli dialog-dismiss\n```\n\n### Advanced: JavaScript Execution\n\n```bash\nplaywright-cli run-code \"async page => await page.title()\"\nplaywright-cli eval \"document.title\"\nplaywright-cli eval \"el => el.textContent\" <ref>\n```\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/running-code.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/running-code.md)\n\n### Browser Sessions\n\nSessions allow multiple independent browser instances with optional persistence:\n\n```bash\n# Named session with persistent profile\nplaywright-cli -s=mysession open https://example.com --persistent\n\n# With custom profile directory\nplaywright-cli -s=mysession open https://example.com --profile=/path/to/profile\n\n# Session management\nplaywright-cli -s=mysession click e6\nplaywright-cli -s=mysession close\nplaywright-cli -s=mysession delete-data\n\n# List and cleanup\nplaywright-cli list\nplaywright-cli close-all\nplaywright-cli kill-all\n```\n\nSession name can be set via environment variable:\n\n```bash\nexport PLAYWRIGHT_CLI_SESSION=\"mysession\"\n```\n\n## MCP Server Integration\n\n### Purpose and Architecture\n\nThe MCP (Model Context Protocol) server provides programmatic access to Playwright's browser automation capabilities for AI agents. The server is defined in `packages/playwright-core/src/tools/mcp/index.ts` and exposes a standardized interface for browser control operations.\n\n```mermaid\ngraph LR\n    A[AI Agent] -->|MCP Protocol| B[MCP Server<br/>index.ts]\n    B --> C[Browser Factory<br/>browserFactory.ts]\n    B --> D[Browser Model<br/>browserModel.ts]\n    C --> E[Chromium]\n    C --> F[Firefox]\n    C --> G[WebKit]\n    D --> H[Browser State<br/>and Context]\n```\n\n### Browser Factory (`browserFactory.ts`)\n\nThe `BrowserFactory` class is responsible for creating and managing browser instances. It provides methods for launching browsers with various configurations:\n\n```typescript\nclass BrowserFactory {\n  async launch(options?: BrowserLaunchOptions): Promise<Browser>;\n  async connect(browserWSEndpoint: string): Promise<Browser>;\n  async close(): Promise<void>;\n}\n```\n\nThe factory handles:\n- Browser type selection (Chromium, Firefox, WebKit)\n- Launch option configuration\n- Browser connection management\n- Resource cleanup\n\n资料来源：[packages/playwright-core/src/tools/mcp/browserFactory.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserFactory.ts)\n\n### Browser Model (`browserModel.ts`)\n\nThe `BrowserModel` maintains state and context for browser instances:\n\n```typescript\nclass BrowserModel {\n  id: string;\n  browser: Browser;\n  context: BrowserContext;\n  pages: Page[];\n  sessionName?: string;\n  createdAt: Date;\n}\n```\n\nKey responsibilities:\n- Tracking active pages and contexts\n- Managing browser lifecycle\n- Providing access to current state\n- Handling browser events\n\n资料来源：[packages/playwright-core/src/tools/mcp/browserModel.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp/browserModel.ts)\n\n### MCP Tool Interface\n\nThe MCP server exposes tools through the `tools.ts` backend:\n\n```typescript\n// Defined in packages/playwright-core/src/tools/backend/tools.ts\nexport interface Tool {\n  name: string;\n  description: string;\n  execute(params: ToolParams): Promise<ToolResult>;\n}\n```\n\nAvailable tool categories include:\n- Navigation tools (goto, back, forward, reload)\n- Interaction tools (click, fill, select, hover)\n- Inspection tools (snapshot, screenshot, content)\n- Storage tools (cookies, localStorage, sessionStorage)\n\n## Dashboard and Visualization\n\n### Dashboard Application (`dashboardApp.ts`)\n\nThe Playwright dashboard provides a visual interface for analyzing test results and traces:\n\n```mermaid\ngraph TD\n    A[Test Execution] --> B[Trace Files<br/>.zip format]\n    B --> C[Trace Viewer]\n    C --> D[Dashboard App<br/>dashboardApp.ts]\n    D --> E[Action Timeline]\n    D --> F[Network Log]\n    D --> G[Console Output]\n    D --> H[Screenshots]\n```\n\nThe dashboard displays:\n- Test action timeline with timing information\n- Network request/response logs\n- Console messages and errors\n- DOM snapshots at each step\n- Screenshots for visual verification\n\n资料来源：[packages/playwright-core/src/tools/dashboard/dashboardApp.ts](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/dashboard/dashboardApp.ts)\n\n### Trace Viewer (`workbenchLoader.tsx`)\n\nThe trace viewer is a Progressive Web App that loads locally without sending data externally:\n\n```typescript\n// Loading states\ninterface LoadState {\n  showFileUploadDropArea: boolean;\n  showProgressDialog: boolean;\n  processingErrorMessage?: string;\n  traceURL?: string;\n}\n```\n\nKey features:\n- Drag-and-drop trace file loading\n- File browser selection\n- Progress indication during trace parsing\n- Local-only processing for privacy\n\n资料来源：[packages/trace-viewer/src/ui/workbenchLoader.tsx](https://github.com/microsoft/playwright/blob/main/packages/trace-viewer/src/ui/workbenchLoader.tsx)\n\n### Dashboard React Component\n\nThe main dashboard component renders the UI:\n\n```typescript\n// packages/dashboard/src/dashboard.tsx\nexport const Dashboard: React.FC<DashboardProps> = ({ traceData }) => {\n  // Renders action tree, network log, console output, snapshots\n};\n```\n\n## Spec-Driven Testing Workflow\n\nThe CLI supports a specification-driven testing workflow documented in `spec-driven-testing.md`:\n\n```mermaid\ngraph LR\n    A[Write Spec File<br/>specs/feature.plan.md] --> B[Generate Tests]\n    B --> C[Execute Tests]\n    C --> D[Generate Traces]\n    D --> E[Analyze Results]\n    E --> F[Annotate & Feedback]\n```\n\n### Spec File Structure\n\n```markdown\n# <Feature> Test Plan\n\n## Application Overview\n<Description>\n\n## Test Scenarios\n\n### 1. <Group Name>\n**Seed:** `tests/seed.spec.ts`\n\n#### 1.1. <scenario-name>\n**File:** `tests/<group>/<scenario>.spec.ts`\n**Steps:**\n  1. <User step>\n     - expect: <outcome>\n  2. <Next step>\n     - expect: <outcome>\n```\n\n### Test Generation Flow\n\n1. Create seed test that navigates to the app\n2. Explore app using `playwright-cli attach` and `snapshot`\n3. Write spec file with test scenarios\n4. Generate actual test code from spec\n5. Execute and capture traces\n6. Review results in trace viewer\n\n资料来源：[packages/playwright-core/src/tools/cli-client/skill/references/spec-driven-testing.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/cli-client/skill/references/spec-driven-testing.md)\n\n## Trace CLI Tool\n\n### Command Reference\n\n```bash\n# Open and analyze traces\nnpx playwright trace open <trace.zip>\nnpx playwright trace close\n\n# List actions\nnpx playwright trace actions\nnpx playwright trace actions --grep \"click\"\nnpx playwright trace actions --errors-only\n\n# View specific action\nnpx playwright trace action <action-id>\n\n# View requests, console, errors\nnpx playwright trace requests\nnpx playwright trace console\nnpx playwright trace errors\n\n# Get DOM snapshot\nnpx playwright trace snapshot <action-id>\n```\n\n资料来源：[packages/playwright-core/src/tools/trace/SKILL.md](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/trace/SKILL.md)\n\n### Trace File Structure\n\nWhen tracing is enabled, Playwright creates:\n\n| File/Directory | Content |\n|---------------|---------|\n| `trace-{timestamp}.trace` | Action log with DOM snapshots, screenshots, timing |\n| `trace-{timestamp}.network` | Complete network activity log |\n| `resources/` | Cached resources for replay |\n\n## Tool Backend Architecture\n\nThe tool backend (`packages/playwright-core/src/tools/backend/tools.ts`) serves as the coordination layer:\n\n```mermaid\ngraph TD\n    A[CLI / MCP Server] --> B[Tool Backend<br/>tools.ts]\n    B --> C[Browser Tool]\n    B --> D[Page Tool]\n    B --> E[Storage Tool]\n    B --> F[Trace Tool]\n    C --> G[Playwright Core API]\n    D --> G\n    E --> G\n    F --> G\n```\n\n### Tool Categories\n\n| Category | Tools |\n|----------|-------|\n| Browser | launch, connect, close, context |\n| Navigation | goto, back, forward, reload |\n| Interaction | click, fill, select, hover, drag, type, press |\n| Snapshot | snapshot, screenshot, pdf |\n| Storage | cookies, localStorage, sessionStorage |\n| Network | route, unroute, route-list |\n\n## Package Structure\n\n| Package | Purpose |\n|---------|---------|\n| `playwright` | Main package with all browser support |\n| `@playwright/test` | Testing framework with reporters |\n| `playwright-core` | Core API without browser binaries |\n| `@playwright/browser-chromium` | Chromium browser support |\n| `@playwright/browser-firefox` | Firefox browser support |\n| `@playwright/browser-webkit` | WebKit browser support |\n\n资料来源：[package.json](https://github.com/microsoft/playwright/blob/main/package.json), [packages/playwright-test/package.json](https://github.com/microsoft/playwright/blob/main/packages/playwright-test/package.json), [packages/playwright-webkit/package.json](https://github.com/microsoft/playwright/blob/main/packages/playwright-webkit/package.json)\n\n## Environment Variables\n\n| Variable | Purpose |\n|----------|---------|\n| `PLAYWRIGHT_CLI_SESSION` | Default session name for CLI |\n| `PLAYWRIGHT_HTML_OPEN` | Controls browser launch behavior in tests |\n| `PLAYWRIGHT_BROWSERS_PATH` | Custom browser installation directory |\n\n## Error Handling Patterns\n\n```bash\n# Try-catch in run-code\nplaywright-cli run-code \"async page => {\n  try {\n    await page.getByRole('button', { name: 'Submit' }).click({ timeout: 1000 });\n    return 'clicked';\n  } catch (e) {\n    return 'element not found';\n  }\n}\"\n```\n\n## Installation and Usage\n\n### CLI Installation\n\n```bash\n# Use via npx (no installation required)\nnpx --no-install playwright-cli --version\n\n# Or install globally\nnpm install -g playwright-cli\n```\n\n### Testing Commands\n\nFrom the root `package.json`:\n\n| Script | Purpose |\n|--------|---------|\n| `npm run test` | Run library tests |\n| `npm run ctest` | Chromium tests only |\n| `npm run ftest` | Firefox tests only |\n| `npm run wtest` | WebKit tests only |\n| `npm run biditest` | Bidi protocol tests |\n\n## Summary\n\nThe Playwright CLI, MCP Server, and Agent Integration system provides a layered approach to browser automation:\n\n1. **CLI Layer**: Human-friendly command interface for browser automation tasks\n2. **MCP Layer**: Programmatic interface for AI agents and automated systems\n3. **Tool Backend**: Coordination layer that manages browser factories and models\n4. **Dashboard/Trace Viewer**: Visualization tools for analyzing test results\n\nThese components work together to enable comprehensive browser testing and automation workflows, from simple interactive sessions to complex AI-driven testing scenarios.\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：microsoft/playwright\n\n摘要：发现 38 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：[Feature]: Fail tests on page errors。\n\n## 1. 安装坑 · 来源证据：[Feature]: Fail tests on page errors\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Fail tests on page errors\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_347cf8732e73437a9699e4d8bc55d958 | https://github.com/microsoft/playwright/issues/40880 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：[Feature]: Ubuntu 26.04 LTS support\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Ubuntu 26.04 LTS support\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_764e9005d6a94f41b4a8d9f52decca99 | https://github.com/microsoft/playwright/issues/40117 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：[Feature]: trace correlation hooks for external observability/replay systems\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: trace correlation hooks for external observability/replay systems\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3c11bc1bf38e448f82e5b70d9f909037 | https://github.com/microsoft/playwright/issues/40887 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 运行坑 · 来源证据：[Feature]: support signal in waitFor* APIs\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Feature]: support signal in waitFor* APIs\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_500f564d44534739b16e93ed0b6a86eb | https://github.com/microsoft/playwright/issues/40578 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 5. 维护坑 · 来源证据：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_16f48d22960444cfa514e3e08d959d45 | https://github.com/microsoft/playwright/issues/20749 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 失败模式：security_permissions: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path...\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- 对用户的影响：Developers may expose sensitive permissions or credentials: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only. Context: Observed when using node, docker, playwright, linux\n- 防护动作：Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/microsoft/playwright/issues/40892\n- 证据：failure_mode_cluster:github_issue | fmev_32d5131674a6cea46a3dd9fea57edcee | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only, failure_mode_cluster:github_issue | fmev_5eb5ff7b9134ac254ca127feb48992d6 | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n\n## 7. 安全/权限坑 · 来源证据：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_641150bc817a45af974903e3c724aa41 | https://github.com/microsoft/playwright/issues/40681 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 安装坑 · 失败模式：installation: [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: In VS Code, tests are not displayed in the Testing section.. Context: Observed when using node, playwright, windows, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_429f2bbd1fa3334bca8aae5ee7df68b8 | https://github.com/microsoft/playwright/issues/40481 | [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n## 9. 安装坑 · 失败模式：installation: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1. Context: Observed when using node, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_09c75aac9731971717426ccfbe72651b | https://github.com/microsoft/playwright/issues/40904 | [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n## 10. 安装坑 · 失败模式：installation: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests nev...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite. Context: Observed when using node, playwright, windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_bd2b1ca9bdfc4104afb98768ab5f87d4 | https://github.com/microsoft/playwright/issues/40889 | [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n\n## 11. 安装坑 · 失败模式：installation: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect w...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials. Context: Observed when using node, playwright, windows, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_f50999f1a6066b929ea1a2971fefc95a | https://github.com/microsoft/playwright/issues/40768 | [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n\n## 12. 安装坑 · 失败模式：installation: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix s...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length. Context: Observed when using node, playwright, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_0f40df2fb212e08cdc02306a91f914c1 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length, failure_mode_cluster:github_issue | fmev_a8ab1c8959a949b8aee2604c9969fcc4 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n\n## 13. 安装坑 · 失败模式：installation: [Feature] Configure web servers per project\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Feature] Configure web servers per project\n- 对用户的影响：Developers may fail before the first successful local run: [Feature] Configure web servers per project\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature] Configure web servers per project. Context: Observed when using node, python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_4722870d2dbf6cec9abf1c0c8bcde960 | https://github.com/microsoft/playwright/issues/22496 | [Feature] Configure web servers per project\n\n## 14. 安装坑 · 失败模式：installation: [Regression]: install-deps --dry-run can no longer be used to generate install script\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Regression]: install-deps --dry-run can no longer be used to generate install script\n- 对用户的影响：Developers may fail before the first successful local run: [Regression]: install-deps --dry-run can no longer be used to generate install script\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Regression]: install-deps --dry-run can no longer be used to generate install script. Context: Observed when using node, docker, playwright, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_c8dd7be64694731b0c1d899e67c604ae | https://github.com/microsoft/playwright/issues/40885 | [Regression]: install-deps --dry-run can no longer be used to generate install script\n\n## 15. 安装坑 · 来源证据：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2c207034cca249f7b5c12ac82005f46f | https://github.com/microsoft/playwright/issues/13027 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 16. 安装坑 · 来源证据：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_1099381b0b074addae62105e5328e211 | https://github.com/microsoft/playwright/issues/40826 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 17. 安装坑 · 来源证据：[Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: In VS Code, tests are not displayed in the Testing section.\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_37a2f26303c64848818cc2f7865f7426 | https://github.com/microsoft/playwright/issues/40481 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 18. 安装坑 · 来源证据：[Feature] Configure web servers per project\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Configure web servers per project\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_528a2b31f563446684290d7dc62c0b9f | https://github.com/microsoft/playwright/issues/22496 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 19. 安装坑 · 来源证据：[Feature]: Configurable last-run file location for improved CI shard use\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Configurable last-run file location for improved CI shard use\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_0e5ae6ed54b0470dad14f33379cd267a | https://github.com/microsoft/playwright/issues/40805 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 20. 安装坑 · 来源证据：[Feature]: keyboard.pressSequence() for batched named key presses\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: keyboard.pressSequence() for batched named key presses\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_0ea0c22b305a43d48f3cd020cb99d222 | https://github.com/microsoft/playwright/issues/40740 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 21. 安装坑 · 来源证据：[Regression]: install-deps --dry-run can no longer be used to generate install script\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Regression]: install-deps --dry-run can no longer be used to generate install script\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f01d9cdd9bf0431b887c561d41e500d4 | https://github.com/microsoft/playwright/issues/40885 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 22. 配置坑 · 失败模式：configuration: [Bug]: newPage sometimes hangs indefinitely on Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Bug]: newPage sometimes hangs indefinitely on Firefox\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug]: newPage sometimes hangs indefinitely on Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: newPage sometimes hangs indefinitely on Firefox. Context: Observed when using windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_e47d5fda2471b4288d1427ec676e3942 | https://github.com/microsoft/playwright/issues/40882 | [Bug]: newPage sometimes hangs indefinitely on Firefox\n\n## 23. 配置坑 · 失败模式：configuration: [Feature]: Configurable last-run file location for improved CI shard use\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Configurable last-run file location for improved CI shard use\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Configurable last-run file location for improved CI shard use\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Configurable last-run file location for improved CI shard use. Context: Observed when using python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7cbc84a1a300e023acd52c21ad246467 | https://github.com/microsoft/playwright/issues/40805 | [Feature]: Configurable last-run file location for improved CI shard use\n\n## 24. 配置坑 · 失败模式：configuration: [Feature]: Fail tests on page errors\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Fail tests on page errors\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Fail tests on page errors\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Fail tests on page errors. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_face5b21f87e009618730d0ba96565c5 | https://github.com/microsoft/playwright/issues/40880 | [Feature]: Fail tests on page errors\n\n## 25. 配置坑 · 失败模式：configuration: [Feature]: Hierarchal Projects\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Hierarchal Projects\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Hierarchal Projects\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Hierarchal Projects. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_4c57d49ac0e7f3d85ed34fcff015d2c1 | https://github.com/microsoft/playwright/issues/40890 | [Feature]: Hierarchal Projects\n\n## 26. 配置坑 · 失败模式：configuration: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces. Context: Observed when using python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_8ef6929f8ee894946dadbc5a2e818841 | https://github.com/microsoft/playwright/issues/40681 | [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n## 27. 配置坑 · 来源证据：[Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_eefd168ed7194785a44744e0d489dc34 | https://github.com/microsoft/playwright/issues/31162 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 28. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:221981891 | https://github.com/microsoft/playwright | README/documentation is current enough for a first validation pass.\n\n## 29. 运行坑 · 失败模式：runtime: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [BUG] \"NS_BINDING_ABORTED\" error in Firefox. Context: Observed when using node, playwright, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_21f0858060c2b2d6c7f5f8f26ec42f3e | https://github.com/microsoft/playwright/issues/20749 | [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n## 30. 运行坑 · 失败模式：runtime: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox. Context: Observed when using node, docker, playwright, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_fb1936317ab9129c8d5d5dc060c212ee | https://github.com/microsoft/playwright/issues/13027 | [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n## 31. 运行坑 · 失败模式：runtime: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_18f4dc6435817d05134a997d1ad7134e | https://github.com/microsoft/playwright/issues/31162 | [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n## 32. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | last_activity_observed missing\n\n## 33. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:221981891 | https://github.com/microsoft/playwright | no_demo; severity=medium\n\n## 34. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:221981891 | https://github.com/microsoft/playwright | no_demo; severity=medium\n\n## 35. 安全/权限坑 · 来源证据：[Feature] support WebAuthn\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature] support WebAuthn\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_874db657219c4a63a90b030fed024459 | https://github.com/microsoft/playwright/issues/7276 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 36. 安全/权限坑 · 来源证据：[Feature]: Multi-Tab and Multi-Browser Recording Support\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Multi-Tab and Multi-Browser Recording Support\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dcba5ea273d149518992b7a0beaa9868 | https://github.com/microsoft/playwright/issues/40769 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 37. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | issue_or_pr_quality=unknown\n\n## 38. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | release_recency=unknown\n\n<!-- canonical_name: microsoft/playwright; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：microsoft/playwright\n\n摘要：发现 38 个潜在踩坑项，其中 7 个为 high/blocking；最高优先级：安装坑 - 来源证据：[Feature]: Fail tests on page errors。\n\n## 1. 安装坑 · 来源证据：[Feature]: Fail tests on page errors\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Fail tests on page errors\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_347cf8732e73437a9699e4d8bc55d958 | https://github.com/microsoft/playwright/issues/40880 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：[Feature]: Ubuntu 26.04 LTS support\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Ubuntu 26.04 LTS support\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_764e9005d6a94f41b4a8d9f52decca99 | https://github.com/microsoft/playwright/issues/40117 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：[Feature]: trace correlation hooks for external observability/replay systems\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: trace correlation hooks for external observability/replay systems\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3c11bc1bf38e448f82e5b70d9f909037 | https://github.com/microsoft/playwright/issues/40887 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 运行坑 · 来源证据：[Feature]: support signal in waitFor* APIs\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Feature]: support signal in waitFor* APIs\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_500f564d44534739b16e93ed0b6a86eb | https://github.com/microsoft/playwright/issues/40578 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 5. 维护坑 · 来源证据：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_16f48d22960444cfa514e3e08d959d45 | https://github.com/microsoft/playwright/issues/20749 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 6. 安全/权限坑 · 失败模式：security_permissions: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path...\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：Developers should check this security_permissions risk before relying on the project: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- 对用户的影响：Developers may expose sensitive permissions or credentials: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only. Context: Observed when using node, docker, playwright, linux\n- 防护动作：Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/microsoft/playwright/issues/40892\n- 证据：failure_mode_cluster:github_issue | fmev_32d5131674a6cea46a3dd9fea57edcee | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only, failure_mode_cluster:github_issue | fmev_5eb5ff7b9134ac254ca127feb48992d6 | https://github.com/microsoft/playwright/issues/40892 | [Bug]: MCP createUserDataDir writes profile data to PLAYWRIGHT_BROWSERS_PATH, fails when path is read-only\n\n## 7. 安全/权限坑 · 来源证据：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_641150bc817a45af974903e3c724aa41 | https://github.com/microsoft/playwright/issues/40681 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 8. 安装坑 · 失败模式：installation: [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: In VS Code, tests are not displayed in the Testing section.\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: In VS Code, tests are not displayed in the Testing section.. Context: Observed when using node, playwright, windows, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_429f2bbd1fa3334bca8aae5ee7df68b8 | https://github.com/microsoft/playwright/issues/40481 | [Bug]: In VS Code, tests are not displayed in the Testing section.\n\n## 9. 安装坑 · 失败模式：installation: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1. Context: Observed when using node, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_09c75aac9731971717426ccfbe72651b | https://github.com/microsoft/playwright/issues/40904 | [Bug]: Reporter ignores NO_COLOR — colors and cursor codes still emitted with NO_COLOR=1\n\n## 10. 安装坑 · 失败模式：installation: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests nev...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite. Context: Observed when using node, playwright, windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_bd2b1ca9bdfc4104afb98768ab5f87d4 | https://github.com/microsoft/playwright/issues/40889 | [Bug]: VSCode extension aborts run after a single slow (>10s) API test — subsequent tests never execute despite\n\n## 11. 安装坑 · 失败模式：installation: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect w...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials. Context: Observed when using node, playwright, windows, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_f50999f1a6066b929ea1a2971fefc95a | https://github.com/microsoft/playwright/issues/40768 | [Bug]: WebKit on Windows hangs when CONNECT proxy closes socket after 407 doesn't reconnect with credentials\n\n## 12. 安装坑 · 失败模式：installation: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix s...\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n- 对用户的影响：Developers may fail before the first successful local run: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length. Context: Observed when using node, playwright, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_0f40df2fb212e08cdc02306a91f914c1 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length, failure_mode_cluster:github_issue | fmev_a8ab1c8959a949b8aee2604c9969fcc4 | https://github.com/microsoft/playwright/issues/40878 | [Bug]: playwright-cli open fails with EINVAL when session name is long on macOS due to unix socket path length\n\n## 13. 安装坑 · 失败模式：installation: [Feature] Configure web servers per project\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Feature] Configure web servers per project\n- 对用户的影响：Developers may fail before the first successful local run: [Feature] Configure web servers per project\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature] Configure web servers per project. Context: Observed when using node, python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_4722870d2dbf6cec9abf1c0c8bcde960 | https://github.com/microsoft/playwright/issues/22496 | [Feature] Configure web servers per project\n\n## 14. 安装坑 · 失败模式：installation: [Regression]: install-deps --dry-run can no longer be used to generate install script\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: [Regression]: install-deps --dry-run can no longer be used to generate install script\n- 对用户的影响：Developers may fail before the first successful local run: [Regression]: install-deps --dry-run can no longer be used to generate install script\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Regression]: install-deps --dry-run can no longer be used to generate install script. Context: Observed when using node, docker, playwright, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_c8dd7be64694731b0c1d899e67c604ae | https://github.com/microsoft/playwright/issues/40885 | [Regression]: install-deps --dry-run can no longer be used to generate install script\n\n## 15. 安装坑 · 来源证据：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2c207034cca249f7b5c12ac82005f46f | https://github.com/microsoft/playwright/issues/13027 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 16. 安装坑 · 来源证据：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Compound ANSI SGR codes lose styling in HTML reporter and trace viewer\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_1099381b0b074addae62105e5328e211 | https://github.com/microsoft/playwright/issues/40826 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 17. 安装坑 · 来源证据：[Bug]: In VS Code, tests are not displayed in the Testing section.\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: In VS Code, tests are not displayed in the Testing section.\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_37a2f26303c64848818cc2f7865f7426 | https://github.com/microsoft/playwright/issues/40481 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 18. 安装坑 · 来源证据：[Feature] Configure web servers per project\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Configure web servers per project\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_528a2b31f563446684290d7dc62c0b9f | https://github.com/microsoft/playwright/issues/22496 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 19. 安装坑 · 来源证据：[Feature]: Configurable last-run file location for improved CI shard use\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: Configurable last-run file location for improved CI shard use\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_0e5ae6ed54b0470dad14f33379cd267a | https://github.com/microsoft/playwright/issues/40805 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 20. 安装坑 · 来源证据：[Feature]: keyboard.pressSequence() for batched named key presses\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature]: keyboard.pressSequence() for batched named key presses\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_0ea0c22b305a43d48f3cd020cb99d222 | https://github.com/microsoft/playwright/issues/40740 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 21. 安装坑 · 来源证据：[Regression]: install-deps --dry-run can no longer be used to generate install script\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Regression]: install-deps --dry-run can no longer be used to generate install script\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f01d9cdd9bf0431b887c561d41e500d4 | https://github.com/microsoft/playwright/issues/40885 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 22. 配置坑 · 失败模式：configuration: [Bug]: newPage sometimes hangs indefinitely on Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Bug]: newPage sometimes hangs indefinitely on Firefox\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Bug]: newPage sometimes hangs indefinitely on Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: newPage sometimes hangs indefinitely on Firefox. Context: Observed when using windows\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_e47d5fda2471b4288d1427ec676e3942 | https://github.com/microsoft/playwright/issues/40882 | [Bug]: newPage sometimes hangs indefinitely on Firefox\n\n## 23. 配置坑 · 失败模式：configuration: [Feature]: Configurable last-run file location for improved CI shard use\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Configurable last-run file location for improved CI shard use\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Configurable last-run file location for improved CI shard use\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Configurable last-run file location for improved CI shard use. Context: Observed when using python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_7cbc84a1a300e023acd52c21ad246467 | https://github.com/microsoft/playwright/issues/40805 | [Feature]: Configurable last-run file location for improved CI shard use\n\n## 24. 配置坑 · 失败模式：configuration: [Feature]: Fail tests on page errors\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Fail tests on page errors\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Fail tests on page errors\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Fail tests on page errors. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_face5b21f87e009618730d0ba96565c5 | https://github.com/microsoft/playwright/issues/40880 | [Feature]: Fail tests on page errors\n\n## 25. 配置坑 · 失败模式：configuration: [Feature]: Hierarchal Projects\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Hierarchal Projects\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Hierarchal Projects\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Hierarchal Projects. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_4c57d49ac0e7f3d85ed34fcff015d2c1 | https://github.com/microsoft/playwright/issues/40890 | [Feature]: Hierarchal Projects\n\n## 26. 配置坑 · 失败模式：configuration: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this configuration risk before relying on the project: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces. Context: Observed when using python, playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_8ef6929f8ee894946dadbc5a2e818841 | https://github.com/microsoft/playwright/issues/40681 | [Feature]: Trace viewer: Add timeout-risk highlighting for actions in Playwright traces\n\n## 27. 配置坑 · 来源证据：[Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_eefd168ed7194785a44744e0d489dc34 | https://github.com/microsoft/playwright/issues/31162 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 28. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:221981891 | https://github.com/microsoft/playwright | README/documentation is current enough for a first validation pass.\n\n## 29. 运行坑 · 失败模式：runtime: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [BUG] \"NS_BINDING_ABORTED\" error in Firefox. Context: Observed when using node, playwright, linux\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_21f0858060c2b2d6c7f5f8f26ec42f3e | https://github.com/microsoft/playwright/issues/20749 | [BUG] \"NS_BINDING_ABORTED\" error in Firefox\n\n## 30. 运行坑 · 失败模式：runtime: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox. Context: Observed when using node, docker, playwright, macos\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_fb1936317ab9129c8d5d5dc060c212ee | https://github.com/microsoft/playwright/issues/13027 | [BUG] page.goto: NS_ERROR_NET_TIMEOUT in Firefox\n\n## 31. 运行坑 · 失败模式：runtime: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this runtime risk before relying on the project: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 对用户的影响：Developers may hit a documented source-backed failure mode: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker. Context: Observed when using playwright\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_issue | fmev_18f4dc6435817d05134a997d1ad7134e | https://github.com/microsoft/playwright/issues/31162 | [Bug]: Unable to Listen to Download Event While Using window.showSaveFilePicker\n\n## 32. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | last_activity_observed missing\n\n## 33. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:221981891 | https://github.com/microsoft/playwright | no_demo; severity=medium\n\n## 34. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:221981891 | https://github.com/microsoft/playwright | no_demo; severity=medium\n\n## 35. 安全/权限坑 · 来源证据：[Feature] support WebAuthn\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature] support WebAuthn\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_874db657219c4a63a90b030fed024459 | https://github.com/microsoft/playwright/issues/7276 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 36. 安全/权限坑 · 来源证据：[Feature]: Multi-Tab and Multi-Browser Recording Support\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature]: Multi-Tab and Multi-Browser Recording Support\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_dcba5ea273d149518992b7a0beaa9868 | https://github.com/microsoft/playwright/issues/40769 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 37. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | issue_or_pr_quality=unknown\n\n## 38. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:221981891 | https://github.com/microsoft/playwright | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# playwright - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for microsoft/playwright.\n\nProject:\n- Name: playwright\n- Repository: https://github.com/microsoft/playwright\n- Summary: Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.\n- Host target: local_cli\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. page-1: Playwright Introduction and Project Overview. Produce one small intermediate artifact and wait for confirmation.\n2. page-2: Package Ecosystem and Monorepo Structure. Produce one small intermediate artifact and wait for confirmation.\n3. page-3: Client-Server Communication Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. page-4: Browser Launch and Process Management. Produce one small intermediate artifact and wait for confirmation.\n5. page-5: Test Runner and Execution Engine. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/microsoft/playwright\n- https://github.com/microsoft/playwright#readme\n- .claude/skills/playwright-dev/SKILL.md\n- .claude/skills/playwright-devops/SKILL.md\n- packages/playwright-core/src/tools/cli-client/skill/SKILL.md\n- packages/playwright-core/src/tools/trace/SKILL.md\n- README.md\n- packages/playwright/package.json\n- packages/playwright-core/package.json\n- package.json\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：microsoft/playwright\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm i -g @playwright/cli@latest\n```\n\n来源：https://github.com/microsoft/playwright#readme\n\n## 来源\n\n- repo: https://github.com/microsoft/playwright\n- docs: https://github.com/microsoft/playwright#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_92cb4f86971644e48c9c64d546891493"
}
