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-16 Codex P2 — durable failure notify, inbox-visible failures, clear-on-idle Stop

cyhe662b42cb7a5
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index fd326f073..f2d63a4eb 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -122,17 +122,18 @@ class ClaudeAgent(BaseAgent):
)
if not handled:
await self.session_handler.handle_session_error(runtime_session_key, context, e)
- # ``handle_session_error`` sends through the IM client, but
- # ``AvibeBot.send_message`` doesn't persist to ``messages`` and the
- # web Chat renders only durable ``message.new`` rows — so persist a
- # terminal notify too, or the avibe user sees their prompt stop
- # with no explanation (Codex P2). Mirrors _stream_terminal_error.
- try:
- from core.message_mirror import persist_agent_message
+ # Persist a durable terminal notify in BOTH branches: the IM sends
+ # (handle_session_error / the auth-recovery reset-OAuth button via
+ # send_message_with_buttons) don't write to ``messages``, and the web
+ # Chat renders only durable ``message.new`` rows — so without this the
+ # avibe user sees their prompt stop with no explanation, including on
+ # an expired Claude login (Codex P2). Mirrors _stream_terminal_error.
+ 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 error row", exc_info=True)
+ 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
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 15a90ea8f..657e7e7f2 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -356,10 +356,12 @@ def unread_counts(
Used by the sidebar / hover popover to show per-session unread dots
plus the global count without dragging every row through Python.
- Filtered to ``type='result'`` so it agrees with the inbox feed, whose
- unread/preview/eligibility are all result-only — otherwise intermediate
- ``assistant`` / ``tool_call`` rows (now persisted for avibe too) would
- inflate the badge past what the feed shows.
+ Filtered to ``type='result'`` so it agrees with the inbox feed's UNREAD
+ count, which is also result-only — otherwise intermediate ``assistant`` /
+ ``tool_call`` rows (now persisted for avibe too) would inflate the badge
+ past what the feed shows. (Inbox *eligibility* and *preview* also accept a
+ terminal ``notify`` so failed turns stay visible, but a failure notify is
+ not an unread reply — it never bumps this badge.)
"""
query = (
@@ -448,7 +450,12 @@ def list_inbox_sessions(
any_ranked = any_ranked.subquery()
latest_any = select(any_ranked).where(any_ranked.c.rn == 1).subquery()
- # Rank agent messages by recency → latest agent reply = preview (also proves eligibility).
+ # 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.
agent_ranked = (
select(
m.c.session_id.label("session_id"),
@@ -460,7 +467,7 @@ def list_inbox_sessions(
.label("rn"),
)
.where(m.c.session_id.is_not(None))
- .where(m.c.type == "result")
+ .where(m.c.type.in_(("result", "notify")))
)
if platform is not None:
agent_ranked = agent_ranked.where(m.c.platform == platform)
@@ -563,8 +570,9 @@ def get_inbox_session(
*,
platform: Optional[str] = "avibe",
) -> Optional[dict[str, Any]]:
- """Return one session's inbox row (or None if it has no agent ``result``
- yet). Used to build realtime ``inbox.session.updated`` payloads."""
+ """Return one session's inbox row (or None if it has no agent ``result`` /
+ terminal ``notify`` yet). Used to build realtime ``inbox.session.updated``
+ payloads."""
rows = list_inbox_sessions(conn, platform=platform, only_session=session_id, limit=1)["sessions"]
return rows[0] if rows else None
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 3eda8bf8e..3e6162b7d 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -247,8 +247,9 @@ def test_persist_agent_publishes_message_and_inbox_for_avibe(isolated_state):
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`` — the inbox stays result-only, so a
- session with no ``result`` yet doesn't surface a card.
+ 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.
"""
from core import inbox_events
@@ -299,6 +300,59 @@ def test_persist_agent_intermediate_streams_but_not_inbox(isolated_state):
assert seen[0][1]["session_id"] == "ses_noresult"
+def test_persist_agent_terminal_notify_updates_inbox(isolated_state):
+ """A terminal ``notify`` (a turn that failed before any ``result``) DOES
+ publish ``inbox.session.updated`` so the failed conversation surfaces on the
+ inbox in realtime, with the error as preview — not only after a reload."""
+ from core import inbox_events
+
+ engine = create_sqlite_engine()
+ now = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_z", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_failpub",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_ses_failpub",
+ native_session_id="",
+ title="Boom",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id="ses_failpub",
+ platform="avibe",
+ platform_specific={"agent_session_id": "ses_failpub"},
+ )
+
+ async def scenario():
+ sub_id, queue = inbox_events.bus.subscribe()
+ events: dict[str, dict] = {}
+ try:
+ persist_agent_message(ctx, "notify", "❌ Claude error: boom")
+ for _ in range(2): # message.new + inbox.session.updated, any order
+ evt = await asyncio.wait_for(queue.get(), timeout=1.0)
+ events[evt[0]] = evt[1]
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+ return events
+
+ events = asyncio.run(scenario())
+ assert "inbox.session.updated" in events
+ card = events["inbox.session.updated"]
+ assert card["session_id"] == "ses_failpub"
+ assert card["preview_text"] == "❌ Claude error: boom"
+
+
def test_inbound_sets_source_user(isolated_state):
"""Human IM turns carry source='user' (origin), distinct from author role."""
mirror_inbound(_slack_ctx(), "hello there")
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 12d34848c..e62af19db 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -449,6 +449,32 @@ def test_list_inbox_sessions_per_session_feed(isolated_state):
assert b["unread_count"] == by_session["ses_b"]
+def test_list_inbox_sessions_includes_notify_only_failed_turn(isolated_state):
+ """A turn that fails before producing any ``result`` persists only a terminal
+ ``notify``; that failed conversation must still surface in the inbox (with the
+ error as preview) instead of vanishing once the user leaves the Chat page."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_titled_session(conn, scope_id, "ses_fail", "Failed")
+ _insert_msg(conn, scope_id, "ses_fail", "user", "do the thing", "2026-05-30T10:00:00Z")
+ # No ``result`` ever lands — only a terminal failure notify.
+ _insert_msg(
+ conn, scope_id, "ses_fail", "agent", "❌ Claude error: boom",
+ "2026-05-30T10:00:05Z", read=False, msg_type="notify",
+ )
+
+ with engine.connect() as conn:
+ rows = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"]
+
+ assert [r["session_id"] for r in rows] == ["ses_fail"]
+ row = rows[0]
+ # Preview is the failure notify so the user sees WHY the turn ended.
+ assert row["preview_text"] == "❌ Claude error: boom"
+ # ``replied`` reflects who spoke last (the agent's notify), not the user.
+ assert row["replied"] is False
+
+
def test_list_inbox_sessions_pagination(isolated_state):
"""Keyset 'load more' walks sessions in last-activity order."""
engine = create_sqlite_engine()
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index ed45f3474..bbb537d70 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -36,6 +36,15 @@ const effortOptionsFor = (backend: string): string[] => EFFORT_BY_BACKEND[backen
// would hide Stop on a live turn (Codex P2).
const WORKING_FALLBACK_MS = 11 * 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
+// registered in the controller's in-flight map until POST→dispatch_async lands,
+// so an idle snapshot taken inside that gap is a false negative — wait this long
+// (comfortably above dispatch latency) before letting a reconnect/visibility
+// idle check clear Stop. A genuinely stale turn (missed ``turn.end``) was set
+// working far longer ago than this, so it still clears (Codex P2).
+const WORKING_SETTLE_GRACE_MS = 4000;
+
// The transcript-visible message types — mirrors the server filter on
// ``GET /api/sessions/{id}/messages`` so the live ``message.new`` feed appends
// the same rows the initial load shows (assistant / tool_call are process log).
@@ -93,6 +102,22 @@ export const ChatPage: React.FC = () => {
// ``working`` = a turn is in flight for this session (from our send, or any
// other origin we observe). Drives the thinking bubble + the Send→Stop swap.
const [working, setWorking] = useState(false);
+ // Lifecycle guards for ``syncTurnState``'s clear-on-idle (Codex P2):
+ // - ``turnEpochRef`` bumps every time a turn STARTS (local send / send-now /
+ // observed ``turn.start``). syncTurnState captures it before its request and
+ // refuses to clear if it changed meanwhile — so an idle snapshot can't stomp
+ // a turn that started WHILE the request was in flight.
+ // - ``workingSetAtRef`` records when we last set working true, so syncTurnState
+ // can ignore an idle reading that lands inside the post-send registration gap.
+ const turnEpochRef = useRef(0);
+ const workingSetAtRef = useRef(0);
+ // 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(() => {
+ turnEpochRef.current += 1;
+ workingSetAtRef.current = Date.now();
+ setWorking(true);
+ }, []);
// Send-while-busy queue (messages sent while a turn runs, shown above the
// composer) + the loaded draft to seed the composer with.
const [queue, setQueue] = useState<WorkbenchMessage[]>([]);
@@ -197,19 +222,29 @@ export const ChatPage: React.FC = () => {
// The fire-and-forget turn survives browser disconnects, so a freshly loaded /
// reconnected page asks the controller whether a turn is still in flight and
- // restores the working/Stop state to match (Codex P2). Authoritative: clears a
- // stale working when idle, sets it when a turn is live.
+ // restores the working/Stop state to match (Codex P2). Authoritative in BOTH
+ // directions: sets Stop when a turn is live, and clears a stale Stop (a
+ // ``turn.end`` we missed while the socket was down) when the controller reports
+ // idle — guarded so it can't drop a turn that's genuinely starting.
const syncTurnState = useCallback(async () => {
if (!sessionId) return;
+ const epochAtRequest = turnEpochRef.current;
try {
const res = await api.getTurnState(sessionId);
if (sessionId !== sessionIdRef.current) return;
- // Only RESTORE Stop for a turn that's running — never clear on an idle
- // snapshot here. On reconnect/visibility a just-sent turn may not be
- // registered yet (the POST→dispatch_async→in_flight gap), so a stale idle
- // reading would wrongly drop the optimistic working state (Codex P2). A
- // genuinely-ended turn is cleared by turn.end + the fallback timer.
- if (res.in_flight) setWorking(true);
+ if (res.in_flight) {
+ setWorking(true);
+ return;
+ }
+ // Idle snapshot — clear the stale indicator, but only when it's safe:
+ // (1) no turn STARTED while this request was in flight (epoch unchanged) —
+ // 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);
} catch {
/* controller unreachable — leave the indicator as-is */
}
@@ -295,7 +330,9 @@ export const ChatPage: React.FC = () => {
// the fallback timer.
},
onTurnStart: (data) => {
- if (data.session_id === sessionIdRef.current) setWorking(true);
+ // markWorking (not setWorking): bump the epoch so a syncTurnState idle
+ // reading already in flight can't clear this freshly-started turn.
+ if (data.session_id === sessionIdRef.current) markWorking();
},
onTurnEnd: (data) => {
// The controller confirms the turn settled (result, agent error, cancel,
@@ -318,7 +355,7 @@ export const ChatPage: React.FC = () => {
},
});
return disconnect;
- }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState]);
+ }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState, markWorking]);
// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the
// SSE feed can be suspended without a clean reconnect, dropping the reply.
@@ -351,7 +388,7 @@ export const ChatPage: React.FC = () => {
// NB: no ``working`` guard — sending WHILE a turn runs is the queue
// feature; the backend enqueues it (202) instead of refusing.
if (!sessionId || !text.trim()) return;
- setWorking(true);
+ markWorking();
setError(null);
try {
// Plain (non-streaming) POST: the turn runs fire-and-forget on the
@@ -390,7 +427,7 @@ export const ChatPage: React.FC = () => {
}
}
},
- [sessionId, appendMessage, refreshQueue],
+ [sessionId, appendMessage, refreshQueue, markWorking],
);
const stopMessage = useCallback(async () => {
@@ -440,7 +477,7 @@ export const ChatPage: React.FC = () => {
// A turn is about to run (the flushed queue) — reflect it immediately so
// Stop stays available even if the controller's turn.start is missed/delayed
// (especially for the idle-flush case that starts a fresh turn) (Codex P2).
- setWorking(true);
+ markWorking();
try {
const res = await api.sendQueuedNow(sessionId, queue[0].id);
// Drop the response if the user switched chats mid-request (Codex P2).
@@ -465,7 +502,7 @@ export const ChatPage: React.FC = () => {
setError(err?.message ?? String(err));
}
}
- }, [api, sessionId, queue, t, refreshQueue]);
+ }, [api, sessionId, queue, t, refreshQueue, markWorking]);
useEffect(() => {
refresh();