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): atomic enqueue, ordered prompt, queue routing/inbox/stop fixes (Codex round 5)

cyh8b3ae80b9dc7
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 999c9fbd2..498a7d007 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -957,6 +957,10 @@ class CommandHandlers(BaseHandler):
if not handled:
channel_context = self._get_channel_context(context)
await im_client.send_message(channel_context, f"ℹ️ {self._t('command.stop.noActiveSession')}")
+ # Return whether the backend actually interrupted a turn, so callers
+ # like web ``send-now`` can confirm the stop before cutting in a queued
+ # turn (a falsy result means nothing was interrupted).
+ return bool(handled)
except Exception as e:
logger.error(f"Error sending stop command: {e}", exc_info=True)
@@ -965,3 +969,4 @@ class CommandHandlers(BaseHandler):
context, # Use original context
f"❌ {self._t('error.stopFailed', error=str(e))}",
)
+ return False
diff --git a/core/internal_server.py b/core/internal_server.py
index 384fbb897..29f0fb80e 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -125,14 +125,14 @@ def create_app(controller: "Controller") -> FastAPI:
should_flush = (not cancelled) or (session_id in flush_on_cancel)
flush_on_cancel.discard(session_id)
if should_flush:
- await _flush_queue(session_id, context)
+ await _flush_queue(session_id)
task = asyncio.create_task(_runner(), name="internal-dispatch-async")
if isinstance(session_id, str) and session_id:
in_flight[session_id] = (task, context)
bus.publish("turn.start", {"session_id": session_id})
- async def _flush_queue(session_id: str, context: MessageContext) -> None:
+ async def _flush_queue(session_id: str) -> None:
"""Pop the messages queued while a turn ran, merge them into one
(newline-joined) user message, and run it as the next turn — recursively
draining the queue. Empty queue → no-op. The merge is the user's choice
@@ -145,6 +145,7 @@ def create_app(controller: "Controller") -> FastAPI:
if not session_id:
return
user_row = None
+ inbox_row = None
try:
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -162,15 +163,27 @@ def create_app(controller: "Controller") -> FastAPI:
message_type="user",
text="\n".join(texts),
)
+ inbox_row = messages_service.get_inbox_session(conn, session_id)
except Exception:
logger.exception("queue flush: failed to pop/merge for session=%s", session_id)
return
if user_row is None:
return
- # Surface the flushed (merged) user message + mark the queue empty, then
- # run it as the next turn.
+ # Surface the flushed (merged) user message, bump the inbox card (so other
+ # workbench views re-rank + flip 'replied' without waiting for the next
+ # result — Codex P2), and mark the queue empty.
bus.publish("message.new", user_row)
+ if inbox_row is not None:
+ bus.publish("inbox.session.updated", inbox_row)
bus.publish("queue.updated", {"session_id": session_id})
+ # Rebuild routing from the CURRENT session row so a queued follow-up uses
+ # the session's latest agent / model / effort — the user may have changed
+ # it while the prior (now-finished) turn was running (Codex P2).
+ try:
+ context = _build_session_context(session_id)
+ except Exception:
+ logger.exception("queue flush: failed to build context for session=%s", session_id)
+ return
await _run_turn(session_id, context, user_row.get("text") or "")
@app.get("/internal/health")
@@ -289,15 +302,27 @@ def create_app(controller: "Controller") -> FastAPI:
return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})
session_id = payload.get("session_id")
- # Same one-turn-per-session guard as the streaming path: refuse before
- # starting a task so we never overwrite the running turn's handle (which
- # would orphan it from ``/internal/cancel``).
if isinstance(session_id, str) and session_id:
existing = in_flight.get(session_id)
if existing is not None and not existing[0].done():
+ # A turn is already running → enqueue (send-while-busy). This is
+ # the ATOMIC decision point: the in_flight check and the
+ # mark-queued below have no ``await`` between them, so on the
+ # single-threaded loop the running turn can't end + flush in the
+ # gap (which would orphan the row). The UI persisted the user row
+ # before dispatching, so we just re-type it as queued; it flushes
+ # when the current turn ends.
+ user_message_id = payload.get("user_message_id")
+ if isinstance(user_message_id, str) and user_message_id:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ messages_service.mark_queued(conn, user_message_id)
return JSONResponse(
- status_code=409,
- content={"ok": False, "code": "turn_in_progress", "session_id": session_id},
+ status_code=202,
+ content={"ok": True, "queued": True, "session_id": session_id, "message_id": user_message_id},
)
await _run_turn(session_id if isinstance(session_id, str) else None, context, text)
@@ -374,22 +399,28 @@ def create_app(controller: "Controller") -> FastAPI:
entry = in_flight.get(session_id)
if entry is not None and not entry[0].done():
_task, turn_context = entry
- flush_on_cancel.add(session_id)
+ # Interrupt the running turn FIRST and only opt into flush-on-cancel
+ # once the backend stop is CONFIRMED — a best-effort stop that didn't
+ # actually interrupt the agent must not start the queued turn, or two
+ # turns would overlap and the first turn's late output could land
+ # after the cut-in (Codex P2). If the stop didn't take, leave the turn
+ # + queue untouched and report it.
+ stopped = False
try:
- await controller.command_handler.handle_stop(turn_context)
+ stopped = bool(await controller.command_handler.handle_stop(turn_context))
except Exception:
logger.exception("internal send-now: backend stop failed for session=%s", session_id)
+ if not stopped:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "stop_failed", "session_id": session_id},
+ )
+ flush_on_cancel.add(session_id)
_task.cancel()
return {"ok": True, "session_id": session_id, "status": "interrupted"}
- # No running turn — flush the queue directly as a new turn.
- try:
- context = _build_session_context(session_id)
- except Exception as err:
- return JSONResponse(
- status_code=404,
- content={"ok": False, "code": "session_not_found", "detail": str(err)},
- )
- await _flush_queue(session_id, context)
+ # No running turn — flush the queue directly as a new turn (it rebuilds
+ # the routing context from the current session row internally).
+ await _flush_queue(session_id)
return {"ok": True, "session_id": session_id, "status": "flushed"}
return app
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 0ba8bd5c8..ee1c58f58 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -239,17 +239,41 @@ def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
- """Read the session's queued messages (oldest first) and delete them within
- the caller's transaction. Returns the popped rows for the caller to merge +
- dispatch; empty list when the queue is empty."""
- rows = list_queued(conn, session_id)
- if rows:
- conn.execute(
- delete(messages).where(messages.c.session_id == session_id).where(messages.c.type == QUEUED_TYPE)
- )
+ """Atomically claim the session's queued messages: delete them and return
+ what was actually deleted (oldest first), so two racing flushers can't both
+ dispatch the same rows (Codex P2). Uses ``DELETE ... RETURNING`` so the
+ read + delete are one statement; empty list when the queue is empty.
+ """
+ stmt = (
+ delete(messages)
+ .where(messages.c.session_id == session_id)
+ .where(messages.c.type == QUEUED_TYPE)
+ .returning(messages)
+ )
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(stmt).mappings().all()]
+ # RETURNING doesn't guarantee order; restore the queue order the caller relies
+ # on for the newline merge.
+ rows.sort(key=lambda r: (r.get("created_at") or "", r.get("id") or ""))
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.
+ """
+ result = conn.execute(
+ update(messages)
+ .where(messages.c.id == message_id)
+ .where(messages.c.type == "user")
+ .values(type=QUEUED_TYPE)
+ )
+ return bool(result.rowcount)
+
+
def remove_queued(conn: Connection, message_id: str) -> bool:
"""Delete one queued message by id. Returns True if a row was removed."""
result = conn.execute(
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index b33cef92d..e4830c472 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -461,10 +461,34 @@ def test_dispatch_async_starts_turn_and_returns_202():
assert events == ["turn.start", "turn.end"], "publishes session turn lifecycle on the bus"
-def test_dispatch_async_refuses_concurrent_turn_with_409():
- """A second fire-and-forget dispatch for a session that already has a turn
- in flight is refused with 409 and never starts a competing agent turn — the
- same one-turn-per-session guard as the streaming path."""
+def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
+ """A dispatch for a session that already has a turn in flight ENQUEUES
+ (send-while-busy) instead of refusing: it atomically re-types the
+ pre-persisted user row as queued and returns 202 {queued}, and never starts
+ a competing agent turn. The row flushes when the running turn ends."""
+ from core.services import sessions as sessions_service
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_enq", now="2026-05-31T00:00:00Z"
+ )
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ # The UI persists the user row before dispatching.
+ 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",
+ )
+ session_id = session["id"]
+
controller = _build_controller_double()
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
@@ -474,21 +498,29 @@ def test_dispatch_async_refuses_concurrent_turn_with_409():
await asyncio.sleep(60)
task = asyncio.create_task(_busy())
- app.state.in_flight_dispatches["ses_b"] = (
+ app.state.in_flight_dispatches[session_id] = (
task,
MessageContext(user_id="U", channel_id="C", platform="avibe"),
)
try:
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_b", "text": "hi"})
+ resp = await client.post(
+ "/internal/dispatch_async",
+ json={"session_id": session_id, "text": "while busy", "user_message_id": user_row["id"]},
+ )
finally:
task.cancel()
return resp
resp = asyncio.run(_go())
- assert resp.status_code == 409
- assert resp.json()["code"] == "turn_in_progress"
+ assert resp.status_code == 202
+ assert resp.json()["queued"] is True
controller.message_handler.handle_user_message.assert_not_awaited()
+ with engine.connect() as conn:
+ # The row was atomically re-typed to queued (now out of the transcript).
+ assert [q["text"] for q in messages_service.list_queued(conn, session_id)] == ["while busy"]
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert transcript["messages"] == []
def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 532c2f228..2fd07fe66 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -166,20 +166,16 @@ def test_non_stream_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
def test_non_stream_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
- """A bare POST while a turn is already running (controller returns 409) is
- ENQUEUED (send-while-busy) instead of dropped: the row persists as type
- 'queued' (out of the transcript), the response is 202 with queued=true, and
- NO transcript 'user' row is created for it."""
+ """When the controller reports a turn already running (202 {queued}), the
+ route persists the user row, hands its id to the controller to re-type as
+ queued, and returns 202 {queued:true} marked as the queued type. (The actual
+ re-type is the controller's atomic job, covered in test_internal_server.)"""
- from storage import messages_service
- from storage.db import create_sqlite_engine
from vibe.ui_server import app
_, session_id = _make_session(tmp_path)
- dispatch_mock = AsyncMock(
- return_value={"status_code": 409, "body": {"ok": False, "code": "turn_in_progress"}}
- )
+ dispatch_mock = AsyncMock(return_value={"status_code": 202, "body": {"ok": True, "queued": True}})
with patch("vibe.internal_client.dispatch_async", dispatch_mock):
client = app.test_client()
headers = csrf_headers(client)
@@ -193,15 +189,11 @@ def test_non_stream_route_enqueues_when_turn_in_progress(isolated_state, tmp_pat
assert body["queued"] is True
assert body["type"] == "queued"
assert body["text"] == "while busy"
-
- engine = create_sqlite_engine()
- with engine.connect() as conn:
- queued = messages_service.list_queued(conn, session_id)
- transcript = messages_service.list_session_messages(
- conn, session_id=session_id, types=("user", "result", "notify")
- )
- assert [q["text"] for q in queued] == ["while busy"]
- assert transcript["messages"] == [], "a busy send must not create a transcript user row"
+ # The user row was persisted first, and its id handed to the controller to
+ # re-type as queued (atomic, no second row).
+ dispatch_mock.assert_awaited_once()
+ sent = dispatch_mock.await_args.args[0]
+ assert sent["user_message_id"] == body["id"]
def test_create_session_without_backend_defers_to_default_agent(isolated_state, tmp_path):
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 43af6ab44..4b4a6dd7d 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -451,7 +451,10 @@ export const ChatPage: React.FC = () => {
<Transcript messages={messages} session={session} working={working} />
<QueueStrip queue={queue} onRemove={removeQueued} onSendNow={sendQueueNow} />
+ {/* key by session so the composer remounts per session — its draft-seeding
+ + local value reset, instead of carrying across sessions (Codex P2). */}
<Compose
+ key={sessionId}
onSend={sendMessage}
onStop={stopMessage}
busy={working}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index dc6574f9e..3219281b2 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3079,10 +3079,12 @@ async def sessions_messages_create(session_id: str):
or ""
)
- def _persist_user_message() -> dict:
- """Persist the user's row, fan it out (message.new + activity + inbox
- bump), and clear any saved draft. Shared by the streaming path and the
- non-streaming turn-started path."""
+ 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."""
with engine.begin() as conn:
row = messages_service.append(
conn,
@@ -3100,15 +3102,17 @@ async def sessions_messages_create(session_id: str):
)
messages_service.clear_draft(conn, session_id)
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."""
broker.publish("message.new", row)
broker.publish(
"session.activity",
{"session_id": session_id, "scope_id": session["scope_id"], "event": "user_message"},
)
- # Bump the session's inbox card for the user's own reply. 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 — publish
- # in-process. No-op until the session has a result.
try:
with engine.connect() as conn:
inbox_row = messages_service.get_inbox_session(conn, session_id, platform="avibe")
@@ -3116,54 +3120,60 @@ 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 row
-
- dispatch_payload = {
- "session_id": session_id,
- "text": dispatch_text,
- "scope_id": session["scope_id"],
- }
if request.args.get("stream") != "1":
- # Content-only message (an attachment with no text): there's nothing for
- # the agent to run and the dispatch endpoint requires non-empty text, so
- # just persist + publish the row (the pre-dispatch behavior) without
- # starting a turn (Codex P2).
+ # 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.
+ 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.
if not dispatch_text.strip():
- return jsonify(_persist_user_message()), 201
+ _publish_user_row(message)
+ return jsonify(message), 201
# Session/page-scoped model (the default web Chat): fire-and-forget the
- # turn; the reply arrives over ``message.new``. Dispatch FIRST so the
- # controller's in_flight check is the single source of truth — 202 →
- # start the turn + persist the user row; 409 (a turn is already running)
- # → ENQUEUE the message (send-while-busy) so it flushes when the current
- # turn ends, rather than dropping it. Dispatching before persisting
- # avoids a user row + a queued row both existing for one message.
+ # 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.
+ dispatch_payload = {
+ "session_id": session_id,
+ "text": dispatch_text,
+ "scope_id": session["scope_id"],
+ "user_message_id": message.get("id"),
+ }
try:
result = await internal_client.dispatch_async(dispatch_payload)
except internal_client.InternalServerUnavailable as exc:
- return jsonify({"error": "internal_unavailable", "detail": str(exc)}), 502
+ # 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
status = result.get("status_code", 500)
- if status == 202:
- return jsonify(_persist_user_message()), 201
- if status == 409:
- with engine.begin() as conn:
- queued = messages_service.enqueue_queued(
- conn,
- scope_id=session["scope_id"],
- session_id=session_id,
- text=dispatch_text,
- author_id=payload.get("author_id"),
- author_name=payload.get("author_name"),
- )
- messages_service.clear_draft(conn, session_id)
+ 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.
broker.publish("queue.updated", {"session_id": session_id, "scope_id": session["scope_id"]})
- return jsonify({**queued, "queued": True}), 202
- return jsonify({"error": "dispatch_failed", "detail": result.get("body")}), 502
+ return jsonify({**message, "type": "queued", "queued": True}), 202
+ if 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_message()
- dispatch_payload["user_message_id"] = message.get("id")
+ message = _persist_user_row()
+ _publish_user_row(message)
+ dispatch_payload = {
+ "session_id": session_id,
+ "text": dispatch_text,
+ "scope_id": session["scope_id"],
+ "user_message_id": message.get("id"),
+ }
async def _proxy_sse():
# ``stream.start`` lets the browser confirm the socket round-trip