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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): retry invalidated owned reads
cyhb9fed2da94fc
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex ddecdc917..7ed03a032 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -81,6 +81,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// one authoritative feed read after that response settles.const authoritativeFeedLoadedRef = useRef(false);const coldRefreshRetryPendingRef = useRef(false);+ const reconcileRetryPendingRef = useRef(false);+ const refreshLoadingGenerationRef = useRef(0);+ const loadMoreLoadingGenerationRef = useRef(0);const acceptSessionMutation = useCallback(() => {readOwnershipRef.current.acceptMutation();@@ -97,6 +100,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>const refresh = useCallback(async () => {const read = readOwnershipRef.current.beginRead('inbox-feed');+ const loadingGeneration = ++refreshLoadingGenerationRef.current;setLoading(true);try {const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });@@ -117,7 +121,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>} catch (err) {console.error('[inbox] refresh failed', err);} finally {- if (readOwnershipRef.current.isLatestRead(read)) setLoading(false);+ if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);}}, [api, applyUnreadMap]);@@ -125,6 +129,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>const cursor = cursorRef.current;if (!cursor) return;const read = readOwnershipRef.current.beginRead('inbox-feed');+ const loadingGeneration = ++loadMoreLoadingGenerationRef.current;setLoadingMore(true);try {const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE, before: cursor });@@ -134,7 +139,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>} catch (err) {console.error('[inbox] load more failed', err);} finally {- if (readOwnershipRef.current.isLatestRead(read)) setLoadingMore(false);+ if (loadMoreLoadingGenerationRef.current === loadingGeneration) setLoadingMore(false);}}, [api]);@@ -170,7 +175,16 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>cache: false,handleError: false,});- if (!readOwnershipRef.current.isCurrent(read)) return;+ if (!readOwnershipRef.current.isCurrent(read)) {+ if (readOwnershipRef.current.epoch() !== read.epoch && !reconcileRetryPendingRef.current) {+ reconcileRetryPendingRef.current = true;+ queueMicrotask(() => {+ reconcileRetryPendingRef.current = false;+ void reconcile();+ });+ }+ return;+ }setInboxSessions((prev) => {const incoming = new Map(result.sessions.map((s) => [s.session_id, s]));const merged = prev.map((s) => incoming.get(s.session_id) ?? s);@@ -215,7 +229,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>handleError: false,});const row = result.sessions.find((s) => s.session_id === sessionId);- if (!readOwnershipRef.current.isCurrent(read, ['inbox-feed', `inbox-session:${sessionId}`])) return;+ if (!readOwnershipRef.current.isCurrent(read)) return;if (row) setInboxSessions((prev) => upsertSession(prev, row));applyUnreadMap(result.unread_by_session ?? {});} catch (err) {diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsxindex ce3233e80..5988dbef7 100644--- a/ui/src/context/WorkbenchProjectsProvider.tsx+++ b/ui/src/context/WorkbenchProjectsProvider.tsx@@ -123,6 +123,8 @@ 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 authoritativeProjectsLoadedRef = useRef(false);+ const bootstrapRetryPendingRef = useRef(false);const acceptSessionMutation = useCallback(() => {readOwnershipRef.current.acceptMutation();@@ -161,9 +163,26 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cconst fetchProjects = useCallback(async (options?: { cache?: boolean }) => {const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);+ const retryAfterMutation = () => {+ if (+ authoritativeProjectsLoadedRef.current ||+ readOwnershipRef.current.epoch() === read.epoch ||+ bootstrapRetryPendingRef.current+ ) {+ return;+ }+ bootstrapRetryPendingRef.current = true;+ queueMicrotask(() => {+ bootstrapRetryPendingRef.current = false;+ if (!authoritativeProjectsLoadedRef.current) void fetchProjects({ cache: false });+ });+ };try {const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });- if (!readOwnershipRef.current.isCurrent(read, 'projects')) return;+ if (!readOwnershipRef.current.isCurrent(read, 'projects')) {+ retryAfterMutation();+ return;+ }setProjects(result.projects);const pages = Object.fromEntries(Object.entries(result.sessions ?? {}).filter(([projectId]) =>@@ -172,11 +191,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c);applyBootstrapSessions(pages);setProjectsError(null);+ authoritativeProjectsLoadedRef.current = true;} catch (err) {// Don't strand consumers on an empty-state for a transient failure — keep// any list we had and surface the error (mobile shows a retry).if (readOwnershipRef.current.isCurrent(read, 'projects')) {setProjectsError(errorMessage(err) ?? String(err));+ } else {+ retryAfterMutation();}}}, [api, applyBootstrapSessions]);@@ -248,6 +270,19 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c[api, queueReconcile, takePendingReconcile],);+ const queueReconcileForSession = useCallback(+ (sessionId: string) => {+ const entry = Object.entries(sessionsRef.current).find(([, state]) =>+ state.sessions?.some((session) => session.id === sessionId),+ );+ if (!entry) return;+ const [projectId, state] = entry;+ if (!inFlightRef.current.has(projectId)) return;+ queueReconcile(projectId, state.sessions?.length ?? 0);+ },+ [queueReconcile],+ );+const reconcileProjectTree = useCallback(async () => {const bootstrapGroups = new Map<number, string[]>();const largeProjectIds: string[] = [];@@ -467,6 +502,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c},onSessionStatus: ({ session_id, agent_status }) => {acceptSessionMutation();+ queueReconcileForSession(session_id);setSessions((prev) =>patchSessionRow(prev, session_id, (s) => (s.agent_status === agent_status ? s : { ...s, agent_status })),);@@ -474,6 +510,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c},onTurnEnd: ({ session_id }) => {acceptSessionMutation();+ queueReconcileForSession(session_id);// The first turn can bind the native_session_id server-side, but the// status event only carries the dot state. Refresh the cached row so// actions gated on native binding, such as Fork session, unlock without@@ -482,7 +519,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c},});return disconnect;- }, [acceptSessionMutation, api, reconcileProjectTree, reconcileSessions, refreshCachedSessionRow]);+ }, [+ acceptSessionMutation,+ api,+ queueReconcileForSession,+ reconcileProjectTree,+ reconcileSessions,+ refreshCachedSessionRow,+ ]);const toggleExpanded = useCallback((projectId: string) => {diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsxindex 88c5a5bd5..4a5aee738 100644--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { act, render } from '@testing-library/react';+import { act, cleanup, render } from '@testing-library/react';import { useEffect } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -86,6 +86,7 @@ const inboxRow = {type FakeApi = {getWorkbenchProjectsBootstrap?: () => Promise<unknown>;listSessions?: (args: { projectId: string }) => Promise<unknown>;+ getSession?: () => Promise<unknown>;listInbox?: () => Promise<unknown>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;};@@ -110,6 +111,7 @@ describe('Workbench session read ownership', () => {});afterEach(() => {+ cleanup();apiRef.current = null;});@@ -162,6 +164,49 @@ describe('Workbench session read ownership', () => {expect(tree?.sessionsOf('proj_a').sessions).toEqual([]);});+ it('retries a cold project bootstrap invalidated by activity', async () => {+ const staleBootstrap = deferred({ projects: [project], sessions: { proj_a: { sessions: [session], next_before_id: null } } });+ const getWorkbenchProjectsBootstrap = vi.fn()+ .mockReturnValueOnce(staleBootstrap.promise)+ .mockResolvedValueOnce({ projects: [project], sessions: { proj_a: { sessions: [session], next_before_id: null } } });+ 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?.onSessionStatus?.({ session_id: session.id, agent_status: 'idle' });+ });+ await act(async () => {+ staleBootstrap.resolve({ projects: [project], sessions: { proj_a: { sessions: [session], next_before_id: null } } });+ await staleBootstrap.promise;+ });+ await settle();++ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);+ expect(tree?.projects).toEqual([project]);+ expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);+ });+it('commits concurrent reads for independent project resources', async () => {const projectARead = deferred({ sessions: [session], next_before_id: null });const projectBRead = deferred({ sessions: [sessionB], next_before_id: null });@@ -209,6 +254,58 @@ describe('Workbench session read ownership', () => {expect(tree?.sessionsOf(projectB.id).sessions).toEqual([sessionB]);});+ it('requeues a project reconcile invalidated by a lifecycle event', async () => {+ const loadedSessions = Array.from({ length: 201 }, (_, index) => ({ ...session, id: `ses_${index}` }));+ const trackedSession = loadedSessions[0];+ const staleRead = deferred({ sessions: [trackedSession], next_before_id: null });+ const listSessions = vi.fn()+ .mockReturnValueOnce(staleRead.promise)+ .mockResolvedValueOnce({ sessions: [{ ...trackedSession, agent_status: 'idle' }], next_before_id: null });+ apiRef.current = {+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({+ projects: [project],+ sessions: { [project.id]: { sessions: loadedSessions, next_before_id: null } },+ }),+ listSessions,+ getSession: vi.fn().mockResolvedValue(trackedSession),+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ };+ let handlers: WorkbenchEventHandlers | null = null;+ 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();+ act(() => {+ handlers?.onSessionStatus?.({ session_id: trackedSession.id, agent_status: 'idle' });+ });+ await act(async () => {+ staleRead.resolve({ sessions: [trackedSession], next_before_id: null });+ await staleRead.promise;+ });+ await settle();++ expect(listSessions).toHaveBeenCalledTimes(2);+ expect(tree?.sessionsOf(project.id).sessions).toEqual([{ ...trackedSession, agent_status: 'idle' }]);+ });+it('does not let an Inbox refresh issued before hide restore the card or unread count', async () => {const staleRefresh = deferred({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } });let handlers: WorkbenchEventHandlers | null = null;@@ -309,6 +406,107 @@ describe('Workbench session read ownership', () => {expect(inbox?.nextCursor).toBeNull();});+ it('retries a resume reconcile invalidated by activity', async () => {+ const staleReconcile = deferred({ sessions: [inboxRow], next_cursor: 'stale_cursor', 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)+ .mockResolvedValue({ sessions: [], next_cursor: null, unread_by_session: {} });+ let handlers: WorkbenchEventHandlers | null = null;+ apiRef.current = {+ listInbox,+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ };+ let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;+ const Probe = () => {+ const value = useWorkbenchInbox();+ useEffect(() => {+ inbox = value;+ }, [value]);+ return null;+ };++ render(+ <WorkbenchInboxProvider>+ <Probe />+ </WorkbenchInboxProvider>,+ );+ await settle();+ act(() => {+ window.dispatchEvent(new Event('focus'));+ });+ await settle();+ act(() => {+ handlers?.onSessionActivity?.({+ session_id: session.id,+ scope_id: session.scope_id,+ event: 'updated',+ visibility: 'background',+ });+ });+ await act(async () => {+ staleReconcile.resolve({ sessions: [inboxRow], next_cursor: 'stale_cursor', unread_by_session: { [session.id]: 3 } });+ await staleReconcile.promise;+ });+ await settle();++ expect(listInbox).toHaveBeenCalledTimes(3);+ expect(inbox?.inboxSessions).toEqual([]);+ expect(inbox?.nextCursor).toBeNull();+ });++ 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 } });+ const listInbox = vi.fn()+ .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } })+ .mockReturnValueOnce(refreshRead.promise)+ .mockReturnValueOnce(loadMoreRead.promise);+ 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;+ };++ render(+ <WorkbenchInboxProvider>+ <Probe />+ </WorkbenchInboxProvider>,+ );+ await settle();+ act(() => {+ void inbox?.refresh();+ void inbox?.loadMore();+ });+ await settle();+ expect(inbox?.loading).toBe(true);+ expect(inbox?.loadingMore).toBe(true);+ await act(async () => {+ refreshRead.resolve({ sessions: [inboxRow], next_cursor: 'cursor_refresh', unread_by_session: { [session.id]: 3 } });+ await refreshRead.promise;+ });+ await settle();+ expect(inbox?.loading).toBe(false);+ expect(inbox?.loadingMore).toBe(true);+ await act(async () => {+ loadMoreRead.resolve({ sessions: [], next_cursor: null, unread_by_session: { [session.id]: 3 } });+ await loadMoreRead.promise;+ });+ await settle();+ expect(inbox?.loading).toBe(false);+ expect(inbox?.loadingMore).toBe(false);+ });+it('keeps the targeted foreground-restore upsert and its cursor untouched', async () => {const listInbox = vi.fn().mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_before_restore', unread_by_session: {} })@@ -358,4 +556,58 @@ describe('Workbench session read ownership', () => {expect(inbox?.unreadBySession).toEqual({ [session.id]: 3 });expect(inbox?.nextCursor).toBe('cursor_before_restore');});++ it('keeps a targeted restore when a newer broad feed read completes first', async () => {+ const targetedRead = deferred({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });+ const broadRead = deferred({ sessions: [], next_cursor: 'cursor_after_refresh', unread_by_session: {} });+ const listInbox = vi.fn()+ .mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_before_restore', unread_by_session: {} })+ .mockReturnValueOnce(targetedRead.promise)+ .mockReturnValueOnce(broadRead.promise);+ let handlers: WorkbenchEventHandlers | null = null;+ apiRef.current = {+ listInbox,+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ };+ let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;+ const Probe = () => {+ const value = useWorkbenchInbox();+ useEffect(() => {+ inbox = value;+ }, [value]);+ return null;+ };++ render(+ <WorkbenchInboxProvider>+ <Probe />+ </WorkbenchInboxProvider>,+ );+ await settle();+ act(() => {+ handlers?.onSessionActivity?.({+ session_id: session.id,+ scope_id: session.scope_id,+ event: 'updated',+ visibility: 'foreground',+ });+ void inbox?.refresh();+ });+ await settle();+ await act(async () => {+ broadRead.resolve({ sessions: [], next_cursor: 'cursor_after_refresh', unread_by_session: {} });+ await broadRead.promise;+ });+ await act(async () => {+ targetedRead.resolve({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });+ await targetedRead.promise;+ });+ await settle();++ expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');+ });});