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): unify the avibe turn lifecycle into one SessionTurnManager (phases 1b + 2) (#385)

Call Whiteee1c97c3e189
diff --git a/core/controller.py b/core/controller.py
index d1fcba1e8..5e2234eeb 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -74,6 +74,15 @@ class Controller:
# up — callers must treat its absence as "fall back to the direct path".
self.session_turn_gate: Optional[Any] = None
+ # Per-session turn owner (FSM). Created here so the controller owns it from
+ # birth — boot stale-reset (below) and the OpenCode poll restore both run
+ # before the internal server binds. ``core.internal_server.create_app`` later
+ # binds the routing-context builder + exposes the gate endpoints; the gate,
+ # dispatcher, and scheduler all share this one owner's in_flight + flush state.
+ from core.session_turns import SessionTurnManager
+
+ self.session_turns = SessionTurnManager(self)
+
# Initialize core modules
self._init_modules()
@@ -116,7 +125,7 @@ class Controller:
# Crash recovery: no turn survives a restart, so any session left
# ``running`` in the table is stale — reset it to ``idle`` so the
# workbench sidebar dot doesn't show a phantom green forever.
- self._reset_stale_agent_status()
+ self.session_turns.reset_stale()
def _init_modules(self):
"""Initialize core modules"""
@@ -632,12 +641,12 @@ class Controller:
# Turn-token guard (mirrors ``_stream_chunk`` / ``_is_active_turn``): a
# SUPERSEDED or OLDER turn ending (a stopped turn whose backend later fires
# turn/completed, or a scheduled/watch run that carries no token) must not
- # close the CURRENT turn's stream. When the live sink HAS a token, only a
- # result with the MATCHING token may complete it — a different OR absent
- # token is stale. Fail-open only when the sink itself is tokenless.
- sink_token = sink.get("turn_token")
- ctx_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
- if sink_token is not None and ctx_token != sink_token:
+ # close the CURRENT turn's stream — the ONE active-turn token rule (shared
+ # with _stream_chunk + _is_active_turn) decides if this emit is the live
+ # turn's; a different OR absent token is stale, fail-open when tokenless.
+ from core.session_turns import emit_matches_active_turn
+
+ if not emit_matches_active_turn(sink, context):
return
done = sink.get("done_event")
if done is not None:
@@ -655,7 +664,7 @@ class Controller:
# A fire-and-forget backend error surfaces as an emitted message, not an
# exception, so terminal failures are emitted as ``result`` + ``is_error`` and
# ride the same outbound chokepoint. ``set_agent_status`` is the shared writer;
- # ``_reset_stale_agent_status`` recovers ``running`` rows to ``idle`` on
+ # ``SessionTurnManager.reset_stale`` recovers ``running`` rows to ``idle`` on
# startup (a turn whose process died never reached the outbound chokepoint).
@staticmethod
@@ -695,28 +704,6 @@ class Controller:
except Exception:
logger.debug("set_agent_status failed for session=%s", session_id, exc_info=True)
- def _reset_stale_agent_status(self) -> None:
- # Runs in ``__init__`` (crash recovery), BEFORE any ``/internal/events``
- # subscriber exists — so it deliberately does NOT broadcast
- # ``session.status`` (the bus drops events with no subscribers). The
- # browser instead reconciles the reset by refetching sessions when its
- # inbox-event stream (re)connects (ui: ``onInboxStreamReady``), which
- # also recovers any other events missed while the controller was down.
- try:
- from core.services import sessions as workbench_sessions_service
- from storage.db import create_sqlite_engine
-
- engine = create_sqlite_engine()
- try:
- with engine.begin() as conn:
- reset = workbench_sessions_service.reset_running_agent_status(conn)
- finally:
- engine.dispose()
- if reset:
- logger.info("Reset %s stale 'running' agent session(s) to idle on startup", reset)
- except Exception:
- logger.debug("agent_status startup reset failed", exc_info=True)
-
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/internal_server.py b/core/internal_server.py
index 2be4d06f8..80cf232e9 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -81,216 +81,64 @@ def create_app(controller: "Controller") -> FastAPI:
# header changed the session's agent / model while the reply was streaming.
# Tasks are registered when the SSE response starts and removed in its
# ``finally`` so cancelled / completed sessions don't leak slots.
- in_flight: dict[str, tuple[asyncio.Task, MessageContext]] = {}
+ # The turn owner (FSM) is created in Controller.__init__ so it exists for boot
+ # stale-reset + OpenCode restore; reuse it here and bind the routing-context
+ # builder now that the gate (which owns _build_session_context) is built. A fake
+ # controller in tests may lack one — create it then. The containers bound below
+ # are the SAME objects the closures + ``controller.session_turn_gate`` use.
+ from core.session_turns import SessionTurnManager
+
+ manager = getattr(controller, "session_turns", None)
+ if not isinstance(manager, SessionTurnManager):
+ # Real controllers create it in __init__; a fake/Mock controller in tests
+ # exposes a truthy stand-in, so gate on the type, not truthiness.
+ manager = SessionTurnManager(controller)
+ controller.session_turns = manager
+ manager.bind_context(_build_session_context)
+
+ in_flight = manager.in_flight
app.state.in_flight_dispatches = in_flight
# Sessions whose current turn should flush its send-while-busy queue EVEN
# though it's ending via cancellation. A plain Stop cancels without flushing
# (the user asked to keep the queue — "不清空队列"); ``send-now`` cancels the
# running turn but sets this so the queue runs immediately afterwards.
- flush_on_cancel: set[str] = set()
+ flush_on_cancel = manager.flush_on_cancel
app.state.flush_on_cancel = flush_on_cancel
# Sessions whose current turn is being stopped by a plain Stop and must NOT
# flush, even if the backend interrupt lets the turn settle NORMALLY (no
# CancelledError) during the awaited stop — a Stop keeps the queue ("不清空").
# Recorded before awaiting the interrupt so the race is covered.
- stop_no_flush: set[str] = set()
-
- async def _noop_chunk(_envelope: dict) -> None:
- # Chunks are discarded — the browser renders from ``message.new``.
- return None
-
- async def _run_turn(
- session_id: Optional[str],
- context: MessageContext,
- text: str,
- *,
- source: str = SOURCE_HUMAN,
- ) -> None:
- """Start a fire-and-forget turn and HOLD it open until it settles.
-
- A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime
- so ``in_flight`` stays populated (Stop works) and the session-level
- ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
- working indicator. On NATURAL completion the queue is flushed: messages
- the user sent while this turn ran are merged + run as the next turn. A
- user Stop (cancellation) does NOT flush — the queue is kept per the
- user's "don't clear the queue on stop" rule — unless ``send-now`` opted
- this session into ``flush_on_cancel``. The reply reaches the browser over
- ``message.new``, not a response stream.
-
- ``source`` selects the human vs. scheduler turn path in ``dispatch_turn``.
- Interactive Chat sends keep the default ``SOURCE_HUMAN``; a scheduled /
- watch run passes ``SOURCE_SCHEDULED`` so it goes through the SAME gate
- (in_flight registration + turn.start/turn.end + queue draining) as a Chat
- turn. Both pass the no-op sink so the turn is HELD open until its terminal
- result (in_flight stays for the turn's whole lifetime); the scheduled
- reply still surfaces over ``message.new`` + the outbound result / dot, not
- an open stream.
- """
- from core.inbox_events import bus
-
- async def _runner() -> None:
- cancelled = False
- failed = False
- try:
- await dispatch_turn(
- controller,
- context,
- text,
- source=source,
- # ALWAYS pass the no-op sink — even for scheduled runs. The sink
- # isn't about the browser (chunks are discarded; avibe renders from
- # message.new); it makes ``dispatch_turn`` HOLD the turn open until
- # the backend's terminal result, which is what keeps ``in_flight``
- # populated for the turn's whole lifetime. With ``on_chunk=None`` an
- # async backend (Codex/Claude) returns at prompt-submit, so the slot
- # would free + a Chat send could preempt the still-running scheduled
- # turn (Codex P2).
- on_chunk=_noop_chunk,
- )
- except asyncio.CancelledError:
- cancelled = True
- raise
- except Exception:
- # dispatch_turn raised before any backend turn was actually
- # dispatched (missing/disabled backend, synchronous setup error).
- # No agent reply was produced, so this is a terminal FAILURE — it
- # must NOT auto-flush the send-while-busy queue onto a fresh turn
- # (Codex P2). (An explicit send-now flush_on_cancel still flushes.)
- failed = True
- logger.exception("internal async dispatch failed for session=%s", session_id)
- finally:
- if isinstance(session_id, str):
- # The turn is over — the agent emitted its terminal result, the
- # user stopped it, or dispatch raised before any backend turn.
- # There is NO turn-duration timeout: a long agent runs for hours
- # and is never killed on a timer, so the slot is freed only by a
- # real terminal signal here (Phase 1a — STUCK/sentinel removed).
- in_flight.pop(session_id, None)
- bus.publish("turn.end", {"session_id": session_id})
- # Converge the no-terminal-result outcome onto the OUTBOUND status
- # chokepoint. The normal path already emitted a terminal result;
- # only ``failed`` reaches here without one: dispatch raised before
- # any backend turn (missing/disabled backend) → empty error result
- # → dot red. This is a real terminal FAILURE, not a timeout.
- if failed:
- await controller.emit_agent_message(context, "result", "", is_error=True)
- # Don't flush after a Stop (keep the queue) or a terminal failure.
- # send-now still forces a flush via flush_on_cancel.
- should_flush = (
- (not cancelled and not failed and session_id not in stop_no_flush)
- or (session_id in flush_on_cancel)
- )
- flush_on_cancel.discard(session_id)
- stop_no_flush.discard(session_id)
- if should_flush:
- await _flush_queue(session_id)
-
- task = asyncio.create_task(_runner(), name="internal-dispatch-async")
- if isinstance(session_id, str) and session_id:
- in_flight[session_id] = (task, context)
- bus.publish("turn.start", {"session_id": session_id})
+ stop_no_flush = manager.stop_no_flush
async def _flush_queue(session_id: str) -> bool:
- """Pop the messages queued while a turn ran, merge them into one
- (newline-joined) user message, and run it as the next turn — recursively
- draining the queue. Returns True if a turn was started, False on an empty
- queue / failure (so ``send-now`` can report idle instead of leaving the
- client stuck waiting). The merge is the user's choice (one dispatch, not
- N); the individual queued rows are deleted by ``pop_queued`` and replaced
- by the single merged user row."""
- from core.inbox_events import bus
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- if not session_id:
- return False
- user_row = None
- inbox_row = None
- try:
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- rows = messages_service.pop_queued(conn, session_id)
- texts = [r.get("text") for r in rows if (r.get("text") or "").strip()]
- if not texts:
- return False
- user_row = messages_service.append(
- conn,
- scope_id=rows[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type="user",
- text="\n".join(texts),
- )
- inbox_row = messages_service.get_inbox_session(conn, session_id)
- except Exception:
- logger.exception("queue flush: failed to pop/merge for session=%s", session_id)
- return False
- if user_row is None:
- return False
- # Surface the flushed (merged) user message, bump the inbox card (so other
- # workbench views re-rank + flip 'replied' without waiting for the next
- # result — Codex P2), and mark the queue empty.
- bus.publish("message.new", user_row)
- if inbox_row is not None:
- bus.publish("inbox.session.updated", inbox_row)
- bus.publish("queue.updated", {"session_id": session_id})
- # Rebuild routing from the CURRENT session row so a queued follow-up uses
- # the session's latest agent / model / effort — the user may have changed
- # it while the prior (now-finished) turn was running (Codex P2).
- try:
- context = _build_session_context(session_id)
- except Exception:
- logger.exception("queue flush: failed to build context for session=%s", session_id)
- return False
- await _run_turn(session_id, context, user_row.get("text") or "")
- return True
+ """Thin delegation to ``SessionTurnManager.flush_queue`` (FSM, Phase 1b):
+ pop + merge the send-while-busy queue and run it as the next turn. Returns
+ True if a turn was started, False on an empty queue / failure."""
+ return await manager.flush_queue(session_id)
async def _submit_scheduled_turn(session_id: str, context: MessageContext, text: str) -> None:
- """Run a scheduled / watch turn through the SAME per-session gate the
- interactive Chat path uses, so a scheduled run can never preempt an active
- Chat turn and always gets the turn lifecycle (in_flight + turn.start /
- turn.end + Stop) the Chat page renders (Codex P2).
-
- Decision mirrors ``_dispatch_async`` (the single-threaded loop keeps the
- busy-check and the enqueue write atomic — no ``await`` between them):
-
- * busy (a turn is in flight) OR a prior Stop left queued rows behind →
- ENQUEUE this run's text so it runs AFTER the active turn / the existing
- queue via the existing ``_flush_queue``. Unlike the Chat path there is
- no pre-persisted ``pending`` row to promote, so we ``append`` a fresh
- ``queued`` row attributed to the harness.
- * idle but a pre-existing queue → drain it (this run joins the queue first,
- then ``_flush_queue`` merges + runs everything in order).
- * idle, empty queue → run the turn now as ``SOURCE_SCHEDULED``.
+ """Run a scheduled / watch turn through the SAME unified ``manager.submit``
+ the interactive Chat path uses, so a scheduled run can never preempt an
+ active Chat turn and gets the full turn lifecycle (in_flight + turn.start /
+ turn.end + Stop) the Chat page renders (Codex P2). Unlike Chat there is no
+ pre-persisted ``pending`` row to promote, so the enqueue callback ``append``s
+ a fresh ``queued`` row attributed to the harness.
"""
if not session_id:
- await _run_turn(None, context, text, source=SOURCE_SCHEDULED)
+ await manager.submit(None, context, text, source=SOURCE_SCHEDULED)
return
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- existing = in_flight.get(session_id)
- busy = existing is not None and not existing[0].done()
- engine = create_sqlite_engine()
- if busy:
- should_enqueue = True
- else:
- with engine.connect() as conn:
- should_enqueue = bool(messages_service.list_queued(conn, session_id))
- if should_enqueue:
+ def _enqueue() -> None:
from core.message_mirror import _scope_id_for_session
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
- # Persist the scheduled prompt as a queued row so it drains via
- # ``_flush_queue`` after the active turn. ``pop_queued`` /
- # ``_flush_queue`` key off ``(session_id, type=queued)`` + ``scope_id`` +
- # ``text`` only, so the harness attribution (author/source) is safe to
- # carry — it just records who triggered the queued run.
+ # ``pop_queued`` / ``flush_queue`` key off (session_id, type=queued) +
+ # scope_id + text only, so the harness attribution (author/source) is safe
+ # to carry — it just records who triggered the queued run.
+ engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = _scope_id_for_session(conn, session_id)
if scope_id is not None:
@@ -304,13 +152,8 @@ def create_app(controller: "Controller") -> FastAPI:
message_type=messages_service.QUEUED_TYPE,
text=text,
)
- # Idle + pre-existing queue → no running turn to flush behind, so drain
- # the whole queue (this row included) now, in order.
- if not busy:
- await _flush_queue(session_id)
- return
- await _run_turn(session_id, context, text, source=SOURCE_SCHEDULED)
+ await manager.submit(session_id, context, text, source=SOURCE_SCHEDULED, enqueue=_enqueue)
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
@@ -318,13 +161,9 @@ def create_app(controller: "Controller") -> FastAPI:
@app.get("/internal/turn-state/{session_id}")
async def _turn_state(session_id: str) -> Any:
- """Whether a turn is currently running for the session. The fire-and-
- forget dispatch survives browser disconnects, so a freshly loaded /
- reconnected Chat page asks this to restore its working/Stop state for a
- turn that is still in flight (Codex P2)."""
- entry = in_flight.get(session_id)
- active = entry is not None and not entry[0].done()
- return {"ok": True, "session_id": session_id, "in_flight": active}
+ """HTTP adapter: whether a turn is running, delegated to the turn owner
+ (FSM, Phase 1b). A reconnected Chat page asks this to restore working/Stop."""
+ return manager.turn_state(session_id)
@app.post("/internal/dispatch")
async def _dispatch(request: Request) -> Any:
@@ -454,39 +293,26 @@ def create_app(controller: "Controller") -> FastAPI:
return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})
session_id = payload.get("session_id")
- if isinstance(session_id, str) and session_id:
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- existing = in_flight.get(session_id)
- busy = existing is not None and not existing[0].done()
- # Enqueue (rather than start a turn) when EITHER a turn is already
- # running OR a prior Stop left queued rows behind — in the latter case
- # the new message must run AFTER them, so it joins the queue instead of
- # jumping ahead (Codex P2). The in_flight check + the mark below have no
- # ``await`` between them, so the running turn can't end + flush in the
- # gap (single-threaded loop) — the atomic enqueue.
- engine = create_sqlite_engine()
- if busy:
- should_enqueue = True
- else:
- with engine.connect() as conn:
- should_enqueue = bool(messages_service.list_queued(conn, session_id))
- if should_enqueue:
- user_message_id = payload.get("user_message_id")
- if isinstance(user_message_id, str) and user_message_id:
- with engine.begin() as conn:
- messages_service.promote_pending(conn, user_message_id, messages_service.QUEUED_TYPE)
- # Idle + pre-existing queue → no running turn to flush behind, so
- # drain the whole queue (this row included) now, in order.
- if not busy:
- await _flush_queue(session_id)
- return JSONResponse(
- status_code=202,
- content={"ok": True, "queued": True, "session_id": session_id, "message_id": user_message_id},
- )
-
- await _run_turn(session_id if isinstance(session_id, str) else None, context, text)
+ sid = session_id if isinstance(session_id, str) and session_id else None
+ user_message_id = payload.get("user_message_id")
+
+ def _enqueue() -> None:
+ # Chat already persisted the user's message as a ``pending`` row; promote
+ # it to ``queued`` so it drains via the queue after the active turn.
+ if isinstance(user_message_id, str) and user_message_id:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ messages_service.promote_pending(conn, user_message_id, messages_service.QUEUED_TYPE)
+
+ outcome = await manager.submit(sid, context, text, enqueue=_enqueue)
+ if outcome == "enqueued":
+ return JSONResponse(
+ status_code=202,
+ content={"ok": True, "queued": True, "session_id": session_id, "message_id": user_message_id},
+ )
return JSONResponse(status_code=202, content={"ok": True, "session_id": session_id})
@app.get("/internal/events")
@@ -527,108 +353,26 @@ def create_app(controller: "Controller") -> FastAPI:
@app.post("/internal/cancel/{session_id}")
async def _cancel(session_id: str) -> Any:
- # ``session_id`` is the dispatch key — matches the body field
- # the dispatch endpoint registered under. Using the session id
- # (rather than introducing a separate run_id contract) keeps
- # the public surface narrow and lets the UI ``Stop`` button
- # work with just the URL it already has.
- entry = in_flight.get(session_id)
- if entry is None:
- return JSONResponse(
- status_code=404,
- content={"ok": False, "code": "not_in_flight", "session_id": session_id},
- )
- task, turn_context = entry
- if task.done():
- return {"ok": True, "session_id": session_id, "status": "already_finished"}
- # Interrupt the agent's backend turn through the SAME path the IM
- # ``/stop`` command uses, so the underlying agent run is actually
- # stopped (Claude interrupt / Codex turn-interrupt / OpenCode abort) —
- # not just this SSE proxy task. Without it the agent keeps running and
- # its late reply leaks into the next turn's stream. We pass the context
- # the turn STARTED under (captured at dispatch time), not one rebuilt
- # from the current session row, so the right backend is interrupted
- # even if the Chat header swapped the session's agent / model mid-turn.
- # Record the no-flush intent BEFORE awaiting the interrupt: if the
- # backend stop lets the turn settle normally during the await (no
- # CancelledError), _run_turn's finally would otherwise treat it as a
- # natural completion and flush the queue — but a plain Stop keeps the
- # queue (Codex P2).
- stop_no_flush.add(session_id)
- stopped = False
- try:
- stopped = bool(await controller.command_handler.handle_stop(turn_context))
- except Exception:
- logger.exception("internal cancel: backend stop failed for session=%s", session_id)
- if not stopped:
- # Stop refused — the turn keeps running, so it isn't being stopped;
- # drop the no-flush marker so a later natural completion flushes
- # normally.
- stop_no_flush.discard(session_id)
- # The backend couldn't interrupt this turn (no interruptible active
- # session). Don't cancel the waiter — that would fire a false
- # ``turn.end``, hide Stop, and let follow-up work start while the turn
- # is still producing output. Keep it cancellable; it ends naturally
- # when the backend finishes (Codex P2).
- return JSONResponse(
- status_code=409,
- content={"ok": False, "code": "stop_failed", "session_id": session_id},
- )
- task.cancel()
- return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
+ """HTTP adapter: delegate Stop to the turn owner (FSM, Phase 1b) and map its
+ result ``code`` to a status — ``not_in_flight`` -> 404, ``stop_failed`` ->
+ 409. ``session_id`` is the dispatch key the turn registered under, so the UI
+ Stop button works with just the URL it already has."""
+ result = await manager.cancel(session_id)
+ code = result.get("code")
+ if code == "not_in_flight":
+ return JSONResponse(status_code=404, content=result)
+ if code == "stop_failed":
+ return JSONResponse(status_code=409, content=result)
+ return result
@app.post("/internal/send-now/{session_id}")
async def _send_now(session_id: str) -> Any:
- """Run the session's send-while-busy queue immediately ("立即发送").
-
- If a turn is running, interrupt it (the user explicitly chose to cut in)
- and opt into ``flush_on_cancel`` so the queue runs as soon as that turn
- unwinds. If nothing is running (e.g. after a Stop left the queue intact),
- flush directly as a fresh turn. No-op when the queue is empty.
- """
- entry = in_flight.get(session_id)
- if entry is not None and not entry[0].done():
- # Don't interrupt a live turn unless there is actually something queued
- # to cut in with — a stale queue item already flushed/removed by
- # another tab would otherwise make send-now an unintended Stop (Codex
- # P2). Report ``empty`` and leave the running turn alone.
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- engine = create_sqlite_engine()
- with engine.connect() as conn:
- has_queue = bool(messages_service.list_queued(conn, session_id))
- if not has_queue:
- return {"ok": True, "session_id": session_id, "status": "empty"}
- _task, turn_context = entry
- # Record the flush intent BEFORE awaiting the interrupt: if the stop
- # lets the turn settle normally during the await, _run_turn's finally
- # consumes the flag and flushes (send-now WANTS the queue to run).
- # Adding it afterwards would either be too late (the finished turn
- # already discarded nothing) or leave a STALE flag that makes a later
- # plain Stop wrongly flush (Codex P2). On a refused/failed stop we
- # drop it again and leave the turn + queue untouched.
- flush_on_cancel.add(session_id)
- stopped = False
- try:
- stopped = bool(await controller.command_handler.handle_stop(turn_context))
- except Exception:
- logger.exception("internal send-now: backend stop failed for session=%s", session_id)
- if not stopped:
- flush_on_cancel.discard(session_id)
- return JSONResponse(
- status_code=409,
- content={"ok": False, "code": "stop_failed", "session_id": session_id},
- )
- _task.cancel()
- return {"ok": True, "session_id": session_id, "status": "interrupted"}
- # No running turn — flush the queue directly as a new turn (it rebuilds
- # the routing context from the current session row internally). Report
- # ``empty`` when there was nothing to flush (a stale queue item already
- # gone) so the client clears its optimistic working state instead of
- # waiting for a turn that never starts (Codex P2).
- flushed = await _flush_queue(session_id)
- return {"ok": True, "session_id": session_id, "status": "flushed" if flushed else "empty"}
+ """HTTP adapter: delegate "立即发送" (run the send-while-busy queue now) to
+ the turn owner (FSM, Phase 1b); ``stop_failed`` -> 409."""
+ result = await manager.send_now(session_id)
+ if result.get("code") == "stop_failed":
+ return JSONResponse(status_code=409, content=result)
+ return result
# Expose the per-session turn gate to in-process callers (the scheduler)
# WITHOUT going through the HTTP surface: ``ScheduledTaskService`` runs on the
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 208858f5c..e3b5a36d8 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -15,6 +15,7 @@ from config.platform_registry import get_platform_descriptor
from modules.im import MessageContext
from core.message_mirror import persist_agent_message
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
+from core.session_turns import emit_matches_active_turn
from storage.background import SQLiteBackgroundTaskStore
from vibe.i18n import t as i18n_t
@@ -70,9 +71,7 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[
# complete it — a different OR absent token is stale. Fail-open only when the
# sink itself is tokenless. The reused-receiver Claude case keeps completing
# because its result emit adopts the live turn's token (see ClaudeAgent).
- sink_token = sink.get("turn_token")
- ctx_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
- if sink_token is not None and ctx_token != sink_token:
+ if not emit_matches_active_turn(sink, context):
return
done = sink.get("done_event")
if done is not None:
@@ -120,34 +119,6 @@ class ConsolidatedMessageDispatcher:
if callable(mark):
mark(context)
- def _is_active_turn(self, context: MessageContext) -> bool:
- """True unless this emit belongs to a SUPERSEDED turn. A late result from a
- stopped / timed-out / older turn (after the user already started a new
- interactive turn in the same session) must not settle the dot for the new
- turn. Fail-open when there is no live sink (no interactive turn in flight),
- when the SINK has no token (nothing to be superseded by), or for controllers
- without the sink registry (test stubs)."""
- get_sink = getattr(self.controller, "get_turn_sink", None)
- if not callable(get_sink):
- return True
- try:
- sink = get_sink(self._get_session_key(context))
- except Exception:
- return True
- if sink is None:
- return True
- sink_token = sink.get("turn_token")
- ctx_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
- # A live sink WITH a token means an interactive turn is in flight; only its
- # OWN result (matching token) may settle the session status. A result whose
- # token differs OR is ABSENT is stale — notably an older scheduled/watch run
- # that finishes mid-interactive-turn carries no ``turn_token``, and must not
- # flip the live turn's dot back to idle/failed. (Fail-open only when the sink
- # itself is tokenless, so non-streaming turns still settle.)
- if sink_token is not None and ctx_token != sink_token:
- return False
- return True
-
def _t(self, key: str, **kwargs) -> str:
translator = getattr(self.controller, "_t", None)
if callable(translator):
@@ -458,13 +429,13 @@ class ConsolidatedMessageDispatcher:
# ``getattr`` keeps it a no-op for controllers without the hook (mirrors
# ``_signal_turn_complete``).
if canonical_type == "result":
- resolve_session = getattr(self.controller, "_session_id_from_context", None)
- status_session_id = resolve_session(context) if callable(resolve_session) else None
- # Only settle the dot for the ACTIVE turn: a late result from a
- # stopped/superseded turn (after the user started a new turn in the
- # same session) must not flip the new turn's ``running`` to idle/failed.
- if status_session_id and self._is_active_turn(context):
- self.controller.set_agent_status(status_session_id, "failed" if is_error else "idle")
+ # Settle the avibe dot for the ACTIVE turn's terminal result (idle, or
+ # failed on is_error) via the turn owner, which applies the active-turn
+ # guard + skips non-avibe contexts. ``getattr`` keeps it a no-op for stub
+ # controllers without the owner.
+ manager = getattr(self.controller, "session_turns", None)
+ if manager is not None:
+ manager.on_terminal_result(context, is_error=is_error)
text = strip_silent_blocks(text)
# ``level="silent"`` is the explicit visibility control (orthogonal to type):
# the message already settled the dot above (for a terminal result), so here
diff --git a/core/session_turns.py b/core/session_turns.py
new file mode 100644
index 000000000..f1fe2ebfc
--- /dev/null
+++ b/core/session_turns.py
@@ -0,0 +1,462 @@
+"""Per-session turn ownership for the avibe workbench.
+
+Phase 1b of the turn-lifecycle FSM (``docs/plans/avibe-turn-lifecycle-fsm.md``):
+introduce ONE owner of a session's turn state so the gate, dispatcher, scheduler,
+and restore paths stop reconciling several separate stores. A session has **at
+most one active turn** (IDLE ↔ RUNNING; no turn-duration timeout — a long agent
+runs until it emits its terminal result or the user Stops it).
+
+``SessionTurnManager`` is wired as ``controller.session_turns`` by
+``core.internal_server.create_app``. It owns the in_flight registry + the
+flush-intent sets, and the turn lifecycle: ``submit`` (start + hold-open) and
+``flush_queue`` (drain the send-while-busy queue). The internal-server HTTP
+handlers and the scheduler are thin callers. Cancel / send-now / turn-state /
+terminal-result move onto the manager in subsequent commits.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import TYPE_CHECKING, Any, Callable, Optional
+
+from core.services.dispatch import SOURCE_HUMAN, dispatch_turn
+
+if TYPE_CHECKING:
+ from modules.im import MessageContext
+
+logger = logging.getLogger(__name__)
+
+
+def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:
+ """The ONE active-turn token rule (FSM Phase 2 — collapses the three previously
+ duplicated guards: ``_stream_chunk`` completion, ``_is_active_turn``, and
+ ``Controller.mark_turn_complete``).
+
+ A live sink WITH a token means an interactive turn is in flight; only its OWN
+ result (matching token) is the active turn's. A result whose token DIFFERS or is
+ ABSENT is stale — a superseded / stopped / older turn, or a scheduled / watch run
+ that carries no token — and must NOT complete the turn (set ``done_event``) or
+ settle its dot. Fail-open when the sink itself is tokenless, so non-streaming
+ turns still settle. (Chunk FORWARDING is deliberately NOT gated — see
+ ``_stream_chunk``; only COMPLETION + dot-settle are.)
+
+ NOTE (no-timeout invariant): with the turn-duration timeout gone, a turn whose
+ OWN terminal result is tokenless would hang here forever. The FSM therefore must
+ guarantee every terminal result carries the active turn's token (Claude adoption
+ / FSM-attached token); this guard is intentionally strict.
+ """
+ sink_token = sink.get("turn_token")
+ ctx_token = (getattr(context, "platform_specific", None) or {}).get("turn_token")
+ return not (sink_token is not None and ctx_token != sink_token)
+
+
+class SessionTurnManager:
+ """Owns the live per-session turn state + lifecycle for avibe sessions.
+
+ Containers (the same shapes the gate used inline):
+
+ - ``in_flight``: ``session_id -> (task, context)`` for the active turn. It is
+ the Stop target (``/internal/cancel``), the ``/turn-state`` source, and the
+ trigger for draining the send-while-busy queue. The stored ``MessageContext``
+ is the one the turn STARTED under, so Stop interrupts the backend the turn
+ actually ran on even if the Chat header later changed agent/model.
+ - ``flush_on_cancel``: sessions whose queue should flush even though the turn is
+ ending via cancellation — ``send-now`` cancels the running turn but wants the
+ queue to run immediately after. A plain Stop keeps the queue ("不清空队列").
+ - ``stop_no_flush``: sessions being stopped by a plain Stop that must NOT flush,
+ even if the backend interrupt lets the turn settle normally (no
+ ``CancelledError``) during the awaited stop.
+
+ ``controller`` reaches the backends + the outbound chokepoint
+ (``emit_agent_message``); ``build_context`` rebuilds a session's routing
+ ``MessageContext`` for a queued follow-up (injected by the gate because it
+ lives in ``internal_server``).
+ """
+
+ def __init__(
+ self,
+ controller: Any = None,
+ *,
+ build_context: Optional[Callable[[str], "MessageContext"]] = None,
+ ) -> None:
+ self.controller = controller
+ self._build_context = build_context
+ self.in_flight: dict[str, tuple[asyncio.Task, "MessageContext"]] = {}
+ self.flush_on_cancel: set[str] = set()
+ self.stop_no_flush: set[str] = set()
+
+ def is_in_flight(self, session_id: Optional[str]) -> bool:
+ """True when ``session_id`` has an active (RUNNING) turn."""
+ return bool(session_id) and session_id in self.in_flight
+
+ def bind_context(self, build_context: Callable[[str], "MessageContext"]) -> None:
+ """Inject the routing-context builder (it lives in ``internal_server``) once
+ the gate is built, so ``flush_queue`` can rebuild a queued follow-up's
+ routing from the current session row."""
+ self._build_context = build_context
+
+ @staticmethod
+ async def _noop_chunk(_envelope: dict) -> None:
+ # Chunks are discarded — the browser renders from ``message.new``.
+ return None
+
+ async def submit(
+ self,
+ session_id: Optional[str],
+ context: "MessageContext",
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ enqueue: Optional[Callable[[], None]] = None,
+ ) -> str:
+ """Unified turn entry for BOTH Chat and the scheduler: idle → run now; busy
+ (or a pre-existing send-while-busy queue) → enqueue and run later.
+
+ Returns ``"ran"`` or ``"enqueued"``. The busy / pre-existing-queue decision,
+ the idle-with-queue drain, and the run are unified here; the caller supplies
+ ``enqueue`` — a 0-arg callable that persists the SOURCE-specific queued row
+ (Chat promotes its pre-saved pending row; the scheduler appends a harness
+ row) — because that row's shape depends on the request. The in_flight check
+ and the enqueue have no ``await`` between them (single-threaded loop), so a
+ running turn cannot end + flush in the gap — the enqueue stays atomic.
+ """
+ if not (isinstance(session_id, str) and session_id):
+ # No session key (CLI-style) — just run; nothing to queue against.
+ await self._run(None, context, text, source=source)
+ return "ran"
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ entry = self.in_flight.get(session_id)
+ busy = entry is not None and not entry[0].done()
+ # Enqueue when a turn is running OR a prior Stop left queued rows behind — the
+ # new message must run AFTER them, not jump ahead (Codex P2).
+ if busy:
+ should_enqueue = True
+ else:
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ should_enqueue = bool(messages_service.list_queued(conn, session_id))
+ if should_enqueue:
+ if enqueue is not None:
+ enqueue()
+ # Idle + pre-existing queue → no running turn to flush behind, so drain
+ # the whole queue (this row included) now, in order.
+ if not busy:
+ await self.flush_queue(session_id)
+ return "enqueued"
+ await self._run(session_id, context, text, source=source)
+ return "ran"
+
+ async def _run(
+ self,
+ session_id: Optional[str],
+ context: "MessageContext",
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ ) -> None:
+ """Start a fire-and-forget turn and HOLD it open until it settles.
+
+ A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime so
+ ``in_flight`` stays populated (Stop works) and the session-level
+ ``turn.start`` / ``turn.end`` lifecycle is published for the browser's
+ working indicator. On NATURAL completion the queue is flushed: messages the
+ user sent while this turn ran are merged + run as the next turn. A user Stop
+ (cancellation) does NOT flush — the queue is kept per the user's "don't
+ clear the queue on stop" rule — unless ``send-now`` opted this session into
+ ``flush_on_cancel``. The reply reaches the browser over ``message.new``.
+
+ ``source`` selects the human vs. scheduler turn path in ``dispatch_turn``;
+ a scheduled / watch run passes ``SOURCE_SCHEDULED`` so it goes through the
+ SAME gate (in_flight + turn.start/turn.end + queue draining) as a Chat turn.
+ There is NO turn-duration timeout: a long agent runs for hours and is freed
+ only by a real terminal signal (Phase 1a — STUCK/sentinel removed).
+ """
+ from core.inbox_events import bus
+
+ async def _runner() -> None:
+ cancelled = False
+ failed = False
+ try:
+ await dispatch_turn(
+ self.controller,
+ context,
+ text,
+ source=source,
+ # ALWAYS pass the no-op sink — even for scheduled runs. It isn't
+ # about the browser (chunks are discarded; avibe renders from
+ # message.new); it makes ``dispatch_turn`` HOLD the turn open
+ # until the backend's terminal result, keeping ``in_flight``
+ # populated for the turn's whole lifetime. With ``on_chunk=None``
+ # an async backend (Codex/Claude) returns at prompt-submit, so the
+ # slot would free + a Chat send could preempt the still-running
+ # scheduled turn (Codex P2).
+ on_chunk=self._noop_chunk,
+ )
+ except asyncio.CancelledError:
+ cancelled = True
+ raise
+ except Exception:
+ # dispatch_turn raised before any backend turn was actually
+ # dispatched (missing/disabled backend, synchronous setup error).
+ # No agent reply was produced, so this is a terminal FAILURE — it must
+ # NOT auto-flush the send-while-busy queue onto a fresh turn (Codex
+ # P2). (An explicit send-now flush_on_cancel still flushes.)
+ failed = True
+ logger.exception("internal async dispatch failed for session=%s", session_id)
+ finally:
+ if isinstance(session_id, str):
+ # The turn is over — the agent emitted its terminal result, the
+ # user stopped it, or dispatch raised before any backend turn.
+ # NO turn-duration timeout: the slot is freed only by a real
+ # terminal signal here (Phase 1a — STUCK/sentinel removed).
+ self.in_flight.pop(session_id, None)
+ bus.publish("turn.end", {"session_id": session_id})
+ # Converge the no-terminal-result outcome onto the OUTBOUND status
+ # chokepoint. The normal path already emitted a terminal result;
+ # only ``failed`` reaches here without one: dispatch raised before
+ # any backend turn (missing/disabled backend) → empty error result
+ # → dot red. This is a real terminal FAILURE, not a timeout.
+ if failed:
+ await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ # Don't flush after a Stop (keep the queue) or a terminal failure.
+ # send-now still forces a flush via flush_on_cancel.
+ should_flush = (
+ (not cancelled and not failed and session_id not in self.stop_no_flush)
+ or (session_id in self.flush_on_cancel)
+ )
+ self.flush_on_cancel.discard(session_id)
+ self.stop_no_flush.discard(session_id)
+ if should_flush:
+ await self.flush_queue(session_id)
+
+ task = asyncio.create_task(_runner(), name="internal-dispatch-async")
+ if isinstance(session_id, str) and session_id:
+ self.in_flight[session_id] = (task, context)
+ bus.publish("turn.start", {"session_id": session_id})
+
+ async def flush_queue(self, session_id: str) -> bool:
+ """Pop the messages queued while a turn ran, merge them into one
+ (newline-joined) user message, and run it as the next turn — recursively
+ draining the queue. Returns True if a turn was started, False on an empty
+ queue / failure (so ``send-now`` can report idle instead of leaving the
+ client stuck waiting). The merge is the user's choice (one dispatch, not N);
+ the individual queued rows are deleted by ``pop_queued`` and replaced by the
+ single merged user row."""
+ from core.inbox_events import bus
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ if not session_id:
+ return False
+ user_row = None
+ inbox_row = None
+ try:
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ rows = messages_service.pop_queued(conn, session_id)
+ texts = [r.get("text") for r in rows if (r.get("text") or "").strip()]
+ if not texts:
+ return False
+ user_row = messages_service.append(
+ conn,
+ scope_id=rows[0]["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="\n".join(texts),
+ )
+ inbox_row = messages_service.get_inbox_session(conn, session_id)
+ except Exception:
+ logger.exception("queue flush: failed to pop/merge for session=%s", session_id)
+ return False
+ if user_row is None:
+ return False
+ # Surface the flushed (merged) user message, bump the inbox card (so other
+ # workbench views re-rank + flip 'replied' without waiting for the next
+ # result — Codex P2), and mark the queue empty.
+ bus.publish("message.new", user_row)
+ if inbox_row is not None:
+ bus.publish("inbox.session.updated", inbox_row)
+ bus.publish("queue.updated", {"session_id": session_id})
+ # Rebuild routing from the CURRENT session row so a queued follow-up uses the
+ # session's latest agent / model / effort — the user may have changed it while
+ # the prior (now-finished) turn was running (Codex P2).
+ if self._build_context is None:
+ logger.error("queue flush: no build_context bound for session=%s", session_id)
+ return False
+ try:
+ context = self._build_context(session_id)
+ except Exception:
+ logger.exception("queue flush: failed to build context for session=%s", session_id)
+ return False
+ await self._run(session_id, context, user_row.get("text") or "")
+ return True
+
+ def turn_state(self, session_id: str) -> dict:
+ """Whether a turn is currently RUNNING for the session. The fire-and-forget
+ dispatch survives browser disconnects, so a freshly loaded / reconnected
+ Chat page asks this to restore its working / Stop state (Codex P2)."""
+ entry = self.in_flight.get(session_id)
+ active = entry is not None and not entry[0].done()
+ return {"ok": True, "session_id": session_id, "in_flight": active}
+
+ async def cancel(self, session_id: str) -> dict:
+ """Stop the active turn: interrupt the agent's backend run via the SAME path
+ the IM ``/stop`` command uses (Claude interrupt / Codex turn-interrupt /
+ OpenCode abort) — not just the waiter — keeping the send-while-busy queue
+ ("不清空"). Returns a result dict; ``code`` is ``not_in_flight`` /
+ ``stop_failed`` for the HTTP adapter to map to 404 / 409, else a 200 status.
+ """
+ entry = self.in_flight.get(session_id)
+ if entry is None:
+ return {"ok": False, "code": "not_in_flight", "session_id": session_id}
+ task, turn_context = entry
+ if task.done():
+ return {"ok": True, "session_id": session_id, "status": "already_finished"}
+ # Record the no-flush intent BEFORE awaiting the interrupt: if the backend
+ # stop lets the turn settle normally during the await (no CancelledError),
+ # submit()'s finally would otherwise treat it as a natural completion and
+ # flush — but a plain Stop keeps the queue (Codex P2). We pass the context the
+ # turn STARTED under so the right backend is interrupted even if the Chat
+ # header swapped the session's agent / model mid-turn.
+ self.stop_no_flush.add(session_id)
+ stopped = False
+ try:
+ stopped = bool(await self.controller.command_handler.handle_stop(turn_context))
+ except Exception:
+ logger.exception("internal cancel: backend stop failed for session=%s", session_id)
+ if not stopped:
+ # Stop refused — the turn keeps running, so it isn't being stopped; drop
+ # the no-flush marker so a later natural completion flushes normally.
+ # Don't cancel the waiter — that would fire a false ``turn.end``, hide
+ # Stop, and let follow-up work start while the turn still produces output
+ # (Codex P2).
+ self.stop_no_flush.discard(session_id)
+ return {"ok": False, "code": "stop_failed", "session_id": session_id}
+ task.cancel()
+ return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
+
+ async def send_now(self, session_id: str) -> dict:
+ """Run the session's send-while-busy queue immediately ("立即发送").
+
+ If a turn is running (and something is queued), interrupt it (the user chose
+ to cut in) and opt into ``flush_on_cancel`` so the queue runs as that turn
+ unwinds. If nothing is running, flush directly as a fresh turn. No-op when
+ the queue is empty. Returns a result dict (``code='stop_failed'`` → 409 for
+ the HTTP adapter).
+ """
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ entry = self.in_flight.get(session_id)
+ if entry is not None and not entry[0].done():
+ # Don't interrupt a live turn unless there is actually something queued to
+ # cut in with — a stale queue item already flushed by another tab would
+ # otherwise make send-now an unintended Stop (Codex P2).
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ has_queue = bool(messages_service.list_queued(conn, session_id))
+ if not has_queue:
+ return {"ok": True, "session_id": session_id, "status": "empty"}
+ _task, turn_context = entry
+ # Record the flush intent BEFORE awaiting the interrupt (same race as
+ # cancel, opposite intent: send-now WANTS the queue to run). Drop it on a
+ # refused stop and leave the turn + queue untouched (Codex P2).
+ self.flush_on_cancel.add(session_id)
+ stopped = False
+ try:
+ stopped = bool(await self.controller.command_handler.handle_stop(turn_context))
+ except Exception:
+ logger.exception("internal send-now: backend stop failed for session=%s", session_id)
+ if not stopped:
+ self.flush_on_cancel.discard(session_id)
+ return {"ok": False, "code": "stop_failed", "session_id": session_id}
+ _task.cancel()
+ return {"ok": True, "session_id": session_id, "status": "interrupted"}
+ # No running turn — flush the queue directly as a new turn (rebuilds routing
+ # from the current session row internally). ``empty`` when nothing flushed.
+ flushed = await self.flush_queue(session_id)
+ return {"ok": True, "session_id": session_id, "status": "flushed" if flushed else "empty"}
+
+ # --- the two status chokepoints (the dot is a projection of the turn) ---------
+
+ def on_running(self, context: "MessageContext") -> None:
+ """INBOUND status chokepoint: mark the avibe session ``running`` when a turn
+ starts (every source / backend funnels through AgentService.handle_message).
+ Non-avibe turns carry no workbench session id and are skipped."""
+ if self.controller is None:
+ return
+ session_id = self.controller._session_id_from_context(context)
+ if session_id:
+ self.controller.set_agent_status(session_id, "running")
+
+ def on_terminal_result(self, context: "MessageContext", *, is_error: bool) -> None:
+ """OUTBOUND status chokepoint: settle the avibe dot when the ACTIVE turn's
+ terminal ``result`` is emitted — ``idle`` normally, ``failed`` on
+ ``is_error``. A late result from a superseded / stopped turn (the active-turn
+ guard) or a non-avibe context (no session id) is skipped, so it can't flip a
+ newer turn's ``running`` back."""
+ if self.controller is None:
+ return
+ session_id = self.controller._session_id_from_context(context)
+ if not session_id or not self.is_active_emit(context):
+ return
+ self.controller.set_agent_status(session_id, "failed" if is_error else "idle")
+
+ def is_active_emit(self, context: "MessageContext") -> bool:
+ """Whether an emit belongs to the live turn (not a superseded one). Fail-open
+ when there's no sink registry / no live sink (non-streaming turns still
+ 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)
+ if not callable(get_sink) or not callable(get_key):
+ return True
+ try:
+ sink = get_sink(get_key(context))
+ except Exception:
+ return True
+ if sink is None:
+ return True
+ return emit_matches_active_turn(sink, context)
+
+ # --- boot / restore edge transitions -----------------------------------------
+
+ @staticmethod
+ def reset_stale() -> None:
+ """Crash recovery (boot): no turn survives a restart, so any avibe session
+ left ``running`` in the table is stale → reset it to ``idle`` so the sidebar
+ dot doesn't show a phantom green forever. Runs in ``Controller.__init__``
+ BEFORE any ``/internal/events`` subscriber exists, so it does NOT broadcast
+ ``session.status`` (the bus drops events with no subscribers); the browser
+ reconciles by refetching sessions when its inbox stream (re)connects."""
+ try:
+ from core.services import sessions as workbench_sessions_service
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine()
+ try:
+ with engine.begin() as conn:
+ reset = workbench_sessions_service.reset_running_agent_status(conn)
+ finally:
+ engine.dispose()
+ if reset:
+ logger.info("Reset %s stale 'running' agent session(s) to idle on startup", reset)
+ except Exception:
+ logger.debug("agent_status startup reset failed", exc_info=True)
+
+ def restore_running(self, session_id: Optional[str]) -> None:
+ """Re-mark an avibe session ``running`` when its OpenCode poll is restored
+ after a restart: the restored poll resumes the backend turn WITHOUT
+ re-entering the inbound chokepoint (``handle_message``), so without this the
+ dot would read idle for a still-live turn until the poll's terminal result
+ settles it back. IM polls carry no workbench session id, so they pass nothing
+ here and stay dot-less."""
+ if session_id and self.controller is not None:
+ self.controller.set_agent_status(session_id, "running")
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 7bc8057a3..a2af17ab3 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -532,17 +532,18 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})"
)
- # Re-mark the avibe workbench session ``running``. ``_reset_stale_agent_status``
- # flips every ``running`` row to ``idle`` on startup, but a restored poll
- # resumes the backend turn WITHOUT re-entering ``AgentService.handle_message``
- # (the inbound status chokepoint), so without this the sidebar dot would show
- # idle/gray for a turn that is still live until it settles. The outbound
- # chokepoint (the poll loop's terminal result) settles it back to idle/failed,
- # so only the ``running`` flip is missing here (Codex P2). IM polls carry no
- # workbench session id, so they are unaffected — only avibe sessions get a dot.
+ # Re-mark the avibe workbench session ``running`` via the turn owner (FSM).
+ # ``SessionTurnManager.reset_stale`` flips every ``running`` row to ``idle``
+ # on startup, but a restored poll resumes the backend turn WITHOUT
+ # re-entering ``AgentService.handle_message`` (the inbound status
+ # chokepoint), so without this the sidebar dot would show idle/gray for a
+ # turn that is still live until it settles. The outbound chokepoint (the
+ # poll loop's terminal result) settles it back to idle/failed, so only the
+ # ``running`` flip is missing here (Codex P2). IM polls carry no workbench
+ # session id, so they are unaffected — only avibe sessions get a dot.
workbench_session_id = self._workbench_session_id_for_poll(poll_info)
if workbench_session_id:
- self.controller.set_agent_status(workbench_session_id, "running")
+ self.controller.session_turns.restore_running(workbench_session_id)
task = asyncio.create_task(self._run_restored_poll_loop_with_tracking(poll_info))
self._active_requests[poll_info.base_session_id] = task
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 83b20f431..340c3b363 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -32,9 +32,9 @@ class AgentService:
# single place that marks an avibe session "running". The matching idle /
# failed is written by the outbound terminal result. Non-avibe turns carry
# no workbench session id and are skipped.
- session_id = self.controller._session_id_from_context(request.context)
- if session_id:
- self.controller.set_agent_status(session_id, "running")
+ manager = getattr(self.controller, "session_turns", None)
+ if manager is not None:
+ manager.on_running(request.context)
await agent.handle_message(request)
async def clear_sessions(self, session_key: str) -> Dict[str, int]:
diff --git a/tests/test_controller_agent_status.py b/tests/test_controller_agent_status.py
index 00f160484..447ad850d 100644
--- a/tests/test_controller_agent_status.py
+++ b/tests/test_controller_agent_status.py
@@ -43,6 +43,11 @@ def _service_with_capture():
_session_id_from_context=staticmethod(Controller._session_id_from_context).__func__,
set_agent_status=lambda sid, status: calls.append((sid, status)),
)
+ # The inbound chokepoint now marks running via the turn owner (FSM); wire a real
+ # one so on_running reaches this stub's set_agent_status recorder.
+ from core.session_turns import SessionTurnManager
+
+ controller.session_turns = SessionTurnManager(controller)
service = AgentService(controller)
return service, calls
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 9566bb95d..cea5d7604 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -24,7 +24,7 @@ import httpx
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from core import internal_server
+from core import internal_server, session_turns
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
from modules.im import MessageContext
@@ -362,7 +362,7 @@ def test_dispatch_async_no_terminal_result_keeps_session_in_flight(monkeypatch,
started.set()
await asyncio.sleep(60)
- monkeypatch.setattr(internal_server, "dispatch_turn", _never_settles)
+ monkeypatch.setattr(session_turns, "dispatch_turn", _never_settles)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -671,7 +671,7 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
captured["in_flight_while_running"] = "ses_sched" in app.state.in_flight_dispatches
started.set()
- monkeypatch.setattr(internal_server, "dispatch_turn", _fake_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn", _fake_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -739,7 +739,7 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
async def _explode_dispatch_turn(*args, **kwargs):
raise AssertionError("a busy scheduled run must enqueue, not dispatch a turn")
- monkeypatch.setattr(internal_server, "dispatch_turn", _explode_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn", _explode_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -802,7 +802,7 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):
started.set()
await asyncio.sleep(5) # held until the test cancels it
- monkeypatch.setattr(internal_server, "dispatch_turn", _long_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn", _long_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index d89b2fa5b..b69af4c20 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -288,6 +288,11 @@ class _AvibeStatusController(_StubController):
super().__init__(platform="avibe")
self.status_calls = []
self.active_sink = None # set to {"turn_token": ...} to simulate a live turn
+ from core.session_turns import SessionTurnManager
+
+ # The dot now settles via the turn owner (FSM); wire a real one so its
+ # on_terminal_result reaches this stub's set_agent_status recorder.
+ self.session_turns = SessionTurnManager(self)
@staticmethod
def _session_id_from_context(context):
diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.py
index 7e68bc788..40927f059 100644
--- a/tests/test_opencode_restore_polls.py
+++ b/tests/test_opencode_restore_polls.py
@@ -76,6 +76,13 @@ def _build_agent(active_polls: dict[str, ActivePollInfo]):
removed.append(session_id)
class _Controller:
+ def __init__(self):
+ from core.session_turns import SessionTurnManager
+
+ # The restore path re-marks running via the turn owner, which delegates
+ # to set_agent_status — wire a real manager so the full path is exercised.
+ self.session_turns = SessionTurnManager(self)
+
def set_agent_status(self, session_id, status):
status_writes.append((session_id, status))