Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): round-17 Codex — P1 stale-result completion guard + 3 P2
cyha8994571fc10
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 403f2979e..4734f99c6 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -58,8 +58,20 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[# reply. Log + swallow, same posture as ``mirror_outbound``.logger.exception("turn on_chunk raised; dropping chunk kind=%s", kind)if kind == "result":- # The result is the turn's final answer — release the streaming- # dispatch so it can close the SSE stream right after this chunk.+ # 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).+ 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:+ returndone = sink.get("done_event")if done is not None:done.set()diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex f2d63a4eb..a092c8ae5 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -528,6 +528,15 @@ class ClaudeAgent(BaseAgent):pending_request = self._pop_pending_request(composite_key)+ # The receiver is long-lived and reused across a session's+ # turns, so ``context`` still carries the FIRST turn's+ # ``turn_token``. Adopt the token of the turn THIS result+ # belongs to (the FIFO-matched pending request) so the+ # streaming completion guard in ``_stream_chunk`` correlates+ # the result to the live sink instead of rejecting it as a+ # stale straggler. No-op for fresh sessions / absent tokens.+ self._adopt_pending_turn_token(context, pending_request)+await self.emit_result_message(context,result_text,@@ -638,6 +647,28 @@ class ClaudeAgent(BaseAgent):self._pending_requests.pop(composite_key, None)return request+ @staticmethod+ def _adopt_pending_turn_token(context: MessageContext, pending_request: Optional[AgentRequest]) -> None:+ """Copy the pending turn's ``turn_token`` onto the reused receiver context.++ Claude runs one long-lived receiver per session, so the context captured+ when it started carries the FIRST turn's ``turn_token``. The streaming+ completion guard in ``core.message_dispatcher._stream_chunk`` correlates a+ ``result`` emit to the live turn sink by that token; without this the+ current turn's result would carry a stale token and be rejected, hanging+ the SSE stream until the safety timeout. Pulling the token from the+ FIFO-matched pending request realigns it. No-op when there's no pending+ request or it carries no token (fail-open: completion stays ungated)."""+ if pending_request is None:+ return+ src = getattr(pending_request, "context", None)+ token = (getattr(src, "platform_specific", None) or {}).get("turn_token") if src is not None else None+ if not token:+ return+ if context.platform_specific is None:+ context.platform_specific = {}+ context.platform_specific["turn_token"] = token+def _has_pending_requests(self, composite_key: str) -> bool:return bool(self._pending_requests.get(composite_key))diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 657e7e7f2..1cd4d8e8e 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -261,21 +261,32 @@ def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:- """Atomically claim the session's queued messages: delete them and return- what was actually deleted (oldest first), so two racing flushers can't both- dispatch the same rows (Codex P2). Uses ``DELETE ... RETURNING`` so the- read + delete are one statement; empty list when the queue is empty.+ """Claim the session's queued messages: read them (oldest first), then delete+ them in the SAME transaction, so the rows are returned exactly once. Empty+ list when the queue is empty.++ Select-then-delete rather than ``DELETE ... RETURNING``: RETURNING needs+ SQLite >= 3.35, which the project does not pin, so on an older libsqlite the+ flush would raise — ``_flush_queue`` returns False and the send-while-busy+ queue never dispatches, stranding the user's queued follow-up (Codex P2).+ Atomic in practice: the local service is the single writer and this runs as+ one synchronous transaction, so no concurrent flush interleaves between the+ read and the delete (which is what the original RETURNING claim guarded)."""- stmt = (+ rows_q = (+ select(messages)+ .where(messages.c.session_id == session_id)+ .where(messages.c.type == QUEUED_TYPE)+ .order_by(messages.c.created_at.asc(), messages.c.id.asc())+ )+ rows = [_row_to_payload(dict(row)) for row in conn.execute(rows_q).mappings().all()]+ if not rows:+ return []+ conn.execute(delete(messages).where(messages.c.session_id == session_id).where(messages.c.type == QUEUED_TYPE)- .returning(messages))- rows = [_row_to_payload(dict(row)) for row in conn.execute(stmt).mappings().all()]- # RETURNING doesn't guarantee order; restore the queue order the caller relies- # on for the newline merge.- rows.sort(key=lambda r: (r.get("created_at") or "", r.get("id") or ""))return rowsdiff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 861ff4abb..ef08c727a 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -810,5 +810,32 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()+class AdoptPendingTurnTokenTests(unittest.TestCase):+ """``_adopt_pending_turn_token`` realigns the reused receiver's stale token+ with the turn a result belongs to, so the streaming completion guard in+ ``_stream_chunk`` correlates it to the live sink instead of rejecting it."""++ def test_adopts_pending_requests_token(self):+ # Reused receiver context still carries turn-1's token; the FIFO-matched+ # pending request is turn-2 → adopt T2 so completion correlates.+ ctx = SimpleNamespace(platform_specific={"turn_token": "T1"})+ pending = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "T2"}))+ ClaudeAgent._adopt_pending_turn_token(ctx, pending)+ self.assertEqual(ctx.platform_specific["turn_token"], "T2")++ def test_noop_without_pending_request(self):+ ctx = SimpleNamespace(platform_specific={"turn_token": "T1"})+ ClaudeAgent._adopt_pending_turn_token(ctx, None)+ self.assertEqual(ctx.platform_specific["turn_token"], "T1")++ def test_noop_when_pending_request_has_no_token(self):+ # Fail-open: nothing to adopt → leave the context untouched (completion+ # then falls back to fail-open in _stream_chunk).+ ctx = SimpleNamespace(platform_specific={"turn_token": "T1"})+ pending = SimpleNamespace(context=SimpleNamespace(platform_specific={}))+ ClaudeAgent._adopt_pending_turn_token(ctx, pending)+ self.assertEqual(ctx.platform_specific["turn_token"], "T1")++if __name__ == "__main__":unittest.main()diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.pyindex 02f76691b..a219b171c 100644--- a/tests/test_dispatcher_stream_chunk.py+++ b/tests/test_dispatcher_stream_chunk.py@@ -43,8 +43,9 @@ class _ControllerDouble:return self.active_turn_sinks.get(session_key)-def _ctx(platform="avibe", channel="C"):- return MessageContext(user_id="U", channel_id=channel, platform=platform)+def _ctx(platform="avibe", channel="C", turn_token=None):+ spec = {"turn_token": turn_token} if turn_token is not None else None+ return MessageContext(user_id="U", channel_id=channel, platform=platform, platform_specific=spec)def test_noop_when_no_sink():@@ -90,6 +91,40 @@ def test_resolves_sink_by_session_key_despite_stale_context():cb.assert_awaited_once()+def test_result_with_matching_turn_token_completes():+ # The live turn's own result (token matches the sink) completes it.+ 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="T2"), text="final", message_id="m1", kind="result"))+ assert done.is_set(), "a result for the active turn must release the stream"+++def test_stale_result_does_not_complete_active_turn_but_still_forwards():+ # A late result from a SUPERSEDED turn (token T1) resolves the CURRENT turn's+ # sink (token T2) by session key. It must NOT complete the active turn (Codex+ # P1) — otherwise dispatch pops in_flight / flushes the queue while the live+ # backend runs — but the chunk itself is still forwarded (forwarding stays+ # ungated so reused-receiver Claude chunks keep streaming).+ controller = _ControllerDouble()+ done = asyncio.Event()+ cb = AsyncMock()+ controller.register_turn_sink("avibe::C", on_chunk=cb, done_event=done, turn_token="T2")+ asyncio.run(_stream_chunk(controller, _ctx(turn_token="T1"), text="stale", message_id="m1", kind="result"))+ assert not done.is_set(), "a stale turn's result must not end the active turn"+ 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.+ 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)"++def test_swallows_sink_on_chunk_exception():controller = _ControllerDouble()diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex bbb537d70..d5b666fda 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -233,7 +233,10 @@ export const ChatPage: React.FC = () => {const res = await api.getTurnState(sessionId);if (sessionId !== sessionIdRef.current) return;if (res.in_flight) {- setWorking(true);+ // markWorking (not setWorking): bump the epoch + timestamp so an OLDER+ // overlapping sync whose idle response lands AFTER this one can't clear+ // the Stop we just confirmed live — its captured epoch is now stale (P2).+ markWorking();return;}// Idle snapshot — clear the stale indicator, but only when it's safe:@@ -248,7 +251,7 @@ export const ChatPage: React.FC = () => {} catch {/* controller unreachable — leave the indicator as-is */}- }, [api, sessionId]);+ }, [api, sessionId, markWorking]);const refresh = useCallback(async () => {if (!sessionId) return;@@ -275,8 +278,11 @@ export const ChatPage: React.FC = () => {setQueue(queued.queued ?? []);setInitialDraft(draft.text ?? '');// Restore Stop for a turn that is still running (e.g. opened in another tab- // or reloaded mid-turn).- setWorking(turnState.in_flight);+ // or reloaded mid-turn). markWorking on the live branch so a racing+ // syncTurnState idle response can't clear it; an idle load is authoritative+ // for the fresh page, so clear directly (Codex P2).+ if (turnState.in_flight) markWorking();+ else setWorking(false);} catch (err: any) {// Only surface the error if we're still on the session that failed — a// stale failure must not stamp an error onto the chat the user moved to.@@ -286,7 +292,7 @@ export const ChatPage: React.FC = () => {// its own loading state into a premature not-found / error view (Codex P2).if (sessionId === sessionIdRef.current) setLoading(false);}- }, [api, sessionId]);+ }, [api, sessionId, markWorking]);// Clear per-session state the instant the session changes (React Router swaps// only :sessionId, reusing this instance), before the new session's@@ -877,6 +883,12 @@ const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({ session, agents, onconst navigate = useNavigate();const [open, setOpen] = useState(false);const [modelsByBackend, setModelsByBackend] = useState<Record<string, string[]>>({});+ // Claude reasoning efforts are MODEL-specific (newer Opus/Sonnet add+ // xhigh/max), so the backend returns them keyed by model (plus a '' default).+ // Cached from /api/claude/models so the effort column can offer exactly the+ // efforts the selected model supports instead of a static low/medium/high+ // that hides xhigh/max (Codex P2).+ const [claudeReasoning, setClaudeReasoning] = useState<Record<string, { value: string; label: string }[]>>({});const [loadingModels, setLoadingModels] = useState(false);const [patching, setPatching] = useState(false);@@ -919,8 +931,13 @@ const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({ session, agents, on(async () => {try {let models: string[] = [];- if (backend === 'claude') models = (await api.claudeModels()).models ?? [];- else if (backend === 'codex') models = (await api.codexModels()).models ?? [];+ if (backend === 'claude') {+ const res = await api.claudeModels();+ models = res.models ?? [];+ // Capture the per-model effort sets so Column 3 can offer xhigh/max+ // only for the models that actually support them.+ if (!cancelled && res.reasoning_options) setClaudeReasoning(res.reasoning_options);+ } else if (backend === 'codex') models = (await api.codexModels()).models ?? [];else if (backend === 'opencode')// The providers endpoint returns RAW model ids per provider (never// provider-prefixed), and the OpenCode adapter resolves the override@@ -947,6 +964,20 @@ const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({ session, agents, onconst models = modelsByBackend[backend] ?? [];+ // Effort options for Column 3. Claude is model-aware: prefer the selected+ // model's reasoning set, fall back to the backend's '' default set, then the+ // static list (before /api/claude/models has resolved). The '__default__'+ // sentinel is dropped — effort is cleared by switching agents, not via a+ // pseudo-option. Other backends keep their static superset (Codex P2).+ const effortOptions = useMemo(() => {+ if (backend === 'claude') {+ const perModel = claudeReasoning[currentModel ?? ''] ?? claudeReasoning[''];+ const values = perModel?.filter((o) => o.value !== '__default__').map((o) => o.value);+ if (values && values.length) return values;+ }+ return effortOptionsFor(backend);+ }, [backend, currentModel, claudeReasoning]);+return (<Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild>@@ -1051,9 +1082,9 @@ const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({ session, agents, on)}</RouteColumn>- {/* Column 3 — Effort (options match the selected backend) */}+ {/* Column 3 — Effort (Claude: model-specific; others: backend superset) */}<RouteColumn title={t('chat.picker.effort')}>- {effortOptionsFor(backend).map((opt) => (+ {effortOptions.map((opt) => (<RouteItemkey={opt}active={opt === currentEffort}