Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(browser): keep cold starts connected and seed new viewers
rubenluetke10-beep2100ba184f88
diff --git a/jarvis/society/browser/live_runner.py b/jarvis/society/browser/live_runner.pyindex ceee601ae6..57aa7dbafe 100644--- a/jarvis/society/browser/live_runner.py+++ b/jarvis/society/browser/live_runner.py@@ -449,6 +449,18 @@ class Worker:)if op == "subscribe":self.viewers = bool(args.get("enabled"))+ if self.viewers and self.page and not self.page.is_closed():+ # A second viewer may join an unchanged page whose screencast+ # has nothing new to emit. Give it current pixels immediately.+ captured_at = time.time()+ blob = await self.page.screenshot(type="jpeg", quality=65, timeout=5000)+ self.latest = {+ "data": base64.b64encode(blob).decode(),+ "timestamp": captured_at,+ "target": self.target,+ "width": 1280,+ "height": 800,+ }return {}if op == "cancel":if self.job and not self.job.done():diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsxindex 316b715c7e..202ddda631 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx@@ -98,7 +98,7 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {{state.ready && !state.connected && <div className="absolute bottom-2 rounded bg-background/90 px-2 py-1 text-xs">{status}</div>}</div><div className="mt-2 flex flex-wrap justify-center gap-1">- <button className={buttonClass} disabled={!state.connected || state.controlPending}+ <button className={buttonClass} disabled={!state.connected || !state.ready || state.controlPending}onClick={() => { setExpanded(true); control("takeover", { enabled: !state.manual }); }}>{t(state.manual ? "society.browser_live.return_control" : "society.browser_live.take_control")}</button>diff --git a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsxindex 1b3c780c1f..63e585cfb4 100644--- a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.test.tsx@@ -53,3 +53,27 @@ test("static page heartbeats preserve a healthy connection without new images",expect(hook.result.current.state.connected).toBe(true);expect(Socket.current.close).not.toHaveBeenCalled();});++test("cold browser startup stays connected until pixels are available", async () => {+ const hook = await mount();+ for (let n = 0; n < 50; n++) {+ act(() => {+ vi.advanceTimersByTime(2000);+ Socket.current.onmessage?.({ data: JSON.stringify({ kind: "starting" }) });+ });+ }+ expect(hook.result.current.state.connected).toBe(true);+ expect(hook.result.current.state.ready).toBe(false);+ expect(Socket.current.close).not.toHaveBeenCalled();+});++test("startup failure remains visible while reconnecting", async () => {+ const hook = await mount();+ act(() => {+ Socket.current.onmessage?.({ data: JSON.stringify({ kind: "error", error: "Browser startup failed" }) });+ Socket.current.close();+ Socket.current.onopen?.();+ });+ expect(hook.result.current.state.error).toBe("Browser startup failed");+ expect(hook.result.current.state.ready).toBe(false);+});diff --git a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.tsindex 05c030e102..4d1f0527b5 100644--- a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts+++ b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts@@ -58,7 +58,7 @@ export function useBrowserView(agentId: string) {// Read-only diagnostics for end-to-end stream acceptance and support.el.dataset.browserFrameAgeMs = String(Math.max(0, Date.now() - frame.timestamp * 1000));el.dataset.browserRenderedFrames = String(++renderedFrames);- setState((s) => s.ready ? s : { ...s, ready: true });+ setState((s) => s.ready ? s : { ...s, ready: true, error: "" });}decodeBusy = false;decodeFrame();@@ -80,9 +80,8 @@ export function useBrowserView(agentId: string) {(ticket ? "?ticket=" + encodeURIComponent(ticket) : ""));socket.current = ws;ws.onopen = () => {- attempt = 0;lastLiveEvent = Date.now();- setState((s) => ({ ...s, connected: true, error: "" }));+ setState((s) => ({ ...s, connected: true, ready: false }));};ws.onmessage = (message) => {if (disposed || socket.current !== ws) return;@@ -92,6 +91,7 @@ export function useBrowserView(agentId: string) {if (typeof event.data !== "string" || typeof event.sequence !== "number") return;if (!Number.isFinite(event.timestamp)) return;lastLiveEvent = Date.now();+ attempt = 0;if (event.generation !== generation) {generation = event.generation;lastSequence = -1;@@ -101,6 +101,10 @@ export function useBrowserView(agentId: string) {lastSequence = event.sequence;latestFrame = event;decodeFrame();+ } else if (event.kind === "starting") {+ lastLiveEvent = Date.now();+ } else if (event.kind === "error") {+ setState((s) => ({ ...s, ready: false, error: event.error }));} else if (event.kind === "state") {lastLiveEvent = Date.now();setState((s) => ({ ...s, manual: event.manual, running: event.running,diff --git a/jarvis/ui/web/society_browser_routes.py b/jarvis/ui/web/society_browser_routes.pyindex 3ca25780c2..bee6c044c1 100644--- a/jarvis/ui/web/society_browser_routes.py+++ b/jarvis/ui/web/society_browser_routes.py@@ -32,6 +32,25 @@ OPERATIONS = {}+async def _subscribe_with_progress(live: Any, agent: Any, send: Any) -> Any:+ """Keep the viewer alive during provisioning and cold Chromium startup."""+ await send({"kind": "starting"})+ task = asyncio.create_task(live.subscribe(agent))+ try:+ while not task.done():+ done, _ = await asyncio.wait({task}, timeout=2)+ if not done:+ await send({"kind": "starting"})+ return await task+ except BaseException:+ task.cancel()+ result = (await asyncio.gather(task, return_exceptions=True))[0]+ if isinstance(result, tuple):+ session, queue = result+ await live.unsubscribe(session, queue, "")+ raise++def validate_control(value: Any) -> tuple[str, dict]:if not isinstance(value, dict) or value.get("op") not in OPERATIONS:raise ValueError("Unsupported browser control")@@ -124,7 +143,7 @@ async def agent_browser_live(websocket: WebSocket, agent_id: str) -> None:await websocket.send_json(value)try:- session, queue = await live.subscribe(agent)+ session, queue = await _subscribe_with_progress(live, agent, send)async def frames() -> None:while True:@@ -172,6 +191,13 @@ async def agent_browser_live(websocket: WebSocket, agent_id: str) -> None:except Exception:log.debug("Browser view disconnected for %s", agent_id, exc_info=True)with contextlib.suppress(Exception):+ if session is None:+ await send(+ {+ "kind": "error",+ "error": "Browser startup failed. Retry or repair the installation.",+ }+ )await websocket.close(code=1011)finally:for task in (receive, pending):diff --git a/tests/contract/test_browser_contract.py b/tests/contract/test_browser_contract.pyindex a32eebfee9..2add434f28 100644--- a/tests/contract/test_browser_contract.py+++ b/tests/contract/test_browser_contract.py@@ -21,6 +21,56 @@ def test_browser_capability_roundtrip():assert "browser-use" in rows[0].aliases+async def test_cold_browser_start_emits_progress_until_subscription_ready():+ import asyncio+ from jarvis.ui.web.society_browser_routes import _subscribe_with_progress++ ready = asyncio.Event()+ messages = []+ subscription = (object(), object())++ async def subscribe(_):+ await ready.wait()+ return subscription++ async def send(event):+ messages.append(event)+ if len(messages) == 2:+ ready.set()++ result = await asyncio.wait_for(+ _subscribe_with_progress(SimpleNamespace(subscribe=subscribe), object(), send), 4+ )+ assert result is subscription+ assert messages == [{"kind": "starting"}, {"kind": "starting"}]+++async def test_starting_viewer_transport_failure_cancels_subscription():+ import asyncio+ from jarvis.ui.web.society_browser_routes import _subscribe_with_progress++ cancelled = asyncio.Event()+ sends = 0++ async def subscribe(_):+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ async def send(_):+ nonlocal sends+ sends += 1+ if sends == 2:+ raise ConnectionError("Viewer disconnected")++ with pytest.raises(ConnectionError):+ await asyncio.wait_for(+ _subscribe_with_progress(SimpleNamespace(subscribe=subscribe), object(), send), 4+ )+ assert cancelled.is_set()++async def test_stopped_browser_turn_cannot_retry_but_new_user_turn_can(tmp_path):from jarvis.society.browser.live import LiveSessionsfrom jarvis.society.browser.bridge import execute_livediff --git a/tests/contract/test_browser_live.py b/tests/contract/test_browser_live.pyindex 3340063d2f..ce29f102dd 100644--- a/tests/contract/test_browser_live.py+++ b/tests/contract/test_browser_live.py@@ -96,6 +96,23 @@ async def test_live_pixels_change_between_tasks_and_sessions_stay_open(live, sitawait live.close()+async def test_second_viewer_receives_static_page_without_new_browser(live):+ agent = SimpleNamespace(agent_id="static", model="", browser_allowed_domains=[])+ try:+ session, first = await live.subscribe(agent)+ while (await asyncio.wait_for(first.get(), 5))["kind"] != "frame":+ pass # Drain initial state before attaching the second viewer.+ await asyncio.sleep(1)+ same, second = await live.subscribe(agent)+ assert same is session+ while (await asyncio.wait_for(second.get(), 5))["kind"] != "frame":+ pass # State can precede the first image for a new viewer.+ assert len(live.sessions) == 1+ assert len(session.subscribers) == 2+ finally:+ await live.close()++async def test_takeover_pauses_and_resumes_the_same_browser_job(live, site):import jsonimport contextvars