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): stream agent replies live instead of closing the stream early

cyh6aad8e68087e
diff --git a/core/controller.py b/core/controller.py
index cd8ffafef..70856f9a3 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -56,6 +56,16 @@ class Controller:
self.session_last_activity: Dict[str, float] = {}
self.claude_active_sessions: set[str] = set()
+ # Streaming turn sinks, keyed by session key. A live SSE caller (the
+ # web Chat surface via core/internal_server.py) registers one before
+ # dispatching a turn so the agent's *background* receiver task — which
+ # emits the reply asynchronously, after handle_user_message has already
+ # returned — can still reach this turn's stream and signal completion.
+ # Keyed by session key (not the per-turn context) so reused agent
+ # sessions, whose long-lived receiver carries a stale context, still
+ # resolve the current turn's sink. Empty for IM/CLI turns.
+ self.active_turn_sinks: Dict[str, Dict[str, Any]] = {}
+
# Initialize core modules
self._init_modules()
@@ -557,6 +567,21 @@ class Controller:
def _get_im_client_for_platform(self, platform: str) -> BaseIMClient:
return self.im_clients.get(platform, self.im_clients[self.primary_platform])
+ # --- Streaming turn sinks -------------------------------------------
+ # A live SSE caller registers a sink before dispatching a turn so the
+ # async agent receiver can forward chunks to the open stream and mark the
+ # 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:
+ self.active_turn_sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event}
+
+ def pop_turn_sink(self, session_key: str) -> None:
+ self.active_turn_sinks.pop(session_key, None)
+
+ def get_turn_sink(self, session_key: str) -> Optional[Dict[str, Any]]:
+ return self.active_turn_sinks.get(session_key)
+
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/message_dispatcher.py b/core/message_dispatcher.py
index d366be057..ac1627761 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -21,26 +21,35 @@ from vibe.i18n import t as i18n_t
logger = 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.
+async def _stream_chunk(controller, context, *, text: str, message_id: Optional[str], kind: str) -> None:
+ """Forward one durable agent message to the live streaming turn sink.
+
+ A web Chat caller registers a per-session sink in
+ ``controller.active_turn_sinks`` (see ``core.services.dispatch.dispatch_turn``)
+ so the SSE response stream sees notify + result emits as they happen —
+ even though the agent's receiver runs on a background task carrying a
+ stale per-turn context. We resolve the sink by *session key* (stable
+ across a session's turns) rather than off the context, so reused agent
+ sessions stream correctly too. A ``result`` emit also marks the turn
+ complete so ``dispatch_turn`` can close the stream right after it. No
+ sink (IM / CLI turns) => no-op, byte-identical to master.
"""
- callback = (context.platform_specific or {}).get("turn_chunk_callback")
- if callback is None:
+ sink = controller.get_turn_sink(controller._get_session_key(context))
+ if sink is None:
return
try:
- await callback({"text": text, "message_id": message_id, "kind": kind})
+ await sink["on_chunk"]({"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)
+ # A misbehaving SSE consumer must not block the underlying agent
+ # reply. Log + swallow, same posture as ``mirror_outbound``.
+ logger.exception("turn on_chunk raised; dropping chunk kind=%s", kind)
+ if kind == "result":
+ # The result is the turn's final answer — release the streaming
+ # dispatch so it can close the SSE stream right after this chunk.
+ done = sink.get("done_event")
+ if done is not None:
+ done.set()
_WECHAT_TEXT_LIMIT = 1900
@@ -380,7 +389,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")
+ await _stream_chunk(self.controller, context, text=text, message_id=message_id, kind="notify")
return message_id
except Exception as err:
logger.error("Failed to send notify message: %s", err)
@@ -539,7 +548,7 @@ class ConsolidatedMessageDispatcher:
kind="result",
)
await _stream_chunk(
- context, text=display_text, message_id=primary_message_id, kind="result"
+ self.controller, context, text=display_text, message_id=primary_message_id, kind="result"
)
return primary_message_id
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index 01c83b009..eac06a9da 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -26,6 +26,8 @@ because no caller passes it yet.
from __future__ import annotations
+import asyncio
+import logging
from typing import Awaitable, Callable, Optional, TYPE_CHECKING
from modules.im import MessageContext
@@ -33,14 +35,21 @@ 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.
+logger = logging.getLogger(__name__)
+
+# Streaming hook for the N3 socket path. Receives one envelope per
+# ``emit_agent_message`` notify/result emit for the turn, on the same loop.
ChunkCallback = Callable[[dict], Awaitable[None]]
SOURCE_HUMAN = "human"
SOURCE_SCHEDULED = "scheduled"
+# Safety cap for how long a streaming dispatch holds the SSE stream open
+# waiting for a turn to emit its result when the agent never produces one
+# (crash, hang, auth failure). Real turns resolve far sooner via the
+# result-emit signal; this only bounds the pathological no-result case.
+TURN_STREAM_TIMEOUT = 600.0
+
async def dispatch_turn(
controller: "Controller",
@@ -54,20 +63,40 @@ async def dispatch_turn(
``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
+ ``on_chunk`` (the N3 socket / web Chat path) receives each notify/result
+ emit for this turn as it happens. Because the agent backends are
+ fire-and-forget — ``handle_user_message`` returns once the message is sent
+ and the reply streams in later on a background receiver task — we register
+ a per-session sink and hold here until the turn emits its result (or the
+ safety timeout fires), so the caller doesn't close the SSE stream before
+ any chunk arrives.
+ """
handler = controller.message_handler
- if source == SOURCE_SCHEDULED:
- return await handler.handle_scheduled_message(context, text)
- return await handler.handle_user_message(context, text)
+
+ async def _run() -> Optional[str]:
+ if source == SOURCE_SCHEDULED:
+ return await handler.handle_scheduled_message(context, text)
+ return await handler.handle_user_message(context, text)
+
+ if on_chunk is None:
+ # IM / CLI: fire-and-forget; no live stream to hold open.
+ return await _run()
+
+ session_key = controller._get_session_key(context)
+ done = asyncio.Event()
+ controller.register_turn_sink(session_key, on_chunk=on_chunk, done_event=done)
+ try:
+ result = await _run()
+ try:
+ await asyncio.wait_for(done.wait(), timeout=TURN_STREAM_TIMEOUT)
+ except asyncio.TimeoutError:
+ logger.warning(
+ "dispatch_turn: streaming turn for %s emitted no result within %.0fs; closing stream",
+ session_key,
+ TURN_STREAM_TIMEOUT,
+ )
+ return result
+ finally:
+ controller.pop_turn_sink(session_key)
diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.py
index 157d8f949..bcffdaadd 100644
--- a/tests/test_core_services_dispatch.py
+++ b/tests/test_core_services_dispatch.py
@@ -5,9 +5,10 @@ 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.
+3. The ``on_chunk`` callback (streaming path) is registered as a
+ per-session turn sink on the controller, and ``dispatch_turn`` holds
+ until the turn emits its result (which sets the sink's done event)
+ before returning — so the SSE caller doesn't close the stream early.
Locking this here means swapping the underlying handler (e.g. when N3
streaming lands) cannot break the public contract silently.
@@ -69,10 +70,12 @@ def test_default_source_is_human():
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.
+def test_streaming_registers_turn_sink_and_waits_for_result():
+ """The streaming path (on_chunk set) registers a per-session turn sink
+ on the controller — keyed by session key, not stashed on the context —
+ and holds until the turn signals completion (a result emit sets the
+ sink's done event), so the SSE caller doesn't close the stream before
+ chunks arrive. The sink is cleaned up after the turn.
"""
controller = _build_controller_double()
ctx = _ctx()
@@ -81,12 +84,31 @@ def test_on_chunk_is_stashed_on_context():
async def _on_chunk(envelope: dict) -> None:
received.append(envelope)
+ captured: dict = {}
+
+ def _register(session_key, *, on_chunk, done_event):
+ captured["session_key"] = session_key
+ captured["on_chunk"] = on_chunk
+ captured["done_event"] = done_event
+ # 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.
+ done_event.set()
+
+ controller._get_session_key = MagicMock(return_value="slack::C")
+ controller.register_turn_sink = MagicMock(side_effect=_register)
+ controller.pop_turn_sink = MagicMock()
+
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 captured["session_key"] == "slack::C"
+ assert captured["on_chunk"] is _on_chunk
+ assert isinstance(captured["done_event"], asyncio.Event)
+ controller.pop_turn_sink.assert_called_once_with("slack::C")
+ # dispatch_turn never invokes on_chunk itself — the emit path does.
assert received == []
+ # No longer stashed on the context.
+ assert "turn_chunk_callback" not in (ctx.platform_specific or {})
def test_on_chunk_absent_keeps_platform_specific_untouched():
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index 16c780cdc..d4daeeffd 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -1,9 +1,13 @@
"""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.
+The hook bridges the in-process dispatcher to the SSE stream exposed by
+``core.internal_server``. It resolves the live turn sink by *session key*
+from ``controller.active_turn_sinks`` — not off the context — so a reused
+agent session, whose long-lived receiver carries a stale per-turn context,
+still streams to the current turn. It forwards the envelope to the
+registered ``on_chunk``, swallows callback errors, and a ``result`` emit
+sets the sink's done event so ``dispatch_turn`` can close the stream. No
+sink (IM bots / CLI) => silent no-op.
"""
from __future__ import annotations
@@ -19,27 +23,75 @@ 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"))
+class _ControllerDouble:
+ """Minimal controller exposing the real turn-sink registry surface."""
+ def __init__(self):
+ self.active_turn_sinks: dict = {}
-def test_invokes_callback_when_present():
- ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")
+ 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 get_turn_sink(self, session_key):
+ return self.active_turn_sinks.get(session_key)
+
+
+def _ctx(platform="avibe", channel="C"):
+ return MessageContext(user_id="U", channel_id=channel, platform=platform)
+
+
+def test_noop_when_no_sink():
+ controller = _ControllerDouble()
+ # No sink registered for this session => silent no-op (IM / CLI turn).
+ asyncio.run(_stream_chunk(controller, _ctx(), text="hi", message_id="m1", kind="notify"))
+
+
+def test_forwards_envelope_to_sink_on_chunk():
+ controller = _ControllerDouble()
cb = AsyncMock()
- ctx.platform_specific = {"turn_chunk_callback": cb}
- asyncio.run(_stream_chunk(ctx, text="agent reply", message_id="m_42", kind="result"))
+ controller.register_turn_sink("avibe::C", on_chunk=cb, done_event=asyncio.Event())
+ asyncio.run(_stream_chunk(controller, _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")
+def test_result_kind_sets_done_event():
+ controller = _ControllerDouble()
+ done = asyncio.Event()
+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done)
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+ assert done.is_set(), "a result emit must release the streaming dispatch"
+
+
+def test_notify_kind_leaves_done_event_unset():
+ controller = _ControllerDouble()
+ done = asyncio.Event()
+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done)
+ asyncio.run(_stream_chunk(controller, _ctx(), text="thinking", message_id="m1", kind="notify"))
+ assert not done.is_set(), "notify is intermediate; the turn isn't done yet"
+
+
+def test_resolves_sink_by_session_key_despite_stale_context():
+ # The agent receiver emits with a context captured at session start; a
+ # later turn registers its sink under the same session key. _stream_chunk
+ # must resolve by session key so the reused-session reply still streams,
+ # even though the emitting context object is a different instance.
+ controller = _ControllerDouble()
+ cb = AsyncMock()
+ controller.register_turn_sink("avibe::sesX", on_chunk=cb, done_event=asyncio.Event())
+ stale_ctx = _ctx(channel="sesX")
+ asyncio.run(_stream_chunk(controller, stale_ctx, text="r", message_id="m", kind="notify"))
+ cb.assert_awaited_once()
+
+
+def test_swallows_sink_on_chunk_exception():
+ controller = _ControllerDouble()
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"))
+ 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"))
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index df436a1bb..09c478073 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -25,6 +25,7 @@ import httpx
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core import internal_server
+from core.message_dispatcher import _stream_chunk
from core.services.dispatch import dispatch_turn
from modules.im import MessageContext
@@ -36,13 +37,28 @@ from modules.im import MessageContext
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``.
+ can be patched to emit chunks via the real ``_stream_chunk`` hook.
+
+ It carries a *real* turn-sink registry (not MagicMock auto-attrs) so
+ ``dispatch_turn`` and ``_stream_chunk`` interoperate exactly as in
+ production: dispatch_turn registers the sink, the handler's emits
+ resolve it by session key, and a result emit releases the dispatch.
"""
controller = MagicMock()
controller.message_handler = MagicMock()
controller.message_handler.handle_user_message = AsyncMock(side_effect=handler or (lambda ctx, text: None))
+
+ sinks: dict = {}
+ 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}
+
+ controller.register_turn_sink = _register
+ controller.pop_turn_sink = lambda session_key: sinks.pop(session_key, None)
+ controller.get_turn_sink = lambda session_key: sinks.get(session_key)
return controller
@@ -120,10 +136,14 @@ def test_dispatch_streams_chunks_emitted_by_handler():
]
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"
+ # Simulate the agent's background receiver emitting via the real
+ # dispatcher hook: it resolves the sink dispatch_turn registered
+ # (by session key) and forwards each envelope to the SSE stream.
+ # The trailing result emit also releases dispatch_turn.
for c in chunks:
- await callback(c)
+ await _stream_chunk(
+ controller, ctx, text=c["text"], message_id=c["message_id"], kind=c["kind"]
+ )
return chunks[-1]["message_id"]
controller = _build_controller_double(handler=fake_handle_user_message)
@@ -154,6 +174,54 @@ def test_dispatch_streams_chunks_emitted_by_handler():
assert chunk_events == chunks, "chunks must be forwarded in order without rewriting"
+def test_dispatch_waits_for_async_result_after_handler_returns():
+ """The crux of the streaming lifecycle fix: the agent backends are
+ fire-and-forget — ``handle_user_message`` returns after *sending*, and
+ the reply is emitted later by a background receiver task. ``dispatch_turn``
+ must hold the SSE stream open until that async result emit (done), not
+ close it the instant the handler returns. (Pre-fix, ``turn.end`` fired
+ immediately and the late result missed the closed stream.)
+ """
+
+ emitted = asyncio.Event()
+
+ async def fire_and_forget(ctx, text):
+ # Schedule the result emit to happen *after* this returns, then
+ # return immediately (the message has been "sent").
+ async def _late_emit():
+ await asyncio.sleep(0.05)
+ await _stream_chunk(controller, ctx, text="late answer", message_id="m_late", kind="result")
+ emitted.set()
+
+ asyncio.create_task(_late_emit())
+ return None
+
+ controller = _build_controller_double(handler=fire_and_forget)
+ 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_async", "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
+
+ events = asyncio.run(_go())
+ kinds = [name for name, _ in events]
+ chunk_texts = [data.get("text") for name, data in events if name == "turn.chunk"]
+ assert "late answer" in chunk_texts, "a result emitted after the handler returned must still stream"
+ assert kinds[-1] == "turn.end"
+ assert emitted.is_set()
+
+
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
@@ -192,6 +260,11 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, t
async def capture(ctx, text):
captured["platform_specific"] = dict(ctx.platform_specific or {})
+ # Release the streaming dispatch (simulate the turn completing) so it
+ # doesn't wait out the safety timeout.
+ sink = controller.get_turn_sink(controller._get_session_key(ctx))
+ if sink:
+ sink["done_event"].set()
controller = _build_controller_double(handler=capture)
app = internal_server.create_app(controller)
@@ -242,8 +315,7 @@ def test_cancel_marks_in_flight_session_as_requested():
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"})
+ await _stream_chunk(controller, ctx, text="starting", message_id=None, kind="notify")
started.set()
try:
# Sleep long enough that the test's cancel arrives mid-flight.
@@ -316,22 +388,27 @@ def test_dispatch_emits_error_chunk_on_handler_exception():
# ---------------------------------------------------------------------
-def test_dispatch_turn_stashes_on_chunk_for_dispatcher_hook():
+def test_dispatch_turn_registers_sink_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.
+ ``_stream_chunk`` helper: the streaming ``on_chunk`` is registered as a
+ per-session turn sink (resolvable by session key while the turn runs)
+ and cleaned up afterward — not stashed on the per-turn context.
"""
async def on_chunk(envelope):
pass
- seen_callbacks: list = []
+ seen: dict = {}
- async def capture_callback(ctx, text):
- seen_callbacks.append((ctx.platform_specific or {}).get("turn_chunk_callback"))
+ async def capture(ctx, text):
+ sink = controller.get_turn_sink(controller._get_session_key(ctx))
+ seen["on_chunk"] = sink["on_chunk"] if sink else None
+ # Release the dispatch the way a real result emit would.
+ if sink:
+ sink["done_event"].set()
- controller = _build_controller_double(handler=capture_callback)
+ controller = _build_controller_double(handler=capture)
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]
+ assert seen["on_chunk"] is on_chunk
+ assert controller.get_turn_sink("avibe::C") is None, "sink cleaned up after the turn"