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 broad session snapshots

cyh9e74c909f8e4
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index f0e4f5245..60d6d3393 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -83,11 +83,12 @@ 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. Preserve broad intents while
- // a cursor request is active so either start order commits the requested page
- // before the broad refresh/reconcile runs.
+ // 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.
const refreshPendingRef = useRef(false);
const reconcilePendingRef = useRef(false);
+ const broadReadInFlightRef = useRef(false);
const cursorReadsInFlightRef = useRef(0);
const refreshRunnerRef = useRef<() => void>(() => {});
const reconcileRunnerRef = useRef<() => void>(() => {});
@@ -101,7 +102,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());
const flushBroadReadIntent = useCallback(() => {
- if (cursorReadsInFlightRef.current > 0) return;
+ if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) return;
if (refreshPendingRef.current) {
refreshPendingRef.current = false;
// A replacement refresh owns the same top-of-feed recovery as a pending
@@ -183,10 +184,11 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}, []);
const refresh = useCallback(async function refresh() {
- if (cursorReadsInFlightRef.current > 0) {
+ if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) {
queueRefreshIntent();
return;
}
+ broadReadInFlightRef.current = true;
refreshPendingRef.current = false;
reconcilePendingRef.current = false;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-refresh']);
@@ -229,8 +231,10 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (!retryAfterInvalidation()) console.error('[inbox] refresh failed', err);
} finally {
if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);
+ broadReadInFlightRef.current = false;
+ flushBroadReadIntent();
}
- }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots, queueRefreshIntent]);
+ }, [acceptFeedRows, api, applyUnreadMap, flushBroadReadIntent, mergeTargetedSnapshots, queueRefreshIntent]);
const loadMore = useCallback(async function loadMore() {
const cursor = cursorRef.current;
@@ -297,10 +301,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 (cursorReadsInFlightRef.current > 0) {
+ if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) {
queueReconcileIntent();
return;
}
+ broadReadInFlightRef.current = true;
reconcilePendingRef.current = false;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-reconcile']);
const retryAfterInvalidation = () => {
@@ -368,8 +373,11 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}
} catch (err) {
if (!retryAfterInvalidation()) console.error('[inbox] reconcile failed', err);
+ } finally {
+ broadReadInFlightRef.current = false;
+ flushBroadReadIntent();
}
- }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots, queueReconcileIntent]);
+ }, [acceptFeedRows, api, applyUnreadMap, flushBroadReadIntent, 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
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index dbb36916d..f81d05806 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -129,8 +129,42 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// paginated read, or targeted row read that started before a newer mutation
// must not commit its snapshot after that mutation is accepted.
const readOwnershipRef = useRef(createWorkbenchSessionReadOwnership());
- const bootstrapRetryPendingRef = useRef(false);
- const projectTreeRetryPendingRef = useRef(false);
+ // Initial/manual project fetches and reconnect bootstraps claim the same
+ // global resources. Serialize them and retain trailing intents so a later
+ // failed recovery cannot invalidate an earlier successful snapshot.
+ const bootstrapReadInFlightRef = useRef(false);
+ const fetchProjectsPendingRef = useRef<{ cache?: boolean } | null>(null);
+ const projectTreePendingRef = useRef(false);
+ const fetchProjectsRunnerRef = useRef<(options?: { cache?: boolean }) => void>(() => {});
+ const projectTreeRunnerRef = useRef<() => void>(() => {});
+
+ const flushBootstrapReadIntent = useCallback(() => {
+ if (bootstrapReadInFlightRef.current) return;
+ const pendingFetch = fetchProjectsPendingRef.current;
+ if (pendingFetch) {
+ fetchProjectsPendingRef.current = null;
+ fetchProjectsRunnerRef.current(pendingFetch);
+ return;
+ }
+ if (projectTreePendingRef.current) {
+ projectTreePendingRef.current = false;
+ projectTreeRunnerRef.current();
+ }
+ }, []);
+
+ const queueFetchProjectsIntent = useCallback((options?: { cache?: boolean }) => {
+ const pending = fetchProjectsPendingRef.current;
+ fetchProjectsPendingRef.current =
+ options?.cache === false || pending?.cache === false
+ ? { cache: false }
+ : pending ?? options ?? {};
+ queueMicrotask(flushBootstrapReadIntent);
+ }, [flushBootstrapReadIntent]);
+
+ const queueProjectTreeIntent = useCallback(() => {
+ projectTreePendingRef.current = true;
+ queueMicrotask(flushBootstrapReadIntent);
+ }, [flushBootstrapReadIntent]);
const acceptSessionMutation = useCallback((projectId?: string | null, sessionId?: string) => {
const resources = ['projects-bootstrap'];
@@ -199,20 +233,16 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}, [acceptProjectRows]);
const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
+ if (bootstrapReadInFlightRef.current) {
+ queueFetchProjectsIntent(options);
+ return;
+ }
+ bootstrapReadInFlightRef.current = true;
const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);
const retryAfterMutation = () => {
- if (
- readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap']) ||
- !readOwnershipRef.current.isLatestRead(read) ||
- bootstrapRetryPendingRef.current
- ) {
- return;
- }
- bootstrapRetryPendingRef.current = true;
- queueMicrotask(() => {
- bootstrapRetryPendingRef.current = false;
- void fetchProjects({ cache: false });
- });
+ if (readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) return;
+ // Upgrade any already-pending cached fetch to the authoritative retry.
+ queueFetchProjectsIntent({ cache: false });
};
try {
const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
@@ -241,8 +271,11 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
} else {
retryAfterMutation();
}
+ } finally {
+ bootstrapReadInFlightRef.current = false;
+ flushBootstrapReadIntent();
}
- }, [api, applyBootstrapSessions]);
+ }, [api, applyBootstrapSessions, flushBootstrapReadIntent, queueFetchProjectsIntent]);
useEffect(() => {
void fetchProjects();
@@ -314,19 +347,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
);
const reconcileProjectTree = useCallback(async function reconcileProjectTree() {
+ if (bootstrapReadInFlightRef.current) {
+ queueProjectTreeIntent();
+ return;
+ }
+ bootstrapReadInFlightRef.current = true;
const retryAfterInvalidation = (read: WorkbenchSessionReadStamp) => {
- if (
- readOwnershipRef.current.isCurrent(read, 'projects-bootstrap') ||
- !readOwnershipRef.current.isLatestRead(read) ||
- projectTreeRetryPendingRef.current
- ) {
- return;
- }
- projectTreeRetryPendingRef.current = true;
- queueMicrotask(() => {
- projectTreeRetryPendingRef.current = false;
- void reconcileProjectTree();
- });
+ if (readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;
+ queueProjectTreeIntent();
};
const bootstrapGroups = new Map<number, string[]>();
const largeProjectIds: string[] = [];
@@ -407,8 +435,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
for (const projectId of [...projectIds, ...largeProjectIds]) {
void reconcileSessions(projectId);
}
+ } finally {
+ bootstrapReadInFlightRef.current = false;
+ flushBootstrapReadIntent();
}
- }, [api, applyBootstrapSessions, queueReconcile, reconcileSessions]);
+ }, [api, applyBootstrapSessions, flushBootstrapReadIntent, queueProjectTreeIntent, queueReconcile, reconcileSessions]);
+
+ fetchProjectsRunnerRef.current = (options) => void fetchProjects(options);
+ projectTreeRunnerRef.current = () => void reconcileProjectTree();
const refreshCachedSessionRow = useCallback(async function refreshCachedSessionRow(sessionId: string) {
if (cachedRowRefreshInFlightRef.current.has(sessionId)) {
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 6968093ad..e54623be7 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -208,6 +208,56 @@ describe('Workbench session read ownership', () => {
expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);
});
+ it('serializes the initial project bootstrap with reconnect recovery', async () => {
+ const initialBootstrap = deferred({
+ projects: [project],
+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },
+ });
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockReturnValueOnce(initialBootstrap.promise)
+ .mockRejectedValueOnce(new Error('later reconnect failed'));
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: ReturnType<typeof useWorkbenchProjectsTree> | null = null;
+ const Probe = () => {
+ const value = useWorkbenchProjectsTree();
+ useEffect(() => {
+ tree = value;
+ }, [value]);
+ return null;
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <Probe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ act(() => {
+ handlers?.onConnected?.({ sub_id: 2, source: 'browser' });
+ });
+ await settle();
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ initialBootstrap.resolve({
+ projects: [project],
+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },
+ });
+ await initialBootstrap.promise;
+ });
+ await settle();
+
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);
+ expect(tree?.projects).toEqual([project]);
+ expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);
+ });
+
it('retries a cold project list invalidated by a local project upsert', async () => {
const staleBootstrap = deferred({
projects: [project, projectB],
@@ -1263,6 +1313,125 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBe('cursor_after_load_more');
});
+ it('serializes duplicate resume reconciles so a later failure cannot discard an earlier success', async () => {
+ const reconciledRow = { ...inboxRow, title: 'Recovered from the first reconcile' };
+ const firstReconcile = deferred({
+ sessions: [reconciledRow],
+ next_cursor: 'cursor_after_reconcile',
+ unread_by_session: { [session.id]: 3 },
+ });
+ const laterFailure = new Error('later reconcile failed');
+ const listInbox = vi.fn()
+ .mockResolvedValueOnce({
+ sessions: [inboxRow],
+ next_cursor: 'cursor_a',
+ unread_by_session: { [session.id]: 3 },
+ })
+ .mockReturnValueOnce(firstReconcile.promise)
+ .mockRejectedValueOnce(laterFailure);
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;
+ const Probe = () => {
+ const value = useWorkbenchInbox();
+ useEffect(() => {
+ inbox = value;
+ }, [value]);
+ return null;
+ };
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ render(
+ <WorkbenchInboxProvider>
+ <Probe />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ act(() => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ window.dispatchEvent(new Event('focus'));
+ });
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ await act(async () => {
+ firstReconcile.resolve({
+ sessions: [reconciledRow],
+ next_cursor: 'cursor_after_reconcile',
+ unread_by_session: { [session.id]: 3 },
+ });
+ await firstReconcile.promise;
+ });
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(3);
+ expect(inbox?.inboxSessions).toEqual([reconciledRow]);
+ expect(inbox?.nextCursor).toBe('cursor_a');
+ expect(consoleError).toHaveBeenCalledWith('[inbox] reconcile failed', laterFailure);
+ consoleError.mockRestore();
+ });
+
+ it('serializes duplicate refreshes so a later failure cannot discard an earlier success', async () => {
+ const refreshedRow = { ...inboxRow, title: 'Recovered from the first refresh' };
+ const firstRefresh = deferred({
+ sessions: [refreshedRow],
+ next_cursor: 'cursor_after_refresh',
+ unread_by_session: { [session.id]: 3 },
+ });
+ const laterFailure = new Error('later refresh failed');
+ const listInbox = vi.fn()
+ .mockResolvedValueOnce({
+ sessions: [inboxRow],
+ next_cursor: 'cursor_a',
+ unread_by_session: { [session.id]: 3 },
+ })
+ .mockReturnValueOnce(firstRefresh.promise)
+ .mockRejectedValueOnce(laterFailure);
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;
+ const Probe = () => {
+ const value = useWorkbenchInbox();
+ useEffect(() => {
+ inbox = value;
+ }, [value]);
+ return null;
+ };
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ render(
+ <WorkbenchInboxProvider>
+ <Probe />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ act(() => {
+ void inbox?.refresh();
+ void inbox?.refresh();
+ });
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ await act(async () => {
+ firstRefresh.resolve({
+ sessions: [refreshedRow],
+ next_cursor: 'cursor_after_refresh',
+ unread_by_session: { [session.id]: 3 },
+ });
+ await firstRefresh.promise;
+ });
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(3);
+ expect(inbox?.inboxSessions).toEqual([refreshedRow]);
+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');
+ expect(inbox?.loading).toBe(false);
+ expect(consoleError).toHaveBeenCalledWith('[inbox] refresh failed', laterFailure);
+ consoleError.mockRestore();
+ });
+
it('clears independent Inbox loading flags when reads overlap', 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 } });