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
feat(dispatch): fire-and-forget /internal/dispatch_async for session-scoped send
cyh15ff8c475abb
diff --git a/core/internal_server.py b/core/internal_server.pyindex c30b614f0..eaf74011e 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -178,6 +178,60 @@ def create_app(controller: "Controller") -> FastAPI:headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},)+ @app.post("/internal/dispatch_async")+ async def _dispatch_async(request: Request) -> Any:+ """Fire-and-forget turn dispatch for the session/page-scoped stream.++ Unlike ``/internal/dispatch`` (which streams the reply back over the+ response for the legacy per-turn web stream), this starts the turn and+ 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.+ """+ payload = await _safe_json(request)+ try:+ text, context = _build_dispatch_payload(payload)+ except ValueError as err:+ 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+ # creating 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():+ return JSONResponse(+ status_code=409,+ 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++ 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)++ task = asyncio.create_task(_runner(), name="internal-dispatch-async")+ if isinstance(session_id, str) and session_id:+ in_flight[session_id] = (task, context)+ return JSONResponse(status_code=202, content={"ok": True, "session_id": session_id})+@app.get("/internal/events")async def _events() -> Any:"""Long-lived SSE feed of Controller-side inbox events.diff --git a/tests/test_internal_client.py b/tests/test_internal_client.pyindex 6e0efede9..b1e98a0f4 100644--- a/tests/test_internal_client.py+++ b/tests/test_internal_client.py@@ -23,7 +23,7 @@ from unittest.mock import patchimport httpximport pytestfrom fastapi import FastAPI-from fastapi.responses import StreamingResponse+from fastapi.responses import JSONResponse, StreamingResponsesys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -149,6 +149,40 @@ def test_cancel_dispatch_missing_socket_raises_unavailable(tmp_path):asyncio.run(internal_client.cancel_dispatch("ses_x", socket_path=sock))+def test_dispatch_async_round_trip(tmp_path):+ """``dispatch_async`` posts the payload to ``/internal/dispatch_async`` and+ surfaces the controller's status + body so the UI route can tell a started+ turn (202) from a concurrent-turn refusal (409)."""+ app = FastAPI()+ captured: dict = {}++ @app.post("/internal/dispatch_async")+ async def _async(payload: dict):+ captured["payload"] = payload+ return JSONResponse(status_code=202, content={"ok": True, "session_id": payload.get("session_id")})++ sock = tmp_path / "dispatch.sock"+ sock.touch()++ async def _go():+ fake_transport = httpx.ASGITransport(app=app)+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):+ return await internal_client.dispatch_async(+ {"session_id": "ses_z", "text": "hi"}, socket_path=sock+ )++ result = asyncio.run(_go())+ assert captured["payload"] == {"session_id": "ses_z", "text": "hi"}+ assert result["status_code"] == 202+ assert result["body"] == {"ok": True, "session_id": "ses_z"}+++def test_dispatch_async_missing_socket_raises_unavailable(tmp_path):+ sock = tmp_path / "missing.sock"+ with pytest.raises(internal_client.InternalServerUnavailable):+ asyncio.run(internal_client.dispatch_async({"session_id": "s", "text": "x"}, socket_path=sock))++def test_data_json_parsing_skips_malformed(tmp_path):"""A malformed ``data:`` payload should not raise; the client logsand continues so a single bad frame doesn't kill the stream.diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex af41101a2..a7daeaa04 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -104,6 +104,7 @@ def test_create_app_exposes_minimal_endpoints():# Endpoints locked by the design doc §7.4 v1 row + the health probe.assert ("/internal/health", ("GET",)) in routesassert ("/internal/dispatch", ("POST",)) in routes+ assert ("/internal/dispatch_async", ("POST",)) in routesassert ("/internal/cancel/{session_id}", ("POST",)) in routes@@ -408,6 +409,72 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, tassert target.get("reasoning_effort") == "high"+def test_dispatch_async_starts_turn_and_returns_202():+ """The fire-and-forget path starts the turn and returns 202 immediately.+ It still holds the turn open (via a no-op on_chunk) so ``in_flight`` is set+ for the turn's lifetime, then released when the turn completes — the reply+ itself reaches the browser over ``message.new``, not this response."""+ started = asyncio.Event()++ async def handler(ctx, text):+ started.set()+ # Release the held turn the way a real result emit would.+ controller.mark_turn_complete(ctx)+ 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:+ resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_a", "text": "hi"})+ # The background runner finishes after the 202; wait for it + the+ # in_flight slot to clear.+ await asyncio.wait_for(started.wait(), timeout=3)+ for _ in range(100):+ if "ses_a" not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)+ return resp++ resp = asyncio.run(_go())+ assert resp.status_code == 202+ assert resp.json()["ok"] is True+ controller.message_handler.handle_user_message.assert_awaited()+ assert "ses_a" not in app.state.in_flight_dispatches, "slot released after the turn"+++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."""+ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ async def _go():+ async def _busy():+ await asyncio.sleep(60)++ task = asyncio.create_task(_busy())+ app.state.in_flight_dispatches["ses_b"] = (+ 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"})+ finally:+ task.cancel()+ return resp++ resp = asyncio.run(_go())+ assert resp.status_code == 409+ assert resp.json()["code"] == "turn_in_progress"+ controller.message_handler.handle_user_message.assert_not_awaited()++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/vibe/internal_client.py b/vibe/internal_client.pyindex a578a30b7..0dd89311a 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -170,6 +170,38 @@ async def stream_events(raise InternalServerUnavailable(str(exc)) from exc+async def dispatch_async(+ payload: dict[str, Any],+ *,+ socket_path: Optional[Path] = None,+ timeout: float = 10.0,+) -> dict[str, Any]:+ """Start a fire-and-forget turn on the controller and return immediately.++ Hits ``POST /internal/dispatch_async``: the controller starts the turn and+ responds ``202`` right away (the reply arrives over the persistent+ ``message.new`` session stream, not this response). Returns+ ``{"status_code", "body"}`` so the caller can distinguish a started turn+ (202) from a concurrent-turn refusal (409). Raises+ ``InternalServerUnavailable`` on socket failure so the route can degrade.+ """++ target = (socket_path or default_socket_path()).expanduser().resolve()+ if not target.exists():+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")+ transport = httpx.AsyncHTTPTransport(uds=str(target))+ try:+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://localhost",+ timeout=httpx.Timeout(timeout, connect=5.0),+ ) as client:+ resp = await client.post("/internal/dispatch_async", json=payload)+ except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:+ raise InternalServerUnavailable(str(exc)) from exc+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}++async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:"""Ask the controller to cancel a running ``dispatch_turn`` for``session_id``.diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 02b1c1248..15c779fa0 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3106,9 +3106,6 @@ async def sessions_messages_create(session_id: str):except Exception:logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)- if request.args.get("stream") != "1":- return jsonify(message), 201-dispatch_payload = {"session_id": session_id,"text": message.get("text") or (text if isinstance(text, str) else ""),@@ -3116,6 +3113,25 @@ async def sessions_messages_create(session_id: str):"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.+ 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+ status = result.get("status_code", 500)+ 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+async def _proxy_sse():# ``stream.start`` lets the browser confirm the socket round-trip# is healthy before it commits to the long-lived UI; bundles the