Coverage for src/ai_shell/local_chrome.py: 85%
420 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
1"""Local Chrome bridge for attaching chrome-devtools-mcp to a host browser.
3Probes the Windows host's Chrome debug port from inside the container and
4writes a minimal MCP config JSON that Claude Code can consume.
6Chrome's DevTools Protocol rejects HTTP requests whose ``Host`` header is
7not ``localhost`` or an IP address. Because the MCP server inside the
8container connects via ``host.docker.internal``, Chrome returns HTTP 500.
9To work around this, we start a small Node.js TCP proxy inside the
10container that forwards ``localhost:<port>`` to ``host.docker.internal:<port>``.
11The MCP server then connects to ``localhost:<port>`` and Chrome sees a
12``Host: localhost`` header.
13"""
15from __future__ import annotations
17import ipaddress
18import json
19import logging
20import os
21import platform
22import re
23import shutil
24import socket
25import subprocess
26import sys
27import tempfile
28import time
29from collections.abc import Callable, Mapping
30from dataclasses import dataclass
31from hashlib import sha1
32from http.client import HTTPConnection, HTTPException
33from pathlib import Path
34from typing import Any
36from rich.console import Console
38from ai_shell.defaults import unique_project_name
40logger = logging.getLogger(__name__)
41console = Console()
43CHROME_DEBUG_HOST = "host.docker.internal"
44CHROME_HOST_PROBE_TIMEOUT_SECONDS = 20.0
45CHROME_CONTAINER_PROBE_TIMEOUT_SECONDS = 10.0
46CHROME_PROBE_INTERVAL_SECONDS = 0.5
47CHROME_DEBUG_PORT_RANGE_START = 40000
48CHROME_DEBUG_PORT_RANGE_SIZE = 20000
50MCP_CONFIG_FILENAME = "chrome-mcp.json"
52# User-data-dir for ai-shell project-specific Chrome profiles (keeps them
53# separate from the user's normal browsing and from other repos).
54_CHROME_PROFILE_ROOT_DIR_NAME = "ai-shell"
55# Slug prefix for account-scoped profiles so they can never collide with a
56# project slug of the same name.
57_ACCOUNT_PROFILE_PREFIX = "account-"
59# Well-known Chrome install paths on Windows
60_CHROME_CANDIDATES = [
61 r"C:\Program Files\Google\Chrome\Application\chrome.exe",
62 r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
63]
64# macOS app bundles (system-wide, then per-user)
65_CHROME_MAC_CANDIDATES = [
66 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
67 "~/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
68 "/Applications/Chromium.app/Contents/MacOS/Chromium",
69]
70# Linux: whatever is on PATH, Chrome first, then Chromium builds
71_CHROME_LINUX_CANDIDATES = (
72 "google-chrome",
73 "google-chrome-stable",
74 "google-chrome-beta",
75 "chromium",
76 "chromium-browser",
77)
78LOOPBACK = "127.0.0.1"
80# Inline Node.js TCP proxy template -- forwards localhost:PORT to
81# host.docker.internal:PORT so Chrome sees Host: localhost.
82_NODE_PROXY_TEMPLATE = (
83 "const net=require('net');"
84 "net.createServer(c=>{{"
85 "const s=net.connect({port},'host.docker.internal',()=>{{c.pipe(s);s.pipe(c)}});"
86 "s.on('error',()=>c.destroy());c.on('error',()=>s.destroy())"
87 "}}).listen({port},'127.0.0.1')"
88)
91class LocalChromeUnavailable(Exception):
92 """Raised when the host Chrome debug port is not reachable."""
95def find_chrome() -> str | None:
96 """Locate the Chrome executable on the host.
98 Windows: well-known install paths, then the per-user install. macOS: the
99 app bundles. Linux: Chrome or Chromium on PATH. Returns the path as a
100 string or ``None`` if Chrome is not found.
101 """
102 system = platform.system()
103 if system == "Windows":
104 for candidate in _CHROME_CANDIDATES:
105 if Path(candidate).exists():
106 return candidate
107 # Fallback: per-user Chrome install
108 local_app = os.environ.get("LOCALAPPDATA", "")
109 if local_app:
110 user_chrome = Path(local_app) / "Google" / "Chrome" / "Application" / "chrome.exe"
111 if user_chrome.exists():
112 return str(user_chrome)
113 return None
114 if system == "Darwin":
115 for candidate in _CHROME_MAC_CANDIDATES:
116 path = Path(candidate).expanduser()
117 if path.exists():
118 return str(path)
119 return None
120 for name in _CHROME_LINUX_CANDIDATES:
121 found = shutil.which(name)
122 if found:
123 return found
124 return None
127def chrome_bind_address(container_name: str) -> str:
128 """Address the container reaches the host at, where the DevTools port must answer.
130 Docker Desktop (Windows, macOS) forwards ``host.docker.internal`` to the
131 host's loopback, so ``127.0.0.1`` works there. On a Linux host (Docker or
132 podman) ``host.docker.internal`` resolves to a real host address, and a
133 loopback-only listener is unreachable from containers. A windowed Chrome
134 binds to loopback only (it ignores ``--remote-debugging-address``), so on
135 that address ai-shell runs :mod:`ai_shell.cdp_relay`, which forwards to
136 Chrome's loopback port and serves the host's own addresses only.
137 """
138 if platform.system() != "Linux":
139 return LOOPBACK
140 result = subprocess.run(
141 ["docker", "exec", container_name, "getent", "hosts", CHROME_DEBUG_HOST],
142 capture_output=True,
143 text=True,
144 )
145 if result.returncode == 0 and result.stdout.strip():
146 candidate = result.stdout.split()[0]
147 try:
148 ipaddress.ip_address(candidate)
149 except ValueError:
150 logger.debug("Unexpected %s resolution %r", CHROME_DEBUG_HOST, candidate)
151 else:
152 return candidate
153 logger.warning(
154 "%s does not resolve inside %s; only Chrome's loopback port exists, which Linux "
155 "containers cannot reach. Docker needs `host-gateway` support (20.10+), podman 4.1+.",
156 CHROME_DEBUG_HOST,
157 container_name,
158 )
159 return LOOPBACK
162def _project_slug(project_name: str, project_dir: str | Path | None = None) -> str:
163 """Return a stable slug for project-scoped Chrome state."""
164 if project_dir is not None:
165 try:
166 return unique_project_name(Path(project_dir), project_name)
167 except (TypeError, ValueError):
168 logger.debug("Falling back to project-name-only slug for %s", project_name)
169 slug = "".join(ch if ch.isalnum() or ch == "-" else "-" for ch in project_name.lower())
170 slug = "-".join(part for part in slug.split("-") if part)
171 return slug or "project"
174def _chrome_slug(
175 project_name: str,
176 project_dir: str | Path | None = None,
177 profile: str | None = None,
178) -> str:
179 """Slug that keys a Chrome instance: per account when *profile* is set, else per project.
181 Logged-in browser state follows a person, not a repo, so a selected Claude
182 account gets one Chrome (profile dir + debug port) shared by every project
183 that uses that account. Two accounts never share a window.
184 """
185 if profile:
186 slug = "".join(ch if ch.isalnum() or ch == "-" else "-" for ch in profile.lower())
187 slug = "-".join(part for part in slug.split("-") if part)
188 return _ACCOUNT_PROFILE_PREFIX + (slug or "default")
189 return _project_slug(project_name, project_dir)
192def _chrome_profile_dir(
193 project_name: str,
194 project_dir: str | Path | None = None,
195 profile: str | None = None,
196) -> str:
197 """Return the user-data-dir path for a project's (or account's) ai-shell Chrome."""
198 slug = _chrome_slug(project_name, project_dir, profile)
199 local_app = os.environ.get("LOCALAPPDATA", "")
200 if local_app:
201 return str(Path(local_app) / "Google" / "Chrome" / _CHROME_PROFILE_ROOT_DIR_NAME / slug)
202 return str(Path.home() / ".config" / "google-chrome" / _CHROME_PROFILE_ROOT_DIR_NAME / slug)
205def _project_debug_port(
206 project_name: str,
207 project_dir: str | Path | None = None,
208 profile: str | None = None,
209) -> int:
210 """Return a stable Chrome remote debugging port for the project or account."""
211 slug = _chrome_slug(project_name, project_dir, profile)
212 # nosemgrep: python.lang.security.insecure-hash-algorithms.insecure-hash-algorithm-sha1
213 digest = sha1(slug.encode("utf-8"), usedforsecurity=False).hexdigest()
214 return CHROME_DEBUG_PORT_RANGE_START + (int(digest[:8], 16) % CHROME_DEBUG_PORT_RANGE_SIZE)
217#: How many ports after the preferred one to try. Windows reserves ports in
218#: blocks of 100, often several in a row, so a short walk is not enough.
219CHROME_DEBUG_PORT_ATTEMPTS = 2000
222def _port_bindable(port: int, host: str = LOOPBACK) -> bool:
223 """True when the host lets a process listen on *host*:*port*."""
224 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
225 try:
226 sock.bind((host, port))
227 except OSError:
228 return False
229 return True
232def _free_debug_port(preferred: int) -> int:
233 """*preferred*, or the first port after it (inside the range) that the host lets Chrome bind.
235 Windows reserves blocks of ports for Hyper-V, WSL and Docker Desktop
236 (``netsh int ipv4 show excludedportrange protocol=tcp``), and the blocks
237 move between boots. Chrome told to listen inside one opens its window
238 with no DevTools port and reports nothing, so the port is checked first.
239 """
240 offset = preferred - CHROME_DEBUG_PORT_RANGE_START
241 for step in range(CHROME_DEBUG_PORT_ATTEMPTS):
242 port = CHROME_DEBUG_PORT_RANGE_START + (offset + step) % CHROME_DEBUG_PORT_RANGE_SIZE
243 if _port_bindable(port):
244 if port != preferred:
245 logger.info("Port %d is reserved or in use; Chrome gets port %d", preferred, port)
246 return port
247 raise LocalChromeUnavailable(
248 f"No free port for Chrome's DevTools in the {CHROME_DEBUG_PORT_ATTEMPTS} ports from "
249 f"{preferred}. See `netsh int ipv4 show excludedportrange protocol=tcp` on Windows."
250 )
253def _chrome_command_lines() -> list[str]:
254 """Command lines of the Chrome processes running on the host (empty when unknown)."""
255 if platform.system() == "Windows":
256 script = (
257 "Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" | "
258 "ForEach-Object { $_.CommandLine }"
259 )
260 args = ["powershell", "-NoProfile", "-NonInteractive", "-Command", script]
261 else:
262 args = ["ps", "-axww", "-o", "command="]
263 try:
264 result = subprocess.run(args, capture_output=True, text=True, timeout=30) # noqa: S603
265 except (OSError, subprocess.TimeoutExpired):
266 logger.debug("Could not list Chrome processes", exc_info=True)
267 return []
268 return [line for line in result.stdout.splitlines() if line.strip()]
271def _holds_profile(command_line: str, profile_dir: str) -> bool:
272 """True when *command_line* names exactly *profile_dir* as its user-data-dir."""
273 flag = f"--user-data-dir={profile_dir}"
274 start = command_line.find(flag)
275 while start != -1:
276 end = start + len(flag)
277 if end == len(command_line) or command_line[end] in " \"'":
278 return True
279 start = command_line.find(flag, end)
280 return False
283def running_chrome_port(profile_dir: str | Path) -> int | None:
284 """The DevTools port of the Chrome that holds *profile_dir*.
286 Returns ``None`` when no Chrome holds the profile, and ``0`` when one
287 holds it without a DevTools port. The answer comes from the browser
288 process's own command line, so a port is never taken from a Chrome on
289 another profile (another account's window on a neighbouring port).
290 """
291 profile_dir = str(profile_dir)
292 for line in _chrome_command_lines():
293 # Renderer and helper processes repeat the user-data-dir; only the browser has no --type.
294 if "--type=" in line or not _holds_profile(line, profile_dir):
295 continue
296 match = re.search(r"--remote-debugging-port=(\d+)", line)
297 return int(match.group(1)) if match else 0
298 return None
301def _build_setup_instructions(
302 project_name: str,
303 profile_dir: str,
304 port: int,
305 bind_address: str = LOOPBACK,
306 proxy: str | None = None,
307) -> str:
308 """Return manual setup instructions for the project's Chrome profile."""
309 binary = "chrome.exe" if platform.system() == "Windows" else "google-chrome"
310 proxy_flag = f" \\\n --proxy-server={proxy}" if proxy else ""
311 return f"""\
312Chrome could not be found or launched automatically, and the debug port \
313is not reachable.
315To fix, launch Chrome manually with these flags:
317 {binary} --remote-debugging-port={port} \\
318 --remote-allow-origins=* \\
319 --user-data-dir="{profile_dir}"{proxy_flag}
321Then re-run this command for project '{project_name}'; ai-shell relays the port to \
322{bind_address} for the container when that is needed.
323See README.md "Attaching to host Chrome" for details."""
326def _proxy_args(proxy: str | None) -> list[str]:
327 """Chrome flags that send its traffic through *proxy* (empty when unset).
329 ``--proxy-server`` takes ``http://host:port``, ``socks5://host:port`` or
330 a bare ``host:port``. Chrome never proxies loopback, so the DevTools
331 bridge and the sign-in code flow are unaffected.
332 """
333 return [f"--proxy-server={proxy}"] if proxy else []
336def _spawn_detached(args: list[str], stderr: Any = subprocess.DEVNULL) -> subprocess.Popen[bytes]:
337 """Start *args* so the process outlives the CLI, on every platform."""
338 from ai_shell.standalone import detached_subprocess_env
340 env = detached_subprocess_env()
341 env_kwargs: dict[str, Any] = {"env": env} if env is not None else {}
342 if platform.system() == "Windows":
343 creation_flags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) | getattr(
344 subprocess, "DETACHED_PROCESS", 0
345 )
346 return subprocess.Popen( # noqa: S603
347 args,
348 stdout=subprocess.DEVNULL,
349 stderr=stderr,
350 stdin=subprocess.DEVNULL,
351 creationflags=creation_flags,
352 **env_kwargs,
353 )
354 return subprocess.Popen( # noqa: S603
355 args,
356 stdout=subprocess.DEVNULL,
357 stderr=stderr,
358 stdin=subprocess.DEVNULL,
359 start_new_session=True,
360 **env_kwargs,
361 )
364#: How long a freshly started Chrome gets to prove it stays up. A Chrome that
365#: cannot open a window (no display, a broken profile) exits well within it.
366CHROME_START_SECONDS = 2.0
369def no_display_reason(environ: Mapping[str, str] | None = None) -> str | None:
370 """Why Chrome cannot open a window from this terminal, or None when it can.
372 Only Linux needs a display variable; Windows and macOS always have a
373 desktop. A terminal reached over SSH or Session Manager has neither
374 ``DISPLAY`` nor ``WAYLAND_DISPLAY``, and Chrome then exits at once.
375 """
376 if platform.system() != "Linux":
377 return None
378 env = os.environ if environ is None else environ
379 if env.get("DISPLAY") or env.get("WAYLAND_DISPLAY"):
380 return None
381 return (
382 "This terminal has no desktop display (DISPLAY and WAYLAND_DISPLAY are unset), so "
383 "Chrome cannot open a window from it. Run this in a terminal on the desktop itself "
384 "(on a dev box, the DCV session), not over SSH or Session Manager."
385 )
388def _exited_early(process: subprocess.Popen[bytes], seconds: float) -> int | None:
389 """The exit code when *process* ends within *seconds*, else None (it is still up)."""
390 try:
391 return process.wait(timeout=seconds)
392 except subprocess.TimeoutExpired:
393 return None
396CHROME_CLOSE_TIMEOUT_SECONDS = 20.0
399def _wait_until_profile_free(profile_dir: str | Path, port: int, timeout: float) -> bool:
400 """Wait until no Chrome holds *profile_dir* (lock gone, debug port closed)."""
401 deadline = time.monotonic() + timeout
402 while time.monotonic() < deadline:
403 if not chrome_profile_in_use(profile_dir) and not probe_host_chrome_port(port):
404 return True
405 time.sleep(0.5)
406 return not chrome_profile_in_use(profile_dir) and not probe_host_chrome_port(port)
409def close_chrome_profile(profile_dir: str | Path, port: int) -> bool:
410 """Ask the Chrome that holds *profile_dir* to quit, and wait for it.
412 The window is ai-shell's own (its profile directory is under the
413 ``ai-shell`` folder), so closing it is in scope. The request is a
414 graceful one (SIGTERM on POSIX, ``taskkill`` without ``/F`` on Windows), so
415 Chrome flushes its cookies: the whole point is to keep the session for
416 the next launch. Returns ``True`` when the profile is free afterwards.
417 """
418 profile_dir = str(profile_dir)
419 if platform.system() == "Windows":
420 script = (
421 "Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" | "
422 f"Where-Object {{ $_.CommandLine -like '*--user-data-dir={profile_dir}*' }} | "
423 "ForEach-Object { taskkill /PID $_.ProcessId | Out-Null }"
424 )
425 args = ["powershell", "-NoProfile", "-NonInteractive", "-Command", script]
426 else:
427 args = ["pkill", "-TERM", "-f", "--", f"--user-data-dir={re.escape(profile_dir)}"]
428 logger.info("Closing Chrome on profile %s", profile_dir)
429 subprocess.run(args, capture_output=True, text=True) # noqa: S603
430 return _wait_until_profile_free(profile_dir, port, CHROME_CLOSE_TIMEOUT_SECONDS)
433def launch_chrome(
434 port: int,
435 *,
436 project_name: str,
437 project_dir: str | Path | None = None,
438 profile: str | None = None,
439 bind_address: str = LOOPBACK,
440 proxy: str | None = None,
441) -> bool:
442 """Launch Chrome on the host with the debug port enabled.
444 Returns ``True`` if Chrome was launched, ``False`` if Chrome could
445 not be found. The process is started detached so it outlives the CLI.
446 With *proxy*, Chrome sends its traffic through that proxy server (a VPN
447 container's HTTP proxy, for example).
448 """
449 chrome_path = find_chrome()
450 if chrome_path is None:
451 return False
453 profile_dir = _chrome_profile_dir(project_name, project_dir, profile)
454 # No --remote-debugging-address: a windowed Chrome ignores it and binds to
455 # loopback regardless; *bind_address* is served by the relay instead.
456 del bind_address
457 args = [
458 chrome_path,
459 f"--remote-debugging-port={port}",
460 "--remote-allow-origins=*",
461 f"--user-data-dir={profile_dir}",
462 # A fresh profile dir otherwise opens first-run / default-browser dialogs.
463 "--no-first-run",
464 "--no-default-browser-check",
465 *_proxy_args(proxy),
466 ]
467 logger.info("Launching Chrome: %s", " ".join(args))
468 _spawn_detached(args)
469 return True
472def chrome_profile_in_use(profile_dir: str | Path) -> bool:
473 """True when a Chrome process holds *profile_dir* open.
475 Chrome on Linux and macOS leaves a ``SingletonLock`` link in the profile
476 while it runs and removes it on exit. Windows keeps its ``lockfile`` on
477 disk after exit, so there the running processes are asked instead.
478 """
479 if platform.system() == "Windows":
480 return running_chrome_port(profile_dir) is not None
481 return Path(profile_dir, "SingletonLock").is_symlink()
484@dataclass
485class PlainChrome:
486 """A Chrome window ai-shell opened without the DevTools port."""
488 profile_dir: str
489 port: int
490 process: subprocess.Popen[bytes]
492 def close(self) -> bool:
493 """Quit the window gracefully and wait until the profile is free."""
494 if self.process.poll() is None:
495 if platform.system() == "Windows":
496 subprocess.run( # noqa: S603
497 ["taskkill", "/PID", str(self.process.pid)], capture_output=True, text=True
498 )
499 else:
500 self.process.terminate()
501 try:
502 self.process.wait(timeout=CHROME_CLOSE_TIMEOUT_SECONDS)
503 except subprocess.TimeoutExpired:
504 logger.warning("Chrome did not quit in time; forcing it")
505 self.process.kill()
506 return _wait_until_profile_free(self.profile_dir, self.port, CHROME_CLOSE_TIMEOUT_SECONDS)
509def launch_plain_chrome(
510 *,
511 project_name: str,
512 project_dir: str | Path | None = None,
513 profile: str | None = None,
514 proxy: str | None = None,
515 url: str | None = None,
516 close_running: bool = False,
517) -> PlainChrome:
518 """Open the project's (or account's) ai-shell Chrome WITHOUT the debug port.
520 Google refuses to sign in inside a browser that exposes a DevTools port
521 ("This browser or app may not be secure"), so a Google (or Google SSO)
522 sign-in has to happen in a plain window on the same profile directory.
523 The cookies it leaves behind are what the debug-port Chrome reuses on
524 the next ``--local-chrome`` launch.
526 Raises :class:`LocalChromeUnavailable` when Chrome is not installed, or
527 when a Chrome already holds that profile (a second launch would only
528 open a window inside the running, debug-port process). With
529 *close_running*, that Chrome is asked to quit first: it is ai-shell's own
530 window.
531 """
532 chrome_path = find_chrome()
533 if chrome_path is None:
534 raise LocalChromeUnavailable(
535 "Chrome could not be found. Install Google Chrome or Chromium, or put it on PATH."
536 )
537 profile_dir = _chrome_profile_dir(project_name, project_dir, profile)
538 port = _project_debug_port(project_name, project_dir, profile)
539 if chrome_profile_in_use(profile_dir) or probe_host_chrome_port(port):
540 if not (close_running and close_chrome_profile(profile_dir, port)):
541 raise LocalChromeUnavailable(
542 f"A Chrome window already uses the profile {profile_dir}.\n"
543 "Close every window of that Chrome (the one ai-shell opened with the "
544 "DevTools port) and run this again: a second launch would open inside "
545 "the running process, where Google still refuses the sign-in."
546 )
547 reason = no_display_reason()
548 if reason:
549 raise LocalChromeUnavailable(reason)
550 args = [
551 chrome_path,
552 f"--user-data-dir={profile_dir}",
553 "--no-first-run",
554 "--no-default-browser-check",
555 *_proxy_args(proxy),
556 ]
557 if url:
558 args.append(url)
559 logger.info("Launching plain Chrome: %s", " ".join(args))
560 # Chrome's stderr goes to a temp file: when it exits at once, its own
561 # words ("Missing X server or $DISPLAY", a profile error) are the reason.
562 stderr = tempfile.TemporaryFile()
563 process = _spawn_detached(args, stderr=stderr)
564 code = _exited_early(process, CHROME_START_SECONDS)
565 if code is not None:
566 stderr.seek(0)
567 output = stderr.read().decode("utf-8", "replace").strip()
568 stderr.close()
569 tail = "\n".join(output.splitlines()[-8:]) or "(no output)"
570 raise LocalChromeUnavailable(
571 f"Chrome exited at once (code {code}) instead of opening the window. Its output:\n{tail}"
572 )
573 stderr.close()
574 return PlainChrome(profile_dir=profile_dir, port=port, process=process)
577def probe_chrome_port(container_name: str, port: int) -> bool:
578 """Check whether a Chrome debug port is reachable from the container.
580 Returns ``True`` if reachable, ``False`` otherwise.
581 """
582 probe_url = f"http://{CHROME_DEBUG_HOST}:{port}/json/version"
583 args = [
584 "docker",
585 "exec",
586 container_name,
587 "curl",
588 "-sS",
589 "--max-time",
590 "3",
591 "-H",
592 f"Host: localhost:{port}",
593 probe_url,
594 ]
595 logger.debug("Probing Chrome debug port: %s", " ".join(args))
596 result = subprocess.run(args, capture_output=True, text=True)
597 if result.returncode != 0 or not result.stdout.strip():
598 return False
599 logger.info("Chrome debug port reachable: %s", result.stdout.strip()[:120])
600 return True
603def relay_log_path(port: int) -> Path:
604 """Where the relay for *port* writes its log."""
605 return Path.home() / ".augint" / "chrome" / f"cdp-relay-{port}.log"
608def start_cdp_relay(bind_address: str, port: int) -> None:
609 """Relay *bind_address*:*port* to Chrome's loopback port, detached, unless one answers already.
611 The relay is :mod:`ai_shell.cdp_relay`, run with the same interpreter
612 that runs ai-shell; it exits by itself once Chrome's port is gone.
613 """
614 if probe_host_chrome_port(port, bind_address):
615 return
616 log_path = relay_log_path(port)
617 log_path.parent.mkdir(parents=True, exist_ok=True)
618 args = [sys.executable, "-m", "ai_shell.cdp_relay", bind_address, str(port)]
619 logger.info("Starting the DevTools relay: %s", " ".join(args))
620 with log_path.open("ab") as log:
621 _spawn_detached(args, stderr=log)
624def probe_host_chrome_port(port: int, host: str = LOOPBACK) -> bool:
625 """Check whether a Chrome debug port is reachable on the host at *host*."""
626 connection = HTTPConnection(host, port, timeout=2)
627 try:
628 connection.request("GET", "/json/version")
629 response = connection.getresponse()
630 return response.status == 200 and bool(response.read().strip())
631 except (OSError, HTTPException):
632 return False
633 finally:
634 connection.close()
637def _wait_until_ready(
638 probe_fn: Callable[..., bool],
639 *args: object,
640 timeout_seconds: float,
641 interval_seconds: float = CHROME_PROBE_INTERVAL_SECONDS,
642) -> bool:
643 """Poll until a probe succeeds or the timeout expires."""
644 deadline = time.monotonic() + timeout_seconds
645 while True:
646 if probe_fn(*args):
647 return True
648 remaining = deadline - time.monotonic()
649 if remaining <= 0:
650 return False
651 time.sleep(min(interval_seconds, remaining))
654def ensure_host_chrome(
655 container_name: str,
656 *,
657 project_name: str,
658 project_dir: str | Path | None = None,
659 profile: str | None = None,
660 proxy: str | None = None,
661) -> int:
662 """Ensure Chrome is running with a debug port reachable from the container.
664 Each project gets its own debug profile directory and a stable debug port,
665 so different repos can keep separate logged-in Chrome instances alive.
666 When *profile* is given (a Claude account), the profile and port are keyed
667 by it instead, so one account keeps one browser across projects and two
668 accounts never share one. *proxy* is handed to Chrome as
669 ``--proxy-server`` when ai-shell has to launch it; a Chrome that is
670 already running keeps whatever proxy it was started with.
672 The port is the one the Chrome already holding the profile listens on,
673 else the stable hashed port, else the next one the host lets Chrome bind
674 (Windows reserves port blocks that move between boots). A Chrome that
675 holds the profile without a working port is ai-shell's own window and
676 useless to the container, and a new launch would only open inside it,
677 so it is closed gracefully (cookies kept) first.
679 Returns the port number Chrome is listening on.
680 """
681 profile_dir = _chrome_profile_dir(project_name, project_dir, profile)
682 running = running_chrome_port(profile_dir)
684 if running and probe_host_chrome_port(running):
685 port = running
686 if probe_chrome_port(container_name, port):
687 return port
688 bind_address = chrome_bind_address(container_name)
689 else:
690 if running is not None:
691 logger.info("Chrome holds %s without a working DevTools port; closing it", profile_dir)
692 if not close_chrome_profile(profile_dir, running):
693 raise LocalChromeUnavailable(
694 f"A Chrome window uses the profile {profile_dir} without a DevTools port "
695 "ai-shell can reach, and it did not close when asked.\n"
696 "Close every window of that Chrome and run this again."
697 )
698 port = _free_debug_port(_project_debug_port(project_name, project_dir, profile))
699 logger.info("Launching Chrome for project %s on port %d", project_name, port)
701 bind_address = chrome_bind_address(container_name)
702 if not launch_chrome(
703 port,
704 project_name=project_name,
705 project_dir=project_dir,
706 profile=profile,
707 bind_address=bind_address,
708 proxy=proxy,
709 ):
710 raise LocalChromeUnavailable(
711 _build_setup_instructions(project_name, profile_dir, port, bind_address, proxy)
712 )
714 if not _wait_until_ready(
715 probe_host_chrome_port,
716 port,
717 LOOPBACK,
718 timeout_seconds=CHROME_HOST_PROBE_TIMEOUT_SECONDS,
719 ):
720 raise LocalChromeUnavailable(
721 f"Chrome was launched for project '{project_name}' on port {port}, but the "
722 f"debug port did not open on {LOOPBACK} within "
723 f"{int(CHROME_HOST_PROBE_TIMEOUT_SECONDS)} seconds.\n\n"
724 f"Close every window of the Chrome on {profile_dir} and retry."
725 )
727 if bind_address != LOOPBACK:
728 # Linux: the container reaches the host at bind_address, where only
729 # the relay can answer (Chrome itself listens on loopback alone).
730 start_cdp_relay(bind_address, port)
731 if not _wait_until_ready(
732 probe_host_chrome_port,
733 port,
734 bind_address,
735 timeout_seconds=CHROME_HOST_PROBE_TIMEOUT_SECONDS,
736 ):
737 raise LocalChromeUnavailable(
738 f"Chrome answers on {LOOPBACK}:{port}, but ai-shell's relay did not open "
739 f"{bind_address}:{port} within {int(CHROME_HOST_PROBE_TIMEOUT_SECONDS)} "
740 f"seconds. Its log: {relay_log_path(port)}"
741 )
743 if _wait_until_ready(
744 probe_chrome_port,
745 container_name,
746 port,
747 timeout_seconds=CHROME_CONTAINER_PROBE_TIMEOUT_SECONDS,
748 ):
749 logger.info("Chrome ready on port %d for project %s", port, project_name)
750 return port
752 raise LocalChromeUnavailable(
753 f"Chrome is listening on {bind_address}:{port} for project '{project_name}', but the "
754 "debug port did not become reachable from the dev container within "
755 f"{int(CHROME_CONTAINER_PROBE_TIMEOUT_SECONDS)} seconds.\n\n"
756 "Check that the container can reach the host via host.docker.internal "
757 "(Docker Desktop on Windows/macOS; `host-gateway` on Linux Docker 20.10+ or podman 4.1+)."
758 )
761def start_chrome_proxy(container_name: str, port: int) -> None:
762 """Start a TCP proxy inside the container: localhost:<port> -> host.docker.internal:<port>.
764 Chrome rejects DevTools Protocol requests with a non-localhost Host
765 header. This proxy lets the MCP server connect to ``localhost:<port>``
766 so Chrome sees ``Host: localhost``.
768 The proxy runs as a detached background process via ``docker exec -d``.
769 It's idempotent -- if the port is already in use (previous proxy still
770 running), the new one fails silently and the existing one keeps working.
771 """
772 script = _NODE_PROXY_TEMPLATE.format(port=port)
773 args = [
774 "docker",
775 "exec",
776 "-d",
777 container_name,
778 "node",
779 "-e",
780 script,
781 ]
782 logger.debug("Starting Chrome proxy: %s", " ".join(args))
783 result = subprocess.run(args, capture_output=True, text=True)
784 if result.returncode != 0:
785 logger.warning(
786 "Chrome proxy start returned %d: %s", result.returncode, result.stderr.strip()
787 )
790CHROME_MCP_SERVER_NAME = "chrome-devtools"
791CHROME_MCP_BIN = "chrome-devtools-mcp"
792CHROME_MCP_PACKAGE = "chrome-devtools-mcp@latest"
793CHROME_MCP_INSTALL_TIMEOUT_SECONDS = 900
794CHROME_MCP_PROBE_TIMEOUT_SECONDS = 45.0
795_MCP_PROTOCOL_VERSION = "2025-06-18"
798def chrome_mcp_server_spec(port: int) -> dict[str, object]:
799 """MCP server definition for chrome-devtools-mcp against the in-container proxy.
801 Points at ``localhost:<port>`` (the proxy), not ``host.docker.internal``,
802 because Chrome rejects the latter's Host header. The command is the
803 binary installed in the image (``npm install -g``), not ``npx ...@latest``:
804 an npx fetch on a cold container took longer than Claude Code's MCP
805 startup timeout, and the server then showed as "failed to start" with
806 no reason. :func:`ensure_chrome_mcp` installs it on older images.
807 """
808 return {
809 "command": CHROME_MCP_BIN,
810 "args": ["--browserUrl", f"http://localhost:{port}"],
811 }
814def _login_shell(script: str) -> list[str]:
815 return ["bash", "-lc", script]
818def ensure_chrome_mcp(container_name: str) -> None:
819 """Install ``chrome-devtools-mcp`` globally in the container when the image lacks it."""
820 probe = subprocess.run(
821 ["docker", "exec", container_name, *_login_shell(f"command -v {CHROME_MCP_BIN}")],
822 capture_output=True,
823 text=True,
824 timeout=60,
825 )
826 if probe.returncode == 0:
827 return
828 console.print(
829 f"[dim]Installing the Chrome DevTools MCP server (npm install -g {CHROME_MCP_PACKAGE})...[/dim]"
830 )
831 result = subprocess.run(
832 ["docker", "exec", container_name, *_login_shell(f"npm install -g {CHROME_MCP_PACKAGE}")],
833 capture_output=True,
834 text=True,
835 timeout=CHROME_MCP_INSTALL_TIMEOUT_SECONDS,
836 )
837 if result.returncode != 0:
838 raise LocalChromeUnavailable(
839 "Could not install chrome-devtools-mcp in the dev container, so Claude would "
840 "have no Chrome tools.\n"
841 f" npm said: {(result.stderr or result.stdout).strip()[-500:]}"
842 )
845def _mcp_probe_messages() -> str:
846 """The three JSON-RPC lines of the probe: handshake, then one real tool call."""
847 messages = [
848 {
849 "jsonrpc": "2.0",
850 "id": 1,
851 "method": "initialize",
852 "params": {
853 "protocolVersion": _MCP_PROTOCOL_VERSION,
854 "capabilities": {},
855 "clientInfo": {"name": "ai-shell", "version": "0"},
856 },
857 },
858 {"jsonrpc": "2.0", "method": "notifications/initialized"},
859 {
860 "jsonrpc": "2.0",
861 "id": 2,
862 "method": "tools/call",
863 "params": {"name": "list_pages", "arguments": {}},
864 },
865 ]
866 return "".join(json.dumps(m) + "\n" for m in messages)
869def _mcp_tool_text(result: dict[str, object]) -> str:
870 content = result.get("content")
871 if not isinstance(content, list):
872 return ""
873 return "\n".join(
874 str(item.get("text", "")) for item in content if isinstance(item, dict)
875 ).strip()
878def probe_chrome_mcp(
879 container_name: str,
880 port: int,
881 *,
882 timeout_seconds: float = CHROME_MCP_PROBE_TIMEOUT_SECONDS,
883) -> str:
884 """Start chrome-devtools-mcp once in the container and make it list Chrome's pages.
886 The server connects to the browser lazily, so a handshake alone proves
887 nothing; ``list_pages`` exercises the whole path (binary, Node, the
888 in-container proxy, the DevTools port). Returns the tool's text on
889 success and raises :class:`LocalChromeUnavailable` with the server's own
890 output otherwise, so the failure is reported at launch instead of
891 surfacing inside Claude as a server that "failed to start".
892 """
893 import tempfile
894 import threading
896 spec = chrome_mcp_server_spec(port)
897 command = " ".join(str(part) for part in [spec["command"], *spec["args"]]) # type: ignore[misc]
898 lines: list[str] = []
899 done = threading.Event()
900 with tempfile.TemporaryFile(mode="w+", encoding="utf-8") as stderr:
901 proc = subprocess.Popen(
902 ["docker", "exec", "-i", container_name, *_login_shell(f"exec {command}")],
903 stdin=subprocess.PIPE,
904 stdout=subprocess.PIPE,
905 stderr=stderr,
906 text=True,
907 encoding="utf-8",
908 )
910 def _read() -> None:
911 assert proc.stdout is not None
912 for line in proc.stdout:
913 lines.append(line)
914 try:
915 message = json.loads(line)
916 except ValueError:
917 continue
918 if isinstance(message, dict) and message.get("id") == 2:
919 done.set()
920 return
921 done.set()
923 reader = threading.Thread(target=_read, daemon=True)
924 reader.start()
925 try:
926 assert proc.stdin is not None
927 proc.stdin.write(_mcp_probe_messages())
928 proc.stdin.flush()
929 except (OSError, ValueError):
930 pass
931 answered = done.wait(timeout_seconds)
932 try:
933 if proc.stdin is not None:
934 proc.stdin.close()
935 except OSError:
936 pass
937 proc.terminate()
938 try:
939 proc.wait(timeout=5)
940 except subprocess.TimeoutExpired:
941 proc.kill()
942 reader.join(timeout=1)
943 stderr.seek(0)
944 server_said = stderr.read().strip()[-800:]
946 reply: dict[str, object] | None = None
947 for line in lines:
948 try:
949 message = json.loads(line)
950 except ValueError:
951 continue
952 if isinstance(message, dict) and message.get("id") == 2:
953 reply = message
954 break
956 detail = f"\n server output: {server_said}" if server_said else ""
957 if not answered or reply is None:
958 raise LocalChromeUnavailable(
959 f"chrome-devtools-mcp did not answer within {int(timeout_seconds)} seconds "
960 f"(command: {command}).{detail}"
961 )
962 error = reply.get("error")
963 if isinstance(error, dict):
964 raise LocalChromeUnavailable(
965 f"chrome-devtools-mcp refused list_pages: {error.get('message', error)}{detail}"
966 )
967 result = reply.get("result")
968 if not isinstance(result, dict):
969 raise LocalChromeUnavailable(f"chrome-devtools-mcp sent no result for list_pages.{detail}")
970 text = _mcp_tool_text(result)
971 if result.get("isError"):
972 raise LocalChromeUnavailable(
973 f"chrome-devtools-mcp could not reach Chrome on localhost:{port} from the "
974 f"container: {text or 'no detail'}{detail}"
975 )
976 return text
979def prepare_chrome_mcp(container_name: str, port: int) -> str:
980 """Make sure the Chrome MCP server is installed and answers before Claude starts."""
981 ensure_chrome_mcp(container_name)
982 return probe_chrome_mcp(container_name, port)
985def write_mcp_config(port: int, config_dir: Path | None = None) -> Path:
986 """Write the chrome-devtools-mcp server config JSON.
988 Returns the path to the written file. The file lives under
989 ``~/.config/ai-shell/`` by default so it persists across sessions
990 without polluting the project directory.
991 """
992 if config_dir is None:
993 config_dir = Path.home() / ".config" / "ai-shell"
994 config_dir.mkdir(parents=True, exist_ok=True)
996 mcp_config = {"mcpServers": {CHROME_MCP_SERVER_NAME: chrome_mcp_server_spec(port)}}
998 path = config_dir / MCP_CONFIG_FILENAME
999 path.write_text(json.dumps(mcp_config, indent=2) + "\n", encoding="utf-8")
1000 logger.debug("Wrote MCP config: %s", path)
1001 return path