Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(workbench): scope streaming emits to a per-turn token (#1, no cross-feed)

cyh9d96511f2f57
diff --git a/core/controller.py b/core/controller.py
index 8e065785a..e7bbcd3f0 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -573,7 +573,7 @@ class Controller:
# turn complete. See ``core/services/dispatch.py`` and the
# ``ConsolidatedMessageDispatcher._stream_chunk`` consumer.
- def register_turn_sink(self, session_key: str, *, on_chunk, done_event) -> None:
+ def register_turn_sink(self, session_key: str, *, on_chunk, done_event, turn_token=None) -> None:
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
@@ -581,7 +581,13 @@ class Controller:
# result satisfy a replacement sink (cross-feeding the wrong turn).
logger.warning("Ignoring duplicate turn sink registration for %s", session_key)
return
- self.active_turn_sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event}
+ # ``turn_token`` correlates emits to this exact turn so a late straggler
+ # from a superseded turn (same session key) is dropped in _stream_chunk.
+ self.active_turn_sinks[session_key] = {
+ "on_chunk": on_chunk,
+ "done_event": done_event,
+ "turn_token": turn_token,
+ }
def pop_turn_sink(self, session_key: str, done_event=None) -> None:
# Identity-guarded: only remove the sink this turn registered. A
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 938e79248..d40f66de8 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -44,6 +44,17 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[
sink = get_sink(get_key(context))
if sink is None:
return
+ # Turn-token guard: only forward emits that belong to the turn this sink
+ # was registered for. A late straggler from a superseded turn (same session
+ # key, after the user stopped it or it timed out and a NEW turn registered)
+ # carries the OLD turn's token and is dropped here — so it neither
+ # cross-feeds the new turn's stream nor (for ``result``) prematurely
+ # completes it. Fail-open: if either token is absent we forward as before.
+ sink_token = sink.get("turn_token")
+ emit_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
+ if sink_token is not None and emit_token is not None and sink_token != emit_token:
+ logger.debug("dropping stale stream chunk kind=%s (turn token mismatch)", kind)
+ return
try:
await sink["on_chunk"]({"text": text, "message_id": message_id, "kind": kind})
except Exception:
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index 0a2b63237..46d99f731 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -28,6 +28,7 @@ from __future__ import annotations
import asyncio
import logging
+import uuid
from typing import Awaitable, Callable, Optional, TYPE_CHECKING
from modules.im import MessageContext
@@ -95,8 +96,18 @@ async def dispatch_turn(
# streaming undisturbed.
await on_chunk({"kind": "error", "text": controller._t("error.streamTurnInProgress"), "message_id": None})
return None
+ # Tag this turn with a unique token, stamped into the context the agent
+ # receiver will carry. ``_stream_chunk`` only forwards an emit to the sink
+ # when the emit's context token matches the registered sink's token, so a
+ # late straggler emit from a PREVIOUS (stopped / timed-out) turn can't
+ # cross-feed into this turn's live stream or prematurely complete it.
+ # Fail-open: emits without a token still flow (byte-identical to before).
+ turn_token = uuid.uuid4().hex
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific["turn_token"] = turn_token
done = asyncio.Event()
- controller.register_turn_sink(session_key, on_chunk=on_chunk, done_event=done)
+ controller.register_turn_sink(session_key, on_chunk=on_chunk, done_event=done, turn_token=turn_token)
try:
result = await _run()
try:
diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.py
index bee29580a..f981e61fb 100644
--- a/tests/test_core_services_dispatch.py
+++ b/tests/test_core_services_dispatch.py
@@ -86,10 +86,11 @@ def test_streaming_registers_turn_sink_and_waits_for_result():
captured: dict = {}
- def _register(session_key, *, on_chunk, done_event):
+ def _register(session_key, *, on_chunk, done_event, turn_token=None):
captured["session_key"] = session_key
captured["on_chunk"] = on_chunk
captured["done_event"] = done_event
+ captured["turn_token"] = turn_token
# Simulate the agent's background receiver emitting the result,
# which sets the done event so dispatch_turn returns promptly
# instead of waiting out the safety timeout.
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index d4daeeffd..c649a2209 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -32,8 +32,12 @@ class _ControllerDouble:
def _get_session_key(self, ctx):
return f"{ctx.platform}::{ctx.channel_id}"
- def register_turn_sink(self, session_key, *, on_chunk, done_event):
- self.active_turn_sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event}
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None):
+ self.active_turn_sinks[session_key] = {
+ "on_chunk": on_chunk,
+ "done_event": done_event,
+ "turn_token": turn_token,
+ }
def get_turn_sink(self, session_key):
return self.active_turn_sinks.get(session_key)
@@ -95,3 +99,43 @@ def test_swallows_sink_on_chunk_exception():
controller.register_turn_sink("avibe::C", on_chunk=_raises, done_event=asyncio.Event())
# Must not propagate — a misbehaving UI consumer cannot kill the agent reply.
asyncio.run(_stream_chunk(controller, _ctx(), text="x", message_id=None, kind="notify"))
+
+
+def test_drops_stale_chunk_on_turn_token_mismatch():
+ # A late straggler from a SUPERSEDED turn (same session key, but the user
+ # stopped it / it timed out and a NEW turn registered) carries the old
+ # turn's token. It must NOT be forwarded to the new turn's sink, and a
+ # stale ``result`` must NOT complete the new turn.
+ controller = _ControllerDouble()
+ cb = AsyncMock()
+ done = asyncio.Event()
+ controller.register_turn_sink("avibe::C", on_chunk=cb, done_event=done, turn_token="turn-new")
+ stale_ctx = MessageContext(
+ user_id="U", channel_id="C", platform="avibe", platform_specific={"turn_token": "turn-old"}
+ )
+ asyncio.run(_stream_chunk(controller, stale_ctx, text="stale", message_id="m", kind="result"))
+ cb.assert_not_awaited()
+ assert not done.is_set(), "a stale-turn result must not complete the newer turn"
+
+
+def test_forwards_chunk_on_turn_token_match():
+ controller = _ControllerDouble()
+ cb = AsyncMock()
+ done = asyncio.Event()
+ controller.register_turn_sink("avibe::C", on_chunk=cb, done_event=done, turn_token="turn-1")
+ ctx = MessageContext(
+ user_id="U", channel_id="C", platform="avibe", platform_specific={"turn_token": "turn-1"}
+ )
+ asyncio.run(_stream_chunk(controller, ctx, text="ok", message_id="m", kind="result"))
+ cb.assert_awaited_once()
+ assert done.is_set()
+
+
+def test_fails_open_when_no_token_present():
+ # Sink without a token (older/legacy registration) still forwards every
+ # emit — the guard must never drop legitimate messages.
+ controller = _ControllerDouble()
+ cb = AsyncMock()
+ controller.register_turn_sink("avibe::C", on_chunk=cb, done_event=asyncio.Event())
+ asyncio.run(_stream_chunk(controller, _ctx(), text="hi", message_id="m", kind="notify"))
+ cb.assert_awaited_once()
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index d3bfeb56f..af41101a2 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -53,8 +53,8 @@ def _build_controller_double(handler=None):
controller.active_turn_sinks = sinks
controller._get_session_key = lambda ctx: f"{getattr(ctx, 'platform', None)}::{getattr(ctx, 'channel_id', None)}"
- def _register(session_key, *, on_chunk, done_event):
- sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event}
+ def _register(session_key, *, on_chunk, done_event, turn_token=None):
+ sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event, "turn_token": turn_token}
controller.register_turn_sink = _register