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): page older chat history (#459)

Call White1e8def45337b
diff --git a/storage/messages_service.py b/storage/messages_service.py
index e283ee946..3a3ebce36 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -198,6 +198,7 @@ def list_session_messages(
*,
session_id: str,
after_id: Optional[str] = None,
+ before_id: Optional[str] = None,
limit: int = 50,
types: Optional[Iterable[str]] = None,
include_metadata_sources: Iterable[str] = (),
@@ -215,11 +216,14 @@ def list_session_messages(
so Show-Page transcript marks (written with ``author='agent'`` → ``type
='assistant'``) stay visible alongside the user/result dialogue.
+ ``before_id`` returns the page immediately older than that row, still in
+ chronological order. This powers upward history loading from the chat page.
+
``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.
+ and returns no forward cursor.
"""
query = select(messages).where(messages.c.session_id == session_id)
@@ -235,10 +239,37 @@ def list_session_messages(
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)
+ query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+ has_older = len(rows) > effective_limit
+ rows = rows[:effective_limit]
+ rows.reverse()
+ return {
+ "messages": rows,
+ "next_after_id": None,
+ "next_before_id": rows[0]["id"] if has_older and rows else None,
+ }
+ if before_id:
+ anchor = conn.execute(
+ select(messages.c.created_at).where(messages.c.id == before_id)
+ ).scalar_one_or_none()
+ if anchor is not None:
+ query = query.where(
+ or_(
+ messages.c.created_at < anchor,
+ and_(messages.c.created_at == anchor, messages.c.id < before_id),
+ )
+ )
+ query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)
rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+ has_older = len(rows) > effective_limit
+ rows = rows[:effective_limit]
rows.reverse()
- return {"messages": rows, "next_after_id": None}
+ return {
+ "messages": rows,
+ "next_after_id": None,
+ "next_before_id": rows[0]["id"] if has_older and rows else None,
+ }
if after_id:
anchor = conn.execute(
select(messages.c.created_at).where(messages.c.id == after_id)
@@ -256,7 +287,7 @@ def list_session_messages(
# would otherwise receive a full 500-row page with a null cursor and
# silently stop paginating.
next_after = rows[-1]["id"] if len(rows) == effective_limit else None
- return {"messages": rows, "next_after_id": next_after}
+ return {"messages": rows, "next_after_id": next_after, "next_before_id": None}
def first_user_text(conn: Connection, session_id: str) -> str:
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index d88c4590a..457e40152 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -730,6 +730,37 @@ def test_list_session_messages_tail_returns_recent_window(isolated_state):
assert recent["next_after_id"] is None
+def test_list_session_messages_before_id_returns_older_window(isolated_state):
+ """The chat page opens on the recent tail, then pages upward from the first
+ loaded row to recover the older transcript without replacing the tail."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_before")
+ for i in range(6):
+ _insert_msg(conn, scope_id, "ses_before", "user", f"m{i}", f"2026-05-30T10:0{i}:00Z")
+
+ with engine.connect() as conn:
+ recent = messages_service.list_session_messages(conn, session_id="ses_before", limit=2, tail=True)
+ older = messages_service.list_session_messages(
+ conn,
+ session_id="ses_before",
+ limit=2,
+ before_id=recent["next_before_id"],
+ )
+ oldest = messages_service.list_session_messages(
+ conn,
+ session_id="ses_before",
+ limit=2,
+ before_id=older["next_before_id"],
+ )
+
+ assert [m["text"] for m in recent["messages"]] == ["m4", "m5"]
+ assert [m["text"] for m in older["messages"]] == ["m2", "m3"]
+ assert [m["text"] for m in oldest["messages"]] == ["m0", "m1"]
+ assert oldest["next_before_id"] is None
+
+
def test_quick_reply_choice_recorded_on_agent_message_once(isolated_state):
"""The chosen quick-reply is recorded on the AGENT message itself (the single
source of truth for the locked/answered state), once, and only for offered
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index de130f9af..1044df49a 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -107,6 +107,11 @@ export const ChatPage: React.FC = () => {
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [defaultAgentName, setDefaultAgentName] = useState<string | null>(null);
const [messages, setMessages] = useState<WorkbenchMessage[]>([]);
+ const [olderCursor, setOlderCursor] = useState<string | null>(null);
+ const [loadingOlder, setLoadingOlder] = useState(false);
+ const loadingOlderRef = useRef(false);
+ const oldestLoadedIdRef = useRef<string | null>(null);
+ const newestLoadedIdRef = useRef<string | null>(null);
const [messageFontSize, setMessageFontSize] = useState(() => normalizeChatMessageFontSize(undefined));
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -168,6 +173,11 @@ export const ChatPage: React.FC = () => {
setMessages((prev) => (prev.some((m) => m.id === msg.id) ? prev : mergeById(prev, [msg])));
}, []);
+ useEffect(() => {
+ oldestLoadedIdRef.current = messages[0]?.id ?? null;
+ newestLoadedIdRef.current = messages[messages.length - 1]?.id ?? null;
+ }, [messages]);
+
// Reconcile against durable storage after a window where ``message.new`` could
// have been missed — the SSE broker is an in-memory fan-out with no replay, so
// a reconnect or a backgrounded mobile tab can drop events while the reply is
@@ -187,7 +197,17 @@ export const ChatPage: React.FC = () => {
if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
const fresh = res.messages.filter(isTranscriptMessage);
if (fresh.length) {
+ const tailOldestId = fresh[0].id;
+ const previousOldestId = oldestLoadedIdRef.current;
+ const previousNewestId = newestLoadedIdRef.current;
setMessages((prev) => mergeById(prev, fresh));
+ if (
+ previousOldestId &&
+ previousNewestId &&
+ tailOldestId > previousNewestId
+ ) {
+ setOlderCursor(res.next_before_id ?? null);
+ }
}
} catch {
/* keep the current transcript; the next reconnect retries */
@@ -207,6 +227,28 @@ export const ChatPage: React.FC = () => {
}
}, [api, sessionId]);
+ const loadOlderMessages = useCallback(async () => {
+ if (!sessionId || !olderCursor || loadingOlderRef.current) return;
+ loadingOlderRef.current = true;
+ setLoadingOlder(true);
+ try {
+ const res = await api.listSessionMessages(sessionId, { limit: 50, beforeId: olderCursor });
+ if (sessionId !== sessionIdRef.current) return; // switched chats mid-fetch
+ const older = res.messages.filter(isTranscriptMessage);
+ if (older.length) {
+ setMessages((prev) => mergeById(prev, older));
+ }
+ setOlderCursor(res.next_before_id ?? null);
+ } catch {
+ /* keep the current transcript; another scroll can retry */
+ } finally {
+ if (sessionId === sessionIdRef.current) {
+ loadingOlderRef.current = false;
+ setLoadingOlder(false);
+ }
+ }
+ }, [api, olderCursor, sessionId]);
+
// Persist the composer's unsent text server-side (debounced) so it survives a
// reload / device switch. The send path clears it server-side; this only
// saves while typing.
@@ -318,6 +360,7 @@ export const ChatPage: React.FC = () => {
// Merge (not replace) so a row that arrived over the stream during the
// load isn't clobbered; the session-change reset keeps prior sessions out.
setMessages((prev) => mergeById(msgs.messages, prev));
+ setOlderCursor(msgs.next_before_id ?? null);
setQueue(queued.queued ?? []);
setInitialDraft(draft.text ?? '');
// Restore Stop for a turn that is still running (e.g. opened in another tab
@@ -349,6 +392,11 @@ export const ChatPage: React.FC = () => {
// loading state until refresh() resolves the new session.
setSession(null);
setMessages([]);
+ setOlderCursor(null);
+ oldestLoadedIdRef.current = null;
+ newestLoadedIdRef.current = null;
+ loadingOlderRef.current = false;
+ setLoadingOlder(false);
setWorking(false);
setQueue([]);
setInitialDraft(null);
@@ -802,6 +850,9 @@ export const ChatPage: React.FC = () => {
messages={messages}
session={session}
working={working}
+ hasOlder={!!olderCursor}
+ loadingOlder={loadingOlder}
+ onLoadOlder={loadOlderMessages}
messageFontSize={messageFontSize}
onQuickReply={handleQuickReply}
/>
@@ -1030,11 +1081,23 @@ interface TranscriptProps {
messages: WorkbenchMessage[];
session: WorkbenchSession;
working: boolean;
+ hasOlder: boolean;
+ loadingOlder: boolean;
+ onLoadOlder: () => void;
messageFontSize: number;
onQuickReply: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
}
-const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, messageFontSize, onQuickReply }) => {
+const Transcript: React.FC<TranscriptProps> = ({
+ messages,
+ session,
+ working,
+ hasOlder,
+ loadingOlder,
+ onLoadOlder,
+ messageFontSize,
+ onQuickReply,
+}) => {
const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
@@ -1050,6 +1113,11 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, mes
const anchorRef = useRef<{ el: HTMLElement; top: number } | null>(null);
const lastSessionRef = useRef<string | null>(null);
const [showJump, setShowJump] = useState(false);
+ const loadOlderRef = useRef(onLoadOlder);
+
+ useEffect(() => {
+ loadOlderRef.current = onLoadOlder;
+ }, [onLoadOlder]);
// The reply arrives atomically as a persisted ``result`` row (no streaming
// card), so the thinking bubble shows for the whole gap between send and
@@ -1107,6 +1175,9 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, mes
// is free to grow). Re-capturing here keeps it current as the user scrolls.
if (pinned) anchorRef.current = null;
else captureAnchor();
+ if (hasOlder && !loadingOlder && el.scrollTop < 120) {
+ loadOlderRef.current();
+ }
};
// Open each session pinned to the latest message (instant, no animation) —
@@ -1170,6 +1241,11 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, mes
<div className="relative flex min-h-0 flex-1 flex-col">
<div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
+ {loadingOlder && (
+ <div className="flex h-8 items-center justify-center text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ )}
{messages.map((message) => (
<MessageRow
key={message.id}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 7e671ba0b..dc2104470 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -157,7 +157,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; tail?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null }>;
+ listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; limit?: number; tail?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_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 }>;
@@ -1390,6 +1390,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
listSessionMessages: (sessionId, params) => {
const search = new URLSearchParams();
if (params?.afterId) search.set('after_id', params.afterId);
+ if (params?.beforeId) search.set('before_id', params.beforeId);
if (params?.limit) search.set('limit', String(params.limit));
if (params?.tail) search.set('tail', '1');
const qs = search.toString();
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 23ce3420e..770392218 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3443,6 +3443,7 @@ def sessions_messages_list(session_id: str):
limit = int(request.args.get("limit") or 50)
except (TypeError, ValueError):
limit = 50
+ before_id = request.args.get("before_id") or None
# ``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"
@@ -3464,6 +3465,7 @@ def sessions_messages_list(session_id: str):
conn,
session_id=session_id,
after_id=after_id,
+ before_id=before_id,
limit=limit,
types=messages_service.TRANSCRIPT_TYPES,
include_metadata_sources=("show_page",),