Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): address Codex review round 2 on PR #339
cyhfe9d6ea0e1f4
diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 9e8fa6196..fec4d7485 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -133,11 +133,13 @@ def list_session_messages(and_(messages.c.created_at == anchor, messages.c.id > after_id),))- query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(- min(max(int(limit), 1), 500)- )+ effective_limit = min(max(int(limit), 1), 500)+ query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(effective_limit)rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]- next_after = rows[-1]["id"] if len(rows) == limit else None+ # Compare against the clamped page size; a caller requesting > 500+ # would otherwise receive a full 500-row page with a null cursor and+ # silently stop paginating.+ next_after = rows[-1]["id"] if len(rows) == effective_limit else Nonereturn {"messages": rows, "next_after_id": next_after}@@ -175,11 +177,12 @@ def list_inbox(and_(messages.c.created_at == anchor, messages.c.id < before_id),))- query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(- min(max(int(limit), 1), 200)- )+ effective_limit = min(max(int(limit), 1), 200)+ query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit)rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]- next_before = rows[-1]["id"] if len(rows) == limit else None+ # Same fix as ``list_session_messages``: gate the cursor on the+ # clamped page size, not the raw caller-supplied limit.+ next_before = rows[-1]["id"] if len(rows) == effective_limit else Nonereturn {"messages": rows, "next_before_id": next_before}diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex e5ea4530c..923e1f59b 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -108,17 +108,21 @@ def list_sessions(& (agent_sessions.c.id < before_id)))+ effective_limit = min(max(int(limit), 1), 200)query = (query.order_by(agent_sessions.c.last_active_at.desc(),agent_sessions.c.created_at.desc(),agent_sessions.c.id.desc(),)- .limit(min(max(int(limit), 1), 200))+ .limit(effective_limit))rows = [dict(row) for row in conn.execute(query).mappings().all()]sessions = [_row_to_payload(row) for row in rows]- next_cursor = sessions[-1]["id"] if len(sessions) == limit else None+ # Use the clamped page size for the cursor check — comparing against+ # the raw ``limit`` would emit ``next_before_id=null`` for callers who+ # requested > 200 and force them to stop paginating mid-history.+ next_cursor = sessions[-1]["id"] if len(sessions) == effective_limit else Nonereturn {"sessions": sessions, "next_before_id": next_cursor}diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 6bae06ec1..ea0558d4b 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -135,3 +135,54 @@ def test_mark_session_read_without_anchor_marks_all(isolated_state):with engine.begin() as conn:updated = messages_service.mark_session_read(conn, "ses_all")assert updated == 3+++def test_list_session_messages_cursor_uses_clamped_limit(isolated_state):+ """Regression: callers that pass ``limit > 500`` must still get a+ cursor when the result is a full clamped page, so they can paginate+ past the 500 mark instead of silently truncating at the cap.+ """+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_page")+ # 501 rows so the clamped 500-row page returns full and a+ # follow-up cursor is needed.+ for _ in range(501):+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_page",+ platform="avibe",+ author="agent",+ text="row",+ )++ with engine.connect() as conn:+ page = messages_service.list_session_messages(conn, session_id="ses_page", limit=1000)+ # Pre-fix this returned ``next_after_id=None`` even though there were+ # 501 rows total. The clamp-aware fix emits a cursor.+ assert len(page["messages"]) == 500+ assert page["next_after_id"] is not None+++def test_list_inbox_cursor_uses_clamped_limit(isolated_state):+ """Same regression as the per-session pagination, for the Inbox feed."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_inbox")+ for _ in range(201):+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_inbox",+ platform="avibe",+ author="agent",+ text="ping",+ )++ with engine.connect() as conn:+ page = messages_service.list_inbox(conn, platform="avibe", limit=1000)+ assert len(page["messages"]) == 200+ assert page["next_before_id"] is not Nonediff --git a/tests/test_sse_broker.py b/tests/test_sse_broker.pynew file mode 100644index 000000000..2a5d48d3c--- /dev/null+++ b/tests/test_sse_broker.py@@ -0,0 +1,76 @@+"""Threading invariants for ``vibe.sse_broker.SSEBroker``.++Reviewers flagged that ``publish`` runs from arbitrary threads (sync REST+routes, IM threads) while ``subscribe`` / ``unsubscribe`` mutate the+subscriber map on the event loop thread. A bare ``list(dict.values())``+can raise ``RuntimeError: dictionary changed size during iteration`` and+take down whichever caller was publishing the event. The lock added to+``SSEBroker`` removes that race; this test exercises it under load.+"""++from __future__ import annotations++import asyncio+import sys+import threading+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from vibe.sse_broker import SSEBroker+++def test_publish_survives_concurrent_subscribe_churn():+ broker = SSEBroker()++ # Seed an event loop the broker can reuse — publish() captures it+ # lazily, normally on the first subscribe() call.+ loop = asyncio.new_event_loop()++ def _runner() -> None:+ try:+ loop.run_forever()+ except Exception:+ pass++ runner = threading.Thread(target=_runner, daemon=True)+ runner.start()++ async def _seed_initial_subscriber():+ broker.subscribe()++ asyncio.run_coroutine_threadsafe(_seed_initial_subscriber(), loop).result(timeout=5)++ stop = threading.Event()+ errors: list[BaseException] = []++ def _publisher() -> None:+ try:+ while not stop.is_set():+ broker.publish("ping", {"n": 1})+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)++ publisher = threading.Thread(target=_publisher, daemon=True)+ publisher.start()++ # Hammer subscribe/unsubscribe on the loop thread while the publisher+ # is iterating. Without the lock this reliably trips+ # ``RuntimeError: dictionary changed size during iteration`` within+ # a few hundred churn cycles.+ async def _churn(iterations: int = 800) -> None:+ for _ in range(iterations):+ sub_id, _ = broker.subscribe()+ broker.unsubscribe(sub_id)+ await asyncio.sleep(0)++ asyncio.run_coroutine_threadsafe(_churn(), loop).result(timeout=15)++ stop.set()+ publisher.join(timeout=5)++ loop.call_soon_threadsafe(loop.stop)+ runner.join(timeout=5)+ loop.close()++ assert not errors, f"publish() raised under concurrent churn: {errors!r}"diff --git a/vibe/sse_broker.py b/vibe/sse_broker.pyindex 417c5fe7c..fed5d2293 100644--- a/vibe/sse_broker.py+++ b/vibe/sse_broker.py@@ -24,6 +24,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import threadingimport timefrom typing import Any@@ -35,24 +36,36 @@ class SSEBroker:self._subscribers: dict[int, asyncio.Queue] = {}self._next_id = 0self._loop: asyncio.AbstractEventLoop | None = None+ # ``subscribe`` / ``unsubscribe`` run on the event loop thread while+ # ``publish`` runs from any thread (sync REST routes, IM threads).+ # Plain ``list(dict.values())`` mid-mutation can raise+ # ``RuntimeError: dictionary changed size during iteration``, so we+ # guard the read with a short-held lock.+ self._lock = threading.Lock()def subscribe(self) -> tuple[int, asyncio.Queue]:"""Register a new subscriber. Must be called from an event-loop coroutine."""self._loop = asyncio.get_event_loop()- sub_id = self._next_id- self._next_id += 1queue: asyncio.Queue = asyncio.Queue(maxsize=200)- self._subscribers[sub_id] = queue- logger.debug("SSE subscriber %s connected (total=%s)", sub_id, len(self._subscribers))+ with self._lock:+ sub_id = self._next_id+ self._next_id += 1+ self._subscribers[sub_id] = queue+ total = len(self._subscribers)+ logger.debug("SSE subscriber %s connected (total=%s)", sub_id, total)return sub_id, queuedef unsubscribe(self, sub_id: int) -> None:- if self._subscribers.pop(sub_id, None) is not None:- logger.debug("SSE subscriber %s disconnected (total=%s)", sub_id, len(self._subscribers))+ with self._lock:+ removed = self._subscribers.pop(sub_id, None) is not None+ total = len(self._subscribers)+ if removed:+ logger.debug("SSE subscriber %s disconnected (total=%s)", sub_id, total)def subscriber_count(self) -> int:- return len(self._subscribers)+ with self._lock:+ return len(self._subscribers)def publish(self, event_type: str, data: Any) -> None:"""Fan a JSON event out to every subscriber.@@ -62,12 +75,16 @@ class SSEBroker:"""loop = self._loop- if loop is None or not self._subscribers:+ if loop is None:return+ # Snapshot under the lock so a concurrent subscribe/unsubscribe on+ # the event loop thread cannot mutate the dict mid-iteration.+ with self._lock:+ if not self._subscribers:+ return+ queues = list(self._subscribers.values())payload = json.dumps({"type": event_type, "data": data, "ts": time.time()})- # Snapshot the queue list before scheduling so a concurrent- # unsubscribe during fan-out doesn't drop a publish on the floor.- for queue in list(self._subscribers.values()):+ for queue in queues:try:loop.call_soon_threadsafe(self._put_nowait, queue, event_type, payload)except RuntimeError: