Settings → Browser, the conversation's Browser dock (noVNC live view and
take-over) and the container's on-demand life move into the lab-chrome
live plugin (ai-agent-plugins). The core keeps the Chrome chip (the
harness capability chrome) and gains three generic hooks:
- sockets[] + aiAgentPlugin.openSocket(id): a frame's websocket, opened by
the host with the reader's cookies and relayed over postMessage to
WS /api/plugins/{pid}/sockets/{sid}, which bridges only to the declared
upstream (owner only, the gate's handshake rules, never the guest host;
operator approval). GET …/sockets/{sid}/probe → {up, open, lastActiveAt}
for the plugin's handlers.
- provides chrome.lab (plugins/chrome_bridge.py): {op: status} → the chip
default and whether guests' runs keep --chrome; {op: ensure} before a
lab --chrome run launches (spawn and resume).
- ui.slots[].size on app.modal (full = near full screen, frame filling it);
conversation.gizmos' update and hub/conversations rows carry chrome.
Gone: backend/chrome/, /api/chrome*, schemas/chrome.py, the SSE chrome
event, the lab.integrations permission, BrowserDock/BrowserSettings/store,
the Browser header button and eye switch, @novnc/novnc. /settings/browser
redirects to /settings/plugin/lab-chrome; carryover.chrome moves
/data/chrome.json into the plugin's config.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
288 lines
14 KiB
Python
288 lines
14 KiB
Python
"""The platform hooks the lab Chrome moved onto when it left the core
|
|
(2026-11-26, the ``lab-chrome`` plugin): ``sockets[]`` (a frame's websocket
|
|
relayed to the plugin's declared upstream, owner only, its probe), the
|
|
``chrome.lab`` provider (the guests switch, the pre-launch ``ensure``), an
|
|
``app.modal`` slot's ``size``, the ``chrome`` flag on ``hub/conversations``
|
|
rows and the carry-over of Settings → Browser's ``/data/chrome.json``."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
os.environ.setdefault("INTERNAL_API_TOKEN", "tok")
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
from starlette.websockets import WebSocketDisconnect # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import carryover, chrome_bridge, manifest, sockets # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from users.caller import OWNER, Caller # noqa: E402
|
|
|
|
|
|
def _plugin(root: pathlib.Path, **extra) -> pathlib.Path:
|
|
src = root / "src"
|
|
(src / "ui").mkdir(parents=True)
|
|
(src / "handlers").mkdir()
|
|
(src / "ui" / "live.html").write_text("<p>x</p>")
|
|
(src / "handlers" / "h.py").write_text("import json; print(json.dumps({}))\n")
|
|
mf = {"schema": 1, "id": "lc", "name": "L",
|
|
"actions": {"browser": {"script": "handlers/h.py"}},
|
|
"sockets": [{"id": "vnc", "url": "ws://chrome:6080/websockify",
|
|
"subprotocols": ["binary"], "label": "Screen"}],
|
|
"provides": {"chrome.lab": "browser"},
|
|
"ui": {"slots": [{"id": "live", "where": "app.modal", "html": "ui/live.html", "size": "full"}]}}
|
|
mf.update(extra)
|
|
(src / "plugin.json").write_text(json.dumps(mf))
|
|
return src
|
|
|
|
|
|
class TestManifest(unittest.TestCase):
|
|
def test_sockets_provider_and_modal_size(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = manifest.validate_manifest(_plugin(pathlib.Path(td)))
|
|
self.assertEqual(mf["sockets"], [{"id": "vnc", "url": "ws://chrome:6080/websockify",
|
|
"subprotocols": ["binary"], "label": "Screen"}])
|
|
self.assertEqual(mf["provides"], {"chrome.lab": "browser"})
|
|
self.assertEqual(mf["ui"]["slots"][0]["size"], "full")
|
|
# a socket reaches the host's network: the operator approves it
|
|
self.assertTrue(manifest.requires_operator(mf))
|
|
kinds = [i["kind"] for i in manifest.capability_summary(mf)]
|
|
self.assertIn("socket", kinds)
|
|
|
|
def test_bad_sockets_and_sizes_are_refused(self):
|
|
bad = [
|
|
{"sockets": [{"id": "vnc", "url": "http://chrome:6080/"}]},
|
|
{"sockets": [{"id": "vnc", "url": "ws://user:pw@chrome/"}]},
|
|
{"sockets": [{"id": "vnc", "url": "ws://chrome/x?y=1"}]},
|
|
{"sockets": [{"id": "v", "url": "ws://a"}, {"id": "v", "url": "ws://b"}]},
|
|
{"sockets": [{"id": "vnc", "url": "ws://a", "subprotocols": ["bad proto"]}]},
|
|
{"sockets": [{"id": f"s{i}", "url": "ws://a"} for i in range(5)]},
|
|
{"ui": {"slots": [{"id": "live", "where": "app.modal", "html": "ui/live.html", "size": "huge"}]}},
|
|
{"ui": {"slots": [{"id": "live", "where": "conversation.gizmos", "html": "ui/live.html",
|
|
"size": "full"}]}},
|
|
]
|
|
for extra in bad:
|
|
with self.subTest(extra=extra), tempfile.TemporaryDirectory() as td:
|
|
with self.assertRaises(manifest.ManifestError):
|
|
manifest.validate_manifest(_plugin(pathlib.Path(td), **extra))
|
|
|
|
def test_the_fingerprint_moves_only_when_sockets_are_declared(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = manifest.validate_manifest(_plugin(pathlib.Path(td)))
|
|
bare = {k: v for k, v in mf.items() if k != "sockets"}
|
|
self.assertNotEqual(manifest.capability_fingerprint(mf), manifest.capability_fingerprint(bare))
|
|
other = {**mf, "sockets": [{**mf["sockets"][0], "url": "ws://elsewhere:1/"}]}
|
|
self.assertNotEqual(manifest.capability_fingerprint(mf), manifest.capability_fingerprint(other))
|
|
self.assertNotIn("sockets", bare)
|
|
|
|
|
|
class _Upstream:
|
|
"""A real websocket server on a free port: echoes binary frames back,
|
|
says which subprotocol it was offered."""
|
|
|
|
def __init__(self):
|
|
self.loop = asyncio.new_event_loop()
|
|
self.offered: list = []
|
|
self.ready = threading.Event()
|
|
self.port = 0
|
|
self.thread = threading.Thread(target=self._run, daemon=True)
|
|
self.thread.start()
|
|
self.ready.wait(5)
|
|
|
|
def _run(self):
|
|
import websockets
|
|
|
|
async def handler(conn):
|
|
self.offered.append(conn.request.headers.get("Sec-WebSocket-Protocol"))
|
|
await conn.send(b"RFB 003.008\n") # what a VNC server says first
|
|
async for msg in conn:
|
|
await conn.send(msg)
|
|
|
|
async def main_():
|
|
async with websockets.serve(handler, "127.0.0.1", 0, subprotocols=["binary"]) as srv:
|
|
self.port = srv.sockets[0].getsockname()[1]
|
|
self.ready.set()
|
|
await asyncio.Future()
|
|
|
|
self.loop.run_until_complete(main_())
|
|
|
|
|
|
class TestRelay(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.up = _Upstream()
|
|
cls.client = TestClient(main.app)
|
|
|
|
def _rec(self, url=None):
|
|
return {"id": "lab-chrome", "enabled": True, "manifest": {"id": "lab-chrome", "sockets": [
|
|
{"id": "vnc", "url": url or f"ws://127.0.0.1:{self.up.port}/websockify",
|
|
"subprotocols": ["binary"]}]}}
|
|
|
|
def _patches(self, caller=OWNER, rec=None):
|
|
rec = rec if rec is not None else self._rec()
|
|
|
|
async def who(ws):
|
|
return caller
|
|
return (mock.patch.object(sockets, "ws_caller", who),
|
|
mock.patch.object(sockets, "_owner_rec", lambda deps, pid: rec))
|
|
|
|
def test_the_owner_gets_the_upstream_both_ways(self):
|
|
a, b = self._patches()
|
|
with a, b, self.client.websocket_connect("/api/plugins/lab-chrome/sockets/vnc",
|
|
subprotocols=["binary"]) as ws:
|
|
self.assertEqual(ws.receive_bytes(), b"RFB 003.008\n")
|
|
self.assertEqual(ws.accepted_subprotocol, "binary")
|
|
ws.send_bytes(b"\x01\x02\x03")
|
|
self.assertEqual(ws.receive_bytes(), b"\x01\x02\x03")
|
|
self.assertEqual(sockets.activity("lab-chrome", "vnc")["open"], 1)
|
|
self.assertEqual(self.up.offered[-1], "binary")
|
|
self.assertGreater(sockets.activity("lab-chrome", "vnc")["at"], 0)
|
|
|
|
def test_a_guest_an_unknown_socket_and_a_down_upstream_are_refused(self):
|
|
guest = Caller(id="ada", role="guest", name="Ada")
|
|
cases = [(self._patches(caller=guest), 4403)]
|
|
cases.append((self._patches(caller=None), 4403))
|
|
cases.append((self._patches(rec={"id": "lab-chrome", "manifest": {}}), 4404))
|
|
cases.append((self._patches(rec=self._rec("ws://127.0.0.1:1/")), 4502))
|
|
for (a, b), code in cases:
|
|
with self.subTest(code=code), a, b:
|
|
with self.assertRaises(WebSocketDisconnect) as cm:
|
|
with self.client.websocket_connect("/api/plugins/lab-chrome/sockets/vnc") as ws:
|
|
ws.receive_bytes()
|
|
self.assertEqual(cm.exception.code, code)
|
|
|
|
def test_the_route_reads_only_the_owners_enabled_approved_install(self):
|
|
class Store:
|
|
def __init__(self, rec):
|
|
self.rec = rec
|
|
|
|
def get_raw(self, uid, pid):
|
|
return self.rec if uid == OWNER_UID else None
|
|
|
|
class Deps:
|
|
pass
|
|
d = Deps()
|
|
for rec, ok in (({"enabled": True}, True), ({"enabled": False}, False),
|
|
({"enabled": True, "needsApproval": True}, False), (None, False)):
|
|
d.plugin_store = Store(rec)
|
|
self.assertEqual(sockets._owner_rec(d, "lab-chrome") is not None, ok, rec)
|
|
|
|
def test_probe_needs_the_plugins_own_handler(self):
|
|
r = self.client.get("/proxy/tools/plugins/lab-chrome/sockets/vnc/probe",
|
|
headers={"Authorization": "Bearer nope"})
|
|
self.assertIn(r.status_code, (401, 403, 429))
|
|
|
|
def test_reachable(self):
|
|
self.assertTrue(sockets._reachable(f"ws://127.0.0.1:{self.up.port}/websockify"))
|
|
self.assertFalse(sockets._reachable("ws://127.0.0.1:1/"))
|
|
|
|
|
|
class TestChromeProvider(unittest.TestCase):
|
|
def setUp(self):
|
|
chrome_bridge.invalidate()
|
|
self.addCleanup(chrome_bridge.invalidate)
|
|
|
|
def test_no_provider_no_guests_no_ensure(self):
|
|
with mock.patch.object(chrome_bridge, "_provider", lambda deps: None):
|
|
self.assertIsNone(chrome_bridge.status(object()))
|
|
self.assertFalse(chrome_bridge.guests_allowed(object()))
|
|
chrome_bridge.ensure(object(), "sid") # a no-op, no raise
|
|
|
|
def test_status_is_normalized_and_cached(self):
|
|
calls = []
|
|
|
|
def run(deps, op, payload, timeout):
|
|
calls.append(op)
|
|
return {"reachable": 1, "chipDefault": "weird", "guests": True, "extra": "x"}
|
|
with mock.patch.object(chrome_bridge, "_provider", lambda deps: ({}, {})), \
|
|
mock.patch.object(chrome_bridge, "_run", run):
|
|
self.assertEqual(chrome_bridge.status(object()),
|
|
{"reachable": True, "chipDefault": "off", "guests": True})
|
|
self.assertTrue(chrome_bridge.guests_allowed(object()))
|
|
self.assertEqual(calls, ["status"]) # the second read came from the cache
|
|
chrome_bridge.ensure(object(), "sid")
|
|
self.assertEqual(calls, ["status", "ensure"])
|
|
chrome_bridge.status(object()) # ensure dropped the cache
|
|
self.assertEqual(calls, ["status", "ensure", "status"])
|
|
|
|
def test_a_broken_provider_never_breaks_a_launch(self):
|
|
def boom(*a, **k):
|
|
raise RuntimeError("plugin crashed")
|
|
with mock.patch.object(chrome_bridge, "_provider", lambda deps: ({"id": "x"}, {"script": "h.py"})), \
|
|
mock.patch("plugins.runner.run_script", boom):
|
|
chrome_bridge.ensure(object(), "sid")
|
|
self.assertFalse(chrome_bridge.guests_allowed(object()))
|
|
|
|
def test_a_guest_keeps_chrome_only_when_the_plugin_says_so(self):
|
|
from runs.routes import _guest_chrome
|
|
with mock.patch.object(chrome_bridge, "guests_allowed", lambda deps: False):
|
|
self.assertIsNone(_guest_chrome(object(), True))
|
|
with mock.patch.object(chrome_bridge, "guests_allowed", lambda deps: True):
|
|
self.assertTrue(_guest_chrome(object(), True))
|
|
self.assertIsNone(_guest_chrome(object(), False))
|
|
|
|
|
|
class TestConversationRow(unittest.TestCase):
|
|
def test_rows_say_whether_the_run_drives_chrome(self):
|
|
from plugins.proxyroutes import _conv_row
|
|
row = _conv_row("/x/y.jsonl", {"sessionId": "s1"}, {"chrome": True, "state": "running"})
|
|
self.assertIs(row["chrome"], True)
|
|
self.assertIs(_conv_row("/x/y.jsonl", {"sessionId": "s1"}, {})["chrome"], False)
|
|
|
|
|
|
class TestCarryOver(unittest.TestCase):
|
|
def _store(self, root: pathlib.Path, install: bool) -> PluginStore:
|
|
store = PluginStore(root / "data")
|
|
if install:
|
|
src = root / "lab-chrome"
|
|
(src / "handlers").mkdir(parents=True)
|
|
(src / "handlers" / "h.py").write_text("print('{}')\n")
|
|
(src / "plugin.json").write_text(json.dumps({
|
|
"schema": 1, "id": "lab-chrome", "name": "Lab Chrome",
|
|
"actions": {"status": {"script": "handlers/h.py"}},
|
|
"settings": {"fields": [
|
|
{"key": "chipDefault", "label": "Chip", "type": "select",
|
|
"options": ["off", "running", "always"], "default": "off"},
|
|
{"key": "guests", "label": "Guests", "type": "checkbox", "default": False},
|
|
{"key": "keep", "label": "Keep", "type": "select", "options": ["idle", "always"],
|
|
"default": "idle"},
|
|
{"key": "idleMinutes", "label": "Idle", "type": "number", "default": 30}]}}))
|
|
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
|
|
return store
|
|
|
|
def test_settings_wait_for_the_install_then_land_in_its_config(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = pathlib.Path(td)
|
|
old = root / "chrome.json"
|
|
old.write_text(json.dumps({"chipDefault": "running", "guests": True, "keep": "always",
|
|
"idleMinutes": 45, "junk": 1}))
|
|
store = self._store(root, install=False)
|
|
self.assertTrue(carryover.chrome(store, str(old)))
|
|
legacy = store.shared_data_dir("lab-chrome") / "legacy-settings.json"
|
|
self.assertEqual(json.loads(legacy.read_text())["idleMinutes"], 45)
|
|
self.assertNotIn("junk", json.loads(legacy.read_text()))
|
|
self.assertTrue(old.exists()) # not installed yet: it waits
|
|
store = self._store(root, install=True)
|
|
# the owner's own pick (off its default) stays; the rest, still at
|
|
# the defaults the install seeded, take the old settings
|
|
store.update(OWNER_UID, "lab-chrome", config={"chipDefault": "always"})
|
|
self.assertTrue(carryover.chrome(store, str(old)))
|
|
cfg = store.get_raw(OWNER_UID, "lab-chrome")["config"]
|
|
self.assertEqual(cfg, {"guests": True, "chipDefault": "always", "keep": "always",
|
|
"idleMinutes": 45})
|
|
self.assertFalse(old.exists())
|
|
self.assertTrue((root / "chrome.json.migrated").exists())
|
|
self.assertFalse(carryover.chrome(store, str(old))) # once
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|