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): complete session read ownership
cyhbdbfa46003c9
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex ca948bb3a..21fb61b23 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -32,8 +32,10 @@ const upsertSession = (list: InboxSession[], row: InboxSession): InboxSession[]};const appendPage = (prev: InboxSession[], page: InboxSession[]): InboxSession[] => {- const seen = new Set(prev.map((s) => s.session_id));- const merged = prev.concat(page.filter((s) => !seen.has(s.session_id)));+ const incoming = new Map(page.map((row) => [row.session_id, row]));+ const merged = prev.map((row) => incoming.get(row.session_id) ?? row);+ const seen = new Set(prev.map((row) => row.session_id));+ for (const row of page) if (!seen.has(row.session_id)) merged.push(row);merged.sort(byActivityDesc);return merged;};@@ -109,6 +111,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// replacement cannot erase a restored card merely because the row sorts// outside the page; a later broad omission revalidates them by exact id.const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());+ const targetedReadInFlightRef = useRef<Set<string>>(new Set());+ const targetedReadPendingRef = useRef<Set<string>>(new Set());+ const committedWholeUnreadGenerationRef = useRef(0);const flushFeedReadIntent = useCallback(() => {if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) return;@@ -168,6 +173,17 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>setUnreadLoaded(true);}, []);+ const applyWholeUnreadRead = useCallback((+ read: WorkbenchSessionReadStamp,+ map: Record<string, number>,+ ) => {+ committedWholeUnreadGenerationRef.current = Math.max(+ committedWholeUnreadGenerationRef.current,+ read.generation,+ );+ applyUnreadMap(map);+ }, [applyUnreadMap]);+const applySessionUnread = useCallback((sessionId: string, count: number) => {setUnreadBySession((prev) => {const next = { ...prev };@@ -188,18 +204,30 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>return next;}, []);- const acceptFeedRows = useCallback((read: WorkbenchSessionReadStamp, rows: InboxSession[]) => {+ const acceptFeedRows = useCallback((+ read: WorkbenchSessionReadStamp,+ rows: InboxSession[],+ revalidateOmissions = false,+ ) => {const returnedIds = new Set(rows.map((row) => row.session_id));for (const row of rows) {const resource = `inbox-session:${row.session_id}`;readOwnershipRef.current.claimRead(read, resource);if (readOwnershipRef.current.isCurrent(read, resource)) {targetedSnapshotsRef.current.delete(row.session_id);+ targetedReadPendingRef.current.delete(row.session_id);}}- return Array.from(targetedSnapshotsRef.current.entries())- .filter(([sessionId, snapshot]) => snapshot.row && !returnedIds.has(sessionId))- .map(([sessionId]) => sessionId);+ if (!revalidateOmissions) return [];+ const omitted = new Set(+ Array.from(targetedSnapshotsRef.current.entries())+ .filter(([sessionId, snapshot]) => snapshot.row && !returnedIds.has(sessionId))+ .map(([sessionId]) => sessionId),+ );+ for (const sessionId of targetedReadInFlightRef.current) {+ if (!returnedIds.has(sessionId)) omitted.add(sessionId);+ }+ return Array.from(omitted);}, []);const refresh = useCallback(async function refresh() {@@ -238,13 +266,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>if (!feedCurrent) {retryAfterInvalidation();} else {- const snapshotsToRevalidate = acceptFeedRows(read, result.sessions);+ const snapshotsToRevalidate = acceptFeedRows(read, result.sessions, true);setInboxSessions(() => mergeTargetedSnapshots(result.sessions));applyNextCursor(result.next_cursor);for (const sessionId of snapshotsToRevalidate) reconcileSessionRef.current(sessionId);}if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {- applyUnreadMap(result.unread_by_session ?? {});+ applyWholeUnreadRead(read, result.unread_by_session ?? {});}} catch (err) {if (!retryAfterInvalidation()) console.error('[inbox] refresh failed', err);@@ -253,7 +281,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>broadReadInFlightRef.current = false;flushFeedReadIntent();}- }, [acceptFeedRows, api, applyNextCursor, applyUnreadMap, flushFeedReadIntent, mergeTargetedSnapshots, queueRefreshIntent]);+ }, [acceptFeedRows, api, applyNextCursor, applyWholeUnreadRead, flushFeedReadIntent, mergeTargetedSnapshots, queueRefreshIntent]);const loadMore = useCallback(async function loadMore() {if (@@ -281,7 +309,8 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>retryAfterInvalidation = readOwnershipRef.current.isLatestRead(read);return;}- setInboxSessions((prev) => appendPage(prev, result.sessions));+ acceptFeedRows(read, result.sessions);+ setInboxSessions((prev) => mergeTargetedSnapshots(appendPage(prev, result.sessions)));applyNextCursor(result.next_cursor);} catch (err) {retryAfterInvalidation =@@ -294,7 +323,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>if (retryAfterInvalidation) queueLoadMoreIntent();else flushFeedReadIntent();}- }, [api, applyNextCursor, flushFeedReadIntent, queueLoadMoreIntent]);+ }, [acceptFeedRows, api, applyNextCursor, flushFeedReadIntent, mergeTargetedSnapshots, queueLoadMoreIntent]);const markRead = useCallback(async (sessionId: string, untilMessageId?: string) => {@@ -381,7 +410,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>if (!feedCurrent || supersededByCursorRead || supersededByReconcileRead) {retryAfterInvalidation();} else {- const snapshotsToRevalidate = acceptFeedRows(read, result.sessions);+ const snapshotsToRevalidate = acceptFeedRows(read, result.sessions, true);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);@@ -404,7 +433,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>if (!overlap) applyNextCursor(result.next_cursor);}if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {- applyUnreadMap(result.unread_by_session ?? {});+ applyWholeUnreadRead(read, result.unread_by_session ?? {});}} catch (err) {if (!retryAfterInvalidation()) console.error('[inbox] reconcile failed', err);@@ -412,7 +441,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>broadReadInFlightRef.current = false;flushFeedReadIntent();}- }, [acceptFeedRows, api, applyNextCursor, applyUnreadMap, flushFeedReadIntent, mergeTargetedSnapshots, queueReconcileIntent]);+ }, [acceptFeedRows, api, applyNextCursor, applyWholeUnreadRead, 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@@ -422,44 +451,58 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// Never touches the cursor or replaces unrelated unread state.const reconcileSession = useCallback(async (sessionId: string) => {- const sessionResource = `inbox-session:${sessionId}`;- const unreadResource = `inbox-unread-session:${sessionId}`;- const read = readOwnershipRef.current.beginRead([sessionResource, unreadResource]);+ if (targetedReadInFlightRef.current.has(sessionId)) {+ targetedReadPendingRef.current.add(sessionId);+ return;+ }+ targetedReadInFlightRef.current.add(sessionId);try {- const result = await api.listInbox({- platform: 'avibe',- onlySession: sessionId,- limit: 1,- cache: false,- handleError: false,- });- const row = result.sessions.find((s) => s.session_id === sessionId);- if (readOwnershipRef.current.isCurrent(read, sessionResource)) {- targetedSnapshotsRef.current.set(sessionId, { row: row ?? null });- setInboxSessions((prev) =>- row ? upsertSession(prev, row) : prev.filter((candidate) => candidate.session_id !== sessionId),- );- }- const newerWholeUnreadRead =- (readOwnershipRef.current.latestGeneration('inbox-unread') ?? 0) > read.generation;- if (- readOwnershipRef.current.isCurrent(read, unreadResource) &&- readOwnershipRef.current.isMutationCurrent(read, 'inbox-unread-all') &&- !newerWholeUnreadRead- ) {- const unreadCount = result.unread_by_session?.[sessionId] ?? 0;- setUnreadBySession((prev) => {- const next = { ...prev };- if (unreadCount > 0) next[sessionId] = unreadCount;- else delete next[sessionId];- return next;- });+ while (true) {+ targetedReadPendingRef.current.delete(sessionId);+ const sessionResource = `inbox-session:${sessionId}`;+ const unreadResource = `inbox-unread-session:${sessionId}`;+ const read = readOwnershipRef.current.beginRead([sessionResource, unreadResource]);+ try {+ const result = await api.listInbox({+ platform: 'avibe',+ onlySession: sessionId,+ limit: 1,+ cache: false,+ handleError: false,+ });+ const supersededByPendingIntent = targetedReadPendingRef.current.has(sessionId);+ const row = result.sessions.find((s) => s.session_id === sessionId);+ if (+ !supersededByPendingIntent &&+ readOwnershipRef.current.isCurrent(read, sessionResource)+ ) {+ targetedSnapshotsRef.current.set(sessionId, { row: row ?? null });+ setInboxSessions((prev) =>+ row+ ? upsertSession(prev, row)+ : prev.filter((candidate) => candidate.session_id !== sessionId),+ );+ }+ const newerCommittedWholeUnread =+ committedWholeUnreadGenerationRef.current > read.generation;+ if (+ !supersededByPendingIntent &&+ readOwnershipRef.current.isCurrent(read, unreadResource) &&+ readOwnershipRef.current.isMutationCurrent(read, 'inbox-unread-all') &&+ !newerCommittedWholeUnread+ ) {+ applySessionUnread(sessionId, result.unread_by_session?.[sessionId] ?? 0);+ }+ } catch (err) {+ console.error('[inbox] reconcileSession failed', err);+ }+ if (!targetedReadPendingRef.current.has(sessionId)) return;}- } catch (err) {- console.error('[inbox] reconcileSession failed', err);+ } finally {+ targetedReadInFlightRef.current.delete(sessionId);}},- [api],+ [api, applySessionUnread],);refreshRunnerRef.current = () => void refresh();reconcileRunnerRef.current = () => void reconcile();diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsxindex f81d05806..53e80af68 100644--- a/ui/src/context/WorkbenchProjectsProvider.tsx+++ b/ui/src/context/WorkbenchProjectsProvider.tsx@@ -353,7 +353,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c}bootstrapReadInFlightRef.current = true;const retryAfterInvalidation = (read: WorkbenchSessionReadStamp) => {- if (readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;+ if (readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) return;queueProjectTreeIntent();};const bootstrapGroups = new Map<number, string[]>();@@ -417,7 +417,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c);applyBootstrapSessions(read, currentPages);}- if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {+ if (!readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) {retryAfterInvalidation(read);return;}@@ -426,7 +426,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cvoid reconcileSessions(projectId);}} catch (err) {- if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {+ if (!readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) {retryAfterInvalidation(read);return;}diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsxindex 4b1db3ffa..0cffcdd2c 100644--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx@@ -306,6 +306,68 @@ describe('Workbench session read ownership', () => {expect(tree?.projects).toEqual([project, projectB]);});+ it('retries reconnect project recovery invalidated by a local project upsert', async () => {+ const recoveredProject = { ...project, display_name: 'Project A from recovery' };+ const localProject = { ...project, display_name: 'Project A opened locally' };+ const staleReconnect = deferred({+ projects: [recoveredProject, projectB],+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },+ });+ const getWorkbenchProjectsBootstrap = vi.fn()+ .mockResolvedValueOnce({+ projects: [project],+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },+ })+ .mockReturnValueOnce(staleReconnect.promise)+ .mockResolvedValueOnce({+ projects: [localProject, projectB],+ sessions: { [project.id]: { 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?.onConnected?.({ sub_id: 3, source: 'browser' });+ });+ await settle();+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);+ act(() => {+ tree?.upsertProjectToTop(localProject);+ });+ await act(async () => {+ staleReconnect.resolve({+ projects: [recoveredProject, projectB],+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },+ });+ await staleReconnect.promise;+ });+ await settle();++ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(3);+ expect(tree?.projects).toEqual([localProject, projectB]);+ expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);+ });+it('retries an expanded project first-page read invalidated by activity', async () => {const staleFirstPage = deferred({ sessions: [session], next_before_id: null });const listSessions = vi.fn()@@ -1631,7 +1693,8 @@ describe('Workbench session read ownership', () => {const listInbox = vi.fn().mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_before_restore', unread_by_session: {} }).mockReturnValueOnce(targetedRead.promise)- .mockReturnValueOnce(broadRead.promise);+ .mockReturnValueOnce(broadRead.promise)+ .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });let handlers: WorkbenchEventHandlers | null = null;apiRef.current = {listInbox,@@ -1675,11 +1738,186 @@ describe('Workbench session read ownership', () => {});await settle();+ expect(listInbox).toHaveBeenCalledTimes(4);expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);- expect(inbox?.unreadBySession).toEqual({ [sessionB.id]: 5 });+ expect(inbox?.unreadBySession).toEqual({ [sessionB.id]: 5, [session.id]: 3 });+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');+ });++ it('revalidates an in-flight targeted read omitted by a newer broad refresh', 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 exactRevalidation = deferred({ sessions: [], next_cursor: null, unread_by_session: {} });+ const listInbox = vi.fn()+ .mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_before_restore', unread_by_session: {} })+ .mockReturnValueOnce(targetedRead.promise)+ .mockReturnValueOnce(broadRead.promise)+ .mockReturnValueOnce(exactRevalidation.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(listInbox).toHaveBeenCalledTimes(4);+ expect(inbox?.inboxSessions).toEqual([]);+ expect(inbox?.unreadBySession).toEqual({});+ await act(async () => {+ exactRevalidation.resolve({ sessions: [], next_cursor: null, unread_by_session: {} });+ await exactRevalidation.promise;+ });+ await settle();++ expect(inbox?.inboxSessions).toEqual([]);+ expect(inbox?.unreadBySession).toEqual({});expect(inbox?.nextCursor).toBe('cursor_after_refresh');});+ it('keeps targeted unread data when a newer broad refresh fails', async () => {+ const targetedRead = deferred({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });+ const refreshFailure = new Error('refresh failed');+ const listInbox = vi.fn()+ .mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_before_restore', unread_by_session: {} })+ .mockReturnValueOnce(targetedRead.promise)+ .mockRejectedValueOnce(refreshFailure);+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ 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 () => {+ targetedRead.resolve({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });+ await targetedRead.promise;+ });+ await settle();++ expect(inbox?.inboxSessions).toEqual([inboxRow]);+ expect(inbox?.unreadBySession).toEqual({ [session.id]: 3 });+ expect(inbox?.nextCursor).toBe('cursor_before_restore');+ expect(consoleError).toHaveBeenCalledWith('[inbox] refresh failed', refreshFailure);+ consoleError.mockRestore();+ });++ it('lets a newer cursor page replace a targeted session snapshot', async () => {+ const pagedRow = {+ ...inboxRow,+ title: 'Fresh from cursor page',+ last_activity_at: '2026-08-11T02:00:00Z',+ };+ const listInbox = vi.fn()+ .mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_a', unread_by_session: {} })+ .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } })+ .mockResolvedValueOnce({ sessions: [pagedRow], 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(() => {+ handlers?.onSessionActivity?.({+ session_id: session.id,+ scope_id: session.scope_id,+ event: 'updated',+ visibility: 'foreground',+ });+ });+ await settle();+ act(() => {+ void inbox?.loadMore();+ });+ await settle();++ expect(listInbox).toHaveBeenCalledTimes(3);+ expect(listInbox.mock.calls[2]?.[0]).toMatchObject({ before: 'cursor_a' });+ expect(inbox?.inboxSessions).toEqual([pagedRow]);+ expect(inbox?.unreadBySession).toEqual({ [session.id]: 3 });+ expect(inbox?.nextCursor).toBeNull();+ });+it('does not let an older targeted row replace a newer broad row that completed first', async () => {const refreshedRow = {...inboxRow,