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): serialize inbox feed intents

cyh0e078956d536
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 60d6d3393..ca948bb3a 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -71,6 +71,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// without re-creating its identity (and the context value) on every page.
const cursorRef = useRef<string | null>(null);
cursorRef.current = nextCursor;
+ const applyNextCursor = useCallback((cursor: string | null) => {
+ // A queued feed intent may start from the completing request's finally
+ // block, before React renders the state update. Commit both owners together
+ // so that intent always reads the logically latest cursor.
+ cursorRef.current = cursor;
+ setNextCursor(cursor);
+ }, []);
// Mirror the loaded feed so ``reconcile`` can size its re-read to the current
// window without depending on (and re-identifying with) ``inboxSessions``.
const inboxSessionsRef = useRef<InboxSession[]>([]);
@@ -83,15 +90,17 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// Every Inbox read shares one ordering fence. This covers page-one refresh,
// cursor reads, resume reconcile, and the targeted foreground-restore read.
const readOwnershipRef = useRef(createWorkbenchSessionReadOwnership());
- // Broad reads and cursor reads both own the feed. Run only one broad read at a
- // time and preserve trailing intents while it or a cursor request is active,
- // so a later failed duplicate cannot discard an earlier successful recovery.
+ // Broad reads and cursor reads both own the feed. Serialize every feed read
+ // and preserve trailing intents so response completion order cannot discard a
+ // recovery snapshot or a page the user asked to load.
const refreshPendingRef = useRef(false);
const reconcilePendingRef = useRef(false);
+ const loadMorePendingRef = useRef(false);
const broadReadInFlightRef = useRef(false);
const cursorReadsInFlightRef = useRef(0);
const refreshRunnerRef = useRef<() => void>(() => {});
const reconcileRunnerRef = useRef<() => void>(() => {});
+ const loadMoreRunnerRef = useRef<() => void>(() => {});
const reconcileSessionRef = useRef<(sessionId: string) => void>(() => {});
const refreshLoadingGenerationRef = useRef(0);
const loadMoreLoadingGenerationRef = useRef(0);
@@ -101,7 +110,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// outside the page; a later broad omission revalidates them by exact id.
const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());
- const flushBroadReadIntent = useCallback(() => {
+ const flushFeedReadIntent = useCallback(() => {
if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) return;
if (refreshPendingRef.current) {
refreshPendingRef.current = false;
@@ -114,18 +123,28 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (reconcilePendingRef.current) {
reconcilePendingRef.current = false;
reconcileRunnerRef.current();
+ return;
+ }
+ if (loadMorePendingRef.current) {
+ loadMorePendingRef.current = false;
+ loadMoreRunnerRef.current();
}
}, []);
const queueRefreshIntent = useCallback(() => {
refreshPendingRef.current = true;
- queueMicrotask(flushBroadReadIntent);
- }, [flushBroadReadIntent]);
+ queueMicrotask(flushFeedReadIntent);
+ }, [flushFeedReadIntent]);
const queueReconcileIntent = useCallback(() => {
reconcilePendingRef.current = true;
- queueMicrotask(flushBroadReadIntent);
- }, [flushBroadReadIntent]);
+ queueMicrotask(flushFeedReadIntent);
+ }, [flushFeedReadIntent]);
+
+ const queueLoadMoreIntent = useCallback(() => {
+ loadMorePendingRef.current = true;
+ queueMicrotask(flushFeedReadIntent);
+ }, [flushFeedReadIntent]);
const acceptSessionMutation = useCallback((sessionId: string) => {
readOwnershipRef.current.acceptMutation([
@@ -221,7 +240,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} else {
const snapshotsToRevalidate = acceptFeedRows(read, result.sessions);
setInboxSessions(() => mergeTargetedSnapshots(result.sessions));
- setNextCursor(result.next_cursor);
+ applyNextCursor(result.next_cursor);
for (const sessionId of snapshotsToRevalidate) reconcileSessionRef.current(sessionId);
}
if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {
@@ -232,11 +251,23 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} finally {
if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);
broadReadInFlightRef.current = false;
- flushBroadReadIntent();
+ flushFeedReadIntent();
}
- }, [acceptFeedRows, api, applyUnreadMap, flushBroadReadIntent, mergeTargetedSnapshots, queueRefreshIntent]);
+ }, [acceptFeedRows, api, applyNextCursor, applyUnreadMap, flushFeedReadIntent, mergeTargetedSnapshots, queueRefreshIntent]);
const loadMore = useCallback(async function loadMore() {
+ if (
+ broadReadInFlightRef.current ||
+ refreshPendingRef.current ||
+ reconcilePendingRef.current
+ ) {
+ queueLoadMoreIntent();
+ return;
+ }
+ // A duplicate click while the same cursor is already loading is not a new
+ // page intent. Mutation invalidation queues its retry explicitly below.
+ if (cursorReadsInFlightRef.current > 0) return;
+ loadMorePendingRef.current = false;
const cursor = cursorRef.current;
if (!cursor) return;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-cursor']);
@@ -251,7 +282,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
return;
}
setInboxSessions((prev) => appendPage(prev, result.sessions));
- setNextCursor(result.next_cursor);
+ applyNextCursor(result.next_cursor);
} catch (err) {
retryAfterInvalidation =
!readOwnershipRef.current.isCurrent(read, 'inbox-feed') &&
@@ -260,10 +291,10 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} finally {
cursorReadsInFlightRef.current -= 1;
if (loadMoreLoadingGenerationRef.current === loadingGeneration) setLoadingMore(false);
- if (retryAfterInvalidation) queueMicrotask(() => void loadMore());
- else flushBroadReadIntent();
+ if (retryAfterInvalidation) queueLoadMoreIntent();
+ else flushFeedReadIntent();
}
- }, [api, flushBroadReadIntent]);
+ }, [api, applyNextCursor, flushFeedReadIntent, queueLoadMoreIntent]);
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
@@ -301,7 +332,11 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// that arrived during the gap surface at top. No loading flag — the user
// already has content; this is a silent catch-up.
const reconcile = useCallback(async () => {
- if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) {
+ if (
+ broadReadInFlightRef.current ||
+ cursorReadsInFlightRef.current > 0 ||
+ refreshPendingRef.current
+ ) {
queueReconcileIntent();
return;
}
@@ -366,7 +401,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// between this read and the old feed — adopt result.next_cursor so "Load
// more" can page through them (loadMore dedupes the overlap).
const overlap = result.sessions.some((s) => loadedIds.has(s.session_id));
- if (!overlap) setNextCursor(result.next_cursor);
+ if (!overlap) applyNextCursor(result.next_cursor);
}
if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {
applyUnreadMap(result.unread_by_session ?? {});
@@ -375,9 +410,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (!retryAfterInvalidation()) console.error('[inbox] reconcile failed', err);
} finally {
broadReadInFlightRef.current = false;
- flushBroadReadIntent();
+ flushFeedReadIntent();
}
- }, [acceptFeedRows, api, applyUnreadMap, flushBroadReadIntent, mergeTargetedSnapshots, queueReconcileIntent]);
+ }, [acceptFeedRows, api, applyNextCursor, applyUnreadMap, flushFeedReadIntent, mergeTargetedSnapshots, queueReconcileIntent]);
// Targeted reconcile for one session (contract A6 foreground restore): fetch
// that exact session by id and upsert its card, so a restored session
@@ -428,6 +463,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
);
refreshRunnerRef.current = () => void refresh();
reconcileRunnerRef.current = () => void reconcile();
+ loadMoreRunnerRef.current = () => void loadMore();
reconcileSessionRef.current = (sessionId) => void reconcileSession(sessionId);
useEffect(() => {
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index e54623be7..4b1db3ffa 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -880,31 +880,34 @@ describe('Workbench session read ownership', () => {
expect(inbox?.unreadBySession).toEqual({ [sessionB.id]: 5 });
});
- it('retries a loaded Inbox refresh superseded by load-more', async () => {
- const staleRefresh = deferred({
- sessions: [inboxRow],
- next_cursor: 'stale_cursor',
+ it('defers a later load-more until an in-flight Inbox refresh completes', async () => {
+ const pageRow = {
+ ...inboxRow,
+ session_id: sessionB.id,
+ scope_id: sessionB.scope_id,
+ title: sessionB.title,
+ preview_message_id: 'msg_b',
+ last_activity_at: '2026-08-10T23:00:00Z',
+ };
+ const refreshedRow = { ...inboxRow, title: 'Fresh before deferred load-more' };
+ const refreshRead = deferred({
+ sessions: [refreshedRow],
+ next_cursor: 'cursor_after_refresh',
unread_by_session: { [session.id]: 3 },
});
const loadMoreRead = deferred({
- sessions: [],
+ sessions: [pageRow],
next_cursor: 'cursor_after_load_more',
unread_by_session: { [session.id]: 3 },
});
- const refreshedRow = { ...inboxRow, title: 'Fresh after explicit refresh' };
const listInbox = vi.fn()
.mockResolvedValueOnce({
sessions: [inboxRow],
next_cursor: 'cursor_a',
unread_by_session: { [session.id]: 3 },
})
- .mockReturnValueOnce(staleRefresh.promise)
- .mockReturnValueOnce(loadMoreRead.promise)
- .mockResolvedValueOnce({
- sessions: [refreshedRow],
- next_cursor: 'cursor_after_refresh',
- unread_by_session: { [session.id]: 3 },
- });
+ .mockReturnValueOnce(refreshRead.promise)
+ .mockReturnValueOnce(loadMoreRead.promise);
apiRef.current = {
listInbox,
connectWorkbenchEvents: vi.fn(() => vi.fn()),
@@ -926,30 +929,36 @@ describe('Workbench session read ownership', () => {
await settle();
act(() => {
void inbox?.refresh();
+ });
+ await settle();
+ act(() => {
void inbox?.loadMore();
});
await settle();
+ expect(listInbox).toHaveBeenCalledTimes(2);
await act(async () => {
- loadMoreRead.resolve({
- sessions: [],
- next_cursor: 'cursor_after_load_more',
+ refreshRead.resolve({
+ sessions: [refreshedRow],
+ next_cursor: 'cursor_after_refresh',
unread_by_session: { [session.id]: 3 },
});
- await loadMoreRead.promise;
+ await refreshRead.promise;
});
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(3);
+ expect(listInbox.mock.calls[2]?.[0]).toMatchObject({ before: 'cursor_after_refresh' });
await act(async () => {
- staleRefresh.resolve({
- sessions: [inboxRow],
- next_cursor: 'stale_cursor',
+ loadMoreRead.resolve({
+ sessions: [pageRow],
+ next_cursor: 'cursor_after_load_more',
unread_by_session: { [session.id]: 3 },
});
- await staleRefresh.promise;
+ await loadMoreRead.promise;
});
await settle();
- expect(listInbox).toHaveBeenCalledTimes(4);
- expect(inbox?.inboxSessions).toEqual([refreshedRow]);
- expect(inbox?.nextCursor).toBe('cursor_after_refresh');
+ expect(inbox?.inboxSessions).toEqual([refreshedRow, pageRow]);
+ expect(inbox?.nextCursor).toBe('cursor_after_load_more');
});
it('defers a later Inbox refresh until an in-flight load-more completes', async () => {
@@ -1081,15 +1090,30 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBeNull();
});
- it('retries a resume reconcile superseded by load-more', async () => {
- const staleReconcile = deferred({ sessions: [inboxRow], next_cursor: 'stale_cursor', unread_by_session: { [session.id]: 3 } });
- const loadMoreRead = deferred({ sessions: [], next_cursor: 'cursor_after_load_more', unread_by_session: { [session.id]: 3 } });
- const retryReconcile = deferred({ sessions: [inboxRow], next_cursor: 'cursor_after_reconcile', unread_by_session: { [session.id]: 3 } });
+ it('defers a later load-more until an in-flight resume reconcile completes', async () => {
+ const pageRow = {
+ ...inboxRow,
+ session_id: sessionB.id,
+ scope_id: sessionB.scope_id,
+ title: sessionB.title,
+ preview_message_id: 'msg_b',
+ last_activity_at: '2026-08-10T23:00:00Z',
+ };
+ const reconciledRow = { ...inboxRow, title: 'Fresh before deferred load-more' };
+ const reconcileRead = deferred({
+ sessions: [reconciledRow],
+ next_cursor: 'cursor_after_reconcile',
+ unread_by_session: { [session.id]: 3 },
+ });
+ const loadMoreRead = deferred({
+ sessions: [pageRow],
+ next_cursor: 'cursor_after_load_more',
+ unread_by_session: { [session.id]: 3 },
+ });
const listInbox = vi.fn()
.mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } })
- .mockReturnValueOnce(staleReconcile.promise)
- .mockReturnValueOnce(loadMoreRead.promise)
- .mockReturnValueOnce(retryReconcile.promise);
+ .mockReturnValueOnce(reconcileRead.promise)
+ .mockReturnValueOnce(loadMoreRead.promise);
let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;
const Probe = () => {
const value = useWorkbenchInbox();
@@ -1117,27 +1141,33 @@ describe('Workbench session read ownership', () => {
void inbox?.loadMore();
});
await settle();
+ expect(listInbox).toHaveBeenCalledTimes(2);
await act(async () => {
- loadMoreRead.resolve({ sessions: [], next_cursor: 'cursor_after_load_more', unread_by_session: { [session.id]: 3 } });
- await loadMoreRead.promise;
- });
- await act(async () => {
- staleReconcile.resolve({ sessions: [inboxRow], next_cursor: 'stale_cursor', unread_by_session: { [session.id]: 3 } });
- await staleReconcile.promise;
+ reconcileRead.resolve({
+ sessions: [reconciledRow],
+ next_cursor: 'cursor_after_reconcile',
+ unread_by_session: { [session.id]: 3 },
+ });
+ await reconcileRead.promise;
});
await settle();
- expect(listInbox).toHaveBeenCalledTimes(4);
+ expect(listInbox).toHaveBeenCalledTimes(3);
+ expect(listInbox.mock.calls[2]?.[0]).toMatchObject({ before: 'cursor_a' });
await act(async () => {
- retryReconcile.resolve({ sessions: [inboxRow], next_cursor: 'cursor_after_reconcile', unread_by_session: { [session.id]: 3 } });
- await retryReconcile.promise;
+ loadMoreRead.resolve({
+ sessions: [pageRow],
+ next_cursor: 'cursor_after_load_more',
+ unread_by_session: { [session.id]: 3 },
+ });
+ await loadMoreRead.promise;
});
await settle();
- expect(inbox?.inboxSessions).toEqual([inboxRow]);
+ expect(inbox?.inboxSessions).toEqual([reconciledRow, pageRow]);
expect(inbox?.nextCursor).toBe('cursor_after_load_more');
});
- it('defers a resume retry until a later load-more completes', async () => {
+ it('runs a queued resume retry before a later load-more', async () => {
const pageRow = {
...inboxRow,
session_id: sessionB.id,
@@ -1154,12 +1184,12 @@ describe('Workbench session read ownership', () => {
const loadMoreRead = deferred({
sessions: [pageRow],
next_cursor: 'cursor_after_load_more',
- unread_by_session: { [session.id]: 3 },
+ unread_by_session: {},
});
const retryReconcile = deferred({
- sessions: [inboxRow],
+ sessions: [],
next_cursor: 'cursor_after_reconcile',
- unread_by_session: { [session.id]: 3 },
+ unread_by_session: {},
});
const listInbox = vi.fn()
.mockResolvedValueOnce({
@@ -1168,11 +1198,15 @@ describe('Workbench session read ownership', () => {
unread_by_session: { [session.id]: 3 },
})
.mockReturnValueOnce(staleReconcile.promise)
- .mockReturnValueOnce(loadMoreRead.promise)
- .mockReturnValueOnce(retryReconcile.promise);
+ .mockReturnValueOnce(retryReconcile.promise)
+ .mockReturnValueOnce(loadMoreRead.promise);
+ let handlers: WorkbenchEventHandlers | null = null;
apiRef.current = {
listInbox,
- connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
};
let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;
const Probe = () => {
@@ -1194,6 +1228,12 @@ describe('Workbench session read ownership', () => {
});
await settle();
act(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'background',
+ });
void inbox?.loadMore();
});
await settle();
@@ -1208,29 +1248,27 @@ describe('Workbench session read ownership', () => {
await settle();
expect(listInbox).toHaveBeenCalledTimes(3);
await act(async () => {
- loadMoreRead.resolve({
- sessions: [pageRow],
- next_cursor: 'cursor_after_load_more',
- unread_by_session: { [session.id]: 3 },
+ retryReconcile.resolve({
+ sessions: [],
+ next_cursor: 'cursor_after_reconcile',
+ unread_by_session: {},
});
- await loadMoreRead.promise;
+ await retryReconcile.promise;
});
await settle();
expect(listInbox).toHaveBeenCalledTimes(4);
+ expect(listInbox.mock.calls[3]?.[0]).toMatchObject({ before: 'cursor_after_reconcile' });
await act(async () => {
- retryReconcile.resolve({
- sessions: [inboxRow],
- next_cursor: 'cursor_after_reconcile',
- unread_by_session: { [session.id]: 3 },
+ loadMoreRead.resolve({
+ sessions: [pageRow],
+ next_cursor: 'cursor_after_load_more',
+ unread_by_session: {},
});
- await retryReconcile.promise;
+ await loadMoreRead.promise;
});
await settle();
- expect(inbox?.inboxSessions.map((row) => row.session_id).sort()).toEqual([
- session.id,
- sessionB.id,
- ]);
+ expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([sessionB.id]);
expect(inbox?.nextCursor).toBe('cursor_after_load_more');
});
@@ -1432,14 +1470,13 @@ describe('Workbench session read ownership', () => {
consoleError.mockRestore();
});
- it('clears independent Inbox loading flags when reads overlap', async () => {
+ it('starts the load-more indicator only after a blocking refresh settles', async () => {
const refreshRead = deferred({ sessions: [inboxRow], next_cursor: 'cursor_refresh', unread_by_session: { [session.id]: 3 } });
const loadMoreRead = deferred({ sessions: [], next_cursor: null, unread_by_session: { [session.id]: 3 } });
const listInbox = vi.fn()
.mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } })
.mockReturnValueOnce(refreshRead.promise)
- .mockReturnValueOnce(loadMoreRead.promise)
- .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_refresh', unread_by_session: { [session.id]: 3 } });
+ .mockReturnValueOnce(loadMoreRead.promise);
apiRef.current = {
listInbox,
connectWorkbenchEvents: vi.fn(() => vi.fn()),
@@ -1465,7 +1502,8 @@ describe('Workbench session read ownership', () => {
});
await settle();
expect(inbox?.loading).toBe(true);
- expect(inbox?.loadingMore).toBe(true);
+ expect(inbox?.loadingMore).toBe(false);
+ expect(listInbox).toHaveBeenCalledTimes(2);
await act(async () => {
refreshRead.resolve({ sessions: [inboxRow], next_cursor: 'cursor_refresh', unread_by_session: { [session.id]: 3 } });
await refreshRead.promise;
@@ -1473,6 +1511,7 @@ describe('Workbench session read ownership', () => {
await settle();
expect(inbox?.loading).toBe(false);
expect(inbox?.loadingMore).toBe(true);
+ expect(listInbox).toHaveBeenCalledTimes(3);
await act(async () => {
loadMoreRead.resolve({ sessions: [], next_cursor: null, unread_by_session: { [session.id]: 3 } });
await loadMoreRead.promise;