Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

refactor(workbench): remove turn-duration timeout — never kill long-running agents (#383)

Call White9c61d3f48edd
diff --git a/core/internal_server.py b/core/internal_server.py
index 2b4124810..2be4d06f8 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -47,12 +47,6 @@ if TYPE_CHECKING: # pragma: no cover - typing only
logger = 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.
@@ -169,101 +163,24 @@ def create_app(controller: "Controller") -> FastAPI:
logger.exception("internal async dispatch failed for session=%s", session_id)
finally:
if isinstance(session_id, str):
- timed_out = bool((context.platform_specific or {}).get("turn_timed_out"))
- stop_confirmed = False
- if timed_out:
- # The 600s wait elapsed with the backend still running.
- # Interrupt it BEFORE releasing the session, so /turn-state
- # can't report idle (and a manual send can't start a turn)
- # while a live backend turn is still producing output
- # (Codex P2). A turn silent for 10 min is treated as stuck.
- try:
- stop_confirmed = bool(await controller.command_handler.handle_stop(context))
- except Exception:
- logger.exception("dispatch timeout: backend stop failed for session=%s", 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.
+ # The turn is over — the agent emitted its terminal result, the
+ # user stopped it, or dispatch raised before any backend turn.
+ # There is NO turn-duration timeout: a long agent runs for hours
+ # and is never killed on a timer, so the slot is freed only by a
+ # real terminal signal here (Phase 1a — STUCK/sentinel removed).
+ in_flight.pop(session_id, None)
+ bus.publish("turn.end", {"session_id": session_id})
+ # Converge the no-terminal-result outcome onto the OUTBOUND status
+ # chokepoint. The normal path already emitted a terminal result;
+ # only ``failed`` reaches here without one: dispatch raised before
+ # any backend turn (missing/disabled backend) → empty error result
+ # → dot red. This is a real terminal FAILURE, not a timeout.
+ if failed:
+ await controller.emit_agent_message(context, "result", "", is_error=True)
+ # Don't flush after a Stop (keep the queue) or a terminal failure.
+ # send-now still forces a flush via flush_on_cancel.
should_flush = (
- (not cancelled and not failed and not timed_out and session_id not in stop_no_flush)
+ (not cancelled and not failed and session_id not in stop_no_flush)
or (session_id in flush_on_cancel)
)
flush_on_cancel.discard(session_id)
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index 5ff00730b..e6710c4c5 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -45,12 +45,6 @@ ChunkCallback = Callable[[dict], Awaitable[None]]
SOURCE_HUMAN = "human"
SOURCE_SCHEDULED = "scheduled"
-# Safety cap for how long a streaming dispatch holds the SSE stream open
-# waiting for a turn to emit its result when the agent never produces one
-# (crash, hang, auth failure). Real turns resolve far sooner via the
-# result-emit signal; this only bounds the pathological no-result case.
-TURN_STREAM_TIMEOUT = 600.0
-
async def dispatch_turn(
controller: "Controller",
@@ -69,9 +63,12 @@ async def dispatch_turn(
emit for this turn as it happens. Because the agent backends are
fire-and-forget — ``handle_user_message`` returns once the message is sent
and the reply streams in later on a background receiver task — we register
- a per-session sink and hold here until the turn emits its result (or the
- safety timeout fires), so the caller doesn't close the SSE stream before
- any chunk arrives.
+ a per-session sink and hold here until the turn emits its REAL terminal
+ result, however long that takes, so the caller doesn't close the SSE stream
+ before any chunk arrives. There is NO turn-duration timeout: an agent turn
+ may legitimately run for hours, and the controller must never kill it on a
+ timer. A user Stop/cancel cancels the task, propagating ``CancelledError``
+ out of ``done.wait()``; the ``finally`` still pops the sink.
"""
handler = controller.message_handler
@@ -110,21 +107,11 @@ async def dispatch_turn(
controller.register_turn_sink(session_key, on_chunk=on_chunk, done_event=done, turn_token=turn_token)
try:
result = await _run()
- try:
- await asyncio.wait_for(done.wait(), timeout=TURN_STREAM_TIMEOUT)
- except asyncio.TimeoutError:
- logger.warning(
- "dispatch_turn: streaming turn for %s emitted no result within %.0fs; closing stream",
- session_key,
- TURN_STREAM_TIMEOUT,
- )
- # The backend may STILL be running (a long command that hasn't
- # produced a result yet). Mark the turn as unresolved so the async
- # wrapper does NOT flush the queue / start a new turn on top of it —
- # otherwise two turns overlap. The late result (if any) just appends.
- if context.platform_specific is None:
- context.platform_specific = {}
- context.platform_specific["turn_timed_out"] = True
+ # Wait for the agent's REAL terminal result, however long it takes — a
+ # turn may legitimately run for hours, so there is NO timeout here. A
+ # user Stop/cancel cancels this task; the ``CancelledError`` propagates
+ # out of ``done.wait()`` and the ``finally`` below pops the sink.
+ await done.wait()
return result
finally:
# Pass our own done event so a turn that was superseded by a newer
diff --git a/docs/plans/avibe-turn-lifecycle-fsm.md b/docs/plans/avibe-turn-lifecycle-fsm.md
new file mode 100644
index 000000000..abae2dd69
--- /dev/null
+++ b/docs/plans/avibe-turn-lifecycle-fsm.md
@@ -0,0 +1,317 @@
+# avibe Turn Lifecycle → one per-session Turn state machine
+
+Status: **design / pre-implementation**. Branch `refactor/avibe-turn-state-machine` (off master @ e324cc0, which includes #367 `2c88c7b`).
+Author: refactor follow-up to PR #367. Tracks task #85; folds in #84 + Codex #3336001455.
+
+> Read this top-to-bottom before touching code. Part 1 is the EXHAUSTIVE current
+> behavior (so nothing is lost). Part 2 is the target. Part 3 is the migration.
+> Part 4 is the edge-case catalog = the regression suite. Part 5 = open decisions.
+
+---
+
+## 0. Why this exists (the diagnosis)
+
+Across ~15 Codex review rounds on #367, the review **never converged**: each round
+surfaced 3–5 new P2s, almost all in the avibe turn lifecycle. Root cause:
+
+> "a turn's lifecycle" for an avibe session is **not one thing** — it is ~6
+> independent mechanisms with **no single source of truth**. Every new scenario
+> (timeout+stop-fail, scheduled+busy, crash+restored-poll, receiver-crash+token,
+> send-now+stuck) is a fresh **reconciliation between these mechanisms**, and Codex
+> keeps finding pairs that disagree. That is an infinite tail *by construction*.
+
+Deeper tension: backends are **fire-and-forget async** (`handle_message` returns
+before the turn ends; the result/error streams back later on a reused receiver /
+poll / event handler), and avibe (strict turn lifecycle: working indicator, Stop,
+queue, dot) is **retrofitted onto an IM-shaped loose message flow**. So "did the
+turn end / succeed / is it still mine" must be *caught + reconciled*, not *read*.
+
+The fix is **not** more edge patches. It is to make the turn lifecycle ONE
+authoritative per-session state machine; the dot, the in-flight gate, the
+lifecycle events, and the queue become **projections** of it.
+
+---
+
+## PART 1 — CURRENT STATE (exhaustive map)
+
+### 1.1 The 6 reconciled mechanisms (what each owns, where)
+
+| # | Mechanism | Owns | Lives in |
+|---|-----------|------|----------|
+| 1 | **Status dot** `agent_sessions.agent_status` ∈ {idle, running, failed} | the persisted sidebar tri-state (sticky `failed`) | `workbench_sessions_service.set_agent_status`/`reset_running_agent_status`; written by `controller.set_agent_status` (broadcasts `session.status`) |
+| 2 | **in_flight gate** `dict[session_id → (asyncio.Task, MessageContext)]` | "is a turn busy", the Stop target, the queue gate | `internal_server.create_app` closure (`app.state.in_flight_dispatches`) |
+| 3 | **turn-sink + turn_token** | correlate an async terminal emit to the live turn; hold the SSE/dispatch open | `dispatch_turn` stamps token + registers sink; `controller.register/pop_turn_sink`, `active_turn_sinks` |
+| 4 | **send-while-busy queue** (`messages.type='queued'`) | messages typed while a turn runs | `messages_service.enqueue/list/pop_queued`, `promote_pending`; drained by `internal_server._flush_queue` |
+| 5 | **lifecycle events** `turn.start` / `turn.end` | the browser working indicator + Stop visibility | published by `internal_server._run_turn` |
+| 6 | **stuck-turn sentinel + crash recovery** | 600s-timeout-stop-unconfirmed holding; reset stale `running` on boot | sentinel task in `_run_turn` finally; `controller._reset_stale_agent_status`; OpenCode `restore_active_polls` |
+
+No single object knows "the turn's state". The state is **derived** and **scattered**:
+busy = `in_flight` has a not-done task; running = dot column; working = the FE bit;
+done = a token-matched terminal `result` reached the outbound chokepoint.
+
+### 1.2 The two status chokepoints (the ONE good invariant — keep it)
+
+- **INBOUND → running**: `modules/agents/service.py` `AgentService.handle_message:35-37`
+ — every source/backend funnels here; `if session_id: set_agent_status(session_id,"running")` then `await agent.handle_message`. avibe-gated (only avibe ctx carries `agent_session_id`).
+- **OUTBOUND → idle/failed**: `core/message_dispatcher.py` `emit_agent_message:460-467`
+ — only `canonical_type=="result"` AND `_is_active_turn(context)` settles `failed if is_error else idle`.
+
+`_session_id_from_context` (`controller.py:661-665`) reads `platform_specific["agent_session_id"]` — only avibe turns carry it, so IM/CLI never touch the dot.
+
+### 1.3 End-to-end turn lifecycle (interactive Chat)
+
+1. UI server writes a `pending` message row, POSTs `/internal/dispatch_async` (session_id, text).
+2. `_dispatch_async` (internal_server): **gate decision** — busy OR pre-existing queue → `promote_pending(→queued)` (+ flush if idle); else `_run_turn`.
+3. `_run_turn`: create `_runner` task; `in_flight[session_id]=(task,ctx)`; publish `turn.start`. Run `dispatch_turn(ctx, text, source, on_chunk=_noop_chunk)` — **always a sink** so the turn is HELD open until the terminal result.
+4. `dispatch_turn` (`services/dispatch.py`): stamp `turn_token=uuid` on ctx; `register_turn_sink(token, done_event)`; `await handler.handle_user_message` (or `handle_scheduled_message`); then **`await done.wait()` up to 600s** (`TURN_STREAM_TIMEOUT`).
+5. `handle_user_message → _handle_turn → AgentService.handle_message` → **set dot running** (inbound chokepoint) → `agent.handle_message` (fire-and-forget submit; returns before reply).
+6. Backend later emits the terminal `result` (success/error/silent) on its receiver/poll/handler, carrying the turn_token → `emit_agent_message` → **outbound chokepoint settles dot** (idle/failed) → empty/silent → `_signal_turn_complete → mark_turn_complete` sets the sink `done_event`.
+7. `done.wait()` returns → `dispatch_turn` returns → `_runner.finally`: pop `in_flight`, publish `turn.end`, flush the queue (unless stop/timeout/cancel rules say otherwise).
+
+### 1.4 Per-backend participation (the async-correlation complexity)
+
+All three are **pure participants**: they emit **exactly one terminal `result` per turn**
+(success / `is_error=True` / `level="silent"` stop) carrying the turn's token; they never
+write the dot, in_flight, queue, or lifecycle events. Differences that the FSM must absorb:
+
+- **Claude** (`claude_agent.py`): ONE long-lived **reused receiver** per session serving all
+ turns; a per-session **FIFO `_pending_requests`**; the receiver's captured ctx holds **turn 1's
+ token**, so every terminal emit must `_adopt_pending_turn_token` from the FIFO-matched request
+ (4 sites: success pop, in-loop auth head, `_retire_failed_auth_turn`, receiver-crash head — adopt
+ BEFORE `_clear_pending_reactions` which nukes the whole FIFO). Asymmetry: assistant-auth clears-all;
+ system/result-auth retire-one. **No turn restore on restart.**
+- **Codex** (`codex/agent.py`,`event_handler.py`): in-memory **turn registry** (`_turns`,
+ `_active_turns`, `_pending_turn_starts` bootstrap race); **inherits** the token by carrying
+ `request.context` (never stamps/adopts); **interrupts-before-start** within a session
+ (`handle_message:130-155`) — the in-session preempt safety net. **No turn restore.** First-turn
+ bind swaps `platform_specific` to a copied dict (token survives).
+- **OpenCode** (`opencode/agent.py`,`poll_loop.py`): turn = a **2s poll loop**; `(final_text,
+ should_emit)` contract (`should_emit=False` ⇒ "I already emitted my terminal result, don't
+ double-settle"); the only backend with **persisted crash recovery** — `restore_active_polls`
+ re-spawns polls on boot and **re-marks the avibe session `running`** (it bypasses the inbound
+ chokepoint; recovers the dot the boot reset cleared). Inherits token via shared ctx; restored
+ polls are effectively tokenless (rely on fail-open, no live sink after restart).
+
+### 1.5 The gate internals (internal_server)
+
+- `in_flight` busy-check is `entry is not None and not entry[0].done()` — used by `_turn_state`,
+ `_dispatch_async`, `_cancel`, `_send_now`, `_submit_scheduled_turn`.
+- `_run_turn(session_id, ctx, text, source=HUMAN)`: the runner; on terminal/timeout in its `finally`
+ it (a) for **timeout+stop-unconfirmed (`stuck`)** installs a **self-healing sentinel task** that
+ registers a sink under the timed-out token, awaits a late result OR `STUCK_TURN_RECOVERY_TIMEOUT`
+ (600s) cap, defers `turn.end` until release, and on cap-expiry emits a failed result; honors
+ `flush_on_cancel`/`stop_no_flush` on release; (b) else pops in_flight + publishes turn.end +
+ conditionally flushes.
+- `_flush_queue`: `pop_queued` → merge into ONE `user` row → publish `message.new`+`inbox.session.updated`+`queue.updated` → rebuild ctx from current session row → recurse `_run_turn` (as **SOURCE_HUMAN**).
+- `_submit_scheduled_turn` (gate entry for scheduled): busy/queued → append a `queued` row
+ (`author=source=harness`); idle → `_run_turn(source=SCHEDULED)`.
+- `_cancel`: read in_flight; `task.done()`→already-finished; else `handle_stop(stored ctx)` →
+ True→`task.cancel()`; False→409 `stop_failed` (no cancel). Sets `stop_no_flush` before the await.
+- `_send_now`: busy+has-queue → `flush_on_cancel` + interrupt + cancel; idle → flush directly.
+- Markers: `flush_on_cancel` (send-now wants the queue to run on cancel), `stop_no_flush` (plain Stop keeps the queue).
+
+### 1.6 Scheduled / watch / webhook / agent_run entry
+
+`scheduled_tasks._execute_request:1556-1564`: `if platform=="avibe" and session_id and gate: await gate.submit_scheduled(...); return None` else `handle_scheduled_message` (IM, byte-identical). `_build_context` sets `channel_id=session_id`, `agent_session_id`, `turn_source="scheduled"`, `suppress_delivery`, `delivery_override`, `agent_session_target`. Triggers: cron/one-shot (`task_run`/`scheduled`), `hook_send`, watch-waiter (`watch`), `agent_run` (`vibe agent run --async`); `webhook` is defined-but-unwired.
+
+### 1.7 The frontend contract (MUST be preserved verbatim)
+
+Single `EventSource('/api/events')`; envelope `{type,data,ts}`. Two distinct FE state machines:
+
+- **`working`** (Chat page, one bit): set on `turn.start`, **cleared ONLY on `turn.end`** (the
+ authoritative "turn over"); reconciled by `GET /turn-state → {in_flight}` on reconnect/visibility;
+ 11-min fallback; a `result`/`error` row hides the *thinking bubble* early but does NOT clear `working`.
+ Drives the Stop button (busy ⇒ Stop, else Send).
+- **`agent_status`** (sidebar dot, tri-state idle/running/failed): from the session row +
+ `session.status` event; reconciled by `listSessions` on reconnect (trusts REST over replayed events).
+
+Events that MUST keep firing (name + `session_id` minimum): `turn.start`, `turn.end`,
+`session.status`(+agent_status), `queue.updated`, `message.new`(full row), `inbox.session.updated`,
+`inbox.unread.changed`, `session.activity`, `connected`.
+REST that MUST keep its contract: `POST /messages → {id}` (started) vs `{queued:true}` (202);
+`GET /turn-state → {in_flight}` (truthful incl. the post-POST registration window; FE has a 4s grace);
+`POST /cancel → {ok:false,code:'not_in_flight'}` when idle (≠ transport failure);
+`POST /queue/{id}/send-now → code 'stop_failed' | status 'empty'`.
+Message `type` filter (`user/result/error/notify` + `metadata.source=='show_page'`) identical between
+the REST list and the `message.new` stream; `assistant`/`tool_call` persisted but NOT streamed/listed;
+`system` never persisted. Unread = `result` only. `error`/`notify` show but don't count unread.
+
+---
+
+## PART 2 — TARGET: one `SessionTurnManager` FSM
+
+### 2.0 LOCKED DECISIONS (Alex, 2026-06-02)
+
+- **NO turn-duration timeout.** An agent turn may legitimately run for hours; the
+ controller must NEVER kill it on a timer. Remove `TURN_STREAM_TIMEOUT` (the 600s
+ `dispatch_turn` cap) entirely — `await done.wait()` waits for the agent's REAL
+ terminal result, however long. This deletes the cause of the whole STUCK problem.
+- **NO STUCK state, NO sentinel.** They existed ONLY to handle the timeout. Gone.
+ FSM = **IDLE ↔ RUNNING** (+ enqueue when busy).
+- **Genuine failure is detected by REAL signals, not a timer**: backends emit a
+ terminal `error` result on crash/connection-loss/auth-fail (already built); the
+ user's **Stop** ends a wedged turn; controller restart resets stale `running`.
+ Concurrent sends never collide because a busy session **enqueues** (the gate).
+- **KEEP transport-level health timeouts** — Codex's 120s per-RPC-call timeout,
+ OpenCode's 15s `wait_for_session_idle`. These bound individual handshake/abort
+ calls, NOT the agent's working duration; they do not kill long agents.
+- **Frontend coupling**: ChatPage's 11-min `WORKING_FALLBACK_MS` force-clear was
+ tied to the backend 600s timeout — REMOVE it. `working` clears only on `turn.end`,
+ reconciled by `GET /turn-state` (already polled on reconnect/visibility), never a
+ timer. Otherwise a long agent's Stop button/indicator would vanish at 11 min.
+- A turn that is genuinely wedged (alive, no output, no error, user never stops)
+ blocks only ITS session until Stop/restart — accepted (vs killing real long agents).
+ If silent-wedge ever becomes real, fix it at the backend (heartbeat/error emit),
+ not a turn-kill timer.
+
+### 2.1 The model
+
+ONE authoritative `Turn` per avibe session, owned by a `SessionTurnManager` on the
+Controller (`controller.session_turns`). A session has **at most one active Turn**.
+
+```
+Turn:
+ session_id, turn_token (uuid), source (human|scheduled),
+ state: RUNNING # the only live state; terminal is transient → retire
+ context (MessageContext started under) # for Stop / interrupt / restored-poll
+ task (asyncio.Task) # for cancel
+ done_event # dispatch_turn hold-open (NO timeout — waits for the real result)
+ flush_intent: keep_queue | flush_on_release # was stop_no_flush / flush_on_cancel
+ started_at
+```
+
+State machine (per session) — just IDLE ↔ RUNNING (no timeout, no STUCK):
+
+```
+ submit(idle) terminal_result(matching token) [success/error]
+ IDLE ───────────────▶ RUNNING ───────────────────────────────────▶ (retire → IDLE; dot idle/failed; turn.end; flush)
+ ▲ │
+ │ submit(busy) └─ stop(confirmed) / cancel ──────────────▶ (retire → IDLE; dot idle, silent; turn.end)
+ │ → enqueue (runs after, in order)
+ │
+ └── boot: reset stale RUNNING dot → idle; OpenCode restore → re-enter RUNNING
+
+ A RUNNING turn stays RUNNING until the agent emits its terminal result OR the user stops it —
+ NO timer. dispatch holds open via ``await done.wait()`` with no timeout.
+```
+
+### 2.2 Projections (derived — the FSM is the single writer)
+
+| Today (scattered) | Becomes (projection of the FSM) |
+|---|---|
+| `agent_status` column | written by the FSM on RUNNING-enter (running) + terminal (idle/failed). The persisted value is the dot; `failed` stays until the next RUNNING. |
+| `in_flight` busy | `session has an active Turn (RUNNING\|STUCK)`. `/turn-state.in_flight` = that. |
+| `turn.start`/`turn.end` | emitted by the FSM on RUNNING-enter / terminal-release. `turn.end` deferred while STUCK (already the rule). |
+| turn-sink + token | the Turn owns `done_event` + `turn_token`; `terminal_result` is matched by token = the ONE active-turn guard (replaces `_is_active_turn` + `_stream_chunk`-complete + `mark_turn_complete`). |
+| queue | unchanged storage; the FSM flushes on terminal-release per `flush_intent`. |
+| sentinel | the `STUCK` state + its transitions (not an ad-hoc task pattern). |
+
+### 2.3 What stays exactly the same (the contracts)
+
+- The **two chokepoints** stay the FSM's two main transitions: inbound `handle_message` →
+ `manager.on_running(session_id)` (or the gate's `submit` already set it); outbound
+ `emit_agent_message` terminal `result` → `manager.on_terminal_result(ctx, is_error, level)`.
+- The **backend contract** is unchanged: emit exactly one terminal `result` per turn carrying the
+ token. Claude's token adoption, Codex's registry, OpenCode's poll/restore stay backend-internal —
+ the FSM just consumes the terminal result + token.
+- The **frontend contract** (1.7) is unchanged — same events, same REST, same message types. The FSM
+ emits the same events as projections.
+
+### 2.4 What the FSM ELIMINATES
+
+- 3 duplicated token guards → 1 (`Turn.is_active_emit(token)`).
+- duplicated flush contracts (runner finally vs sentinel) → 1 terminal-release handler.
+- in_flight + dot + working-bit as separate stores → 1 `Turn.state` (+ persisted dot projection).
+- the sentinel as a bespoke task → the `STUCK` state.
+- the gate decision spread across `_dispatch_async` + `_submit_scheduled_turn` → 1
+ `manager.submit(session_id, ctx, text, source)` (busy→enqueue, idle→run) used by BOTH Chat + scheduler.
+- folds in #84 (the queue re-run loses scheduled provenance) — the FSM enqueues a Turn *intent*
+ (carrying source + suppress_delivery), so a flushed scheduled run re-runs as `SOURCE_SCHEDULED` with
+ its delivery metadata, not as a plain human turn; and publishes `queue.updated` on enqueue (#3336001455).
+
+### 2.5 Home + shape
+
+`core/session_turns.py`: `class SessionTurnManager` holding `dict[session_id → Turn]`.
+Wired as `controller.session_turns`. Thin callers:
+- `internal_server._dispatch_async` → `manager.submit(...)`; `_cancel`/`_send_now`/`_turn_state` → manager.
+- `message_dispatcher.emit_agent_message` (outbound) → `manager.on_terminal_result(...)`.
+- `service.handle_message` (inbound) → `manager.on_running(...)` (idempotent confirm of submit).
+- `scheduled_tasks` → `manager.submit(source=SCHEDULED)`.
+- `controller._reset_stale_agent_status` → `manager.reset_stale()`; OpenCode restore → `manager.restore_running(session_id, ctx)`.
+The dispatch hold-open (`dispatch_turn` sink/`done_event`) stays, owned per-Turn.
+
+---
+
+## PART 3 — Migration (phased, behavior-preserving; "万无一失")
+
+- **Phase 0** — this doc + lock the edge-case catalog (Part 4) as a regression test list. ✅ when reviewed.
+- **Phase 1 — extract, don't change.** Introduce `SessionTurnManager` and MOVE the existing
+ in_flight + dot-writes + sink/token + queue + sentinel + lifecycle into it, BEHIND the current
+ external behavior. HTTP handlers / chokepoints / scheduler / restore become thin callers. **No
+ observable behavior change**; every Part-4 edge test stays green. (This is the risky-but-mechanical
+ re-homing — do it in small, individually-tested commits.)
+- **Phase 2 — collapse the reconciliation.** Now that one owner exists: unify the 3 token guards;
+ delete the duplicated flush; simplify Claude's adoption to "tag the terminal emit with the active
+ Turn's token" provided by the FSM; the sentinel becomes the STUCK transition.
+- **Phase 3 — fold in the deferred follow-ups.** #84 (scheduled provenance through the queue) +
+ #3336001455 (`queue.updated` on enqueue) fall out of the unified `submit`/enqueue.
+- Each phase = its own reviewed PR; run the Part-4 regression list + ruff + the CI groups each time.
+
+---
+
+## PART 4 — Edge-case catalog (the regression suite; from ~15 Codex rounds)
+
+Each MUST stay green through every phase (most already have tests — cited):
+
+1. Dot settles idle on success result; failed on `is_error`; notify never settles. (`test_message_dispatcher_result_fallback`)
+2. Superseded/older-token result does NOT settle the new turn's dot. (active-turn guard)
+3. Tokenless result does NOT settle when a live tokened sink exists. (the tightened guard)
+4. The 3 guards share one rule (absent/mismatched token = stale when a live tokened sink exists).
+5. Intentional stop = single silent `result` (level=silent): dot idle, NO bubble, stream released. (codex/opencode/claude `handle_stop`)
+6. Terminal failures emit `result`+`is_error` (NOT notify) on every backend path incl. OpenCode retry-exhaustion (+ `return None,False` so the idle "(No response)" doesn't reset it).
+7. Claude reused-receiver: 2nd+ turn terminal emit adopts the FIFO token → dot settles promptly (not 600s). Receiver-crash + auth + system + assistant paths.
+8. `_clear_pending_reactions` clears the whole FIFO (no stale request survives) — the false-positive class.
+9. **NO turn-duration timeout** (replaces the old timeout/sentinel tests): a RUNNING turn
+ stays running indefinitely until the agent emits its terminal result (long agents run
+ for hours, never killed); a busy session enqueues new sends; the user's Stop ends a
+ wedged turn; restart resets stale running. (Delete the `test_internal_server` 600s-timeout
+ + stuck-sentinel tests; add: long-running turn is NOT auto-settled; busy→enqueue.)
+10. Scheduled avibe run: queues behind an active Chat turn (no preempt); gets in_flight + turn.start/turn.end + Stop; IM scheduled byte-identical. (`test_scheduled_tasks`, `test_internal_server`)
+11. Restored OpenCode poll re-marks the avibe session running; IM poll does not. (`test_opencode_restore_polls`)
+12. Sidebar reconnect refetches the full loaded window (no truncation). (`WorkbenchSidebar`)
+13. `error` first-class type: in transcript+inbox, NOT counted unread. (`test_message_mirror`, `messages_service`)
+14. Empty/silent result settles + releases but does NOT persist/deliver. (`test_agent_silent_result`)
+15. avibe auth-recovery durable copy is button-free + `/setup`-actionable. (`test_agent_auth_service`)
+16. Crash recovery: stale running → idle on boot; reconnect trusts REST.
+17. `_handle_turn` returns None on dispatched success (ok=not error).
+
+---
+
+## PART 5 — Decisions (RESOLVED with Alex 2026-06-02)
+
+1. ✅ **No turn-duration timeout** — remove `TURN_STREAM_TIMEOUT` + the timed-out/stuck/sentinel
+ branch + the FE 11-min fallback. Keep transport-level health timeouts (Codex 120s RPC,
+ OpenCode 15s wait-idle). (See 2.0.)
+2. ✅ **No STUCK state / sentinel** — FSM = IDLE ↔ RUNNING.
+3. ✅ **Manager home**: `controller.session_turns` (Controller-owned).
+4. ✅ **Sticky `failed` dot**: keep (FE depends on it).
+5. ✅ **Scope**: avibe-only (gated on `agent_session_id`; IM/CLI keep the no-gate path).
+6. ✅ **#84** (scheduled provenance through the queue): Phase 3 (don't expand scope during the extract).
+7. ✅ **Inbox `replied`/`preview`**: leave as-is (server-computed, orthogonal).
+
+### Revised phases (timeout removal is the first, behavior-FIX step)
+
+- **Phase 1a** — remove the turn-duration timeout + STUCK + sentinel (backend) + the 11-min FE
+ fallback; FE relies on `/turn-state` reconciliation. This both implements the locked decision
+ AND shrinks the surface before the extract. (A real behavior fix: long agents no longer killed.)
+- **Phase 1b** — extract `SessionTurnManager` (IDLE ↔ RUNNING) as the single owner of in_flight +
+ dot + sink/token + queue + lifecycle, behavior-preserving; thin callers.
+- **Phase 2** — collapse the 3 token guards → 1; delete duplicated flush; simplify Claude adoption.
+ **Critical invariant (now that there's no timeout bail-out)**: every legitimate terminal result
+ MUST carry the active turn's token, or the (correctly strict) token guard blocks its completion and
+ the turn hangs forever. So the FSM must guarantee the token round-trips — bulletproof Claude
+ adoption, or have the FSM attach the active Turn's token at the chokepoint rather than trusting the
+ backend to echo it. (Pre-existing stale test `test_dispatcher_stream_chunk.py` updated in Phase 1a:
+ a tokenless emit must NOT complete a tokened turn — the strict rule; the hang risk is why the FSM
+ owns token round-trip.)
+- **Phase 3** — fold in #84 + `queue.updated` on enqueue (#3336001455).
diff --git a/docs/plans/workbench-dispatch-architecture.md b/docs/plans/workbench-dispatch-architecture.md
index 0ea5cb8ec..8cdba4c27 100644
--- a/docs/plans/workbench-dispatch-architecture.md
+++ b/docs/plans/workbench-dispatch-architecture.md
@@ -54,11 +54,12 @@ sections below.
path adopts the FIFO-matched pending request's token before emitting, so the
current turn completes; a turn that fails (auth error) retires its pending
request so the next turn isn't desynced.
-- **600s stream-timeout with a failed backend interrupt.** If a turn exceeds
- `TURN_STREAM_TIMEOUT` and the backend interrupt is refused/fails, the session
- is released **with a logged warning** rather than held in-flight forever — a
- permanently stuck session is worse than a rare overlap. Plain Stop is
- no-flush; timeout does not flush.
+- **No turn-duration timeout (Phase 1a, see `avibe-turn-lifecycle-fsm.md`).** An
+ agent turn may legitimately run for hours, so the controller never kills it on
+ a timer: `dispatch_turn` holds the stream open with a plain `await done.wait()`
+ until the agent's REAL terminal result. A genuinely wedged turn blocks only its
+ own session until the user's Stop ends it or a restart resets stale state. Plain
+ Stop is no-flush.
### Provenance + queue (added beyond the original plan)
diff --git a/docs/plans/workbench-message-queue.md b/docs/plans/workbench-message-queue.md
index 92d251dc6..d447e55d5 100644
--- a/docs/plans/workbench-message-queue.md
+++ b/docs/plans/workbench-message-queue.md
@@ -52,8 +52,9 @@ the Chat UI **and stop the spinner**, for both **startup** failures and
complete).
- To add: a real **error message type** (or a flagged `notify`) persisted +
rendered distinctly; the backend error emit must `_stream_chunk(kind=error)`
- **and** signal turn-complete so `dispatch_turn` closes the stream instead of
- waiting for `TURN_STREAM_TIMEOUT`.
+ **and** signal turn-complete so `dispatch_turn` closes the stream — there is no
+ turn-duration timeout, so a real terminal signal is the only thing that
+ releases the held `await done.wait()`.
## #3 — Message queue (the feature)
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index a219b171c..09b8fc4a1 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -115,14 +115,21 @@ def test_stale_result_does_not_complete_active_turn_but_still_forwards():
cb.assert_awaited_once() # but the chunk was still forwarded
-def test_result_completes_when_ctx_token_absent_fail_open():
- # Fail-open: an emit with no turn_token (IM/CLI, or a Claude result that
- # didn't adopt one) still completes — byte-identical to pre-guard behavior.
+def test_absent_ctx_token_does_not_complete_tokened_turn():
+ # When the live sink HAS a token, a result with NO turn_token is treated as stale
+ # (a superseded/older turn that didn't carry this turn's token) and must NOT
+ # complete the live turn — same rule as a mismatched token (Codex P2 #3331953260):
+ # a stray tokenless emit must not fire a premature turn.end / queue flush on the
+ # active turn. (Genuine fail-open — a TOKENLESS *sink* — is covered by
+ # test_result_kind_sets_done_event.) NOTE for the FSM refactor: with the turn-
+ # duration timeout removed, a turn whose OWN terminal result is tokenless would
+ # hang here; the FSM must guarantee every terminal result carries the active
+ # turn's token (bulletproof Claude adoption / FSM-attached token).
controller = _ControllerDouble()
done = asyncio.Event()
controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done, turn_token="T2")
asyncio.run(_stream_chunk(controller, _ctx(turn_token=None), text="final", message_id="m1", kind="result"))
- assert done.is_set(), "absent ctx token must fail open (complete)"
+ assert not done.is_set(), "tokenless emit must NOT complete a tokened (live) turn"
def test_swallows_sink_on_chunk_exception():
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 509fa31af..9566bb95d 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -18,7 +18,7 @@ from __future__ import annotations
import asyncio
import sys
from pathlib import Path
-from unittest.mock import ANY, AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock
import httpx
@@ -337,246 +337,61 @@ 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
+def test_dispatch_async_no_terminal_result_keeps_session_in_flight(monkeypatch, tmp_path):
+ """There is NO turn-duration timeout (Phase 1a): a turn whose backend never
+ emits a terminal result stays in_flight indefinitely — the slot is freed ONLY
+ by a real terminal result or a cancel, never by any timer. A long-running
+ agent can run for hours and must keep its Stop control the whole time.
- 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
+ We patch ``dispatch_turn`` to a coroutine that just sleeps (never fires the
+ turn's done_event), confirm the session is still held in_flight after a beat,
+ then cancel to clean up.
+ """
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)
+ started = asyncio.Event()
- 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
+ async def _never_settles(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
+ # Model a long agent turn: the backend accepted the prompt but hasn't
+ # produced its terminal result yet. dispatch_turn would normally hold on
+ # ``await done.wait()`` with no timeout — emulate that by just sleeping so
+ # the turn never settles on its own.
+ started.set()
+ await asyncio.sleep(60)
- 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"]
+ monkeypatch.setattr(internal_server, "dispatch_turn", _never_settles)
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".
+ resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_long", "text": "hi"})
+ assert resp.status_code == 202
+ await asyncio.wait_for(started.wait(), timeout=3)
+ # Give any (nonexistent) timer ample time to fire, then confirm the slot
+ # is STILL held — no timer auto-freed it.
+ await asyncio.sleep(0.1)
+ entry = app.state.in_flight_dispatches.get("ses_long")
+ captured["held"] = entry is not None and not entry[0].done()
+ # Only a real cancel frees the slot — clean up so the loop tears down.
+ resp_cancel = await client.post("/internal/cancel/ses_long")
+ captured["cancel_status"] = resp_cancel.status_code
for _ in range(200):
- if "cut in" in dispatched and session_id not in app.state.in_flight_dispatches:
+ if "ses_long" 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
+ captured["freed_after_cancel"] = "ses_long" not 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"
+ assert captured["held"] is True, "a turn with no terminal result is NOT auto-freed by any timer"
+ assert captured["cancel_status"] == 200, "the user's Stop ends the wedged turn"
+ assert captured["freed_after_cancel"] is True, "only a cancel (or terminal result) frees the slot"
def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index b66c2b2d4..d5eda25e8 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -17,13 +17,13 @@ import { Markdown } from '../ui/markdown';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Composer } from './Composer';
-// Last-resort failsafe for a LOST ``turn.end`` event. The controller is the
-// authority on turn end (``turn.start`` / ``turn.end`` over the bus) and its own
-// dispatch safety timeout is 600s, so a real turn always ends by then. This is
-// deliberately longer (11 min) so it only fires if the ``turn.end`` event itself
-// was dropped in transit — never while the backend could still be running, which
-// would hide Stop on a live turn (Codex P2).
-const WORKING_FALLBACK_MS = 11 * 60 * 1000;
+// While a turn is in flight, reconcile the working/Stop state against the
+// controller on this cadence (the backend ``GET /turn-state`` is authoritative).
+// This recovers a DROPPED ``turn.end`` without ever killing a live turn on a
+// timer: there is no turn-duration timeout, so a long agent (which can run for
+// hours) keeps Stop + the indicator for as long as ``/turn-state`` reports
+// ``in_flight:true``; only an idle reading (past the post-send grace) clears it.
+const WORKING_RECONCILE_INTERVAL_MS = 60 * 1000;
// Grace window after we optimistically set ``working`` from a local send before
// an idle ``/turn-state`` reading is trusted to CLEAR it. A just-sent turn isn't
@@ -105,7 +105,7 @@ export const ChatPage: React.FC = () => {
// to the latest syncTurnState, so an idle reading that arrives INSIDE the grace
// (which we can't trust to clear yet) still gets re-evaluated once the grace
// passes — otherwise a quick turn whose turn.end was missed leaves Stop stuck
- // until the 11-min fallback (Codex P2).
+ // until the next reconcile poll (Codex P2).
const graceResyncRef = useRef<number | null>(null);
const syncTurnStateRef = useRef<(() => void) | null>(null);
// Mark a turn as live: bump the epoch + stamp the time, then show Stop. Used by
@@ -250,7 +250,7 @@ export const ChatPage: React.FC = () => {
// Idle INSIDE the grace: either the registration gap (don't clear) or a
// quick turn that already finished and whose turn.end we missed (a
// backgrounded tab). Re-check once the grace expires so the latter clears
- // instead of waiting out the 11-min fallback. One pending retry at a time.
+ // instead of waiting out the next reconcile poll. One pending retry at a time.
graceResyncRef.current = window.setTimeout(() => {
graceResyncRef.current = null;
syncTurnStateRef.current?.();
@@ -351,8 +351,8 @@ export const ChatPage: React.FC = () => {
// result can belong to an EARLIER turn while a newer queued turn is
// already running, so clearing on it would hide Stop on the live turn
// (Codex P2). ``turn.end`` is the authoritative end signal; a dropped
- // turn.end is recovered by syncTurnState (reconnect / visibility) and
- // the fallback timer.
+ // turn.end is recovered by syncTurnState (reconnect / visibility / the
+ // while-working reconcile poll).
},
onTurnStart: (data) => {
// markWorking (not setWorking): bump the epoch so a syncTurnState idle
@@ -360,8 +360,9 @@ export const ChatPage: React.FC = () => {
if (data.session_id === sessionIdRef.current) markWorking();
},
onTurnEnd: (data) => {
- // The controller confirms the turn settled (result, agent error, cancel,
- // or its own timeout) — the authoritative end of the working state.
+ // The controller confirms the turn settled (terminal result, agent error,
+ // or user cancel) — the authoritative end of the working state. There is
+ // no turn-duration timeout, so this only fires on a REAL terminal signal.
if (data.session_id === sessionIdRef.current) setWorking(false);
},
onQueueUpdated: (data) => {
@@ -400,13 +401,23 @@ export const ChatPage: React.FC = () => {
return () => document.removeEventListener('visibilitychange', onVisible);
}, [sessionId, reconcile, refreshQueue, syncTurnState]);
- // Fallback timer so a turn that never emits a result doesn't pin the
- // indicator. Armed when ``working`` flips true, cleared when it flips false.
+ // Reconcile (don't kill) while a turn is in flight: there is no turn-duration
+ // timeout, so a long agent can run for hours and must keep Stop + the indicator
+ // the whole time. Instead of a force-clear timer, poll the controller's
+ // authoritative ``GET /turn-state`` on an interval while ``working`` is true AND
+ // the page is visible. ``syncTurnState``'s grace-guarded logic clears ``working``
+ // only when the backend reports ``in_flight:false`` — so a dropped ``turn.end``
+ // is recovered, while a still-running turn keeps Stop. Cleared when ``working``
+ // flips false / on unmount; skipped while hidden (visibilitychange already
+ // reconciles on resume).
useEffect(() => {
if (!working) return;
- const timer = window.setTimeout(() => setWorking(false), WORKING_FALLBACK_MS);
- return () => window.clearTimeout(timer);
- }, [working]);
+ const interval = window.setInterval(() => {
+ if (document.visibilityState !== 'visible') return;
+ void syncTurnState();
+ }, WORKING_RECONCILE_INTERVAL_MS);
+ return () => window.clearInterval(interval);
+ }, [working, syncTurnState]);
const sendMessage = useCallback(
async (text: string) => {