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): drop _stream_chunk turn-token gate (P1) + opencode/claude turn-end hooks

cyh8a5f6f63b28e
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index d40f66de8..403f2979e 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -44,17 +44,13 @@ 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
+ # NB: we deliberately do NOT gate forwarding on a per-turn token here.
+ # Claude reuses ONE long-lived receiver across a session's turns, and it
+ # emits the CURRENT turn's output carrying an EARLIER turn's context
+ # (the documented "stale per-turn context"); a token gate would drop those
+ # legitimate current-turn chunks. Resolution stays by session key. (The
+ # cross-feed of a stopped turn's late straggler is handled at the
+ # turn-completion layer / left as a known edge — see docs/plans.)
try:
await sink["on_chunk"]({"text": text, "message_id": message_id, "kind": kind})
except Exception:
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 9c340995d..6eb4ef7b1 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -122,6 +122,14 @@ class ClaudeAgent(BaseAgent):
)
if not handled:
await self.session_handler.handle_session_error(runtime_session_key, context, e)
+ # Synchronous failure (query/setup raised) — no async receiver
+ # result is coming for this turn, so release the web-Chat stream
+ # waiter now (token-guarded, no-op for IM/CLI) instead of waiting
+ # out the safety timeout. Defensive: tolerate controllers without
+ # streaming completion support.
+ _mark = getattr(self.controller, "mark_turn_complete", None)
+ if callable(_mark):
+ _mark(context)
finally:
await self._delete_ack(context, request)
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index e2925c8b5..b30b256b4 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -78,6 +78,15 @@ class CodexEventHandler:
else:
logger.debug("Unhandled Codex notification: %s", method)
+ def _release_stream_turn(self, context) -> None:
+ """Release any web-Chat SSE stream waiting on this turn so it closes
+ promptly. Token-guarded in the controller (a superseded turn won't
+ close a newer turn's stream); no-op for IM/CLI turns and for
+ controllers that don't expose streaming completion."""
+ mark = getattr(self._agent.controller, "mark_turn_complete", None)
+ if callable(mark):
+ mark(context)
+
# ------------------------------------------------------------------
# Notification handlers
# ------------------------------------------------------------------
@@ -129,7 +138,7 @@ class CodexEventHandler:
await self._agent._remove_ack_reaction(tracked_request)
# Turn ended without a result — release any web-Chat stream waiter
# (token-guarded, so a superseded turn won't close a newer stream).
- self._agent.controller.mark_turn_complete(tracked_request.context)
+ self._release_stream_turn(tracked_request.context)
return
if status == "failed":
@@ -166,7 +175,7 @@ class CodexEventHandler:
await self._agent._remove_ack_reaction(tracked_request)
# Failed turn surfaced an error notify but no result — close the
# web-Chat stream now instead of waiting out the safety timeout.
- self._agent.controller.mark_turn_complete(tracked_request.context)
+ self._release_stream_turn(tracked_request.context)
return
if not should_emit_result:
@@ -176,7 +185,7 @@ class CodexEventHandler:
self._clear_generated_image_snapshot(params)
self._agent._turn_registry.pop_turn(turn_id)
logger.debug("Ignoring inactive turn/completed for turn %s", turn_id)
- self._agent.controller.mark_turn_complete(tracked_request.context)
+ self._release_stream_turn(tracked_request.context)
return
pending = turn_state.pending_assistant if turn_state else None
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index ea75db73b..cfcf6d6ae 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -106,6 +106,16 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if self._active_requests.get(request.base_session_id) is task:
self._active_requests.pop(request.base_session_id, None)
self._session_manager.pop_request_session(request.base_session_id)
+ # The poll loop ran to completion above (handle_message awaits the
+ # task), so the turn is fully settled here. Release any web-Chat
+ # stream waiter: a no-result failure (only a notify was emitted)
+ # ends the spinner now instead of waiting out the safety timeout.
+ # Token-guarded + no-op for IM/CLI; success already released via the
+ # result emit during the poll. Defensive: tolerate controllers
+ # without streaming completion support.
+ _mark = getattr(self.controller, "mark_turn_complete", None)
+ if callable(_mark):
+ _mark(request.context)
async def _process_message(self, request: AgentRequest) -> None:
run_registered = False
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index c649a2209..02f76691b 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -99,43 +99,3 @@ 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()