Files
ai-agent/backend/chrome/lifecycle.py
Gabriel Vidal dd5ba797cc feat(chrome): drive the lab Chrome with claude --chrome — composer chip, Browser panel (noVNC proxy), Settings → Browser, on-demand container
- sidecar: chrome flag on spawn/resume/fork → --chrome; /chrome status + start/stop/restart/reset-profile (docker)
- backend: chrome/ package — status + settings (/api/chrome), owner-only websocket proxy to the container's websockify (/api/chrome/ws), ensure-start before a --chrome lab run, idle reaper; meta.chrome kept on resume
- frontend: Chrome chip (trigger words via the chrome skill tag), ChromeBadge on resume, BrowserDock gizmo + take-over panel (@novnc/novnc), Settings → Browser page, visibility toggle, mock backend
- docs: CLAUDE.md section
2026-10-23 12:13:24 +02:00

106 lines
4.0 KiB
Python

"""The lab Chrome's on-demand life (Settings → Browser, ``keep: "idle"``).
``ensure_up`` runs before a lab run is launched with ``--chrome``: the host
sidecar starts the container when it is down and we wait for its noVNC port
so the extension is pairing by the time the run's first browser call lands.
``IdleReaper`` stops it again once no ``--chrome`` conversation has been
running, and no live view has been open, for ``idleMinutes``. Both are
no-ops with ``keep: "always"`` (nothing is ever stopped; a down container is
still started on demand) and in standalone mode (no sidecar)."""
import logging
import threading
import time
from fastapi import HTTPException
from core.state import AppState
log = logging.getLogger("chrome")
# When the owner last had a live view connected (the websocket proxy stamps
# it) — watching counts as using.
_last_watched = {"at": 0.0}
# When a --chrome run was last seen live.
_last_driving = {"at": 0.0}
def touch_watch() -> None:
_last_watched["at"] = time.time()
def ensure_up(deps: AppState, wait_s: float = 25.0) -> None:
"""Start the container if it is down (through the sidecar) and wait for
its noVNC port. Failures are logged, never fatal: the run still launches,
and its first browser call will say what is wrong."""
from chrome import routes as chrome_routes
if chrome_routes._reachable(fresh=True):
return
try:
from runs.sidecar_client import _sidecar_call
_sidecar_call(deps, "/chrome/start", {}, timeout=60)
except HTTPException as e:
log.info("chrome ensure_up: could not start the container: %s", e.detail)
return
deadline = time.monotonic() + wait_s
while time.monotonic() < deadline:
if chrome_routes._reachable(fresh=True):
deps.hub.publish({"type": "chrome"})
return
time.sleep(1.0)
log.info("chrome ensure_up: container started but noVNC not up after %.0fs", wait_s)
deps.hub.publish({"type": "chrome"})
class IdleReaper(threading.Thread):
"""Every minute: with ``keep: "idle"``, stop a reachable container that
nothing has used for ``idleMinutes``."""
def __init__(self, deps: AppState, interval_s: float = 60.0):
super().__init__(name="chrome-idle", daemon=True)
self.deps = deps
self.interval_s = interval_s
def run(self) -> None: # pragma: no cover - timing
while True:
time.sleep(self.interval_s)
try:
self.tick()
except Exception as e:
log.info("chrome idle reaper: %s", e)
def tick(self) -> None:
from chrome import routes as chrome_routes
cfg = self.deps.chrome_store.get()
if cfg.get("keep") != "idle":
return
if chrome_routes._driving(self.deps):
_last_driving["at"] = time.time()
return
if not chrome_routes._reachable():
return
idle_s = cfg.get("idleMinutes", 30) * 60
last = max(_last_watched["at"], _last_driving["at"])
host = chrome_routes._host_status(self.deps)
started = host.get("startedAt") if host else None
if started:
try:
import datetime
ts = datetime.datetime.fromisoformat(started.replace("Z", "+00:00")[:26] + "+00:00") \
if "." in started else datetime.datetime.fromisoformat(started.replace("Z", "+00:00"))
last = max(last, ts.timestamp())
except ValueError:
pass
if time.time() - last < idle_s:
return
log.info("chrome idle reaper: stopping the lab Chrome after %d min idle",
int((time.time() - last) // 60))
try:
from runs.sidecar_client import _sidecar_call
_sidecar_call(deps=self.deps, path="/chrome/stop", payload={}, timeout=90)
except HTTPException as e:
log.info("chrome idle reaper: stop failed: %s", e.detail)
return
chrome_routes._reach_cache["at"] = 0.0
self.deps.hub.publish({"type": "chrome"})