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.

fix(workbench): round-18 Codex P2 — auth-failure terminal handling + grace resync

cyh8176fc9be3e8
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index a092c8ae5..079f1e482 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -513,6 +513,28 @@ 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 too: the reset-OAuth prompt
+ # goes out over the IM client but isn't a durable ``messages`` row, so
+ # persist a terminal notify (otherwise the web Chat shows nothing) and
+ # mark the streaming turn complete under its own token.
+ self._adopt_pending_turn_token(context, failed_request)
+ try:
+ from core.message_mirror import persist_agent_message
+
+ persist_agent_message(context, "notify", f"❌ Claude error: {result_text}")
+ except Exception:
+ logger.debug("claude: failed to persist auth-failure notify", exc_info=True)
+ _mark = getattr(self.controller, "mark_turn_complete", None)
+ if callable(_mark):
+ _mark(context)
mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
if callable(mark_session_idle):
mark_session_idle(composite_key)
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index b30b256b4..2eb3bf470 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -165,6 +165,19 @@ class CodexEventHandler:
"notify",
message,
)
+ else:
+ # The reset-OAuth prompt went out over the IM client
+ # (``send_message_with_buttons``) but isn't a durable ``messages``
+ # row, and the web Chat renders only durable ``message.new`` rows —
+ # so persist a terminal notify here too, or an expired Codex login
+ # stops the prompt with no on-screen explanation (Codex P2). The
+ # not-handled branch already persists via ``emit_agent_message``.
+ try:
+ from core.message_mirror import persist_agent_message
+
+ persist_agent_message(tracked_request.context, "notify", message)
+ except Exception:
+ logger.debug("codex: failed to persist auth-recovery notify", exc_info=True)
error_was_user_visible = True
else:
logger.info("Suppressing inactive Codex turn failure for %s: %s", turn_id, error_msg)
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index ef08c727a..3ade78e36 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -3,7 +3,7 @@ import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -540,11 +540,18 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)
controller._get_session_key = lambda context: "telegram::user::U1"
controller.emit_agent_message = AsyncMock()
+ controller.mark_turn_complete = MagicMock()
agent = ClaudeAgent(controller)
agent._clear_pending_reactions = AsyncMock()
agent.emit_result_message = AsyncMock()
- context = SimpleNamespace()
+ # platform=None keeps the durable notify a no-op (no real-state write);
+ # platform_specific is the dict the failed turn's token is adopted into.
+ context = SimpleNamespace(platform=None, platform_specific=None)
composite_key = "session-1:/tmp/work"
+ # A failed turn's pending request lingers in the FIFO (preserved for resume);
+ # the auth-failure path must retire it so the NEXT turn isn't desynced (#216).
+ failed_req = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "Ta"}))
+ agent._pending_requests[composite_key] = [failed_req]
current_task = asyncio.current_task()
controller.receiver_tasks[composite_key] = current_task
controller.claude_sessions[composite_key] = _StubClient()
@@ -577,6 +584,12 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
controller.session_handler.cleanup_session.assert_not_awaited()
self.assertNotIn(composite_key, controller.receiver_tasks)
self.assertNotIn(composite_key, controller.claude_sessions)
+ # #216: the failed turn's pending request was retired from the FIFO (so the
+ # next successful turn won't adopt its stale token), and the streaming Chat
+ # turn was released under that token instead of hanging to the timeout.
+ self.assertFalse(agent._pending_requests.get(composite_key))
+ self.assertEqual(context.platform_specific.get("turn_token"), "Ta")
+ controller.mark_turn_complete.assert_called_once()
agent.emit_result_message.assert_not_awaited()
async def test_init_message_binds_native_session_to_existing_agent_session(self):
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index d5b666fda..dbc6c0ce0 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -111,6 +111,13 @@ export const ChatPage: React.FC = () => {
// can ignore an idle reading that lands inside the post-send registration gap.
const turnEpochRef = useRef(0);
const workingSetAtRef = useRef(0);
+ // A single pending "re-check after the post-send grace expires" timer + a ref
+ // 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).
+ 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
// every "a turn is starting now" path so clear-on-idle stays race-safe.
const markWorking = useCallback(() => {
@@ -244,15 +251,32 @@ export const ChatPage: React.FC = () => {
// otherwise we'd stomp a turn.start that raced our idle reading;
// (2) we're past the post-send registration grace — a turn we just sent may
// not be in the controller's in-flight map yet, making this idle a
- // false negative. Inside the grace we leave Stop up; turn.start or the
- // fallback timer resolves it.
- const settled = Date.now() - workingSetAtRef.current > WORKING_SETTLE_GRACE_MS;
- if (turnEpochRef.current === epochAtRequest && settled) setWorking(false);
+ // false negative.
+ if (turnEpochRef.current !== epochAtRequest) return;
+ const sinceSet = Date.now() - workingSetAtRef.current;
+ if (sinceSet > WORKING_SETTLE_GRACE_MS) {
+ setWorking(false);
+ } else if (graceResyncRef.current === null) {
+ // 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.
+ graceResyncRef.current = window.setTimeout(() => {
+ graceResyncRef.current = null;
+ syncTurnStateRef.current?.();
+ }, WORKING_SETTLE_GRACE_MS - sinceSet + 50);
+ }
} catch {
/* controller unreachable — leave the indicator as-is */
}
}, [api, sessionId, markWorking]);
+ // Keep a ref to the latest syncTurnState so the grace-resync timer can call the
+ // current closure without baking it into a dependency cycle.
+ useEffect(() => {
+ syncTurnStateRef.current = syncTurnState;
+ }, [syncTurnState]);
+
const refresh = useCallback(async () => {
if (!sessionId) return;
setLoading(true);
@@ -309,6 +333,11 @@ export const ChatPage: React.FC = () => {
setWorking(false);
setQueue([]);
setInitialDraft(null);
+ // Drop any pending grace-resync so it can't fire against the new session.
+ if (graceResyncRef.current !== null) {
+ window.clearTimeout(graceResyncRef.current);
+ graceResyncRef.current = null;
+ }
}, [sessionId]);
// Persistent per-session subscription: append every transcript-visible