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
feat(agents): register agent-initiated turns with the turn FSM (Stop control) (#689)
Call White0eb6da2ee3da
diff --git a/core/session_turns.py b/core/session_turns.pyindex a0b506e20..c6b8202f9 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -1227,6 +1227,86 @@ class SessionTurnManager:returnself.controller.set_agent_status(session_id, "failed" if is_error else "idle")+ def register_agent_initiated_turn(self, context: "MessageContext") -> bool:+ """Register a turn the BACKEND started on its own (agent-initiated:+ background-task completion / ScheduleWakeup) as a first-class FSM citizen,+ so the Workbench Stop button works and the browser sees ``turn.start`` /+ ``turn.end``.++ Unlike a user / scheduled turn there is NO dispatch task sending a query —+ the backend already started — so this does NOT go through ``dispatch_turn`` /+ ``_run``. The unsolicited output is ALREADY streaming on the long-lived+ receiver, so the sink + ``in_flight`` are registered SYNCHRONOUSLY here+ (before the receiver's next emit), and a small holder task keeps the turn+ open until the terminal result's ``done_event``. Settling (pop sink ++ ``in_flight`` + ``turn.end`` + flush) mirrors ``_run``'s finally. Stop works+ because ``cancel`` interrupts the backend via ``handle_stop(turn.context)``+ and cancels this holder.++ avibe-only: a turn with no workbench session id (IM / CLI) has no Stop+ control and no sink, so this is a no-op there — the gate + outbound+ chokepoint still deliver the reply. Returns ``True`` when a turn was+ registered.+ """+ if self.controller is None:+ return False+ session_id = self.controller._session_id_from_context(context)+ if not session_id:+ return False+ get_key = getattr(self.controller, "_get_session_key", None)+ if not callable(get_key):+ return False+ session_key = get_key(context)+ # Defensive: ``begin_agent_initiated_turn`` only opens on a free gate, so a+ # turn shouldn't already be tracked/streaming — but never clobber one.+ if session_id in self.in_flight or self.get_turn_sink(session_key) is not None:+ return False+ from core.inbox_events import bus++ turn_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")+ done = asyncio.Event()+ self.register_turn_sink(+ session_key,+ on_chunk=self._noop_chunk,+ done_event=done,+ turn_token=turn_token,+ context=context,+ )++ async def _holder() -> None:+ cancelled = False+ try:+ await done.wait()+ except asyncio.CancelledError:+ cancelled = True+ raise+ finally:+ self.pop_turn_sink(session_key, done)+ turn = self.in_flight.pop(session_id, None)+ if turn is not None:+ bus.publish("turn.end", {"session_id": session_id})+ # Flush the send-while-busy queue on NATURAL completion (mirrors+ # ``_run``): a plain Stop keeps the queue, send_now opts back in.+ should_flush = (not cancelled and not (turn is not None and turn.stop_no_flush)) or (+ turn is not None and turn.flush_on_cancel+ )+ if should_flush:+ try:+ await self.flush_queue(session_id)+ except Exception:+ logger.debug("agent-initiated turn: flush_queue failed", exc_info=True)++ try:+ task = asyncio.create_task(_holder(), name="agent-initiated-turn-holder")+ except RuntimeError:+ # No running loop (sync test/stub context): can't hold the turn open —+ # roll the sink back so it doesn't leak, and skip FSM registration.+ self.pop_turn_sink(session_key, done)+ return False+ self.in_flight[session_id] = Turn(task=task, context=context)+ bus.publish("turn.start", {"session_id": session_id})+ return True+def is_active_emit(self, context: "MessageContext") -> bool:"""Whether an emit belongs to the live turn (not a superseded one). Fail-openwhen there's no sink registry / no live sink (non-streaming turns stilldiff --git a/docs/plans/agent-initiated-turn-fsm.md b/docs/plans/agent-initiated-turn-fsm.mdnew file mode 100644index 000000000..9819304e8--- /dev/null+++ b/docs/plans/agent-initiated-turn-fsm.md@@ -0,0 +1,75 @@+# Agent-initiated turns as first-class FSM citizens (#688)++## Background++#687 made the Claude backend's **agent-initiated** output (a background-task+completion / ScheduleWakeup reply) actually reach the user, by opening a runtime+gate turn for it (`AgentService.begin_agent_initiated_turn`). But that turn was+only half-integrated: it set the sidebar dot to `running` (`on_running`) and held+the gate, yet it was never registered with the turn **FSM**+(`SessionTurnManager.in_flight` + `turn.start`/`turn.end`). Two gaps (Codex review+on #687):++- **No Stop control.** The Workbench cancel endpoint delegates to+ `SessionTurnManager.cancel`, which returns `not_in_flight` with no entry — a+ long-running agent-initiated turn shows `running` but can't be stopped.+- **Contended-delivery loss.** The deadlock-safe gate open bails when a user turn+ holds/just-acquired the gate, so an agent-initiated reply buffered in that+ window is dropped (now logged, not silent).++## Part A — FSM registration / Stop control (this PR)++`SessionTurnManager.register_agent_initiated_turn(context)`:++- An agent-initiated turn has **no query-sending dispatch task** (the backend+ already started), so it does NOT go through `dispatch_turn` / `_run`. The+ unsolicited output is ALREADY streaming on the long-lived receiver, so the sink+ + `in_flight` are registered **synchronously** here (before the receiver's next+ emit — no output-before-sink race), and a small holder task keeps the turn open+ until the terminal result's `done_event`.+- Settling (pop sink + `in_flight` + `turn.end` + flush the send-while-busy queue+ on natural completion) mirrors `_run`'s finally.+- Stop works: `cancel` interrupts the backend via the shared+ `handle_stop(turn.context)` path (Claude `client.interrupt()` by+ `composite_session_id`) and cancels the holder.+- avibe-only: a turn with no workbench session id (IM/CLI) has no Stop control or+ sink, so it's a no-op there — the gate + outbound chokepoint still deliver.++Wired into `begin_agent_initiated_turn` right after `on_running` (guarded; the+backend-agnostic open stays backend-agnostic).++## Part B — contended-delivery preservation (NOT in this PR; needs design)++Preserving the reply when the gate is contended is harder than a receiver-side+patch:++- Cleanly distinguishing an *orphaned agent-initiated* result from a *stale+ straggler* (which must stay dropped) is subtle.+- A `persist`-only fallback bypasses the dispatcher's text cleaning / file-link /+ quick-reply handling.+- For **IM** sessions, persisting a row does NOT deliver to the user's phone+ (that needs the dispatcher's `im_client.send_message`), so a persist fallback+ only helps avibe/workbench.++A correct fix needs proper output deferral / re-queue across the contending turn,+which is a separate design effort. The loss is rare (requires the buffered-output++ just-acquiring-user-turn race) and is currently logged, not silent. Tracked.++## Evidence layers++- Unit — `tests/test_agent_initiated_turn_fsm.py`: registration sets `in_flight`+ + sink + `turn.start` synchronously; terminal result `done_event` settles (pop+ + `turn.end` + flush); `cancel` interrupts the backend (`handle_stop`) and+ settles without flush; no-op without a workbench session id; no-op when a turn+ already streams. Adjacent suites green (agent_service, internal_server,+ controller_agent_status, dispatch, stream_chunk; 110 total).+- Contract / Scenario — N/A.+- Residual manual — local Incus regression: start a long background task in an+ agent session, confirm the sidebar Stop interrupts the agent-initiated turn.++## Todo++- [x] `register_agent_initiated_turn` + wire-in+- [x] FSM unit tests+- [ ] ruff + focused pytest (done locally) → CI+- [ ] Part B design decision (defer vs build)diff --git a/modules/agents/service.py b/modules/agents/service.pyindex e8d9d576b..16043f84a 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -322,14 +322,22 @@ class AgentService:# (which no-ops anyway with no live sink for this session).context.platform_specific[AGENT_TURN_TOKEN] = gate.token# INBOUND status chokepoint (mirrors ``handle_message``): mark the avibe- # session ``running`` so the sidebar dot reflects the agent-initiated work.- # Non-avibe contexts resolve to no session id and are skipped.+ # session ``running`` so the sidebar dot reflects the agent-initiated work,+ # and register the turn with the FSM so the Workbench Stop button works and+ # the browser sees turn.start/turn.end. Non-avibe contexts resolve to no+ # session id and are skipped (no-op).manager = getattr(self.controller, "session_turns", None)if manager is not None:try:manager.on_running(context)except Exception:logger.debug("on_running failed for agent-initiated turn", exc_info=True)+ register = getattr(manager, "register_agent_initiated_turn", None)+ if callable(register):+ try:+ register(context)+ except Exception:+ logger.debug("register_agent_initiated_turn failed", exc_info=True)return gate.tokendef release_runtime_turn(self, context: Any) -> None:diff --git a/tests/test_agent_initiated_turn_fsm.py b/tests/test_agent_initiated_turn_fsm.pynew file mode 100644index 000000000..f33ca757a--- /dev/null+++ b/tests/test_agent_initiated_turn_fsm.py@@ -0,0 +1,120 @@+"""Agent-initiated turns are first-class FSM citizens (#688).++``SessionTurnManager.register_agent_initiated_turn`` registers a backend-started+turn (a Claude background-task completion / ScheduleWakeup reply) in ``in_flight``++ a no-op sink + ``turn.start``, held open by a small task until the terminal+result's ``done_event`` (or a Stop). This makes the Workbench Stop button work+(``cancel`` interrupts the backend via ``handle_stop`` and cancels the holder) and+keeps the browser turn lifecycle consistent — without a query-sending dispatch+task, since the backend already started.+"""++from __future__ import annotations++import asyncio+import sys+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core import session_turns+++def _ctx(session_id: str = "s1"):+ return SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={"agent_session_id": session_id, "turn_token": "T-ai"},+ )+++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')}",+ set_agent_status=lambda sid, status: None,+ command_handler=SimpleNamespace(handle_stop=AsyncMock(return_value=True)),+ )+ mgr = session_turns.SessionTurnManager(controller=controller)+ # The holder flushes the send-while-busy queue on natural completion; stub it so+ # the test doesn't reach the DB.+ mgr.flush_queue = AsyncMock(return_value=False)+ return mgr, controller+++async def _settle(times: int = 3) -> None:+ for _ in range(times):+ await asyncio.sleep(0)+++class RegisterAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):+ async def test_registers_in_flight_then_terminal_result_settles(self):+ mgr, _ = _manager()+ ctx = _ctx("s1")+ events: list[tuple[str, str]] = []+ with patch(+ "core.inbox_events.bus.publish",+ side_effect=lambda topic, payload: events.append((topic, (payload or {}).get("session_id"))),+ ):+ ok = mgr.register_agent_initiated_turn(ctx)+ self.assertTrue(ok)+ # Stop target + sink exist synchronously (before any further receiver emit).+ self.assertIn("s1", mgr.in_flight)+ sink = mgr.get_turn_sink("avibe::s1")+ self.assertIsNotNone(sink)+ self.assertIn(("turn.start", "s1"), events)++ # The terminal result sets the sink's done_event → the holder settles.+ sink["done_event"].set()+ await _settle()++ self.assertNotIn("s1", mgr.in_flight)+ self.assertIsNone(mgr.get_turn_sink("avibe::s1"))+ self.assertIn(("turn.end", "s1"), events)+ # Natural completion flushes the send-while-busy queue (mirrors _run).+ mgr.flush_queue.assert_awaited()++ async def test_cancel_interrupts_backend_and_settles_without_flush(self):+ mgr, controller = _manager()+ ctx = _ctx("s2")+ with patch("core.inbox_events.bus.publish"):+ self.assertTrue(mgr.register_agent_initiated_turn(ctx))+ self.assertIn("s2", mgr.in_flight)+ holder = mgr.in_flight["s2"].task+ await _settle() # let the holder park in done.wait() (as in production)++ result = await mgr.cancel("s2")+ await asyncio.gather(holder, return_exceptions=True) # drive the holder's finally++ # Stop interrupted the backend via the shared /stop path, and the turn settled.+ controller.command_handler.handle_stop.assert_awaited()+ self.assertTrue(result.get("ok"))+ self.assertNotIn("s2", mgr.in_flight)+ # A plain Stop keeps the queue (no flush on cancellation).+ mgr.flush_queue.assert_not_awaited()++ async def test_noop_without_workbench_session_id(self):+ mgr, _ = _manager()+ ctx = SimpleNamespace(platform="slack", channel_id="C", platform_specific={}) # no agent_session_id+ with patch("core.inbox_events.bus.publish"):+ ok = mgr.register_agent_initiated_turn(ctx)+ self.assertFalse(ok)+ self.assertEqual(mgr.in_flight, {})++ async def test_noop_when_a_turn_already_streams(self):+ mgr, _ = _manager()+ ctx = _ctx("s3")+ # A streaming turn already owns this session's sink.+ mgr.register_turn_sink("avibe::s3", on_chunk=AsyncMock(), done_event=asyncio.Event())+ with patch("core.inbox_events.bus.publish"):+ ok = mgr.register_agent_initiated_turn(ctx)+ self.assertFalse(ok)+ self.assertNotIn("s3", mgr.in_flight)+++if __name__ == "__main__": # pragma: no cover+ unittest.main()