Skip to content

[Feature]: Verify closure of an extension-owned tab after reconnect #44380

Backlog

Description

Use case

An unattended local client needs to determine whether a tab it previously owned was physically closed if the Playwright Extension connection ends during cleanup. The client must preserve unrelated tabs and cannot assume that a missing page in a new Playwright session means it was closed.

Reproduction

Verified on Windows with Playwright Extension 0.6.0 and both @playwright/mcp 0.0.83 and 0.0.86, using disposable Chromium profiles and only loopback pages.

  1. Put a control tab in a disposable profile and connect Playwright MCP with the extension token. Navigate the new token-created tab to a unique loopback URL. Record the original native tab ID using independent Chrome tab inventory as the test witness.
  2. In case A, disconnect the Playwright browser connection while that tab is still open. In case B, close the tab, verify that the original ID is absent using the same witness, and disconnect. The harness used the public Playwright Browser.close() on the extension-backed connection to cause the disconnect. In A the old Page emitted close and isClosed() became true while the native tab remained.
  3. Start a fresh MCP connection with the same profile, client name, and token, then call browser_tabs with { "action": "list" }.
  4. In both cases the new session sees one new blank tab and cannot see the original page. The independent inventory still sees the original ID in A and confirms it is absent in B. The control tab survives both.

The documented interactive group picker works in the open case: connect without auto-approval, select the old group, and click Allow. On 0.0.83 the reattached page was verified against the exact original native tab ID. This requires user interaction and does not provide a machine-readable result for both cases.

Requested capability

Could the extension offer a profile-scoped, read-only status lookup for an opaque handle issued while the tab was owned, or a durable browser-side acknowledgment for closing that exact handle? For a status lookup, distinguish open, closed, and unknown across transport reconnect. It should create no tabs and expose no unrelated tab information. Unknown handle, wrong profile, lost authorization, or ambiguous state should return unknown.

The two reconnect cases above are acceptance tests, along with wrong profile/handle and preservation of unrelated tabs. The request differs from #41874, which addresses establishing a connection again, and #41864, which concerns the new bootstrap tab.

Activity

  1. carabinshely commented on Nov 25, 2026

    @carabinshely
    Author

    Runnable three-case reproduction

    Save the script below as repro.cjs. Pass four absolute paths: the node_modules for @playwright/mcp@0.0.86, a Chromium executable that supports headless extensions, an unpacked copy of Playwright Extension 0.6.0, and a new output directory under a private temporary directory. Use a test shell with no Playwright MCP browser overrides. Example: node repro.cjs <node_modules> <chromium.exe> <unpacked-extension> <new-output-dir>. It generates its own token within each disposable profile and uses only loopback content.

    The three cases passed on Windows. The control tab survived each case and all disposable processes exited. In the disconnect-open case the old Page reports closed but the original native ID remains; the new token session has a different tab. Disconnect-after-close exposes the same new-session view but the original ID is absent. The extension worker is only the independent observer for this test.

    For a regression test of a fix, assert browser-side status of the same scoped handle: ordinary close → closed, disconnect while open → open, disconnect after close → closed, wrong handle or profile → unknown. Querying the status should not create another tab. No enumeration of other tabs or new browser permissions are needed.

    repro.cjs
    const assert = require('node:assert/strict');
    const fs = require('node:fs');
    const path = require('node:path');
    const cp = require('node:child_process');
    const { EventEmitter } = require('node:events');
    const { randomUUID } = require('node:crypto');
    require('node:dns').setDefaultResultOrder('ipv4first');
    
    const args = process.argv.slice(2);
    assert.equal(args.length, 4, 'Expected: node_modules chromium.exe unpacked-extension new-private-directory');
    assert(args.every(arg => path.isAbsolute(arg)));
    const [modules, executablePath, extension, output] = args.map(arg => path.resolve(arg));
    assert.equal(JSON.parse(fs.readFileSync(path.join(extension, 'manifest.json'), 'utf8')).version, '0.6.0');
    const { chromium } = require(path.join(modules, 'playwright'));
    const { createConnection } = require(path.join(modules, '@playwright/mcp'));
    const { Client } = require(path.join(modules, 'playwright-core/lib/utilsBundle.js'));
    const sdkVersion = require(path.join(modules, '@playwright/mcp/package.json')).version;
    assert.equal(sdkVersion, '0.0.86');
    fs.mkdirSync(output); // Refuse existing paths. Use a new child of a private directory.
    
    const extensionOrigin = 'chrome-extension://mmlmfjhmonkocbjadbfplnigmagldckm';
    const originalSpawn = cp.spawn;
    process.env.PLAYWRIGHT_MCP_PROFILE_DIR_NAME = 'Default';
    
    function pair() {
      const a = { async start() {}, async send(m) { await b.onmessage?.(m); }, async close() { a.onclose?.(); b.onclose?.(); } };
      const b = { async start() {}, async send(m) { await a.onmessage?.(m); }, async close() { b.onclose?.(); a.onclose?.(); } };
      return [a, b];
    }
    
    async function scenario(mode, address) {
      const dir = path.join(output, mode);
      fs.mkdirSync(dir);
      const profile = path.join(dir, 'profile');
      const context = await chromium.launchPersistentContext(profile, {
        executablePath, channel: 'chromium', headless: true, chromiumSandbox: true, timeout: 20000,
        ignoreDefaultArgs: ['--disable-extensions'],
        args: ['--disable-extensions-except=' + extension, '--load-extension=' + extension,
          '--disable-background-networking', '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE localhost, EXCLUDE 127.0.0.1'],
      });
      let client, server;
      try {
        const worker = context.serviceWorkers().find(w => w.url().startsWith(extensionOrigin + '/'))
          ?? await context.waitForEvent('serviceworker', { predicate: w => w.url().startsWith(extensionOrigin + '/'), timeout: 10000 });
        const tabs = () => worker.evaluate(() => chrome.tabs.query({}));
        const control = context.pages()[0];
        const controlUrl = address + '/control';
        await control.goto(controlUrl);
        const manage = await context.newPage();
        await manage.goto(extensionOrigin + '/manage.html');
        await manage.waitForFunction(() => localStorage.getItem('auth-token')?.length >= 16, {}, { timeout: 8000 });
        const token = await manage.evaluate(() => localStorage.getItem('auth-token'));
        await manage.close();
        process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN = token;
        const controlId = (await tabs()).find(tab => tab.url === controlUrl)?.id;
        assert(Number.isSafeInteger(controlId));
    
        const hook = path.join(dir, 'capture.cjs');
        fs.writeFileSync(hook, 'exports.default = ({ page }) => { globalThis.testPage ??= page; };');
        const name = 'close-proof-' + randomUUID();
    
        async function connect() {
          delete globalThis.testPage;
          server = await createConnection({
            extension: true, browser: { userDataDir: profile, launchOptions: { executablePath }, initPage: [hook] },
            snapshot: { mode: 'none' }, codegen: 'none', saveSession: false, outputDir: dir,
          });
          const [a, b] = pair();
          await server.connect(b);
          client = new Client({ name, version: '1' });
          await client.connect(a);
          let connector;
          // Route only the SDK's generated connector URL into the disposable process.
          cp.spawn = (exe, argv) => {
            assert.equal(exe, executablePath);
            assert(argv.includes('--user-data-dir=' + profile));
            const url = new URL(argv.at(-1));
            assert.equal(url.protocol + '//' + url.hostname + url.pathname, extensionOrigin + '/connect.html');
            assert.equal(url.searchParams.get('token') === token, true);
            assert.equal(new URL(url.searchParams.get('mcpRelayUrl')).hostname, '127.0.0.1');
            connector = context.newPage().then(p => p.goto(url.href)).then(() => true, () => false);
            return new EventEmitter();
          };
          let result;
          try {
            result = await client.callTool({ name: 'browser_tabs', arguments: { action: 'list' } }, undefined, { timeout: 20000 });
          } finally {
            cp.spawn = originalSpawn;
            await connector;
          }
          assert.equal(Boolean(result.isError), false, 'browser_tabs list must succeed');
          assert(globalThis.testPage);
          return globalThis.testPage;
        }
    
        const page = await connect();
        const marker = address + '/owned#' + randomUUID();
        await page.goto(marker);
        const matches = (await tabs()).filter(tab => tab.url === marker);
        assert.equal(matches.length, 1);
        const originalId = matches[0].id;
        assert(Number.isSafeInteger(originalId) && originalId !== controlId);
    
        if (mode !== 'disconnect-open') await page.close({ runBeforeUnload: false });
        if (mode !== 'normal-close') {
          await page.context().browser().close();
          assert.equal(page.isClosed(), true);
          await client.close();
          await server.close();
          const existing = new Set((await tabs()).map(tab => tab.id));
          const replacement = await connect();
          assert.deepEqual(replacement.context().pages().map(p => p.url()), ['about:blank']);
          const created = (await tabs()).filter(tab => !existing.has(tab.id));
          assert.equal(created.length, 1);
          assert(created[0].id !== originalId && created[0].url === 'about:blank');
          await replacement.close({ runBeforeUnload: false });
          assert(!(await tabs()).some(tab => tab.id === created[0].id));
        }
        const inventory = await tabs();
        const original = inventory.find(tab => tab.id === originalId);
        assert.equal(Boolean(original), mode === 'disconnect-open');
        if (original) assert.equal(original.url, marker);
        assert(inventory.some(tab => tab.id === controlId && tab.url === controlUrl));
      } finally {
        delete process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;
        try { await client?.close(); } finally {
          try { await server?.close(); } finally { await context.close(); }
        }
      }
      console.log(mode + ': observed expected native state; original control preserved; fixture closed');
    }
    
    async function main() {
      const fixture = require('node:http').createServer((_, res) => {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<title>Isolated extension reproduction</title>');
      });
      await new Promise((resolve, reject) => { fixture.once('error', reject); fixture.listen(0, '127.0.0.1', resolve); });
      try {
        for (const mode of ['normal-close', 'disconnect-open', 'disconnect-after-close']) {
          await scenario(mode, 'http://127.0.0.1:' + fixture.address().port);
        }
      } finally {
        await new Promise(resolve => fixture.close(resolve));
      }
    }
    
    main().catch(error => {
      // Avoid printing connector URLs or credentials from an underlying tool error.
      console.error('Fixture failed: ' + error.name + '\n' + (error.stack?.split('\n').slice(1, 4).join('\n') ?? ''));
      process.exitCode = 1;
    });
  2. microsoft-playwright-automation commented on Nov 25, 2026

    @microsoft-playwright-automation
  3. microsoft-playwright-automation commented on Nov 25, 2026

    @microsoft-playwright-automation
    Contributor

    Hi, I'm the Playwright bot. I checked the extension's ownership rules and tested both reconnect states.

    The requested status lookup is not available today. On current main, a fresh connection cannot distinguish a previously owned tab that is still open from one that was closed. This matches the documented disconnect behavior: ownership ends on disconnect, and a token connection starts with a new blank tab. A missing page, or the old Page.isClosed(), is not proof of physical tab closure.

    This needs a new cross-connection API, not a change to reconnect or tab listing. The current protocol has neither a retained, authorized handle nor a status-query connection that avoids opening a tab. I have not proposed a patch because defining access after ownership ends, revocation and retained close records changes the extension's API and lifetime rules.

    Verification and existing coverage

    Tested on Windows with Playwright 1.66.0-next, commit b9cff8a68a090c27d29d856747265732468acff0, the source-built extension 0.6.0, and headless Chromium 159.0.8154.33.

    I extended the existing client leaves and its tabs stay open without the debugger test locally. It connects directly to the real extension protocol, using the same profile, token and client name on each connection. Native tab IDs from the extension worker serve only as an independent test witness.

    State before reconnect Native witness Fresh connection
    Disconnected while the original tab remained open Exact original ID still present One new blank tab; original ID not announced; attach refused as not owned
    Original tab closed, then disconnected Exact original ID absent One new blank tab; original ID not announced; same attach refusal

    The unrelated control tab kept its original ID. Giving the open tab back to the client restored access to that exact ID. Thus, loss of ownership and physical closure produce the same refusal; that refusal cannot serve as a closure result.

    The extended test passed. The existing protocol tests for ordinary tab creation/removal and browser-wide command restrictions also passed. The existing full client-lifecycle test attempt timed out waiting for the connect page: its JavaScript browser launcher cannot be spawned directly on this Windows runner (EFTYPE). The direct-protocol tests bypass that test launcher, not the extension's ownership checks.

    I did not rerun published MCP 0.0.83/0.0.86, headed mode, or wrong-profile/handle status queries: no such status operation exists. Firefox and WebKit do not run this Chromium extension suite.

    Existing coverage already checks token connections leaving the old group for user selection in client-lifecycle.spec.ts. The implementation releases all ownership on disconnect and removes released tabs from the registry. It keeps no closed-handle history. The manage page's internal getStatus reports current sessions, not historical tab state.

    This is distinct from #41874 and #41864. No pull request linked to this request was found.

    Triaged on Windows by the Playwright bot - agent run

  4. dgozman commented on Nov 25, 2026

    @dgozman
    Collaborator

    I can't say that I understood the request fully. Are you looking for a way to close all tabs upon disconnect? Something like --close-tabs-on-disconnect? See also detach --close-tabs for the cli.

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

    agent-triage-done

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions