Skip to content

playwright-cli attach hangs forever: Tab.headerSnapshot awaits page.title() without a timeout on a half-initialised page #489

Closed

Description

@cyppe

Version

@playwright/cli 0.1.22 with playwright-core 1.64.1 (also seen with 0.1.21 / playwright-core 1.64.0-alpha). Chromium 154 on Linux. Code unchanged on microsoft/playwright main at b4695e3eb2.

Steps to reproduce

  1. Start Chromium with --remote-debugging-port=9222 and use it normally, with many tabs (here 28). In our case a hidden tab that had been reloaded ended up in this state; we have no deterministic way to create it from scratch.
  2. Run playwright-cli -s=s attach --cdp=http://127.0.0.1:9222.

Expected

Attach completes, listing the tabs. A tab that cannot report its title is listed without one.

Actual

attach never returns. The session daemon stays registered, and every later command (even run-code 'async page => 1') queues behind it and hangs too, until the session is detached.

Analysis

Minimal probe (touches no tab):

const { chromium } = require('playwright-core');
(async () => {
  const browser = await chromium.connectOverCDP('http://127.0.0.1:9222');
  for (const page of browser.contexts()[0].pages()) {
    const outcome = await Promise.race([page.title().then(() => 'ok'), new Promise(r => setTimeout(r, 3000, 'HANGS'))]);
    if (outcome !== 'ok') console.log(outcome, JSON.stringify(page.url()));   // -> HANGS ""
  }
  process.exit(0);
})();

Workaround we use

We bound the call: 3 s for the first wait, then 100 ms per later snapshot while the same pending title() is still unresolved, and leave the title empty. With it, attach takes 3.7 s instead of hanging, later commands take 0.3 s, and the tab is listed as - 6: [](). Unpatched, the same browser times out at 60 s every time.

Suggestion

Bound title() in headerSnapshot() (a small change; PR to follow in microsoft/playwright). Separately, the frame never leaving the "commit"/url "" state while the renderer is loaded may be a bug in frame tracking after connectOverCDP; we can collect a pw:protocol log for that tab if it helps.

Activity

  1. dgozman commented on Oct 26, 2026

    @dgozman
    Contributor

    cyppe Any chance you can dump the contents of chrome://discards and chrome://process-internals (all three tabs there) next time this happens? We really need to figure out what's the state of the page that prevents attach from completing, to figure out a long-term solution.

  2. github-actions commented on Oct 31, 2026

    @github-actions
  3. github-actions commented on Oct 31, 2026

    @github-actions

    Hi, I'm the Playwright bot. I tried to reproduce this on Linux.

    I could not recreate the half-initialized frame, on current main or with playwright-core 1.64.1. With 28 tabs, background reloads and frozen tabs, attachment and later commands completed. A coverage test for attachment after a background-tab reload is proposed; it does not fix or simulate the reported missing execution context.

    One relevant detail: page.title() evaluates in Playwright's utility world, not the default world used by bare CDP Runtime.evaluate. A successful default-world evaluation does not establish that the utility-world context was initialized. The timeout patch in microsoft/playwright#43620 was closed without merging, so I have not repeated it.

    Could you share a sanitized DEBUG=pw:protocol,pw:channel log starting before the failing attach, together with the chrome://discards and chrome://process-internals dumps requested above? The missing piece is a way to create, or inspect initialization of, the affected frame.

    What I ran

    All runs were on Linux. Each probe used 28 tabs and checked all titles after CDP connection, with a five-second bound on title collection. Variations were ordinary loaded tabs, a frozen background tab, reload while frozen, thawing that tab, and 20 reload/connection races.

    CLI/core Browser Mode Result
    Upstream 1.65.0-next, a6fb02f5aa494764a21a637f2db6ea1031461935 Chromium 158.0.8127.2 Headless and headed All title probes completed
    Same upstream commit Chrome 156.0.8078.47 Headed All title probes completed, both with the original Playwright sessions attached and after detaching them
    CLI 0.1.22, pinned core 1.64.0-alpha-1790635538000, upstream e8149b8257d32dcf8f72573ecc43e72439da7080 Chromium 155.0.8059.12 Headed All title probes completed
    CLI 0.1.22, core 1.64.1, upstream cfe490d941f992655948eee8fd4fd94e1c4234bf Chrome 156.0.8078.47 Headed All title probes completed

    For upstream Chrome, the pinned core, and core 1.64.1, I also disabled the original session's focus emulation and confirmed document.hidden === true on the background tab before testing. In the four non-race states, actual CLI attach, tab-list, and run-code 'async page => 1' all completed and returned the expected titles/result. No probe produced the reported empty-URL frame.

    The reporter's Chromium 154 and long-running browser profile were not available. These results do not establish that the bug is fixed.

    The existing attach via cdp test now includes the background reload and checks attachment metadata, a snapshot, and a later run-code result. cli-cdp.spec.ts and cli-endpoint.spec.ts passed across the Chrome, Chromium, Firefox, and WebKit projects: 42 passed, 14 skipped. CDP-only cases are skipped for Firefox and WebKit. Build and the full npm run flint check passed.

    Condensed scenario covered by the proposal

    Using the repository's cdpServer, cli, and server fixtures:

    const context = await cdpServer.start();
    const [page] = context.pages();
    await page.goto(server.HELLO_WORLD);
    const backgroundPage = await context.newPage();
    await backgroundPage.goto(server.PREFIX + '/title.html');
    await page.bringToFront();
    await backgroundPage.reload();
    
    const attached = await cli('attach', `--cdp=${cdpServer.endpoint}`);
    expect(attached.exitCode).toBe(0);
    expect(attached.output).toContain(`[Woof-Woof](${server.PREFIX}/title.html)`);
    const result = await cli('run-code', 'async page => 1');
    expect(result.output).toContain('### Result\n1');

    This passes today. It covers the background-reload setup, not the unknown trigger that leaves a frame without an execution context.

    Draft PR: microsoft/playwright#43816

    Triaged on Linux by the Playwright bot - agent run

  4. pavelfeldman commented on Oct 31, 2026

    @pavelfeldman
    Member

    Closing as not reproducible

  5. roman-vm commented on Nov 15, 2026

    @roman-vm

    Reproduced, deterministically, with a fresh profile and local pages only.

    Chrome 157.0.8103.52 on Windows 11 (--headless=new). It fails the same way on playwright-core 1.64.1, 1.65.1 and 1.66.0-alpha-2026-11-15, and with playwright-cli 0.1.22 and 0.1.24.

    Trigger. A CDP client sees a tab, and later that tab switches to a prerendered page. One Target.getTargets that then disconnects is enough. From then on, the tab's page target id and its main frame id differ:

    CDP         http://127.0.0.1:52251/next  targetId=A128AC29  main frame id=D338C73F  activationStart=5002   <-- ids differ
    Playwright  page.url()=""  page.title(): STILL PENDING after 10 s
    

    Control: the same steps with no early CDP client. The ids match and title() resolves:

    CDP         http://127.0.0.1:59200/next  targetId=D2856AA0  main frame id=D2856AA0  activationStart=4994
    Playwright  page.url()="http://127.0.0.1:59200/next"  page.title(): resolved "next"
    

    With the real CLI against that Chrome, attach prints the new session and then Timeout 30000ms exceeded.. After that, tab-list never returns.

    The repro triggers the prerender with speculation rules. My guess at the everyday path, which I have not verified: a browser with remote debugging on, where earlier attaches (an MCP server, earlier playwright-cli attach runs) have listed every tab, and the user later opens a page Chrome prerendered.

    Cause (crPage). _sessionForFrame() walks up from a frame until it finds a session keyed by that frame's id. That assumes the main frame's id equals the target id. Here it doesn't, so the walk runs out of parents and throws Frame has been detached.. Both _onFrameNavigated and _onExecutionContextCreated call it, through _eventBelongsToStaleFrame(). The result:

    • the first navigation is never committed, so page.url() stays "";
    • no execution context is registered, so title() waits for the utility world forever;
    • in 1.64.1, Tab.headerSnapshot() awaits that title() with no timeout, so every CLI command hangs.

    As a probe, not a proposed fix: when _sessionForFrame runs out of parents, return this._mainFrameSession. With that change the repro passes: page.url() is correct and title() resolves. Reverting it brings the hang back.

    Field data. This comes from my own Chrome 157.0.8103.52 on Windows 11, where I first hit the hang. The tab's URL and title are left out.

    • 1 of 28 tabs hung. In two separate attaches, it was the only tab whose target id differed from its main frame id.
    • Its protocol log matches the repro. Runtime.executionContextCreated arrives for the main frame id, for both the default and the utility world, and the title call on that frame never gets an answer.
    • chrome://discards row for that tab: Visibility hidden, Loading State loaded, Lifecycle State hidden, Discardable no, Freezable yes, Discard Count 0.
    • chrome://process-internals: Site Per Process, 58 renderer processes, limit 82, not over the limit.
    pw-489-repro.mjs
    // Repro for microsoft/playwright-cli#489 — page.title() never settles on an attached Chrome tab.
    //
    // Needs Node 22+ and Google Chrome (no Playwright browser download).
    //   npm i playwright-core
    //   node pw-489-repro.mjs              # repro
    //   node pw-489-repro.mjs --no-list    # control: same steps without the early CDP client
    //   node pw-489-repro.mjs --hold       # keep Chrome running to try `playwright-cli attach --cdp=...`
    // Env: CHROME=<chrome binary>, PORT=<debugging port, default 9350>
    //
    // Steps, with a fresh profile and local pages only:
    //   1. Chrome opens /start itself (command line). /start prerenders /next (speculation rules)
    //      and navigates to it after 5 s, so the tab switches to the prerendered page.
    //   2. Before that switch, a CDP client calls Target.getTargets and disconnects.
    //   3. After the switch, Playwright attaches with connectOverCDP and calls page.title().
    import { spawn } from 'node:child_process';
    import http from 'node:http';
    import fs from 'node:fs';
    import os from 'node:os';
    import path from 'node:path';
    import { createRequire } from 'node:module';
    
    const require = createRequire(path.join(process.cwd(), 'x.js'));
    const { chromium } = require('playwright-core');
    const pwVersion = require('playwright-core/package.json').version;
    const CHROME =
      process.env.CHROME ??
      { win32: 'C:/Program Files/Google/Chrome/Application/chrome.exe', darwin: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' }[
        process.platform
      ] ??
      'google-chrome';
    const PORT = Number(process.env.PORT ?? 9350);
    const list = !process.argv.includes('--no-list');
    const hold = process.argv.includes('--hold');
    const wait = (ms, v) => new Promise((r) => setTimeout(r, ms, v));
    const html = (title, body = '') => `<!doctype html><title>${title}</title><body>${title}${body}`;
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'content-type': 'text/html' });
      res.end(
        req.url === '/start'
          ? html(
              'start',
              `<script type="speculationrules">{"prerender":[{"source":"list","urls":["/next"]}]}</script>
               <script>setTimeout(() => { location.href = '/next'; }, 5000);</script>`,
            )
          : html('next'),
      );
    });
    
    function cdp(url) {
      const ws = new WebSocket(url);
      let id = 0;
      const pending = new Map();
      ws.onmessage = (e) => {
        const m = JSON.parse(e.data);
        const p = pending.get(m.id);
        if (!p) return;
        pending.delete(m.id);
        m.error ? p.reject(new Error(m.error.message)) : p.resolve(m.result);
      };
      return {
        opened: new Promise((r) => (ws.onopen = r)),
        close: () => ws.close(),
        send(method, params = {}, sessionId) {
          ws.send(JSON.stringify({ id: ++id, method, params, sessionId }));
          return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
        },
      };
    }
    const endpoint = () => fetch(`http://127.0.0.1:${PORT}/json/version`).then((r) => r.json(), () => undefined);
    
    if (await endpoint()) throw new Error(`port ${PORT} already serves a browser; set PORT=`);
    await new Promise((r) => server.listen(0, '127.0.0.1', r));
    const origin = `http://127.0.0.1:${server.address().port}`;
    const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'pw-489-'));
    const chrome = spawn(
      CHROME,
      [`--remote-debugging-port=${PORT}`, `--user-data-dir=${profile}`, '--no-first-run', '--no-default-browser-check', '--headless=new', `${origin}/start`],
      { stdio: 'ignore' },
    );
    const stop = () => (chrome.kill(), server.close());
    try {
      let version;
      for (let i = 0; i < 100 && !version; i++) version = (await wait(100)) ?? (await endpoint());
      console.log(`${version.Browser}  playwright-core ${pwVersion}  early client: ${list ? 'Target.getTargets' : 'none'}`);
    
      if (list) {
        const early = cdp(version.webSocketDebuggerUrl);
        await early.opened;
        await early.send('Target.getTargets');
        early.close();
      }
      await wait(9000); // the tab switches to the prerendered /next ~5 s after /start loads
    
      const probe = cdp(version.webSocketDebuggerUrl);
      await probe.opened;
      const { targetInfos } = await probe.send('Target.getTargets');
      for (const t of targetInfos.filter((t) => t.type === 'page')) {
        const { sessionId } = await probe.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
        const { frameTree } = await probe.send('Page.getFrameTree', {}, sessionId);
        const { result } = await probe.send(
          'Runtime.evaluate',
          { expression: 'performance.getEntriesByType("navigation")[0].activationStart', returnByValue: true },
          sessionId,
        );
        await probe.send('Target.detachFromTarget', { sessionId });
        console.log(
          `CDP         ${t.url}  targetId=${t.targetId.slice(0, 8)}  main frame id=${frameTree.frame.id.slice(0, 8)}` +
            `  activationStart=${Math.round(result.value)}${t.targetId === frameTree.frame.id ? '' : '   <-- ids differ'}`,
        );
      }
      probe.close();
    
      if (hold) {
        console.log(`\nChrome left running. Try: playwright-cli attach --cdp=http://127.0.0.1:${PORT}   (Ctrl+C here to stop)`);
        process.on('SIGINT', () => (stop(), process.exit(0)));
        await new Promise(() => {});
      }
    
      const browser = await chromium.connectOverCDP(`http://127.0.0.1:${PORT}`);
      for (const p of browser.contexts().flatMap((c) => c.pages())) {
        const title = await Promise.race([
          p.title().then((t) => `resolved ${JSON.stringify(t)}`, (e) => `rejected: ${e.message}`),
          wait(10_000, 'STILL PENDING after 10 s'),
        ]);
        console.log(`Playwright  page.url()=${JSON.stringify(p.url())}  page.title(): ${title}`);
      }
    } finally {
      if (!hold) stop();
      setTimeout(() => process.exit(0), 300);
    }

    npm i playwright-core && node pw-489-repro.mjs. Use --no-list for the control run, and --hold to keep Chrome running so you can try playwright-cli attach --cdp=http://127.0.0.1:9350.

    Since this now reproduces, could the issue be reopened?

  6. cyppe commented on Nov 21, 2026

    @cyppe
    Author

    This matches what we see. Environment: Linux (Arch), Chromium 155.0.8059.84, playwright-core 1.65.0, @playwright/cli 0.1.23, attaching to a long-running headed browser.

    The symptom is the same: one tab sits half-initialised (main frame url "", load state commit only), Tab.headerSnapshot() waits on page.title() forever, and attach and every later command in that session hang. In 1.65.0 that page.title() call still has no deadline. We work around it locally by bounding it with a short timeout, and the hang has not come back since.

    Since there is now a deterministic reproduction above, could this be reopened?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions