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): launch an agent's Chromium only when it is needed
rubenluetke10-beep44db829a4fe9
diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsxindex 45d287b127..03f89fc279 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.test.tsx@@ -11,18 +11,26 @@ vi.mock("@/i18n", () => ({"society.browser_live.back": "Back","society.browser_live.screen": "Live browser of {0}","society.browser_live.live": "Live",+ "society.browser_live.off_hint": "Starts when {0} needs it",+ "society.browser_live.open": "Open browser",} as Record<string, string>)[key] ?? key,}));-const { control, state } = vi.hoisted(() => ({+const { control, state, view, browser } = vi.hoisted(() => ({control: vi.fn(),+ view: vi.fn(),+ browser: { open: true },state: { connected: true, ready: true, fullWindow: false, manual: false, running: false,url: "https://example.com", target: "one", tabs: [{ id: "one", url: "https://example.com" }], error: "" },}));vi.mock("./useBrowserView", () => ({- useBrowserView: () => ({ canvas: { current: null }, state, control, approve: vi.fn() }),+ useBrowserView: (agentId: string, enabled: boolean) => {+ view(agentId, enabled);+ return { canvas: { current: null }, state, control, approve: vi.fn() };+ },}));vi.mock("../cardData", () => ({useBrowserInstallStatus: () => ({ data: { installed: true, running: false } }),+ useAgentBrowserOpen: () => ({ data: browser.open }),}));const agent = { agentId: "scout", name: "Scout" } as SocietyAgent;function mount() {@@ -30,8 +38,24 @@ function mount() {<AgentBrowserPreview agent={agent} /></QueryClientProvider>);}-afterEach(() => { cleanup(); control.mockClear(); state.manual = false; state.fullWindow = false; });+afterEach(() => {+ cleanup(); control.mockClear(); view.mockClear();+ state.manual = false; state.fullWindow = false; browser.open = true;+});describe("live agent browser", () => {+ test("opening the card never launches a browser the agent is not using", () => {+ browser.open = false;+ mount();+ expect(view).toHaveBeenLastCalledWith("scout", false);+ expect(screen.getByTestId("agent-browser-preview").textContent).toContain("Starts when Scout needs it");+ fireEvent.click(screen.getByTestId("agent-browser-open"));+ expect(view).toHaveBeenLastCalledWith("scout", true);+ });+ test("a browser the agent already runs is shown straight away", () => {+ mount();+ expect(view).toHaveBeenLastCalledWith("scout", true);+ expect(screen.queryByTestId("agent-browser-open")).toBeNull();+ });test("full Chrome window never adds a second address bar or tab picker", async () => {state.fullWindow = true;mount();diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsxindex 224bfb3db2..0de57f1530 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx@@ -1,6 +1,7 @@/**- * The real agent browser, continuously rendered in the Options rail.- * Pixels stay out of React state; all manual actions require a control lease.+ * The real agent browser, rendered in the Options rail while it runs.+ * Opening the card never launches one; pixels stay out of React state; all+ * manual actions require a control lease.*/import { useEffect, useState } from "react";import { ArrowLeft, ArrowRight, Maximize2, Minimize2, RotateCw } from "lucide-react";@@ -10,7 +11,7 @@ import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";import { BrandedSelect } from "@/components/ui/select";import type { SocietyAgent } from "../data";-import { useBrowserInstallStatus } from "../cardData";+import { useAgentBrowserOpen, useBrowserInstallStatus } from "../cardData";import { useBrowserView } from "./useBrowserView";import { AgentCursor } from "./AgentCursor";import "./agentCard.css";@@ -20,13 +21,22 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {useLocaleChunk("society");const assistantName = useEventStore((s) => s.assistantName);const displayName = societyDisplayName(agent, assistantName);- const { canvas, state, control, approve } = useBrowserView(agent.agentId);+ // Viewing launches a Chromium, so the view attaches only to a browser the+ // agent already runs, or after the person asks for it.+ const running = useAgentBrowserOpen(agent.agentId);+ const [wanted, setWanted] = useState(false);+ useEffect(() => { setWanted(false); }, [agent.agentId]);+ useEffect(() => { if (running.data) setWanted(true); }, [running.data]);+ const live = wanted || running.data === true;+ const { canvas, state, control, approve } = useBrowserView(agent.agentId, live);const install = useBrowserInstallStatus();const [expanded, setExpanded] = useState(false);const [address, setAddress] = useState("");useEffect(() => setAddress(state.url), [state.url]);useEffect(() => { setExpanded(false); }, [agent.agentId]);- const status = state.connected && state.ready+ const status = !live+ ? t("society.browser_live.off")+ : state.connected && state.ready? t(state.manual ? "society.browser_live.manual" : "society.browser_live.live"): t(install.data && !install.data.installed ? "society.card.browser_setting_up" : "society.card.browser_connecting");const buttonClass = "rounded px-2 py-1 text-xs hover:bg-secondary disabled:opacity-40";@@ -99,7 +109,15 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {{!state.fullWindow && (<AgentCursor pointer={state.ready && state.connected && !state.manual ? state.pointer : undefined} />)}- {!state.ready && <div className="absolute inset-0 grid place-items-center bg-muted p-3 text-center text-xs text-muted-foreground">+ {!live && <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-muted p-3 text-center text-xs text-muted-foreground">+ <p>{t("society.browser_live.off_hint").replace("{0}", displayName)}</p>+ <button type="button" data-testid="agent-browser-open"+ className="rounded-md border border-border bg-background px-3 py-1 text-xs font-medium text-foreground hover:bg-secondary"+ onClick={() => setWanted(true)}>+ {t("society.browser_live.open")}+ </button>+ </div>}+ {live && !state.ready && <div className="absolute inset-0 grid place-items-center bg-muted p-3 text-center text-xs text-muted-foreground">{install.data?.detail || status}{install.data?.running && <span>{install.data.percent}%</span>}</div>}diff --git a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.tsindex e83bf47c70..d57e153117 100644--- a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts+++ b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts@@ -23,7 +23,11 @@ const empty: BrowserViewState = {url: "", tabs: [], target: "", error: "",};-export function useBrowserView(agentId: string) {+/**+ * Opening the live socket launches the agent's Chromium, so callers pass+ * `enabled` only while the browser is wanted: already running, or asked for.+ */+export function useBrowserView(agentId: string, enabled = true) {const canvas = useRef<HTMLCanvasElement>(null);const socket = useRef<WebSocket | null>(null);const [state, setState] = useState<BrowserViewState>(empty);@@ -52,6 +56,7 @@ export function useBrowserView(agentId: string) {if (el) el.width = 1280;};clearCanvas();+ if (!enabled) return;const decodeFrame = () => {if (decodeBusy || !latestFrame || disposed) return;const frame = latestFrame;@@ -212,7 +217,7 @@ export function useBrowserView(agentId: string) {ws?.close();clearCanvas();};- }, [agentId]);+ }, [agentId, enabled]);const control = useCallback((op: string, args: Record<string, unknown> = {}) => {if (op === "cancel") {diff --git a/jarvis/ui/web/frontend/src/components/society/cardData.ts b/jarvis/ui/web/frontend/src/components/society/cardData.tsindex 9ace04453f..1b961b9df8 100644--- a/jarvis/ui/web/frontend/src/components/society/cardData.ts+++ b/jarvis/ui/web/frontend/src/components/society/cardData.ts@@ -279,6 +279,22 @@ function installIsBusy(row: BrowserInstallStatus | undefined): boolean {}/** The one-click browser-use venv on this machine. */+/** Whether the agent's browser is already running. A read that never launches one. */+export function useAgentBrowserOpen(agentId: string) {+ return useQuery({+ queryKey: ["society", "browser-open", agentId],+ staleTime: 2_000,+ refetchInterval: import.meta.env.MODE === "test" ? false : 4_000,+ retry: false,+ queryFn: async (): Promise<boolean> => {+ const body = await getJson<{ open?: boolean }>(+ "/api/society/agents/" + encodeURIComponent(agentId) + "/browser/open",+ );+ return Boolean(body?.open);+ },+ });+}+export function useBrowserInstallStatus() {return useQuery({queryKey: ["society", "browser-install"],diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 31c86481f9..29f29ce703 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -557,7 +557,10 @@"approval": "Browser-Aktion erlauben?","allow": "Erlauben","deny": "Ablehnen",- "repair": "Browser reparieren"+ "repair": "Browser reparieren",+ "off": "Browser aus",+ "off_hint": "Der Browser startet erst, wenn {0} ihn braucht.",+ "open": "Browser öffnen"},"mars": {"rover_title": "Agenten-Rover",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex d571c5a7a1..cc94374c2d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -557,7 +557,10 @@"approval": "Allow browser action?","allow": "Allow","deny": "Deny",- "repair": "Repair browser"+ "repair": "Repair browser",+ "off": "Browser off",+ "off_hint": "The browser starts only when {0} needs it.",+ "open": "Open browser"},"mars": {"rover_title": "Agent rover",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 9abd908b9e..733444cfcc 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -557,7 +557,10 @@"approval": "¿Permitir la acción?","allow": "Permitir","deny": "Denegar",- "repair": "Reparar navegador"+ "repair": "Reparar navegador",+ "off": "Navegador apagado",+ "off_hint": "El navegador solo se inicia cuando {0} lo necesita.",+ "open": "Abrir navegador"},"mars": {"rover_title": "Rover de agentes",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 9c6a495b6b..9761adfa12 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -2880,19 +2880,14 @@ class WebServer:self._schedule_realtime_transport_warm()self._schedule_appshot_shortcut()# Defer provisioning until the boot chain returns control to the server.+ # Only the install is prepared here: a Chromium costs hundreds of MB,+ # so an agent's browser launches when the agent first uses it or the+ # person opens its view, never pre-warmed at boot.async def prepare_browser() -> None:from jarvis.society.browser import installdata_dir = Path(getattr(self.cfg.memory, "data_dir", None) or "data")try:install.start_install(data_dir)- while install.snapshot(data_dir)["running"]:- await asyncio.sleep(1)- if install.is_installed(data_dir):- runtime = self._build_society_runtime()- await runtime.ensure_started()- lead = await runtime.roster.get("jarvis")- if lead is not None:- await runtime.browser.live.ensure(lead)except Exception:logger.debug("Browser preparation deferred after failure", exc_info=True)self._browser_prepare_task = asyncio.create_task(prepare_browser(), name="browser-prepare")diff --git a/jarvis/ui/web/society_browser_routes.py b/jarvis/ui/web/society_browser_routes.pyindex aa32e99609..9eb554f9c6 100644--- a/jarvis/ui/web/society_browser_routes.py+++ b/jarvis/ui/web/society_browser_routes.py@@ -87,6 +87,18 @@ async def ensure_agent_browser(agent_id: str, request: Request) -> dict[str, Anyreturn install.snapshot(rt.data_dir)[email protected]("/agents/{agent_id}/browser/open")+async def agent_browser_open(agent_id: str, request: Request) -> dict[str, Any]:+ """Whether this agent's browser is running — a read that never launches one."""+ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, "Agent not found")+ session = rt.browser.live.sessions.get(agent.agent_id)+ is_open = session is not None and not session.closed+ return {"open": is_open, "running": is_open and session.run_lock.locked()}++@router.post("/browser/repair", openapi_extra={"x-jarvis-dangerous": True})async def repair_browser(request: Request) -> dict[str, Any]:"""Rebuild and verify the managed browser environment."""diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex b9e19fe41c..c89b8611e3 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -94,6 +94,9 @@ WITHHELD: Final[dict[str, str]] = {"POST /api/society/browser/install": "installs software on the machine — never from outside","POST /api/society/browser/repair": "repairs host software; local owner setup","POST /api/society/agents/{agent_id}/browser/cancel": "local browser control belongs to the owner UI",+ "GET /api/society/agents/{agent_id}/browser/open": (+ "whether the owner UI may attach its live view; local process state"+ ),"POST /api/society/agents/{agent_id}/browser/session": ("prepares the host browser environment; owner UI, not an external agent command"),diff --git a/tests/contract/test_browser_contract.py b/tests/contract/test_browser_contract.pyindex ed7e75ebbe..d2c4d07daf 100644--- a/tests/contract/test_browser_contract.py+++ b/tests/contract/test_browser_contract.py@@ -187,6 +187,39 @@ async def test_agent_cancel_releases_the_browser_without_stopping_the_chat(monkeassert seen == [False]+async def test_open_probe_reports_a_running_browser_without_launching_one(monkeypatch):+ import asyncio++ from jarvis.ui.web import society_browser_routes as routes++ ensured = []+ busy = asyncio.Lock()+ await busy.acquire()+ sessions = {+ "busy": SimpleNamespace(closed=False, run_lock=busy),+ "done": SimpleNamespace(closed=True, run_lock=asyncio.Lock()),+ }++ async def resolve(agent_id):+ return SimpleNamespace(agent_id=agent_id)++ async def ensure(agent, **_):+ ensured.append(agent.agent_id)++ async def runtime(_):+ return SimpleNamespace(+ roster=SimpleNamespace(resolve=resolve),+ browser=SimpleNamespace(live=SimpleNamespace(sessions=sessions, ensure=ensure)),+ )++ monkeypatch.setattr(routes, "_runtime", runtime)+ request = SimpleNamespace()+ assert await routes.agent_browser_open("busy", request) == {"open": True, "running": True}+ assert await routes.agent_browser_open("done", request) == {"open": False, "running": False}+ assert await routes.agent_browser_open("idle", request) == {"open": False, "running": False}+ assert ensured == []++async def test_desktop_fetch_stop_still_ends_the_chat(monkeypatch):import asyncio