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): retain pending reconciliation intents

cyhf59e3ca78092
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 98cbc3080..fface4ab7 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -87,14 +87,44 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// neither operation owns the full top-of-feed snapshot requested by refresh.
const refreshRetryPendingRef = useRef(false);
const reconcileRetryPendingRef = useRef(false);
+ const cursorReadsInFlightRef = useRef(0);
+ const refreshRetryRunnerRef = useRef<() => void>(() => {});
+ const reconcileRetryRunnerRef = useRef<() => void>(() => {});
+ const reconcileSessionRef = useRef<(sessionId: string) => void>(() => {});
const refreshLoadingGenerationRef = useRef(0);
const loadMoreLoadingGenerationRef = useRef(0);
// Targeted foreground restores own one session independently from the
// windowed feed. Keep their latest committed values so a later whole-feed
// replacement cannot erase a restored card merely because the row sorts
- // outside the page.
+ // outside the page; a later broad omission revalidates them by exact id.
const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());
+ const flushBroadReadRetry = useCallback(() => {
+ if (cursorReadsInFlightRef.current > 0) return;
+ if (refreshRetryPendingRef.current) {
+ refreshRetryPendingRef.current = false;
+ // A replacement refresh owns the same top-of-feed recovery as a pending
+ // reconcile, so one authoritative read satisfies both intents.
+ reconcileRetryPendingRef.current = false;
+ refreshRetryRunnerRef.current();
+ return;
+ }
+ if (reconcileRetryPendingRef.current) {
+ reconcileRetryPendingRef.current = false;
+ reconcileRetryRunnerRef.current();
+ }
+ }, []);
+
+ const queueRefreshRetry = useCallback(() => {
+ refreshRetryPendingRef.current = true;
+ queueMicrotask(flushBroadReadRetry);
+ }, [flushBroadReadRetry]);
+
+ const queueReconcileRetry = useCallback(() => {
+ reconcileRetryPendingRef.current = true;
+ queueMicrotask(flushBroadReadRetry);
+ }, [flushBroadReadRetry]);
+
const acceptSessionMutation = useCallback((sessionId: string) => {
readOwnershipRef.current.acceptMutation([
'inbox-feed',
@@ -138,6 +168,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}, []);
const acceptFeedRows = useCallback((read: WorkbenchSessionReadStamp, rows: InboxSession[]) => {
+ 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);
@@ -145,9 +176,14 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
targetedSnapshotsRef.current.delete(row.session_id);
}
}
+ return Array.from(targetedSnapshotsRef.current.entries())
+ .filter(([sessionId, snapshot]) => snapshot.row && !returnedIds.has(sessionId))
+ .map(([sessionId]) => sessionId);
}, []);
const refresh = useCallback(async function refresh() {
+ refreshRetryPendingRef.current = false;
+ reconcileRetryPendingRef.current = false;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-refresh']);
const loadingGeneration = ++refreshLoadingGenerationRef.current;
const retryAfterInvalidation = () => {
@@ -166,11 +202,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
) {
return false;
}
- refreshRetryPendingRef.current = true;
- queueMicrotask(() => {
- refreshRetryPendingRef.current = false;
- void refresh();
- });
+ queueRefreshRetry();
return true;
};
setLoading(true);
@@ -180,9 +212,10 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (!feedCurrent) {
retryAfterInvalidation();
} else {
- acceptFeedRows(read, result.sessions);
+ const snapshotsToRevalidate = acceptFeedRows(read, result.sessions);
setInboxSessions(() => mergeTargetedSnapshots(result.sessions));
setNextCursor(result.next_cursor);
+ for (const sessionId of snapshotsToRevalidate) reconcileSessionRef.current(sessionId);
}
if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {
applyUnreadMap(result.unread_by_session ?? {});
@@ -192,12 +225,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} finally {
if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);
}
- }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots]);
+ }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots, queueRefreshRetry]);
const loadMore = useCallback(async function loadMore() {
const cursor = cursorRef.current;
if (!cursor) return;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-cursor']);
+ cursorReadsInFlightRef.current += 1;
const loadingGeneration = ++loadMoreLoadingGenerationRef.current;
let retryAfterInvalidation = false;
setLoadingMore(true);
@@ -215,10 +249,12 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
readOwnershipRef.current.isLatestRead(read);
if (!retryAfterInvalidation) console.error('[inbox] load more failed', err);
} finally {
+ cursorReadsInFlightRef.current -= 1;
if (loadMoreLoadingGenerationRef.current === loadingGeneration) setLoadingMore(false);
if (retryAfterInvalidation) queueMicrotask(() => void loadMore());
+ else flushBroadReadRetry();
}
- }, [api]);
+ }, [api, flushBroadReadRetry]);
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
@@ -256,6 +292,7 @@ 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 () => {
+ reconcileRetryPendingRef.current = false;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-reconcile']);
const retryAfterInvalidation = () => {
const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');
@@ -273,11 +310,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
) {
return false;
}
- reconcileRetryPendingRef.current = true;
- queueMicrotask(() => {
- reconcileRetryPendingRef.current = false;
- void reconcile();
- });
+ queueReconcileRetry();
return true;
};
// Snapshot loaded ids up front: sizes the re-read window, and lets us tell
@@ -299,7 +332,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (!feedCurrent || supersededByCursorRead || supersededByReconcileRead) {
retryAfterInvalidation();
} else {
- acceptFeedRows(read, result.sessions);
+ const snapshotsToRevalidate = acceptFeedRows(read, result.sessions);
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);
@@ -308,6 +341,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
merged.sort(byActivityDesc);
return mergeTargetedSnapshots(merged);
});
+ for (const sessionId of snapshotsToRevalidate) reconcileSessionRef.current(sessionId);
// 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 —
@@ -326,7 +360,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} catch (err) {
if (!retryAfterInvalidation()) console.error('[inbox] reconcile failed', err);
}
- }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots]);
+ }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots, queueReconcileRetry]);
// Targeted reconcile for one session (contract A6 foreground restore): fetch
// that exact session by id and upsert its card, so a restored session
@@ -375,6 +409,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
},
[api],
);
+ refreshRetryRunnerRef.current = () => void refresh();
+ reconcileRetryRunnerRef.current = () => void reconcile();
+ reconcileSessionRef.current = (sessionId) => void reconcileSession(sessionId);
useEffect(() => {
// First mount loads page one; every later rerun reconciles the loaded window
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 4048ddff1..dbb36916d 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -129,7 +129,6 @@ 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 projectTreeRetryPendingRef = useRef(false);
@@ -203,8 +202,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);
const retryAfterMutation = () => {
if (
- authoritativeProjectsLoadedRef.current ||
- readOwnershipRef.current.isCurrent(read, 'projects-bootstrap') ||
+ readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap']) ||
!readOwnershipRef.current.isLatestRead(read) ||
bootstrapRetryPendingRef.current
) {
@@ -213,12 +211,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
bootstrapRetryPendingRef.current = true;
queueMicrotask(() => {
bootstrapRetryPendingRef.current = false;
- if (!authoritativeProjectsLoadedRef.current) void fetchProjects({ cache: false });
+ void fetchProjects({ cache: false });
});
};
try {
const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
- if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjects(result.projects);
+ const projectsCurrent = readOwnershipRef.current.isCurrent(read, 'projects');
+ if (projectsCurrent) setProjects(result.projects);
if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {
retryAfterMutation();
return;
@@ -229,8 +228,11 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
),
);
applyBootstrapSessions(read, pages);
- if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(null);
- authoritativeProjectsLoadedRef.current = true;
+ if (!projectsCurrent) {
+ retryAfterMutation();
+ return;
+ }
+ setProjectsError(null);
} 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).
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 260d4160c..b71d8434d 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -208,6 +208,54 @@ describe('Workbench session read ownership', () => {
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],
+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },
+ });
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockReturnValueOnce(staleBootstrap.promise)
+ .mockResolvedValueOnce({
+ projects: [project, projectB],
+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },
+ });
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap,
+ listSessions: vi.fn().mockResolvedValue({ sessions: [session], next_before_id: null }),
+ connectWorkbenchEvents: vi.fn(() => 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(() => {
+ tree?.upsertProjectToTop(project);
+ });
+ await settle();
+ await act(async () => {
+ staleBootstrap.resolve({
+ projects: [project, projectB],
+ sessions: { [project.id]: { sessions: [session], next_before_id: null } },
+ });
+ await staleBootstrap.promise;
+ });
+ await settle();
+
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);
+ expect(tree?.projects).toEqual([project, projectB]);
+ });
+
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()
@@ -962,6 +1010,103 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBe('cursor_after_load_more');
});
+ it('defers a resume retry until a later load-more 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 staleReconcile = deferred({
+ sessions: [inboxRow],
+ next_cursor: 'stale_cursor',
+ unread_by_session: { [session.id]: 3 },
+ });
+ const loadMoreRead = deferred({
+ sessions: [pageRow],
+ 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 },
+ });
+ 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);
+ 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(() => {
+ window.dispatchEvent(new Event('focus'));
+ });
+ await settle();
+ act(() => {
+ void inbox?.loadMore();
+ });
+ await settle();
+ 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);
+ await act(async () => {
+ loadMoreRead.resolve({
+ sessions: [pageRow],
+ next_cursor: 'cursor_after_load_more',
+ unread_by_session: { [session.id]: 3 },
+ });
+ await loadMoreRead.promise;
+ });
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(4);
+ await act(async () => {
+ retryReconcile.resolve({
+ sessions: [inboxRow],
+ next_cursor: 'cursor_after_reconcile',
+ unread_by_session: { [session.id]: 3 },
+ });
+ await retryReconcile.promise;
+ });
+ await settle();
+
+ expect(inbox?.inboxSessions.map((row) => row.session_id).sort()).toEqual([
+ session.id,
+ sessionB.id,
+ ]);
+ expect(inbox?.nextCursor).toBe('cursor_after_load_more');
+ });
+
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 } });
@@ -1062,6 +1207,60 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBe('cursor_before_restore');
});
+ it('revalidates a targeted snapshot omitted after a missed removal event', async () => {
+ 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: [], next_cursor: 'cursor_after_refresh', unread_by_session: {} })
+ .mockResolvedValueOnce({ 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(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'foreground',
+ });
+ });
+ await settle();
+ expect(inbox?.inboxSessions).toEqual([inboxRow]);
+ act(() => {
+ void inbox?.refresh();
+ });
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(4);
+ expect(inbox?.inboxSessions).toEqual([]);
+ expect(inbox?.unreadBySession).toEqual({});
+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');
+ });
+
it('keeps a targeted restore without replacing a newer broad unread map', 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: { [sessionB.id]: 5 } });
@@ -1243,7 +1442,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: {} });
let handlers: WorkbenchEventHandlers | null = null;
apiRef.current = {
listInbox,
@@ -1288,6 +1488,7 @@ 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({});
expect(inbox?.nextCursor).toBe('cursor_after_refresh');