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
chore(workbench): Step 6 — retire the dead legacy per-turn ?stream=1 path
cyhd795294c242f
diff --git a/core/internal_server.py b/core/internal_server.pyindex dce3aa380..cd4f040e6 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -227,110 +227,17 @@ def create_app(controller: "Controller") -> FastAPI:active = entry is not None and not entry[0].done()return {"ok": True, "session_id": session_id, "in_flight": active}- @app.post("/internal/dispatch")- async def _dispatch(request: Request) -> Any:- 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")-- # One streaming turn per session. If a turn is already in flight for- # this session (a second browser tab, or a resend before the first- # finishes), refuse the new one HERE — before creating a task or- # touching ``in_flight`` — so we never overwrite the real turn's task- # handle. Overwriting it would orphan the running turn: its sink keeps- # streaming but ``/internal/cancel`` could no longer find the task to- # interrupt, so the Stop button would silently no-op.- if isinstance(session_id, str) and session_id:- existing = in_flight.get(session_id)- if existing is not None and not existing[0].done():- async def _busy_stream():- yield _sse_event("turn.start", {"session_id": session_id})- yield _sse_event(- "turn.chunk",- {- "kind": "error",- "text": controller._t("error.streamTurnInProgress"),- "message_id": None,- },- )- yield _sse_event("turn.end", {"session_id": session_id})-- return StreamingResponse(- _busy_stream(),- media_type="text/event-stream",- headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},- )-- # SSE chunked stream — the response body is fed by ``on_chunk``- # callbacks that the dispatcher fires for every successful- # ``emit_agent_message`` notify / result during the turn. The- # turn coroutine and the producer-consumer queue live on the- # same loop, so ordering is preserved.- chunk_queue: asyncio.Queue[Optional[dict]] = asyncio.Queue()-- async def on_chunk(envelope: dict) -> None:- await chunk_queue.put(envelope)-- async def _runner() -> None:- try:- await dispatch_turn(controller, context, text, on_chunk=on_chunk)- except asyncio.CancelledError:- # Surface a cancel envelope so the SSE consumer can- # distinguish "user stopped me" from "agent finished".- await chunk_queue.put({"kind": "cancelled", "text": ""})- raise- except Exception as err:- logger.exception("internal dispatch failed for session=%s", session_id)- await chunk_queue.put({"kind": "error", "text": str(err)})- finally:- # Sentinel signals end-of-stream to the consumer below.- await chunk_queue.put(None)-- task = asyncio.create_task(_runner(), name="internal-dispatch")- if isinstance(session_id, str) and session_id:- in_flight[session_id] = (task, context)-- async def _stream():- try:- yield _sse_event("turn.start", {"session_id": session_id})- while True:- envelope = await chunk_queue.get()- if envelope is None:- break- yield _sse_event("turn.chunk", envelope)- yield _sse_event("turn.end", {"session_id": session_id})- finally:- if not task.done():- task.cancel()- # Release the slot whether the task completed normally,- # was cancelled by the UI, or the SSE consumer- # disconnected mid-stream. ``pop`` is idempotent.- if isinstance(session_id, str):- in_flight.pop(session_id, None)-- return StreamingResponse(- _stream(),- media_type="text/event-stream",- 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. ``_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.+ Starts the turn and returns ``202`` immediately. The reply — plus any+ notify/result — reaches the browser over the persistent ``message.new``+ session stream, 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.+ ``_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:diff --git a/tests/test_internal_client.py b/tests/test_internal_client.pyindex b1e98a0f4..be5365fcc 100644--- a/tests/test_internal_client.py+++ b/tests/test_internal_client.py@@ -1,120 +1,29 @@"""Tests for ``vibe.internal_client``.-The UI server uses this module to reach the controller's Unix socket and-proxy SSE chunks to the browser. We cover the two failure modes that-matter for the C5 ``?stream=1`` fallback to the queue path:--1. Missing socket file => ``InternalServerUnavailable``.-2. End-to-end SSE parsing against a fake ASGI app via- ``httpx.ASGITransport``. The fake app produces a known sequence of- ``event:`` + ``data:`` lines and we assert the client surfaces them- in order.+The UI server uses this module to reach the controller's Unix socket to+start fire-and-forget turns and run the turn-control surface (cancel /+send-now / turn-state). We cover the socket-missing degradation and the+round-trip shape of each call against a fake ASGI app via+``httpx.ASGITransport`` (skips uvicorn)."""from __future__ import annotationsimport asyncio-import jsonimport sysfrom pathlib import Path-from typing import AsyncIteratorfrom unittest.mock import patchimport httpximport pytestfrom fastapi import FastAPI-from fastapi.responses import JSONResponse, StreamingResponse+from fastapi.responses import JSONResponsesys.path.insert(0, str(Path(__file__).resolve().parents[1]))from vibe import internal_client-def test_missing_socket_raises_unavailable(tmp_path):- sock = tmp_path / "missing.sock"- assert not sock.exists()-- async def _go():- async for _ in internal_client.stream_dispatch({"session_id": "s", "text": "hi"}, socket_path=sock):- pass-- with pytest.raises(internal_client.InternalServerUnavailable):- asyncio.run(_go())---def _fake_app_emitting(frames: list[str]) -> FastAPI:- app = FastAPI()-- @app.post("/internal/dispatch")- async def _dispatch():- async def _gen() -> AsyncIterator[bytes]:- for f in frames:- yield f.encode("utf-8")-- return StreamingResponse(_gen(), media_type="text/event-stream")-- return app---def test_stream_dispatch_parses_sse_via_asgi_transport(tmp_path):- """End-to-end shape: we feed the client a known SSE byte stream- through ``httpx.ASGITransport`` (skips uvicorn) and confirm it- surfaces (event_name, data) pairs in order.- """-- frames = [- "event: turn.start\ndata: {\"session_id\": \"s1\"}\n\n",- "event: turn.chunk\ndata: {\"text\": \"hello\", \"kind\": \"result\"}\n\n",- "event: turn.end\ndata: {\"session_id\": \"s1\"}\n\n",- ]- sock = tmp_path / "dispatch.sock"- sock.touch() # presence is all the client checks before opening the transport-- async def _go() -> list[tuple[str, dict]]:- app = _fake_app_emitting(frames)- fake_transport = httpx.ASGITransport(app=app)- with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):- events = []- async for event_name, data in internal_client.stream_dispatch(- {"session_id": "s1", "text": "hi"}, socket_path=sock- ):- events.append((event_name, data))- return events-- events = asyncio.run(_go())- assert events == [- ("turn.start", {"session_id": "s1"}),- ("turn.chunk", {"text": "hello", "kind": "result"}),- ("turn.end", {"session_id": "s1"}),- ]---def test_stream_dispatch_surfaces_500_as_unavailable(tmp_path):- """4xx/5xx from the internal endpoint must raise so the UI route- falls back instead of leaking error HTML into the SSE response.- """-- from starlette.responses import Response-- app = FastAPI()-- @app.post("/internal/dispatch")- async def _dispatch():- return Response(content=b"internal down", status_code=503)-- 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):- async for _ in internal_client.stream_dispatch({"session_id": "s", "text": "x"}, socket_path=sock):- pass-- with pytest.raises(internal_client.InternalServerUnavailable):- asyncio.run(_go())--def test_cancel_dispatch_round_trip(tmp_path):"""``cancel_dispatch`` should forward the session id to thecontroller's ``POST /internal/cancel/<session_id>`` endpoint and@@ -181,27 +90,3 @@ 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 logs- and continues so a single bad frame doesn't kill the stream.- """-- frames = [- "event: turn.chunk\ndata: this is not json\n\n",- "event: turn.chunk\ndata: " + json.dumps({"ok": True}) + "\n\n",- ]- sock = tmp_path / "dispatch.sock"- sock.touch()-- async def _go() -> list[tuple[str, dict]]:- app = _fake_app_emitting(frames)- fake_transport = httpx.ASGITransport(app=app)- with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):- return [event async for event in internal_client.stream_dispatch(- {"session_id": "s", "text": "x"}, socket_path=sock- )]-- events = asyncio.run(_go())- assert events == [("turn.chunk", {"ok": True})]diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 13595f46d..4303f8137 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -1,21 +1,21 @@"""Tests for ``core.internal_server`` — the controller-side Unix socket-ASGI app that exposes ``POST /internal/dispatch`` (SSE chunked) for the-Web UI / future CLI ``--sync`` callers.+ASGI app that exposes ``POST /internal/dispatch_async`` (fire-and-forget turn+dispatch) plus the turn-control surface (cancel / send-now / turn-state) for+the Web UI / CLI callers.We exercise three layers:1. The app's request/response shape via ``httpx.ASGITransport`` (noactual socket; locks the contract independent of uvicorn).-2. The dispatcher hook that streams ``turn_chunk_callback`` envelopes- into the SSE response (regression for the C4 wiring in- ``message_dispatcher._stream_chunk``).+2. The fire-and-forget dispatch lifecycle: the turn is held open (in_flight)+ and its ``turn.start`` / ``turn.end`` published on the bus, the reply+ itself arriving over ``message.new`` rather than the response.3. The boot-time socket file lifecycle (default path + chmod)."""from __future__ import annotationsimport asyncio-import jsonimport sysfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock@@ -25,7 +25,6 @@ import httpxsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core import internal_server-from core.message_dispatcher import _stream_chunkfrom core.services.dispatch import dispatch_turnfrom modules.im import MessageContext@@ -101,11 +100,13 @@ def test_default_socket_path_lives_under_state_dir(monkeypatch, tmp_path):def test_create_app_exposes_minimal_endpoints():app = internal_server.create_app(_build_controller_double())routes = {(r.path, tuple(sorted(r.methods))) for r in app.routes if hasattr(r, "methods")}- # Endpoints locked by the design doc §7.4 v1 row + the health probe.+ # Endpoints locked by the design doc §7.4 v1 row + the health probe. The+ # legacy streaming ``/internal/dispatch`` was retired in Step 6 — the+ # session-scoped stream replaced the per-turn SSE proxy.assert ("/internal/health", ("GET",)) in routes- assert ("/internal/dispatch", ("POST",)) in routesassert ("/internal/dispatch_async", ("POST",)) in routesassert ("/internal/cancel/{session_id}", ("POST",)) in routes+ assert ("/internal/dispatch", ("POST",)) not in routes# ---------------------------------------------------------------------@@ -131,10 +132,12 @@ async def _dispatch_round_trip(body: dict) -> httpx.Response:app = internal_server.create_app(_build_controller_double())transport = httpx.ASGITransport(app=app)async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- return await client.post("/internal/dispatch", json=body)+ return await client.post("/internal/dispatch_async", json=body)def test_dispatch_rejects_missing_text():+ # Payload validation runs before any turn/queue work, so a bad request 400s+ # the same way on the fire-and-forget endpoint.resp = asyncio.run(_dispatch_round_trip({"session_id": "s1"}))assert resp.status_code == 400payload = resp.json()@@ -148,144 +151,6 @@ def test_dispatch_rejects_missing_session_id():assert "session_id" in resp.json()["error"]-def test_dispatch_streams_chunks_emitted_by_handler():- """Round-trip: simulate the handler invoking the on_chunk callback- that ``dispatch_turn`` stashed on ``context.platform_specific``.- The endpoint must surface those envelopes as SSE ``turn.chunk``- events between a single ``turn.start`` and ``turn.end``.- """-- chunks = [- {"text": "thinking", "message_id": "m_1", "kind": "notify"},- {"text": "here is the answer", "message_id": "m_2", "kind": "result"},- ]-- async def fake_handle_user_message(ctx, text):- # Simulate the agent's background receiver emitting via the real- # dispatcher hook: it resolves the sink dispatch_turn registered- # (by session key) and forwards each envelope to the SSE stream.- # The trailing result emit also releases dispatch_turn.- for c in chunks:- await _stream_chunk(- controller, ctx, text=c["text"], message_id=c["message_id"], kind=c["kind"]- )- return chunks[-1]["message_id"]-- controller = _build_controller_double(handler=fake_handle_user_message)- 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:- async with client.stream(- "POST", "/internal/dispatch", json={"session_id": "ses_test", "text": "hello"}- ) as resp:- assert resp.status_code == 200- assert resp.headers["content-type"].startswith("text/event-stream")- events: list[tuple[str, dict]] = []- current_event: str | None = None- async for line in resp.aiter_lines():- if line.startswith("event:"):- current_event = line.split(":", 1)[1].strip()- elif line.startswith("data:") and current_event is not None:- events.append((current_event, json.loads(line[5:].strip())))- return events-- events = asyncio.run(_go())- event_kinds = [name for name, _ in events]- assert event_kinds[0] == "turn.start"- assert event_kinds[-1] == "turn.end"- chunk_events = [data for name, data in events if name == "turn.chunk"]- assert chunk_events == chunks, "chunks must be forwarded in order without rewriting"---def test_dispatch_waits_for_async_result_after_handler_returns():- """The crux of the streaming lifecycle fix: the agent backends are- fire-and-forget — ``handle_user_message`` returns after *sending*, and- the reply is emitted later by a background receiver task. ``dispatch_turn``- must hold the SSE stream open until that async result emit (done), not- close it the instant the handler returns. (Pre-fix, ``turn.end`` fired- immediately and the late result missed the closed stream.)- """-- emitted = asyncio.Event()-- async def fire_and_forget(ctx, text):- # Schedule the result emit to happen *after* this returns, then- # return immediately (the message has been "sent").- async def _late_emit():- await asyncio.sleep(0.05)- await _stream_chunk(controller, ctx, text="late answer", message_id="m_late", kind="result")- emitted.set()-- asyncio.create_task(_late_emit())- return None-- controller = _build_controller_double(handler=fire_and_forget)- 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:- async with client.stream(- "POST", "/internal/dispatch", json={"session_id": "ses_async", "text": "hi"}- ) as resp:- events: list[tuple[str, dict]] = []- current = None- async for line in resp.aiter_lines():- if line.startswith("event:"):- current = line.split(":", 1)[1].strip()- elif line.startswith("data:") and current is not None:- events.append((current, json.loads(line[5:].strip())))- return events-- events = asyncio.run(_go())- kinds = [name for name, _ in events]- chunk_texts = [data.get("text") for name, data in events if name == "turn.chunk"]- assert "late answer" in chunk_texts, "a result emitted after the handler returned must still stream"- assert kinds[-1] == "turn.end"- assert emitted.is_set()---def test_dispatch_closes_when_turn_completes_without_result():- """P1: a turn that finishes WITHOUT emitting a result (missing/disabled- backend, dedup, error, ...) must close the stream promptly via- ``mark_turn_complete`` rather than hang until the 600s safety timeout.- ``MessageHandler._handle_turn`` signals this on every no-dispatch exit;- here we drive it directly.- """-- async def no_result_handler(ctx, text):- await _stream_chunk(controller, ctx, text="working", message_id=None, kind="notify")- # Turn finished without a result emit — release the SSE waiter.- controller.mark_turn_complete(ctx)- return None-- controller = _build_controller_double(handler=no_result_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:- async with client.stream(- "POST", "/internal/dispatch", json={"session_id": "ses_nr", "text": "hi"}- ) as resp:- events: list[tuple[str, dict]] = []- current = None- async for line in resp.aiter_lines():- if line.startswith("event:"):- current = line.split(":", 1)[1].strip()- elif line.startswith("data:") and current is not None:- events.append((current, json.loads(line[5:].strip())))- return events-- # Bounded so a regression (no-result hang) fails fast instead of 600s.- events = asyncio.run(asyncio.wait_for(_go(), timeout=10))- kinds = [name for name, _ in events]- assert kinds[-1] == "turn.end"- assert any(d.get("text") == "working" for n, d in events if n == "turn.chunk")--def test_register_turn_sink_ignores_duplicate_and_pop_is_identity_guarded():"""Streaming turns are serialized per session (dispatch_turn rejects aconcurrent one). As defense in depth, register_turn_sink must NOT clobber@@ -343,7 +208,7 @@ def test_dispatch_rejects_concurrent_same_session_turn():def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, tmp_path):- """Regression for the Codex P1: ``/internal/dispatch`` must hand the+ """Regression for the Codex P1: ``/internal/dispatch_async`` must hand theworkbench session's agent / model / effort to ``MessageHandler`` via``platform_specific["agent_session_target"]`` + ``vibe_agent_name``so the Chat header's chosen agent is actually used instead of the@@ -380,11 +245,9 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, tasync def capture(ctx, text):captured["platform_specific"] = dict(ctx.platform_specific or {})- # Release the streaming dispatch (simulate the turn completing) so it- # doesn't wait out the safety timeout.- sink = controller.get_turn_sink(controller._get_session_key(ctx))- if sink:- sink["done_event"].set()+ # Release the held turn the way a real result emit would so the+ # fire-and-forget dispatch settles promptly.+ controller.mark_turn_complete(ctx)controller = _build_controller_double(handler=capture)app = internal_server.create_app(controller)@@ -392,11 +255,13 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, tasync def _go():async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- async with client.stream(- "POST", "/internal/dispatch", json={"session_id": session_id, "text": "hi"}- ) as resp:- async for _ in resp.aiter_lines():- pass+ resp = await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "hi"})+ assert resp.status_code == 202+ # Fire-and-forget: wait for the background turn to run + capture.+ for _ in range(200):+ if "platform_specific" in captured and session_id not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)asyncio.run(_go())payload = captured["platform_specific"]@@ -680,159 +545,6 @@ def test_cancel_returns_404_when_session_not_in_flight():assert body["code"] == "not_in_flight"-def test_cancel_marks_in_flight_session_as_requested(monkeypatch, tmp_path):- """When a dispatch is in flight, ``cancel`` interrupts the backend turn- through the shared ``/stop`` path AND cancels the SSE proxy task. The- endpoint returns immediately; the SSE consumer observes a ``cancelled``- chunk.- """-- # Hermetic SQLite so cancel's session-context lookup doesn't touch the- # real home (the test session isn't persisted; lookup resolves to None).- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))- from storage.importer import ensure_sqlite_state-- ensure_sqlite_state()-- started = asyncio.Event()- cancelled = asyncio.Event()-- async def long_handle_user_message(ctx, text):- await _stream_chunk(controller, ctx, text="starting", message_id=None, kind="notify")- started.set()- try:- # Sleep long enough that the test's cancel arrives mid-flight.- await asyncio.sleep(5)- except asyncio.CancelledError:- cancelled.set()- raise- return None-- controller = _build_controller_double(handler=long_handle_user_message)- 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:- # Kick off the dispatch in the background; the request stays- # open while the handler is sleeping.- stream_task = asyncio.create_task(- _drain_stream(client, {"session_id": "ses_long", "text": "go"})- )- await asyncio.wait_for(started.wait(), timeout=3)- cancel_resp = await client.post("/internal/cancel/ses_long")- events = await asyncio.wait_for(stream_task, timeout=3)- return cancel_resp, events-- async def _drain_stream(client, body):- async with client.stream("POST", "/internal/dispatch", json=body) as resp:- assert resp.status_code == 200- collected: list[tuple[str, dict]] = []- current = None- async for line in resp.aiter_lines():- if line.startswith("event:"):- current = line.split(":", 1)[1].strip()- elif line.startswith("data:") and current is not None:- collected.append((current, json.loads(line[5:].strip())))- return collected-- cancel_resp, events = asyncio.run(_go())- assert cancel_resp.status_code == 200- assert cancel_resp.json()["status"] == "cancel_requested"- assert cancelled.is_set(), "handler must observe CancelledError"- # The SSE consumer sees the cancelled chunk before turn.end.- chunk_kinds = [data.get("kind") for name, data in events if name == "turn.chunk"]- assert "cancelled" in chunk_kinds---def test_concurrent_dispatch_refused_preserves_cancellable_slot(monkeypatch, tmp_path):- """A second dispatch for a session that already has a turn in flight is- refused with a terminal error chunk WITHOUT evicting the first turn's task- handle — so ``/internal/cancel`` can still interrupt the original- long-running turn (regression: the refusal task used to overwrite the slot- and orphan the real turn, leaving the Stop button a silent no-op).- """-- monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))- from storage.importer import ensure_sqlite_state-- ensure_sqlite_state()-- started = asyncio.Event()- cancelled = asyncio.Event()-- async def long_handle(ctx, text):- await _stream_chunk(controller, ctx, text="starting", message_id=None, kind="notify")- started.set()- try:- await asyncio.sleep(5)- except asyncio.CancelledError:- cancelled.set()- raise- return None-- controller = _build_controller_double(handler=long_handle)- app = internal_server.create_app(controller)- transport = httpx.ASGITransport(app=app)-- async def _drain(client, body):- async with client.stream("POST", "/internal/dispatch", json=body) as resp:- assert resp.status_code == 200- collected: list[tuple[str, dict]] = []- current = None- async for line in resp.aiter_lines():- if line.startswith("event:"):- current = line.split(":", 1)[1].strip()- elif line.startswith("data:") and current is not None:- collected.append((current, json.loads(line[5:].strip())))- return collected-- async def _go():- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- first = asyncio.create_task(_drain(client, {"session_id": "ses_x", "text": "one"}))- await asyncio.wait_for(started.wait(), timeout=3)- # Second concurrent send for the SAME session: refused immediately.- second = await asyncio.wait_for(_drain(client, {"session_id": "ses_x", "text": "two"}), timeout=3)- # The original turn must still be cancellable.- cancel_resp = await client.post("/internal/cancel/ses_x")- first_events = await asyncio.wait_for(first, timeout=3)- return second, cancel_resp, first_events-- second_events, cancel_resp, _first_events = asyncio.run(_go())- # The refused second dispatch got a terminal error chunk, not a real turn.- second_kinds = [data.get("kind") for name, data in second_events if name == "turn.chunk"]- assert "error" in second_kinds- # The first turn's slot survived the refusal: cancel finds it, interrupts- # the backend via the shared /stop path, and the handler is cancelled.- assert cancel_resp.status_code == 200- assert cancel_resp.json()["status"] == "cancel_requested"- assert cancelled.is_set(), "the original turn must still be cancellable"- controller.command_handler.handle_stop.assert_awaited()- # Cancel also interrupted the backend turn via the shared /stop path.- controller.command_handler.handle_stop.assert_awaited()---def test_dispatch_emits_error_chunk_on_handler_exception():- async def boom(ctx, text):- raise RuntimeError("kaboom")-- controller = _build_controller_double(handler=boom)- 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:- async with client.stream(- "POST", "/internal/dispatch", json={"session_id": "s", "text": "go"}- ) as resp:- return "".join([line async for line in resp.aiter_lines()])-- body = asyncio.run(_go())- assert "event: turn.chunk" in body- assert '"kind": "error"' in body- assert "event: turn.end" in body--# ---------------------------------------------------------------------# Dispatcher hook contract# ---------------------------------------------------------------------diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex 2fd07fe66..6a9a11b67 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -1,9 +1,11 @@-"""Tests for ``POST /api/sessions/<id>/messages?stream=1`` and-``POST /api/sessions/<id>/cancel`` in ``vibe.ui_server``.--These cover the C5 + C6 bridge between the browser and the controller's-Unix socket. We mock ``vibe.internal_client`` so the tests stay-hermetic and don't need a real controller process.+"""Tests for ``POST /api/sessions/<id>/messages`` (fire-and-forget dispatch)+and ``POST /api/sessions/<id>/cancel`` in ``vibe.ui_server``.++These cover the bridge between the browser and the controller's Unix socket:+the session/page-scoped model persists the user row and fire-and-forgets the+turn (the reply arrives over the ``message.new`` stream). We mock+``vibe.internal_client`` so the tests stay hermetic and don't need a real+controller process."""from __future__ import annotations@@ -54,86 +56,8 @@ def _make_session(tmp_path: Path) -> tuple[str, str]:return scope_id, session["id"]-def test_stream_route_proxies_internal_sse_frames(isolated_state, tmp_path):- """``?stream=1`` opens the internal socket, forwards the- ``turn.start`` envelope with the persisted user message, and then- relays subsequent ``turn.chunk`` frames verbatim.- """-- from vibe.ui_server import app-- scope_id, session_id = _make_session(tmp_path)-- upstream_events = [- ("turn.chunk", {"text": "thinking", "kind": "notify"}),- ("turn.chunk", {"text": "answer", "kind": "result"}),- ("turn.end", {"session_id": session_id}),- ]-- async def fake_stream_dispatch(payload, **kwargs):- # Lock the request payload shape — the bridge must forward the- # text + session_id + scope_id from the route body.- assert payload["session_id"] == session_id- assert payload["text"] == "hello"- assert payload["scope_id"] == scope_id- for event in upstream_events:- yield event-- with patch("vibe.internal_client.stream_dispatch", fake_stream_dispatch):- client = app.test_client()- headers = csrf_headers(client)- response = client.post(- f"/api/sessions/{session_id}/messages?stream=1",- json={"text": "hello"},- headers=headers,- )-- assert response.status_code == 200- assert response.headers.get("content-type", "").startswith("text/event-stream")- body = response.text- # The route prepends a ``stream.start`` envelope with the persisted- # user message so the browser can render it before the agent reply- # arrives — then forwards the upstream frames verbatim.- assert "event: stream.start" in body- assert "event: turn.chunk" in body- assert '"text": "thinking"' in body- assert '"text": "answer"' in body- assert "event: turn.end" in body---def test_stream_route_emits_stream_error_when_socket_down(isolated_state, tmp_path):- """If the internal socket isn't reachable, the route still persists- the user message and then surfaces a ``stream.error`` frame so the- browser can fall back instead of dying mid-stream.- """-- from vibe import internal_client- from vibe.ui_server import app-- _, session_id = _make_session(tmp_path)-- async def boom(payload, **kwargs):- raise internal_client.InternalServerUnavailable("socket missing")- yield # pragma: no cover — generator marker-- with patch("vibe.internal_client.stream_dispatch", boom):- client = app.test_client()- headers = csrf_headers(client)- response = client.post(- f"/api/sessions/{session_id}/messages?stream=1",- json={"text": "hi"},- headers=headers,- )-- body = response.text- assert "event: stream.start" in body- assert "event: stream.error" in body- assert "internal_server_unavailable" in body---def test_non_stream_route_fire_and_forgets_dispatch(isolated_state, tmp_path):- """Bare POST (no ``stream=1``) — now the default for the session/page-scoped- web Chat — persists the user row AND fire-and-forgets the turn via+def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):+ """The web Chat POST persists the user row AND fire-and-forgets the turn via``/internal/dispatch_async``. The reply arrives over the persistent``message.new`` stream, so the response returns 201 immediately with the row(it does NOT hold the turn open).@@ -165,7 +89,7 @@ def test_non_stream_route_fire_and_forgets_dispatch(isolated_state, tmp_path):assert sent["text"] == "no stream"-def test_non_stream_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):+def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):"""When the controller reports a turn already running (202 {queued}), theroute persists the user row, hands its id to the controller to re-type asqueued, and returns 202 {queued:true} marked as the queued type. (The actualdiff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsxindex 0262481b1..f439dfe7a 100644--- a/ui/src/components/Workbench.tsx+++ b/ui/src/components/Workbench.tsx@@ -64,10 +64,11 @@ export const Workbench: React.FC = () => {// Omit agent_backend so the server routes the new chat through the// configured agents.default_backend rather than a hard-coded one.const session = await api.createSession({ project_id: targetProject.id });- // Hand the typed message to ChatPage as router state. ChatPage replays- // it through its own streaming compose path (POST ?stream=1), so the- // agent turn actually starts and the reply streams in — instead of- // persisting a user message here that no dispatch would ever pick up.+ // Hand the typed message to ChatPage as router state. ChatPage replays it+ // through its fire-and-forget compose path (plain POST → dispatch_async),+ // so the agent turn actually starts and the reply arrives over the+ // session stream — instead of persisting a user message here that no+ // dispatch would ever pick up.navigate(`/chat/${encodeURIComponent(session.id)}`, {state: { initialMessage: text },});diff --git a/ui/src/components/workbench/CreateViaChatDialog.tsx b/ui/src/components/workbench/CreateViaChatDialog.tsxindex f78f8671f..c7310fdb3 100644--- a/ui/src/components/workbench/CreateViaChatDialog.tsx+++ b/ui/src/components/workbench/CreateViaChatDialog.tsx@@ -74,10 +74,10 @@ export const CreateViaChatDialog: React.FC<CreateViaChatDialogProps> = ({ kind,kind === 'task' ? 'harness.createDialog.promptTask' : 'harness.createDialog.promptWatch',);// Hand the seed prompt to ChatPage as router state; it replays the- // message through the streaming compose path (POST ?stream=1) so the- // agent turn actually starts. A bare non-stream send would only- // persist the prompt and never dispatch, leaving the task/watch- // creation stuck with no agent reply.+ // message through the fire-and-forget compose path (plain POST →+ // dispatch_async) so the agent turn actually starts and the reply arrives+ // over the session stream — otherwise the task/watch creation would sit+ // with a persisted prompt that no dispatch ever picks up.navigate(`/chat/${encodeURIComponent(session.id)}`, {state: { initialMessage: prompt },});diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 7781cb08e..dc2db8583 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -2,14 +2,16 @@C5 of Plan 2 (see ``docs/plans/workbench-dispatch-architecture.md``).The UI server runs as its own subprocess; this module is how it reaches-``core.internal_server`` to trigger ``dispatch_turn`` and stream the-agent's SSE chunked response back to the browser.+``core.internal_server`` to start agent turns and observe their lifecycle.Single responsibility: keep all the socket-path / httpx-transport /SSE-parsing boilerplate out of the UI route bodies. Routes call-``stream_dispatch(...)`` and either iterate the resulting async-generator straight into a ``StreamingResponse``, or catch-``InternalServerUnavailable`` to fall back to the N1 queue path.+``dispatch_async(...)`` to start a fire-and-forget turn (the reply arrives+over the persistent ``message.new`` session stream, not the response),+``stream_events(...)`` to subscribe to the controller's event feed, and+``cancel_dispatch`` / ``send_now`` / ``turn_state`` / ``health`` for the+turn-control surface — each raising ``InternalServerUnavailable`` so the+route can degrade gracefully."""from __future__ import annotations@@ -48,71 +50,6 @@ def default_socket_path() -> Path:return paths.get_state_dir() / "dispatch.sock"-async def stream_dispatch(- payload: dict[str, Any],- *,- socket_path: Optional[Path] = None,- timeout: float = 1800.0,-) -> AsyncIterator[tuple[str, dict[str, Any]]]:- """Send a dispatch request to the controller and yield SSE events.-- Each yielded tuple is ``(event_name, parsed_data)`` — e.g.- ``("turn.start", {...})``, ``("turn.chunk", {...})``, ``("turn.end",- {...})``. The caller is expected to re-encode them for the browser- (UI server adds the ``data: {...}\\n\\n`` SSE framing back on the way- out so this layer can stay format-agnostic).-- Raises ``InternalServerUnavailable`` for connect-time failures so- the caller can fall back to N1 (``agent_runs`` queue).- """-- 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:- try:- stream = client.stream("POST", "/internal/dispatch", json=payload)- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:- raise InternalServerUnavailable(str(exc)) from exc-- async with stream as resp:- if resp.status_code >= 400:- detail = await resp.aread()- raise InternalServerUnavailable(- f"dispatch endpoint returned {resp.status_code}: {detail!r}"- )-- current_event: Optional[str] = None- async for line in resp.aiter_lines():- if not line:- # Blank line ends an SSE event block; reset the- # event-name buffer so a missing ``event:`` field- # on the next block defaults to ``message``.- current_event = None- continue- if line.startswith("event:"):- current_event = line.split(":", 1)[1].strip()- elif line.startswith("data:"):- raw = line[5:].lstrip()- try:- parsed = json.loads(raw)- except json.JSONDecodeError:- logger.warning("internal_client: invalid SSE data line %r", raw)- continue- yield (current_event or "message", parsed)- except InternalServerUnavailable:- raise- except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:- raise InternalServerUnavailable(str(exc)) from exc--async def stream_events(*,socket_path: Optional[Path] = None,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 533902c6b..841fb7601 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3040,25 +3040,19 @@ def sessions_messages_list(session_id: str):@app.route("/api/sessions/<session_id>/messages", methods=["POST"])async def sessions_messages_create(session_id: str):- """Persist a user message and (optionally) stream the agent reply.-- Default behavior persists the user message + publishes ``message.new``- over the in-process SSE broker and returns the persisted row, just- like commit 07. When the caller passes ``?stream=1`` the route also- opens the controller's internal Unix-socket endpoint (C4) and- proxies the resulting SSE chunked stream straight back to the- browser, so the agent's reply lands token-by-token without an- extra round-trip.-- If the internal socket isn't reachable, ``?stream=1`` falls back to- the non-streaming response so the user still sees their own message- persist; the reply will then have to come through the queue path- (deferred — see docs/plans/workbench-dispatch-architecture.md §7.8).+ """Persist a user message and fire-and-forget the agent turn.++ Reserves the user's row, then asks the controller to start the turn+ (``/internal/dispatch_async``, 202). The agent's reply — and any+ notify/result — arrives over the persistent ``message.new`` session+ stream, not this response, so the HTTP request returns immediately and a+ closed browser tab can't cancel an in-flight turn. The controller+ atomically either starts the turn (we then promote the row to ``user``)+ or, when a turn is already running, promotes it to ``queued`` itself+ (send-while-busy). The legacy per-turn ``?stream=1`` SSE proxy was retired+ in Step 6 — the session-scoped stream replaced it."""- import json as _json- from starlette.responses import StreamingResponse-from core.services import sessions as workbench_sessions_servicefrom storage import messages_servicefrom vibe import internal_client@@ -3132,86 +3126,44 @@ async def sessions_messages_create(session_id: str):logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)return row- if request.args.get("stream") != "1":- # 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 promote + publish, no turn.- if not dispatch_text.strip():- 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 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,- "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:- # 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)}), 502- status = result.get("status_code", 500)- body = result.get("body") or {}- if status == 202 and body.get("queued"):- # 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}), 202- if status == 202:- # 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())+ # 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 promote + publish, no turn.+ if not dispatch_text.strip():+ return jsonify(_promote_and_publish(message)), 201+ # Session/page-scoped model (the web Chat): fire-and-forget the turn; the+ # reply arrives over ``message.new``. The controller atomically 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,"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- # is healthy before it commits to the long-lived UI; bundles the- # persisted user-message id so the consumer can dedupe against- # the optimistic update it already rendered.- yield _sse_frame("stream.start", {"user_message": message})- try:- async for event_name, data in internal_client.stream_dispatch(dispatch_payload):- yield _sse_frame(event_name, data)- except internal_client.InternalServerUnavailable as exc:- yield _sse_frame(- "stream.error",- {"reason": "internal_server_unavailable", "detail": str(exc)},- )- except Exception as exc: # pragma: no cover - defensive- logger.exception("dispatch stream proxy crashed")- yield _sse_frame(- "stream.error",- {"reason": "proxy_crashed", "detail": str(exc)},- )-- def _sse_frame(event_type: str, data) -> str:- return f"event: {event_type}\ndata: {_json.dumps(data)}\n\n"-- return StreamingResponse(- _proxy_sse(),- media_type="text/event-stream",- headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},- )+ try:+ result = await internal_client.dispatch_async(dispatch_payload)+ except internal_client.InternalServerUnavailable as exc:+ # 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)}), 502+ status = result.get("status_code", 500)+ body = result.get("body") or {}+ if status == 202 and body.get("queued"):+ # 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}), 202+ if status == 202:+ # 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@app.route("/api/sessions/<session_id>/cancel", methods=["POST"])