Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(workbench): round-22 Codex P2 — facade-compatible bind, pre-bind reserved-id guard, claimed-id queue delete

cyh919faab9b274
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index e81d4a13f..3a4f8025d 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -1052,6 +1052,18 @@ class SessionHandler(BaseHandler):
agent_name: str,
session_anchor: str,
) -> Optional[str]:
+ # avibe: pin the reserved workbench row id before any hidden-row creation
+ # (mirrors BaseAgent.ensure_agent_session_id) so a pre-bind setup/query
+ # failure persists the terminal notify under the OPEN Chat session rather
+ # than a freshly-minted hidden row the page never sees (Codex P2).
+ target = (getattr(context, "platform_specific", None) or {}).get("agent_session_target")
+ if isinstance(target, dict) and target.get("id"):
+ reserved_id = str(target["id"]).strip()
+ if reserved_id:
+ payload = dict(context.platform_specific or {})
+ payload["agent_session_id"] = reserved_id
+ context.platform_specific = payload
+ return reserved_id
ensure = getattr(self.sessions, "ensure_agent_session_id", None)
if callable(ensure):
agent_session_id = ensure(session_key, agent_name, session_anchor)
diff --git a/modules/agents/base.py b/modules/agents/base.py
index b00c7e92b..0dbeda561 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -97,6 +97,14 @@ class BaseAgent(ABC):
session_anchor: Optional[str] = None,
) -> Optional[str]:
"""Ensure the Vibe-owned public session id exists on the request context."""
+ # avibe: pin the reserved workbench row id BEFORE any pre-bind ensure can
+ # mint a hidden row and overwrite it. Without this, a setup/start failure
+ # between this ensure and the later native bind would persist the terminal
+ # notify under the hidden id and the open Chat would never see it (Codex P2).
+ reserved_id = self._reserved_agent_session_id(request.context)
+ if reserved_id:
+ self._pin_agent_session_id(request.context, reserved_id)
+ return reserved_id
anchor = session_anchor or request.base_session_id
sessions = getattr(self, "sessions", None)
ensure = getattr(sessions, "ensure_agent_session_id", None)
@@ -126,6 +134,26 @@ class BaseAgent(ABC):
request.context.platform_specific = payload
return agent_session_id
+ @staticmethod
+ def _reserved_agent_session_id(context: Any) -> Optional[str]:
+ """The open Chat session's ``agent_sessions`` PK reserved for an avibe turn.
+
+ avibe dispatch stamps ``platform_specific['agent_session_target']['id']``;
+ IM/CLI turns have no target. Used to keep Claude/Codex replies attributed to
+ the open Chat session instead of a freshly-minted hidden row (Codex P1)."""
+ payload = getattr(context, "platform_specific", None) or {}
+ target = payload.get("agent_session_target")
+ if isinstance(target, dict) and target.get("id"):
+ reserved = str(target["id"]).strip()
+ return reserved or None
+ return None
+
+ @staticmethod
+ def _pin_agent_session_id(context: Any, agent_session_id: str) -> None:
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ payload["agent_session_id"] = agent_session_id
+ context.platform_specific = payload
+
def _bind_reserved_workbench_session(
self,
context: Any,
@@ -135,20 +163,15 @@ class BaseAgent(ABC):
) -> Optional[str]:
"""Bind the backend-native id to the RESERVED workbench session row, by id.
- An avibe turn stamps ``platform_specific['agent_session_target']['id']``
- with the open Chat session's ``agent_sessions`` PK. Claude/Codex must bind
- the native session to THAT row (like OpenCode's ``bind_agent_session_by_id``)
- instead of letting the generic ``bind_agent_session`` mint a fresh row and
- overwrite ``agent_session_id`` — otherwise ``persist_agent_message`` would
- publish ``message.new`` under the new hidden id and the reply would never
- reach the open Chat page (Codex P1). Returns the reserved id when this is an
- avibe turn (so the caller skips its normal binder), else ``None``.
+ Claude/Codex must bind the native session to the reserved workbench row
+ (like OpenCode's ``bind_agent_session_by_id``) instead of letting the
+ generic ``bind_agent_session`` mint a fresh row and overwrite
+ ``agent_session_id`` — otherwise ``persist_agent_message`` would publish
+ ``message.new`` under the new hidden id and the reply would never reach the
+ open Chat page (Codex P1). Returns the reserved id when this is an avibe
+ turn (so the caller skips its normal binder), else ``None``.
"""
- payload = getattr(context, "platform_specific", None) or {}
- target = payload.get("agent_session_target")
- reserved_id = ""
- if isinstance(target, dict) and target.get("id"):
- reserved_id = str(target["id"]).strip()
+ reserved_id = self._reserved_agent_session_id(context)
if not reserved_id:
return None
sessions = getattr(self, "sessions", None)
@@ -156,20 +179,18 @@ class BaseAgent(ABC):
bound: Optional[str] = None
if callable(bind_by_id):
try:
- bound = bind_by_id(
- session_id=reserved_id,
- native_session_id=native_session_id,
- workdir=working_path,
- )
+ # Positional (session_id, native_session_id) — the SessionsFacade
+ # binds by a positional ``agent_session_id``, NOT a keyword, so a
+ # ``session_id=`` call would TypeError and silently skip recording
+ # the native id (Codex P2). Mirrors the OpenCode call.
+ bound = bind_by_id(reserved_id, native_session_id, workdir=working_path)
except Exception:
logger.debug("bind_agent_session_by_id failed; keeping reserved id", exc_info=True)
- # Keep ``agent_session_id`` pinned to the reserved workbench row even if the
- # by-id bind couldn't record the native id — the publish target is what
- # matters for the open Chat page.
+ # Pin ``agent_session_id`` to the reserved row even if the by-id bind
+ # couldn't record the native id — the publish target is what matters for
+ # the open Chat page.
new_id = bound or reserved_id
- new_payload = dict(payload)
- new_payload["agent_session_id"] = new_id
- context.platform_specific = new_payload
+ self._pin_agent_session_id(context, new_id)
return new_id
def bind_agent_session_id(
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 1cd4d8e8e..f619d36ff 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -269,9 +269,13 @@ def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
SQLite >= 3.35, which the project does not pin, so on an older libsqlite the
flush would raise — ``_flush_queue`` returns False and the send-while-busy
queue never dispatches, stranding the user's queued follow-up (Codex P2).
- Atomic in practice: the local service is the single writer and this runs as
- one synchronous transaction, so no concurrent flush interleaves between the
- read and the delete (which is what the original RETURNING claim guarded).
+
+ The DELETE is scoped to the CLAIMED row ids (not a broad session+type
+ predicate): the UI server is a SEPARATE writer that can promote a just-sent
+ prompt to ``queued`` between the SELECT and the DELETE, and a broad delete
+ would drop that newer row without returning it — losing the user's message.
+ Deleting only the ids we actually read leaves any concurrently-enqueued row
+ for the next flush (Codex P2).
"""
rows_q = (
select(messages)
@@ -282,11 +286,8 @@ def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
rows = [_row_to_payload(dict(row)) for row in conn.execute(rows_q).mappings().all()]
if not rows:
return []
- conn.execute(
- delete(messages)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == QUEUED_TYPE)
- )
+ claimed_ids = [r["id"] for r in rows]
+ conn.execute(delete(messages).where(messages.c.id.in_(claimed_ids)))
return rows
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 5a2bea543..a319d48b9 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -851,11 +851,22 @@ class AdoptPendingTurnTokenTests(unittest.TestCase):
self.assertEqual(ctx.platform_specific["turn_token"], "T1")
+class _FakeBaseAgent(BaseAgent):
+ """Minimal concrete BaseAgent so the shared session-binding helpers resolve
+ normally (proper ``self`` method lookup), without a real controller."""
+
+ def __init__(self, sessions, name="claude"):
+ self.sessions = sessions
+ self.name = name
+
+ async def handle_message(self, request): # pragma: no cover - abstract stub
+ return None
+
+
class BindReservedWorkbenchSessionTests(unittest.TestCase):
- """``BaseAgent._bind_reserved_workbench_session`` keeps Claude/Codex avibe
- replies attributed to the OPEN Chat session (the reserved workbench row),
- instead of a freshly-minted hidden row, so ``message.new`` reaches the page
- (Codex P1)."""
+ """``BaseAgent`` keeps Claude/Codex avibe replies attributed to the OPEN Chat
+ session (the reserved workbench row), instead of a freshly-minted hidden row,
+ so ``message.new`` reaches the page (Codex P1/P2)."""
@staticmethod
def _ctx(target_id):
@@ -867,30 +878,50 @@ class BindReservedWorkbenchSessionTests(unittest.TestCase):
def test_avibe_turn_binds_by_reserved_id_and_pins_agent_session_id(self):
calls = {}
- def bind_by_id(*, session_id, native_session_id, workdir=None):
- calls.update(session_id=session_id, native=native_session_id, workdir=workdir)
- return session_id # the reserved row exists → rowcount 1
+ # SessionsFacade.bind_agent_session_by_id takes (agent_session_id,
+ # native_session_id) POSITIONALLY — a session_id= keyword call would
+ # TypeError and silently skip recording the native id (Codex P2).
+ def bind_by_id(agent_session_id, native_session_id, workdir=None):
+ calls.update(session_id=agent_session_id, native=native_session_id, workdir=workdir)
+ return agent_session_id # the reserved row exists → rowcount 1
- fake_self = SimpleNamespace(sessions=SimpleNamespace(bind_agent_session_by_id=bind_by_id))
+ agent = _FakeBaseAgent(SimpleNamespace(bind_agent_session_by_id=bind_by_id))
ctx = self._ctx("ses_workbench")
- ret = BaseAgent._bind_reserved_workbench_session(fake_self, ctx, "claude-native-123", working_path="/tmp/x")
+ ret = agent._bind_reserved_workbench_session(ctx, "claude-native-123", working_path="/tmp/x")
self.assertEqual(ret, "ses_workbench")
self.assertEqual(ctx.platform_specific["agent_session_id"], "ses_workbench")
self.assertEqual(calls, {"session_id": "ses_workbench", "native": "claude-native-123", "workdir": "/tmp/x"})
def test_im_turn_without_target_falls_through(self):
- fake_self = SimpleNamespace(sessions=SimpleNamespace(bind_agent_session_by_id=lambda **k: None))
+ agent = _FakeBaseAgent(SimpleNamespace(bind_agent_session_by_id=lambda *a, **k: None))
ctx = self._ctx(None)
- self.assertIsNone(BaseAgent._bind_reserved_workbench_session(fake_self, ctx, "native"))
+ self.assertIsNone(agent._bind_reserved_workbench_session(ctx, "native"))
# untouched → caller runs its normal binder
self.assertEqual(ctx.platform_specific["agent_session_id"], "from_build")
def test_pins_reserved_id_even_without_bind_by_id_support(self):
- fake_self = SimpleNamespace(sessions=SimpleNamespace()) # no bind_agent_session_by_id
+ agent = _FakeBaseAgent(SimpleNamespace()) # no bind_agent_session_by_id
+ ctx = self._ctx("ses_wb")
+ ret = agent._bind_reserved_workbench_session(ctx, "native")
+ self.assertEqual(ret, "ses_wb")
+ self.assertEqual(ctx.platform_specific["agent_session_id"], "ses_wb")
+
+ def test_ensure_pins_reserved_id_without_minting_hidden_row(self):
+ # #402: the PRE-bind ensure must also reuse the reserved id, or a setup
+ # failure before the native bind would persist the notify under a hidden row.
+ ensure_calls = []
+
+ def ensure(*a, **k):
+ ensure_calls.append((a, k))
+ return "hidden_new_row"
+
+ agent = _FakeBaseAgent(SimpleNamespace(ensure_agent_session_id=ensure))
ctx = self._ctx("ses_wb")
- ret = BaseAgent._bind_reserved_workbench_session(fake_self, ctx, "native")
+ request = SimpleNamespace(context=ctx, base_session_id="anchor", vibe_agent_id=None, vibe_agent_name=None)
+ ret = agent.ensure_agent_session_id(request)
self.assertEqual(ret, "ses_wb")
self.assertEqual(ctx.platform_specific["agent_session_id"], "ses_wb")
+ self.assertEqual(ensure_calls, [], "must not mint a hidden row when a workbench id is reserved")
if __name__ == "__main__":