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(runtime): key the turn sink per thread, not per channel
qiqi1c816a1ddb2d
diff --git a/core/controller.py b/core/controller.pyindex e4d9ab2a3..52948c05b 100644--- a/core/controller.py+++ b/core/controller.py@@ -1147,6 +1147,18 @@ class Controller:settings_key = resolve_context_settings_key(context)return build_context_session_key(context, platform=platform, settings_key=settings_key)+ def _get_turn_sink_key(self, context: MessageContext) -> str:+ """Get the live turn sink's key for ``context``.++ Thread-scoped, unlike ``_get_session_key``: the sink is one agent+ session's turn-concurrency slot, so sharing it across a channel's+ threads made ``dispatch_turn`` refuse unrelated sessions' turns. See+ ``core.message_context.build_context_turn_sink_key``.+ """+ from core.message_context import build_context_turn_sink_key++ return build_context_turn_sink_key(context, session_key=self._get_session_key(context))+def backend_alive(self, context: MessageContext) -> Optional[bool]:"""Best-effort backend liveness for the concise status bubble's footer.@@ -1281,7 +1293,7 @@ class Controller:when an agent turn is genuinely in flight (the result emit releases it)."""if context is None:return- sink = self.get_turn_sink(self._get_session_key(context))+ sink = self.get_turn_sink(self._get_turn_sink_key(context))if sink is None:return# Turn-token guard (mirrors ``_stream_chunk`` / ``_is_active_turn``): adiff --git a/core/message_context.py b/core/message_context.pyindex c5d207d8e..21f398450 100644--- a/core/message_context.py+++ b/core/message_context.py@@ -109,3 +109,40 @@ def build_context_session_key(if requires_typed_user_session_key(context):return f"{resolved_platform}::user::{resolved_settings_key}"return f"{resolved_platform}::{resolved_settings_key}"+++def build_context_turn_sink_key(+ context: MessageContext,+ *,+ session_key: Optional[str] = None,+) -> str:+ """Build the key that identifies ONE agent session's live turn sink.++ Distinct from ``build_context_session_key`` on purpose. That key is+ channel-scoped (``resolve_context_settings_key`` deliberately drops the+ thread), which is right for polls, settings lookup, and message+ consolidation — they are channel-wide concerns. The turn sink is not: it+ is the concurrency slot for a SINGLE agent session, and+ ``dispatch_turn_with_outcome`` refuses any turn that finds the slot taken.++ Keying the sink at channel scope therefore made the refusal channel-wide:+ a long-running Telegram forum topic held the only slot for its whole group,+ so every OTHER topic's turn was refused with ``refused_concurrent_turn``+ before reaching a backend, silently, until that unrelated topic finished.++ The thread scope is resolved the same way every session-anchor caller+ resolves it (``resolve_context_thread_id(context) or context.thread_id``),+ so the key is derived purely from context fields that are already pinned+ before dispatch and carried by every context in a turn's lifetime — the+ dispatch context, the backend receiver's stale per-turn context, and an+ external stop's rebuilt context all land on the same key.+ """++ base = session_key if session_key is not None else build_context_session_key(context)+ # ``getattr`` because this is reached from every turn-lifecycle context, including+ # the lookalike namespaces the workbench/stop paths build. A context without the+ # attribute has no thread, which is the unthreaded case — not an error.+ thread_id = resolve_context_thread_id(context) or getattr(context, "thread_id", None)+ if not thread_id:+ return base+ return f"{base}::thread::{thread_id}"diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 24610f861..fdf780c5d 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -167,16 +167,16 @@ async def _stream_chunk(``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 terminal ``result`` emit also marks the+ stale per-turn context. We resolve the sink by its *thread-scoped sink key*+ (stable across a session's turns) rather than off the context, so reused+ agent sessions stream correctly too. A terminal ``result`` emit also marks theturn complete so ``dispatch_turn`` can close the stream right after it;multi-output callers explicitly pass ``completes_turn=False``. Nosink (IM / CLI turns) => no-op, byte-identical to master."""get_sink = getattr(controller, "get_turn_sink", None)- get_key = getattr(controller, "_get_session_key", None)+ get_key = getattr(controller, "_get_turn_sink_key", None)if not callable(get_sink) or not callable(get_key):# Controller has no streaming turn-sink registry (IM/CLI stubs, older# controllers) => nothing to stream to; stay a no-op.diff --git a/core/services/dispatch.py b/core/services/dispatch.pyindex f3a8876ff..83eb43350 100644--- a/core/services/dispatch.py+++ b/core/services/dispatch.py@@ -141,7 +141,10 @@ async def dispatch_turn_with_outcome(backend_dispatch_attempted=backend_dispatch_attempted(context),)- session_key = controller._get_session_key(context)+ # Thread-scoped, NOT ``_get_session_key`` (channel-scoped): this gate refuses+ # a turn when the slot is taken, so a channel-wide key made one busy Telegram+ # forum topic / Slack thread refuse every sibling thread's turn.+ session_key = controller._get_turn_sink_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 firstdiff --git a/core/services/running_agents.py b/core/services/running_agents.pyindex 639aefb76..ccd35ac47 100644--- a/core/services/running_agents.py+++ b/core/services/running_agents.py@@ -851,7 +851,8 @@ def _build_session_row_stop_context(``avibe::<session_id>``, which can stop the backend when backend ids arepatched in, but cannot find the dispatch sink registered under the originalscope key. Rebuild the same scope context that ``_execute_agent_run`` used so- ``controller._get_session_key`` resolves to the live sink.+ ``controller._get_turn_sink_key`` resolves to the live sink — including the+ row's ``thread_id``, which that key is scoped by."""if not session_id:return Nonediff --git a/core/session_turns.py b/core/session_turns.pyindex 1ce0305e6..daa43aa79 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -396,10 +396,11 @@ class Turn:Queue policy is deliberately absent. The durable Session hold and Turn controlslot decide whether backlog may drain across both process lifetime and restart.- The streaming SINK is deliberately NOT held here: it is keyed by ``session_key``- (platform-prefixed ``avibe::<id>``) not ``session_id``, is registered from the- dispatcher on the emit path, and is platform-agnostic (a future IM stream has a- sink but no avibe ``session_id``). See ``SessionTurnManager.active_turn_sinks``.+ The streaming SINK is deliberately NOT held here: it is keyed by the+ thread-scoped turn-sink key (platform-prefixed, e.g. ``avibe::<id>``) not+ ``session_id``, is registered from the dispatcher on the emit path, and is+ platform-agnostic (an IM stream has a sink but no avibe ``session_id``). See+ ``SessionTurnManager.active_turn_sinks``."""task: asyncio.Task@@ -486,7 +487,7 @@ class SessionTurnManager:- ``in_flight``: ``session_id -> Turn`` for the active turn — the Stop target(``/internal/cancel``) and the ``/turn-state`` projection.- - ``active_turn_sinks``: the live streaming sink per ``session_key`` — the+ - ``active_turn_sinks``: the live streaming sink per turn-sink key — thestreaming half, kept separate on purpose (see ``Turn``).``controller`` reaches the backends + the outbound chokepoint@@ -508,11 +509,18 @@ class SessionTurnManager:self._draining_backends: set[str] = set()self._deferred_restart_sessions: dict[str, set[str]] = {}self._queue_recovery_locks: dict[str, asyncio.Lock] = {}- # 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.+ # The live turn sink per TURN SINK KEY. Each is+ # ``{on_chunk, done_event, turn_token}`` — the turn's stream callback ++ # completion event + correlation token. Every dispatched turn registers one,+ # IM/CLI included (``_run`` always passes ``_noop_chunk`` so the turn stays+ # open until the backend's terminal result), which makes this map the+ # turn-concurrency slot for ALL surfaces, not just web Chat.+ #+ # Keyed by ``controller._get_turn_sink_key`` — the THREAD-scoped key, not the+ # channel-scoped ``_get_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; distinct per thread, so a busy forum topic no longer+ # occupies its siblings' slots.self.active_turn_sinks: dict[str, dict] = {}def _sqlite_engine(self) -> Engine:@@ -4146,7 +4154,7 @@ class SessionTurnManager:return Noneif outcome == "terminal":get_sink = getattr(self.controller, "get_turn_sink", None)- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if callable(get_sink) and callable(get_key):try:sink = get_sink(get_key(context))@@ -6408,7 +6416,7 @@ class SessionTurnManager:if not callable(runtime_started) or runtime_started(context) is not True:return Falsesession_id = self.controller._session_id_from_context(context)- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if not session_id or not callable(get_key):return Falsesession_key = get_key(context)@@ -6504,7 +6512,7 @@ class SessionTurnManager:if current is not None and current.logical_turn_id == logical_turn_id:current.terminal_is_error = current.terminal_is_error or is_errorsink = None- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if callable(get_key):try:sink = self.get_turn_sink(get_key(context))@@ -6557,7 +6565,7 @@ class SessionTurnManager:returncurrent = self.in_flight.get(session_id)sink = None- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if callable(get_key):try:sink = self.get_turn_sink(get_key(context))@@ -6604,7 +6612,7 @@ class SessionTurnManager:session_id = self.controller._session_id_from_context(context)if not session_id:return False- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if not callable(get_key):return Falsesession_key = get_key(context)@@ -6854,7 +6862,7 @@ class SessionTurnManager:settle), else apply the one token rule. Centralizes the old``ConsolidatedMessageDispatcher._is_active_turn``."""get_sink = getattr(self.controller, "get_turn_sink", None)- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if not callable(get_sink) or not callable(get_key):return Truetry:@@ -6959,7 +6967,7 @@ class SessionTurnManager:"""if self.controller is None:return None- get_key = getattr(self.controller, "_get_session_key", None)+ get_key = getattr(self.controller, "_get_turn_sink_key", None)if not callable(get_key):return Nonetry:diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 5cd0834dc..8fb71b3dc 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -89,6 +89,8 @@ capabilities:- tests/test_ui_api.py- tests/test_auth_pipeline.py- tests/test_agent_run_target.py+ - tests/test_core_services_dispatch.pyunit_or_contract_tests:- tests/test_sqlite_settings_store.py+ - tests/test_message_context_helpers.py- tests/test_chat_discovery.pydiff --git a/tests/scenarios/telegram_topic_routing/catalog.yaml b/tests/scenarios/telegram_topic_routing/catalog.yamlindex 91d23b4ec..0fa0f8aac 100644--- a/tests/scenarios/telegram_topic_routing/catalog.yaml+++ b/tests/scenarios/telegram_topic_routing/catalog.yaml@@ -6,6 +6,8 @@ capability:- tests/test_ui_api.py- tests/test_auth_pipeline.py- tests/test_agent_run_target.py+ - tests/test_core_services_dispatch.py+ - tests/test_message_context_helpers.pystatus_legend:covered: automated scenario or contract coverage existsmanual: currently validated by human regression@@ -34,3 +36,9 @@ scenarios:kind: uilayer: manualevidence: output/playwright/telegram-topic-settings.png+ - id: TELEGRAM-TOPIC-005+ name: A topic running a long turn does not block a sibling topic's turn+ status: covered+ kind: concurrency+ layer: contract+ test: tests/test_core_services_dispatch.py::test_busy_sibling_thread_does_not_refuse_this_threads_turndiff --git a/tests/scenarios/telegram_topic_routing/observations.yaml b/tests/scenarios/telegram_topic_routing/observations.yamlindex b2c6a8ad4..04ae75a94 100644--- a/tests/scenarios/telegram_topic_routing/observations.yaml+++ b/tests/scenarios/telegram_topic_routing/observations.yaml@@ -20,3 +20,17 @@ observations:required_updates:- resolve settings from thread then channel- preserve the existing group session key and Telegram reply anchor+ - id: OBS-TELEGRAM-TOPIC-003+ source: field_incident+ related_scenarios:+ - TELEGRAM-TOPIC-005+ summary: >-+ The group-level session key must not be reused for per-turn runtime slots.+ A topic that ran a 15-minute agent held the only turn sink for its whole+ group, so three sibling topics' first turns were settled+ refused_concurrent_turn before reaching a backend, silently, until that+ unrelated topic finished.+ required_updates:+ - key the turn sink at thread scope, not channel scope+ - keep the group session key unchanged for settings, polls, and consolidation+ - assert sibling-topic turn independence at the dispatch contract layerdiff --git a/tests/test_agent_initiated_turn_fsm.py b/tests/test_agent_initiated_turn_fsm.pyindex f33ca757a..a6e5c33ff 100644--- a/tests/test_agent_initiated_turn_fsm.py+++ b/tests/test_agent_initiated_turn_fsm.py@@ -21,6 +21,7 @@ from unittest.mock import AsyncMock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core import session_turns+from core.message_context import build_context_turn_sink_keydef _ctx(session_id: str = "s1"):@@ -36,6 +37,10 @@ def _manager():controller = SimpleNamespace(_session_id_from_context=lambda ctx: (getattr(ctx, "platform_specific", None) or {}).get("agent_session_id"),_get_session_key=lambda ctx: f"avibe::{(getattr(ctx, 'platform_specific', None) or {}).get('agent_session_id')}",+ _get_turn_sink_key=lambda ctx: build_context_turn_sink_key(+ ctx,+ session_key=f"avibe::{(getattr(ctx, 'platform_specific', None) or {}).get('agent_session_id')}",+ ),set_agent_status=lambda sid, status: None,command_handler=SimpleNamespace(handle_stop=AsyncMock(return_value=True)),)diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.pyindex 7e748555c..ff8e1362e 100644--- a/tests/test_core_services_dispatch.py+++ b/tests/test_core_services_dispatch.py@@ -30,6 +30,7 @@ from core.run_settlement import (SETTLED_BY_REFUSED_CONCURRENT_TURN,SETTLED_BY_TERMINAL_RESULT,)+from core.message_context import build_context_turn_sink_keyfrom core.services.dispatch import (SOURCE_HUMAN,SOURCE_SCHEDULED,@@ -110,6 +111,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_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()@@ -139,12 +141,20 @@ def test_on_chunk_absent_keeps_platform_specific_untouched():)-def _streaming_controller(*, sink_settled_by: str | None, in_flight: bool = False) -> MagicMock:+def _streaming_controller(+ *,+ sink_settled_by: str | None,+ in_flight: bool = False,+ in_flight_key: str = "slack::C",+) -> MagicMock:"""A controller double whose registered sink is released like the real one.``sink_settled_by`` is the stamp the release site would have written:``terminal_result`` for a real backend result, ``None`` for a release that leftno trace (``mark_turn_complete`` on a no-dispatch turn).++ ``in_flight_key`` is the sink key the pre-registered turn occupies, so a test can+ park a busy turn on a SIBLING thread's key rather than the one under dispatch."""controller = _build_controller_double()@@ -158,12 +168,17 @@ def _streaming_controller(*, sink_settled_by: str | None, in_flight: bool = Falsdone_event.set()controller._get_session_key = MagicMock(return_value="slack::C")+ # The real controller derives the sink key from the session key by appending the+ # THREAD scope; the double keeps that so a threaded context lands on its own key.+ controller._get_turn_sink_key = MagicMock(+ side_effect=lambda ctx: build_context_turn_sink_key(ctx, session_key="slack::C")+ )controller.get_turn_sink = MagicMock(side_effect=lambda key: sinks.get(key))controller.register_turn_sink = MagicMock(side_effect=_register)controller.pop_turn_sink = MagicMock(side_effect=lambda key, done=None: sinks.pop(key, None))if in_flight:# Pre-register a live sink for the same session: a turn is already streaming.- sinks["slack::C"] = {"on_chunk": AsyncMock(), "done_event": asyncio.Event()}+ sinks[in_flight_key] = {"on_chunk": AsyncMock(), "done_event": asyncio.Event()}return controller@@ -222,6 +237,53 @@ def test_outcome_reports_refused_concurrent_turn():controller.message_handler.handle_user_message.assert_not_called()+def test_busy_sibling_thread_does_not_refuse_this_threads_turn():+ """A turn in flight on ANOTHER thread of the same channel must not block this one.++ The field bug: ``dispatch_turn_with_outcome`` keyed its concurrency slot off the+ channel-scoped ``_get_session_key``, because+ ``resolve_context_settings_key`` deliberately drops the thread. One Telegram forum+ topic running a 15-minute agent therefore held the ONLY slot for its whole group,+ and every sibling topic's first turn was settled ``refused_concurrent_turn``+ before reaching a backend — silently, since IM turns dispatch with the discarding+ ``_noop_chunk`` — until the unrelated topic finished.+ """++ busy_sibling = MessageContext(+ user_id="U", channel_id="C", platform="telegram", thread_id="843", message_id="m0"+ )+ controller = _streaming_controller(+ sink_settled_by=SETTLED_BY_TERMINAL_RESULT,+ in_flight=True,+ in_flight_key=build_context_turn_sink_key(busy_sibling, session_key="slack::C"),+ )+ new_topic = MessageContext(+ user_id="U", channel_id="C", platform="telegram", thread_id="847", message_id="m1"+ )+ outcome = asyncio.run(+ dispatch_turn_with_outcome(controller, new_topic, "create a directory", on_chunk=AsyncMock())+ )+ assert outcome.settled_by == SETTLED_BY_TERMINAL_RESULT+ controller.message_handler.handle_user_message.assert_awaited_once()+++def test_same_thread_turn_is_still_refused():+ """The slot is still exactly one turn per THREAD — the guard must stay real."""++ ctx = MessageContext(+ user_id="U", channel_id="C", platform="telegram", thread_id="843", message_id="m1"+ )+ controller = _streaming_controller(+ sink_settled_by=None,+ in_flight=True,+ in_flight_key=build_context_turn_sink_key(ctx, session_key="slack::C"),+ )+ controller._t = MagicMock(return_value="already streaming")+ outcome = asyncio.run(dispatch_turn_with_outcome(controller, ctx, "hi", on_chunk=AsyncMock()))+ assert outcome.settled_by == SETTLED_BY_REFUSED_CONCURRENT_TURN+ controller.message_handler.handle_user_message.assert_not_called()++def test_outcome_settled_by_is_none_only_without_on_chunk():# ``None`` must mean exactly one thing — "no streaming caller, so no sink" —# otherwise a durable caller cannot tell an unexplained release apart from adiff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.pyindex 3f5908c35..fe7969b18 100644--- a/tests/test_dispatcher_stream_chunk.py+++ b/tests/test_dispatcher_stream_chunk.py@@ -19,6 +19,7 @@ from unittest.mock import AsyncMocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from core.message_context import build_context_turn_sink_keyfrom core.message_dispatcher import _stream_chunkfrom core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULTfrom modules.im import MessageContext@@ -33,6 +34,9 @@ class _ControllerDouble:def _get_session_key(self, ctx):return f"{ctx.platform}::{ctx.channel_id}"+ def _get_turn_sink_key(self, ctx):+ return build_context_turn_sink_key(ctx, session_key=self._get_session_key(ctx))+def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):self.active_turn_sinks[session_key] = {"on_chunk": on_chunk,diff --git a/tests/test_message_context_helpers.py b/tests/test_message_context_helpers.pyindex 8e3bbf52d..2e80b63ea 100644--- a/tests/test_message_context_helpers.py+++ b/tests/test_message_context_helpers.py@@ -1,5 +1,6 @@from core.message_context import (build_context_session_key,+ build_context_turn_sink_key,build_thread_session_anchor,build_thread_session_anchor_candidates,resolve_context_settings_key,@@ -51,6 +52,63 @@ def test_telegram_thread_anchor_candidates_include_legacy_shape():)+def _telegram_topic(thread_id):+ return MessageContext(+ user_id="U1",+ channel_id="-1004266799216",+ platform="telegram",+ thread_id=thread_id,+ platform_specific={"platform": "telegram", "is_forum": True},+ )+++def test_turn_sink_key_separates_forum_topics_that_share_a_session_key():+ """Two topics of one group share a session key but must NOT share a sink slot.++ The sink is a turn-concurrency slot: whoever holds it makes every other turn on+ the same key settle ``refused_concurrent_turn`` before reaching a backend. The+ channel-scoped session key made that refusal group-wide.+ """+ topic_843 = _telegram_topic("843")+ topic_847 = _telegram_topic("847")++ assert build_context_session_key(topic_843) == build_context_session_key(topic_847)+ assert build_context_turn_sink_key(topic_843) != build_context_turn_sink_key(topic_847)+ assert build_context_turn_sink_key(topic_847) == "telegram::-1004266799216::thread::847"+++def test_turn_sink_key_is_stable_across_a_threads_turns():+ """The backend receiver resolves the sink from a stale per-turn context, so the+ key must depend only on the routing scope — never on per-turn state."""+ first = _telegram_topic("847")+ first.platform_specific = {**(first.platform_specific or {}), "turn_token": "tok-1"}+ second = _telegram_topic("847")+ second.platform_specific = {**(second.platform_specific or {}), "turn_token": "tok-2"}++ assert build_context_turn_sink_key(first) == build_context_turn_sink_key(second)+++def test_turn_sink_key_scopes_non_telegram_threads_too():+ """``resolve_context_thread_id`` returns None off Telegram, so the fallback to+ ``context.thread_id`` is what keeps Slack/Discord threads independent."""+ thread_a = MessageContext(+ user_id="U1", channel_id="C1", platform="slack", thread_id="171717.111"+ )+ thread_b = MessageContext(+ user_id="U1", channel_id="C1", platform="slack", thread_id="171717.222"+ )++ assert build_context_turn_sink_key(thread_a) == "slack::C1::thread::171717.111"+ assert build_context_turn_sink_key(thread_a) != build_context_turn_sink_key(thread_b)+++def test_turn_sink_key_falls_back_to_session_key_without_a_thread():+ """A channel-level (unthreaded) context keeps today's key verbatim."""+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")++ assert build_context_turn_sink_key(context) == build_context_session_key(context)++def test_thread_id_from_session_anchor_accepts_canonical_and_legacy_shapes():assert (thread_id_from_session_anchor(diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.pyindex f50ea9add..fa8baca54 100644--- a/tests/test_running_agents_service.py+++ b/tests/test_running_agents_service.py@@ -12,6 +12,7 @@ import typesimport pytest+from core.message_context import build_context_turn_sink_keyfrom core.services import running_agents@@ -947,6 +948,9 @@ def test_end_active_agent_run_binds_stop_context_to_matching_turn_sink(monkeypatdef _get_session_key(self, context):return f"{context.platform}::{context.channel_id}"+ def _get_turn_sink_key(self, context):+ return build_context_turn_sink_key(context, session_key=self._get_session_key(context))+def bind_context_to_turn_sink(self, context, *, agent_session_id=None, backend_base_session_id=None):return self.session_turns.bind_context_to_turn_sink(context,@@ -975,8 +979,11 @@ def test_end_active_agent_run_binds_stop_context_to_matching_turn_sink(monkeypat},},)+ # Register under the key real dispatch would use, derived from the same context. A+ # hardcoded literal here would stop proving that the REBUILT stop context lands on+ # the dispatcher's key, which is the whole point of this test.controller.session_turns.register_turn_sink(- "slack::private-agent-run-scope",+ controller._get_turn_sink_key(dispatch_context),on_chunk=lambda _envelope: None,done_event=sink_done,turn_token="sink-token",@@ -998,6 +1005,11 @@ def test_end_active_agent_run_binds_stop_context_to_matching_turn_sink(monkeypatassert sink_done.is_set()stopped_context = seen["context"]assert controller._get_session_key(stopped_context) == "slack::private-agent-run-scope"+ # The rebuilt stop context must carry the row's thread too, or it lands on a+ # different sink key than the dispatch that registered the sink.+ assert controller._get_turn_sink_key(stopped_context) == controller._get_turn_sink_key(+ dispatch_context+ )assert stopped_context.platform_specific["turn_token"] == "sink-token"assert stopped_context.platform_specific["task_trigger_kind"] == "agent_run"assert stopped_context.platform_specific["task_execution_id"] == "run-primary"@@ -1049,6 +1061,9 @@ def test_end_active_agent_run_does_not_settle_mismatched_turn_sink(monkeypatch):def _get_session_key(self, context):return f"{context.platform}::{context.channel_id}"+ def _get_turn_sink_key(self, context):+ return build_context_turn_sink_key(context, session_key=self._get_session_key(context))+def bind_context_to_turn_sink(self, context, *, agent_session_id=None, backend_base_session_id=None):return self.session_turns.bind_context_to_turn_sink(context,@@ -1076,7 +1091,7 @@ def test_end_active_agent_run_does_not_settle_mismatched_turn_sink(monkeypatch):},)controller.session_turns.register_turn_sink(- "slack::private-agent-run-scope",+ controller._get_turn_sink_key(newer_context),on_chunk=lambda _envelope: None,done_event=sink_done,turn_token="new-token",diff --git a/tests/test_show_git_turn_entrypoints.py b/tests/test_show_git_turn_entrypoints.pyindex 8df86c27e..b9efc7aec 100644--- a/tests/test_show_git_turn_entrypoints.py+++ b/tests/test_show_git_turn_entrypoints.py@@ -12,6 +12,7 @@ from config import pathsfrom core import inbox_events, internal_server, show_gitfrom core.git_binary import ResolvedGitfrom core.inbox_events import InboxEventBus+from core.message_context import build_context_turn_sink_keyfrom core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.message_output import MessageOutputfrom core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore, TaskExecutionStore@@ -140,6 +141,9 @@ class _Controller:def _get_session_key(context) -> str:return f"{context.platform}::{context.channel_id}"+ def _get_turn_sink_key(self, context) -> str:+ return build_context_turn_sink_key(context, session_key=self._get_session_key(context))+def register_turn_sink(self, session_key: str, **kwargs) -> None:self.session_turns.register_turn_sink(session_key, **kwargs)