xtekky/gpt4free · error · RuntimeError

Failed to create new tab target on port {self.port}

Error message

Failed to create new tab target on port {self.port}

What it means

Raised by the async CDPSession in g4f/requests/cdp.py after it repeatedly (with 0.5s backoff) tried PUT http://host:port/json/new to open a new tab target and never got a response containing a webSocketDebuggerUrl. Without a target the session cannot open its WebSocket, so it fails fast instead of connecting blind.

Source

Thrown at g4f/requests/cdp.py:349

        # Create a new tab target
        ws_url = None
        for _ in range(10):
            try:
                req = urllib.request.Request(
                    f"http://{self.host}:{self.port}/json/new", method="PUT"
                )
                with urllib.request.urlopen(req, timeout=2) as response:
                    target = json.loads(response.read().decode("utf-8"))
                    ws_url = target.get("webSocketDebuggerUrl")
                    self.target_id = target.get("id")
                    if ws_url:
                        break
            except Exception:
                await asyncio.sleep(0.5)

        if not ws_url:
            raise RuntimeError(f"Failed to create new tab target on port {self.port}")

        await self.connect(ws_url)

    async def connect(self, ws_url: str):
        """Connect to the target WebSocket debugger."""
        self.session = aiohttp.ClientSession()
        self.ws = await self.session.ws_connect(ws_url)
        self._closing = False

        # Start receiver loop
        self._receive_task = asyncio.create_task(self._receiver_loop())

        # Enable essential domains
        await self.call("Page.enable")
        await self.call("DOM.enable")
        await self.call("Runtime.enable")
        await self.call("Network.enable")
        await self.call("Emulation.setFocusEmulationEnabled", enabled=True)

View on GitHub (pinned to 973504e177)

Solutions

  1. Confirm the browser is alive on that port: curl http://HOST:PORT/json/version.
  2. Verify host/port passed to CDPSession match the actually running Chrome instance (or omit them to let g4f auto-discover).
  3. Restart the browser/Chrome process and retry session creation.
  4. When launching your own Chrome for CDP, include --remote-debugging-port and (Chrome 111+) --remote-allow-origins=*.
Defensive patterns

Strategy: validation

Validate before calling

import urllib.request, json

def cdp_alive(host: str, port: int) -> bool:
    try:
        with urllib.request.urlopen(f"http://{host}:{port}/json/version", timeout=2) as r:
            return r.status == 200
    except Exception:
        return False

Try / catch

try:
    session = CDPSession(port=port, host=host)
    await session.start()
except RuntimeError as e:
    if "Failed to create new tab target" in str(e):
        # browser dead or wrong port: rediscover or restart, then retry once
        restart_shared_browser()
        session = CDPSession(); await session.start()
    else:
        raise

Prevention

When it happens

Trigger: The browser process died between port discovery and tab creation; the CDP endpoint is up but /json/new is blocked or returns an error (some hardened Chrome builds restrict /json endpoints via --remote-allow-origins or remote debugging flags); wrong host/port in CDPSession(port=..., host=...); too many open tabs exhausting targets.

Common situations: Pointing CDPSession at a port where a non-Chrome service listens; Chrome 111+ requiring --remote-allow-origins for some CDP HTTP endpoints; racing with another tool (or a prior crashed session) that closed the browser.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/ba3d6ada6810bb42. Report an issue: GitHub.