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(workbench): message filtering, session-status dot, and scheduled tasks on avibe (#367)
Call White2c88c7be5368
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 2744adac5..381dfd255 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -747,7 +747,15 @@ class AgentAuthService:return Falseasync def maybe_emit_auth_recovery_message(self, context: MessageContext, backend: str, error_text: str) -> bool:- """Emit a reset-oauth button when the backend error is auth-related."""+ """Emit a reset-oauth button when the backend error is auth-related.++ Each backend error-emit site calls this FIRST and emits its own terminal+ error result only when this returns ``False``. When this DOES handle the+ error (auth-related), the recovery message is a button row (not a result),+ so settle the turn through the outbound chokepoint here by emitting a+ terminal ``error`` result — that turns the workbench dot red and releases+ the SSE waiter. No-op off-workbench (the outbound resolves no session id).+ """if not classify_auth_error(backend, error_text):return False@@ -764,12 +772,27 @@ class AgentAuthService:# home for it, rather than each backend persisting an error-only copy that# drops the actionable reset prompt (Codex P2). No-op for contexts without# a resolvable scope (persist_agent_message guards internally).+ #+ # The durable row has NO inline button, so persist a BUTTON-FREE variant:+ # ``resetPrompt`` says "use the button below", which is a dangling+ # instruction on the workbench Chat. Point at the cross-platform+ # ``/setup {backend}`` command instead so the persisted copy is actionable+ # everywhere (Codex P2).+ durable_text = f"{error_text}\n\n{self._t('command.setup.resetPromptPlain', backend=backend)}"try:from core.message_mirror import persist_agent_message- persist_agent_message(context, "notify", recovery_text)+ persist_agent_message(context, "notify", durable_text)except Exception:logger.debug("auth recovery: failed to persist durable notify", exc_info=True)+ # Settle the failed turn through the outbound status chokepoint: an empty+ # terminal ``error`` result turns the dot red and releases the SSE waiter+ # without adding a second visible message (the recovery button above is the+ # visible one). No-op off-workbench.+ try:+ await self.controller.emit_agent_message(context, "result", "", is_error=True)+ except Exception:+ logger.debug("auth recovery: failed to settle turn status", exc_info=True)return Trueasync def _send_message(self, context: MessageContext, text: str) -> Optional[str]:diff --git a/core/controller.py b/core/controller.pyindex a3dfee4ab..d1fcba1e8 100644--- a/core/controller.py+++ b/core/controller.py@@ -66,6 +66,14 @@ class Controller:# resolve the current turn's sink. Empty for IM/CLI turns.self.active_turn_sinks: Dict[str, Dict[str, Any]] = {}+ # Per-session turn gate, published by ``core.internal_server.create_app``+ # once the internal server is built on the loop. The scheduler routes+ # avibe scheduled / watch turns through it so they QUEUE behind an active+ # Chat turn (never preempt it) and get the Chat path's turn lifecycle+ # (in_flight + turn.start / turn.end + Stop). ``None`` until the server is+ # up — callers must treat its absence as "fall back to the direct path".+ self.session_turn_gate: Optional[Any] = None+# Initialize core modulesself._init_modules()@@ -105,6 +113,11 @@ class Controller:# Restore session mappings on startup (after handlers are initialized)self.session_handler.restore_session_mappings()+ # 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()+def _init_modules(self):"""Initialize core modules"""self.im_clients: Dict[str, BaseIMClient] = IMFactory.create_clients(self.config)@@ -616,17 +629,94 @@ class Controller:sink = self.get_turn_sink(self._get_session_key(context))if sink is None:return- # Turn-token guard (mirrors ``_stream_chunk``): a SUPERSEDED turn ending- # (e.g. a stopped turn whose backend later fires turn/completed) must not- # close the CURRENT turn's stream. Fail-open when either token is absent.+ # 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 is not None and sink_token != ctx_token:+ if sink_token is not None and ctx_token != sink_token:returndone = sink.get("done_event")if done is not None:done.set()+ # ----- Live agent-runtime status (workbench sidebar dot) -------------+ #+ # ``agent_sessions.agent_status`` is idle/running/failed, written at EXACTLY+ # two chokepoints every turn funnels through — no per-path / per-backend+ # instrumentation:+ # * inbound — ``AgentService.handle_message`` flips the session to+ # ``running`` (every source/backend dispatches through it).+ # * outbound — ``MessageDispatcher.emit_agent_message`` settles the terminal+ # ``result`` to ``idle`` (or ``failed`` when ``is_error``).+ # 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+ # startup (a turn whose process died never reached the outbound chokepoint).++ @staticmethod+ def _session_id_from_context(context: Optional[MessageContext]) -> Optional[str]:+ spec = getattr(context, "platform_specific", None) or {}+ sid = spec.get("agent_session_id")+ return sid if isinstance(sid, str) and sid else None++ def set_agent_status(self, session_id: Optional[str], status: str) -> None:+ """Persist a session's agent_status and broadcast ``session.status``.++ Best-effort + idempotent: a no-op when the value is unchanged (the+ service reports it), when ``session_id`` is empty, or when the DB write+ fails. The realtime event rides the same controller→browser bus as+ ``turn.start`` / ``turn.end`` so the sidebar dot updates without a refetch.+ """++ if not session_id:+ return+ 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:+ changed = workbench_sessions_service.set_agent_status(conn, session_id, status)+ finally:+ # Dispose the per-turn engine promptly: this fires on every+ # workbench turn start/end, so leaking it would pin SQLite+ # connections/FDs until GC under active Chat use (Codex P3).+ engine.dispose()+ if changed:+ from core.inbox_events import bus++ bus.publish("session.status", {"session_id": session_id, "agent_status": status})+ 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]@@ -748,6 +838,9 @@ class Controller:message_type: str,text: str,parse_mode: Optional[str] = "markdown",+ *,+ is_error: bool = False,+ level: str = "normal",):"""Backward-compatible entrypoint; delegated to message dispatcher."""return await self.message_dispatcher.emit_agent_message(@@ -755,6 +848,8 @@ class Controller:message_type=message_type,text=text,parse_mode=parse_mode,+ is_error=is_error,+ level=level,)# Main run methoddiff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 65c28d30f..972c65dd5 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -404,6 +404,11 @@ class MessageHandler(BaseHandler):agent_dispatched = Trueexcept KeyError:await self._handle_missing_agent(context, agent_name)+ # Synchronous terminal failure (no agent dispatched). Settle the+ # turn through the OUTBOUND status chokepoint: an empty terminal+ # error result turns the dot red + releases the SSE waiter (the+ # missing-agent message was already shown above). No separate latch.+ await self.controller.emit_agent_message(context, "result", "", is_error=True)# Clean up reaction on errorawait self._remove_ack_reaction(context, request)return f"agent '{agent_name}' is not available"@@ -427,9 +432,12 @@ class MessageHandler(BaseHandler):logger.debug(f"Failed to clean up reaction on error: {cleanup_err}")error_text = self.formatter.format_error(self._t("error.processMessageFailed", error=str(e)))await self._get_im_client(context).send_message(context, error_text)- # Also surface the failure into the live web-Chat SSE stream before- # the turn-complete signal below closes it (no-op for IM/CLI).+ # Surface the failure into the live web-Chat SSE stream first...await self._stream_terminal_error(context, error_text)+ # ...then settle the failed turn through the OUTBOUND status chokepoint:+ # an empty terminal error result turns the dot red + releases the SSE+ # waiter (the visible error was sent + streamed above). No separate latch.+ await self.controller.emit_agent_message(context, "result", "", is_error=True)return str(e)finally:if not agent_dispatched:diff --git a/core/internal_server.py b/core/internal_server.pyindex 6871fad47..2b4124810 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -32,13 +32,14 @@ import jsonimport loggingimport osfrom pathlib import Path+from types import SimpleNamespacefrom typing import Any, Optional, TYPE_CHECKINGfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import JSONResponse, StreamingResponsefrom config import paths-from core.services.dispatch import dispatch_turn+from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turnfrom modules.im.base import MessageContextif TYPE_CHECKING: # pragma: no cover - typing only@@ -46,6 +47,12 @@ if TYPE_CHECKING: # pragma: no cover - typing onlylogger = logging.getLogger(__name__)+# Hard cap for how long a stuck (timed-out + interrupt-not-confirmed) session stays+# blocked waiting for the backend to finish on its own before the slot is force-freed.+# A late terminal result releases it sooner; this only bounds the truly-stuck case so a+# session can never block forever (Codex P2).+STUCK_TURN_RECOVERY_TIMEOUT = 600.0+def default_socket_path() -> Path:"""Where the internal server binds by default.@@ -100,7 +107,13 @@ def create_app(controller: "Controller") -> FastAPI:# Chunks are discarded — the browser renders from ``message.new``.return None- async def _run_turn(session_id: Optional[str], context: MessageContext, text: str) -> 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@@ -112,6 +125,15 @@ def create_app(controller: "Controller") -> FastAPI:user's "don't clear the queue on stop" rule — unless ``send-now`` optedthis 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@@ -119,7 +141,21 @@ def create_app(controller: "Controller") -> FastAPI:cancelled = Falsefailed = Falsetry:- await dispatch_turn(controller, context, text, on_chunk=_noop_chunk)+ 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 = Trueraise@@ -134,6 +170,7 @@ def create_app(controller: "Controller") -> FastAPI:finally:if isinstance(session_id, str):timed_out = bool((context.platform_specific or {}).get("turn_timed_out"))+ stop_confirmed = Falseif timed_out:# The 600s wait elapsed with the backend still running.# Interrupt it BEFORE releasing the session, so /turn-state@@ -141,11 +178,87 @@ def create_app(controller: "Controller") -> FastAPI:# while a live backend turn is still producing output# (Codex P2). A turn silent for 10 min is treated as stuck.try:- await controller.command_handler.handle_stop(context)+ stop_confirmed = bool(await controller.command_handler.handle_stop(context))except Exception:logger.exception("dispatch timeout: backend stop failed for session=%s", session_id)- in_flight.pop(session_id, None)- bus.publish("turn.end", {"session_id": session_id})+ stop_confirmed = False+ # A timed-out turn whose interrupt could NOT be confirmed leaves the+ # backend possibly still producing output, so don't free the slot or+ # end the turn yet — but make the block SELF-HEALING + recoverable+ # instead of a never-resolving sentinel (Codex P2):+ # * register a turn sink under the timed-out turn's token so a LATE+ # terminal result (the backend finishing on its own) RELEASES the+ # slot promptly via ``mark_turn_complete``;+ # * a hard cap bounds the truly-stuck case so the session can never+ # block forever; on cap-expiry settle the dot ``failed``;+ # * DEFER ``turn.end`` until the slot actually frees, so the Chat+ # keeps its working indicator + Stop control to recover the turn+ # (a successful /internal/cancel cancels the sentinel below).+ # Meanwhile the busy ``in_flight`` entry makes a new Chat send ENQUEUE+ # rather than collide with the maybe-live backend.+ stuck = timed_out and not stop_confirmed+ if stuck:+ late_done = asyncio.Event()+ stuck_key = controller._get_session_key(context)+ stuck_token = (context.platform_specific or {}).get("turn_token")+ controller.register_turn_sink(+ stuck_key, on_chunk=_noop_chunk, done_event=late_done, turn_token=stuck_token+ )++ async def _await_stuck_release() -> None:+ # The sentinel can release three ways: a LATE terminal result+ # (``late_done`` set → the backend finished on its own), the hard+ # cap expiring (``TimeoutError`` → the turn is abandoned), or+ # ``send-now`` / Stop CANCELLING it (``CancelledError`` raised at+ # the wait). All three must honor the SAME flush contract as the+ # runner finally above, or a ``send-now`` during a stuck sentinel+ # would report ``interrupted`` yet leave the queued message+ # stranded forever and a stale ``flush_on_cancel`` marker behind+ # (Codex P2).+ backend_finished = True+ try:+ await asyncio.wait_for(late_done.wait(), timeout=STUCK_TURN_RECOVERY_TIMEOUT)+ except asyncio.TimeoutError:+ backend_finished = False+ finally:+ controller.pop_turn_sink(stuck_key, late_done)+ in_flight.pop(session_id, None)+ bus.publish("turn.end", {"session_id": session_id})+ # Mirror the runner finally's flush contract: ``send-now``+ # opted this session into ``flush_on_cancel`` before cancelling+ # us, so drain the queue now (a plain Stop sets ``stop_no_flush``+ # instead and keeps the queue). ALWAYS clear both markers so a+ # later, unrelated turn can't be wrongly flushed / suppressed by+ # a stale flag. A ``finally`` runs its awaits to completion+ # before re-raising the CancelledError, and ``_flush_queue``+ # only spawns the next turn (it doesn't await it), so the flush+ # completes even on the cancellation path.+ should_flush = 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)+ # Reached only on a NON-cancelled release (a CancelledError from+ # send-now / Stop re-raises out of the finally above, skipping this).+ if not backend_finished:+ # Cap expired with no late result → the turn is abandoned;+ # settle the dot ``failed`` through the outbound chokepoint.+ await controller.emit_agent_message(context, "result", "", is_error=True)++ in_flight[session_id] = (asyncio.create_task(_await_stuck_release()), context)+ else:+ in_flight.pop(session_id, None)+ bus.publish("turn.end", {"session_id": session_id})+ # Converge the no-terminal-result outcomes onto the OUTBOUND+ # status chokepoint. The normal path already emitted a terminal+ # result; only these reach here without one:+ # * ``failed`` — dispatch raised before any backend turn+ # (missing/disabled backend): empty error result → dot red.+ # * ``timed_out`` with a CONFIRMED stop: empty result → idle.+ if failed:+ await controller.emit_agent_message(context, "result", "", is_error=True)+ elif timed_out:+ await controller.emit_agent_message(context, "result", "")# Don't flush after a Stop (keep the queue) OR after a stream# timeout (the backend was just interrupted; the user can# resume). send-now still forces a flush via flush_on_cancel.@@ -220,6 +333,68 @@ def create_app(controller: "Controller") -> FastAPI:await _run_turn(session_id, context, user_row.get("text") or "")return True+ 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``.+ """+ if not session_id:+ await _run_turn(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:+ from core.message_mirror import _scope_id_for_session++ # 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.+ with engine.begin() as conn:+ scope_id = _scope_id_for_session(conn, session_id)+ if scope_id is not None:+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author="harness",+ source="harness",+ 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)+@app.get("/internal/health")async def _health() -> dict[str, Any]:return {"ok": True, "service": "vibe-remote-internal", "version": 1}@@ -412,7 +587,15 @@ def create_app(controller: "Controller") -> FastAPI:async def _stream():try:- yield ": connected\n\n"+ # A REAL ``connected`` event (not a ``:`` comment, which the+ # internal_client parser swallows) so it flows bridge → broker →+ # browser. The UI sidebar refetches on this, which reconciles+ # agent-status dots after a CONTROLLER restart while the UI server+ # + browser SSE stay up: only this bridge reconnects, so the+ # browser's own ``connected`` never fires and the crash-recovery+ # ``running → idle`` reset (broadcast to no subscriber) would+ # otherwise be invisible until a manual reload (Codex P2).+ yield _sse_event("connected", {})while True:event_type, data = await queue.get()yield _sse_event(event_type, data)@@ -530,6 +713,18 @@ def create_app(controller: "Controller") -> FastAPI:flushed = await _flush_queue(session_id)return {"ok": True, "session_id": session_id, "status": "flushed" if flushed else "empty"}+ # Expose the per-session turn gate to in-process callers (the scheduler)+ # WITHOUT going through the HTTP surface: ``ScheduledTaskService`` runs on the+ # same loop and routes avibe scheduled / watch turns through+ # ``submit_scheduled`` so they share the Chat path's queueing + lifecycle.+ # ``in_flight`` is the SAME dict object as ``app.state.in_flight_dispatches``+ # (the cancel endpoint, turn-state, and the tests all read it), so a scheduled+ # run registered by ``_run_turn`` is Stoppable through ``/internal/cancel``.+ controller.session_turn_gate = SimpleNamespace(+ submit_scheduled=_submit_scheduled_turn,+ in_flight=in_flight,+ )+return appdiff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 4734f99c6..208858f5c 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -61,16 +61,18 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[# The result is the turn's final answer — release the streaming dispatch# so it can close the SSE stream right after this chunk. Unlike chunk# forwarding above, the COMPLETION signal IS turn-token-gated (mirrors- # ``Controller.mark_turn_complete``): a late ``result`` from a SUPERSEDED- # turn (stopped / timed-out) resolves the CURRENT turn's sink by session- # key, and setting its ``done_event`` would pop ``in_flight`` / publish- # ``turn.end`` / flush the queue while the active backend is still running- # (Codex P1). Fail-open when either token is absent (byte-identical to- # IM/CLI). The reused-receiver Claude case keeps completing because its- # result emit adopts the live turn's token (see ClaudeAgent result path).+ # ``Controller.mark_turn_complete`` / ``_is_active_turn``): a late ``result``+ # from a SUPERSEDED or OLDER turn (stopped / timed-out / a scheduled-watch run+ # that carries no token) resolves the CURRENT turn's sink by session key, and+ # setting its ``done_event`` would pop ``in_flight`` / publish ``turn.end`` /+ # flush the queue while the active backend is still running (Codex P1/P2).+ # 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. 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 is not None and sink_token != ctx_token:+ if sink_token is not None and ctx_token != sink_token:returndone = sink.get("done_event")if done is not None:@@ -118,6 +120,34 @@ 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):@@ -386,6 +416,9 @@ class ConsolidatedMessageDispatcher:message_type: str,text: str,parse_mode: Optional[str] = "markdown",+ *,+ is_error: bool = False,+ level: str = "normal",) -> Optional[str]:"""Centralized dispatch for agent messages.@@ -394,19 +427,55 @@ class ConsolidatedMessageDispatcher:editable message per conversation round. Can be hidden by user settings.- Result Message: final output, always sent immediately, not hideable.- Notify Message: notifications, always sent immediately.++ ``is_error`` marks a terminal ``result`` as a FAILED turn. It is the only+ signal the sidebar dot needs on the way out: a terminal result settles the+ session to ``idle`` (or ``failed`` when ``is_error``). Callers that hit a+ terminal failure emit it as ``result`` + ``is_error=True`` instead of a+ bare ``notify`` — that routes the failure through this one outbound+ chokepoint (dot + SSE stream release), so no caller pokes the dot directly.++ ``level`` is the visibility grade — orthogonal to ``message_type``. The+ type says what role the message plays (and drives the dot + unread); the+ level says whether the user should SEE it:+ - ``"normal"`` (default): delivered / persisted / streamed as usual.+ - ``"silent"``: settles the dot + releases the SSE waiter for a terminal+ ``result``, then returns WITHOUT delivering, persisting, or streaming.+ Used for intentional, non-noteworthy lifecycle events (e.g. a user-+ initiated stop) so the turn ends cleanly with no user-facing bubble —+ replacing the old "fake it with empty text" trick with an explicit flag."""settings_manager = self.controller.get_settings_manager_for_context(context)im_client = self._get_im_client(context)canonical_type = settings_manager._canonicalize_message_type(message_type or "")settings_key = self._get_settings_key(context)++ # OUTBOUND status chokepoint (one of exactly two — the other is the+ # inbound AgentService.handle_message). A terminal ``result`` ends the+ # turn, so settle the avibe sidebar dot here regardless of delivery+ # outcome. Non-avibe contexts resolve to no session id and are skipped;+ # ``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")text = strip_silent_blocks(text)- if not text or not text.strip():+ # ``level="silent"`` is the explicit visibility control (orthogonal to type):+ # the message already settled the dot above (for a terminal result), so here+ # we release the SSE waiter and return BEFORE any delivery / persistence /+ # streaming — no user-facing bubble, regardless of body. An empty/stripped+ # body (e.g. a ``<silent>`` directive reduced to nothing) is silent too.+ if level == "silent" or not text or not text.strip():if canonical_type == "result":- # An empty/silent result (e.g. a ``<silent>`` directive whose- # text is stripped to nothing) still means the turn finished —- # release the streaming SSE waiter so it closes now instead of- # hanging until the safety timeout, even with no visible chunk.+ # A terminal result — even silent/empty — still means the turn+ # finished: release the streaming SSE waiter so it closes now+ # instead of hanging until the safety timeout, with no visible chunk.await self._clear_consolidated_state(context)self._signal_turn_complete(context)return None@@ -609,7 +678,10 @@ class ConsolidatedMessageDispatcher:# failed every send/upload (primary_message_id is None) is NOT# recorded, matching the old outbound mirror's success-only rule.if persists_without_delivery or primary_message_id is not None:- persist_agent_message(target_context, "result", persist_text)+ # A failed terminal result persists as type='error' so it shows in+ # the transcript/inbox like any terminal message but is NOT counted+ # as an unread agent reply (unread queries are result-only). Codex P2.+ persist_agent_message(target_context, "error" if is_error else "result", persist_text)if primary_message_id and display_text:# Stream the delivered result to live consumers (avibe SSE).diff --git a/core/message_mirror.py b/core/message_mirror.pyindex 0c9485390..1de4a3628 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -122,6 +122,9 @@ def _scope_id_for_session(conn, session_id: str) -> Optional[str]:# (Codex P2). Genuine terminal failures persist via canonical ``notify``._AGENT_TYPE_BY_CANONICAL = {"result": "result",+ # A terminal FAILED result — kept distinct from ``result`` so unread queries+ # (result-only) don't count it, while it stays in the transcript/inbox.+ "error": "error","notify": "notify","assistant": "assistant","toolcall": "tool_call",@@ -151,6 +154,11 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: streturnif not context.platform:return+ # ``system`` messages are generated by us (init banners, status lines), not the+ # agent — don't persist them at all (they have no place in the transcript and+ # would only be noise in history) (user request).+ if (canonical_type or "") == "system":+ returnmessage_type = _AGENT_TYPE_BY_CANONICAL.get(canonical_type or "", "assistant")session_id = (context.platform_specific or {}).get("agent_session_id")try:@@ -197,8 +205,12 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: stif context.platform == "avibe" and session_id:inbox_row = messages_service.get_inbox_session(conn, session_id)# Fan the row out to an open Chat page (session-scoped stream), then bump- # the inbox card. Both ride the controller→browser bridge.- _publish_session_message(appended_row)+ # the inbox card. Both ride the controller→browser bridge. Only publish+ # transcript-visible types so the live stream carries EXACTLY what the+ # history fetch returns (assistant / tool_call process-log rows are+ # persisted for debugging but neither streamed nor fetched) (user request).+ if message_type in messages_service.TRANSCRIPT_TYPES:+ _publish_session_message(appended_row)if inbox_row is not None:from core.inbox_events import busdiff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex f8b3842c5..9502b1b61 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -214,7 +214,13 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = Noneplatform = str(row["platform"] or "")scope_type = str(row["scope_type"] or "")scope_id = str(row["native_id"] or "")- if not platform or scope_type not in {"channel", "user"} or not scope_id:+ # ``project`` is the avibe workbench's scope type (sessions live under+ # ``avibe::project::proj_<hex>``). A session-id target carries the concrete+ # ``session_id`` (the row PK) regardless of scope type, and the dispatch binds+ # the reply to that reserved session via ``agent_session_target`` — so a+ # project-scoped row IS a valid task target. (``--session-key`` targeting stays+ # channel/user-only: a bare project key wouldn't identify a single session.)+ if not platform or scope_type not in {"channel", "user", "project"} or not scope_id:raise ValueError(f"agent session id cannot be used as a task target: {raw}")anchor = str(row["session_anchor"] or "")@@ -1058,7 +1064,14 @@ class ScheduledTaskService:self.request_store.recover_processing()def validate_platform(self, platform: str) -> None:- if platform not in self.controller.platform_settings_managers:+ # The real IM platforms have a settings manager; ``avibe`` (the web+ # workbench) is a virtual platform with an IM client but no settings+ # manager — accept it too so scheduled tasks/watches can target a+ # workbench session (they fire like a harness turn, reply via message.new).+ if (+ platform not in self.controller.platform_settings_managers+ and platform not in getattr(self.controller, "im_clients", {})+ ):raise ValueError(f"unsupported task platform: {platform}")def start(self) -> None:@@ -1267,7 +1280,13 @@ class ScheduledTaskService:return cachedtry:resolved = resolve_session_id_target(session_id)- key = f"key:{resolved.session_key.to_key()}"+ # avibe/workbench sessions are 1:1 with the session id — a project scope+ # holds many INDEPENDENT sessions, so locking on the project key would+ # serialize unrelated conversations. Lock on the concrete session id.+ if resolved.session_key.platform == "avibe" or resolved.session_key.scope_type == "project":+ key = f"sid:{session_id}"+ else:+ key = f"key:{resolved.session_key.to_key()}"except Exception:# avibe/web sessions (no IM scope) or unresolved ids: fall back to a# carried session key if present, else the id is its own identity.@@ -1518,6 +1537,26 @@ class ScheduledTaskService:agent_name=agent_name,target_info=target_info,)+ # A scheduled avibe turn drives the sidebar dot through the SAME two+ # chokepoints as any other turn — inbound AgentService.handle_message+ # (running) and the outbound terminal result (idle/failed) — because its+ # ``context`` carries the avibe ``agent_session_id`` (set in+ # ``_build_context``). No dot bookkeeping here.+ #+ # Route avibe runs through the per-session turn gate the Chat HTTP path+ # uses, so a scheduled / watch / webhook / agent_run turn targeting an+ # avibe session QUEUES behind an active Chat turn (never preempts it) and+ # gets the in_flight + turn.start / turn.end lifecycle that makes the Chat+ # page show the working indicator + Stop (Codex P2). The gate runs on the+ # controller's loop and is published by ``internal_server.create_app``.+ # Returning ``None`` keeps ``ok = not error`` true (the run's own outcome+ # surfaces via the outbound terminal result + sidebar dot, exactly as the+ # interactive Chat turn does). IM targets NEVER touch the gate — they keep+ # the direct ``handle_scheduled_message`` path byte-for-byte.+ gate = getattr(self.controller, "session_turn_gate", None)+ if target.platform == "avibe" and session_id and gate is not None:+ await gate.submit_scheduled(session_id, context, prompt)+ return Nonereturn await self.controller.message_handler.handle_scheduled_message(context=context,message=prompt,@@ -1548,9 +1587,20 @@ class ScheduledTaskService:delivery_context=delivery_target_context,)+ # avibe workbench: the context IDENTITY is the concrete session, not the+ # project scope — an avibe project holds many independent sessions, so+ # keying the context off the project id would make _get_session_key /+ # consolidated-log grouping collide between concurrent runs in the same+ # project (they'd edit/merge each other's log). Use session_id as the+ # channel_id (matches how the interactive Chat dispatch builds the context);+ # persistence/routing still resolves the project scope via agent_session_id.+ channel_id = session_target_context["channel_id"]+ if platform == "avibe" and session_id:+ channel_id = session_id+return MessageContext(user_id=session_target_context["user_id"],- channel_id=session_target_context["channel_id"],+ channel_id=channel_id,platform=platform,thread_id=target.thread_id,message_id=self._build_message_id(@@ -1604,6 +1654,11 @@ class ScheduledTaskService:def _resolve_target_context(self, target: ParsedSessionKey) -> Dict[str, Any]:platform = target.platform+ if platform not in self.controller.platform_settings_managers:+ # Virtual platform (avibe workbench): no per-platform settings manager+ # and no DM bindings — the scope_id IS the session/channel, and a+ # scheduled run is attributed to a synthetic "scheduled" user.+ return {"user_id": "scheduled", "channel_id": target.scope_id}settings_manager = self.controller.platform_settings_managers[platform]channel_id = target.scope_iddiff --git a/core/services/sessions.py b/core/services/sessions.pyindex 70e1a8861..7b9d4903e 100644--- a/core/services/sessions.py+++ b/core/services/sessions.py@@ -42,6 +42,8 @@ from storage.workbench_sessions_service import (create_session,get_session,list_sessions,+ reset_running_agent_status,+ set_agent_status,touch_session,update_session,)@@ -52,6 +54,8 @@ __all__ = ["create_session","get_session","list_sessions",+ "reset_running_agent_status",+ "set_agent_status","touch_session","update_session","reserve_agent_session",diff --git a/docs/plans/session-status-two-chokepoints.md b/docs/plans/session-status-two-chokepoints.mdnew file mode 100644index 000000000..bfa89c230--- /dev/null+++ b/docs/plans/session-status-two-chokepoints.md@@ -0,0 +1,81 @@+# Session status dot — collapse to two chokepoints++## Problem++`agent_sessions.agent_status` (the sidebar dot: `running` / `idle` / `failed`) is+currently driven by instrumentation scattered across **every turn-entry path** and+**every backend error branch**:++- `mark_turn_running` called from `internal_server._run_turn` (interactive) and+ `ScheduledTaskService._execute_request` (scheduled).+- a failure latch (`Controller._sessions_turn_failed` via `note_turn_failed` /+ `pop_turn_failed`, plus `BaseAgent._note_turn_failed` / `MessageHandler._note_turn_failed`)+ poked from `opencode/agent.py`, `codex/agent.py`, `base.py`, `agent_auth_service.py`,+ `message_handler.py`.++Every new turn path (scheduled, Show Page) or backend error branch (codex missing+CLI) is a place that can be forgotten, so the dot goes stale. Successive reviews+keep finding "another path that wasn't wired" — the symptom of accidental+complexity, not an inherent property of session status.++## The two chokepoints (the only allowed instrumentation)++Every turn already funnels through one inbound and one outbound function:++- **Inbound — `AgentService.handle_message(agent_name, request)`**: the single+ dispatch point every turn (interactive / scheduled / Show Page, every backend)+ passes through to reach a backend. → set `running`.+- **Outbound — `MessageDispatcher.emit_agent_message(...)` on a TERMINAL message**:+ every agent reply/result/error is persisted here as a typed message. A terminal+ `result` → `idle`; a terminal `error` → `failed`.++The dot is gated to avibe via `Controller._session_id_from_context` (only avibe+workbench turns carry `agent_session_id`).++## Convergence (instead of a third instrumentation point)++The outbound only covers everything if **every terminal outcome emits a terminal+message**. Today terminal *failures* are emitted as a `notify` plus a manual+`_note_turn_failed()` plus a manual `_release_stream_turn()` (because a `notify`+does not fire `_signal_turn_complete`). That is three manual steps for the same+event.++Fix: introduce a terminal **`error`** message type (sibling of `result`):++- delivered immediately, persisted with `type="error"`, fires `_signal_turn_complete`.+- The outbound chokepoint sets the dot `failed` on it.++Then every terminal-failure path emits `emit_agent_message(context, "error", text)`+and drops its manual latch + manual stream-release. This converges failures onto+the outbound chokepoint AND fixes the latent "SSE stream hangs until the 600s+timeout on a failure" issue.++Terminal outcomes that produce no agent text (user **Stop**, dispatch **timeout**)+must also settle the dot — they converge by emitting a terminal signal through the+same outbound path (or, where they already run inside the dispatcher's+result/clear path, by reusing `_signal_turn_complete`). Verified case-by-case+during implementation; no new instrumentation point is added.++## Delete++- `Controller._sessions_turn_failed`, `note_turn_failed`, `pop_turn_failed`,+ `mark_turn_running`.+- `BaseAgent._note_turn_failed`, `MessageHandler._note_turn_failed` and all callers.+- The dot lifecycle block in `internal_server._run_turn`'s runner `finally`.+- The r7 dot wrapper in `ScheduledTaskService._execute_request`.++## Keep++- `set_agent_status` (the DB writer — the two chokepoints call it).+- `_signal_turn_complete` / `mark_turn_complete` / the turn-sink + `turn_token`+ (the live SSE stream completion — a separate concern; the dot now rides the same+ terminal-message point but does not replace it).+- `_reset_stale_agent_status` on startup (crash recovery: `running` → `idle`).++## Evidence layers++- unit: controller (only `set_agent_status` + reset remain), message_dispatcher+ (terminal `result`→idle / `error`→failed sets the dot), AgentService inbound.+- contract: `core.services.sessions` surface unchanged except removed latch.+- scenario/manual: avibe interactive, scheduled, Show-Page-dispatched, and a+ backend failure (e.g. codex missing CLI) all drive the dot from the two points.diff --git a/modules/agents/base.py b/modules/agents/base.pyindex ad0501b16..2a12eeb32 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -289,6 +289,12 @@ class BaseAgent(ABC):suffix: Optional[str] = None,request: Optional[AgentRequest] = None,) -> None:+ # An error result subtype (e.g. Claude's ``error_max_turns`` /+ # ``error_during_execution``) is a FAILED turn. Carry that on the terminal+ # ``result`` emit via ``is_error`` so the outbound chokepoint flips the dot+ # red — no separate latch.+ is_error = (subtype or "").startswith("error")+show_duration = getattr(self.config, "show_duration", True)if duration_ms is None:duration_ms = self._calculate_duration_ms(started_at)@@ -300,7 +306,7 @@ class BaseAgent(ABC):has_silent_directive = "<silent" in raw_result.lower() or "<silent" in raw_suffix.lower()if has_silent_directive and not visible_result.strip() and not (visible_suffix or "").strip():- await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode)+ await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode, is_error=is_error)if request:await self._remove_ack_reaction(request)return@@ -315,16 +321,14 @@ class BaseAgent(ABC):parts.append(visible_suffix)if parts:formatted = "\n".join(parts)- await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode)+ await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode, is_error=is_error)else:- # No visible text to send (show_duration off + empty result/suffix):- # emit_agent_message is skipped, so nothing would release the web-Chat- # streaming turn and it would hang until the 600s timeout. Mark the- # turn complete (mirrors the silent-directive path); token-guarded +- # no-op for IM/CLI (Codex P2).- _mark = getattr(self.controller, "mark_turn_complete", None)- if callable(_mark):- _mark(context)+ # No visible text (show_duration off + empty result/suffix) is still+ # a TERMINAL turn: settle it through the OUTBOUND status chokepoint+ # (empty result → dot idle / failed AND releases the web-Chat stream+ # waiter), mirroring the silent-directive path above — otherwise the+ # dot stays green and the stream hangs until the 600s timeout (Codex P2).+ await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode, is_error=is_error)else:formatted = self._get_formatter(context).format_result_message(subtype or "",@@ -334,7 +338,7 @@ class BaseAgent(ABC):)if visible_suffix:formatted = f"{formatted}\n{visible_suffix}"- await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode)+ await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode, is_error=is_error)# Remove ack reaction after result is sentif request:diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 6d4027f21..77f09fd26 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -134,14 +134,12 @@ class ClaudeAgent(BaseAgent):persist_agent_message(context, "notify", f"❌ Claude error: {e}")except Exception:logger.debug("claude: failed to persist terminal error row", exc_info=True)- # Synchronous failure (query/setup raised) — no async receiver- # result is coming for this turn, so release the web-Chat stream- # waiter now (token-guarded, no-op for IM/CLI) instead of waiting- # out the safety timeout. Defensive: tolerate controllers without- # streaming completion support.- _mark = getattr(self.controller, "mark_turn_complete", None)- if callable(_mark):- _mark(context)+ # Synchronous failure (query/setup raised), no async receiver result+ # coming: settle the turn through the OUTBOUND status chokepoint. An+ # empty terminal error result turns the dot red AND releases the+ # web-Chat stream waiter (the visible error was sent + persisted+ # above), instead of waiting out the safety timeout. No-op off-workbench.+ await self.controller.emit_agent_message(context, "result", "", is_error=True)finally:await self._delete_ack(context, request)@@ -319,10 +317,18 @@ class ClaudeAgent(BaseAgent):return Falseclient = self.claude_sessions[composite_key]- await self.controller.emit_agent_message(request.context, "notify", "🛑 Interrupting Claude session...")try:if hasattr(client, "interrupt"):await client.interrupt()+ # A user-initiated stop is terminal but intentional, so it carries+ # NO user-facing message: a single SILENT result settles the dot to+ # idle + releases the SSE waiter through the outbound chokepoint+ # WITHOUT a bubble. Done HERE, before /internal/cancel cancels the+ # _run_turn task (the cancelled branch can't safely emit during+ # cancellation). A genuine interrupt FAILURE below still notifies.+ await self.controller.emit_agent_message(+ request.context, "result", "", level="silent"+ )return Trueelse:await self.controller.emit_agent_message(@@ -483,6 +489,9 @@ class ClaudeAgent(BaseAgent):getattr(message, "subtype", "") or "",formatted_message,):+ # Retire the failed request from the FIFO (else the next+ # successful turn adopts its stale token). Codex P2.+ self._retire_failed_auth_turn(composite_key, context)mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)if callable(mark_session_idle):mark_session_idle(composite_key)@@ -513,22 +522,7 @@ class ClaudeAgent(BaseAgent):getattr(message, "subtype", "") or "",result_text,):- # The auth error IS this turn's (failed) result, so retire its- # pending request from the FIFO queue. ``_handle_auth_failure_result``- # preserves the request list for resume; leaving the failed entry- # there desyncs request↔result pairing, so the NEXT successful turn- # would FIFO-pop this failed request and adopt its stale turn_token —- # then ``_stream_chunk`` refuses to complete the live turn and Stop- # sticks until the safety timeout (Codex P2).- failed_request = self._pop_pending_request(composite_key)- # Release THIS failed turn's Chat stream under its own token.- # ``_handle_auth_failure_result`` already persisted the durable- # recovery notify (error + reset prompt) centrally via- # ``maybe_emit_auth_recovery_message``, so we don't persist here.- self._adopt_pending_turn_token(context, failed_request)- _mark = getattr(self.controller, "mark_turn_complete", None)- if callable(_mark):- _mark(context)+ self._retire_failed_auth_turn(composite_key, context)mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)if callable(mark_session_idle):mark_session_idle(composite_key)@@ -596,6 +590,15 @@ class ClaudeAgent(BaseAgent):f"Error in Claude receiver for session {composite_key}: {e}",exc_info=True,)+ # The reused receiver context still carries the FIRST turn's token, so a+ # 2nd-or-later turn's crash would emit its terminal error under a stale+ # token — the outbound active-turn guard treats it as superseded and drops+ # BOTH the failed-status write and the completion signal, hanging Chat to+ # the 600s timeout. Adopt the CURRENT (FIFO-head) turn's token onto the+ # context BEFORE clearing the FIFO (and before either the auth-recovery or+ # the non-auth emit below), mirroring the in-loop auth-failure paths (Codex P2).+ _pending = self._pending_requests.get(composite_key) or []+ self._adopt_pending_turn_token(context, _pending[0] if _pending else None)# Clean up all pending reactions for this session on error —# the receiver is dead and won't process any more results.await self._clear_pending_reactions(composite_key, context)@@ -606,6 +609,24 @@ class ClaudeAgent(BaseAgent):)if not handled:await self.session_handler.handle_session_error(composite_key, context, e)+ # ``handle_session_error`` sends via the IM client, which doesn't+ # write to ``messages``; the web Chat renders only durable rows, so+ # persist a terminal notify or the avibe user's turn stops with no+ # explanation (mirrors the synchronous query-failure path above).+ try:+ from core.message_mirror import persist_agent_message++ persist_agent_message(context, "notify", f"❌ Claude error: {e}")+ except Exception:+ logger.debug("claude: failed to persist terminal receiver-error row", exc_info=True)+ # A dead receiver is terminal. The HANDLED (auth) branch already+ # settled the turn via ``maybe_emit_auth_recovery_message``; the+ # non-auth branch is settled by NOTHING, so route it through the+ # OUTBOUND status chokepoint here (empty error result → dot red ++ # releases the SSE waiter) instead of letting the avibe Chat hang to+ # the 600s stream timeout and then settle idle. No-op off-workbench+ # (Codex P2).+ await self.controller.emit_agent_message(context, "result", "", is_error=True)# NOTE: no `finally` cleanup of pending reactions here.# When the receiver ends normally (stream exhausted after a result),# new messages may have already queued their reactions via@@ -685,6 +706,23 @@ class ClaudeAgent(BaseAgent):context.platform_specific = {}context.platform_specific["turn_token"] = token+ def _retire_failed_auth_turn(self, composite_key: str, context: MessageContext) -> None:+ """Retire a terminal auth-failure turn from the pending FIFO.++ The auth error IS this turn's (failed) result, so pop its pending request:+ leaving the failed entry desyncs request↔result pairing, so the NEXT+ successful turn would FIFO-pop this stale request and adopt its old+ ``turn_token`` — then ``_stream_chunk`` rejects the live turn's completion+ and Stop sticks until the safety timeout. Adopt the failed turn's own token+ and release its Chat stream now. Called from every auth-failure terminal+ path (result / system / assistant); the dot was already settled and the+ recovery notify persisted by ``maybe_emit_auth_recovery_message``."""+ failed_request = self._pop_pending_request(composite_key)+ self._adopt_pending_turn_token(context, failed_request)+ _mark = getattr(self.controller, "mark_turn_complete", None)+ if callable(_mark):+ _mark(context)+def _has_pending_requests(self, composite_key: str) -> bool:return bool(self._pending_requests.get(composite_key))@@ -838,6 +876,15 @@ class ClaudeAgent(BaseAgent):if not classify_auth_error("claude", text):return False+ # The reused receiver still carries an EARLIER turn's ``turn_token``; adopt+ # THIS turn's token (the FIFO head — the request this result belongs to, per+ # the success path below) BEFORE the auth-recovery emit. The recovery helper+ # now settles the failed dot through the outbound chokepoint, whose+ # active-turn guard would otherwise treat the stale token as a superseded+ # turn and skip the failed-status write for 2nd-or-later Claude auth failures.+ pending = self._pending_requests.get(composite_key) or []+ self._adopt_pending_turn_token(context, pending[0] if pending else None)+handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(context,"claude",diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 5690a8d11..8d4ba9b6b 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -83,22 +83,24 @@ class CodexAgent(BaseAgent):try:transport = await self._get_or_create_transport(request.working_path)except FileNotFoundError:+ # Terminal failure → emit as a RESULT (error): the outbound chokepoint+ # turns the dot red and releases the SSE waiter (no separate latch).await self.controller.emit_agent_message(request.context,- "notify",+ "result","❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",+ is_error=True,)await self._remove_ack_reaction(request)- # Codex gave up before a turn started — release the web-Chat- # working/Stop state now instead of leaving it until the fallback.self._event_handler._release_stream_turn(request.context)returnexcept Exception as e:logger.error("Failed to start Codex transport: %s", e, exc_info=True)await self.controller.emit_agent_message(request.context,- "notify",+ "result",f"❌ Failed to start Codex CLI: {e}",+ is_error=True,)await self._remove_ack_reaction(request)self._event_handler._release_stream_turn(request.context)@@ -138,8 +140,9 @@ class CodexAgent(BaseAgent):logger.warning("Failed to interrupt turn %s: %s", active_turn, e)await self.controller.emit_agent_message(request.context,- "notify",+ "result",f"❌ Failed to interrupt previous Codex turn: {e}",+ is_error=True,)await self._remove_ack_reaction(request)self._event_handler._release_stream_turn(request.context)@@ -186,14 +189,17 @@ class CodexAgent(BaseAgent):error_text,)if not handled:+ # Terminal failure → RESULT (error): the outbound chokepoint+ # turns the dot red. The auth-recovery branch (handled) emits+ # its own terminal error result inside+ # ``maybe_emit_auth_recovery_message``, so both paths settle+ # the dot via the same outbound — no separate latch.await self.controller.emit_agent_message(request.context,- "notify",+ "result",error_text,+ is_error=True,)- # handled == True persists the durable recovery notify centrally in- # ``maybe_emit_auth_recovery_message``; the not-handled branch persists- # via ``emit_agent_message`` above.await self._remove_ack_reaction(request)# The turn never started (all retries failed) — release the# web-Chat working/Stop state instead of leaving it until the@@ -220,10 +226,14 @@ class CodexAgent(BaseAgent):interrupted_request = self._event_handler.clear_pending(turn_id)if interrupted_request:await self._remove_ack_reaction(interrupted_request)+ # A user-initiated stop is terminal but intentional, so it carries NO+ # user-facing message: a single SILENT result settles the dot to idle ++ # releases the SSE waiter through the outbound chokepoint without a+ # bubble. The user already knows they stopped it (avibe shows the dot go+ # idle; IM shows the ack reaction removed above). ``level="silent"`` is+ # the explicit visibility grade rather than faking it via empty text.await self.controller.emit_agent_message(- request.context,- "notify",- "🛑 Terminated Codex execution.",+ request.context, "result", "", level="silent")logger.info("Codex turn %s interrupted via /stop", turn_id)return Truediff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex edd80f202..b29ad6766 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -160,10 +160,14 @@ class CodexEventHandler:message,)if not handled:+ # Terminal failure → RESULT (error): the outbound status+ # chokepoint turns the dot red. The auth-recovery branch+ # settles it via its own terminal error result.await self._agent.controller.emit_agent_message(tracked_request.context,- "notify",+ "result",message,+ is_error=True,)# handled == True persists the durable recovery notify centrally in# ``maybe_emit_auth_recovery_message`` (the auth service is the single@@ -334,10 +338,14 @@ class CodexEventHandler:text,)if not handled:+ # Terminal failure → error RESULT so the outbound chokepoint+ # turns the dot red (the later completed handler suppresses a+ # second message once terminal_error_notified is set).await self._agent.controller.emit_agent_message(request.context,- "notify",+ "result",text,+ is_error=True,)turn_state.terminal_error_notified = Trueelse:@@ -351,10 +359,12 @@ class CodexEventHandler:text,)if not handled:+ # No-turnId terminal error → error RESULT so the dot turns red.await self._agent.controller.emit_agent_message(request.context,- "notify",+ "result",text,+ is_error=True,)def _extract_error_message(self, error: Any) -> str:diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex d2e1fa7ee..7bc8057a3 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -129,10 +129,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await server.ensure_running()except Exception as e:logger.error(f"Failed to start OpenCode server: {e}", exc_info=True)+ # Terminal failure → emit as a RESULT (error): the outbound chokepoint+ # turns the dot red and releases the SSE waiter. No separate latch.await self.controller.emit_agent_message(request.context,- "notify",+ "result",f"Failed to start OpenCode server: {e}",+ is_error=True,)await self._remove_ack_reaction(request)return@@ -143,30 +146,33 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):try:session_id = await self._session_manager.get_or_create_session_id(request, server)except OpenCodeResumeUnavailableError as e:- # The previous session is gone server-side — surface it, don't silently+ # The previous session is gone server-side — surface it as a terminal+ # ERROR result (outbound chokepoint turns the dot red), don't silently# fork a fresh session and lose context.- await self.controller.emit_agent_message(request.context, "notify", f"❌ {e}")+ await self.controller.emit_agent_message(request.context, "result", f"❌ {e}", is_error=True)await self._remove_ack_reaction(request)returnexcept Exception as e:# A transient/transport/auth failure while acquiring the session# (get_session now raises on non-404, Codex P2): surface it as a- # terminal error instead of letting it propagate unhandled or be- # mislabeled as expiry. Route auth errors through the reset-OAuth flow.+ # terminal error result instead of letting it propagate unhandled or be+ # mislabeled as expiry. Route auth errors through the reset-OAuth flow+ # (which settles the dot itself); otherwise emit the error result here.logger.error(f"OpenCode session acquisition failed: {e}", exc_info=True)message = f"OpenCode error: {type(e).__name__}: {e}".strip()handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(request.context, "opencode", message)if not handled:- await self.controller.emit_agent_message(request.context, "notify", message)+ await self.controller.emit_agent_message(request.context, "result", message, is_error=True)await self._remove_ack_reaction(request)returnif not session_id:await self.controller.emit_agent_message(request.context,- "notify",+ "result","Failed to obtain OpenCode session ID",+ is_error=True,)await self._remove_ack_reaction(request)return@@ -373,14 +379,18 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):message,)if not handled:+ # Terminal failure → error RESULT so the outbound chokepoint turns+ # the dot red (auth-classified errors settle via the recovery path).await self.controller.emit_agent_message(request.context,- "notify",+ "result",message,+ is_error=True,)# handled == True persists the durable recovery notify centrally in- # ``maybe_emit_auth_recovery_message``; the not-handled branch persists- # via ``emit_agent_message`` above.+ # ``maybe_emit_auth_recovery_message`` (which also latches the turn+ # failure for the workbench dot — auth AND non-auth); the not-handled+ # branch persists via ``emit_agent_message`` above.finally:if run_registered:await server.mark_run_inactive(session_id)@@ -409,7 +419,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):if opencode_session_id:self.sessions.remove_active_poll(opencode_session_id)- await self.controller.emit_agent_message(request.context, "notify", "Terminated OpenCode execution.")+ # A user-initiated stop is terminal but intentional, so it carries NO+ # user-facing message: a single SILENT result settles the dot to idle ++ # releases the SSE waiter through the outbound chokepoint without a bubble+ # (``level="silent"`` makes that explicit rather than faking it via empty text).+ await self.controller.emit_agent_message(request.context, "result", "", level="silent")logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")return True@@ -451,6 +465,26 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# _remove_ack_reaction is inherited from BaseAgent+ @staticmethod+ def _workbench_session_id_for_poll(poll_info) -> Optional[str]:+ """Resolve the avibe workbench session id a restored poll belongs to, or+ ``None`` for an IM poll.++ Mirrors how the inbound chokepoint resolves it+ (``Controller._session_id_from_context`` reads+ ``platform_specific["agent_session_id"]``): for an avibe turn the dispatch+ stamps ``agent_session_id`` = the workbench session PK, which equals the+ session's anchor and therefore the OpenCode ``base_session_id`` the poll+ ran under (see ``internal_server._build_session_context`` ++ ``SessionHandler.get_base_session_id``). The persisted poll snapshot does+ not carry ``agent_session_id``, so we recover it from ``base_session_id``+ for avibe polls only — IM polls return ``None`` and get no status dot.+ """+ if (poll_info.platform or "") != "avibe":+ return None+ base_session_id = poll_info.base_session_id or ""+ return base_session_id or None+async def restore_active_polls(self) -> int:"""Restore active poll loops that were interrupted by vibe-remote restart."""@@ -498,6 +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.+ workbench_session_id = self._workbench_session_id_for_poll(poll_info)+ if workbench_session_id:+ self.controller.set_agent_status(workbench_session_id, "running")+task = asyncio.create_task(self._run_restored_poll_loop_with_tracking(poll_info))self._active_requests[poll_info.base_session_id] = taskself._session_manager.set_request_session(diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex ca5431d0c..c78ada867 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -188,7 +188,9 @@ class OpenCodePollLoop:if tool_name == "question" and tool_state.get("status") != "completed":message = self._t("error.opencodeQuestionToolDisabled")logger.warning("Aborting OpenCode session %s after disabled question tool call", session_id)- await self._agent.controller.emit_agent_message(request.context, "notify", message)+ # Terminal abort → error RESULT so the outbound chokepoint+ # turns the dot red (not a bare notify that never settles it).+ await self._agent.controller.emit_agent_message(request.context, "result", message, is_error=True)try:await server.abort_session(session_id, request.working_path)except Exception as abort_err:@@ -285,13 +287,22 @@ class OpenCodePollLoop:message,)if not handled:+ # Retry exhausted on a message error → terminal FAILURE.+ # Emit an ERROR result so the outbound chokepoint turns the+ # dot red (a bare notify never settles agent_status) (Codex P2).await self._agent.controller.emit_agent_message(request.context,- "notify",+ "result",message,+ is_error=True,)- final_text = None- break+ # Terminal: stop polling AND signal the caller NOT to emit the+ # "(No response from OpenCode)" warning result — that warning is+ # idle and would reset the dot we (or the auth-recovery path)+ # just settled to failed. Mirrors the question-tool abort's+ # ``return None, False`` rather than ``break`` (→ should_emit+ # True → the idle warning) (Codex P2).+ return None, Falseif last_info.get("finish") != "tool-calls":if not msg_error:@@ -398,7 +409,8 @@ class OpenCodePollLoop:"Aborting restored OpenCode session %s after disabled question tool call",session_id,)- await self._agent.controller.emit_agent_message(context, "notify", message)+ # Terminal abort → error RESULT (settles the dot red).+ await self._agent.controller.emit_agent_message(context, "result", message, is_error=True)try:await server.abort_session(session_id, poll_info.working_path)except Exception as abort_err:@@ -456,10 +468,15 @@ class OpenCodePollLoop:message,)if not handled:+ # Terminal failure (retry exhausted) on the+ # restored poll path → ERROR result so the dot+ # turns red, not a notify that leaves it+ # running until the safety timeout (Codex P2).await self._agent.controller.emit_agent_message(context,- "notify",+ "result",message,+ is_error=True,)self._agent.sessions.remove_active_poll(session_id)await self.remove_restored_ack(poll_info)@@ -532,8 +549,11 @@ class OpenCodePollLoop:message,)if not handled:+ # Terminal failure → error RESULT so the outbound chokepoint turns+ # the dot red (auth-classified errors settle via the recovery path).await self._agent.controller.emit_agent_message(context,- "notify",+ "result",message,+ is_error=True,)diff --git a/modules/agents/service.py b/modules/agents/service.pyindex 64c7c639c..83b20f431 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -26,6 +26,15 @@ class AgentService:async def handle_message(self, agent_name: str, request: AgentRequest):agent = self.get(agent_name)+ # INBOUND status chokepoint (one of exactly two — the other is the outbound+ # MessageDispatcher.emit_agent_message). Every turn, every source (chat /+ # scheduled / Show Page), every backend funnels through here, so this is the+ # 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")await agent.handle_message(request)async def clear_sessions(self, session_key: str) -> Dict[str, int]:diff --git a/storage/alembic/versions/20260601_0012_agent_status.py b/storage/alembic/versions/20260601_0012_agent_status.pynew file mode 100644index 000000000..3eff29a46--- /dev/null+++ b/storage/alembic/versions/20260601_0012_agent_status.py@@ -0,0 +1,59 @@+"""add agent_sessions.agent_status column++Adds a live agent-runtime ``agent_status`` to ``agent_sessions``, distinct from+the lifecycle ``status`` (active/archived). One of ``idle`` / ``running`` /+``failed``: ``running`` while a turn is in flight, ``failed`` when the most+recent turn ended in error, ``idle`` otherwise. Drives the workbench sidebar+status dot (gray / green / red).++Existing rows default to ``idle`` (the column is NOT NULL with a server default,+so the backfill is implicit). A stale ``running`` left by a crash is reset to+``idle`` on controller startup — no turn survives a restart.++Revision ID: 20260601_0012+Revises: 20260601_0011+Create Date: 2026-06-01++(Rebased onto the (scope, anchor) migration 20260601_0011 when the two feature+branches merged — both originally branched from 20260531_0010, producing two+alembic heads. The two changes are independent; this only linearizes them.)+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260601_0012"+down_revision = "20260601_0011"+branch_labels = None+depends_on = None+++def _columns(bind, table: str) -> set[str]:+ return {row[1] for row in bind.exec_driver_sql(f'pragma table_info("{table}")')}+++def _tables(bind) -> set[str]:+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}+++def upgrade() -> None:+ bind = op.get_bind()+ if "agent_sessions" not in _tables(bind):+ return+ if "agent_status" in _columns(bind, "agent_sessions"):+ return++ # NOT NULL with a server default so existing rows backfill to ``idle``+ # without a separate update.+ op.add_column(+ "agent_sessions",+ sa.Column("agent_status", sa.String(), nullable=False, server_default="idle"),+ )+++def downgrade() -> None:+ bind = op.get_bind()+ if "agent_sessions" in _tables(bind) and "agent_status" in _columns(bind, "agent_sessions"):+ op.drop_column("agent_sessions", "agent_status")diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 6594dba23..08547ecb1 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -224,6 +224,18 @@ PENDING_TYPE = "pending"# Ephemeral types that must never count as inbox activity / conversation.NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE)+# The transcript-visible types — the SINGLE source of truth shared by the+# history fetch (``list_session_messages``) AND the live ``message.new`` publish+# gate, so what a page loads and what it receives over the stream are identical.+# Excludes the agent's process log (``assistant`` / ``tool_call``) and ``system``+# (which isn't persisted at all). Harness-triggered prompts are ``user``, so they+# are included. ``show_page`` transcript marks are kept via a metadata-source+# override in the fetch even though their row type is ``assistant``. ``error`` is a+# terminal FAILED result (turned the dot red): shown in the conversation like any+# terminal message, but the unread queries below stay ``result``-only so a failure+# is not counted as an unread agent reply.+TRANSCRIPT_TYPES = ("user", "result", "notify", "error")+def enqueue_queued(conn: Connection,@@ -465,11 +477,12 @@ def list_inbox_sessions(latest_any = select(any_ranked).where(any_ranked.c.rn == 1).subquery()# Rank agent messages by recency → latest agent reply = preview (also proves- # eligibility). Include ``notify`` as well as ``result``: a turn that FAILS- # before producing any result persists only a terminal ``notify``, and that- # failed conversation must still surface in the inbox (with its error) rather- # than disappear once the user leaves the Chat page (Codex P2). Unread counts- # below stay result-only — a failure notify isn't an unread reply.+ # eligibility). Include ``notify`` + ``error`` as well as ``result``: a turn+ # that FAILS persists a terminal ``error`` (or, for an interrupt/info, a+ # ``notify``), and that failed conversation must still surface in the inbox+ # (with its error) rather than disappear once the user leaves the Chat page+ # (Codex P2). Unread counts below stay result-only — a failure isn't an unread+ # reply.agent_ranked = (select(m.c.session_id.label("session_id"),@@ -482,7 +495,7 @@ def list_inbox_sessions(.label("rn"),).where(m.c.session_id.is_not(None))- .where(m.c.type.in_(("result", "notify")))+ .where(m.c.type.in_(("result", "notify", "error"))))if platform is not None:agent_ranked = agent_ranked.where(m.c.platform == platform)diff --git a/storage/models.py b/storage/models.pyindex 9876f9f9e..efd85d625 100644--- a/storage/models.py+++ b/storage/models.py@@ -116,6 +116,11 @@ agent_sessions = Table(Column("native_session_id", Text, nullable=False),Column("title", Text, nullable=True),Column("status", String, nullable=False),+ # Live agent-runtime status, distinct from the lifecycle ``status``+ # (active/archived). One of ``idle`` / ``running`` / ``failed`` —+ # ``running`` while a turn is in flight, ``failed`` when the most recent+ # turn errored, ``idle`` otherwise. Drives the workbench sidebar status dot.+ Column("agent_status", String, nullable=False, server_default="idle"),Column("metadata_json", Text, nullable=False),Column("created_at", String, nullable=False),Column("updated_at", String, nullable=False),diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 29dec3186..1e9dd4a15 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -62,6 +62,9 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:"model": row.get("model"),"reasoning_effort": row.get("reasoning_effort"),"status": row.get("status"),+ # Live agent-runtime status (idle/running/failed), separate from the+ # lifecycle ``status``. Older rows predating the column read as ``idle``.+ "agent_status": row.get("agent_status") or "idle","workdir": row.get("workdir"),# The reserved native-session anchor (workbench sessions self-anchor to# their id). Dispatch carries it so resume binds by the stored anchor@@ -197,6 +200,7 @@ def create_session(native_session_id="",title=title.strip() if (title or "").strip() else None,status="active",+ agent_status="idle",metadata_json=json.dumps(metadata_payload),created_at=now,updated_at=now,@@ -314,3 +318,47 @@ def touch_session(conn: Connection, session_id: str) -> None:.where(agent_sessions.c.id == session_id).values(last_active_at=_utc_now_iso(), updated_at=_utc_now_iso()))+++VALID_AGENT_STATUSES = ("idle", "running", "failed")+++def set_agent_status(conn: Connection, session_id: str, status: str) -> bool:+ """Set a session's live agent-runtime status (idle/running/failed).++ Returns ``True`` when the stored value actually changed, so the caller can+ skip a redundant ``session.status`` broadcast (and the write) when the dot+ colour wouldn't move. Unknown status / missing session is a no-op (False).+ Deliberately does NOT bump ``updated_at`` — a status flip is not a content+ edit and must not re-rank the session list.+ """++ if status not in VALID_AGENT_STATUSES:+ return False+ current = conn.execute(+ select(agent_sessions.c.agent_status).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ if current is None or current == status:+ return False+ conn.execute(+ update(agent_sessions).where(agent_sessions.c.id == session_id).values(agent_status=status)+ )+ return True+++def reset_running_agent_status(conn: Connection) -> int:+ """Reset every ``running`` session to ``idle`` (startup crash recovery).++ No turn survives a controller restart, so a ``running`` left in the table+ is stale. Returns the number of rows reset. The browser reconciles the reset+ by refetching sessions when its inbox-event stream (re)connects, NOT from a+ broadcast — this runs in ``Controller.__init__`` before any event subscriber+ exists, so a broadcast here would be dropped.+ """++ result = conn.execute(+ update(agent_sessions)+ .where(agent_sessions.c.agent_status == "running")+ .values(agent_status="idle")+ )+ return result.rowcount or 0diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex 59c94cc8b..43ab68202 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -66,6 +66,9 @@ class _StubController:get_session_info=lambda context: ("base-1", "/tmp/workdir", "base-1:/tmp/workdir"))self.resolve_agent_for_context = AsyncMock(return_value="codex")+ # Outbound status chokepoint: a handled (auth) recovery settles the failed+ # turn by emitting a terminal error result through here.+ self.emit_agent_message = AsyncMock()def get_im_client_for_context(self, context):return self.im_client@@ -156,14 +159,51 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):_, text, keyboard = controller.im_client.sent_button_messages[0]self.assertIn("401 Unauthorized", text)self.assertEqual(keyboard.buttons[0][0].callback_data, "auth_setup:codex")- # The recovery text is also persisted as a durable notify (the single home- # for it) so the web Chat shows the error + reset instruction, not just the- # transient button payload (Codex P2). Same composed text that was sent.+ # The transient IM message references the inline reset button.+ self.assertIn("button", text.lower())+ # A durable notify is ALSO persisted (the single home for it) so the web Chat+ # shows the error + reset instruction, not just the transient button payload.+ # But the durable row has NO inline button, so the persisted copy must be+ # BUTTON-FREE and point at the cross-platform `/setup` command instead of+ # "the button below" (a dangling instruction on the workbench) (Codex P2).persist.assert_called_once()persisted_ctx, persisted_kind, persisted_text = persist.call_args.args[:3]self.assertEqual(persisted_kind, "notify")- self.assertEqual(persisted_text, text)self.assertIn("401 Unauthorized", persisted_text)+ self.assertIn("/setup codex", persisted_text) # actionable without a button+ self.assertNotIn("button", persisted_text.lower()) # no dangling button reference++ async def test_maybe_emit_auth_recovery_message_settles_turn_for_auth_error(self):+ # An AUTH error is handled here (reset button + persisted notify). The+ # recovery message is a button row, not a result, so this settles the+ # failed turn through the OUTBOUND chokepoint: a terminal error result+ # that turns the dot red + releases the SSE waiter.+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")++ with patch("core.message_mirror.persist_agent_message"):+ handled = await service.maybe_emit_auth_recovery_message(+ context, "codex", "❌ Codex error: 401 Unauthorized"+ )++ self.assertTrue(handled)+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)++ async def test_maybe_emit_auth_recovery_message_defers_non_auth_error_to_caller(self):+ # A NON-auth terminal error returns False: the calling backend emits its+ # OWN terminal error result (which settles the dot via the same outbound+ # chokepoint), so this method must NOT also settle it here.+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")++ handled = await service.maybe_emit_auth_recovery_message(+ context, "codex", "RuntimeError: connection reset by peer"+ )++ self.assertFalse(handled) # not an auth error → no recovery button+ controller.emit_agent_message.assert_not_awaited()async def test_handle_process_text_emits_codex_link_once_url_and_code_exist(self):controller = _StubController()diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.pyindex bf53a9d4e..a28a4f69e 100644--- a/tests/test_agent_silent_result.py+++ b/tests/test_agent_silent_result.py@@ -18,7 +18,7 @@ class _StubController:self.settings_manager = SimpleNamespace(sessions=None)self.messages = []- async def emit_agent_message(self, context, message_type, text, parse_mode="markdown"):+ async def emit_agent_message(self, context, message_type, text, parse_mode="markdown", *, is_error=False, level="normal"):self.messages.append((message_type, text, parse_mode))@@ -44,21 +44,21 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(controller.messages, [("result", "", "markdown")])- async def test_no_visible_result_with_duration_hidden_releases_streaming_turn(self):- # show_duration off + empty result/suffix => emit_agent_message is skipped,- # so nothing would release the web-Chat streaming turn; it must be marked- # complete instead of hanging to the 600s timeout (Codex P2).+ async def test_no_visible_result_with_duration_hidden_settles_via_outbound(self):+ # show_duration off + empty result/suffix is still a TERMINAL turn: it is+ # settled through the OUTBOUND status chokepoint — an empty terminal result+ # emit (→ dot idle/failed + releases the web-Chat stream) instead of being+ # left to hang to the 600s timeout (Codex P2).controller = _StubController()controller.config = SimpleNamespace(show_duration=False)- marked = []- controller.mark_turn_complete = lambda ctx: marked.append(ctx)agent = _StubAgent(controller)context = MessageContext(user_id="U1", channel_id="C1", platform="avibe")await agent.emit_result_message(context, "", subtype="success", duration_ms=0)- self.assertEqual(controller.messages, [], "no visible text => no result emit")- self.assertEqual(len(marked), 1, "the streaming turn must be released")+ # An empty terminal result is emitted (no visible text); the dispatcher's+ # result path settles the dot + releases the stream.+ self.assertEqual(controller.messages, [("result", "", "markdown")])class AgentSessionIdContextTests(unittest.TestCase):diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex a319d48b9..8c02886fb 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -3,7 +3,7 @@ import sysimport unittestfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -536,6 +536,37 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once()agent.session_handler.handle_session_error.assert_not_awaited()+ async def test_receiver_non_auth_error_settles_dot_and_persists(self):+ # A non-auth receiver error (connection loss, concurrent read, …) is NOT+ # handled by the OAuth-recovery path, so it must still settle the terminal+ # turn through the OUTBOUND chokepoint (empty error result → dot red + SSE+ # release) AND persist a durable error notify for the web Chat — instead of+ # hanging running to the 600s stream timeout and then settling idle (Codex P2).+ controller = _StubController()+ controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=False)+ controller.emit_agent_message = AsyncMock()+ controller._get_session_key = lambda context: "telegram::user::U1"+ agent = ClaudeAgent(controller)+ agent.session_handler = SimpleNamespace(handle_session_error=AsyncMock())+ agent._clear_pending_reactions = AsyncMock()+ context = SimpleNamespace()++ class _FailingClient:+ def receive_messages(self):+ async def _iterate():+ raise RuntimeError("Connection lost")+ yield # pragma: no cover++ return _iterate()++ with patch("core.message_mirror.persist_agent_message") as persist:+ await agent._receive_messages(_FailingClient(), "session-1", "/tmp/work", context)++ agent.session_handler.handle_session_error.assert_awaited_once()+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)+ persist.assert_called_once()+ self.assertEqual(persist.call_args.args[1], "notify")+async def test_result_auth_error_prefers_oauth_recovery_message(self):controller = _StubController()controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex ac5e44f52..37a76a987 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -136,7 +136,40 @@ def test_task_add_rejects_disabled_platform_even_with_credentials_present() -> Nassert result == 1assert payload["code"] == "unsupported_platform"- assert payload["details"]["configured_platforms"] == ["slack"]+ # ``avibe`` (the web workbench) is always an available task platform; the+ # disabled discord platform is still correctly rejected.+ assert payload["details"]["configured_platforms"] == ["avibe", "slack"]+++def test_supported_task_platforms_always_includes_avibe() -> None:+ # The web workbench (avibe) is always available, even when only IM platforms+ # are configured — so a scheduled task created from a workbench session isn't+ # rejected as "unsupported platform".+ config = _configured_v2({"slack"})+ with patch("vibe.cli._ensure_config", return_value=config):+ assert "avibe" in cli._supported_task_platforms()+++def test_task_add_rejects_avibe_session_key() -> None:+ # avibe passes the platform gate but a bare session KEY has no agent session+ # id, so the reply couldn't attach to a workbench session — must be rejected+ # (target workbench sessions by --session-id instead).+ args = _parse_task_add(+ [+ "--session-key",+ "avibe::channel::ses3chKBjP5hy",+ "--cron",+ "0 * * * *",+ "--message",+ "hello",+ ]+ )+ config = _configured_v2({"slack"})+ with patch("vibe.cli._ensure_config", return_value=config):+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "avibe_requires_session_id"def test_task_help_describes_session_id_guidance(capsys) -> None:diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 535cd6d13..a5fbf8670 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -675,10 +675,13 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent._event_handler.clear_pending.assert_not_called()agent._remove_ack_reaction.assert_awaited_once_with(request)+ # The failed interrupt is a terminal failure → emitted as an ERROR result+ # (the outbound status chokepoint turns the dot red), not a bare notify.agent.controller.emit_agent_message.assert_awaited_once_with(request.context,- "notify",+ "result","❌ Failed to interrupt previous Codex turn: interrupt failed",+ is_error=True,)async def test_handle_message_recovers_from_broken_transport_once(self):diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.pyindex 1c2387aba..da5acb2a5 100644--- a/tests/test_codex_event_handler.py+++ b/tests/test_codex_event_handler.py@@ -167,8 +167,9 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):)agent.controller.emit_agent_message.assert_awaited_once_with(request.context,- "notify",+ "result","❌ Codex turn failed: unexpected status 401 Unauthorized:",+ is_error=True,)await handler._on_turn_completed(@@ -207,10 +208,13 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):"codex","❌ Codex turn failed: fallback message",)+ # Terminal failure → error RESULT (the outbound status chokepoint turns+ # the dot red), not a bare notify.agent.controller.emit_agent_message.assert_awaited_once_with(request.context,- "notify",+ "result","❌ Codex turn failed: fallback message",+ is_error=True,)agent._remove_ack_reaction.assert_awaited_once_with(request)diff --git a/tests/test_controller_agent_status.py b/tests/test_controller_agent_status.pynew file mode 100644index 000000000..00f160484--- /dev/null+++ b/tests/test_controller_agent_status.py@@ -0,0 +1,79 @@+"""Unit tests for the workbench sidebar-dot status, driven by EXACTLY two+chokepoints (no per-path / per-backend instrumentation):++* inbound — ``AgentService.handle_message`` marks an avibe session ``running``.+* outbound — ``MessageDispatcher.emit_agent_message`` settles a terminal+ ``result`` to ``idle`` (or ``failed`` when ``is_error``); see+ ``test_message_dispatcher_status``.++This file pins the inbound point + the avibe gating in+``Controller._session_id_from_context`` (only workbench turns carry a session id,+so IM/CLI turns never touch the dot).+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.controller import Controller+from modules.agents.service import AgentService+++def _ctx(session_id, *, platform="avibe"):+ spec = {"agent_session_id": session_id} if session_id else {}+ return SimpleNamespace(platform=platform, platform_specific=spec)+++def test_session_id_from_context_reads_agent_session_id():+ assert Controller._session_id_from_context(_ctx("ses-1")) == "ses-1"+ # IM / CLI turns carry no workbench session id → resolve to None (dot skipped).+ assert Controller._session_id_from_context(SimpleNamespace(platform_specific={})) is None+ assert Controller._session_id_from_context(SimpleNamespace(platform_specific=None)) is None+ assert Controller._session_id_from_context(None) is None+++def _service_with_capture():+ calls: list = []+ controller = SimpleNamespace(+ _session_id_from_context=staticmethod(Controller._session_id_from_context).__func__,+ set_agent_status=lambda sid, status: calls.append((sid, status)),+ )+ service = AgentService(controller)+ return service, calls+++def test_inbound_marks_running_for_avibe_turn():+ service, calls = _service_with_capture()+ dispatched = []++ async def _handle(req):+ dispatched.append(req)++ service.agents["claude"] = SimpleNamespace(name="claude", handle_message=_handle)+ request = SimpleNamespace(context=_ctx("ses-abc"))++ asyncio.run(service.handle_message("claude", request))++ # Inbound chokepoint flips the dot green, then dispatches to the backend.+ assert calls == [("ses-abc", "running")]+ assert dispatched == [request]+++def test_inbound_skips_non_avibe_turn():+ service, calls = _service_with_capture()++ async def _handle(req):+ pass++ service.agents["claude"] = SimpleNamespace(name="claude", handle_message=_handle)+ request = SimpleNamespace(context=_ctx(None, platform="slack"))++ asyncio.run(service.handle_message("claude", request))++ # IM turn carries no workbench session id → the dot is never touched.+ assert calls == []diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.pyindex edbf18d81..568ea45b5 100644--- a/tests/test_controller_dispatch_loop.py+++ b/tests/test_controller_dispatch_loop.py@@ -50,7 +50,7 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:controller = Controller.__new__(Controller)loop = asyncio.new_event_loop()controller._loop = loop- stopped: dict[str, bool] = {"watch": False, "tasks": False}+ stopped: dict[str, bool] = {"watch": False, "tasks": False, "runtime": False}class _Stopper:def __init__(self, key: str) -> None:@@ -61,6 +61,7 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:controller.scheduled_task_service = _Stopper("tasks")controller.watch_service = _Stopper("watch")+ controller.runtime_command_watcher = _Stopper("runtime")controller.update_checker = type("UpdateChecker", (), {"stop": lambda self: None})()controller.receiver_tasks = {}controller.im_client = None@@ -73,3 +74,4 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:assert stopped["tasks"] is Trueassert stopped["watch"] is True+ assert stopped["runtime"] is Truediff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex a55388ad8..c92235cbe 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -50,6 +50,8 @@ def test_public_surface_is_stable():"create_session","get_session","list_sessions",+ "reset_running_agent_status",+ "set_agent_status","touch_session","update_session",# Legacy IM-style reservation helpers added in C2 for the CLI:@@ -73,6 +75,8 @@ def test_each_workbench_function_delegates_to_storage():"create_session","get_session","list_sessions",+ "reset_running_agent_status",+ "set_agent_status","touch_session","update_session",):@@ -173,6 +177,62 @@ def test_update_session_present_null_clears_model_and_effort(isolated_state):assert kept["title"] == "renamed"+# --- Live agent-runtime status (sidebar dot) --------------------------+++def test_new_session_agent_status_defaults_idle(isolated_state):+ """A freshly created session starts idle, and the payload exposes it."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ created = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")+ assert created["agent_status"] == "idle"+ with engine.connect() as conn:+ page = sessions_service.list_sessions(conn, scope_id=scope_id)+ assert page["sessions"][0]["agent_status"] == "idle"+++def test_set_agent_status_changes_and_reports_delta(isolated_state):+ """set_agent_status persists the value and returns True only on a real change."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]+ assert sessions_service.set_agent_status(conn, sid, "running") is True+ # Idempotent: same value reports no change (so the caller skips the broadcast).+ assert sessions_service.set_agent_status(conn, sid, "running") is False+ assert sessions_service.set_agent_status(conn, sid, "failed") is True+ with engine.connect() as conn:+ assert sessions_service.get_session(conn, sid)["agent_status"] == "failed"+++def test_set_agent_status_rejects_unknown_value(isolated_state):+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]+ assert sessions_service.set_agent_status(conn, sid, "bogus") is False+ assert sessions_service.set_agent_status(conn, "ses-missing", "running") is False+ with engine.connect() as conn:+ assert sessions_service.get_session(conn, sid)["agent_status"] == "idle"+++def test_reset_running_agent_status_clears_only_running(isolated_state):+ """Startup recovery: stale ``running`` → ``idle``; failed/idle untouched."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ running = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]+ failed = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="claude")["id"]+ sessions_service.set_agent_status(conn, running, "running")+ sessions_service.set_agent_status(conn, failed, "failed")+ reset = sessions_service.reset_running_agent_status(conn)+ assert reset == 1+ with engine.connect() as conn:+ assert sessions_service.get_session(conn, running)["agent_status"] == "idle"+ assert sessions_service.get_session(conn, failed)["agent_status"] == "failed"++def test_update_session_pins_backend_after_native_bound(isolated_state):"""A session is locked to its backend once it has a native conversation:same-backend agent/model changes are allowed; a cross-backend switch raisesdiff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex a748faae6..509fa31af 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -18,14 +18,14 @@ from __future__ import annotationsimport asyncioimport sysfrom pathlib import Path-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import ANY, AsyncMock, MagicMockimport httpxsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core import internal_server-from core.services.dispatch import dispatch_turn+from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turnfrom modules.im import MessageContext@@ -337,6 +337,248 @@ def test_dispatch_async_starts_turn_and_returns_202(monkeypatch, tmp_path):assert events == ["turn.start", "turn.end"], "publishes session turn lifecycle on the bus"+def _run_timeout_dispatch(monkeypatch, tmp_path, *, stop_confirmed: bool):+ """Drive the 600s stuck-turn timeout branch: patch dispatch_turn to flag the+ context as timed-out, set the stop outcome. Returns ``(controller, app, events)``+ where ``events`` are the bus event names published while the runner settled."""+ from core import inbox_events+ from storage.importer import ensure_sqlite_state++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()++ controller = _build_controller_double()+ controller.command_handler.handle_stop = AsyncMock(return_value=stop_confirmed)+ controller.emit_agent_message = AsyncMock()++ async def _timeout_dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ # Simulate the 600s no-result wait: the dispatch machinery flags the context+ # (and stamps a turn_token, as the real streaming dispatch_turn does).+ ctx.platform_specific = dict(ctx.platform_specific or {})+ ctx.platform_specific["turn_timed_out"] = True+ ctx.platform_specific.setdefault("turn_token", "stuck-token")++ monkeypatch.setattr(internal_server, "dispatch_turn", _timeout_dispatch)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)+ events: list[str] = []+ # Captured INSIDE the loop — reading in_flight after asyncio.run() would be wrong,+ # since loop teardown cancels the pending sentinel (its finally pops the slot).+ captured: dict = {}++ async def _go():+ sub_id, queue = inbox_events.bus.subscribe()+ try:+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_t", "text": "hi"})+ # handle_stop runs early in the runner's finally; wait for it, then let the+ # rest of the finally (stuck-sentinel setup / idle emit) settle.+ for _ in range(100):+ if controller.command_handler.handle_stop.await_count > 0:+ break+ await asyncio.sleep(0.02)+ await asyncio.sleep(0.05)+ entry = app.state.in_flight_dispatches.get("ses_t")+ captured["present"] = entry is not None+ captured["blocked"] = entry is not None and not entry[0].done()+ while True:+ try:+ evt, _data = queue.get_nowait()+ events.append(evt)+ except asyncio.QueueEmpty:+ break+ finally:+ inbox_events.bus.unsubscribe(sub_id)+ return resp++ resp = asyncio.run(_go())+ assert resp.status_code == 202+ controller.command_handler.handle_stop.assert_awaited_once()+ return controller, events, captured+++def test_dispatch_async_timeout_settles_idle_when_stop_confirmed(monkeypatch, tmp_path):+ # Timeout + the stuck backend was actually interrupted (handle_stop → True):+ # clear the dot to idle (empty non-error result), free the slot, end the turn.+ controller, events, captured = _run_timeout_dispatch(monkeypatch, tmp_path, stop_confirmed=True)+ controller.emit_agent_message.assert_awaited_once_with(ANY, "result", "")+ assert captured["present"] is False # slot freed → new send can start+ assert "turn.end" in events+++def test_dispatch_async_timeout_keeps_session_blocked_and_recoverable_when_stop_unconfirmed(monkeypatch, tmp_path):+ # Timeout but the interrupt could NOT be applied (handle_stop → False): the backend+ # may still be producing output. Keep the session in-flight via a SELF-HEALING+ # sentinel task (not a never-resolving future) so a new Chat send enqueues, and+ # DEFER turn.end so the Chat keeps its Stop control to recover the turn (Codex P2).+ controller, events, captured = _run_timeout_dispatch(monkeypatch, tmp_path, stop_confirmed=False)+ # No premature terminal emit while the turn is still (maybe) running.+ controller.emit_agent_message.assert_not_awaited()+ # Session kept in-flight by a not-done sentinel task.+ assert captured["blocked"] is True+ # turn.end is DEFERRED until the slot frees → Chat keeps working + Stop.+ assert "turn.end" not in events+++def test_dispatch_async_timeout_sentinel_releases_on_late_result(monkeypatch, tmp_path):+ # The stuck sentinel must RESOLVE when the backend finishes late: a late terminal+ # result fires the registered sink's done_event, releasing the slot + publishing+ # turn.end — instead of blocking the session forever (Codex P2).+ from core import inbox_events+ from storage.importer import ensure_sqlite_state++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()++ controller = _build_controller_double()+ controller.command_handler.handle_stop = AsyncMock(return_value=False) # unconfirmed → stuck+ controller.emit_agent_message = AsyncMock()++ async def _timeout_dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ ctx.platform_specific = dict(ctx.platform_specific or {})+ ctx.platform_specific["turn_timed_out"] = True+ ctx.platform_specific.setdefault("turn_token", "stuck-token")++ monkeypatch.setattr(internal_server, "dispatch_turn", _timeout_dispatch)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ captured: dict = {}++ async def _go():+ sub_id, queue = inbox_events.bus.subscribe()+ try:+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ await client.post("/internal/dispatch_async", json={"session_id": "ses_t", "text": "hi"})+ # Wait for the sentinel to be installed + its recovery sink registered.+ for _ in range(100):+ entry = app.state.in_flight_dispatches.get("ses_t")+ if entry is not None and not entry[0].done() and controller.active_turn_sinks:+ break+ await asyncio.sleep(0.02)+ # Simulate the backend finishing late: fire the registered sink's done_event.+ for sink in list(controller.active_turn_sinks.values()):+ sink["done_event"].set()+ # The sentinel resolves → frees the slot + publishes turn.end. Capture the+ # release INSIDE the loop (after asyncio.run, teardown would free it anyway).+ for _ in range(100):+ if "ses_t" not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)+ captured["released"] = "ses_t" not in app.state.in_flight_dispatches+ events: list[str] = []+ while True:+ try:+ evt, _data = queue.get_nowait()+ events.append(evt)+ except asyncio.QueueEmpty:+ break+ captured["events"] = events+ finally:+ inbox_events.bus.unsubscribe(sub_id)++ asyncio.run(_go())+ assert captured["released"] is True # the late result (not loop teardown) freed the slot+ assert "turn.end" in captured["events"]+ # A late result settled the dot itself, so the sentinel does NOT emit a failed result.+ controller.emit_agent_message.assert_not_awaited()+++def test_send_now_during_stuck_sentinel_flushes_queue(monkeypatch, tmp_path):+ """A ``send-now`` that cuts in while a session is held by the stuck-turn+ SENTINEL (timed-out + interrupt-unconfirmed) must still drain the queue: the+ sentinel's release honors the SAME ``flush_on_cancel`` contract as the normal+ runner finally. Before the fix the sentinel only popped ``in_flight`` ++ published ``turn.end``, so the queued message stayed queued forever and the+ stale ``flush_on_cancel`` marker could wrongly flush a later turn (Codex P2).++ The sentinel is reached when the first turn times out and the backend+ interrupt is unconfirmed. ``send-now`` then sets ``flush_on_cancel`` and+ cancels the sentinel; its finally must flush + clear the marker.+ """+ from core.services import sessions as sessions_service+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_stuck_flush", now="2026-06-02T00:00:00Z"+ )+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ session_id = session["id"]++ controller = _build_controller_double()+ # The first ``handle_stop`` is the runner's own timeout interrupt — UNCONFIRMED+ # (False) so the turn becomes the stuck sentinel. The second is ``send-now``'s+ # interrupt — CONFIRMED (True) so it proceeds to cancel the sentinel and flush.+ controller.command_handler.handle_stop = AsyncMock(side_effect=[False, True])+ controller.emit_agent_message = AsyncMock()++ dispatched: list[str] = []++ async def _dispatch(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ dispatched.append(text)+ if text == "hi":+ # First turn: simulate the 600s no-result timeout. The runner finally+ # then interrupts (handle_stop → False, unconfirmed) → installs the+ # stuck sentinel that holds in_flight.+ ctx.platform_specific = dict(ctx.platform_specific or {})+ ctx.platform_specific["turn_timed_out"] = True+ ctx.platform_specific.setdefault("turn_token", "stuck-token")+ return+ # The flush turn for the queued message: complete normally so it doesn't+ # spin up a second sentinel — release the held turn like a real result emit.+ controller.mark_turn_complete(ctx)++ monkeypatch.setattr(internal_server, "dispatch_turn", _dispatch)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)+ flush_on_cancel = app.state.flush_on_cancel+ captured: dict = {}++ async def _go():+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ # Start the first turn; it times out + leaves an unconfirmed-stop sentinel.+ await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "hi"})+ # Wait for the stuck sentinel to be installed (in_flight holds a not-done task).+ for _ in range(200):+ entry = app.state.in_flight_dispatches.get(session_id)+ if entry is not None and not entry[0].done() and controller.active_turn_sinks:+ break+ await asyncio.sleep(0.02)+ # Queue a message while the session is stuck, then send-now to cut in.+ with engine.begin() as conn:+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="cut in")+ resp = await client.post(f"/internal/send-now/{session_id}")+ captured["send_now_status"] = resp.json().get("status")+ # The cancelled sentinel's finally flushes → a turn runs for "cut in".+ for _ in range(200):+ if "cut in" in dispatched and session_id not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)+ # Capture INSIDE the loop — after asyncio.run, teardown would clear state.+ captured["flush_on_cancel_after"] = session_id in flush_on_cancel+ captured["in_flight_after"] = session_id in app.state.in_flight_dispatches++ asyncio.run(_go())+ assert captured["send_now_status"] == "interrupted", "send-now cut into the stuck sentinel"+ # The queued message ran as a turn (the sentinel's cancellation honored flush_on_cancel).+ assert "cut in" in dispatched, "the stuck-sentinel cancellation flushed the queued message"+ assert captured["flush_on_cancel_after"] is False, "the flush_on_cancel marker was cleared"+ assert captured["in_flight_after"] is False, "the slot freed after the flushed turn settled"+ with engine.connect() as conn:+ assert messages_service.list_queued(conn, session_id) == [], "the queue drained"+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))+ assert [m["text"] for m in transcript["messages"]] == ["cut in"], "the flush persisted the merged user row"++def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):"""A dispatch for a session that already has a turn in flight ENQUEUES(send-while-busy) instead of refusing: it atomically re-types the@@ -579,3 +821,196 @@ def test_dispatch_turn_registers_sink_for_dispatcher_hook():asyncio.run(dispatch_turn(controller, ctx, "ping", on_chunk=on_chunk))assert seen["on_chunk"] is on_chunkassert controller.get_turn_sink("avibe::C") is None, "sink cleaned up after the turn"+++# ---------------------------------------------------------------------+# Scheduled / watch turn gate (controller.session_turn_gate)+# ---------------------------------------------------------------------+++def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):+ """An IDLE scheduled run goes through ``_run_turn`` like a Chat turn: it+ registers ``in_flight`` + publishes ``turn.start`` / ``turn.end`` on the bus+ (so the Chat page shows the working indicator + Stop works) and calls+ ``dispatch_turn`` with ``source=SOURCE_SCHEDULED`` and the no-op chunk sink —+ NOT ``on_chunk=None``. 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 keeps ``in_flight`` populated+ for the scheduled turn's whole lifetime so a Chat send can't preempt a+ still-running scheduled turn (Codex P2)."""+ from core import inbox_events+ from storage.importer import ensure_sqlite_state++ # submit_scheduled reads the queue (idle → empty-queue happy path), so it+ # needs an initialized state DB.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()++ captured: dict = {}+ started = asyncio.Event()++ async def _fake_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ captured["source"] = source+ captured["on_chunk"] = on_chunk+ captured["text"] = text+ captured["in_flight_while_running"] = "ses_sched" in app.state.in_flight_dispatches+ started.set()++ monkeypatch.setattr(internal_server, "dispatch_turn", _fake_dispatch_turn)++ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ ctx = MessageContext(user_id="workbench", channel_id="ses_sched", platform="avibe")++ async def _go():+ sub_id, queue = inbox_events.bus.subscribe()+ events: list[str] = []+ try:+ await controller.session_turn_gate.submit_scheduled("ses_sched", ctx, "digest please")+ await asyncio.wait_for(started.wait(), timeout=3)+ for _ in range(100):+ if "ses_sched" not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)+ for _ in range(2):+ try:+ evt, _data = await asyncio.wait_for(queue.get(), timeout=1.0)+ events.append(evt)+ except asyncio.TimeoutError:+ break+ finally:+ inbox_events.bus.unsubscribe(sub_id)+ return events++ events = asyncio.run(_go())+ assert captured["source"] == SOURCE_SCHEDULED, "scheduled run dispatches on the scheduler path"+ # A scheduled run passes the no-op chunk SINK (callable, NOT None) so dispatch_turn+ # HOLDS the turn open to its terminal result — same as a Chat turn — instead of an+ # async backend returning at prompt-submit and freeing the slot (Codex P2). The sink+ # discards chunks; the reply still surfaces over ``message.new``, not a live stream.+ assert captured["on_chunk"] is not None, "scheduled run holds the turn open via the no-op sink"+ assert callable(captured["on_chunk"]), "the held-open sink is the no-op chunk callable"+ assert captured["text"] == "digest please"+ assert captured["in_flight_while_running"] is True, "registered in_flight (Stop works) while running"+ assert events == ["turn.start", "turn.end"], "publishes the session turn lifecycle on the bus"+ assert "ses_sched" not in app.state.in_flight_dispatches, "slot released after the turn"+++def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch, tmp_path):+ """A scheduled run for a session that already has a turn in flight ENQUEUES a+ harness-attributed ``queued`` row (so it runs AFTER the active turn via the+ existing flush) instead of preempting it — and it never starts a competing+ turn nor disturbs the in-flight Chat task (Codex P2)."""+ from core.services import sessions as sessions_service+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_sched_busy", now="2026-05-31T00:00:00Z"+ )+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ session_id = session["id"]++ # A scheduled run must NEVER reach dispatch_turn while busy — a call here fails+ # the test loudly.+ 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)++ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ ctx = MessageContext(user_id="workbench", channel_id=session_id, platform="avibe")++ async def _go():+ async def _busy():+ await asyncio.sleep(60)++ chat_task = asyncio.create_task(_busy())+ chat_ctx = MessageContext(user_id="U", channel_id="C", platform="avibe")+ app.state.in_flight_dispatches[session_id] = (chat_task, chat_ctx)+ try:+ await controller.session_turn_gate.submit_scheduled(session_id, ctx, "scheduled while busy")+ finally:+ entry = app.state.in_flight_dispatches.get(session_id)+ # The in-flight Chat turn is undisturbed: same task object, not cancelled.+ assert entry is not None and entry[0] is chat_task and not chat_task.done()+ chat_task.cancel()+ return chat_ctx++ chat_ctx = asyncio.run(_go())+ controller.message_handler.handle_user_message.assert_not_awaited()+ with engine.connect() as conn:+ queued = messages_service.list_queued(conn, session_id)+ # The queued row is drainable + carries the session's scope and harness+ # attribution; it stays OUT of the user transcript.+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))+ assert [q["text"] for q in queued] == ["scheduled while busy"]+ assert queued[0]["scope_id"] == scope_id+ assert queued[0]["author"] == "harness"+ assert transcript["messages"] == []+++def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):+ """Stop works for a scheduled run: because the run goes through ``_run_turn``+ it registers the scheduled ``context`` in ``in_flight``, so+ ``/internal/cancel/{session_id}`` finds the task + reuses the IM ``/stop`` path+ to interrupt the backend (mirrors the Chat cancel test)."""+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_sched_cancel", now="2026-05-31T00:00:00Z"+ )+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ session_id = session["id"]++ started = asyncio.Event()++ async def _long_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):+ started.set()+ await asyncio.sleep(5) # held until the test cancels it++ monkeypatch.setattr(internal_server, "dispatch_turn", _long_dispatch_turn)++ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)+ ctx = MessageContext(user_id="workbench", channel_id=session_id, platform="avibe")++ async def _go():+ # Start the scheduled run in the background (it holds in_flight open).+ run = asyncio.create_task(controller.session_turn_gate.submit_scheduled(session_id, ctx, "scheduled run"))+ await asyncio.wait_for(started.wait(), timeout=3)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ resp = await client.post(f"/internal/cancel/{session_id}")+ for _ in range(200):+ if session_id not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)+ run.cancel()+ return resp++ resp = asyncio.run(_go())+ assert resp.status_code == 200+ assert resp.json()["status"] == "cancel_requested"+ # The cancel interrupted the backend through the IM /stop path with the+ # scheduled run's own context.+ controller.command_handler.handle_stop.assert_awaited_once()+ assert session_id not in app.state.in_flight_dispatches, "slot released after the scheduled run was stopped"diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 230475369..d89b2fa5b 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -281,5 +281,139 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(controller.session_handler.calls, [])+class _AvibeStatusController(_StubController):+ """avibe controller stub that records the sidebar-dot writes."""++ def __init__(self):+ super().__init__(platform="avibe")+ self.status_calls = []+ self.active_sink = None # set to {"turn_token": ...} to simulate a live turn++ @staticmethod+ def _session_id_from_context(context):+ return ((context.platform_specific or {}).get("agent_session_id")) or None++ def get_turn_sink(self, session_key):+ return self.active_sink++ def set_agent_status(self, session_id, status):+ self.status_calls.append((session_id, status))+++def _avibe_ctx():+ return MessageContext(+ user_id="U1",+ channel_id="ses-1",+ platform="avibe",+ platform_specific={"agent_session_id": "ses-1"},+ )+++class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):+ """The OUTBOUND status chokepoint: a terminal ``result`` settles the avibe dot+ (idle, or failed when ``is_error``); a ``notify`` is not terminal and leaves it."""++ async def test_terminal_result_settles_dot_idle(self):+ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(_avibe_ctx(), "result", "")+ self.assertEqual(controller.status_calls, [("ses-1", "idle")])++ async def test_terminal_error_result_settles_dot_failed(self):+ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(_avibe_ctx(), "result", "", is_error=True)+ self.assertEqual(controller.status_calls, [("ses-1", "failed")])++ async def test_notify_does_not_settle_dot(self):+ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(_avibe_ctx(), "notify", "fyi")+ self.assertEqual(controller.status_calls, [])++ async def test_superseded_turn_result_does_not_settle_dot(self):+ # A late result whose turn_token != the active sink's token (a stopped or+ # superseded turn) must NOT settle the dot for the new active turn.+ controller = _AvibeStatusController()+ controller.active_sink = {"turn_token": "new-turn"}+ dispatcher = ConsolidatedMessageDispatcher(controller)+ ctx = MessageContext(+ user_id="U1",+ channel_id="ses-1",+ platform="avibe",+ platform_specific={"agent_session_id": "ses-1", "turn_token": "old-turn"},+ )+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(ctx, "result", "", is_error=True)+ self.assertEqual(controller.status_calls, [])++ async def test_active_turn_token_match_settles_dot(self):+ # Same token (the live turn) → the dot settles normally.+ controller = _AvibeStatusController()+ controller.active_sink = {"turn_token": "turn-1"}+ dispatcher = ConsolidatedMessageDispatcher(controller)+ ctx = MessageContext(+ user_id="U1",+ channel_id="ses-1",+ platform="avibe",+ platform_specific={"agent_session_id": "ses-1", "turn_token": "turn-1"},+ )+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(ctx, "result", "")+ self.assertEqual(controller.status_calls, [("ses-1", "idle")])++ async def test_tokenless_result_does_not_settle_dot_when_live_turn_exists(self):+ # A live interactive turn registered a sink WITH a token; an older+ # scheduled/watch result arrives tokenless (scheduled runs register no sink).+ # It must NOT settle the live turn's dot — previously the guard fail-opened on+ # the absent token, so the stale result flipped the live turn to idle (Codex P2).+ controller = _AvibeStatusController()+ controller.active_sink = {"turn_token": "live-turn"}+ dispatcher = ConsolidatedMessageDispatcher(controller)+ ctx = MessageContext(+ user_id="U1",+ channel_id="ses-1",+ platform="avibe",+ platform_specific={"agent_session_id": "ses-1"}, # no turn_token (scheduled)+ )+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(ctx, "result", "")+ self.assertEqual(controller.status_calls, [])++ async def test_silent_result_settles_dot_but_suppresses_delivery(self):+ # ``level="silent"`` is the explicit visibility grade (orthogonal to type):+ # a terminal result still settles the dot + releases the stream, but is NOT+ # delivered or persisted — even with NON-EMPTY text. This is what an+ # intentional stop emits: the turn ends cleanly with no user-facing bubble,+ # replacing the old "fake invisibility via empty text" trick.+ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ message_id = await dispatcher.emit_agent_message(+ _avibe_ctx(), "result", "🛑 stopped", level="silent"+ )+ self.assertIsNone(message_id)+ self.assertEqual(controller.status_calls, [("ses-1", "idle")]) # dot still settles+ persist.assert_not_called() # never recorded in history+ self.assertEqual(controller.im_client.sent_messages, []) # no user-facing bubble++ async def test_silent_notify_is_not_terminal_and_suppressed(self):+ # A silent NON-result (notify) is not terminal: it neither settles the dot+ # nor is delivered/persisted.+ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ message_id = await dispatcher.emit_agent_message(+ _avibe_ctx(), "notify", "fyi", level="silent"+ )+ self.assertIsNone(message_id)+ self.assertEqual(controller.status_calls, [])+ persist.assert_not_called()+ self.assertEqual(controller.im_client.sent_messages, [])++if __name__ == "__main__":unittest.main()diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex a4c5b0eb1..c4ab33fa5 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -192,6 +192,11 @@ class _StubController:def update_thread_message_id(self, context):return None+ async def emit_agent_message(self, context, message_type, text, parse_mode="markdown", *, is_error=False, level="normal"):+ # Terminal error results settle the dot + release the SSE waiter via the+ # outbound chokepoint; a no-op here (these are IM turns, no workbench dot).+ return None+def get_im_client_for_context(self, context):return self.im_clientdiff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex 3c42f7fa5..a83a582e3 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -244,14 +244,15 @@ def test_persist_agent_publishes_message_and_inbox_for_avibe(isolated_state):assert len(agent_rows) == 1 and agent_rows[0]["type"] == "result"-def test_persist_agent_intermediate_streams_but_not_inbox(isolated_state):- """An intermediate ``assistant`` message DOES publish a session-scoped- ``message.new`` (the session/page stream carries every message), but must- NOT publish ``inbox.session.updated`` — inbox eligibility is result/notify- only, so a session whose newest agent row is a transient ``assistant`` (no- ``result`` / terminal ``notify`` yet) doesn't surface a card.+def test_persist_agent_intermediate_persisted_but_not_streamed(isolated_state):+ """An intermediate ``assistant`` (process-log) message is PERSISTED for+ history/debugging, but publishes NEITHER ``message.new`` NOR+ ``inbox.session.updated`` — the live stream carries only transcript types+ (user/result/notify), exactly matching what the history fetch returns, and+ process log is neither streamed nor inbox-eligible (user request)."""from core import inbox_events+ from storage import messages_serviceengine = create_sqlite_engine()now = "2026-05-30T12:00:00Z"@@ -285,26 +286,26 @@ def test_persist_agent_intermediate_streams_but_not_inbox(isolated_state):seen = []try:persist_agent_message(ctx, "assistant", "thinking out loud")- # First event is the session-stream message.new; there must be no- # second (inbox) event.- seen.append(await asyncio.wait_for(queue.get(), timeout=1.0))+ # No events at all — assistant is process log: not streamed, not inbox.with pytest.raises(asyncio.TimeoutError):- await asyncio.wait_for(queue.get(), timeout=0.05)+ await asyncio.wait_for(queue.get(), timeout=0.1)finally:inbox_events.bus.unsubscribe(sub_id)return seen- seen = asyncio.run(scenario())- assert [e[0] for e in seen] == ["message.new"]- assert seen[0][1]["type"] == "assistant"- assert seen[0][1]["session_id"] == "ses_noresult"+ asyncio.run(scenario())+ # ...but the row IS still persisted (for history / debugging).+ with engine.connect() as conn:+ every = messages_service.list_session_messages(conn, session_id="ses_noresult", types=("assistant",))+ assert [m["type"] for m in every["messages"]] == ["assistant"]-def test_persist_system_message_maps_to_assistant_not_notify(isolated_state):- """A canonical ``system`` (process/init log) persists as type ``assistant``,- NOT ``notify`` — so it stays process log and does NOT become inbox-eligible- (which would create a junk Inbox card before any real reply) (Codex P2)."""+def test_persist_system_message_is_not_persisted(isolated_state):+ """A canonical ``system`` message (init banner / status line — generated by+ us, not the agent) is NOT persisted at all and publishes nothing (user+ request). Replaces the earlier system→assistant mapping."""from core import inbox_events+ from storage import messages_serviceengine = create_sqlite_engine()now = "2026-05-30T12:00:00Z"@@ -325,19 +326,17 @@ def test_persist_system_message_maps_to_assistant_not_notify(isolated_state):async def scenario():sub_id, queue = inbox_events.bus.subscribe()- seen = []try:- persist_agent_message(ctx, "system", "Claude session initialized")- seen.append(await asyncio.wait_for(queue.get(), timeout=1.0))- with pytest.raises(asyncio.TimeoutError): # no inbox event for process log- await asyncio.wait_for(queue.get(), timeout=0.05)+ persist_agent_message(ctx, "system", "🔧 System init\n✨ Ready to work!")+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(queue.get(), timeout=0.1)finally:inbox_events.bus.unsubscribe(sub_id)- return seen- seen = asyncio.run(scenario())- assert [e[0] for e in seen] == ["message.new"]- assert seen[0][1]["type"] == "assistant" # folded into process log, not notify+ asyncio.run(scenario())+ with engine.connect() as conn:+ every = messages_service.list_session_messages(conn, session_id="ses_sys")+ assert every["messages"] == [], "system messages must not be persisted"def test_persist_agent_terminal_notify_updates_inbox(isolated_state):diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex fb09635d0..f46c95fa9 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -192,6 +192,30 @@ def test_list_session_messages_filters_to_user_facing_types(isolated_state):assert [m["text"] for m in dialogue["messages"]] == ["q", "final"]+def test_error_terminal_in_transcript_but_not_unread(isolated_state):+ """A terminal FAILED result (type='error') is part of the conversation+ (transcript / inbox) but must NOT count as an unread agent reply — only a+ successful 'result' bumps the unread badge, so a failed turn doesn't look+ like an answer arrived (Codex P2)."""+ from storage.messages_service import TRANSCRIPT_TYPES++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_err")+ _insert_msg(conn, scope_id, "ses_err", "user", "q", "2026-05-30T10:00:00Z", msg_type="user")+ _insert_msg(conn, scope_id, "ses_err", "agent", "❌ boom", "2026-05-30T10:00:01Z", read=False, msg_type="error")++ with engine.connect() as conn:+ transcript = messages_service.list_session_messages(conn, session_id="ses_err", types=TRANSCRIPT_TYPES)+ unread = messages_service.unread_counts(conn)++ # The error is visible in the conversation...+ assert [m["type"] for m in transcript["messages"]] == ["user", "error"]+ # ...but it is NOT an unread agent reply (unread is result-only).+ assert unread.get(scope_id, 0) == 0++def test_same_second_messages_order_by_insertion(isolated_state):"""Rows sharing a (second-resolution) created_at still order by insertion inthe transcript: the monotonic message id breaks the ``(created_at, id)`` tie,diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 5359dbaba..df4d7c492 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -529,7 +529,7 @@ def test_opencode_poll_aborts_disabled_question_toolcall():def _t(self, key):return f"translated:{key}"- async def emit_agent_message(self, context, message_type, text, parse_mode=None):+ async def emit_agent_message(self, context, message_type, text, parse_mode=None, *, is_error=False, level="normal"):emitted.append((message_type, text))class _Agent:@@ -591,10 +591,96 @@ def test_opencode_poll_aborts_disabled_question_toolcall():assert final_text is Noneassert should_emit is Falseassert aborted == [("oc-session", "/tmp/work")]- assert emitted[0][0] == "notify"+ # A disabled-question abort is a terminal FAILURE → emitted as an error RESULT+ # (the outbound chokepoint turns the dot red), not a bare notify that never+ # settles the dot.+ assert emitted[0][0] == "result"assert emitted[0][1] == "translated:error.opencodeQuestionToolDisabled"+def test_opencode_poll_emits_error_result_on_retry_exhaustion():+ # A completed assistant message carrying an error, with retries exhausted+ # (error_retry_limit=0) and the auth-recovery path declining (non-auth error),+ # is a terminal FAILURE. It must (a) emit an ERROR result so the dot turns red+ # and (b) return should_emit=False so the caller does NOT then emit the idle+ # "(No response from OpenCode)" warning that would reset the dot to idle (Codex P2).+ emitted = []++ class _AuthSvc:+ async def maybe_emit_auth_recovery_message(self, context, backend, message):+ return False # non-auth error → caller emits the terminal result itself++ class _Formatter:+ def format_toolcall(self, *args, **kwargs):+ return "tool"++ class _Controller:+ agent_auth_service = _AuthSvc()++ def _t(self, key):+ return f"translated:{key}"++ async def emit_agent_message(self, context, message_type, text, parse_mode=None, *, is_error=False, level="normal"):+ emitted.append((message_type, is_error))++ class _Agent:+ opencode_config = type("OpenCodeConfig", (), {"error_retry_limit": 0})()+ controller = _Controller()+ im_client = type("IM", (), {"formatter": _Formatter()})()++ def _get_formatter(self, context):+ return _Formatter()++ def _to_relative_path(self, path, working_path):+ return path++ def _extract_response_text(self, message):+ return ""++ class _Server:+ async def list_messages(self, session_id, directory):+ return [+ {+ "info": {+ "id": "msg-err",+ "role": "assistant",+ "time": {"completed": 1},+ "error": {"name": "ProviderError", "data": {"message": "rate limited"}},+ },+ "parts": [],+ }+ ]++ request = AgentRequest(+ context=MessageContext(user_id="u", channel_id="c", platform="slack"),+ message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::c",+ )++ loop = OpenCodePollLoop(_Agent())+ final_text, should_emit = asyncio.run(+ loop.run_prompt_poll(+ request,+ _Server(),+ "oc-session",+ agent_to_use=None,+ model_dict=None,+ reasoning_effort=None,+ baseline_message_ids=set(),+ )+ )++ assert final_text is None+ # should_emit False → caller skips the idle "(No response)" warning that would+ # otherwise reset the dot we just turned red.+ assert should_emit is False+ assert ("result", True) in emitted+ assert not any(mtype == "notify" for mtype, _ in emitted)++def test_processing_indicator_handle_is_source_of_truth_for_backend_cleanup():wechat = _StubClient("wechat")diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pynew file mode 100644index 000000000..7e68bc788--- /dev/null+++ b/tests/test_opencode_restore_polls.py@@ -0,0 +1,141 @@+"""Tests for ``OpenCodeAgent.restore_active_polls`` status recovery.++On a controller restart mid-OpenCode-turn, ``_reset_stale_agent_status`` flips+every ``running`` workbench session to ``idle``. ``restore_active_polls`` then+RESUMES the still-active OpenCode poll — but the resumed poll does NOT re-enter+``AgentService.handle_message`` (the inbound status chokepoint), so the avibe+sidebar dot would stay idle/gray for a backend turn that is still live unless the+restore path re-marks the session ``running`` itself. These tests lock that:++* an avibe poll → ``controller.set_agent_status(session_id, "running")``;+* an IM poll → NO status write (only avibe sessions get a dot).+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config.v2_sessions import ActivePollInfo # noqa: E402+from modules.agents.opencode.agent import OpenCodeAgent # noqa: E402+++def _make_poll(*, platform: str, base_session_id: str, opencode_session_id: str) -> ActivePollInfo:+ return ActivePollInfo(+ opencode_session_id=opencode_session_id,+ base_session_id=base_session_id,+ channel_id="chan",+ thread_id="thread",+ settings_key="key",+ working_path="/tmp/work",+ platform=platform,+ )+++def _build_agent(active_polls: dict[str, ActivePollInfo]):+ """Assemble an ``OpenCodeAgent`` with the minimal collaborators+ ``restore_active_polls`` touches, plus a controller that records+ ``set_agent_status`` writes."""+ status_writes: list[tuple[str, str]] = []+ removed: list[str] = []++ class _Server:+ async def list_messages(self, session_id, directory):+ # One in-progress assistant message → the session is "still active",+ # so the poll is restored (not pruned as stale).+ return [{"info": {"role": "assistant", "time": {}}}]++ async def mark_run_active(self, session_id):+ return None++ async def mark_run_inactive(self, session_id):+ return None++ class _PollLoop:+ async def run_restored_poll_loop(self, poll_info):+ return None++ async def remove_restored_ack(self, poll_info):+ return None++ class _SessionManager:+ def set_request_session(self, *args):+ return None++ def pop_request_session(self, *args):+ return None++ class _Sessions:+ def get_all_active_polls(self):+ return dict(active_polls)++ def remove_active_poll(self, session_id):+ removed.append(session_id)++ class _Controller:+ def set_agent_status(self, session_id, status):+ status_writes.append((session_id, status))++ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = _Controller()+ agent.sessions = _Sessions()+ agent._poll_loop = _PollLoop()+ agent._session_manager = _SessionManager()+ agent._active_requests = {}++ server = _Server()++ async def _get_server():+ return server++ agent._get_server = _get_server+ return agent, status_writes, removed+++def test_restored_avibe_poll_marks_session_running():+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ agent, status_writes, _ = _build_agent({"oc-1": poll})++ async def _run():+ restored = await agent.restore_active_polls()+ # Let the spawned restore task settle so it doesn't leak a warning.+ await asyncio.sleep(0)+ for task in list(agent._active_requests.values()):+ if not task.done():+ await task+ return restored++ restored = asyncio.run(_run())+ assert restored == 1+ # The restore path re-marks the avibe workbench session running via the+ # controller's status writer — keyed by the OpenCode base_session_id, which+ # for avibe IS the workbench session id (= agent_session_id / anchor).+ assert ("ses_wb", "running") in status_writes+++def test_restored_im_poll_does_not_touch_agent_status():+ poll = _make_poll(platform="slack", base_session_id="slack:thread", opencode_session_id="oc-2")+ agent, status_writes, _ = _build_agent({"oc-2": poll})++ async def _run():+ restored = await agent.restore_active_polls()+ await asyncio.sleep(0)+ for task in list(agent._active_requests.values()):+ if not task.done():+ await task+ return restored++ restored = asyncio.run(_run())+ assert restored == 1+ # IM polls carry no workbench session id → no dot, so no status write at all.+ assert status_writes == []+++def test_workbench_session_id_for_poll_resolution():+ avibe = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ slack = _make_poll(platform="slack", base_session_id="slack:thread", opencode_session_id="oc-2")+ assert OpenCodeAgent._workbench_session_id_for_poll(avibe) == "ses_wb"+ assert OpenCodeAgent._workbench_session_id_for_poll(slack) is Nonediff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 6c1bc7510..bebc6e892 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -12,6 +12,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from config import pathsfrom core.scheduled_tasks import (+ ParsedSessionKey,ScheduledTaskService,ScheduledTaskStore,TaskExecutionRequest,@@ -113,6 +114,40 @@ def test_resolve_session_id_target_preserves_reserved_user_scope(tmp_path: Path)assert resolved.session_key.is_dm is True+def test_resolve_session_id_target_accepts_avibe_project_session(tmp_path: Path) -> None:+ """avibe workbench sessions live under ``avibe::project::proj_<hex>``. A+ ``--session-id`` task target must resolve them (the dispatch binds the reply+ to the session via ``agent_session_target``); rejecting the project scope made+ scheduled tasks unusable on the workbench."""+ from storage.db import create_sqlite_engine+ from storage.sessions_service import SQLiteSessionsService+ from storage.settings_service import upsert_scope+ from storage import workbench_sessions_service++ db_path = tmp_path / "vibe.sqlite"+ # Build + migrate the schema, then seed an avibe project scope + session row.+ SQLiteSessionsService(db_path).close()+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_test", now="2026-05-31T00:00:00Z"+ )+ session = workbench_sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="default"+ )+ finally:+ engine.dispose()++ resolved = resolve_session_id_target(session["id"], db_path=db_path)++ assert resolved.session_id == session["id"]+ assert resolved.session_key.platform == "avibe"+ assert resolved.session_key.scope_type == "project"+ assert resolved.session_key.scope_id == "proj_test"+ assert resolved.agent_backend == "claude"++def test_parse_session_key_rejects_invalid_scope_type() -> None:try:parse_session_key("slack::room::C123")@@ -568,6 +603,38 @@ def test_build_context_separates_delivery_target_from_session_target() -> None:assert context.platform_specific["scheduled_delivery_alias"]["clear_source"] is False+def test_build_context_avibe_keys_on_session_id_not_project() -> None:+ # An avibe project holds many independent sessions. The scheduled context's+ # identity (channel_id) must be the concrete session, not the project scope,+ # so two concurrent runs in the same project don't collide on _get_session_key+ # / consolidated-log grouping and edit each other's visible log message.+ controller = SimpleNamespace(+ platform_settings_managers={},+ im_clients={"avibe": SimpleNamespace()},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )+ service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))+ target = ParsedSessionKey(platform="avibe", scope_type="project", scope_id="proj_890721e64fc8")++ context = asyncio.run(+ service._build_context(+ target,+ execution_id="exec-1",+ task_id="task-1",+ session_id="ses3chKBjP5hy",+ )+ )++ # Context identity is the session, not the project.+ assert context.channel_id == "ses3chKBjP5hy"+ assert context.platform_specific["agent_session_id"] == "ses3chKBjP5hy"+ # The project scope is still carried for persistence/routing.+ assert context.platform_specific["session_key_external"] == "avibe::project::proj_890721e64fc8"++def test_build_context_clears_provisional_anchor_for_cross_scope_delivery() -> None:settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))controller = SimpleNamespace(@@ -1510,3 +1577,164 @@ def test_drain_serializes_task_only_scheduled_runs(tmp_path: Path) -> None:await tasyncio.run(_exercise())+++# ---------------------------------------------------------------------+# avibe scheduled runs route through the per-session turn gate+# ---------------------------------------------------------------------+++def _avibe_controller_double(*, gate, handle_scheduled_message):+ """A controller double sufficient for ``_execute_request`` → ``_build_context``+ on an avibe target: a virtual ``avibe`` IM client (so ``validate_platform``+ passes) plus the thread-policy hooks ``_build_context`` consults."""+ return SimpleNamespace(+ platform_settings_managers={},+ im_clients={"avibe": SimpleNamespace()},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ session_turn_gate=gate,+ message_handler=SimpleNamespace(handle_scheduled_message=handle_scheduled_message),+ )+++def _make_avibe_session(monkeypatch, tmp_path) -> str:+ """Create a real avibe workbench session so ``resolve_session_id_target``+ resolves it to ``platform='avibe'`` (the gate trigger)."""+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_gate_exec", now="2026-05-31T00:00:00Z"+ )+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ return session["id"]+++def test_execute_request_avibe_routes_through_gate(monkeypatch, tmp_path) -> None:+ """An avibe scheduled run is dispatched via ``session_turn_gate.submit_scheduled``+ (so it queues behind an active Chat turn + gets the turn lifecycle) and does+ NOT call ``handle_scheduled_message`` directly. It returns ``None`` so the+ caller's ``ok = not error`` stays true — the run's own outcome surfaces via+ the outbound terminal result + sidebar dot."""+ session_id = _make_avibe_session(monkeypatch, tmp_path)++ submitted: list[tuple] = []+ handler_calls: list = []++ async def _submit_scheduled(sid, ctx, text):+ submitted.append((sid, text, getattr(ctx, "platform", None)))++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ handler_calls.append(message)+ return "should not be called"++ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})+ controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)+ service = ScheduledTaskService(+ controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ )++ error = asyncio.run(+ service._execute_request(+ session_key=None,+ post_to=None,+ deliver_key=None,+ prompt="run the digest",+ execution_id="exec-gate-1",+ trigger_kind="scheduled",+ session_id=session_id,+ )+ )++ assert error is None, "dispatched-success returns None so ok=not error stays true"+ assert submitted == [(session_id, "run the digest", "avibe")], "routed through the turn gate"+ assert handler_calls == [], "the direct handle_scheduled_message path is bypassed for avibe"+++def test_execute_request_im_bypasses_gate(monkeypatch, tmp_path) -> None:+ """An IM (slack/discord/...) scheduled run NEVER touches the gate — it keeps+ the direct ``handle_scheduled_message`` path byte-for-byte, even when a gate+ is present on the controller."""+ submitted: list = []+ handler_calls: list = []++ async def _submit_scheduled(sid, ctx, text):+ submitted.append((sid, text))++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ handler_calls.append((message, context.platform))+ return None++ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_k: None))+ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ session_turn_gate=gate,+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),+ )+ service = ScheduledTaskService(+ controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ )++ error = asyncio.run(+ service._execute_request(+ session_key="slack::channel::C123",+ post_to=None,+ deliver_key=None,+ prompt="send digest",+ execution_id="exec-im-1",+ trigger_kind="scheduled",+ )+ )++ assert error is None+ assert submitted == [], "IM runs must never reach the turn gate"+ assert handler_calls == [("send digest", "slack")], "IM keeps the direct scheduled path"+++def test_execute_request_avibe_falls_back_when_no_gate(monkeypatch, tmp_path) -> None:+ """When the internal server hasn't published the gate yet+ (``session_turn_gate is None``), an avibe scheduled run falls back to the+ direct ``handle_scheduled_message`` path instead of crashing."""+ session_id = _make_avibe_session(monkeypatch, tmp_path)++ handler_calls: list = []++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ handler_calls.append((message, context.platform))+ return None++ controller = _avibe_controller_double(gate=None, handle_scheduled_message=_handle_scheduled_message)+ service = ScheduledTaskService(+ controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ )++ error = asyncio.run(+ service._execute_request(+ session_key=None,+ post_to=None,+ deliver_key=None,+ prompt="run the digest",+ execution_id="exec-gate-fallback",+ trigger_kind="scheduled",+ session_id=session_id,+ )+ )++ assert error is None+ assert handler_calls == [("run the digest", "avibe")], "no gate → direct scheduled path"diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex d208aed83..8a4f4dca0 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260601_0011"+HEAD_REVISION = "20260601_0012"def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex f31126253..b66c2b2d4 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -40,6 +40,7 @@ const WORKING_SETTLE_GRACE_MS = 4000;const isTranscriptMessage = (msg: WorkbenchMessage): boolean =>msg.type === 'user' ||msg.type === 'result' ||+ msg.type === 'error' ||msg.type === 'notify' ||(msg.metadata as { source?: string } | null)?.source === 'show_page';@@ -1105,11 +1106,12 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working }) =const bottomRef = useRef<HTMLDivElement | null>(null);// The reply arrives atomically as a persisted ``result`` row (no streaming// card), so the thinking bubble shows for the whole gap between send and- // reply. Hide it the moment the last row is already a fresh agent result.+ // reply. Hide it the moment the last row is a fresh agent terminal — a+ // successful ``result`` OR a failed ``error`` both end the turn.const lastIsAgentResult =messages.length > 0 &&messages[messages.length - 1].author === 'agent' &&- messages[messages.length - 1].type === 'result';+ (messages[messages.length - 1].type === 'result' || messages[messages.length - 1].type === 'error');const showThinking = working && !lastIsAgentResult;// Auto-scroll to the bottom whenever a new message arrives or the thinking// bubble toggles — mirrors how every other chat client behaves and saves thediff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex ed8835124..202a05eed 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -175,6 +175,15 @@ const InboxHoverPopover: React.FC<{);};+// Session status dot colours. Maps the agent-runtime status to the user's+// gray / green / red: idle → muted (gray), running → mint (green) + glow,+// failed → destructive (red) + glow. Tokens resolve from src/index.css.+const STATUS_DOT_CLASS: Record<string, string> = {+ running: 'bg-mint shadow-[0_0_6px_0_rgba(91,255,160,0.65)]',+ failed: 'bg-destructive shadow-[0_0_6px_0_rgba(255,107,107,0.6)]',+ idle: 'bg-muted',+};+// One project row + (when expanded) the session list under it. Mirrors// design.pen N96dsm/C68Ul (project row) and C7clY/R2C8U (session row).const ProjectRow: React.FC<{@@ -369,9 +378,10 @@ const ProjectRow: React.FC<{)}><span+ title={t(`workbench.sessionStatus.${session.agent_status}`)}className={clsx(- 'size-[5px] shrink-0 rounded-full bg-mint',- unread > 0 && 'shadow-[0_0_6px_0_rgba(91,255,160,0.6)]',+ 'size-[5px] shrink-0 rounded-full',+ STATUS_DOT_CLASS[session.agent_status] ?? STATUS_DOT_CLASS.idle,)}/><span@@ -433,6 +443,16 @@ export const WorkbenchSidebar: React.FC = () => {const sessionsInFlightRef = useRef<Set<string>>(new Set());const [creatingSession, setCreatingSession] = useState<Set<string>>(new Set());const [showNewProject, setShowNewProject] = useState(false);+ // Mirror the set of projects whose sessions are currently loaded so the+ // (re)connect handler can refetch exactly those without re-subscribing the+ // event stream on every expand (stale-closure-safe, like cursorRef in the+ // inbox context).+ const loadedProjectsRef = useRef<string[]>([]);+ loadedProjectsRef.current = Object.keys(sessionsByProject);+ // Mirror the loaded session rows so the (re)connect reconcile can refetch the+ // SAME already-paged-in window (not just the first page) without a stale closure.+ const sessionsByProjectRef = useRef<Record<string, WorkbenchSession[]>>({});+ sessionsByProjectRef.current = sessionsByProject;const fetchProjects = useCallback(async () => {try {@@ -448,38 +468,10 @@ export const WorkbenchSidebar: React.FC = () => {fetchProjects();}, [fetchProjects]);- // Keep cached session rows in sync with edits made elsewhere (e.g. renaming- // a session from the chat header). The server broadcasts session.activity- // with event "updated"; patch the matching row's title in place so the- // sidebar label tracks the chat header without a manual refresh.- useEffect(() => {- const disconnect = api.connectWorkbenchEvents({- onSessionActivity: (data) => {- if (data.event !== 'updated' || !data.scope_id) return;- const projectId = data.scope_id.split('::').pop();- if (!projectId) return;- const nextTitle = data.title ?? null;- setSessionsByProject((prev) => {- const list = prev[projectId];- if (!list) return prev;- let changed = false;- const next = list.map((s) => {- if (s.id === data.session_id && s.title !== nextTitle) {- changed = true;- return { ...s, title: nextTitle };- }- return s;- });- return changed ? { ...prev, [projectId]: next } : prev;- });- },- });- return disconnect;- }, [api]);-const fetchSessions = useCallback(- async (projectId: string, opts?: { append?: boolean }) => {+ async (projectId: string, opts?: { append?: boolean; reconcile?: boolean }) => {const append = opts?.append ?? false;+ const reconcile = opts?.reconcile ?? false;if (append && !sessionCursorRef.current[projectId]) return; // nothing more to loadif (sessionsInFlightRef.current.has(projectId)) return; // serialise per projectsessionsInFlightRef.current.add(projectId);@@ -489,10 +481,16 @@ export const WorkbenchSidebar: React.FC = () => {setSessionsLoading((prev) => ({ ...prev, [projectId]: true }));}try {+ // A (re)connect reconcile refetches the SAME already-loaded window (every+ // paged-in row), not just the first page — otherwise a transient SSE+ // reconnect / controller restart truncates an expanded project back to the+ // first SESSIONS_PAGE_SIZE rows until the user pages again (Codex P2).+ const loadedCount = sessionsByProjectRef.current[projectId]?.length ?? 0;+ const limit = reconcile ? Math.max(loadedCount, SESSIONS_PAGE_SIZE) : SESSIONS_PAGE_SIZE;const result = await api.listSessions({projectId,status: 'active',- limit: SESSIONS_PAGE_SIZE,+ limit,beforeId: append ? sessionCursorRef.current[projectId] ?? undefined : undefined,});// Mutate the ref in place so a concurrent load for another project@@ -527,6 +525,68 @@ export const WorkbenchSidebar: React.FC = () => {[api],);+ // Keep cached session rows in sync with edits made elsewhere (e.g. renaming+ // a session from the chat header). The server broadcasts session.activity+ // with event "updated"; patch the matching row's title in place so the+ // sidebar label tracks the chat header without a manual refresh.+ useEffect(() => {+ const disconnect = api.connectWorkbenchEvents({+ // (Re)connect reconciliation: after a controller restart the crash-recovery+ // reset (running → idle) ran server-side with NO event subscriber to+ // broadcast to, and any status events during the drop were missed. The+ // sidebar dots' authoritative source is listSessions, so refetch projects ++ // every already-expanded project's sessions whenever the stream (re)opens.+ onConnected: () => {+ fetchProjects();+ for (const projectId of loadedProjectsRef.current) {+ fetchSessions(projectId, { reconcile: true });+ }+ },+ onSessionActivity: (data) => {+ if (data.event !== 'updated' || !data.scope_id) return;+ const projectId = data.scope_id.split('::').pop();+ if (!projectId) return;+ const nextTitle = data.title ?? null;+ setSessionsByProject((prev) => {+ const list = prev[projectId];+ if (!list) return prev;+ let changed = false;+ const next = list.map((s) => {+ if (s.id === data.session_id && s.title !== nextTitle) {+ changed = true;+ return { ...s, title: nextTitle };+ }+ return s;+ });+ return changed ? { ...prev, [projectId]: next } : prev;+ });+ },+ // Recolor the session dot when its agent-runtime status changes. The+ // event carries only session_id, so find the project list holding it and+ // patch that row in place (mirrors the title patch above).+ onSessionStatus: (data) => {+ setSessionsByProject((prev) => {+ let changed = false;+ const next: Record<string, WorkbenchSession[]> = {};+ for (const [projectId, list] of Object.entries(prev)) {+ let listChanged = false;+ const patched = list.map((s) => {+ if (s.id === data.session_id && s.agent_status !== data.agent_status) {+ listChanged = true;+ return { ...s, agent_status: data.agent_status };+ }+ return s;+ });+ next[projectId] = listChanged ? patched : list;+ if (listChanged) changed = true;+ }+ return changed ? next : prev;+ });+ },+ });+ return disconnect;+ }, [api, fetchProjects, fetchSessions]);+const toggleExpanded = useCallback((projectId: string) => {setExpanded((prev) => {diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 29a3a123a..452a5b3e9 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -177,6 +177,9 @@ export type WorkbenchSession = {model: string | null;reasoning_effort: string | null;status: string;+ /** Live agent-runtime status driving the sidebar dot: idle (gray) /+ * running (green) / failed (red). Distinct from the lifecycle ``status``. */+ agent_status: 'idle' | 'running' | 'failed';workdir: string | null;native_session_id: string | null;created_at: string;@@ -366,6 +369,10 @@ export type WorkbenchEventHandlers = {// button without the browser having to infer turn end from message rows.onTurnStart?: (data: { session_id: string }) => void;onTurnEnd?: (data: { session_id: string }) => void;+ // A session's live agent-runtime status changed (idle/running/failed) — the+ // sidebar dot recolors from this without a refetch. Same controller→browser+ // bus as turn.start/turn.end; published only when the value actually moves.+ onSessionStatus?: (data: { session_id: string; agent_status: 'idle' | 'running' | 'failed' }) => void;// The send-while-busy queue for a session changed (enqueue / flush / remove).onQueueUpdated?: (data: { session_id: string }) => void;onAny?: (event: WorkbenchEventEnvelope) => void;@@ -1404,6 +1411,22 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenhandlers.onTurnEnd?.(envelope.data);}});+ source.addEventListener('session.status', (e: MessageEvent) => {+ const envelope = (() => {+ try {+ return JSON.parse(e.data) as WorkbenchEventEnvelope<{+ session_id: string;+ agent_status: 'idle' | 'running' | 'failed';+ }>;+ } catch {+ return null;+ }+ })();+ if (envelope) {+ handlers.onAny?.(envelope);+ handlers.onSessionStatus?.(envelope.data);+ }+ });source.addEventListener('queue.updated', (e: MessageEvent) => {const envelope = (() => {try {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 20d76d22f..de46652a7 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -471,6 +471,11 @@"sessionsEmpty": "No sessions in this project.","sessionsLoadMore": "Load more","untitledSession": "Untitled session",+ "sessionStatus": {+ "idle": "Idle",+ "running": "Running",+ "failed": "Last turn failed"+ },"newProjectDialog": {"title": "Open project","description": "Pick a working directory. Opening a folder you've used before reopens that project — restoring it if it was archived.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex ebf7bb625..653066b0a 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -471,6 +471,11 @@"sessionsEmpty": "项目里还没有会话。","sessionsLoadMore": "加载更多","untitledSession": "未命名会话",+ "sessionStatus": {+ "idle": "空闲",+ "running": "运行中",+ "failed": "上一回合失败"+ },"newProjectDialog": {"title": "打开项目","description": "选一个工作目录。打开你之前用过的文件夹会重新打开那个项目 —— 如果它被归档过,会一并恢复。",diff --git a/vibe/cli.py b/vibe/cli.pyindex b48b008d9..af34372c3 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -1159,14 +1159,19 @@ def _watch_runtime_store() -> WatchRuntimeStateStore:def _supported_task_platforms() -> set[str]:+ # ``avibe`` (the web workbench) is ALWAYS available as an in-process platform,+ # even though it's not in the configured IM platform list — so scheduled+ # tasks / watches can target a workbench session. Include it unconditionally.+ platforms = {"avibe"}try:config = _ensure_config()except Exception:- return set()+ return platformsenabled = getattr(config, "enabled_platforms", None)if callable(enabled):- return set(enabled())- return {getattr(config, "platform", "slack")}+ return platforms | set(enabled())+ platforms.add(getattr(config, "platform", "slack"))+ return platformsdef _is_completed_one_shot(task) -> bool:@@ -1205,6 +1210,18 @@ def _parse_validated_session_key("configured_platforms_text": supported_text,},)+ if parsed.platform == "avibe":+ # A bare avibe session KEY carries no agent_session_id, so a dispatched+ # reply can't attach to a workbench session (persist_agent_message can't+ # resolve a project scope) — target workbench sessions by --session-id.+ raise TaskCliError(+ "avibe workbench sessions must be targeted with --session-id, not --session-key",+ code="avibe_requires_session_id",+ hint="A workbench session key has no agent session id, so the reply wouldn't attach to the Chat. Pass the session id via --session-id.",+ example="--session-id ses3chKBjP5hy",+ help_command=help_command,+ details={"session_key": session_key},+ )return parseddiff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex eb67d23b6..10dfce193 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -265,6 +265,7 @@"claudeMethodPrompt": "Choose the Claude sign-in source before starting OAuth.","claudeMethodFallback": "Choose a Claude sign-in source with `/setup claude claudeai` or `/setup claude console`.","resetPrompt": "{backend} looks logged out. Use the button below to restart OAuth setup.",+ "resetPromptPlain": "{backend} looks logged out. Run `/setup {backend}` to restart OAuth setup.","manualFallback": "If inline buttons are unavailable, run `/setup {backend}`.","codexInstructions": "Codex setup started.\n\n1. Open this URL in your browser:\n{url}\n\n2. Enter this one-time code:\n`{code}`\n\nThe bot will keep waiting here and confirm when login finishes.","claudeInstructions": "Claude setup started.\n\nOpen this URL in your browser and finish the login flow:\n{url}\n\nWhen the browser callback page shows the final `authorizationCode#state` value, send it back directly in this chat.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e7c45c909..376b92602 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -265,6 +265,7 @@"claudeMethodPrompt": "开始 Claude OAuth 之前,请先选择登录站点。","claudeMethodFallback": "如果当前平台不支持按钮,请执行 `/setup claude claudeai` 或 `/setup claude console`。","resetPrompt": "{backend} 看起来已经掉线了。请点击下面的按钮重新发起 OAuth 登录。",+ "resetPromptPlain": "{backend} 看起来已经掉线了。请发送 `/setup {backend}` 重新发起 OAuth 登录。","manualFallback": "如果当前平台不支持按钮,请执行 `/setup {backend}`。","codexInstructions": "Codex 登录修复已开始。\n\n1. 在浏览器打开这个地址:\n{url}\n\n2. 输入这个一次性验证码:\n`{code}`\n\nBot 会继续等待,并在登录完成后回消息确认。","claudeInstructions": "Claude 登录修复已开始。\n\n请在浏览器打开下面的地址并完成登录:\n{url}\n\n浏览器回调页面会显示最终的 `authorizationCode#state`,请直接把它发回当前聊天。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 22c4da646..bfd82eb07 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3138,7 +3138,7 @@ def sessions_messages_list(session_id: str):session_id=session_id,after_id=after_id,limit=limit,- types=("user", "result", "notify"),+ types=messages_service.TRANSCRIPT_TYPES,include_metadata_sources=("show_page",),tail=tail,)