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): retry superseded session reads

cyhb4709b153d8c
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 7ed03a032..6fcbe7a99 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -35,6 +35,11 @@ const appendPage = (prev: InboxSession[], page: InboxSession[]): InboxSession[]
return merged;
};
+type TargetedInboxSnapshot = {
+ row: InboxSession | null;
+ unreadCount: number;
+};
+
/** Provider that owns the Inbox state shared across WorkbenchSidebar + InboxPage.
*
* Connects to ``/api/events`` and updates the per-session feed in place:
@@ -84,6 +89,11 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const reconcileRetryPendingRef = useRef(false);
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 or unread count merely because
+ // the row sorts outside the page.
+ const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());
const acceptSessionMutation = useCallback(() => {
readOwnershipRef.current.acceptMutation();
@@ -98,8 +108,30 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
setUnreadLoaded(true);
}, []);
+ const applyFeedUnreadMap = useCallback(
+ (map: Record<string, number>) => {
+ const next = { ...map };
+ for (const [sessionId, snapshot] of targetedSnapshotsRef.current) {
+ if (snapshot.unreadCount > 0) next[sessionId] = snapshot.unreadCount;
+ else delete next[sessionId];
+ }
+ applyUnreadMap(next);
+ },
+ [applyUnreadMap],
+ );
+
+ const mergeTargetedSnapshots = useCallback((rows: InboxSession[]): InboxSession[] => {
+ let next = rows;
+ for (const [sessionId, snapshot] of targetedSnapshotsRef.current) {
+ next = snapshot.row
+ ? upsertSession(next, snapshot.row)
+ : next.filter((row) => row.session_id !== sessionId);
+ }
+ return next;
+ }, []);
+
const refresh = useCallback(async () => {
- const read = readOwnershipRef.current.beginRead('inbox-feed');
+ const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-refresh']);
const loadingGeneration = ++refreshLoadingGenerationRef.current;
setLoading(true);
try {
@@ -114,21 +146,21 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}
return;
}
- setInboxSessions(result.sessions);
+ setInboxSessions(() => mergeTargetedSnapshots(result.sessions));
setNextCursor(result.next_cursor);
- applyUnreadMap(result.unread_by_session ?? {});
+ applyFeedUnreadMap(result.unread_by_session ?? {});
authoritativeFeedLoadedRef.current = true;
} catch (err) {
console.error('[inbox] refresh failed', err);
} finally {
if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);
}
- }, [api, applyUnreadMap]);
+ }, [api, applyFeedUnreadMap, mergeTargetedSnapshots]);
const loadMore = useCallback(async () => {
const cursor = cursorRef.current;
if (!cursor) return;
- const read = readOwnershipRef.current.beginRead('inbox-feed');
+ const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-cursor']);
const loadingGeneration = ++loadMoreLoadingGenerationRef.current;
setLoadingMore(true);
try {
@@ -146,6 +178,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
const result = await api.markSessionRead(sessionId, untilMessageId);
+ targetedSnapshotsRef.current.delete(sessionId);
acceptSessionMutation();
// The unread map is authoritative for badges; the card's unread styling
// derives from it, so clearing here clears the dot without touching the
@@ -163,7 +196,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 () => {
- const read = readOwnershipRef.current.beginRead('inbox-feed');
+ const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-reconcile']);
// 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));
@@ -175,8 +208,21 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
cache: false,
handleError: false,
});
- if (!readOwnershipRef.current.isCurrent(read)) {
- if (readOwnershipRef.current.epoch() !== read.epoch && !reconcileRetryPendingRef.current) {
+ const stale = !readOwnershipRef.current.isCurrent(read) || !readOwnershipRef.current.isLatestRead(read);
+ const invalidatedByMutation = readOwnershipRef.current.epoch() !== read.epoch;
+ 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 (stale || supersededByCursorRead || supersededByReconcileRead) {
+ if (
+ (invalidatedByMutation || supersededByCursorRead) &&
+ !supersededByRefresh &&
+ !supersededByReconcileRead &&
+ !reconcileRetryPendingRef.current
+ ) {
reconcileRetryPendingRef.current = true;
queueMicrotask(() => {
reconcileRetryPendingRef.current = false;
@@ -191,10 +237,10 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const have = new Set(prev.map((s) => s.session_id));
for (const s of result.sessions) if (!have.has(s.session_id)) merged.push(s);
merged.sort(byActivityDesc);
- return merged;
+ return mergeTargetedSnapshots(merged);
});
// Whole-account unread map (not paginated) — always authoritative.
- applyUnreadMap(result.unread_by_session ?? {});
+ applyFeedUnreadMap(result.unread_by_session ?? {});
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
@@ -210,7 +256,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} catch (err) {
console.error('[inbox] reconcile failed', err);
}
- }, [api, applyUnreadMap]);
+ }, [api, applyFeedUnreadMap, mergeTargetedSnapshots]);
// Targeted reconcile for one session (contract A6 foreground restore): fetch
// that exact session by id and upsert its card, so a restored session
@@ -230,7 +276,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
});
const row = result.sessions.find((s) => s.session_id === sessionId);
if (!readOwnershipRef.current.isCurrent(read)) return;
- if (row) setInboxSessions((prev) => upsertSession(prev, row));
+ targetedSnapshotsRef.current.set(sessionId, {
+ row: row ?? null,
+ unreadCount: result.unread_by_session?.[sessionId] ?? 0,
+ });
+ setInboxSessions((prev) =>
+ row ? upsertSession(prev, row) : prev.filter((candidate) => candidate.session_id !== sessionId),
+ );
applyUnreadMap(result.unread_by_session ?? {});
} catch (err) {
console.error('[inbox] reconcileSession failed', err);
@@ -254,6 +306,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}
const disconnect = api.connectWorkbenchEvents({
onInboxSessionUpdated: (row) => {
+ targetedSnapshotsRef.current.delete(row.session_id);
acceptSessionMutation();
setInboxSessions((prev) => upsertSession(prev, row));
setUnreadBySession((prev) => {
@@ -265,6 +318,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
});
},
onInboxUnreadChanged: (data) => {
+ targetedSnapshotsRef.current.clear();
acceptSessionMutation();
if (data?.unread_by_session) {
applyUnreadMap(data.unread_by_session);
@@ -278,11 +332,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// See lib/inboxActivity.
const action = sessionActivityInboxAction(data);
if (action === 'reconcile') {
+ targetedSnapshotsRef.current.delete(data.session_id);
acceptSessionMutation();
void reconcileSession(data.session_id);
return;
}
if (action === 'ignore') return;
+ targetedSnapshotsRef.current.delete(data.session_id);
acceptSessionMutation();
// action === 'drop': remove the card + its unread live, instead of
// waiting for the next reconnect/refresh to filter it.
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 5988dbef7..64132d02c 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -11,7 +11,10 @@ import {
import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';
import { orderProjectSessions } from '../lib/sessionPinning';
import { errorMessage } from '@/lib/errorMessage';
-import { createWorkbenchSessionReadOwnership } from '../lib/workbenchSessionReadOwnership';
+import {
+ createWorkbenchSessionReadOwnership,
+ type WorkbenchSessionReadStamp,
+} from '../lib/workbenchSessionReadOwnership';
// How many sessions to load per page under a project. The server clamps the
// /api/sessions limit (to 200) and returns a cursor (next_before_id); both the
@@ -125,6 +128,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const readOwnershipRef = useRef(createWorkbenchSessionReadOwnership());
const authoritativeProjectsLoadedRef = useRef(false);
const bootstrapRetryPendingRef = useRef(false);
+ const projectTreeRetryPendingRef = useRef(false);
const acceptSessionMutation = useCallback(() => {
readOwnershipRef.current.acceptMutation();
@@ -283,7 +287,21 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
[queueReconcile],
);
- const reconcileProjectTree = useCallback(async () => {
+ const reconcileProjectTree = useCallback(async function reconcileProjectTree() {
+ 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();
+ });
+ };
const bootstrapGroups = new Map<number, string[]>();
const largeProjectIds: string[] = [];
for (const [projectId, state] of Object.entries(sessionsRef.current)) {
@@ -318,7 +336,10 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
limit,
cache: false,
});
- if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;
+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {
+ retryAfterInvalidation(read);
+ return;
+ }
nextProjects = result.projects;
for (const [projectId, page] of Object.entries(result.sessions ?? {})) {
const currentCount = sessionsRef.current[projectId]?.sessions?.length ?? 0;
@@ -342,13 +363,19 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
);
applyBootstrapSessions(currentPages);
}
- if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;
+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {
+ retryAfterInvalidation(read);
+ return;
+ }
if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(null);
for (const projectId of largeProjectIds) {
void reconcileSessions(projectId);
}
} catch (err) {
- if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;
+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {
+ retryAfterInvalidation(read);
+ return;
+ }
if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(errorMessage(err) ?? String(err));
const projectIds = [...bootstrapGroups.values()].flat();
for (const projectId of [...projectIds, ...largeProjectIds]) {
@@ -376,7 +403,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// Load the first page (append=false) or the next page (append=true) of a
// project's sessions, with dedupe + per-project serialisation.
const fetchSessions = useCallback(
- async (projectId: string, opts?: { append?: boolean }) => {
+ async function fetchSessions(projectId: string, opts?: { append?: boolean }) {
const append = opts?.append ?? false;
if (append && !sessionsRef.current[projectId]?.cursor) return; // nothing more to load
if (inFlightRef.current.has(projectId)) return; // serialise per project
@@ -390,11 +417,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
});
const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;
const read = readOwnershipRef.current.beginRead(`project:${projectId}`);
+ let retryFirstPage = false;
try {
const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId });
+ const currentRead = readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]);
+ retryFirstPage = !currentRead && !append && sessionsRef.current[projectId]?.sessions === null;
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
- if (!readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {
+ if (!currentRead) {
return {
...prev,
[projectId]: append ? { ...cur, loadingMore: false } : { ...cur, loading: false },
@@ -412,10 +442,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
};
});
} catch {
+ const currentRead = readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]);
+ retryFirstPage = !currentRead && !append && sessionsRef.current[projectId]?.sessions === null;
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
if (!readOwnershipRef.current.isLatestRead(read)) return prev;
- if (!readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {
+ if (!currentRead) {
return append
? { ...prev, [projectId]: { ...cur, loadingMore: false } }
: { ...prev, [projectId]: { ...cur, loading: false } };
@@ -429,6 +461,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
});
} finally {
inFlightRef.current.delete(projectId);
+ if (retryFirstPage) {
+ queueMicrotask(() => {
+ const current = sessionsRef.current[projectId];
+ if (current?.sessions === null && !inFlightRef.current.has(projectId)) {
+ void fetchSessions(projectId);
+ }
+ });
+ }
const pendingMinCount = takePendingReconcile(projectId);
if (pendingMinCount !== null) {
void reconcileSessions(projectId, { minCount: pendingMinCount });
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 4a5aee738..4b61e6e83 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -207,6 +207,52 @@ describe('Workbench session read ownership', () => {
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()
+ .mockReturnValueOnce(staleFirstPage.promise)
+ .mockResolvedValueOnce({ sessions: [session], next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({ projects: [project], sessions: {} }),
+ listSessions,
+ 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(() => {
+ tree?.toggleExpanded(project.id);
+ });
+ await settle();
+ act(() => {
+ handlers?.onSessionStatus?.({ session_id: session.id, agent_status: 'idle' });
+ });
+ await act(async () => {
+ staleFirstPage.resolve({ sessions: [session], next_before_id: null });
+ await staleFirstPage.promise;
+ });
+ await settle();
+
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ 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 });
@@ -306,6 +352,58 @@ describe('Workbench session read ownership', () => {
expect(tree?.sessionsOf(project.id).sessions).toEqual([{ ...trackedSession, agent_status: 'idle' }]);
});
+ it('retries a reconnect project tree read invalidated by a live event', async () => {
+ const staleTree = deferred({ projects: [project], sessions: { [project.id]: { sessions: [session], next_before_id: null } } });
+ const refreshedSession = { ...session, title: 'Fresh after reconnect' };
+ const getWorkbenchProjectsBootstrap = vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: { [project.id]: { sessions: [session], next_before_id: null } } })
+ .mockReturnValueOnce(staleTree.promise)
+ .mockResolvedValueOnce({ projects: [project], sessions: { [project.id]: { sessions: [refreshedSession], 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();
+ act(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ title: 'Fresh after reconnect',
+ });
+ });
+ await act(async () => {
+ staleTree.resolve({ projects: [project], sessions: { [project.id]: { sessions: [session], next_before_id: null } } });
+ await staleTree.promise;
+ });
+ await settle();
+
+ expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(3);
+ expect(tree?.sessionsOf(project.id).sessions).toEqual([refreshedSession]);
+ });
+
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;
@@ -458,6 +556,62 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBeNull();
});
+ it('retries a resume reconcile superseded by load-more', async () => {
+ const staleReconcile = 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 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);
+ let inbox: ReturnType<typeof useWorkbenchInbox> | null = null;
+ const Probe = () => {
+ const value = useWorkbenchInbox();
+ useEffect(() => {
+ inbox = value;
+ }, [value]);
+ return null;
+ };
+
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ render(
+ <WorkbenchInboxProvider>
+ <Probe />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ act(() => {
+ window.dispatchEvent(new Event('focus'));
+ });
+ await settle();
+ act(() => {
+ 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 () => {
+ staleReconcile.resolve({ sessions: [inboxRow], next_cursor: 'stale_cursor', unread_by_session: { [session.id]: 3 } });
+ await staleReconcile.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).toEqual([inboxRow]);
+ 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 } });
@@ -610,4 +764,60 @@ describe('Workbench session read ownership', () => {
expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);
expect(inbox?.nextCursor).toBe('cursor_after_refresh');
});
+
+ it('keeps a targeted restore when the broad refresh completes last', 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 () => {
+ targetedRead.resolve({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });
+ await targetedRead.promise;
+ });
+ await settle();
+ await act(async () => {
+ broadRead.resolve({ sessions: [], next_cursor: 'cursor_after_refresh', unread_by_session: {} });
+ await broadRead.promise;
+ });
+ await settle();
+
+ expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);
+ expect(inbox?.unreadBySession).toEqual({ [session.id]: 3 });
+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');
+ });
});
diff --git a/ui/src/lib/workbenchSessionReadOwnership.test.ts b/ui/src/lib/workbenchSessionReadOwnership.test.ts
index 4380bbb2f..7caf5bc6d 100644
--- a/ui/src/lib/workbenchSessionReadOwnership.test.ts
+++ b/ui/src/lib/workbenchSessionReadOwnership.test.ts
@@ -44,4 +44,13 @@ describe('Workbench session read ownership', () => {
expect(ownership.isCurrent(bootstrap, ['projects-bootstrap', 'project:a'])).toBe(false);
expect(ownership.isCurrent(project, ['projects-bootstrap', 'project:a'])).toBe(true);
});
+
+ it('exposes the latest generation for operation-specific retry decisions', () => {
+ const ownership = createWorkbenchSessionReadOwnership();
+ const reconcile = ownership.beginRead(['inbox-feed', 'inbox-feed-reconcile']);
+ const cursor = ownership.beginRead(['inbox-feed', 'inbox-feed-cursor']);
+
+ expect(ownership.latestGeneration('inbox-feed-cursor')).toBe(cursor.generation);
+ expect(ownership.latestGeneration('inbox-feed-reconcile')).toBe(reconcile.generation);
+ });
});
diff --git a/ui/src/lib/workbenchSessionReadOwnership.ts b/ui/src/lib/workbenchSessionReadOwnership.ts
index f970cadee..7ae158432 100644
--- a/ui/src/lib/workbenchSessionReadOwnership.ts
+++ b/ui/src/lib/workbenchSessionReadOwnership.ts
@@ -20,6 +20,7 @@ export type WorkbenchSessionReadOwnership = {
resources?: string | readonly string[],
) => boolean;
isLatestRead: (stamp: WorkbenchSessionReadStamp) => boolean;
+ latestGeneration: (resource: string) => number | undefined;
epoch: () => number;
};
@@ -52,6 +53,7 @@ export function createWorkbenchSessionReadOwnership(): WorkbenchSessionReadOwner
},
isLatestRead: (stamp) =>
stamp.resources.every((resource) => latestByResource.get(resource) === stamp.generation),
+ latestGeneration: (resource) => latestByResource.get(resource),
epoch: () => mutationEpoch,
};
}