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): hide pre-dispatch rows behind a pending type + guard loads by session (Codex round 7)
cyhe5bb67b455bb
diff --git a/core/internal_server.py b/core/internal_server.pyindex d3aecaad1..42fde8a8f 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -324,7 +324,7 @@ def create_app(controller: "Controller") -> FastAPI:user_message_id = payload.get("user_message_id")if isinstance(user_message_id, str) and user_message_id:with engine.begin() as conn:- messages_service.mark_queued(conn, user_message_id)+ messages_service.promote_pending(conn, user_message_id, messages_service.QUEUED_TYPE)# Idle + pre-existing queue → no running turn to flush behind, so# drain the whole queue (this row included) now, in order.if not busy:diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 5c9a3454e..69171bc33 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -201,6 +201,15 @@ def list_session_messages(QUEUED_TYPE = "queued"DRAFT_TYPE = "draft"+# A reserved-but-not-yet-accepted user row: persisted BEFORE dispatch (so it+# reserves its (created_at, id) for correct ordering) but hidden from the+# transcript, the queue AND the inbox until the controller decides whether the+# turn started (→ promote to 'user') or must be queued (→ promote to 'queued').+# This stops another tab from briefly seeing the row as a sent prompt during the+# dispatch window (Codex P2).+PENDING_TYPE = "pending"+# Ephemeral types that must never count as inbox activity / conversation.+NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE)def enqueue_queued(@@ -257,19 +266,19 @@ def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:return rows-def mark_queued(conn: Connection, message_id: str) -> bool:- """Flip a freshly-persisted ``user`` row to ``queued`` (send-while-busy).-- Lets the user row be reserved BEFORE dispatch (so its ``(created_at, id)``- precedes any fast reply — correct transcript order) and then atomically- re-typed as queued when the controller finds a turn already running, instead- of writing a second row. Returns True if a row was re-typed.+def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:+ """Promote a reserved ``pending`` row to its decided type — ``user`` once the+ turn is accepted, or ``queued`` when a turn is already running. The row is+ persisted as ``pending`` BEFORE dispatch (reserving its (created_at, id) for+ correct ordering) and stays hidden until this promotes it, so no other tab+ can briefly see it as a sent prompt during the dispatch window. Returns True+ if a pending row was promoted."""result = conn.execute(update(messages).where(messages.c.id == message_id)- .where(messages.c.type == "user")- .values(type=QUEUED_TYPE)+ .where(messages.c.type == PENDING_TYPE)+ .values(type=to_type))return bool(result.rowcount)@@ -419,7 +428,7 @@ def list_inbox_sessions(.label("rn"),).where(m.c.session_id.is_not(None))- .where(m.c.type.notin_((QUEUED_TYPE, DRAFT_TYPE)))+ .where(m.c.type.notin_(NON_CONVERSATION_TYPES)))if platform is not None:any_ranked = any_ranked.where(m.c.platform == platform)diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 2086f18b9..c893c6b32 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -488,10 +488,11 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):session = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude", agent_name="worker")- # The UI persists the user row before dispatching.+ # The UI reserves the user row as 'pending' before dispatching; the+ # controller promotes it to 'queued' when it finds a turn in flight.user_row = messages_service.append(conn, scope_id=scope_id, session_id=session["id"], platform="avibe", author="user",- source="user", message_type="user", text="while busy",+ source="user", message_type=messages_service.PENDING_TYPE, text="while busy",)session_id = session["id"]diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex c678ee516..aeaa82f67 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -98,6 +98,12 @@ export const ChatPage: React.FC = () => {// Latest appended message id — the cursor for reconciling durable storage// after a missed-event window (see ``reconcile``).const lastIdRef = useRef<string | null>(null);+ // The session the component is currently on. Async loads capture their+ // request's sessionId and compare against this before committing state, so a+ // load that resolves after the user switched chats can't leak the previous+ // session's rows into the current one (Codex P2).+ const sessionIdRef = useRef(sessionId);+ sessionIdRef.current = sessionId;const appendMessage = useCallback((msg: WorkbenchMessage) => {// Dedupe by id (a sent user row is appended optimistically AND echoed over@@ -124,6 +130,7 @@ export const ChatPage: React.FC = () => {const after = lastIdRef.current;try {const res = await api.listSessionMessages(sessionId, after ? { afterId: after, limit: 50 } : { limit: 50 });+ if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetchconst fresh = res.messages.filter(isTranscriptMessage);if (fresh.length) {setMessages((prev) => mergeById(prev, fresh));@@ -145,6 +152,7 @@ export const ChatPage: React.FC = () => {if (!sessionId) return;try {const res = await api.listSessionQueue(sessionId);+ if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetchsetQueue(res.queued ?? []);} catch {/* leave the last-known queue; the next queue.updated refetches */@@ -199,6 +207,8 @@ export const ChatPage: React.FC = () => {api.listSessionQueue(sessionId),api.getSessionDraft(sessionId),]);+ // Dropped if the user switched chats while this load was in flight.+ if (sessionId !== sessionIdRef.current) return;setSession(fetched);setAgents(agentList.agents);// Merge (not replace) so a row that arrived over the stream during thediff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 2ed454119..432f2d819 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3080,11 +3080,12 @@ async def sessions_messages_create(session_id: str):)def _persist_user_row() -> dict:- """Persist the user's row + clear any saved draft, WITHOUT publishing —- so the row reserves its ``(created_at, id)`` BEFORE the turn dispatches- and a fast reply can't sort ahead of its prompt (Codex P2). The caller- publishes (or, when the row is enqueued, re-types it) once it knows the- dispatch outcome."""+ """Reserve the user's row as ``pending`` (hidden from transcript/queue/+ inbox) + clear any saved draft, WITHOUT publishing. This locks the row's+ ``(created_at, id)`` BEFORE the turn dispatches (so a fast reply can't+ sort ahead of its prompt) yet keeps it invisible during the dispatch+ window, so another tab can't briefly see it as a sent prompt (Codex P2).+ The caller promotes it (→ user / queued) once the outcome is known."""with engine.begin() as conn:row = messages_service.append(conn,@@ -3093,7 +3094,7 @@ async def sessions_messages_create(session_id: str):platform="avibe",author="user",source="user",- message_type="user",+ message_type=messages_service.PENDING_TYPE,text=text if isinstance(text, str) else None,content=content if isinstance(content, dict) else None,metadata=payload.get("metadata") or {},@@ -3104,10 +3105,15 @@ async def sessions_messages_create(session_id: str):workbench_sessions_service.touch_session(conn, session_id)return row- def _publish_user_row(row: dict) -> None:- """Fan a persisted user row out: message.new + activity + inbox bump.- The agent-reply side rides the controller→browser bridge, but the user- row is persisted in this UI process so the controller bus never sees it."""+ def _promote_and_publish(row: dict) -> dict:+ """Promote the reserved pending row to a transcript-visible ``user`` row+ and fan it out (message.new + activity + inbox bump). Returns the row+ with its type corrected. The agent-reply side rides the controller→+ browser bridge, but the user row is persisted in this UI process so the+ controller bus never sees it."""+ with engine.begin() as conn:+ messages_service.promote_pending(conn, row["id"], "user")+ row = {**row, "type": "user"}broker.publish("message.new", row)broker.publish("session.activity",@@ -3120,21 +3126,21 @@ async def sessions_messages_create(session_id: str):broker.publish("inbox.session.updated", inbox_row)except Exception:logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)+ return rowif request.args.get("stream") != "1":- # Persist the user row FIRST (reserves created_at/id before any reply can- # be produced), then decide what to do with it by the dispatch outcome.+ # Reserve the row FIRST (pending), then decide by the dispatch outcome.message = _persist_user_row()# Content-only message (attachment, no text): nothing to run + the- # dispatch endpoint requires text, so just publish the row, no turn.+ # dispatch endpoint requires text, so just promote + publish, no turn.if not dispatch_text.strip():- _publish_user_row(message)- return jsonify(message), 201+ return jsonify(_promote_and_publish(message)), 201# Session/page-scoped model (the default web Chat): fire-and-forget the# turn; the reply arrives over ``message.new``. The controller atomically- # either starts the turn or — if one is already running — re-types this- # row as queued (send-while-busy), so we never write a second row and- # there's no enqueue/flush race.+ # either lets the turn start (we then promote the row to user) or — if a+ # turn is already running — promotes this row to queued itself+ # (send-while-busy), so we never write a second row and there's no+ # enqueue/flush race and no transcript flash.dispatch_payload = {"session_id": session_id,"text": dispatch_text,@@ -3144,30 +3150,28 @@ async def sessions_messages_create(session_id: str):try:result = await internal_client.dispatch_async(dispatch_payload)except internal_client.InternalServerUnavailable as exc:- # Couldn't reach the controller — surface the (already persisted) row- # so the user sees their message, plus the failure.- _publish_user_row(message)- return jsonify({**message, "dispatch_error": "internal_unavailable", "detail": str(exc)}), 502+ # Couldn't reach the controller — promote + surface the row so the+ # user still sees their message, plus the failure.+ published = _promote_and_publish(message)+ return jsonify({**published, "dispatch_error": "internal_unavailable", "detail": str(exc)}), 502status = result.get("status_code", 500)body = result.get("body") or {}if status == 202 and body.get("queued"):- # Enqueued behind a running turn: the controller re-typed the row as- # queued, so it stays OUT of the transcript (no message.new); show it- # above the composer via queue.updated.+ # Enqueued behind a running turn: the controller already promoted the+ # row pending→queued, so it stays OUT of the transcript (no+ # message.new); show it above the composer via queue.updated.broker.publish("queue.updated", {"session_id": session_id, "scope_id": session["scope_id"]})return jsonify({**message, "type": "queued", "queued": True}), 202if status == 202:- # Turn started — publish the prompt.- _publish_user_row(message)- return jsonify(message), 201- # Dispatch failed: still show the persisted row + the error.- _publish_user_row(message)- return jsonify({**message, "dispatch_error": "dispatch_failed", "detail": body}), 502-- # Legacy ?stream=1 path (retired in Step 6): persist the user row first, then- # proxy the per-turn SSE stream back to the browser.- message = _persist_user_row()- _publish_user_row(message)+ # Turn started — promote + publish the prompt.+ return jsonify(_promote_and_publish(message)), 201+ # Dispatch failed: still promote + show the row + the error.+ published = _promote_and_publish(message)+ return jsonify({**published, "dispatch_error": "dispatch_failed", "detail": body}), 502++ # Legacy ?stream=1 path (retired in Step 6): reserve + promote + publish the+ # user row first, then proxy the per-turn SSE stream back to the browser.+ message = _promote_and_publish(_persist_user_row())dispatch_payload = {"session_id": session_id,"text": dispatch_text,