Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): route per-session model/effort + harden stop concurrency
cyhc6d79f52c87a
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex d51e12982..9321c877a 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -210,6 +210,21 @@ class MessageHandler(BaseHandler):scope_model_override = routing_model_for_backend(routing, agent_name)scope_reasoning_override = routing_reasoning_effort_for_backend(routing, agent_name)+ # A workbench Chat session carries the user's explicit per-session+ # agent / model / effort picks in ``agent_session_target`` (the Chat+ # header cascade writes them onto the session row, and the dispatch+ # layer copies the row here). Those are the highest-precedence+ # override for this turn — above channel-routing scope overrides and+ # the VibeAgent's own defaults — otherwise the header's model /+ # effort picker would be cosmetic: persisted and displayed but never+ # actually routed to the backend.+ session_target_model = (+ session_target.get("model") if isinstance(session_target, dict) else None+ )+ session_target_reasoning = (+ session_target.get("reasoning_effort") if isinstance(session_target, dict) else None+ )+matched_prefix = Nonesubagent_message = Nonesubagent_name = None@@ -336,8 +351,11 @@ class MessageHandler(BaseHandler):vibe_agent_id=vibe_agent.id if vibe_agent else None,vibe_agent_name=vibe_agent.name if vibe_agent else None,vibe_agent_backend=vibe_agent.backend if vibe_agent else None,- vibe_agent_model=scope_model_override or (vibe_agent.model if vibe_agent else None),- vibe_agent_reasoning_effort=scope_reasoning_override+ vibe_agent_model=session_target_model+ or scope_model_override+ or (vibe_agent.model if vibe_agent else None),+ vibe_agent_reasoning_effort=session_target_reasoning+ or scope_reasoning_overrideor (vibe_agent.reasoning_effort if vibe_agent else None),vibe_agent_system_prompt=vibe_agent.system_prompt if vibe_agent else None,processing_indicator=processing_indicator,diff --git a/core/internal_server.py b/core/internal_server.pyindex c8d507563..000e9e4dd 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -72,12 +72,15 @@ def create_app(controller: "Controller") -> FastAPI: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+ # In-flight ``dispatch_turn`` tasks per session, each stored together with+ # the routing ``MessageContext`` the turn STARTED under. The cancel+ # endpoint looks the task up here so the UI can stop a runaway turn without+ # waiting for the agent to settle, and reuses the stored context so it+ # interrupts the backend the turn actually started on — even if the Chat+ # header changed the session's agent / model while the reply was streaming.+ # 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] = {}+ in_flight: dict[str, tuple[asyncio.Task, MessageContext]] = {}app.state.in_flight_dispatches = in_flight@app.get("/internal/health")@@ -94,6 +97,34 @@ def create_app(controller: "Controller") -> FastAPI:session_id = payload.get("session_id")+ # One streaming turn per session. If a turn is already in flight for+ # this session (a second browser tab, or a resend before the first+ # finishes), refuse the new one HERE — before creating a task or+ # touching ``in_flight`` — so we never overwrite the real turn's task+ # handle. Overwriting it would orphan the running turn: its sink keeps+ # streaming but ``/internal/cancel`` could no longer find the task to+ # interrupt, so the Stop button would silently no-op.+ if isinstance(session_id, str) and session_id:+ existing = in_flight.get(session_id)+ if existing is not None and not existing[0].done():+ async def _busy_stream():+ yield _sse_event("turn.start", {"session_id": session_id})+ yield _sse_event(+ "turn.chunk",+ {+ "kind": "error",+ "text": controller._t("error.streamTurnInProgress"),+ "message_id": None,+ },+ )+ yield _sse_event("turn.end", {"session_id": session_id})++ return StreamingResponse(+ _busy_stream(),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},+ )+# SSE chunked stream — the response body is fed by ``on_chunk``# callbacks that the dispatcher fires for every successful# ``emit_agent_message`` notify / result during the turn. The@@ -121,7 +152,7 @@ def create_app(controller: "Controller") -> FastAPI:task = asyncio.create_task(_runner(), name="internal-dispatch")if isinstance(session_id, str) and session_id:- in_flight[session_id] = task+ in_flight[session_id] = (task, context)async def _stream():try:@@ -154,23 +185,25 @@ def create_app(controller: "Controller") -> FastAPI:# (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:+ entry = in_flight.get(session_id)+ if entry is None:return JSONResponse(status_code=404,content={"ok": False, "code": "not_in_flight", "session_id": session_id},)+ task, turn_context = entryif task.done():return {"ok": True, "session_id": session_id, "status": "already_finished"}# Interrupt the agent's backend turn through the SAME path the IM# ``/stop`` command uses, so the underlying agent run is actually# stopped (Claude interrupt / Codex turn-interrupt / OpenCode abort) —# not just this SSE proxy task. Without it the agent keeps running and- # its late reply leaks into the next turn's stream. Reuses- # ``command_handler.handle_stop`` verbatim with the session's own- # routing context, so stop is one mechanism across IM, CLI, and web.+ # its late reply leaks into the next turn's stream. We pass the context+ # the turn STARTED under (captured at dispatch time), not one rebuilt+ # from the current session row, so the right backend is interrupted+ # even if the Chat header swapped the session's agent / model mid-turn.try:- await controller.command_handler.handle_stop(_build_session_context(session_id))+ await controller.command_handler.handle_stop(turn_context)except Exception:logger.exception("internal cancel: backend stop failed for session=%s", session_id)task.cancel()diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex a61e8f4c9..d3bfeb56f 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -79,6 +79,10 @@ def _build_controller_double(handler=None):# Cancel reuses the IM /stop path to interrupt the backend turn.controller.command_handler = MagicMock()controller.command_handler.handle_stop = AsyncMock(return_value=True)++ # ``_t`` returns the key verbatim so refusal chunks stay JSON-serializable+ # (a bare MagicMock would blow up ``json.dumps`` in ``_sse_event``).+ controller._t = lambda key, **kwargs: keyreturn controller@@ -482,6 +486,71 @@ def test_cancel_marks_in_flight_session_as_requested(monkeypatch, tmp_path):# The SSE consumer sees the cancelled chunk before turn.end.chunk_kinds = [data.get("kind") for name, data in events if name == "turn.chunk"]assert "cancelled" in chunk_kinds+++def test_concurrent_dispatch_refused_preserves_cancellable_slot(monkeypatch, tmp_path):+ """A second dispatch for a session that already has a turn in flight is+ refused with a terminal error chunk WITHOUT evicting the first turn's task+ handle — so ``/internal/cancel`` can still interrupt the original+ long-running turn (regression: the refusal task used to overwrite the slot+ and orphan the real turn, leaving the Stop button a silent no-op).+ """++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ from storage.importer import ensure_sqlite_state++ ensure_sqlite_state()++ started = asyncio.Event()+ cancelled = asyncio.Event()++ async def long_handle(ctx, text):+ await _stream_chunk(controller, ctx, text="starting", message_id=None, kind="notify")+ started.set()+ try:+ await asyncio.sleep(5)+ except asyncio.CancelledError:+ cancelled.set()+ raise+ return None++ controller = _build_controller_double(handler=long_handle)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ async def _drain(client, body):+ async with client.stream("POST", "/internal/dispatch", json=body) as resp:+ assert resp.status_code == 200+ collected: list[tuple[str, dict]] = []+ current = None+ async for line in resp.aiter_lines():+ if line.startswith("event:"):+ current = line.split(":", 1)[1].strip()+ elif line.startswith("data:") and current is not None:+ collected.append((current, json.loads(line[5:].strip())))+ return collected++ async def _go():+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ first = asyncio.create_task(_drain(client, {"session_id": "ses_x", "text": "one"}))+ await asyncio.wait_for(started.wait(), timeout=3)+ # Second concurrent send for the SAME session: refused immediately.+ second = await asyncio.wait_for(_drain(client, {"session_id": "ses_x", "text": "two"}), timeout=3)+ # The original turn must still be cancellable.+ cancel_resp = await client.post("/internal/cancel/ses_x")+ first_events = await asyncio.wait_for(first, timeout=3)+ return second, cancel_resp, first_events++ second_events, cancel_resp, _first_events = asyncio.run(_go())+ # The refused second dispatch got a terminal error chunk, not a real turn.+ second_kinds = [data.get("kind") for name, data in second_events if name == "turn.chunk"]+ assert "error" in second_kinds+ # The first turn's slot survived the refusal: cancel finds it, interrupts+ # the backend via the shared /stop path, and the handler is cancelled.+ assert cancel_resp.status_code == 200+ assert cancel_resp.json()["status"] == "cancel_requested"+ assert cancelled.is_set(), "the original turn must still be cancellable"+ controller.command_handler.handle_stop.assert_awaited()# Cancel also interrupted the backend turn via the shared /stop path.controller.command_handler.handle_stop.assert_awaited()