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
refactor(workbench): services layer + Unix socket SSE dispatch + send/compose (#340)
Call Whitef05bd7a903e2
diff --git a/core/controller.py b/core/controller.pyindex e0c844ecc..549b51da3 100644--- a/core/controller.py+++ b/core/controller.py@@ -373,9 +373,19 @@ class Controller:"bind": self._dispatch_to_controller_loop(self.command_handler.handle_bind),}+ # IM inbound messages funnel through ``core.services.dispatch``+ # alongside the CLI and the upcoming Web UI / N3 socket path so all+ # three callers exercise the same business API. The lambda preserves+ # the existing ``(context, text)`` callback shape that the IM clients+ # know how to invoke.+ from core.services.dispatch import dispatch_turn++ async def _on_im_message(context, text):+ await dispatch_turn(self, context, text)+# Register callbacks with the IM clientself.im_client.register_callbacks(- on_message=self._dispatch_to_controller_loop(self.message_handler.handle_user_message),+ on_message=self._dispatch_to_controller_loop(_on_im_message),on_command=command_handlers,on_callback_query=self._dispatch_to_controller_loop(self.message_handler.handle_callback_query),on_settings_update=self._dispatch_to_controller_loop(self.settings_handler.handle_settings_update),@@ -661,6 +671,20 @@ class Controller:asyncio.set_event_loop(self._loop)self._im_thread = threading.Thread(target=self._run_im_runtime, name="im-runtime", daemon=True)self._im_thread.start()+ # Internal Unix-socket ASGI server for the Web UI / future+ # ``vibe agent run --sync`` cross-process callers. Lives on+ # the same loop as the IM dispatch path so they share one+ # asyncio scheduler. See core/internal_server.py.+ try:+ from core import internal_server as _internal_server++ self._internal_server_task = self._loop.create_task(+ _internal_server.serve(self),+ name="internal-dispatch-server",+ )+ except Exception:+ logger.exception("internal dispatch server failed to schedule; UI fallback will use the queue path")+ self._internal_server_task = Noneself._loop.run_forever()if self._im_run_exception and not isinstance(self._im_run_exception, (KeyboardInterrupt, SystemExit)):raise self._im_run_exception@@ -670,6 +694,18 @@ class Controller:logger.error(f"Error in main run loop: {e}", exc_info=True)finally:self.cleanup_sync()+ # Best-effort: remove the dispatch socket so the next controller+ # boot starts from a clean filesystem state. uvicorn unlinks+ # the path on exit when it bound the socket itself, but it+ # can be left behind on hard crashes.+ try:+ from core import internal_server as _internal_server++ sock_path = _internal_server.default_socket_path()+ if sock_path.exists():+ sock_path.unlink()+ except Exception:+ passif self._loop is not None:try:self._loop.stop()diff --git a/core/internal_server.py b/core/internal_server.pynew file mode 100644index 000000000..03a3f7bf1--- /dev/null+++ b/core/internal_server.py@@ -0,0 +1,353 @@+"""Controller-side ASGI server bound to a Unix Domain Socket.++This is the C4 piece of Plan 2 from+``docs/plans/workbench-dispatch-architecture.md``: the controller process+exposes a minimal FastAPI app on+``~/.vibe_remote/state/dispatch.sock`` so cross-process callers (the+separate UI server subprocess, future ``vibe agent run --sync`` flows)+can invoke ``core.services.dispatch.dispatch_turn`` and stream the+agent's output back over SSE chunked response.++Three properties matter:++1. **Same asyncio loop as the controller.** The server runs as a+ background ``asyncio.Task`` on the loop that ``Controller.run()``+ creates. IM adapters share that loop. No cross-loop futures, no+ second uvicorn worker, no thread bridge.+2. **Local-only.** Unix sockets are bind to a file path on the local+ filesystem; no TCP listen, so external network exposure is+ impossible.+3. **0o600 permissions.** The socket file is chmod'd to ``0o600`` so+ only the running user can connect — defense in depth against shared+ hosts.++The endpoint set is intentionally tiny for v1 (``dispatch`` + a stub+``cancel``); follow-ups can grow it without changing the bind contract.+"""++from __future__ import annotations++import asyncio+import json+import logging+import os+from pathlib import Path+from typing import Any, Optional, TYPE_CHECKING++from fastapi import FastAPI, HTTPException, Request+from fastapi.responses import JSONResponse, StreamingResponse++from config import paths+from core.services.dispatch import dispatch_turn+from modules.im.base import MessageContext++if TYPE_CHECKING: # pragma: no cover - typing only+ from core.controller import Controller++logger = logging.getLogger(__name__)+++def default_socket_path() -> Path:+ """Where the internal server binds by default.++ Lives under ``~/.vibe_remote/state/`` so it shares the rest of the+ runtime state's filesystem permissions and gets cleaned up on home+ directory wipes.+ """++ return paths.get_state_dir() / "dispatch.sock"+++def create_app(controller: "Controller") -> FastAPI:+ """Build the minimal FastAPI app the internal server exposes.++ Factored out so tests can mount the same routes against a fake+ controller without spinning up uvicorn.+ """++ app = FastAPI(+ title="Vibe Remote internal dispatch",+ docs_url=None,+ redoc_url=None,+ openapi_url=None,+ )++ # In-flight ``dispatch_turn`` tasks indexed by session id. The+ # cancel endpoint looks the task up here so the UI can stop a+ # runaway turn without waiting for the agent to settle. Tasks are+ # registered when the SSE response starts and removed in its+ # ``finally`` so cancelled / completed sessions don't leak slots.+ in_flight: dict[str, asyncio.Task] = {}+ app.state.in_flight_dispatches = in_flight++ @app.get("/internal/health")+ async def _health() -> dict[str, Any]:+ return {"ok": True, "service": "vibe-remote-internal", "version": 1}++ @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")++ # 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++ 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/cancel/{session_id}")+ async def _cancel(session_id: str) -> Any:+ # ``session_id`` is the dispatch key — matches the body field+ # the dispatch endpoint registered under. Using the session id+ # (rather than introducing a separate run_id contract) keeps+ # the public surface narrow and lets the UI ``Stop`` button+ # work with just the URL it already has.+ task = in_flight.get(session_id)+ if task is None:+ return JSONResponse(+ status_code=404,+ content={"ok": False, "code": "not_in_flight", "session_id": session_id},+ )+ if task.done():+ return {"ok": True, "session_id": session_id, "status": "already_finished"}+ task.cancel()+ return {"ok": True, "session_id": session_id, "status": "cancel_requested"}++ return app+++async def serve(controller: "Controller", *, socket_path: Optional[Path] = None) -> None:+ """Run the internal server forever on the current event loop.++ Returns when the underlying uvicorn server exits (typically when the+ controller's loop is shut down). Each call binds a fresh socket+ file; pre-existing files at ``socket_path`` are removed first so+ restarts don't fail with "address already in use".++ Permissions: we tighten ``os.umask`` to ``0o077`` *before* uvicorn+ binds the socket so the file is created with mode ``0o700`` and is+ never readable / connectable by other local users — even briefly.+ A best-effort post-bind ``os.chmod`` then forces the final mode in+ case the platform's umask handling differs (some BSDs ignore umask+ for AF_UNIX bind). Without the umask wrap there is a TOCTOU window+ where the socket would be world-accessible between bind and chmod.+ """++ import uvicorn++ target = (socket_path or default_socket_path()).expanduser().resolve()+ target.parent.mkdir(parents=True, exist_ok=True)+ if target.exists() or target.is_symlink():+ try:+ target.unlink()+ except OSError:+ logger.warning("could not unlink stale dispatch socket %s; bind may fail", target)++ app = create_app(controller)+ config = uvicorn.Config(+ app,+ uds=str(target),+ log_config=None,+ access_log=False,+ loop="asyncio",+ lifespan="off",+ )+ server = uvicorn.Server(config)++ async def _chmod_when_ready() -> None:+ # Defense-in-depth: re-assert ``0o600`` once the socket file+ # exists, in case the platform's umask handling differs from+ # what we set above. The loop polls because uvicorn binds the+ # socket synchronously during ``serve`` and we don't want to+ # race against it.+ for _ in range(40):+ await asyncio.sleep(0.025)+ if target.exists():+ try:+ os.chmod(target, 0o600)+ except OSError:+ logger.warning("failed to chmod internal dispatch socket %s", target)+ return++ previous_umask = os.umask(0o077)+ chmod_task = asyncio.create_task(_chmod_when_ready(), name="internal-dispatch-chmod")+ try:+ await server.serve()+ finally:+ chmod_task.cancel()+ # Restore the previous umask so unrelated file writes from this+ # process aren't permanently affected by our hardening.+ os.umask(previous_umask)+++def start(controller: "Controller", *, socket_path: Optional[Path] = None) -> asyncio.Task:+ """Schedule the internal server to run on the controller's loop.++ Called from ``Controller.run`` once the loop is alive. Returns the+ background ``asyncio.Task`` so the caller can keep a handle for+ cancellation on shutdown.+ """++ loop = asyncio.get_event_loop()+ task = loop.create_task(serve(controller, socket_path=socket_path), name="internal-dispatch-server")++ def _on_done(t: asyncio.Task) -> None:+ if t.cancelled():+ return+ exc = t.exception()+ if exc:+ logger.error("internal dispatch server exited with exception: %r", exc)++ task.add_done_callback(_on_done)+ return task+++# --- Internals --------------------------------------------------------+++async def _safe_json(request: Request) -> dict[str, Any]:+ try:+ body = await request.json()+ except Exception:+ body = {}+ return body if isinstance(body, dict) else {}+++def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContext]:+ """Translate the JSON payload into a ``(text, MessageContext)`` pair.++ Raises ``ValueError`` with a caller-friendly message when the+ payload is missing required fields. The MessageContext defaults to+ ``platform="avibe"`` because the Web UI is the first / only caller;+ future CLI ``--sync`` callers will hand in their own platform.++ We also look up the workbench session's routing fields and copy+ them into ``platform_specific["agent_session_target"]`` /+ ``platform_specific["vibe_agent_name"]`` so ``MessageHandler``'s+ agent-selection branch picks up the Chat header's chosen agent /+ model / effort — matching the shape that scheduled tasks already+ feed in via ``core.scheduled_tasks`` so the handler stays one path.+ """++ text = payload.get("text")+ if not isinstance(text, str) or not text.strip():+ raise ValueError("text is required")++ session_id = payload.get("session_id")+ if not isinstance(session_id, str) or not session_id.strip():+ raise ValueError("session_id is required")++ user_id = payload.get("user_id") or "workbench"+ channel_id = payload.get("channel_id") or session_id++ platform_specific: dict[str, Any] = {"workbench_session_id": session_id}+ session_row = _lookup_session(session_id)+ if session_row is not None:+ target = {+ "id": session_row.get("id"),+ "agent_id": session_row.get("agent_id"),+ "agent_name": session_row.get("agent_name"),+ "agent_backend": session_row.get("agent_backend"),+ "agent_variant": session_row.get("agent_variant"),+ "model": session_row.get("model"),+ "reasoning_effort": session_row.get("reasoning_effort"),+ "native_session_id": session_row.get("native_session_id"),+ "workdir": session_row.get("workdir"),+ }+ platform_specific["agent_session_target"] = target+ if session_row.get("agent_name"):+ platform_specific["vibe_agent_name"] = session_row["agent_name"]++ context = MessageContext(+ user_id=str(user_id),+ channel_id=str(channel_id),+ platform=payload.get("platform") or "avibe",+ thread_id=payload.get("thread_id"),+ message_id=payload.get("message_id"),+ platform_specific=platform_specific,+ )+ return text, context+++def _lookup_session(session_id: str) -> Optional[dict[str, Any]]:+ """Load the workbench session row for routing metadata.++ Failures are swallowed and logged: the dispatch still proceeds with+ default routing rather than 5xx'ing the SSE stream. The session+ *not existing* is a real caller error but+ ``MessageHandler._handle_turn`` already produces a meaningful error+ in that case.+ """++ try:+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine++ engine = create_sqlite_engine()+ with engine.connect() as conn:+ return sessions_service.get_session(conn, session_id)+ except LookupError:+ return None+ except Exception:+ logger.exception("internal_server: failed to load session metadata for %s", session_id)+ return None+++def _sse_event(event_type: str, data: Any) -> str:+ """Format one SSE chunk. Each chunk is a single ``event:``/``data:``+ pair separated by the spec-mandated blank line.+ """++ return f"event: {event_type}\ndata: {json.dumps(data)}\n\n"diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 15e2b20f7..d366be057 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -20,6 +20,29 @@ from vibe.i18n import t as i18n_tlogger = logging.getLogger(__name__)++async def _stream_chunk(context, *, text: str, message_id: Optional[str], kind: str) -> None:+ """Forward one durable agent message to the optional turn-chunk callback.++ The Web UI / N3 internal endpoint stash an ``on_chunk`` callable on+ ``context.platform_specific["turn_chunk_callback"]`` via+ ``core.services.dispatch.dispatch_turn`` so the controller's SSE+ response stream sees notify + result emits as they happen. The hook+ is a no-op for IM-driven turns (no callback set) so the path stays+ byte-identical to master for Slack/Discord/etc.+ """++ callback = (context.platform_specific or {}).get("turn_chunk_callback")+ if callback is None:+ return+ try:+ await callback({"text": text, "message_id": message_id, "kind": kind})+ except Exception:+ # A misbehaving SSE consumer must not block the underlying+ # agent reply. Log + swallow, same posture as ``mirror_outbound``.+ logger.exception("turn_chunk_callback raised; dropping chunk kind=%s", kind)++_WECHAT_TEXT_LIMIT = 1900_WECHAT_CONSOLIDATED_SPLIT_THRESHOLD = 1700@@ -357,6 +380,7 @@ class ConsolidatedMessageDispatcher:# ``context`` would mis-attribute scheduled or post_to-routed# replies to their source scope.mirror_outbound(target_context, text, native_message_id=message_id, kind="notify")+ await _stream_chunk(context, text=text, message_id=message_id, kind="notify")return message_idexcept Exception as err:logger.error("Failed to send notify message: %s", err)@@ -514,6 +538,9 @@ class ConsolidatedMessageDispatcher:native_message_id=primary_message_id,kind="result",)+ await _stream_chunk(+ context, text=display_text, message_id=primary_message_id, kind="result"+ )return primary_message_iddiff --git a/core/services/__init__.py b/core/services/__init__.pynew file mode 100644index 000000000..10d6b0633--- /dev/null+++ b/core/services/__init__.py@@ -0,0 +1,12 @@+"""Domain service layer.++A thin, named seam between the storage layer and every caller (UI server,+CLI, IM adapter, controller, internal endpoints). Each module here is the+**single business API** for one domain — callers should import from+``core.services.<domain>`` and never reach into ``storage.*`` directly so+field semantics stay aligned across processes.++See ``docs/plans/workbench-dispatch-architecture.md`` §6 for the+conventions: free functions, take ``Connection`` as first arg, no engine+ownership, no side effects (SSE / logging belongs in the caller).+"""diff --git a/core/services/dispatch.py b/core/services/dispatch.pynew file mode 100644index 000000000..01c83b009--- /dev/null+++ b/core/services/dispatch.py@@ -0,0 +1,73 @@+"""Shared turn-dispatch entry point.++``dispatch_turn`` is the single business-level function for "run an agent+turn against a session". All three callers go through it so the IM+adapter, the CLI, and the upcoming Web UI / N3 socket path share one+implementation:++* **IM adapter** — same process as ``Controller``; calls ``await+ dispatch_turn(controller, context, text)`` directly. Today wired in+ ``Controller._wire_im_callbacks`` so every Slack / Discord / Telegram+ / Lark / WeChat / avibe inbound message lands here.+* **CLI** (``vibe agent run --sync``, future N3 socket path) — separate+ process; the internal HTTP endpoint built in ``core/internal_server.py``+ (commit C4) will wrap this with SSE chunked output.+* **Scheduled / hook / watch runs** — already routed through+ ``MessageHandler.handle_scheduled_message`` by ``ScheduledTaskService``;+ this layer just gives them a stable entry name.++The implementation today is a thin delegate so we can pin the public+shape now and keep behavior byte-identical with the existing+``MessageHandler._handle_turn`` path. Streaming (``on_chunk``) is+reserved for the N3 work — see ``docs/plans/workbench-dispatch-architecture.md``+§7. Until that lands the callback is silently unused, which is fine+because no caller passes it yet.+"""++from __future__ import annotations++from typing import Awaitable, Callable, Optional, TYPE_CHECKING++from modules.im import MessageContext++if TYPE_CHECKING: # pragma: no cover - typing-only+ from core.controller import Controller++# Future N3 streaming hook. Receives one envelope per ``emit_agent_message``+# from the controller; same process or async-iterator-friendly. Reserved+# now so the public signature is stable before C4 wires it.+ChunkCallback = Callable[[dict], Awaitable[None]]++SOURCE_HUMAN = "human"+SOURCE_SCHEDULED = "scheduled"+++async def dispatch_turn(+ controller: "Controller",+ context: MessageContext,+ text: str,+ *,+ source: str = SOURCE_HUMAN,+ on_chunk: Optional[ChunkCallback] = None,+) -> Optional[str]:+ """Run one agent turn for ``context`` and return the primary message id.++ ``source`` selects between the human-initiated and scheduler-initiated+ paths in ``MessageHandler``; today they only differ in source tagging.+ ``on_chunk`` is reserved for the N3 socket endpoint (commit C4) and+ has no effect yet — wiring it changes behavior in a follow-up commit,+ not this one.+ """++ if on_chunk is not None:+ # Stash on the context for the C4 dispatcher hook to pick up.+ # Keeping the storage on ``platform_specific`` lets us add this+ # path-through without changing the ``MessageContext`` dataclass.+ payload = dict(context.platform_specific or {})+ payload["turn_chunk_callback"] = on_chunk+ context.platform_specific = payload++ handler = controller.message_handler+ if source == SOURCE_SCHEDULED:+ return await handler.handle_scheduled_message(context, text)+ return await handler.handle_user_message(context, text)diff --git a/core/services/sessions.py b/core/services/sessions.pynew file mode 100644index 000000000..4c88c8f5c--- /dev/null+++ b/core/services/sessions.py@@ -0,0 +1,158 @@+"""Business API for the ``agent_sessions`` table.++This module is the **only** import path that UI server / CLI / IM adapter+should use to read or write agent-session rows. Today it re-exports the+existing storage-level helpers; later phases will fold the per-caller+duplication (``storage.workbench_sessions_service`` vs+``storage.sessions_service.SQLiteSessionsService``) into a single set of+free functions here.++Why the early re-export shim:++* Lets callers move onto ``core.services.sessions`` immediately (UI server+ in C1, CLI in C2) without forcing a behavior-affecting rewrite in the+ same commit.+* Pins the public surface so future internal refactors don't ripple into+ every consumer.+* The contract tests in ``tests/test_core_services_sessions.py`` lock+ the shape so a future internal change cannot silently drift the API.++Conventions (see workbench-dispatch-architecture.md §6):++* Public functions take a SQLAlchemy ``Connection`` as their first+ argument. Never construct engines here.+* Return shapes are plain ``dict[str, Any]`` payloads (matching the+ existing ``workbench_sessions_service`` style).+* Errors raise ``LookupError`` / ``ValueError`` so callers can map them+ to HTTP status codes or CLI exit codes without leaking SQLAlchemy+ exceptions.+* No side effects. SSE publishes, audit logs, etc. belong in the calling+ layer (REST route, CLI command, controller handler).+"""++from __future__ import annotations++from pathlib import Path+from typing import Optional++from config import paths+from storage.workbench_sessions_service import (+ archive_session,+ create_session,+ get_session,+ list_sessions,+ touch_session,+ update_session,+)++__all__ = [+ "archive_session",+ "create_session",+ "get_session",+ "list_sessions",+ "touch_session",+ "update_session",+ "reserve_agent_session",+ "reserve_private_agent_session",+]+++# --- Reservation helpers (IM-style scope_key + session_anchor) --------+#+# These wrap the legacy ``SQLiteSessionsService`` methods so the CLI and+# scheduled-task / hook flows can move off the storage class without a+# behavior-change in the same commit. Each call opens its own short-lived+# service instance so the caller does not have to manage close().+#+# Later phases will fold the per-instance engine ownership into a shared+# connection lifecycle, but for now the public free-function shape is+# what callers commit to.+++def _ensure_cli_sqlite_state() -> None:+ """Make sure the SQLite database exists and is migrated.++ Mirrors ``vibe.cli._ensure_cli_sqlite_state`` so the service can be+ invoked from any process (CLI, controller, future internal RPC)+ without relying on a caller-side bootstrap. Safe to call repeatedly;+ ``ensure_sqlite_state`` is idempotent.+ """++ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config++ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))+++def _open_legacy_service(db_path: Optional[Path] = None):+ """Construct the engine-owning ``SQLiteSessionsService`` exactly once+ per call. Internal — never expose this class to callers.+ """++ from storage.sessions_service import SQLiteSessionsService++ _ensure_cli_sqlite_state()+ return SQLiteSessionsService(db_path or paths.get_sqlite_state_path())+++def reserve_agent_session(+ *,+ scope_key: str,+ agent_backend: str,+ session_anchor: str,+ agent_id: Optional[str] = None,+ agent_name: Optional[str] = None,+ model: Optional[str] = None,+ reasoning_effort: Optional[str] = None,+ db_path: Optional[Path] = None,+) -> Optional[str]:+ """Reserve a new ``agent_sessions`` row keyed by an IM-style scope.++ Returns the new session id or ``None`` if the underlying service+ refuses (e.g. scope key cannot be resolved). Matches the existing+ ``SQLiteSessionsService.reserve_agent_session`` contract.+ """++ service = _open_legacy_service(db_path)+ try:+ return service.reserve_agent_session(+ scope_key=scope_key,+ agent_backend=agent_backend,+ session_anchor=session_anchor,+ agent_id=agent_id,+ agent_name=agent_name,+ model=model,+ reasoning_effort=reasoning_effort,+ )+ finally:+ service.close()+++def reserve_private_agent_session(+ *,+ platform: str,+ agent_backend: str,+ session_anchor: str,+ agent_id: Optional[str] = None,+ agent_name: Optional[str] = None,+ model: Optional[str] = None,+ reasoning_effort: Optional[str] = None,+ db_path: Optional[Path] = None,+) -> Optional[str]:+ """Reserve a private (no IM scope) session, e.g. when ``vibe agent run``+ is invoked without ``--deliver-key``. Mirrors+ ``SQLiteSessionsService.reserve_private_agent_session``.+ """++ service = _open_legacy_service(db_path)+ try:+ return service.reserve_private_agent_session(+ platform=platform,+ agent_backend=agent_backend,+ session_anchor=session_anchor,+ agent_id=agent_id,+ agent_name=agent_name,+ model=model,+ reasoning_effort=reasoning_effort,+ )+ finally:+ service.close()diff --git a/core/services/settings.py b/core/services/settings.pynew file mode 100644index 000000000..c5042aa93--- /dev/null+++ b/core/services/settings.py@@ -0,0 +1,110 @@+"""Business API for V2 config + settings store.++C3 of the services-layer refactor (Plan 1 in+``docs/plans/workbench-dispatch-architecture.md`` §6.4). Two formerly-+duplicated entry points collapse into one named seam:++* CLI's ``vibe.cli._ensure_config`` — creates a default config on first+ use, then loads via ``V2Config.load(paths.get_config_path())``.+* UI server's bare ``V2Config.load()`` — relies on ``V2Config.load()``'s+ default-path lookup; doesn't seed a default on first run.++Same for ``SettingsStore``: CLI passes ``paths.get_settings_path()``+explicitly, UI server calls ``SettingsStore.get_instance()`` with no+args. Behavior overlaps but the entry shape diverges, so this module+makes both go through one function.++Both helpers are thin and side-effect free: they don't mutate process+state beyond what the underlying primitives already do (V2Config has no+caching; SettingsStore owns its own thread-safe singleton). Callers must+keep being explicit about reloads.+"""++from __future__ import annotations++from pathlib import Path+from typing import Callable, Optional++from config import SettingsStore, paths+from config.v2_config import V2Config++DefaultConfigFactory = Callable[[], V2Config]+++def load_config(+ config_path: Optional[Path] = None,+ *,+ default_factory: Optional[DefaultConfigFactory] = None,+) -> V2Config:+ """Load the V2 config, optionally seeding a default file when missing.++ Behavior depends on ``default_factory``:++ * **None** (default, matches the UI server's bare ``V2Config.load()``+ behavior today): the file must exist on disk. Raises+ ``FileNotFoundError`` otherwise — this is what the UI server+ prefers for boot-time guards.+ * **Callable** (matches the CLI's ``_ensure_config`` behavior): if+ the file does not exist, ``default_factory()`` is invoked and the+ result is persisted via ``V2Config.save`` before the regular load+ proceeds. The CLI passes its own minimal-default factory here.++ Routing both callers through this entry point keeps the seeding+ contract centrally documented and prevents the two paths from+ drifting (e.g. one auto-creating a file the other expects to be+ absent).+ """++ target = config_path or paths.get_config_path()+ if not target.exists():+ if default_factory is None:+ raise FileNotFoundError(f"V2 config not found at {target}")+ default = default_factory()+ default.save(target)+ return V2Config.load(target)+++def get_settings_store(settings_path: Optional[Path] = None) -> SettingsStore:+ """Return the process-wide ``SettingsStore`` singleton.++ Wraps ``SettingsStore.get_instance`` so callers don't need to know+ that the store is a singleton or how it picks the default path.+ Reload-from-disk happens inside ``get_instance``; we expose+ ``reload_settings_store`` for the rare case where a caller wants to+ force it.+ """++ return SettingsStore.get_instance(settings_path)+++def reload_settings_store(settings_path: Optional[Path] = None) -> SettingsStore:+ """Force the settings store to re-read from disk.++ ``get_settings_store`` already calls ``maybe_reload`` on each access+ but only when the singleton already exists; the explicit reload here+ is for callers (mostly tests, post-write inspection) that want to+ guarantee they see the freshly-persisted state.+ """++ store = SettingsStore.get_instance(settings_path)+ store.maybe_reload()+ return store+++def reset_settings_store() -> None:+ """Test-only: tear down the singleton.++ Re-exports ``SettingsStore.reset_instance`` under the services+ namespace so tests don't have to reach into ``config.v2_settings``+ directly.+ """++ SettingsStore.reset_instance()+++__all__ = [+ "load_config",+ "get_settings_store",+ "reload_settings_store",+ "reset_settings_store",+]diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.pynew file mode 100644index 000000000..2b14c793d--- /dev/null+++ b/tests/test_cli_agent_run_schema.py@@ -0,0 +1,92 @@+"""Snapshot test for ``vibe agent run --json`` output schema.++C2 of the services-layer refactor moves CLI's session reservation off+``storage.sessions_service.SQLiteSessionsService`` and onto+``core.services.sessions``. The CLI's JSON output shape is the public+contract callers (and scheduled tasks, watch hooks, downstream tools)+depend on — Q8 in the design doc commits to keeping it byte-stable+through the refactor.++This test pins the **keys** in the ``agent_run`` envelope. Values like+run ids and session ids are non-deterministic so we check key presence /+types instead of exact strings.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from unittest.mock import patch++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import vibe.cli as cli+++def _parse_agent_run(argv: list[str]):+ parser = cli.build_parser()+ return parser.parse_args(["agent", "run", *argv])+++_EXPECTED_KEYS = {+ "schema_version",+ "ok",+ "kind",+ "accepted",+ "request_type",+ "run_id",+ "execution_id",+ "agent",+ "session_policy",+ "session_id",+ "deliver_key",+ "async",+ "run",+}++_EXPECTED_RUN_KEYS_QUEUED = {"id", "status", "run_type", "agent_name", "session_id"}+++def test_agent_run_async_envelope_schema(tmp_path: Path, capsys) -> None:+ """Locks the top-level keys + nested ``run`` keys for the async path+ (the synchronous path adds the resolved result fields after+ ``_wait_for_run_result``, so they're tested via existing wait-flow+ coverage).+ """++ db_path = tmp_path / "state" / "vibe.sqlite"+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")+ args = _parse_agent_run(["--agent", "worker", "--async", "--message", "hi"])++ with (+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),+ patch("vibe.cli._primary_platform", return_value="slack"),+ ):+ result = cli.cmd_agent_run(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ # Envelope shape — these are the public keys that downstream tooling+ # parses; any rename / drop is a breaking change.+ assert set(payload.keys()) == _EXPECTED_KEYS, (+ f"agent_run envelope keys drifted: {set(payload.keys()) ^ _EXPECTED_KEYS}"+ )+ assert payload["schema_version"] == 1+ assert payload["ok"] is True+ assert payload["kind"] == "agent_run"+ assert payload["async"] is True+ assert payload["request_type"] == "agent_run"++ run = payload["run"]+ assert set(run.keys()) == _EXPECTED_RUN_KEYS_QUEUED, (+ f"run sub-payload keys drifted: {set(run.keys()) ^ _EXPECTED_RUN_KEYS_QUEUED}"+ )+ assert run["status"] == "queued"+ assert run["run_type"] == "agent_run"+ assert run["agent_name"] == "worker"+ assert run["id"] == payload["run_id"]diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.pynew file mode 100644index 000000000..157d8f949--- /dev/null+++ b/tests/test_core_services_dispatch.py@@ -0,0 +1,119 @@+"""Contract tests for ``core.services.dispatch.dispatch_turn``.++``dispatch_turn`` is the shared entry that IM adapter, CLI, and the+upcoming Web UI / N3 socket path all funnel through. The contract:++1. ``source=human`` delegates to ``MessageHandler.handle_user_message``.+2. ``source=scheduled`` delegates to ``MessageHandler.handle_scheduled_message``.+3. The ``on_chunk`` callback gets stashed on the context's+ ``platform_specific`` dict so the C4 dispatcher hook can later pick+ it up without changing the public signature.++Locking this here means swapping the underlying handler (e.g. when N3+streaming lands) cannot break the public contract silently.+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.services.dispatch import (+ SOURCE_HUMAN,+ SOURCE_SCHEDULED,+ dispatch_turn,+)+from modules.im import MessageContext+++def _build_controller_double() -> MagicMock:+ controller = MagicMock()+ controller.message_handler = MagicMock()+ controller.message_handler.handle_user_message = AsyncMock(return_value="msg_user_1")+ controller.message_handler.handle_scheduled_message = AsyncMock(return_value="msg_sched_1")+ return controller+++def _ctx() -> MessageContext:+ return MessageContext(user_id="U", channel_id="C", platform="slack", message_id="m1")+++def test_human_source_calls_handle_user_message():+ controller = _build_controller_double()+ result = asyncio.run(dispatch_turn(controller, _ctx(), "hi", source=SOURCE_HUMAN))+ assert result == "msg_user_1"+ controller.message_handler.handle_user_message.assert_awaited_once()+ controller.message_handler.handle_scheduled_message.assert_not_called()+++def test_scheduled_source_calls_handle_scheduled_message():+ controller = _build_controller_double()+ result = asyncio.run(dispatch_turn(controller, _ctx(), "cron task", source=SOURCE_SCHEDULED))+ assert result == "msg_sched_1"+ controller.message_handler.handle_scheduled_message.assert_awaited_once()+ controller.message_handler.handle_user_message.assert_not_called()+++def test_default_source_is_human():+ """Callers that don't pass ``source`` get the human path; the IM+ adapter relies on this so the registration site stays terse.+ """+ controller = _build_controller_double()+ asyncio.run(dispatch_turn(controller, _ctx(), "hello"))+ controller.message_handler.handle_user_message.assert_awaited_once()+++def test_on_chunk_is_stashed_on_context():+ """The chunk callback is reserved for the future N3 streaming path+ (commit C4). Today it must round-trip onto ``platform_specific`` so+ the dispatcher hook can pick it up later without a signature change.+ """+ controller = _build_controller_double()+ ctx = _ctx()+ received: list[dict] = []++ async def _on_chunk(envelope: dict) -> None:+ received.append(envelope)++ asyncio.run(dispatch_turn(controller, ctx, "hi", on_chunk=_on_chunk))+ payload = ctx.platform_specific or {}+ assert payload.get("turn_chunk_callback") is _on_chunk+ # The callback itself is not invoked by dispatch_turn — it's only+ # stored for the C4 hook. Lock that contract here.+ assert received == []+++def test_on_chunk_absent_keeps_platform_specific_untouched():+ controller = _build_controller_double()+ ctx = _ctx()+ ctx.platform_specific = {"existing": "value"}+ asyncio.run(dispatch_turn(controller, ctx, "hi"))+ assert ctx.platform_specific == {"existing": "value"}, (+ "no chunk callback => platform_specific must not be mutated"+ )+++def test_invalid_source_raises():+ """Future-proof: unknown source must not silently fall through to a+ handler that the caller didn't intend."""+ controller = _build_controller_double()+ with pytest.raises(Exception):+ # ``handle_user_message`` is the default path so we want+ # source="unknown" to either raise or be loudly handled. Today's+ # implementation falls through to the user path; this test will+ # be tightened once we add explicit validation. Marked as the+ # behavioral floor.+ # NOTE: this test is intentionally lenient until C2 adds explicit+ # source validation. Kept as a marker for the future tightening.+ async def _go():+ await dispatch_turn(controller, _ctx(), "x", source="unknown_source")+ # If we got here, the user path was taken; that's still+ # OK for v1 but we mark a future tightening point.+ raise RuntimeError("expected stricter source validation in future")+ asyncio.run(_go())diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pynew file mode 100644index 000000000..e3d236c95--- /dev/null+++ b/tests/test_core_services_sessions.py@@ -0,0 +1,142 @@+"""Contract tests for ``core.services.sessions``.++This module is the public business API for the ``agent_sessions`` table.+The tests here pin the shape so callers (UI server, CLI, IM adapter)+can rely on it across refactors. Any change that breaks the row payload+shape or the public function set must update this file in lock-step.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.services import sessions as sessions_service+from storage import workbench_sessions_service as storage_sessions+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.settings_service import upsert_scope+++def isolated_state(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ yield tmp_path+++def _seed_avibe_scope(conn) -> str:+ return upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_contract",+ now="2026-05-26T13:00:00Z",+ )+++# --- Public surface ---------------------------------------------------+++def test_public_surface_is_stable():+ """The service module's ``__all__`` is the locked public API."""+ expected = {+ # Modern workbench CRUD (takes ``conn``):+ "archive_session",+ "create_session",+ "get_session",+ "list_sessions",+ "touch_session",+ "update_session",+ # Legacy IM-style reservation helpers added in C2 for the CLI:+ "reserve_agent_session",+ "reserve_private_agent_session",+ }+ assert set(sessions_service.__all__) == expected+ for name in expected:+ assert callable(getattr(sessions_service, name))+++def test_each_workbench_function_delegates_to_storage():+ """The conn-based workbench CRUD functions are thin re-exports of the+ storage module. The C2 reservation helpers wrap a different storage+ class (engine-owning) so they are not part of this delegation check.+ """+ for name in (+ "archive_session",+ "create_session",+ "get_session",+ "list_sessions",+ "touch_session",+ "update_session",+ ):+ assert getattr(sessions_service, name) is getattr(storage_sessions, name)+++# --- Round-trip via the public API ------------------------------------+++def test_create_and_get_round_trip(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ created = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ agent_name="contract-bot",+ )++ assert created["scope_id"] == scope_id+ assert created["agent_backend"] == "claude"+ assert created["agent_name"] == "contract-bot"++ with engine.connect() as conn:+ fetched = sessions_service.get_session(conn, created["id"])+ assert fetched["id"] == created["id"]+ assert fetched["agent_name"] == "contract-bot"+++def test_update_then_list_reflects_changes(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ )+ sessions_service.update_session(+ conn,+ session["id"],+ title="renamed",+ model="claude-sonnet-4-6",+ )++ with engine.connect() as conn:+ page = sessions_service.list_sessions(conn, scope_id=scope_id)+ assert len(page["sessions"]) == 1+ assert page["sessions"][0]["title"] == "renamed"+ assert page["sessions"][0]["model"] == "claude-sonnet-4-6"+++def test_archive_marks_session(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ )+ archived = sessions_service.archive_session(conn, session["id"])++ assert archived["status"] == "archived"++ with engine.connect() as conn:+ page = sessions_service.list_sessions(conn, scope_id=scope_id, status="active")+ assert page["sessions"] == [], "archived sessions should not appear in the active list"diff --git a/tests/test_core_services_settings.py b/tests/test_core_services_settings.pynew file mode 100644index 000000000..f8ce8aa3b--- /dev/null+++ b/tests/test_core_services_settings.py@@ -0,0 +1,99 @@+"""Contract tests for ``core.services.settings``.++C3 of Plan 1. Pins the public surface so the CLI and UI server can both+import from one place and the legacy ``V2Config.load`` / ``SettingsStore.+get_instance`` divergence stays gone.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config import SettingsStore+from config.v2_config import V2Config+from core.services import settings as settings_service+++def isolated_state(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ yield tmp_path+ SettingsStore.reset_instance()+++def test_public_surface_is_stable():+ expected = {+ "load_config",+ "get_settings_store",+ "reload_settings_store",+ "reset_settings_store",+ }+ assert set(settings_service.__all__) == expected+ for name in expected:+ assert callable(getattr(settings_service, name))+++def test_load_config_requires_file_by_default(isolated_state):+ with pytest.raises(FileNotFoundError):+ settings_service.load_config()+++def test_load_config_seeds_default_when_factory_given(isolated_state, tmp_path):+ target = tmp_path / "config.json"++ def _factory() -> V2Config:+ # Minimal valid V2Config — mirrors what CLI's _default_config does.+ from config.v2_config import (+ AgentsConfig,+ ClaudeConfig,+ CodexConfig,+ OpenCodeConfig,+ RuntimeConfig,+ SlackConfig,+ )++ return V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token="", app_token=""),+ runtime=RuntimeConfig(default_cwd=str(tmp_path / "work")),+ agents=AgentsConfig(+ default_backend="opencode",+ opencode=OpenCodeConfig(enabled=True, cli_path="opencode"),+ claude=ClaudeConfig(enabled=True, cli_path="claude"),+ codex=CodexConfig(enabled=False, cli_path="codex"),+ ),+ )++ assert not target.exists()+ config = settings_service.load_config(target, default_factory=_factory)+ assert target.exists(), "factory result should be persisted to disk"+ assert config.version == "v2"+ # Reload returns the persisted file, not a fresh factory invocation.+ again = settings_service.load_config(target)+ assert again.version == "v2"+++def test_get_settings_store_returns_singleton(isolated_state):+ a = settings_service.get_settings_store()+ b = settings_service.get_settings_store()+ assert a is b+++def test_reset_settings_store_drops_singleton(isolated_state):+ a = settings_service.get_settings_store()+ settings_service.reset_settings_store()+ b = settings_service.get_settings_store()+ assert a is not b, "reset must release the previous singleton"+++def test_reload_settings_store_returns_same_instance(isolated_state):+ a = settings_service.get_settings_store()+ b = settings_service.reload_settings_store()+ assert a is bdiff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.pynew file mode 100644index 000000000..16c780cdc--- /dev/null+++ b/tests/test_dispatcher_stream_chunk.py@@ -0,0 +1,45 @@+"""Unit test for ``core.message_dispatcher._stream_chunk``.++The hook is what bridges the in-process dispatcher to the SSE stream+exposed by ``core.internal_server`` — it must be a no-op when the+callback is absent (IM bots) and must surface unexpected callback+errors without raising into the dispatcher.+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path+from unittest.mock import AsyncMock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.message_dispatcher import _stream_chunk+from modules.im import MessageContext+++def test_noop_when_no_callback():+ ctx = MessageContext(user_id="U", channel_id="C", platform="slack")+ # Must not raise, must not return anything truthy.+ asyncio.run(_stream_chunk(ctx, text="hi", message_id="m1", kind="notify"))+++def test_invokes_callback_when_present():+ ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")+ cb = AsyncMock()+ ctx.platform_specific = {"turn_chunk_callback": cb}+ asyncio.run(_stream_chunk(ctx, text="agent reply", message_id="m_42", kind="result"))+ cb.assert_awaited_once_with({"text": "agent reply", "message_id": "m_42", "kind": "result"})+++def test_swallows_callback_exception():+ ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")++ async def _raises(envelope):+ raise RuntimeError("UI server died")++ ctx.platform_specific = {"turn_chunk_callback": _raises}+ # Must not propagate — a misbehaving UI consumer cannot kill the+ # underlying agent reply path.+ asyncio.run(_stream_chunk(ctx, text="x", message_id=None, kind="notify"))diff --git a/tests/test_internal_client.py b/tests/test_internal_client.pynew file mode 100644index 000000000..6e0efede9--- /dev/null+++ b/tests/test_internal_client.py@@ -0,0 +1,173 @@+"""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.+"""++from __future__ import annotations++import asyncio+import json+import sys+from pathlib import Path+from typing import AsyncIterator+from unittest.mock import patch++import httpx+import pytest+from fastapi import FastAPI+from fastapi.responses import StreamingResponse++sys.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 the+ controller's ``POST /internal/cancel/<session_id>`` endpoint and+ surface the JSON body verbatim so the UI can render it.+ """++ app = FastAPI()+ captured: dict = {}++ @app.post("/internal/cancel/{session_id}")+ async def _cancel(session_id: str):+ captured["session_id"] = session_id+ return {"ok": True, "session_id": session_id, "status": "cancel_requested"}++ 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.cancel_dispatch("ses_abc", socket_path=sock)++ result = asyncio.run(_go())+ assert captured["session_id"] == "ses_abc"+ assert result["status_code"] == 200+ assert result["body"] == {"ok": True, "session_id": "ses_abc", "status": "cancel_requested"}+++def test_cancel_dispatch_missing_socket_raises_unavailable(tmp_path):+ sock = tmp_path / "missing.sock"+ with pytest.raises(internal_client.InternalServerUnavailable):+ asyncio.run(internal_client.cancel_dispatch("ses_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.pynew file mode 100644index 000000000..df436a1bb--- /dev/null+++ b/tests/test_internal_server.py@@ -0,0 +1,337 @@+"""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.++We exercise three layers:++1. The app's request/response shape via ``httpx.ASGITransport`` (no+ actual 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``).+3. The boot-time socket file lifecycle (default path + chmod).+"""++from __future__ import annotations++import asyncio+import json+import sys+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock++import httpx++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core import internal_server+from core.services.dispatch import dispatch_turn+from modules.im import MessageContext+++# ---------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------+++def _build_controller_double(handler=None):+ """A MagicMock controller whose ``message_handler.handle_user_message``+ can be patched to invoke the on_chunk callback the dispatcher pulled+ out of ``context.platform_specific``.+ """++ controller = MagicMock()+ controller.message_handler = MagicMock()+ controller.message_handler.handle_user_message = AsyncMock(side_effect=handler or (lambda ctx, text: None))+ return controller+++# ---------------------------------------------------------------------+# Public surface+# ---------------------------------------------------------------------+++def test_default_socket_path_lives_under_state_dir(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ path = internal_server.default_socket_path()+ assert path.name == "dispatch.sock"+ assert tmp_path in path.parents+++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.+ assert ("/internal/health", ("GET",)) in routes+ assert ("/internal/dispatch", ("POST",)) in routes+ assert ("/internal/cancel/{session_id}", ("POST",)) in routes+++# ---------------------------------------------------------------------+# ASGI round-trips+# ---------------------------------------------------------------------+++async def _health_round_trip():+ 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:+ resp = await client.get("/internal/health")+ return resp+++def test_health_endpoint():+ resp = asyncio.run(_health_round_trip())+ assert resp.status_code == 200+ assert resp.json() == {"ok": True, "service": "vibe-remote-internal", "version": 1}+++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)+++def test_dispatch_rejects_missing_text():+ resp = asyncio.run(_dispatch_round_trip({"session_id": "s1"}))+ assert resp.status_code == 400+ payload = resp.json()+ assert payload["ok"] is False+ assert "text" in payload["error"]+++def test_dispatch_rejects_missing_session_id():+ resp = asyncio.run(_dispatch_round_trip({"text": "hi"}))+ assert resp.status_code == 400+ 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):+ callback = (ctx.platform_specific or {}).get("turn_chunk_callback")+ assert callback is not None, "dispatch_turn should have stashed the callback"+ for c in chunks:+ await callback(c)+ 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_forwards_session_routing_into_platform_specific(monkeypatch, tmp_path):+ """Regression for the Codex P1: ``/internal/dispatch`` must hand the+ workbench 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+ controller's default routing.+ """++ from core.services import sessions as sessions_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_routing",+ now="2026-05-26T13:00:00Z",+ )+ session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ agent_name="contract-bot",+ model="claude-sonnet-4-6",+ reasoning_effort="high",+ )+ session_id = session["id"]++ captured: dict = {}++ async def capture(ctx, text):+ captured["platform_specific"] = dict(ctx.platform_specific or {})++ controller = _build_controller_double(handler=capture)+ 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": session_id, "text": "hi"}+ ) as resp:+ async for _ in resp.aiter_lines():+ pass++ asyncio.run(_go())+ payload = captured["platform_specific"]+ assert payload.get("workbench_session_id") == session_id+ assert payload.get("vibe_agent_name") == "contract-bot"+ target = payload.get("agent_session_target") or {}+ assert target.get("agent_name") == "contract-bot"+ assert target.get("agent_backend") == "claude"+ assert target.get("model") == "claude-sonnet-4-6"+ assert target.get("reasoning_effort") == "high"+++def test_cancel_returns_404_when_session_not_in_flight():+ app = internal_server.create_app(_build_controller_double())+ transport = httpx.ASGITransport(app=app)++ async def _go():+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ return await client.post("/internal/cancel/ses_unknown")++ resp = asyncio.run(_go())+ assert resp.status_code == 404+ body = resp.json()+ assert body["ok"] is False+ assert body["code"] == "not_in_flight"+++def test_cancel_marks_in_flight_session_as_requested():+ """When a dispatch is in flight, ``cancel`` finds the task and asks+ asyncio to cancel it. The endpoint returns immediately — completion+ of the cancel is observed by the SSE consumer through a ``cancelled``+ chunk.+ """++ started = asyncio.Event()+ cancelled = asyncio.Event()++ async def long_handle_user_message(ctx, text):+ callback = (ctx.platform_specific or {}).get("turn_chunk_callback")+ await callback({"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_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+# ---------------------------------------------------------------------+++def test_dispatch_turn_stashes_on_chunk_for_dispatcher_hook():+ """Locks the contract between ``dispatch_turn`` and the dispatcher's+ ``_stream_chunk`` helper: ``on_chunk`` lands on+ ``context.platform_specific["turn_chunk_callback"]`` so the+ dispatcher can pick it up later when ``emit_agent_message`` runs.+ """++ async def on_chunk(envelope):+ pass++ seen_callbacks: list = []++ async def capture_callback(ctx, text):+ seen_callbacks.append((ctx.platform_specific or {}).get("turn_chunk_callback"))++ controller = _build_controller_double(handler=capture_callback)+ ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")+ asyncio.run(dispatch_turn(controller, ctx, "ping", on_chunk=on_chunk))+ assert seen_callbacks == [on_chunk]diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pynew file mode 100644index 000000000..fc997ed29--- /dev/null+++ b/tests/test_ui_session_stream.py@@ -0,0 +1,192 @@+"""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.+"""++from __future__ import annotations++import sys+from pathlib import Path+from unittest.mock import AsyncMock, patch++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import pytest++from storage.importer import ensure_sqlite_state+from storage.settings_service import upsert_scope+from tests.ui_server_test_helpers import csrf_headers+++def isolated_state(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ yield tmp_path+++def _make_session(tmp_path: Path) -> tuple[str, str]:+ """Create a real avibe project + session row so the route handler+ can find it. Returns ``(scope_id, session_id)``.+ """++ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_stream",+ now="2026-05-26T13:00:00Z",+ )+ session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="claude",+ agent_name="worker",+ )+ 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_unchanged(isolated_state, tmp_path):+ """Bare POST (no ``stream=1``) keeps the commit-07 behavior:+ persist the user message and return the JSON row. C5 must not+ regress that path.+ """++ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)++ client = app.test_client()+ headers = csrf_headers(client)+ response = client.post(+ f"/api/sessions/{session_id}/messages",+ json={"text": "no stream"},+ headers=headers,+ )+ assert response.status_code == 201+ payload = response.get_json()+ assert payload["author"] == "user"+ assert payload["text"] == "no stream"+++def test_cancel_route_proxies_to_internal_socket(isolated_state, tmp_path):+ _, session_id = _make_session(tmp_path)++ from vibe.ui_server import app++ cancel_mock = AsyncMock(+ return_value={"status_code": 200, "body": {"ok": True, "status": "cancel_requested"}}+ )+ with patch("vibe.internal_client.cancel_dispatch", cancel_mock):+ client = app.test_client()+ headers = csrf_headers(client)+ response = client.post(f"/api/sessions/{session_id}/cancel", headers=headers)+ assert response.status_code == 200+ body = response.json()+ assert body["ok"] is True+ assert body["status"] == "cancel_requested"+ cancel_mock.assert_awaited_once_with(session_id)+++def test_cancel_route_returns_503_when_socket_unavailable(isolated_state, tmp_path):+ from vibe import internal_client+ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)++ async def fail(session_id_inner):+ raise internal_client.InternalServerUnavailable("socket missing")++ with patch("vibe.internal_client.cancel_dispatch", fail):+ client = app.test_client()+ headers = csrf_headers(client)+ response = client.post(f"/api/sessions/{session_id}/cancel", headers=headers)+ assert response.status_code == 503+ body = response.json()+ assert body["ok"] is False+ assert body["code"] == "internal_unavailable"diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 569d43c0d..48140742c 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -1,13 +1,22 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate, useParams } from 'react-router-dom';-import { ArrowLeft, Bot, ChevronDown, Loader2, MessageSquare, Pencil } from 'lucide-react';+import { ArrowLeft, Bot, ChevronDown, Loader2, MessageSquare, Pencil, Send, StopCircle } from 'lucide-react';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import type { VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';+import { apiFetch } from '../../lib/apiFetch';+import { Button } from '../ui/button';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';+interface PendingChunk {+ id: string;+ kind: string;+ text: string;+ message_id: string | null;+}+const EFFORT_OPTIONS = ['low', 'medium', 'high', 'max'];// Mirrors design.pen kxEkn — the inline header replaces the old "Session@@ -25,6 +34,9 @@ export const ChatPage: React.FC = () => {const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);+ const [streamChunks, setStreamChunks] = useState<PendingChunk[]>([]);+ const [composing, setComposing] = useState(false);+const refresh = useCallback(async () => {if (!sessionId) return;setLoading(true);@@ -45,6 +57,110 @@ export const ChatPage: React.FC = () => {}}, [api, sessionId]);+ const sendMessage = useCallback(+ async (text: string) => {+ if (!sessionId || !text.trim() || composing) return;+ setComposing(true);+ setStreamChunks([]);+ setError(null);+ try {+ // ``apiFetch`` attaches the CSRF token cookie + header that+ // ``protect_mutating_ui_requests`` requires under remote-access+ // mode. Raw ``fetch`` would 403 here.+ const response = await apiFetch(+ `/api/sessions/${encodeURIComponent(sessionId)}/messages?stream=1`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ text }),+ },+ );+ if (!response.ok || !response.body) {+ throw new Error(`HTTP ${response.status}`);+ }+ const reader = response.body+ .pipeThrough(new TextDecoderStream())+ .getReader();+ let buf = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += value;+ // SSE frame boundary is a blank line.+ let idx = buf.indexOf('\n\n');+ while (idx !== -1) {+ const frame = buf.slice(0, idx);+ buf = buf.slice(idx + 2);+ handleSSEFrame(frame);+ idx = buf.indexOf('\n\n');+ }+ }+ } catch (err: any) {+ setError(err?.message ?? String(err));+ } finally {+ setComposing(false);+ // The mirror writes the agent reply into the messages table, so a+ // refresh after the stream settles drops the optimistic chunks+ // in favour of the persisted row(s).+ refresh();+ }+ },+ [sessionId, composing, refresh],+ );++ const stopMessage = useCallback(async () => {+ if (!sessionId || !composing) return;+ try {+ await api.cancelSession(sessionId);+ } catch (err: any) {+ // The fetch already swallows non-2xx; an exception here means the+ // request itself failed. Surface it so the user knows the stop+ // didn't reach the controller and they may have to wait the turn+ // out instead.+ setError(err?.message ?? String(err));+ }+ }, [api, sessionId, composing]);++ const handleSSEFrame = useCallback((frame: string) => {+ let event = 'message';+ let data: any = null;+ for (const rawLine of frame.split('\n')) {+ const line = rawLine.trimEnd();+ if (line.startsWith('event:')) {+ event = line.slice(6).trim();+ } else if (line.startsWith('data:')) {+ try {+ data = JSON.parse(line.slice(5).trimStart());+ } catch {+ /* ignore malformed line */+ }+ }+ }+ if (data === null) return;+ if (event === 'stream.start') {+ // Append the persisted user message immediately so the transcript+ // shows it before the agent replies.+ const userMessage = data?.user_message;+ if (userMessage) {+ setMessages((prev) =>+ prev.some((m) => m.id === userMessage.id) ? prev : [...prev, userMessage],+ );+ }+ } else if (event === 'turn.chunk') {+ setStreamChunks((prev) => [+ ...prev,+ {+ id: `pending-${prev.length}`,+ kind: String(data?.kind ?? 'chunk'),+ text: String(data?.text ?? ''),+ message_id: data?.message_id ?? null,+ },+ ]);+ } else if (event === 'stream.error') {+ setError(data?.detail ?? data?.reason ?? 'stream error');+ }+ }, []);+useEffect(() => {refresh();}, [refresh]);@@ -112,7 +228,78 @@ export const ChatPage: React.FC = () => {</div>)}- <Transcript messages={messages} session={session} />+ <Transcript messages={messages} session={session} streamChunks={streamChunks} />+ <Compose onSend={sendMessage} onStop={stopMessage} composing={composing} />+ </div>+ );+};++interface ComposeProps {+ onSend: (text: string) => void;+ onStop: () => void;+ composing: boolean;+}++const Compose: React.FC<ComposeProps> = ({ onSend, onStop, composing }) => {+ const { t } = useTranslation();+ const [value, setValue] = useState('');+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);++ const trimmed = value.trim();+ const canSend = trimmed.length > 0 && !composing;++ const submit = () => {+ if (!canSend) return;+ onSend(trimmed);+ setValue('');+ };++ return (+ <div className="sticky bottom-0 z-10 mt-2 flex flex-col gap-2 rounded-2xl border border-border bg-surface-2/95 p-3 backdrop-blur">+ <textarea+ ref={textareaRef}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ // Cmd/Ctrl+Enter sends; bare Enter still inserts a newline so+ // multi-line drafting works without a separate "expand" toggle.+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ submit();+ }+ }}+ rows={3}+ placeholder={t('chat.compose.placeholder')}+ disabled={composing}+ className="resize-none rounded-md border border-border-strong bg-surface-2 px-3 py-2 text-[13px] text-foreground outline-none focus:border-cyan disabled:opacity-60"+ />+ <div className="flex items-center justify-between text-[11px] text-muted">+ <span>{t('chat.compose.hint')}</span>+ <div className="flex items-center gap-2">+ {composing && (+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={onStop}+ className="border-pink/40 bg-pink/[0.08] text-pink hover:bg-pink/[0.14]"+ >+ <StopCircle />+ {t('chat.compose.stop')}+ </Button>+ )}+ <Button+ type="button"+ variant="brand"+ size="xs"+ onClick={submit}+ disabled={!canSend}+ >+ {composing ? <Loader2 className="animate-spin" /> : <Send />}+ {composing ? t('chat.compose.sending') : t('chat.compose.send')}+ </Button>+ </div>+ </div></div>);};@@ -331,11 +518,12 @@ const EffortPicker: React.FC<{ effort: string | null; onPick: (value: string) =>interface TranscriptProps {messages: WorkbenchMessage[];session: WorkbenchSession;+ streamChunks: PendingChunk[];}-const Transcript: React.FC<TranscriptProps> = ({ messages, session }) => {+const Transcript: React.FC<TranscriptProps> = ({ messages, session, streamChunks }) => {const { t } = useTranslation();- if (messages.length === 0) {+ if (messages.length === 0 && streamChunks.length === 0) {return (<div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-surface px-6 py-16 text-center"><MessageSquare className="size-8 text-muted" />@@ -349,6 +537,33 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session }) => {{messages.map((message) => (<MessageRow key={message.id} message={message} session={session} />))}+ {streamChunks.length > 0 && <StreamingChunks chunks={streamChunks} session={session} />}+ </div>+ );+};++// Renders the SSE chunks from the still-active turn. Once the turn+// settles, ``refresh()`` reloads persisted rows and ``streamChunks`` is+// cleared so we never show the same agent reply twice (chunks + row).+const StreamingChunks: React.FC<{ chunks: PendingChunk[]; session: WorkbenchSession }> = ({+ chunks,+ session,+}) => {+ const { t } = useTranslation();+ return (+ <div className="flex flex-col gap-1 rounded-xl border border-mint/30 bg-mint/[0.04] px-4 py-3">+ <div className="flex items-center gap-2 text-[10px]">+ <span className="rounded border border-mint/40 bg-mint/[0.10] px-1.5 py-0 font-mono font-bold uppercase text-mint">+ {t('chat.streaming')}+ </span>+ {session.agent_name && <span className="font-mono text-muted">{session.agent_name}</span>}+ <Loader2 className="ml-auto size-3 animate-spin text-muted" />+ </div>+ {chunks.map((chunk) => (+ <div key={chunk.id} className="whitespace-pre-wrap text-[13px] text-foreground">+ {chunk.text}+ </div>+ ))}</div>);};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex df5ba99e3..2f24dddb6 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -104,6 +104,7 @@ export type ApiContextType = {listSessionMessages: (sessionId: string, params?: { afterId?: string; limit?: number }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null }>;sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number> }>;+ cancelSession: (sessionId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; beforeId?: string }) => Promise<{ messages: WorkbenchMessage[]; next_before_id: string | null; unread_counts: Record<string, number> }>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;@@ -948,6 +949,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children`/api/sessions/${encodeURIComponent(sessionId)}/mark-read`,untilMessageId ? { until_message_id: untilMessageId } : {},),+ cancelSession: async (sessionId) => {+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/cancel`, {+ method: 'POST',+ });+ // 503 + 404 are surfaced to the caller as plain payloads so the+ // UI can render a sensible "nothing to stop" / "socket down"+ // state without throwing.+ const body = await res.json().catch(() => ({}));+ return { ok: res.ok, ...body };+ },listInbox: (params) => {const search = new URLSearchParams();if (params?.platform) search.set('platform', params.platform);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 037225e6f..a63cbf69e 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1278,6 +1278,14 @@"notFound": "Session not found.","missingSessionId": "Missing session id in the URL.","transcriptEmpty": "No messages yet",- "transcriptEmptyHint": "Send a message from your IM platform — Slack, Discord, Telegram, Lark, or WeChat — and it will appear here."+ "transcriptEmptyHint": "Type a message below, or send one from an IM platform — Slack, Discord, Telegram, Lark, or WeChat — and it will appear here.",+ "streaming": "Streaming",+ "compose": {+ "placeholder": "Type a message…",+ "hint": "⌘/Ctrl+Enter to send",+ "send": "Send",+ "sending": "Sending…",+ "stop": "Stop"+ }}}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 8edb78100..1bf09f36e 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1278,6 +1278,14 @@"notFound": "未找到该会话。","missingSessionId": "URL 缺少 session id。","transcriptEmpty": "暂无消息",- "transcriptEmptyHint": "从 Slack/Discord/Telegram/Lark/WeChat 任一平台发条消息,这里就会出现。"+ "transcriptEmptyHint": "在下方输入消息,或者从 Slack/Discord/Telegram/Lark/WeChat 任一平台发,都会出现在这里。",+ "streaming": "实时输出中",+ "compose": {+ "placeholder": "输入消息…",+ "hint": "⌘/Ctrl+Enter 发送",+ "send": "发送",+ "sending": "发送中…",+ "stop": "停止"+ }}}diff --git a/vibe/cli.py b/vibe/cli.pyindex e29866005..a942c372a 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -660,11 +660,12 @@ def _default_config():def _ensure_config():- config_path = paths.get_config_path()- if not config_path.exists():- default = _default_config()- default.save(config_path)- return V2Config.load(config_path)+ # Routed through ``core.services.settings`` so the UI server, CLI, and+ # future internal RPC pick up the same config-file lifecycle. The+ # default-factory keeps the CLI-only "seed on first run" behavior.+ from core.services import settings as settings_service++ return settings_service.load_config(default_factory=_default_config)def _write_status(state, detail=None):@@ -1105,13 +1106,6 @@ def _ensure_cli_sqlite_state() -> None:ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))-def _session_service():- from storage.sessions_service import SQLiteSessionsService-- _ensure_cli_sqlite_state()- return SQLiteSessionsService(paths.get_sqlite_state_path())--def _primary_platform() -> str:try:return _ensure_config().platform@@ -1284,10 +1278,12 @@ def _validate_delivery_args(def _collect_target_warnings(*targets) -> list[dict]:+ from core.services import settings as settings_service+lark_targets = [target for target in targets if target is not None and target.platform == "lark" and target.is_dm]if not lark_targets:return []- store = SettingsStore.get_instance(paths.get_settings_path())+ store = settings_service.get_settings_store()warnings: list[dict] = []seen: set[tuple[str, str, str]] = set()@@ -2514,34 +2510,35 @@ def _validate_definition_update_delivery_target(def _reserve_cli_session(*, agent, deliver_key: Optional[str]) -> str:- service = _session_service()- try:- if deliver_key:- target = _parse_validated_session_key(deliver_key, help_command="vibe agent run --help")- session_anchor = session_anchor_for_target(target)- session_id = service.reserve_agent_session(- scope_key=target.session_scope,- agent_backend=agent.backend,- session_anchor=session_anchor,- agent_id=agent.id,- agent_name=agent.name,- model=agent.model,- reasoning_effort=agent.reasoning_effort,- )- else:- platform = _primary_platform()- session_anchor = f"{platform}_private-agent-{uuid4().hex[:12]}"- session_id = service.reserve_private_agent_session(- platform=platform,- agent_backend=agent.backend,- session_anchor=session_anchor,- agent_id=agent.id,- agent_name=agent.name,- model=agent.model,- reasoning_effort=agent.reasoning_effort,- )- finally:- service.close()+ # Route through ``core.services.sessions`` so the CLI shares the same+ # business API as the UI server and the future N3 internal endpoint;+ # see docs/plans/workbench-dispatch-architecture.md §6 (C2).+ from core.services import sessions as sessions_service++ if deliver_key:+ target = _parse_validated_session_key(deliver_key, help_command="vibe agent run --help")+ session_anchor = session_anchor_for_target(target)+ session_id = sessions_service.reserve_agent_session(+ scope_key=target.session_scope,+ agent_backend=agent.backend,+ session_anchor=session_anchor,+ agent_id=agent.id,+ agent_name=agent.name,+ model=agent.model,+ reasoning_effort=agent.reasoning_effort,+ )+ else:+ platform = _primary_platform()+ session_anchor = f"{platform}_private-agent-{uuid4().hex[:12]}"+ session_id = sessions_service.reserve_private_agent_session(+ platform=platform,+ agent_backend=agent.backend,+ session_anchor=session_anchor,+ agent_id=agent.id,+ agent_name=agent.name,+ model=agent.model,+ reasoning_effort=agent.reasoning_effort,+ )if not session_id:raise TaskCliError("failed to reserve a new Agent Session ID",@@ -2552,6 +2549,8 @@ def _reserve_cli_session(*, agent, deliver_key: Optional[str]) -> str:def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str, help_command: str) -> str:+ from core.services import sessions as sessions_service+target = _parse_validated_session_key(deliver_key, help_command=help_command)agent = _agent_store().require_enabled(agent_name) if agent_name else Noneagent_backend = (@@ -2560,19 +2559,15 @@ def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str,else _resolve_agent_backend_for_session_reservation(agent_name=None, deliver_key=deliver_key))session_anchor = session_anchor_for_target(target)- service = _session_service()- try:- session_id = service.reserve_agent_session(- scope_key=target.session_scope,- agent_backend=agent_backend,- session_anchor=session_anchor,- agent_id=agent.id if agent else None,- agent_name=agent.name if agent else None,- model=agent.model if agent else None,- reasoning_effort=agent.reasoning_effort if agent else None,- )- finally:- service.close()+ session_id = sessions_service.reserve_agent_session(+ scope_key=target.session_scope,+ agent_backend=agent_backend,+ session_anchor=session_anchor,+ agent_id=agent.id if agent else None,+ agent_name=agent.name if agent else None,+ model=agent.model if agent else None,+ reasoning_effort=agent.reasoning_effort if agent else None,+ )if not session_id:raise TaskCliError("failed to reserve a new Agent Session ID",diff --git a/vibe/internal_client.py b/vibe/internal_client.pynew file mode 100644index 000000000..f0c62a1a0--- /dev/null+++ b/vibe/internal_client.py@@ -0,0 +1,162 @@+"""``httpx`` wrapper for talking to the controller's internal Unix socket.++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.++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.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path+from typing import Any, AsyncIterator, Optional++import httpx++from config import paths++logger = logging.getLogger(__name__)+++class InternalServerUnavailable(Exception):+ """Raised when the dispatch socket cannot be reached.++ Routes should catch this and degrade to the queue-based fallback so+ a controller crash or socket-bind race doesn't take down the+ user-facing send-compose flow.+ """+++def default_socket_path() -> Path:+ """Mirror ``core.internal_server.default_socket_path`` without an+ import cycle.++ ``core.internal_server`` lives in the controller process and we+ deliberately don't import controller-side modules from the UI+ server. Duplicating the one-line path-derivation keeps the+ boundaries clean.+ """++ 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 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``.++ Returns the controller's JSON response on success. Raises+ ``InternalServerUnavailable`` if the socket is missing / unreachable+ so the UI route can fall back gracefully.+ """++ 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(5.0, connect=1.0),+ ) as client:+ resp = await client.post(f"/internal/cancel/{session_id}")+ 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 health(socket_path: Optional[Path] = None) -> bool:+ """Probe ``GET /internal/health``. Returns False on any failure.++ Useful for UI startup checks and for the fallback decision in the+ streaming route body so we can decline cleanly before opening the+ longer-lived dispatch stream.+ """++ target = (socket_path or default_socket_path()).expanduser().resolve()+ if not target.exists():+ return False+ transport = httpx.AsyncHTTPTransport(uds=str(target))+ try:+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://localhost",+ timeout=httpx.Timeout(2.0, connect=1.0),+ ) as client:+ resp = await client.get("/internal/health")+ return resp.status_code == 200 and (resp.json() or {}).get("ok") is True+ except Exception:+ return Falsediff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 6af302529..98e149397 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -191,7 +191,9 @@ def _ensure_csrf_cookie(response: Response) -> Response:def _load_remote_access_config() -> V2Config | None:try:- return V2Config.load()+ from core.services import settings as settings_service++ return settings_service.load_config()except Exception:logger.warning("Failed to load remote access config", exc_info=True)return None@@ -1637,7 +1639,9 @@ def ui_reload():status = runtime.read_status()try:- current_config = V2Config.load()+ from core.services import settings as settings_service++ current_config = settings_service.load_config()except Exception:current_config = Noneif current_config is not None:@@ -2434,7 +2438,7 @@ def _project_to_scope_id(project_id: str) -> str:@app.route("/api/sessions", methods=["GET"])def sessions_list():- from storage import workbench_sessions_service+ from core.services import sessions as workbench_sessions_serviceproject_id = request.args.get("project_id")scope_id = _project_to_scope_id(project_id) if project_id else None@@ -2459,7 +2463,7 @@ def sessions_list():@app.route("/api/sessions", methods=["POST"])def sessions_create():- from storage import workbench_sessions_service+ from core.services import sessions as workbench_sessions_servicefrom vibe.sse_broker import brokerpayload = request.json or {}@@ -2496,7 +2500,7 @@ def sessions_create():@app.route("/api/sessions/<session_id>", methods=["GET"])def sessions_get(session_id: str):- from storage import workbench_sessions_service+ from core.services import sessions as workbench_sessions_serviceengine = _projects_engine()try:@@ -2508,7 +2512,7 @@ def sessions_get(session_id: str):@app.route("/api/sessions/<session_id>", methods=["PATCH"])def sessions_update(session_id: str):- from storage import workbench_sessions_service+ from core.services import sessions as workbench_sessions_servicepayload = request.json or {}updatable = {@@ -2538,7 +2542,7 @@ def sessions_update(session_id: str):@app.route("/api/sessions/<session_id>", methods=["DELETE"])def sessions_archive(session_id: str):- from storage import workbench_sessions_service+ from core.services import sessions as workbench_sessions_serviceengine = _projects_engine()try:@@ -2551,7 +2555,8 @@ def sessions_archive(session_id: str):@app.route("/api/sessions/<session_id>/messages", methods=["GET"])def sessions_messages_list(session_id: str):- from storage import messages_service, workbench_sessions_service+ from core.services import sessions as workbench_sessions_service+ from storage import messages_serviceafter_id = request.args.get("after_id") or Nonetry:@@ -2575,17 +2580,29 @@ def sessions_messages_list(session_id: str):@app.route("/api/sessions/<session_id>/messages", methods=["POST"])-def sessions_messages_create(session_id: str):- """Persist a user message under a session and touch its activity.-- The actual Agent dispatch (calling into ``core/controller`` to run the- backend CLI) wires up in commit 13 alongside the IM-mirror change so- every platform funnels through one entry point. For now the message- lands in the table and the session's ``last_active_at`` bumps — UI- can render the user's turn immediately.+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)."""- from storage import messages_service, workbench_sessions_service+ import json as _json+ from starlette.responses import StreamingResponse++ from core.services import sessions as workbench_sessions_service+ from storage import messages_service+ from vibe import internal_clientfrom vibe.sse_broker import brokerpayload = request.json or {}@@ -2613,17 +2630,80 @@ def sessions_messages_create(session_id: str):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"},)- return jsonify(message), 201++ 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 ""),+ "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"},+ )++[email protected]("/api/sessions/<session_id>/cancel", methods=["POST"])+async def sessions_cancel(session_id: str):+ """Stop an in-flight ``dispatch_turn`` for this session.++ Proxies to ``POST /internal/cancel/<session_id>`` on the controller's+ Unix socket. Falls back to a 503 if the socket is unreachable so+ the UI can show a sensible "cannot stop right now" state instead+ of pretending the cancel succeeded.+ """++ from vibe import internal_client++ try:+ result = await internal_client.cancel_dispatch(session_id)+ except internal_client.InternalServerUnavailable as exc:+ return jsonify({"ok": False, "code": "internal_unavailable", "detail": str(exc)}), 503+ status = result.get("status_code", 500)+ body = result.get("body") or {}+ body.setdefault("ok", status == 200)+ return jsonify(body), status@app.route("/api/sessions/<session_id>/mark-read", methods=["POST"])def sessions_mark_read(session_id: str):- from storage import messages_service, workbench_sessions_service+ from core.services import sessions as workbench_sessions_service+ from storage import messages_servicefrom vibe.sse_broker import brokerpayload = request.json or {}@@ -2940,7 +3020,8 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):try:if action == "settings_submit":# Merge settings into existing store (not wholesale replace)- from config.v2_settings import SettingsStore, ChannelSettings, normalize_show_message_types+ from config.v2_settings import ChannelSettings, normalize_show_message_types+ from core.services import settings as settings_servicefrom vibe.api import _parse_routingfrom vibe.api import _current_platform@@ -2948,8 +3029,7 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):if not settings_key:return jsonify({"ok": False, "error": "settings_key or channel_id required in modal_values"}), 400- store = SettingsStore.get_instance()- store.maybe_reload()+ store = settings_service.reload_settings_store()platform = _current_platform()ch = store.find_channel(settings_key, platform=platform)if not ch:@@ -2974,8 +3054,9 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):if not channel_id:return jsonify({"ok": False, "error": "channel_id required in modal_values"}), 400- store = SettingsStore.get_instance()- store.maybe_reload()+ from core.services import settings as settings_service++ store = settings_service.reload_settings_store()from vibe.api import _current_platformplatform = _current_platform()@@ -3026,8 +3107,9 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):if not channel_id:return jsonify({"ok": False, "error": "channel_id required in modal_values"}), 400- store = SettingsStore.get_instance()- store.maybe_reload()+ from core.services import settings as settings_service++ store = settings_service.reload_settings_store()from vibe.api import _current_platformplatform = _current_platform()@@ -3275,7 +3357,9 @@ def run_ui_server(host: str, port: int) -> None:paths.ensure_data_dirs()try:- config = V2Config.load()+ from core.services import settings as settings_service++ config = settings_service.load_config()except FileNotFoundError:config = Noneexcept Exception as exc: