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.

refactor(workbench): re-home the turn-sink registry onto SessionTurnManager (#386)

Call White91ad2711eb11
diff --git a/core/controller.py b/core/controller.py
index 5e2234eeb..f50770eae 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -56,15 +56,9 @@ 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]] = {}
+ # The live streaming turn-sink registry now lives on the turn owner
+ # (``self.session_turns.active_turn_sinks``); the register/pop/get methods +
+ # the ``active_turn_sinks`` property below delegate to it.
# Per-session turn gate, published by ``core.internal_server.create_app``
# once the internal server is built on the loop. The scheduler routes
@@ -595,37 +589,21 @@ class Controller:
# turn complete. See ``core/services/dispatch.py`` and the
# ``ConsolidatedMessageDispatcher._stream_chunk`` consumer.
+ @property
+ def active_turn_sinks(self) -> Dict[str, Dict[str, Any]]:
+ # Owned by the turn owner (FSM); exposed here for back-compat readers.
+ return self.session_turns.active_turn_sinks
+
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
- # 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)
- return
- # ``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,
- }
+ self.session_turns.register_turn_sink(
+ 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
- # concurrent/retried turn may have replaced it (same session key,
- # different done_event); the older turn's cleanup must not evict the
- # newer turn's sink (which would stop its stream). ``done_event=None``
- # pops unconditionally for non-streaming/legacy callers.
- sink = self.active_turn_sinks.get(session_key)
- if sink is None:
- return
- if done_event is not None and sink.get("done_event") is not done_event:
- return
- self.active_turn_sinks.pop(session_key, None)
+ self.session_turns.pop_turn_sink(session_key, done_event)
def get_turn_sink(self, session_key: str) -> Optional[Dict[str, Any]]:
- return self.active_turn_sinks.get(session_key)
+ return self.session_turns.get_turn_sink(session_key)
def mark_turn_complete(self, context: Optional[MessageContext] = None) -> None:
"""Release a streaming turn sink whose turn finished WITHOUT emitting a
diff --git a/core/session_turns.py b/core/session_turns.py
index f1fe2ebfc..3ffd4cae0 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -85,6 +85,12 @@ class SessionTurnManager:
self.in_flight: dict[str, tuple[asyncio.Task, "MessageContext"]] = {}
self.flush_on_cancel: set[str] = set()
self.stop_no_flush: set[str] = set()
+ # The live streaming turn sink per SESSION KEY (avibe/web-Chat only; IM/CLI
+ # turns register none). Each is ``{on_chunk, done_event, turn_token}`` — the
+ # turn's stream callback + completion event + correlation token. Keyed by
+ # session_key (stable across a session's turns) so a reused agent receiver
+ # carrying a stale per-turn context still resolves the current turn's sink.
+ self.active_turn_sinks: dict[str, dict] = {}
def is_in_flight(self, session_id: Optional[str]) -> bool:
"""True when ``session_id`` has an active (RUNNING) turn."""
@@ -426,6 +432,38 @@ class SessionTurnManager:
return True
return emit_matches_active_turn(sink, context)
+ # --- the live streaming turn sink (owned here; Controller delegates) ----------
+
+ 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 does, keep the in-flight turn's sink rather than clobbering
+ # it (replacing it once let a stale result satisfy a replacement sink).
+ logger.warning("Ignoring duplicate turn sink registration for %s", session_key)
+ return
+ # 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 concurrent /
+ # retried turn may have replaced it (same session key, different done_event);
+ # the older turn's cleanup must not evict the newer turn's sink. done_event=None
+ # pops unconditionally (non-streaming / legacy callers).
+ sink = self.active_turn_sinks.get(session_key)
+ if sink is None:
+ return
+ if done_event is not None and sink.get("done_event") is not done_event:
+ return
+ self.active_turn_sinks.pop(session_key, None)
+
+ def get_turn_sink(self, session_key: str) -> Optional[dict]:
+ return self.active_turn_sinks.get(session_key)
+
# --- boot / restore edge transitions -----------------------------------------
@staticmethod
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index cea5d7604..83dc290b6 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -157,26 +157,23 @@ def test_register_turn_sink_ignores_duplicate_and_pop_is_identity_guarded():
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 types
-
- from core.controller import Controller
-
- fake = types.SimpleNamespace(active_turn_sinks={})
+ another turn's sink. The sink registry is owned by SessionTurnManager (the
+ Controller methods are thin delegations)."""
+ mgr = session_turns.SessionTurnManager()
first = asyncio.Event()
- Controller.register_turn_sink(fake, "avibe::s", on_chunk=AsyncMock(), done_event=first)
+ mgr.register_turn_sink("avibe::s", on_chunk=AsyncMock(), done_event=first)
second = asyncio.Event()
- Controller.register_turn_sink(fake, "avibe::s", on_chunk=AsyncMock(), done_event=second)
+ mgr.register_turn_sink("avibe::s", on_chunk=AsyncMock(), done_event=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 mgr.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
+ mgr.pop_turn_sink("avibe::s", second)
+ assert "avibe::s" in mgr.active_turn_sinks
+ mgr.pop_turn_sink("avibe::s", first)
+ assert "avibe::s" not in mgr.active_turn_sinks
def test_dispatch_rejects_concurrent_same_session_turn():