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): tail reconcile, interrupt timed-out turns, sync turn-state on visibility, longer stop timeout (Codex round 11)

cyh3b28a23d7098
diff --git a/core/internal_server.py b/core/internal_server.py
index c63c6fda5..d5b8251cd 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -120,13 +120,22 @@ 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"))
+ 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:
+ await controller.command_handler.handle_stop(context)
+ except Exception:
+ logger.exception("dispatch timeout: backend stop failed for session=%s", session_id)
in_flight.pop(session_id, None)
bus.publish("turn.end", {"session_id": session_id})
# Don't flush after a Stop (keep the queue) OR after a stream
- # timeout (the backend may still be running, so flushing would
- # overlap a second turn on top of it). send-now still forces a
- # flush via flush_on_cancel.
- timed_out = bool((context.platform_specific or {}).get("turn_timed_out"))
+ # timeout (the backend was just interrupted; the user can
+ # resume). send-now still forces a flush via flush_on_cancel.
should_flush = (not cancelled and not timed_out) or (session_id in flush_on_cancel)
flush_on_cancel.discard(session_id)
if should_flush:
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 69171bc33..15a90ea8f 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -144,6 +144,7 @@ def list_session_messages(
limit: int = 50,
types: Optional[Iterable[str]] = None,
include_metadata_sources: Iterable[str] = (),
+ tail: bool = False,
) -> dict[str, Any]:
"""Return messages for one session in chronological order with cursor pagination.
@@ -156,6 +157,12 @@ def list_session_messages(
when their type is filtered out — the chat transcript passes ``('show_page',)``
so Show-Page transcript marks (written with ``author='agent'`` → ``type
='assistant'``) stay visible alongside the user/result dialogue.
+
+ ``tail`` returns the most-recent ``limit`` rows (still chronological) instead
+ of the oldest page — used by the Chat page's reconnect/visibility gap
+ recovery, which needs the RECENT window (a long chat's oldest page would
+ never surface a missed latest prompt/reply). ``tail`` ignores ``after_id``
+ and returns no cursor.
"""
query = select(messages).where(messages.c.session_id == session_id)
@@ -168,6 +175,13 @@ def list_session_messages(
)
else:
query = query.where(type_filter)
+ effective_limit = min(max(int(limit), 1), 500)
+ if tail:
+ # Newest ``limit`` rows, then flip back to chronological for the caller.
+ query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit)
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+ rows.reverse()
+ return {"messages": rows, "next_after_id": None}
if after_id:
anchor = conn.execute(
select(messages.c.created_at).where(messages.c.id == after_id)
@@ -179,7 +193,6 @@ def list_session_messages(
and_(messages.c.created_at == anchor, messages.c.id > after_id),
)
)
- effective_limit = min(max(int(limit), 1), 500)
query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(effective_limit)
rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
# Compare against the clamped page size; a caller requesting > 500
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 14e1e964a..12d34848c 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -583,3 +583,23 @@ def test_inbox_ignores_draft_and_queued_activity(isolated_state):
assert row["last_activity_at"] == "2026-05-30T10:00:01Z"
assert row["last_message_author"] == "agent"
assert row["replied"] is False
+
+
+def test_list_session_messages_tail_returns_recent_window(isolated_state):
+ """``tail=True`` returns the most-recent ``limit`` rows in chronological
+ order (not the oldest page), so the Chat page's gap recovery sees the latest
+ messages even in a long session."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_tail")
+ for i in range(5):
+ _insert_msg(conn, scope_id, "ses_tail", "user", f"m{i}", f"2026-05-30T10:0{i}:00Z")
+
+ with engine.connect() as conn:
+ oldest = messages_service.list_session_messages(conn, session_id="ses_tail", limit=3)
+ recent = messages_service.list_session_messages(conn, session_id="ses_tail", limit=3, tail=True)
+ # Default page = oldest 3; tail = newest 3, still chronological.
+ assert [m["text"] for m in oldest["messages"]] == ["m0", "m1", "m2"]
+ assert [m["text"] for m in recent["messages"]] == ["m2", "m3", "m4"]
+ assert recent["next_after_id"] is None
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 8b901104f..70bb91b46 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -133,7 +133,9 @@ export const ChatPage: React.FC = () => {
const reconcile = useCallback(async () => {
if (!sessionId) return;
try {
- const res = await api.listSessionMessages(sessionId, { limit: 50 });
+ // tail: the RECENT window (not the oldest page), so a missed latest row in
+ // a long chat is actually recovered (Codex P2).
+ const res = await api.listSessionMessages(sessionId, { limit: 50, tail: true });
if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
const fresh = res.messages.filter(isTranscriptMessage);
if (fresh.length) {
@@ -316,11 +318,16 @@ export const ChatPage: React.FC = () => {
useEffect(() => {
if (!sessionId) return;
const onVisible = () => {
- if (document.visibilityState === 'visible') void reconcile();
+ if (document.visibilityState !== 'visible') return;
+ // A suspended tab can drop the reply AND the turn.end, so recover all
+ // three: missed rows, the queue, and the working/Stop state (Codex P2).
+ void reconcile();
+ void refreshQueue();
+ void syncTurnState();
};
document.addEventListener('visibilitychange', onVisible);
return () => document.removeEventListener('visibilitychange', onVisible);
- }, [sessionId, reconcile]);
+ }, [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.
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 8f19eb7d0..235c2ebe3 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -101,7 +101,7 @@ export type ApiContextType = {
getSession: (sessionId: string) => Promise<WorkbenchSession>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
archiveSession: (sessionId: string) => Promise<WorkbenchSession>;
- listSessionMessages: (sessionId: string, params?: { afterId?: string; limit?: number }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null }>;
+ listSessionMessages: (sessionId: string, params?: { afterId?: string; limit?: number; tail?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null }>;
sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;
markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;
cancelSession: (sessionId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
@@ -1122,6 +1122,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const search = new URLSearchParams();
if (params?.afterId) search.set('after_id', params.afterId);
if (params?.limit) search.set('limit', String(params.limit));
+ if (params?.tail) search.set('tail', '1');
const qs = search.toString();
const base = `/api/sessions/${encodeURIComponent(sessionId)}/messages`;
return getJson(qs ? `${base}?${qs}` : base);
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index f8d106c11..7781cb08e 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -219,7 +219,11 @@ async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None
async with httpx.AsyncClient(
transport=transport,
base_url="http://localhost",
- timeout=httpx.Timeout(5.0, connect=1.0),
+ # The cancel now WAITS for the backend interrupt to confirm before
+ # acking (so a refused stop keeps the turn cancellable), and a
+ # Claude interrupt / OpenCode abort can take a few seconds — give it
+ # room so a slow-but-successful stop isn't read-timed-out into a 500.
+ timeout=httpx.Timeout(30.0, connect=1.0),
) as client:
resp = await client.post(f"/internal/cancel/{session_id}")
except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
@@ -242,7 +246,10 @@ async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> di
async with httpx.AsyncClient(
transport=transport,
base_url="http://localhost",
- timeout=httpx.Timeout(10.0, connect=1.0),
+ # send-now interrupts the running turn before flushing, and that
+ # backend stop can take a few seconds — match the cancel timeout so a
+ # slow-but-successful interrupt isn't read-timed-out.
+ timeout=httpx.Timeout(30.0, connect=1.0),
) as client:
resp = await client.post(f"/internal/send-now/{session_id}")
except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 7d86e6b72..533902c6b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3009,6 +3009,9 @@ def sessions_messages_list(session_id: str):
limit = int(request.args.get("limit") or 50)
except (TypeError, ValueError):
limit = 50
+ # ``tail=1`` returns the most-recent window (for the Chat page's gap recovery)
+ # instead of the oldest page.
+ tail = request.args.get("tail") == "1"
engine = _projects_engine()
with engine.connect() as conn:
@@ -3030,6 +3033,7 @@ def sessions_messages_list(session_id: str):
limit=limit,
types=("user", "result", "notify"),
include_metadata_sources=("show_page",),
+ tail=tail,
)
return jsonify(result)