Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): round-24 — restore stream_dispatch for Show page (Step-6 regression) + no-flush on failed turn + agent_variant
cyhf0be232c497f
diff --git a/core/internal_server.py b/core/internal_server.pyindex cd4f040e6..0838c4a1f 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -117,12 +117,19 @@ def create_app(controller: "Controller") -> FastAPI:async def _runner() -> None:cancelled = False+ failed = Falsetry:await dispatch_turn(controller, context, text, on_chunk=_noop_chunk)except asyncio.CancelledError:cancelled = Trueraiseexcept Exception:+ # dispatch_turn raised before any backend turn was actually+ # dispatched (missing/disabled backend, synchronous setup error).+ # No agent reply was produced, so this is a terminal FAILURE — it+ # must NOT auto-flush the send-while-busy queue onto a fresh turn+ # (Codex P2). (An explicit send-now flush_on_cancel still flushes.)+ failed = Truelogger.exception("internal async dispatch failed for session=%s", session_id)finally:if isinstance(session_id, str):@@ -143,7 +150,7 @@ def create_app(controller: "Controller") -> FastAPI:# timeout (the backend was just interrupted; the user can# resume). send-now still forces a flush via flush_on_cancel.should_flush = (- (not cancelled and not timed_out and session_id not in stop_no_flush)+ (not cancelled and not failed and not timed_out and session_id not in stop_no_flush)or (session_id in flush_on_cancel))flush_on_cancel.discard(session_id)@@ -227,6 +234,103 @@ 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:+ """Streaming turn dispatch: runs a turn and proxies its notify/result+ chunks back over an SSE response. The web **Chat** page no longer uses+ this (it's fire-and-forget via ``/internal/dispatch_async`` ++ ``message.new``); this backs the **Show-page** dispatch flow, where+ ``ui_server._run_show_event_dispatch`` re-publishes each event as+ ``show.dispatch`` for the open Show page."""+ 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.diff --git a/docs/plans/workbench-dispatch-architecture.md b/docs/plans/workbench-dispatch-architecture.mdindex 0a54a430e..0ea5cb8ec 100644--- a/docs/plans/workbench-dispatch-architecture.md+++ b/docs/plans/workbench-dispatch-architecture.md@@ -27,12 +27,18 @@ sections below.**fire-and-forget**: `POST .../messages` → `/internal/dispatch_async` (202),reply arrives over the stream. A closed tab can't cancel an in-flight turn.-2. **Legacy per-turn stream retired (Step 6).** With no caller left, the- streaming `?stream=1` chain was removed: `internal_client.stream_dispatch`,- the streaming `POST /internal/dispatch` endpoint, and the ui_server- `?stream=1` branch (~790 lines). The turn-sink / `on_chunk` machinery stays —- `dispatch_async` drives it with a no-op `on_chunk` to keep `in_flight`+2. **Legacy per-turn Chat stream retired (Step 6).** The Chat page's+ `?stream=1` proxy was removed: the ui_server `?stream=1` route branch (the+ Chat page is now fire-and-forget). The turn-sink / `on_chunk` machinery stays+ — `dispatch_async` drives it with a no-op `on_chunk` to keep `in_flight`populated (Stop) and to flush the send-while-busy queue on settle.+ **Correction:** `internal_client.stream_dispatch` + the streaming+ `POST /internal/dispatch` endpoint were initially removed too, but the merged+ show-annotation feature (#360) streams a turn back to the Show page via+ `ui_server._run_show_event_dispatch` → `stream_dispatch`, so both were+ restored. The streaming dispatch is NOT dead — it backs the Show-page flow;+ only the Chat `?stream=1` route is gone. (Guarded by+ `test_show_event_dispatch_streams_via_stream_dispatch`.)3. **`turn_token` is load-bearing — NOT rolled back.** The plan treated theper-turn token as scaffolding. It is now the completion guard: `_stream_chunk`diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 4303f8137..648f966d0 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -100,13 +100,14 @@ 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. The- # legacy streaming ``/internal/dispatch`` was retired in Step 6 — the- # session-scoped stream replaced the per-turn SSE proxy.+ # Endpoints locked by the design doc §7.4 v1 row + the health probe. Both+ # dispatch shapes exist: ``/internal/dispatch_async`` (fire-and-forget, the+ # Chat page) and the streaming ``/internal/dispatch`` (the Show-page dispatch+ # flow re-publishes its SSE chunks as ``show.dispatch``).assert ("/internal/health", ("GET",)) in routesassert ("/internal/dispatch_async", ("POST",)) in routesassert ("/internal/cancel/{session_id}", ("POST",)) in routes- assert ("/internal/dispatch", ("POST",)) not in routes+ assert ("/internal/dispatch", ("POST",)) in routes# ---------------------------------------------------------------------diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.pyindex 24be33319..b4f7515cd 100644--- a/tests/test_show_session_events.py+++ b/tests/test_show_session_events.py@@ -309,3 +309,46 @@ def test_show_event_store_lists_after_cursor(isolated_state):store.close()assert [event["id"] for event in page["events"]] == [second["id"]]+++def test_show_event_dispatch_streams_via_stream_dispatch(isolated_state, monkeypatch):+ """Regression guard: the Show-page dispatch flow MUST call+ ``internal_client.stream_dispatch`` and re-publish each turn event as+ ``show.dispatch``. Step 6 removed ``stream_dispatch`` as dead, but the merged+ show-annotation feature still depends on it — without this test that removal+ passed CI yet broke the Show page at runtime (Codex P2)."""+ import asyncio++ from vibe import internal_client, ui_server+ from vibe.sse_broker import broker++ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(broker, "publish", lambda event, data: published.append((event, data)))++ async def fake_stream_dispatch(payload, **kwargs):+ assert payload["session_id"] == "ses_show" and payload["text"] == "do the thing"+ yield ("turn.start", {"session_id": "ses_show"})+ yield ("turn.chunk", {"text": "working", "kind": "notify"})+ yield ("turn.end", {"session_id": "ses_show"})++ # setattr requires the attribute to exist — so this also asserts stream_dispatch+ # wasn't removed again.+ monkeypatch.setattr(internal_client, "stream_dispatch", fake_stream_dispatch)++ asyncio.run(+ ui_server._run_show_event_dispatch(+ {+ "id": "evt1",+ "session_id": "ses_show",+ "scope_id": "scope1",+ "transcript_text": "do the thing",+ "message_id": "m1",+ }+ )+ )++ assert [d["event"] for (e, d) in published if e == "show.dispatch"] == [+ "turn.start",+ "turn.chunk",+ "turn.end",+ ]diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex c2295ac81..85540b38e 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -1071,6 +1071,13 @@ const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({ session, agents, onagent_name: agent.name,agent_id: agent.id,agent_backend: agent.backend,+ // Track agent_variant to the backend: the persisted+ // native-session map is keyed by agent_variant while+ // Claude/Codex resume by backend name, so leaving a stale+ // variant (old agent name / 'default') means the session+ // can't resume its native thread after a restart and starts+ // fresh (Codex P2).+ agent_variant: agent.backend,// Explicit null (not undefined, which JSON.stringify// drops) so switching to an agent with no default model /// effort CLEARS the previous agent's override server-side.diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex dc2db8583..bdd38b886 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -6,12 +6,13 @@ The UI server runs as its own subprocess; this module is how it reachesSingle responsibility: keep all the socket-path / httpx-transport /SSE-parsing boilerplate out of the UI route bodies. Routes call-``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.+``dispatch_async(...)`` to start a fire-and-forget turn (the Chat page — the+reply arrives over the persistent ``message.new`` session stream, not the+response), ``stream_dispatch(...)`` to run a turn and stream its chunks back+(the Show-page dispatch flow), ``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@@ -50,6 +51,71 @@ 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 and yield the turn's SSE events as they arrive.++ Each yielded tuple is ``(event_name, parsed_data)`` — e.g. ``("turn.start",+ {...})``, ``("turn.chunk", {...})``, ``("turn.end", {...})``. The caller+ re-encodes them for the browser. Raises ``InternalServerUnavailable`` for+ connect-time failures so the caller can degrade.++ NB: the web **Chat** page no longer uses this (it's fire-and-forget ++ ``message.new``); this streaming round-trip backs the **Show-page** dispatch+ flow (``_run_show_event_dispatch`` re-publishes each event as ``show.dispatch``).+ """++ 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,