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): close streaming turns that finish without a result + guard concurrent same-session turns
cyh4da3368ffc99
diff --git a/core/controller.py b/core/controller.pyindex 70856f9a3..49aec376a 100644--- a/core/controller.py+++ b/core/controller.py@@ -574,6 +574,17 @@ class Controller:# ``ConsolidatedMessageDispatcher._stream_chunk`` consumer.def register_turn_sink(self, session_key: str, *, on_chunk, done_event) -> None:+ existing = self.active_turn_sinks.get(session_key)+ if existing is not None:+ # A concurrent / retried streaming turn for the same session is+ # starting (e.g. two browser tabs, or a resend before the first+ # finishes). Release the previous waiter so its SSE stream closes+ # cleanly instead of hanging until the safety timeout, and so the+ # session keeps exactly one live sink.+ prev_done = existing.get("done_event")+ if prev_done is not None:+ prev_done.set()+ logger.warning("Replacing active turn sink for %s (concurrent streaming turn)", session_key)self.active_turn_sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event}def pop_turn_sink(self, session_key: str) -> None:@@ -582,6 +593,20 @@ class Controller:def get_turn_sink(self, session_key: str) -> Optional[Dict[str, Any]]:return self.active_turn_sinks.get(session_key)+ def mark_turn_complete(self, context: Optional[MessageContext] = None) -> None:+ """Release a streaming turn sink whose turn finished WITHOUT emitting a+ result (missing/disabled backend, dedup, inline-stop, error, or any+ synchronous no-agent path) so the SSE dispatch closes promptly instead+ of waiting out the safety timeout. No-op for non-streaming turns or+ when an agent turn is genuinely in flight (the result emit releases it)."""+ if context is None:+ return+ sink = self.get_turn_sink(self._get_session_key(context))+ if sink is not None:+ done = sink.get("done_event")+ if done is not None:+ done.set()+def get_settings_manager_for_context(self, context: Optional[MessageContext] = None) -> SettingsManager:if context is None:return self.platform_settings_managers[self.primary_platform]diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 561029892..d51e12982 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -65,6 +65,12 @@ class MessageHandler(BaseHandler):async def _handle_turn(self, context: MessageContext, message: str, *, source: str) -> Optional[str]:"""Shared turn-processing pipeline used by both human and scheduled turns."""processing_indicator = None+ # Tracks whether we actually dispatched an agent turn (whose reply+ # streams in asynchronously). If we leave this method WITHOUT having+ # dispatched — early returns, missing/disabled backend, errors — no+ # async result is coming, so the ``finally`` releases any streaming SSE+ # waiter for this turn instead of leaving it open until the timeout.+ agent_dispatched = Falsetry:is_human = source == self.TURN_SOURCE_HUMANcontrol_message = self._get_control_message(context, message) if is_human else message@@ -341,6 +347,7 @@ class MessageHandler(BaseHandler):self.controller.processing_indicator.apply_to_request(request, processing_indicator)try:await self.controller.agent_service.handle_message(agent_name, request)+ agent_dispatched = Trueexcept KeyError:await self._handle_missing_agent(context, agent_name)# Clean up reaction on error@@ -369,6 +376,15 @@ class MessageHandler(BaseHandler):self.formatter.format_error(self._t("error.processMessageFailed", error=str(e))),)return str(e)+ finally:+ if not agent_dispatched:+ # Synchronous completion — no async agent reply is coming, so+ # release any live streaming SSE waiter for this turn now+ # instead of holding it open until the dispatch safety+ # timeout. No-op for non-streaming (IM/CLI) turns.+ mark_complete = getattr(self.controller, "mark_turn_complete", None)+ if callable(mark_complete):+ mark_complete(context)@staticmethoddef _build_agent_request(**kwargs: Any) -> AgentRequest:diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 09c478073..be60f113b 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -59,6 +59,13 @@ def _build_controller_double(handler=None):controller.register_turn_sink = _registercontroller.pop_turn_sink = lambda session_key: sinks.pop(session_key, None)controller.get_turn_sink = lambda session_key: sinks.get(session_key)++ def _mark_turn_complete(ctx):+ sink = sinks.get(controller._get_session_key(ctx))+ if sink and sink.get("done_event") is not None:+ sink["done_event"].set()++ controller.mark_turn_complete = _mark_turn_completereturn controller@@ -222,6 +229,64 @@ def test_dispatch_waits_for_async_result_after_handler_returns():assert emitted.is_set()+def test_dispatch_closes_when_turn_completes_without_result():+ """P1: a turn that finishes WITHOUT emitting a result (missing/disabled+ backend, dedup, error, ...) must close the stream promptly via+ ``mark_turn_complete`` rather than hang until the 600s safety timeout.+ ``MessageHandler._handle_turn`` signals this on every no-dispatch exit;+ here we drive it directly.+ """++ async def no_result_handler(ctx, text):+ await _stream_chunk(controller, ctx, text="working", message_id=None, kind="notify")+ # Turn finished without a result emit — release the SSE waiter.+ controller.mark_turn_complete(ctx)+ return None++ controller = _build_controller_double(handler=no_result_handler)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ async def _go():+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ async with client.stream(+ "POST", "/internal/dispatch", json={"session_id": "ses_nr", "text": "hi"}+ ) as resp:+ events: list[tuple[str, dict]] = []+ current = None+ async for line in resp.aiter_lines():+ if line.startswith("event:"):+ current = line.split(":", 1)[1].strip()+ elif line.startswith("data:") and current is not None:+ events.append((current, json.loads(line[5:].strip())))+ return events++ # Bounded so a regression (no-result hang) fails fast instead of 600s.+ events = asyncio.run(asyncio.wait_for(_go(), timeout=10))+ kinds = [name for name, _ in events]+ assert kinds[-1] == "turn.end"+ assert any(d.get("text") == "working" for n, d in events if n == "turn.chunk")+++def test_register_turn_sink_releases_previous_for_same_session():+ """P2: a concurrent / retried streaming turn for the same session must+ release the previous turn's waiter when it registers, so the earlier SSE+ stream closes instead of hanging — and the session keeps one live sink."""+ import types++ from core.controller import Controller++ fake = types.SimpleNamespace(active_turn_sinks={})+ first = asyncio.Event()+ Controller.register_turn_sink(fake, "avibe::s", on_chunk=AsyncMock(), done_event=first)+ second = asyncio.Event()+ Controller.register_turn_sink(fake, "avibe::s", on_chunk=AsyncMock(), done_event=second)++ assert first.is_set(), "the previous turn's waiter must be released on re-register"+ assert not second.is_set()+ assert fake.active_turn_sinks["avibe::s"]["done_event"] is second++def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, tmp_path):"""Regression for the Codex P1: ``/internal/dispatch`` must hand theworkbench session's agent / model / effort to ``MessageHandler`` via