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): serialize streaming turns per session instead of replacing sinks
cyh64f9aaa887a2
diff --git a/core/controller.py b/core/controller.pyindex 5e86319c2..8e065785a 100644--- a/core/controller.py+++ b/core/controller.py@@ -574,17 +574,13 @@ 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)+ if session_key in self.active_turn_sinks:+ # ``dispatch_turn`` serializes streaming turns per session, so this+ # should not happen. If it ever does, keep the in-flight turn's+ # sink rather than clobbering it — replacing it is what let a stale+ # result satisfy a replacement sink (cross-feeding the wrong turn).+ logger.warning("Ignoring duplicate turn sink registration for %s", session_key)+ returnself.active_turn_sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event}def pop_turn_sink(self, session_key: str, done_event=None) -> None:diff --git a/core/services/dispatch.py b/core/services/dispatch.pyindex 637c7c060..0a2b63237 100644--- a/core/services/dispatch.py+++ b/core/services/dispatch.py@@ -85,6 +85,16 @@ async def dispatch_turn(return await _run()session_key = controller._get_session_key(context)+ if controller.get_turn_sink(session_key) is not None:+ # Serialize per session. A streaming turn is already in flight for+ # this session (a second browser tab, or a resend before the first+ # finishes). The session's single agent client can't run two turns at+ # once, and two live sinks under one session key would cross-feed+ # chunks and complete each other early. Refuse the concurrent turn+ # with a terminal chunk instead of racing — the in-flight turn keeps+ # streaming undisturbed.+ await on_chunk({"kind": "error", "text": controller._t("error.streamTurnInProgress"), "message_id": None})+ return Nonedone = asyncio.Event()controller.register_turn_sink(session_key, on_chunk=on_chunk, done_event=done)try:diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.pyindex 7a8652bdc..bee29580a 100644--- a/tests/test_core_services_dispatch.py+++ b/tests/test_core_services_dispatch.py@@ -96,6 +96,7 @@ def test_streaming_registers_turn_sink_and_waits_for_result():done_event.set()controller._get_session_key = MagicMock(return_value="slack::C")+ controller.get_turn_sink = MagicMock(return_value=None) # no turn in flight => not rejectedcontroller.register_turn_sink = MagicMock(side_effect=_register)controller.pop_turn_sink = MagicMock()diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 3002517eb..b2c07cc62 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -277,10 +277,12 @@ def test_dispatch_closes_when_turn_completes_without_result():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."""+def test_register_turn_sink_ignores_duplicate_and_pop_is_identity_guarded():+ """Streaming turns are serialized per session (dispatch_turn rejects a+ concurrent one). As defense in depth, register_turn_sink must NOT clobber+ an in-flight sink, and pop_turn_sink must only remove the sink whose+ done_event matches the caller's — so no stale turn can satisfy or evict+ another turn's sink."""import typesfrom core.controller import Controller@@ -291,34 +293,44 @@ def test_register_turn_sink_releases_previous_for_same_session():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+ # The in-flight sink is kept; the duplicate is dropped and NOT released.+ assert fake.active_turn_sinks["avibe::s"]["done_event"] is first+ assert not first.is_set()+ # pop is identity-guarded: a non-matching done_event is a no-op.+ Controller.pop_turn_sink(fake, "avibe::s", second)+ assert "avibe::s" in fake.active_turn_sinks+ Controller.pop_turn_sink(fake, "avibe::s", first)+ assert "avibe::s" not in fake.active_turn_sinks-def test_pop_turn_sink_does_not_evict_a_newer_turns_sink():- """A superseded turn's cleanup must remove only the sink IT registered,- not whatever sink is currently stored — otherwise the older turn's- ``finally`` would evict the newer concurrent turn's sink and stall it."""- import types- from core.controller import Controller+def test_dispatch_rejects_concurrent_same_session_turn():+ """dispatch_turn serializes per session: when a streaming turn is already+ in flight (a sink is registered), a second streaming dispatch is refused+ with a terminal error chunk and never starts a competing agent turn —+ so two streams can't race over one session and cross-feed."""+ chunks: list[dict] = []- fake = types.SimpleNamespace(active_turn_sinks={})- old = asyncio.Event()- Controller.register_turn_sink(fake, "avibe::s", on_chunk=AsyncMock(), done_event=old)- new = asyncio.Event()- Controller.register_turn_sink(fake, "avibe::s", on_chunk=AsyncMock(), done_event=new)-- # Older turn resumes (its waiter was released) and cleans up — must NOT- # remove the newer sink.- Controller.pop_turn_sink(fake, "avibe::s", old)- assert fake.active_turn_sinks.get("avibe::s") is not None- assert fake.active_turn_sinks["avibe::s"]["done_event"] is new-- # The newer turn's own cleanup removes it.- Controller.pop_turn_sink(fake, "avibe::s", new)- assert "avibe::s" not in fake.active_turn_sinks+ async def on_chunk(env):+ chunks.append(env)++ handler_calls: list = []++ async def handler(ctx, text):+ handler_calls.append(text)++ controller = _build_controller_double(handler=handler)+ controller._t = lambda key, **kw: f"i18n:{key}"+ ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")+ # Simulate a streaming turn already in flight for this session.+ controller.register_turn_sink(+ controller._get_session_key(ctx), on_chunk=AsyncMock(), done_event=asyncio.Event()+ )++ asyncio.run(dispatch_turn(controller, ctx, "second", on_chunk=on_chunk))++ assert handler_calls == [], "a concurrent turn must not start the agent"+ assert any(c.get("kind") == "error" for c in chunks), "a terminal error chunk must be emitted"def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, tmp_path):diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex dffde69cc..84c30bbb4 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -42,6 +42,7 @@"processActionFailed": "Error processing action: {error}","agentNotConfigured": "Agent `{agent}` is not configured. Make sure the Codex CLI is installed and environment variables are set if this channel is routed to Codex.","processMessageFailed": "Error: {error}",+ "streamTurnInProgress": "⚠️ A reply is already streaming for this session — wait for it to finish, then try again.","sessionReset": "Session error detected. Session has been reset. Please try your message again.","sessionConnectionLost": "Connection to Claude was lost. Please try your message again.","claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 6b8ce673c..354dac699 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -42,6 +42,7 @@"processActionFailed": "处理操作时出错:{error}","agentNotConfigured": "Agent `{agent}` 未配置。若此频道路由到 Codex,请确保已安装 Codex CLI 并设置环境变量。","processMessageFailed": "出错:{error}",+ "streamTurnInProgress": "⚠️ 这个会话已经有一条回复在生成中,请等它完成后再试。","sessionReset": "检测到会话错误。会话已重置,请重试。","sessionConnectionLost": "与 Claude 的连接已断开,请重试。","claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。",