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): preserve ordered read intents
cyhfbc4bda93f84
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex 2f96fd613..98cbc3080 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -83,11 +83,9 @@ 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());- // A stale cold-start snapshot cannot be replaced by an event patch alone: the- // event may have dropped a card that was never loaded in this provider. Retry- // one authoritative feed read after that response settles.- const authoritativeFeedLoadedRef = useRef(false);- const coldRefreshRetryPendingRef = useRef(false);+ // A stale refresh cannot be replaced by an event patch or cursor page alone:+ // neither operation owns the full top-of-feed snapshot requested by refresh.+ const refreshRetryPendingRef = useRef(false);const reconcileRetryPendingRef = useRef(false);const refreshLoadingGenerationRef = useRef(0);const loadMoreLoadingGenerationRef = useRef(0);@@ -119,6 +117,16 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>setUnreadLoaded(true);}, []);+ const applySessionUnread = useCallback((sessionId: string, count: number) => {+ setUnreadBySession((prev) => {+ const next = { ...prev };+ if (count > 0) next[sessionId] = count;+ else delete next[sessionId];+ return next;+ });+ setUnreadLoaded(true);+ }, []);+const mergeTargetedSnapshots = useCallback((rows: InboxSession[]): InboxSession[] => {let next = rows;for (const [sessionId, snapshot] of targetedSnapshotsRef.current) {@@ -139,32 +147,48 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}}, []);- const refresh = useCallback(async () => {+ const refresh = useCallback(async function refresh() {const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-refresh']);const loadingGeneration = ++refreshLoadingGenerationRef.current;+ const retryAfterInvalidation = () => {+ const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');+ const supersededByCursorRead =+ (readOwnershipRef.current.latestGeneration('inbox-feed-cursor') ?? 0) > read.generation;+ const supersededByRefresh =+ (readOwnershipRef.current.latestGeneration('inbox-feed-refresh') ?? 0) > read.generation;+ const supersededByReconcile =+ (readOwnershipRef.current.latestGeneration('inbox-feed-reconcile') ?? 0) > read.generation;+ if (+ (!invalidatedByMutation && !supersededByCursorRead) ||+ supersededByRefresh ||+ supersededByReconcile ||+ refreshRetryPendingRef.current+ ) {+ return false;+ }+ refreshRetryPendingRef.current = true;+ queueMicrotask(() => {+ refreshRetryPendingRef.current = false;+ void refresh();+ });+ return true;+ };setLoading(true);try {const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });const feedCurrent = readOwnershipRef.current.isCurrent(read, 'inbox-feed');if (!feedCurrent) {- if (!authoritativeFeedLoadedRef.current && !coldRefreshRetryPendingRef.current) {- coldRefreshRetryPendingRef.current = true;- queueMicrotask(() => {- coldRefreshRetryPendingRef.current = false;- if (!authoritativeFeedLoadedRef.current) void refresh();- });- }+ retryAfterInvalidation();} else {acceptFeedRows(read, result.sessions);setInboxSessions(() => mergeTargetedSnapshots(result.sessions));setNextCursor(result.next_cursor);- authoritativeFeedLoadedRef.current = true;}if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {applyUnreadMap(result.unread_by_session ?? {});}} catch (err) {- console.error('[inbox] refresh failed', err);+ if (!retryAfterInvalidation()) console.error('[inbox] refresh failed', err);} finally {if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);}@@ -198,15 +222,30 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>const markRead = useCallback(async (sessionId: string, untilMessageId?: string) => {- const read = readOwnershipRef.current.beginRead('inbox-unread');+ const operation = readOwnershipRef.current.beginRead(`inbox-mark-read:${sessionId}`);const result = await api.markSessionRead(sessionId, untilMessageId);- if (!readOwnershipRef.current.isCurrent(read, 'inbox-unread')) return;+ if (+ !readOwnershipRef.current.isMutationCurrent(operation, [+ `inbox-session:${sessionId}`,+ 'inbox-unread-all',+ ])+ ) {+ return;+ }+ // A successful write commits after every read that was already in flight,+ // even when one of those reads started later and returns last. The endpoint+ // mutates only this session, so merge only that count; concurrent mark-read+ // writes for other sessions remain independent.+ readOwnershipRef.current.acceptMutation([+ 'inbox-unread',+ `inbox-unread-session:${sessionId}`,+ ]);// The unread map is authoritative for badges; the card's unread styling// derives from it, so clearing here clears the dot without touching the// feed order (a read doesn't change last activity).- applyUnreadMap(result.unread_by_session ?? {});+ applySessionUnread(sessionId, result.unread_by_session?.[sessionId] ?? 0);},- [api, applyUnreadMap],+ [api, applySessionUnread],);// Resume reconcile: re-read the feed WITHOUT collapsing pagination. A@@ -218,6 +257,29 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// already has content; this is a silent catch-up.const reconcile = useCallback(async () => {const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-reconcile']);+ const retryAfterInvalidation = () => {+ const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');+ const supersededByCursorRead =+ (readOwnershipRef.current.latestGeneration('inbox-feed-cursor') ?? 0) > read.generation;+ const supersededByReconcileRead =+ (readOwnershipRef.current.latestGeneration('inbox-feed-reconcile') ?? 0) > read.generation;+ const supersededByRefresh =+ (readOwnershipRef.current.latestGeneration('inbox-feed-refresh') ?? 0) > read.generation;+ if (+ (!invalidatedByMutation && !supersededByCursorRead) ||+ supersededByRefresh ||+ supersededByReconcileRead ||+ reconcileRetryPendingRef.current+ ) {+ return false;+ }+ reconcileRetryPendingRef.current = true;+ queueMicrotask(() => {+ reconcileRetryPendingRef.current = false;+ void reconcile();+ });+ return true;+ };// Snapshot loaded ids up front: sizes the re-read window, and lets us tell// afterward whether the read overlapped what we already had (cursor note).const loadedIds = new Set(inboxSessionsRef.current.map((s) => s.session_id));@@ -230,26 +292,12 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>handleError: false,});const feedCurrent = readOwnershipRef.current.isCurrent(read, 'inbox-feed');- const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');const supersededByCursorRead =(readOwnershipRef.current.latestGeneration('inbox-feed-cursor') ?? 0) > read.generation;const supersededByReconcileRead =(readOwnershipRef.current.latestGeneration('inbox-feed-reconcile') ?? 0) > read.generation;- const supersededByRefresh =- (readOwnershipRef.current.latestGeneration('inbox-feed-refresh') ?? 0) > read.generation;if (!feedCurrent || supersededByCursorRead || supersededByReconcileRead) {- if (- (invalidatedByMutation || supersededByCursorRead) &&- !supersededByRefresh &&- !supersededByReconcileRead &&- !reconcileRetryPendingRef.current- ) {- reconcileRetryPendingRef.current = true;- queueMicrotask(() => {- reconcileRetryPendingRef.current = false;- void reconcile();- });- }+ retryAfterInvalidation();} else {acceptFeedRows(read, result.sessions);setInboxSessions((prev) => {@@ -260,7 +308,6 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>merged.sort(byActivityDesc);return mergeTargetedSnapshots(merged);});- authoritativeFeedLoadedRef.current = true;// Cursor: the loaded feed is always a contiguous run from the top, and// this reads the newest `limit` rows. If the read shares ANY row with what// we had (overlap), the two runs are contiguous — no gap below the read —@@ -277,7 +324,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>applyUnreadMap(result.unread_by_session ?? {});}} catch (err) {- console.error('[inbox] reconcile failed', err);+ if (!retryAfterInvalidation()) console.error('[inbox] reconcile failed', err);}}, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots]);diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsxindex 3a5aaede9..4048ddff1 100644--- a/ui/src/context/WorkbenchProjectsProvider.tsx+++ b/ui/src/context/WorkbenchProjectsProvider.tsx@@ -123,6 +123,8 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cconst inFlightRef = useRef<Set<string>>(new Set());const pendingReconcileRef = useRef<Map<string, number>>(new Map());const sessionProjectRef = useRef<Map<string, string>>(new Map());+ const cachedRowRefreshInFlightRef = useRef<Set<string>>(new Set());+ const pendingCachedRowRefreshRef = useRef<Set<string>>(new Set());// All reads owned by this provider share one ordering fence. A bootstrap,// paginated read, or targeted row read that started before a newer mutation// must not commit its snapshot after that mutation is accepted.@@ -407,28 +409,41 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c}, [api, applyBootstrapSessions, queueReconcile, reconcileSessions]);const refreshCachedSessionRow = useCallback(async function refreshCachedSessionRow(sessionId: string) {- const projectId = Object.entries(sessionsRef.current).find(([, state]) =>- state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),- )?.[0];- if (!projectId) return;- const resource = `project-session:${sessionId}`;- const read = readOwnershipRef.current.beginRead(resource);+ if (cachedRowRefreshInFlightRef.current.has(sessionId)) {+ pendingCachedRowRefreshRef.current.add(sessionId);+ return;+ }+ cachedRowRefreshInFlightRef.current.add(sessionId);try {- const updated = await api.getSession(sessionId, { cache: false });- if (readOwnershipRef.current.isCurrent(read, resource)) {- sessionProjectRef.current.set(updated.id, projectId);- setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));- } else if (readOwnershipRef.current.isLatestRead(read)) {- queueMicrotask(() => void refreshCachedSessionRow(sessionId));+ while (true) {+ pendingCachedRowRefreshRef.current.delete(sessionId);+ const projectId = Object.entries(sessionsRef.current).find(([, state]) =>+ state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),+ )?.[0];+ if (!projectId) return;+ const resource = `project-session:${sessionId}`;+ const read = readOwnershipRef.current.beginRead(resource);+ let stale = false;+ try {+ const updated = await api.getSession(sessionId, { cache: false });+ stale = !readOwnershipRef.current.isCurrent(read, resource);+ if (!stale) {+ sessionProjectRef.current.set(updated.id, projectId);+ setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));+ return;+ }+ } catch {+ stale = !readOwnershipRef.current.isCurrent(read, resource);+ if (!stale && !pendingCachedRowRefreshRef.current.has(sessionId)) return;+ /* current best-effort failures are recovered by reconnect reconcile */+ }+ if (!stale && !pendingCachedRowRefreshRef.current.has(sessionId)) return;}- } catch {- if (- !readOwnershipRef.current.isCurrent(read, resource) &&- readOwnershipRef.current.isLatestRead(read)- ) {+ } finally {+ cachedRowRefreshInFlightRef.current.delete(sessionId);+ if (pendingCachedRowRefreshRef.current.delete(sessionId)) {queueMicrotask(() => void refreshCachedSessionRow(sessionId));}- /* best-effort current failures are recovered by reconnect reconcile */}}, [api]);diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsxindex 92d742b73..260d4160c 100644--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx@@ -411,6 +411,59 @@ describe('Workbench session read ownership', () => {expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);});+ it('coalesces cached-row refreshes and retries after a newer lifecycle mutation', async () => {+ const staleRowRead = deferred({ ...session, native_session_id: 'native_stale' });+ const boundSession = { ...session, native_session_id: 'native_fresh' };+ const getSession = vi.fn()+ .mockReturnValueOnce(staleRowRead.promise)+ .mockResolvedValueOnce(boundSession);+ let handlers: WorkbenchEventHandlers | null = null;+ apiRef.current = {+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({+ projects: [project],+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },+ }),+ getSession,+ 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 settle();+ act(() => {+ handlers?.onTurnEnd?.({ session_id: session.id });+ });+ await settle();++ expect(getSession).toHaveBeenCalledTimes(1);+ await act(async () => {+ staleRowRead.resolve({ ...session, native_session_id: 'native_stale' });+ await staleRowRead.promise;+ });+ await settle();++ expect(getSession).toHaveBeenCalledTimes(2);+ expect(tree?.sessionsOf(project.id).sessions).toEqual([boundSession]);+ });+it('retries an invalidated project pagination read', async () => {const pageSession = { ...sessionB, scope_id: project.scope_id, project_id: project.id };const stalePage = deferred({ sessions: [pageSession], next_before_id: null });@@ -525,7 +578,8 @@ describe('Workbench session read ownership', () => {apiRef.current = {listInbox: vi.fn().mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } })- .mockReturnValueOnce(staleRefresh.promise),+ .mockReturnValueOnce(staleRefresh.promise)+ .mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_a', unread_by_session: {} }),connectWorkbenchEvents: vi.fn((next) => {handlers = next;return vi.fn();@@ -565,6 +619,7 @@ describe('Workbench session read ownership', () => {});await settle();+ expect(apiRef.current?.listInbox).toHaveBeenCalledTimes(3);expect(inbox?.inboxSessions).toEqual([]);expect(inbox?.unreadBySession).toEqual({});expect(inbox?.nextCursor).toBe('cursor_a');@@ -671,6 +726,134 @@ describe('Workbench session read ownership', () => {expect(inbox?.unreadBySession).toEqual({});});+ it('keeps a successful mark-read result when an older unread snapshot finishes last', async () => {+ const markReadResult = deferred({ unread_by_session: { [sessionB.id]: 5 } });+ const staleRefresh = deferred({+ sessions: [inboxRow],+ next_cursor: 'stale_cursor',+ unread_by_session: { [session.id]: 3, [sessionB.id]: 5 },+ });+ const listInbox = vi.fn()+ .mockResolvedValueOnce({+ sessions: [inboxRow],+ next_cursor: 'cursor_a',+ unread_by_session: { [session.id]: 3, [sessionB.id]: 5 },+ })+ .mockReturnValueOnce(staleRefresh.promise);+ apiRef.current = {+ listInbox,+ markSessionRead: vi.fn().mockReturnValue(markReadResult.promise),+ 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?.markRead(session.id);+ void inbox?.refresh();+ });+ await settle();+ await act(async () => {+ markReadResult.resolve({ unread_by_session: { [sessionB.id]: 5 } });+ await markReadResult.promise;+ });+ await act(async () => {+ staleRefresh.resolve({+ sessions: [inboxRow],+ next_cursor: 'stale_cursor',+ unread_by_session: { [session.id]: 3, [sessionB.id]: 5 },+ });+ await staleRefresh.promise;+ });+ await settle();++ 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',+ unread_by_session: { [session.id]: 3 },+ });+ const loadMoreRead = deferred({+ sessions: [],+ 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 },+ });+ 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();+ await act(async () => {+ loadMoreRead.resolve({+ sessions: [],+ next_cursor: 'cursor_after_load_more',+ unread_by_session: { [session.id]: 3 },+ });+ await loadMoreRead.promise;+ });+ await act(async () => {+ staleRefresh.resolve({+ sessions: [inboxRow],+ next_cursor: 'stale_cursor',+ unread_by_session: { [session.id]: 3 },+ });+ await staleRefresh.promise;+ });+ await settle();++ expect(listInbox).toHaveBeenCalledTimes(4);+ expect(inbox?.inboxSessions).toEqual([refreshedRow]);+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');+ });+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()@@ -785,7 +968,8 @@ describe('Workbench session read ownership', () => {const listInbox = vi.fn().mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } }).mockReturnValueOnce(refreshRead.promise)- .mockReturnValueOnce(loadMoreRead.promise);+ .mockReturnValueOnce(loadMoreRead.promise)+ .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_refresh', unread_by_session: { [session.id]: 3 } });apiRef.current = {listInbox,connectWorkbenchEvents: vi.fn(() => vi.fn()),