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): order session reads against realtime mutations

cyhfc6e2d4ce8ab
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 0745ae650..3d4b3ddae 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -6,6 +6,7 @@ import type { InboxSession } from './ApiContext';
import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext';
import { sessionActivityInboxAction } from '../lib/inboxActivity';
import { syncFaviconBadge } from '../lib/faviconBadge';
+import { createWorkbenchSessionReadOwnership } from '../lib/workbenchSessionReadOwnership';
const PAGE_SIZE = 30;
@@ -72,6 +73,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// — reconciles the loaded window instead, so a non-resume
// rerun never collapses a multi-page feed back to page one.
const initialFetched = useRef(false);
+ // 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());
+
+ const acceptSessionMutation = useCallback(() => {
+ readOwnershipRef.current.acceptMutation();
+ }, []);
// One home for "an authoritative unread map arrived": set the map and flip
// ``unreadLoaded`` together so the two can never drift apart. Every whole-account
@@ -83,43 +91,48 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}, []);
const refresh = useCallback(async () => {
+ const read = readOwnershipRef.current.beginRead();
setLoading(true);
try {
const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });
+ if (!readOwnershipRef.current.isCurrent(read)) return;
setInboxSessions(result.sessions);
setNextCursor(result.next_cursor);
applyUnreadMap(result.unread_by_session ?? {});
} catch (err) {
console.error('[inbox] refresh failed', err);
} finally {
- setLoading(false);
+ if (readOwnershipRef.current.isLatestRead(read)) setLoading(false);
}
}, [api, applyUnreadMap]);
const loadMore = useCallback(async () => {
const cursor = cursorRef.current;
if (!cursor) return;
+ const read = readOwnershipRef.current.beginRead();
setLoadingMore(true);
try {
const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE, before: cursor });
+ if (!readOwnershipRef.current.isCurrent(read)) return;
setInboxSessions((prev) => appendPage(prev, result.sessions));
setNextCursor(result.next_cursor);
} catch (err) {
console.error('[inbox] load more failed', err);
} finally {
- setLoadingMore(false);
+ if (readOwnershipRef.current.isLatestRead(read)) setLoadingMore(false);
}
}, [api]);
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
const result = await api.markSessionRead(sessionId, untilMessageId);
+ 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
// feed order (a read doesn't change last activity).
applyUnreadMap(result.unread_by_session ?? {});
},
- [api, applyUnreadMap],
+ [acceptSessionMutation, api, applyUnreadMap],
);
// Resume reconcile: re-read the feed WITHOUT collapsing pagination. A
@@ -130,6 +143,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();
// 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));
@@ -141,6 +155,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
cache: false,
handleError: false,
});
+ if (!readOwnershipRef.current.isCurrent(read)) 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);
@@ -174,6 +189,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// whole-account unread map, so refresh that too. Never touches the cursor.
const reconcileSession = useCallback(
async (sessionId: string) => {
+ const read = readOwnershipRef.current.beginRead();
try {
const result = await api.listInbox({
platform: 'avibe',
@@ -183,6 +199,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
handleError: false,
});
const row = result.sessions.find((s) => s.session_id === sessionId);
+ if (!readOwnershipRef.current.isCurrent(read)) return;
if (row) setInboxSessions((prev) => upsertSession(prev, row));
applyUnreadMap(result.unread_by_session ?? {});
} catch (err) {
@@ -207,6 +224,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
}
const disconnect = api.connectWorkbenchEvents({
onInboxSessionUpdated: (row) => {
+ acceptSessionMutation();
setInboxSessions((prev) => upsertSession(prev, row));
setUnreadBySession((prev) => {
if ((prev[row.session_id] ?? 0) === row.unread_count) return prev;
@@ -217,11 +235,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
});
},
onInboxUnreadChanged: (data) => {
+ acceptSessionMutation();
if (data?.unread_by_session) {
applyUnreadMap(data.unread_by_session);
}
},
onSessionActivity: (data) => {
+ acceptSessionMutation();
// Contract A6: react to visibility/scope changes carried on the event.
// background ⇒ drop the card (like an archive); foreground ⇒ fetch that
// exact session and upsert its card so it reappears even if it sorts past
@@ -250,7 +270,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
},
});
return disconnect;
- }, [api, refresh, reconcile, reconcileSession, applyUnreadMap]);
+ }, [acceptSessionMutation, api, refresh, reconcile, reconcileSession, applyUnreadMap]);
// Recover after the OS suspended us. A backgrounded mobile PWA has its page
// frozen and its SSE socket dropped, and the broker never replays the gap;
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 44c9942a0..af2649552 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -11,6 +11,7 @@ import {
import { createdReconcileMinCount } from '../lib/sessionVisibilityEvents';
import { orderProjectSessions } from '../lib/sessionPinning';
import { errorMessage } from '@/lib/errorMessage';
+import { createWorkbenchSessionReadOwnership } 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
@@ -118,6 +119,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// reconcile per project so they can't race or truncate an append.
const inFlightRef = useRef<Set<string>>(new Set());
const pendingReconcileRef = useRef<Map<string, number>>(new Map());
+ // 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.
+ const readOwnershipRef = useRef(createWorkbenchSessionReadOwnership());
+
+ const acceptSessionMutation = useCallback(() => {
+ readOwnershipRef.current.acceptMutation();
+ }, []);
const queueReconcile = useCallback((projectId: string, minCount = 0) => {
const pending = pendingReconcileRef.current.get(projectId) ?? 0;
@@ -151,15 +160,19 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}, []);
const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
+ const read = readOwnershipRef.current.beginRead();
try {
const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
+ if (!readOwnershipRef.current.isCurrent(read)) return;
setProjects(result.projects);
applyBootstrapSessions(result.sessions ?? {});
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).
- setProjectsError(errorMessage(err) ?? String(err));
+ if (readOwnershipRef.current.isCurrent(read)) {
+ setProjectsError(errorMessage(err) ?? String(err));
+ }
}
}, [api, applyBootstrapSessions]);
@@ -183,6 +196,8 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const targetCount = Math.max(sessionsRef.current[projectId]?.sessions?.length ?? 0, minCount);
if (targetCount === 0) return; // nothing loaded to reconcile
inFlightRef.current.add(projectId);
+ const read = readOwnershipRef.current.beginRead();
+ let stale = false;
try {
const acc: WorkbenchSession[] = [];
const seen = new Set<string>();
@@ -196,6 +211,10 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
beforeId: before,
cache: false,
});
+ if (!readOwnershipRef.current.isCurrent(read)) {
+ stale = true;
+ break;
+ }
for (const s of res.sessions) {
if (!seen.has(s.id)) {
seen.add(s.id);
@@ -205,10 +224,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
nextBeforeId = res.next_before_id;
before = res.next_before_id ?? undefined;
} while (before && acc.length < targetCount);
- setSessions((prev) => ({
- ...prev,
- [projectId]: { sessions: acc, cursor: nextBeforeId, loading: false, loadingMore: false, error: false },
- }));
+ if (!stale && readOwnershipRef.current.isCurrent(read)) {
+ setSessions((prev) => ({
+ ...prev,
+ [projectId]: { sessions: acc, cursor: nextBeforeId, loading: false, loadingMore: false, error: false },
+ }));
+ }
} catch {
/* keep the current window on a failed reconcile */
} finally {
@@ -223,6 +244,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
);
const reconcileProjectTree = useCallback(async () => {
+ const read = readOwnershipRef.current.beginRead();
const bootstrapGroups = new Map<number, string[]>();
const largeProjectIds: string[] = [];
for (const [projectId, state] of Object.entries(sessionsRef.current)) {
@@ -245,6 +267,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const groups = Array.from(bootstrapGroups.entries());
if (groups.length === 0) {
const result = await api.getWorkbenchProjectsBootstrap({ cache: false });
+ if (!readOwnershipRef.current.isCurrent(read)) return;
setProjects(result.projects);
} else {
let nextProjects: WorkbenchProject[] | null = null;
@@ -256,6 +279,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
limit,
cache: false,
});
+ if (!readOwnershipRef.current.isCurrent(read)) return;
nextProjects = result.projects;
for (const [projectId, page] of Object.entries(result.sessions ?? {})) {
const currentCount = sessionsRef.current[projectId]?.sessions?.length ?? 0;
@@ -266,14 +290,17 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}
}
}
+ if (!readOwnershipRef.current.isCurrent(read)) return;
if (nextProjects) setProjects(nextProjects);
applyBootstrapSessions(pages);
}
+ if (!readOwnershipRef.current.isCurrent(read)) return;
setProjectsError(null);
for (const projectId of largeProjectIds) {
void reconcileSessions(projectId);
}
} catch (err) {
+ if (!readOwnershipRef.current.isCurrent(read)) return;
setProjectsError(errorMessage(err) ?? String(err));
const projectIds = [...bootstrapGroups.values()].flat();
for (const projectId of [...projectIds, ...largeProjectIds]) {
@@ -287,9 +314,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),
);
if (!needsRefresh) return;
+ const read = readOwnershipRef.current.beginRead();
try {
const updated = await api.getSession(sessionId, { cache: false });
- setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));
+ if (readOwnershipRef.current.isCurrent(read)) {
+ setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));
+ }
} catch {
/* best-effort: reconnect reconcile will refresh the row later */
}
@@ -310,11 +340,18 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
[projectId]: append ? { ...cur, loadingMore: true } : { ...cur, loading: true, error: false },
};
});
+ const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;
+ const read = readOwnershipRef.current.beginRead();
try {
- const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;
const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId });
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
+ if (!readOwnershipRef.current.isCurrent(read)) {
+ return {
+ ...prev,
+ [projectId]: append ? { ...cur, loadingMore: false } : { ...cur, loading: false },
+ };
+ }
const existing = append ? cur.sessions ?? [] : [];
// Cursor pages can overlap if a row's last_active_at shifts between
// fetches (the cursor is just a row id resolved against current
@@ -329,6 +366,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
} catch {
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
+ if (!readOwnershipRef.current.isLatestRead(read)) return prev;
+ if (!readOwnershipRef.current.isCurrent(read)) {
+ return append
+ ? { ...prev, [projectId]: { ...cur, loadingMore: false } }
+ : { ...prev, [projectId]: { ...cur, loading: false } };
+ }
// Load-more failure: keep the list + cursor so the button stays usable.
// First-page failure: flag error (mobile retry; re-expand refetches) and
// keep `sessions` non-null so the desktop still renders its empty state.
@@ -357,6 +400,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
void reconcileProjectTree();
},
onSessionActivity: (data) => {
+ acceptSessionMutation();
if (data.event === 'archived') {
// Terminal archive (here or in another tab) — drop the row live.
setSessions((prev) => removeSessionRow(prev, data.session_id));
@@ -409,12 +453,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
void reconcileSessions(projectId, { minCount });
},
onSessionStatus: ({ session_id, agent_status }) => {
+ acceptSessionMutation();
setSessions((prev) =>
patchSessionRow(prev, session_id, (s) => (s.agent_status === agent_status ? s : { ...s, agent_status })),
);
if (agent_status !== 'running') void refreshCachedSessionRow(session_id);
},
onTurnEnd: ({ session_id }) => {
+ acceptSessionMutation();
// 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
@@ -423,7 +469,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
},
});
return disconnect;
- }, [api, reconcileProjectTree, reconcileSessions, refreshCachedSessionRow]);
+ }, [acceptSessionMutation, api, reconcileProjectTree, reconcileSessions, refreshCachedSessionRow]);
const toggleExpanded = useCallback(
(projectId: string) => {
@@ -454,6 +500,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
try {
// No overrides → omit agent fields so the server defers to the default Agent.
const session = await api.createSession({ project_id: projectId, ...overrides });
+ acceptSessionMutation();
if (alreadyLoaded) {
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
@@ -486,19 +533,20 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
});
}
},
- [api, fetchSessions],
+ [acceptSessionMutation, api, fetchSessions],
);
const renameProject = useCallback(
async (projectId: string, name: string) => {
try {
const updated = await api.updateProject(projectId, { display_name: name });
+ acceptSessionMutation();
setProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
} catch (err) {
console.error('[workbench] rename project failed', err);
}
},
- [api],
+ [acceptSessionMutation, api],
);
const forkSession = useCallback(
@@ -510,6 +558,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const alreadyLoaded = projectId != null && sessionsRef.current[projectId]?.sessions != null;
try {
const session = await api.forkSession(sessionId);
+ acceptSessionMutation();
if (projectId == null) return session;
if (alreadyLoaded) {
setSessions((prev) => {
@@ -537,7 +586,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
return null;
}
},
- [api, fetchSessions],
+ [acceptSessionMutation, api, fetchSessions],
);
const setProjectDefaultAgent = useCallback(
@@ -562,6 +611,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
async (projectId: string) => {
try {
await api.archiveProject(projectId);
+ acceptSessionMutation();
setProjects((prev) => (prev ? prev.filter((p) => p.id !== projectId) : prev));
setExpanded((prev) => {
if (!prev.has(projectId)) return prev;
@@ -573,7 +623,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
console.error('[workbench] archive project failed', err);
}
},
- [api],
+ [acceptSessionMutation, api],
);
const renameSession = useCallback(
@@ -583,6 +633,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// broadcast then reconciles the same value. Throws on failure (caller's
// inline editor catches it) so a failed rename leaves the old title.
const updated = await api.updateSession(sessionId, { title });
+ acceptSessionMutation();
setSessions((prev) => {
const state = prev[projectId];
if (!state?.sessions) return prev;
@@ -595,12 +646,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
};
});
},
- [api],
+ [acceptSessionMutation, api],
);
const setSessionPinned = useCallback(
async (projectId: string | null, sessionId: string, pinned: boolean) => {
const updated = await api.updateSession(sessionId, { pinned });
+ acceptSessionMutation();
// Session-keyed: patches whatever project holds the row (none, for a
// standalone session). Only the pinned-first re-order needs a project.
setSessions((prev) => patchSessionRow(prev, sessionId, () => updated, true));
@@ -608,7 +660,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const loaded = sessionsRef.current[projectId]?.sessions?.length ?? 0;
void reconcileSessions(projectId, { minCount: loaded });
},
- [api, reconcileSessions],
+ [acceptSessionMutation, api, reconcileSessions],
);
const archiveSession = useCallback(
@@ -616,6 +668,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// Archive is terminal — the API reclaims bound tasks/watches/runs server-side.
// Drop the row from the tree on success; throw so the caller's dialog can react.
await api.archiveSession(sessionId);
+ acceptSessionMutation();
if (projectId == null) return; // standalone session: no tree row to drop
setSessions((prev) => {
const state = prev[projectId];
@@ -626,7 +679,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
};
});
},
- [api],
+ [acceptSessionMutation, api],
);
const upsertProjectToTop = useCallback(
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
new file mode 100644
index 000000000..9fb38e9dc
--- /dev/null
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -0,0 +1,242 @@
+// @vitest-environment jsdom
+
+import { act, render } from '@testing-library/react';
+import { useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkbenchInboxProvider } from './WorkbenchInboxProvider';
+import { useWorkbenchInbox } from './WorkbenchInboxContext';
+import { WorkbenchProjectsProvider } from './WorkbenchProjectsProvider';
+import { useWorkbenchProjectsTree } from './WorkbenchProjectsContext';
+import type { WorkbenchEventHandlers } from './ApiContext';
+
+type Deferred<T> = {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+};
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((next) => {
+ resolve = next;
+ });
+ return { promise, resolve };
+}
+
+const session = {
+ id: 'ses_a',
+ scope_id: 'scope_a',
+ project_id: 'proj_a',
+ title: 'Visible before hide',
+ agent_id: null,
+ agent_name: null,
+ agent_backend: 'codex',
+ agent_variant: null,
+ model: null,
+ reasoning_effort: null,
+ status: 'active',
+ visibility: 'foreground' as const,
+ pinned: false,
+ agent_status: 'idle' as const,
+ workdir: null,
+ native_session_id: null,
+ created_at: '2026-08-11T00:00:00Z',
+ updated_at: '2026-08-11T00:00:00Z',
+ last_active_at: '2026-08-11T00:00:00Z',
+ metadata: {},
+};
+
+const project = {
+ id: 'proj_a',
+ scope_id: 'scope_a',
+ display_name: 'Project A',
+ folder_path: '/tmp/project-a',
+ created_at: '2026-08-11T00:00:00Z',
+ last_active_at: null,
+ archived: false,
+};
+
+const inboxRow = {
+ session_id: session.id,
+ scope_id: session.scope_id,
+ title: session.title,
+ preview: 'A stale inbox snapshot',
+ preview_message_id: 'msg_a',
+ last_activity_at: session.last_active_at,
+ unread_count: 3,
+ visibility: 'foreground' as const,
+};
+
+type FakeApi = {
+ getWorkbenchProjectsBootstrap?: () => Promise<unknown>;
+ listInbox?: () => Promise<unknown>;
+ connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
+};
+
+const apiRef = { current: null as FakeApi | null };
+
+vi.mock('./ApiContext', async () => {
+ const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');
+ return { ...actual, useApi: () => apiRef.current };
+});
+
+function settle() {
+ return act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+describe('Workbench session read ownership', () => {
+ beforeEach(() => {
+ apiRef.current = null;
+ });
+
+ afterEach(() => {
+ apiRef.current = null;
+ });
+
+ it('does not let a bootstrap issued before hide repopulate the projects tree', async () => {
+ const staleBootstrap = deferred({ projects: [project], sessions: { proj_a: { sessions: [session], next_before_id: null } } });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn()
+ .mockResolvedValueOnce({ projects: [project], sessions: { proj_a: { sessions: [session], next_before_id: null } } })
+ .mockReturnValueOnce(staleBootstrap.promise),
+ 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: 1, source: 'browser' });
+ });
+ await settle();
+ act(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'archived',
+ });
+ });
+ await act(async () => {
+ staleBootstrap.resolve({ projects: [project], sessions: { proj_a: { sessions: [session], next_before_id: null } } });
+ await staleBootstrap.promise;
+ });
+ await settle();
+
+ expect(tree?.projects).toEqual([project]);
+ expect(tree?.sessionsOf('proj_a').sessions).toEqual([]);
+ });
+
+ 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;
+ apiRef.current = {
+ listInbox: vi.fn()
+ .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } })
+ .mockReturnValueOnce(staleRefresh.promise),
+ 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(() => {
+ void inbox?.refresh();
+ });
+ await settle();
+ act(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'background',
+ });
+ });
+ await act(async () => {
+ staleRefresh.resolve({ sessions: [inboxRow], next_cursor: 'cursor_a', unread_by_session: { [session.id]: 3 } });
+ await staleRefresh.promise;
+ });
+ await settle();
+
+ expect(inbox?.inboxSessions).toEqual([]);
+ expect(inbox?.unreadBySession).toEqual({});
+ expect(inbox?.nextCursor).toBe('cursor_a');
+ });
+
+ 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: {} })
+ .mockResolvedValueOnce({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });
+ 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(listInbox).toHaveBeenCalledTimes(2);
+ expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);
+ expect(inbox?.unreadBySession).toEqual({ [session.id]: 3 });
+ expect(inbox?.nextCursor).toBe('cursor_before_restore');
+ });
+});
diff --git a/ui/src/lib/workbenchSessionReadOwnership.test.ts b/ui/src/lib/workbenchSessionReadOwnership.test.ts
new file mode 100644
index 000000000..d10d72eff
--- /dev/null
+++ b/ui/src/lib/workbenchSessionReadOwnership.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { createWorkbenchSessionReadOwnership } from './workbenchSessionReadOwnership';
+
+describe('Workbench session read ownership', () => {
+ it('accepts only the newest read in the current mutation epoch', () => {
+ const ownership = createWorkbenchSessionReadOwnership();
+ const older = ownership.beginRead();
+ const newer = ownership.beginRead();
+
+ expect(ownership.isCurrent(older)).toBe(false);
+ expect(ownership.isCurrent(newer)).toBe(true);
+ });
+
+ it('invalidates reads issued before an accepted session mutation', () => {
+ const ownership = createWorkbenchSessionReadOwnership();
+ const read = ownership.beginRead();
+
+ expect(ownership.epoch()).toBe(0);
+ expect(ownership.acceptMutation()).toBe(1);
+ expect(ownership.isCurrent(read)).toBe(false);
+ expect(ownership.isLatestRead(read)).toBe(true);
+ });
+});
diff --git a/ui/src/lib/workbenchSessionReadOwnership.ts b/ui/src/lib/workbenchSessionReadOwnership.ts
new file mode 100644
index 000000000..077b6d483
--- /dev/null
+++ b/ui/src/lib/workbenchSessionReadOwnership.ts
@@ -0,0 +1,40 @@
+/**
+ * Orders asynchronous Workbench reads against accepted session mutations.
+ *
+ * A response is only allowed to commit when it belongs to the current
+ * mutation epoch and is the newest read issued by this data owner. This keeps
+ * HTTP completion order from deciding whether a stale snapshot wins over a
+ * realtime event or a newer read.
+ */
+export type WorkbenchSessionReadStamp = {
+ epoch: number;
+ generation: number;
+};
+
+export type WorkbenchSessionReadOwnership = {
+ beginRead: () => WorkbenchSessionReadStamp;
+ acceptMutation: () => number;
+ isCurrent: (stamp: WorkbenchSessionReadStamp) => boolean;
+ isLatestRead: (stamp: WorkbenchSessionReadStamp) => boolean;
+ epoch: () => number;
+};
+
+export function createWorkbenchSessionReadOwnership(): WorkbenchSessionReadOwnership {
+ let mutationEpoch = 0;
+ let latestGeneration = 0;
+
+ return {
+ beginRead: () => {
+ latestGeneration += 1;
+ return { epoch: mutationEpoch, generation: latestGeneration };
+ },
+ acceptMutation: () => {
+ mutationEpoch += 1;
+ return mutationEpoch;
+ },
+ isCurrent: (stamp) =>
+ stamp.epoch === mutationEpoch && stamp.generation === latestGeneration,
+ isLatestRead: (stamp) => stamp.generation === latestGeneration,
+ epoch: () => mutationEpoch,
+ };
+}