Skip to content

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.

fix(society): keep a browser task alive when its tool call times out

rubenluetke10-beep0d3282975b17
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 3a531f52d7..340b4dec27 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -24,6 +24,7 @@ import json
import logging
import re
import shutil
+import time
import uuid
from collections.abc import Callable
from dataclasses import replace
@@ -576,6 +577,7 @@ class AgentChatService:
)
async def _body() -> None:
+ started = time.monotonic()
origin = ChatTurn(
session_id,
turn_id,
@@ -646,7 +648,7 @@ class AgentChatService:
{
"turn_id": turn_id,
"status": "cancelled",
- "duration_ms": 0,
+ "duration_ms": int((time.monotonic() - started) * 1000),
"usage": {},
"error": None,
},
diff --git a/jarvis/society/browser/live.py b/jarvis/society/browser/live.py
index 66675702fa..3a92fd6396 100644
--- a/jarvis/society/browser/live.py
+++ b/jarvis/society/browser/live.py
@@ -21,6 +21,12 @@ from . import install
log = logging.getLogger(__name__)
RPC = Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]
MAX_LINE = 8 * 1024 * 1024
+_BUSY = "This browser is busy or under manual control"
+_PAUSED = (
+ "This browser is paused until you allow the action in the browser panel. "
+ "It is still working. Leave it running and call society_browser again after "
+ "it is allowed. Do not cancel the browser over HTTP."
+)
class LiveUpdates:
@@ -225,6 +231,51 @@ class LiveSession:
self.closed = True
+async def claim_browser(session: LiveSession, chat_session_id: str) -> None:
+ """Reserve the browser, replacing this chat's own unfinished run.
+
+ A client that stops waiting (the three-minute tool deadline) leaves the
+ run holding the lock. The same chat's next call is that abandoned run,
+ so it takes over. A person at the controls, another chat, or a run that
+ is paused for approval stays as it is.
+ """
+ if session.control_owner:
+ raise RuntimeError(_BUSY)
+ if not session.run_lock.locked():
+ return
+ same_chat = bool(chat_session_id) and session.active_chat == chat_session_id
+ if same_chat and "approval" in session.attention:
+ raise RuntimeError(_PAUSED)
+ if same_chat:
+ await _replace_owned_run(session)
+ return
+ if not session.active_chat:
+ # The owner is already leaving; wait out the hand-off instead of
+ # telling the caller the browser is busy.
+ try:
+ async with asyncio.timeout(5):
+ async with session.run_lock:
+ pass
+ except TimeoutError:
+ raise RuntimeError(_BUSY) from None
+ return
+ raise RuntimeError(_BUSY)
+
+
+async def _replace_owned_run(session: LiveSession) -> None:
+ if not session.closed:
+ try:
+ await session.command("cancel", timeout=5)
+ except Exception:
+ log.warning("Could not stop the chat's previous browser task", exc_info=True)
+ try:
+ async with asyncio.timeout(15):
+ async with session.run_lock:
+ pass
+ except TimeoutError:
+ raise RuntimeError(_BUSY) from None
+
+
class LiveSessions:
def __init__(self, data_dir: Path) -> None:
self.data_dir = data_dir
@@ -242,8 +293,13 @@ class LiveSessions:
while len(self.stopped_turns) > 512:
self.stopped_turns.pop(next(iter(self.stopped_turns)))
- async def cancel(self, session: LiveSession) -> dict:
- self.stop_turn(session.agent_id, session.active_trace)
+ async def cancel(self, session: LiveSession, *, end_turn: bool = True) -> dict:
+ # end_turn is the viewer's Stop button. A bare cancel only releases the
+ # browser, so the agent can keep working after its own recovery call.
+ if end_turn:
+ self.stop_turn(session.agent_id, session.active_trace)
+ if session.closed:
+ return {}
return await session.command("cancel")
def release_when_idle(self, session: LiveSession) -> None:
@@ -424,8 +480,9 @@ class LiveSessions:
chat_session_id: str = "",
) -> dict:
session = await self.ensure(agent)
+ await claim_browser(session, chat_session_id)
if session.run_lock.locked() or session.control_owner:
- raise RuntimeError("This browser is busy or under manual control")
+ raise RuntimeError(_BUSY)
async with session.run_lock:
session.rpc = {"llm": llm, "action": action}
session.rpc_context = contextvars.copy_context()
diff --git a/jarvis/society/browser/tool.py b/jarvis/society/browser/tool.py
index 4a583ae3db..b3636fcdce 100644
--- a/jarvis/society/browser/tool.py
+++ b/jarvis/society/browser/tool.py
@@ -109,7 +109,9 @@ class BrowserTool:
"first. This is the live browser shown in your Options rail. Use this tool "
"when the user selects Browser or asks to operate the visible browser, and "
"for web tasks without a suitable connected API. Otherwise prefer a connected "
- "plugin or CLI when one exists for the service."
+ "plugin or CLI when one exists for the service. If your own earlier call is "
+ "still finishing, call this tool again: that run is replaced. If it is waiting "
+ "for approval, leave it running. Do not cancel the browser over HTTP."
)
schema: dict[str, Any] = {
"type": "object",
diff --git a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts
index da4ae4655a..c4782837ca 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts
+++ b/jarvis/ui/web/frontend/src/components/society/card/useBrowserView.ts
@@ -217,7 +217,7 @@ export function useBrowserView(agentId: string) {
const control = useCallback((op: string, args: Record<string, unknown> = {}) => {
if (op === "cancel") {
void fetch("/api/society/agents/" + encodeURIComponent(agentId) + "/browser/cancel",
- { method: "POST" }).then((res) => {
+ { method: "POST", headers: { "X-Jarvis-Stop-Chat": "1" } }).then((res) => {
if (!res.ok) setState((s) => ({ ...s, error: "Browser stop failed: " + res.status }));
}).catch(() => setState((s) => ({ ...s, error: "Browser stop could not connect" })));
return;
diff --git a/jarvis/ui/web/society_browser_routes.py b/jarvis/ui/web/society_browser_routes.py
index 43fdefea57..2ead610a2b 100644
--- a/jarvis/ui/web/society_browser_routes.py
+++ b/jarvis/ui/web/society_browser_routes.py
@@ -108,11 +108,16 @@ async def cancel_agent_browser(agent_id: str, request: Request) -> dict[str, Any
if session is None or session.closed:
return {"cancelled": False}
running = session.run_lock.locked()
- chat_session_id = getattr(session, "active_chat", "") or f"society:{agent.agent_id}"
- await rt.browser.live.cancel(session)
- # The owning chat must also stop; otherwise its planner may try another tool.
+ # The viewer Stop button sends this header and ends the planner too.
+ # A bare POST only releases the browser. The agent calls that bare URL
+ # when a tool client has already given up; ending the chat there is the
+ # turn dying in the middle of the task.
+ headers = getattr(request, "headers", None)
+ stop_chat = bool(headers and headers.get("x-jarvis-stop-chat") == "1")
+ await rt.browser.live.cancel(session, end_turn=stop_chat)
chat = getattr(request.app.state, "agent_chat", None)
- if running and chat is not None:
+ if running and stop_chat and chat is not None:
+ chat_session_id = getattr(session, "active_chat", "") or f"society:{agent.agent_id}"
await chat.cancel(chat_session_id)
return {"cancelled": running}
diff --git a/tests/contract/test_browser_contract.py b/tests/contract/test_browser_contract.py
index e8b7a73fe3..12ba4748b6 100644
--- a/tests/contract/test_browser_contract.py
+++ b/tests/contract/test_browser_contract.py
@@ -124,9 +124,9 @@ async def test_stop_button_also_stops_the_owning_chat(monkeypatch, chat_id):
await lock.acquire()
session = SimpleNamespace(closed=False, run_lock=lock, active_chat=chat_id)
- async def cancel_browser(value):
+ async def cancel_browser(value, *, end_turn=True):
assert value is session
- seen.append("browser")
+ seen.append(("browser", end_turn))
async def cancel_chat(value):
seen.append(value)
@@ -143,11 +143,154 @@ async def test_stop_button_also_stops_the_owning_chat(monkeypatch, chat_id):
)
request = SimpleNamespace(
- app=SimpleNamespace(state=SimpleNamespace(agent_chat=SimpleNamespace(cancel=cancel_chat)))
+ headers={"x-jarvis-stop-chat": "1"},
+ app=SimpleNamespace(state=SimpleNamespace(agent_chat=SimpleNamespace(cancel=cancel_chat))),
)
monkeypatch.setattr(routes, "_runtime", runtime)
assert await routes.cancel_agent_browser("test", request) == {"cancelled": True}
- assert seen == ["browser", chat_id or "society:test"]
+ assert seen == [("browser", True), chat_id or "society:test"]
+
+
+async def test_agent_cancel_releases_the_browser_without_stopping_the_chat(monkeypatch):
+ import asyncio
+
+ from jarvis.ui.web import society_browser_routes as routes
+
+ seen = []
+ lock = asyncio.Lock()
+ await lock.acquire()
+ session = SimpleNamespace(closed=False, run_lock=lock, active_chat="society:test-bot")
+
+ async def cancel_browser(value, *, end_turn=True):
+ seen.append(end_turn)
+
+ async def cancel_chat(value):
+ seen.append(value)
+
+ async def resolve(_):
+ return SimpleNamespace(agent_id="test-bot")
+
+ async def runtime(_):
+ return SimpleNamespace(
+ roster=SimpleNamespace(resolve=resolve),
+ browser=SimpleNamespace(
+ live=SimpleNamespace(sessions={"test-bot": session}, cancel=cancel_browser)
+ ),
+ )
+
+ request = SimpleNamespace(
+ headers={},
+ app=SimpleNamespace(state=SimpleNamespace(agent_chat=SimpleNamespace(cancel=cancel_chat))),
+ )
+ monkeypatch.setattr(routes, "_runtime", runtime)
+ assert await routes.cancel_agent_browser("test-bot", request) == {"cancelled": True}
+ assert seen == [False]
+
+
+async def test_same_chat_replaces_an_abandoned_browser_run():
+ import asyncio
+
+ from jarvis.society.browser.live import claim_browser
+
+ lock = asyncio.Lock()
+ started = asyncio.Event()
+ released = asyncio.Event()
+
+ async def owner():
+ async with lock:
+ started.set()
+ await released.wait()
+
+ task = asyncio.create_task(owner())
+ await started.wait()
+
+ async def command(op, **_kwargs):
+ assert op == "cancel"
+ released.set()
+ return {}
+
+ session = SimpleNamespace(
+ control_owner=None,
+ run_lock=lock,
+ active_chat="society:test-bot",
+ attention={},
+ closed=False,
+ command=command,
+ )
+ await claim_browser(session, "society:test-bot")
+ assert not lock.locked()
+ await task
+
+
+async def test_another_chat_and_manual_control_stay_busy():
+ import asyncio
+
+ from jarvis.society.browser.live import claim_browser
+
+ lock = asyncio.Lock()
+ await lock.acquire()
+ session = SimpleNamespace(
+ control_owner=None,
+ run_lock=lock,
+ active_chat="society:other",
+ attention={},
+ closed=False,
+ )
+ with pytest.raises(RuntimeError, match="busy"):
+ await claim_browser(session, "society:test-bot")
+ session.control_owner = "viewer"
+ session.active_chat = ""
+ lock.release()
+ with pytest.raises(RuntimeError, match="busy"):
+ await claim_browser(session, "society:test-bot")
+
+
+async def test_pending_approval_is_not_replaced():
+ import asyncio
+
+ from jarvis.society.browser.live import claim_browser
+
+ lock = asyncio.Lock()
+ await lock.acquire()
+ called = []
+
+ async def command(op, **_kwargs):
+ called.append(op)
+ return {}
+
+ session = SimpleNamespace(
+ control_owner=None,
+ run_lock=lock,
+ active_chat="society:test-bot",
+ attention={"approval": {"id": "1"}},
+ closed=False,
+ command=command,
+ )
+ with pytest.raises(RuntimeError, match="paused"):
+ await claim_browser(session, "society:test-bot")
+ assert called == []
+ assert lock.locked()
+ lock.release()
+
+
+async def test_bare_cancel_does_not_mark_the_turn_stopped(tmp_path):
+ from jarvis.society.browser.live import LiveSessions
+
+ live = LiveSessions(tmp_path)
+ called = []
+
+ async def command(op, **_kwargs):
+ called.append(op)
+ return {}
+
+ session = SimpleNamespace(
+ agent_id="test-bot", active_trace="trace-1", closed=False, command=command
+ )
+ await live.cancel(session, end_turn=False)
+ assert called == ["cancel"]
+ assert ("test-bot", "trace-1") not in live.stopped_turns
+ await live.cancel(session, end_turn=True)
+ assert ("test-bot", "trace-1") in live.stopped_turns
async def test_jarvis_chat_uses_the_lead_browser_with_its_selected_model(tmp_path, monkeypatch):