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(web): AP-20 mission WS reader discipline and lossless replay handoff

Ruben Lütkefd51d1fa5fc6
diff --git a/jarvis/ui/web/missions_ws_routes.py b/jarvis/ui/web/missions_ws_routes.py
index 75949b6714..fea8bf7027 100644
--- a/jarvis/ui/web/missions_ws_routes.py
+++ b/jarvis/ui/web/missions_ws_routes.py
@@ -177,6 +177,49 @@ class ConnectionManager:
# ---------------------------------------------------------------------------
+async def _drain_client_frames(ws: WebSocket) -> None:
+ """Reads and discards inbound client frames until the socket closes.
+
+ Reserved for future control frames (pause/resume etc.); today only a
+ ``{"type": "ping"}`` frame is recognized and silently ignored — the
+ server needs no reply since uvicorn handles WS pings itself.
+
+ Module-level (not a closure) so it is unit-testable against a fake
+ ``ws`` duck-typing only ``receive_json()``.
+ """
+ while True:
+ try:
+ msg = await ws.receive_json()
+ except WebSocketDisconnect:
+ return
+ except RuntimeError as exc:
+ # AP-20: an unclean client disconnect raises RuntimeError
+ # ("WebSocket is not connected ...") instead of
+ # WebSocketDisconnect. `continue` here would re-poll the dead
+ # socket forever — treat it as terminal.
+ logger.debug(
+ "missions_ws: reader socket error (%s) — closing", exc
+ )
+ return
+ except ValueError as exc:
+ # Malformed JSON (json.JSONDecodeError is a ValueError) on an
+ # otherwise-live socket — skip the bad frame, keep reading.
+ logger.debug(
+ "missions_ws: client frame decode error (%s) — ignoring",
+ exc,
+ )
+ continue
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "missions_ws: reader unexpected error (%s) — closing", exc
+ )
+ return
+ # Reserved for future control frames (pause/resume etc.).
+ if isinstance(msg, dict) and msg.get("type") == "ping":
+ # Silent pong skip — bus pings are enough.
+ continue
+
+
def _resolve_manager(ws: WebSocket) -> tuple[ConnectionManager, "MissionManager"] | None:
"""Looks up ``missions_ws_manager`` + ``mission_manager`` in app.state."""
app = ws.scope["app"]
@@ -232,41 +275,8 @@ async def missions_ws(ws: WebSocket) -> None:
queue = await conn_mgr.connect(client_id, last_seq, mission_manager.store)
# 2. Reader task (drains client frames without interpreting them).
- async def _reader() -> None:
- while True:
- try:
- msg = await ws.receive_json()
- except WebSocketDisconnect:
- return
- except RuntimeError as exc:
- # AP-20: an unclean client disconnect raises RuntimeError
- # ("WebSocket is not connected ...") instead of
- # WebSocketDisconnect. `continue` here would re-poll the dead
- # socket forever — treat it as terminal.
- logger.debug(
- "missions_ws: reader socket error (%s) — closing", exc
- )
- return
- except ValueError as exc:
- # Malformed JSON (json.JSONDecodeError is a ValueError) on an
- # otherwise-live socket — skip the bad frame, keep reading.
- logger.debug(
- "missions_ws: client frame decode error (%s) — ignoring",
- exc,
- )
- continue
- except Exception as exc: # noqa: BLE001
- logger.warning(
- "missions_ws: reader unexpected error (%s) — closing", exc
- )
- return
- # Reserved for future control frames (pause/resume etc.).
- if isinstance(msg, dict) and msg.get("type") == "ping":
- # Silent pong skip — bus pings are enough.
- continue
-
reader_task = asyncio.create_task(
- _reader(), name=f"missions_ws-reader-{client_id[:8]}"
+ _drain_client_frames(ws), name=f"missions_ws-reader-{client_id[:8]}"
)
# 3. Writer loop. Stop on WS disconnect.
diff --git a/tests/missions/api/test_missions_ws.py b/tests/missions/api/test_missions_ws.py
index 49b93da1ba..52b5bdf693 100644
--- a/tests/missions/api/test_missions_ws.py
+++ b/tests/missions/api/test_missions_ws.py
@@ -1,6 +1,7 @@
"""WebSocket tests for /api/missions/ws (hello + replay + live fanout)."""
from __future__ import annotations
+import asyncio
from pathlib import Path
import pytest
@@ -9,6 +10,7 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
+from jarvis.missions.events import EventEnvelope, MissionDispatched
from jarvis.missions.manager import MissionManager
from jarvis.ui.web.missions_auth import (
issue_token,
@@ -18,10 +20,21 @@ from jarvis.ui.web.missions_auth import (
from jarvis.ui.web.missions_routes import router as missions_router
from jarvis.ui.web.missions_ws_routes import (
ConnectionManager,
+ _drain_client_frames,
router as missions_ws_router,
)
+def _make_envelope(seq: int, mission_id: str = "m1") -> EventEnvelope:
+ return EventEnvelope(
+ seq=seq,
+ mission_id=mission_id,
+ source_actor="system",
+ ts_ms=1,
+ payload=MissionDispatched(prompt=f"p{seq}"),
+ )
+
+
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -155,3 +168,122 @@ def test_ws_live_fanout_after_connect(
assert frame["mission_id"] == mid
assert frame["payload"]["event_type"] == "MissionDispatched"
assert frame["payload"]["prompt"] == "live!"
+
+
+# ---------------------------------------------------------------------------
+# FIX 1 — AP-20: the client-frame reader must never spin on a dead socket
+# ---------------------------------------------------------------------------
+
+
+class _FakeWS:
+ """Duck-types only the ``receive_json`` surface ``_drain_client_frames`` uses."""
+
+ def __init__(self, effects: list) -> None:
+ self._effects = list(effects)
+ self.call_count = 0
+
+ async def receive_json(self):
+ self.call_count += 1
+ effect = self._effects.pop(0)
+ if isinstance(effect, Exception):
+ raise effect
+ return effect
+
+
+async def test_reader_terminates_on_runtime_error_no_spin() -> None:
+ """A RuntimeError (unclean disconnect) must return, not `continue` forever."""
+ ws = _FakeWS([RuntimeError("WebSocket is not connected. Need to call accept.")])
+ await asyncio.wait_for(_drain_client_frames(ws), timeout=1.0)
+ assert ws.call_count == 1
+
+
+async def test_reader_survives_malformed_frame_then_exits_on_disconnect() -> None:
+ """A malformed JSON frame (ValueError) is skipped; a clean disconnect exits."""
+ ws = _FakeWS([ValueError("Expecting value: line 1 column 1"), WebSocketDisconnect(1006)])
+ await asyncio.wait_for(_drain_client_frames(ws), timeout=1.0)
+ assert ws.call_count == 2
+
+
+# ---------------------------------------------------------------------------
+# FIX 2 — replay/registration race + drop-oldest gap notice
+# ---------------------------------------------------------------------------
+
+
+class _RacyStore:
+ """Fires a live event via ``fanout()`` while ``events_since()`` is "in flight".
+
+ Simulates the race the fix closes: a client already registered, but the
+ replay SELECT hasn't returned yet, when a new event is published.
+ """
+
+ def __init__(
+ self,
+ conn_mgr: ConnectionManager,
+ replay: list,
+ live: EventEnvelope | None,
+ ) -> None:
+ self._conn_mgr = conn_mgr
+ self._replay = replay
+ self._live = live
+
+ async def events_since(self, after_seq: int) -> list:
+ if self._live is not None:
+ await self._conn_mgr.fanout(self._live)
+ return list(self._replay)
+
+
+async def test_connect_captures_event_published_during_replay_query() -> None:
+ """An event fired while events_since() is in flight is not lost."""
+ conn_mgr = ConnectionManager()
+ replay = [_make_envelope(1), _make_envelope(2)]
+ live = _make_envelope(3)
+ store = _RacyStore(conn_mgr, replay, live)
+
+ queue = await conn_mgr.connect("client-1", last_seq=0, store=store)
+
+ received = []
+ while not queue.empty():
+ received.append(queue.get_nowait())
+ assert [env.seq for env in received] == [1, 2, 3]
+
+
+async def test_connect_dedupes_event_already_covered_by_replay() -> None:
+ """An event that both the SELECT and the live fanout captured is delivered once."""
+ conn_mgr = ConnectionManager()
+ env = _make_envelope(1)
+ store = _RacyStore(conn_mgr, [env], env)
+
+ queue = await conn_mgr.connect("client-1", last_seq=0, store=store)
+
+ received = []
+ while not queue.empty():
+ received.append(queue.get_nowait())
+ assert len(received) == 1
+ assert received[0].seq == 1
+
+
+async def test_fanout_overflow_emits_one_gap_frame() -> None:
+ """A drop-oldest overflow arms exactly one {"type": "gap"} frame per client.
+
+ maxsize=3: seq 1..3 fill the queue exactly; seq 4 is the single overflow
+ that drops seq 1 and arms the gap notice (which itself then evicts seq 2).
+ """
+ conn_mgr = ConnectionManager()
+ queue: asyncio.Queue = asyncio.Queue(maxsize=3)
+ conn_mgr._clients["client-1"] = queue # noqa: SLF001 - test-only direct wiring
+
+ for seq in range(1, 5):
+ await conn_mgr.fanout(_make_envelope(seq))
+
+ items = []
+ while not queue.empty():
+ items.append(queue.get_nowait())
+ gap_frames = [item for item in items if isinstance(item, dict) and item.get("type") == "gap"]
+ assert len(gap_frames) == 1
+ real_seqs = [item.seq for item in items if isinstance(item, EventEnvelope)]
+ assert real_seqs == [3, 4]
diff --git a/tests/unit/ui/web/test_wiki_ws.py b/tests/unit/ui/web/test_wiki_ws.py
index d26ea80d41..72375e978e 100644
--- a/tests/unit/ui/web/test_wiki_ws.py
+++ b/tests/unit/ui/web/test_wiki_ws.py
@@ -139,6 +139,45 @@ def test_disconnect_unsubscribes_from_bus(client_bus):
)
+def test_disconnect_without_any_event_still_unsubscribes(client_bus):
+ """FIX 3: an idle tab that closes before any wiki event ever fires must
+ still be unsubscribed promptly.
+
+ Before the two-task race (a reader awaiting ``ws.receive_text()``
+ racing the queue forward via ``asyncio.wait``), the forwarding loop
+ only ever woke up on ``queue.get()`` — so a tab closed with no further
+ wiki events left its subscriber (and task) leaked for the rest of the
+ server's lifetime.
+ """
+ client, bus = client_bus
+
+ def _count_subs() -> int:
+ return len(bus._subscribers.get(WikiPageChanged, [])) # noqa: SLF001
+
+ assert _count_subs() == 0
+
+ with client.websocket_connect("/api/wiki/live") as _ws:
+ # Poll for the subscription to become visible before closing, so we
+ # don't race the server coroutine's own startup.
+ deadline = 0
+ while _count_subs() == 0 and deadline < 50:
+ deadline += 1
+ import time as _t
+ _t.sleep(0.02)
+ assert _count_subs() == 1
+
+ # No WikiPageChanged was ever published — the only signal available to
+ # the endpoint is the client closing the socket.
+ deadline = 0
+ while _count_subs() != 0 and deadline < 50:
+ deadline += 1
+ import time as _t
+ _t.sleep(0.05)
+ assert _count_subs() == 0, (
+ "an idle WS with no wiki events must still unsubscribe on disconnect"
+ )
+
+
def test_unrelated_event_does_not_appear(client_bus):
"""Events of a different type are not forwarded."""
from jarvis.core.events import SystemStateChanged