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.

feat(workbench): send-while-busy queue backend — enqueue + flush + queue/draft API (Step 5b/5c)

cyh5e96dd6473fa
diff --git a/core/internal_server.py b/core/internal_server.py
index 2fbbb4134..99c49bf83 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -83,6 +83,81 @@ def create_app(controller: "Controller") -> FastAPI:
in_flight: dict[str, tuple[asyncio.Task, MessageContext]] = {}
app.state.in_flight_dispatches = in_flight
+ async def _noop_chunk(_envelope: dict) -> None:
+ # Chunks are discarded — the browser renders from ``message.new``.
+ return None
+
+ async def _run_turn(session_id: Optional[str], context: MessageContext, text: str) -> None:
+ """Start a fire-and-forget turn and HOLD it open until it settles.
+
+ A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime
+ so ``in_flight`` stays populated (Stop works) and the session-level
+ ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
+ working indicator. On completion the queue is flushed: messages the user
+ sent while this turn ran are merged + run as the next turn. The reply
+ itself reaches the browser over ``message.new``, not a response stream.
+ """
+ from core.inbox_events import bus
+
+ async def _runner() -> None:
+ try:
+ await dispatch_turn(controller, context, text, on_chunk=_noop_chunk)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("internal async dispatch failed for session=%s", session_id)
+ finally:
+ if isinstance(session_id, str):
+ in_flight.pop(session_id, None)
+ bus.publish("turn.end", {"session_id": session_id})
+ await _flush_queue(session_id, context)
+
+ 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:
+ """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
+ (one dispatch, not N); the individual queued rows are deleted by
+ ``pop_queued`` and replaced by the single merged user row."""
+ from core.inbox_events import bus
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ if not session_id:
+ return
+ user_row = None
+ try:
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ rows = messages_service.pop_queued(conn, session_id)
+ texts = [r.get("text") for r in rows if (r.get("text") or "").strip()]
+ if not texts:
+ return
+ user_row = messages_service.append(
+ conn,
+ scope_id=rows[0]["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="\n".join(texts),
+ )
+ 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.
+ bus.publish("message.new", user_row)
+ bus.publish("queue.updated", {"session_id": session_id})
+ await _run_turn(session_id, context, user_row.get("text") or "")
+
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
return {"ok": True, "service": "vibe-remote-internal", "version": 1}
@@ -187,12 +262,10 @@ def create_app(controller: "Controller") -> FastAPI:
returns ``202`` immediately. The reply — plus any notify/result —
reaches the browser over the persistent ``message.new`` session stream
instead, so the HTTP response isn't held open for the turn's duration
- and a closed browser tab can't cancel an in-flight turn.
-
- A no-op ``on_chunk`` is still passed so ``dispatch_turn`` registers a
- turn sink and HOLDS until the turn completes — that keeps ``in_flight``
- populated for the turn's whole lifetime, so the Stop button
- (``/internal/cancel``) can still interrupt the backend.
+ and a closed browser tab can't cancel an in-flight turn. ``_run_turn``
+ holds the turn open (keeping ``in_flight`` populated so Stop works),
+ publishes the turn lifecycle, and flushes the send-while-busy queue when
+ it settles.
"""
payload = await _safe_json(request)
try:
@@ -202,7 +275,7 @@ def create_app(controller: "Controller") -> FastAPI:
session_id = payload.get("session_id")
# Same one-turn-per-session guard as the streaming path: refuse before
- # creating a task so we never overwrite the running turn's handle (which
+ # 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)
@@ -212,36 +285,7 @@ def create_app(controller: "Controller") -> FastAPI:
content={"ok": False, "code": "turn_in_progress", "session_id": session_id},
)
- async def _noop_chunk(_envelope: dict) -> None:
- # Chunks are discarded — the browser renders from ``message.new``.
- return None
-
- # Session-level turn lifecycle for the browser's working indicator. The
- # Chat page can't reliably infer turn end from message rows (a Codex
- # ``system``/``thread.started`` row also persists as ``notify`` mid-turn),
- # so the controller is the authority: publish ``turn.start`` when the turn
- # is accepted and ``turn.end`` when it settles — normal result, agent
- # error/terminal (mark_turn_complete), cancel, or the safety timeout all
- # unblock the held ``dispatch_turn`` and reach the finally below. These
- # ride the same bus→bridge→broker path as ``message.new``.
- from core.inbox_events import bus
-
- async def _runner() -> None:
- try:
- await dispatch_turn(controller, context, text, on_chunk=_noop_chunk)
- except asyncio.CancelledError:
- raise
- except Exception:
- logger.exception("internal async dispatch failed for session=%s", session_id)
- finally:
- if isinstance(session_id, str):
- in_flight.pop(session_id, None)
- bus.publish("turn.end", {"session_id": 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})
+ await _run_turn(session_id if isinstance(session_id, str) else None, context, text)
return JSONResponse(status_code=202, content={"ok": True, "session_id": session_id})
@app.get("/internal/events")
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index f4acdafac..00e7e73db 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -491,6 +491,61 @@ def test_dispatch_async_refuses_concurrent_turn_with_409():
controller.message_handler.handle_user_message.assert_not_awaited()
+def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
+ """When a turn ends, messages queued (send-while-busy) during it are popped,
+ merged (newline-joined) into ONE user row, and run as the next turn —
+ draining the queue. Exercises the controller-side flush wiring end to end."""
+ 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_flush", now="2026-05-31T00:00:00Z"
+ )
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ session_id = session["id"]
+ # Two messages queued while the (about-to-start) turn runs.
+ with engine.begin() as conn:
+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")
+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q2")
+
+ seen_texts: list[str] = []
+
+ async def handler(ctx, text):
+ seen_texts.append(text)
+ controller.mark_turn_complete(ctx) # release each turn immediately
+ return None
+
+ controller = _build_controller_double(handler=handler)
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "first turn"})
+ # Wait for the first turn AND the flush turn to both drain the queue.
+ for _ in range(200):
+ if len(seen_texts) >= 2 and session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+
+ asyncio.run(_go())
+ # First the user's turn, then ONE merged flush turn for the two queued msgs.
+ assert seen_texts == ["first turn", "q1\nq2"]
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert [m["text"] for m in transcript["messages"]] == ["q1\nq2"], "the flush persisted one merged user row"
+
+
def test_cancel_returns_404_when_session_not_in_flight():
app = internal_server.create_app(_build_controller_double())
transport = httpx.ASGITransport(app=app)
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index d004fc8fe..532c2f228 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -165,11 +165,14 @@ def test_non_stream_route_fire_and_forgets_dispatch(isolated_state, tmp_path):
assert sent["text"] == "no stream"
-def test_non_stream_route_returns_409_when_turn_in_progress(isolated_state, tmp_path):
- """A bare POST while a turn is already running for the session surfaces the
- controller's 409 (refused, not started) so the compose box can react — the
- user row is still persisted + published for the transcript."""
+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."""
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
from vibe.ui_server import app
_, session_id = _make_session(tmp_path)
@@ -182,11 +185,23 @@ def test_non_stream_route_returns_409_when_turn_in_progress(isolated_state, tmp_
headers = csrf_headers(client)
response = client.post(
f"/api/sessions/{session_id}/messages",
- json={"text": "second"},
+ json={"text": "while busy"},
headers=headers,
)
- assert response.status_code == 409
- assert response.get_json()["dispatch_error"] == "turn_in_progress"
+ assert response.status_code == 202
+ body = response.get_json()
+ 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"
def test_create_session_without_backend_defers_to_default_agent(isolated_state, tmp_path):
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 15c779fa0..59caccd98 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3068,9 +3068,23 @@ async def sessions_messages_create(session_id: str):
engine = _projects_engine()
try:
- with engine.begin() as conn:
+ with engine.connect() as conn:
session = workbench_sessions_service.get_session(conn, session_id)
- message = messages_service.append(
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+
+ dispatch_text = (
+ (text if isinstance(text, str) else None)
+ or (content.get("text") if isinstance(content, dict) else None)
+ 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."""
+ with engine.begin() as conn:
+ row = messages_service.append(
conn,
scope_id=session["scope_id"],
session_id=session_id,
@@ -3084,53 +3098,66 @@ async def sessions_messages_create(session_id: str):
author_id=payload.get("author_id"),
author_name=payload.get("author_name"),
)
+ messages_service.clear_draft(conn, session_id)
workbench_sessions_service.touch_session(conn, session_id)
- except LookupError as err:
- return jsonify({"error": str(err)}), 404
-
- broker.publish("message.new", message)
- 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: re-rank it to the
- # top and flip the "replied" badge. The agent-reply side of this is covered
- # by the cross-process bridge (controller persists + publishes), but the
- # user message is persisted here in the 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")
- if inbox_row is not None:
- broker.publish("inbox.session.updated", inbox_row)
- except Exception:
- logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)
+ 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")
+ if inbox_row is not None:
+ 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": message.get("text") or (text if isinstance(text, str) else ""),
+ "text": dispatch_text,
"scope_id": session["scope_id"],
- "user_message_id": message.get("id"),
}
if request.args.get("stream") != "1":
- # Session/page-scoped stream model (the default for the web Chat): the
- # browser renders from the persistent ``message.new`` feed, so we don't
- # hold this HTTP response open for the turn. Fire-and-forget the
- # dispatch; the agent reply arrives over ``/api/events``. The user row
- # is already persisted + published above, so it shows immediately even
- # if the dispatch is refused.
+ # 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.
try:
result = await internal_client.dispatch_async(dispatch_payload)
except internal_client.InternalServerUnavailable as exc:
- return jsonify({**message, "dispatch_error": "internal_unavailable", "detail": str(exc)}), 502
+ return jsonify({"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:
- # A turn is already running for this session — refused, not started.
- return jsonify({**message, "dispatch_error": "turn_in_progress"}), 409
- if status >= 400:
- return jsonify({**message, "dispatch_error": "dispatch_failed", "detail": result.get("body")}), 502
- return jsonify(message), 201
+ 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)
+ 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
+
+ # 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")
async def _proxy_sse():
# ``stream.start`` lets the browser confirm the socket round-trip
@@ -3225,6 +3252,62 @@ def sessions_mark_read(session_id: str):
)
[email protected]("/api/sessions/<session_id>/queue", methods=["GET"])
+def sessions_queue_list(session_id: str):
+ """Pending send-while-busy messages for a session (shown above the composer)."""
+ from storage import messages_service
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ queued = messages_service.list_queued(conn, session_id)
+ return jsonify({"queued": queued})
+
+
[email protected]("/api/sessions/<session_id>/queue/<message_id>", methods=["DELETE"])
+def sessions_queue_remove(session_id: str, message_id: str):
+ """Drop one queued message (the per-item delete in the queue strip)."""
+ from storage import messages_service
+ from vibe.sse_broker import broker
+
+ engine = _projects_engine()
+ with engine.begin() as conn:
+ removed = messages_service.remove_queued(conn, message_id)
+ if removed:
+ broker.publish("queue.updated", {"session_id": session_id})
+ return jsonify({"removed": bool(removed)})
+
+
[email protected]("/api/sessions/<session_id>/draft", methods=["GET"])
+def sessions_draft_get(session_id: str):
+ """The session's saved unsent compose text (restored on open / device switch)."""
+ from storage import messages_service
+
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ draft = messages_service.get_draft(conn, session_id)
+ return jsonify({"text": (draft or {}).get("text") or ""})
+
+
[email protected]("/api/sessions/<session_id>/draft", methods=["PUT"])
+def sessions_draft_set(session_id: str):
+ """Upsert the session's draft (debounced from the composer). Blank clears it."""
+ from core.services import sessions as workbench_sessions_service
+ from storage import messages_service
+
+ payload = request.json or {}
+ text = payload.get("text")
+ engine = _projects_engine()
+ try:
+ with engine.begin() as conn:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ messages_service.set_draft(
+ conn, scope_id=session["scope_id"], session_id=session_id, text=text if isinstance(text, str) else None
+ )
+ except LookupError as err:
+ return jsonify({"error": str(err)}), 404
+ return jsonify({"ok": True})
+
+
@app.route("/api/events", methods=["GET"])
async def workbench_events():
"""Server-Sent Events stream for the workbench.