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 independent read ordering
cyh19fb303bc4a9
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex 3d4b3ddae..ddecdc917 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -76,6 +76,11 @@ 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);const acceptSessionMutation = useCallback(() => {readOwnershipRef.current.acceptMutation();@@ -91,14 +96,24 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}, []);const refresh = useCallback(async () => {- const read = readOwnershipRef.current.beginRead();+ const read = readOwnershipRef.current.beginRead('inbox-feed');setLoading(true);try {const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });- if (!readOwnershipRef.current.isCurrent(read)) return;+ if (!readOwnershipRef.current.isCurrent(read)) {+ if (!authoritativeFeedLoadedRef.current && !coldRefreshRetryPendingRef.current) {+ coldRefreshRetryPendingRef.current = true;+ queueMicrotask(() => {+ coldRefreshRetryPendingRef.current = false;+ if (!authoritativeFeedLoadedRef.current) void refresh();+ });+ }+ return;+ }setInboxSessions(result.sessions);setNextCursor(result.next_cursor);applyUnreadMap(result.unread_by_session ?? {});+ authoritativeFeedLoadedRef.current = true;} catch (err) {console.error('[inbox] refresh failed', err);} finally {@@ -109,7 +124,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>const loadMore = useCallback(async () => {const cursor = cursorRef.current;if (!cursor) return;- const read = readOwnershipRef.current.beginRead();+ const read = readOwnershipRef.current.beginRead('inbox-feed');setLoadingMore(true);try {const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE, before: cursor });@@ -143,7 +158,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();+ const read = readOwnershipRef.current.beginRead('inbox-feed');// 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));@@ -166,6 +181,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>});// Whole-account unread map (not paginated) — always authoritative.applyUnreadMap(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// we had (overlap), the two runs are contiguous — no gap below the read —@@ -189,7 +205,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();+ const read = readOwnershipRef.current.beginRead(`inbox-session:${sessionId}`);try {const result = await api.listInbox({platform: 'avibe',@@ -199,7 +215,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 (!readOwnershipRef.current.isCurrent(read, ['inbox-feed', `inbox-session:${sessionId}`])) return;if (row) setInboxSessions((prev) => upsertSession(prev, row));applyUnreadMap(result.unread_by_session ?? {});} catch (err) {@@ -241,7 +257,6 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}},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@@ -249,10 +264,12 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>// See lib/inboxActivity.const action = sessionActivityInboxAction(data);if (action === 'reconcile') {+ acceptSessionMutation();void reconcileSession(data.session_id);return;}if (action === 'ignore') return;+ acceptSessionMutation();// action === 'drop': remove the card + its unread live, instead of// waiting for the next reconnect/refresh to filter it.setInboxSessions((prev) => prev.filter((s) => s.session_id !== data.session_id));diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsxindex af2649552..ce3233e80 100644--- a/ui/src/context/WorkbenchProjectsProvider.tsx+++ b/ui/src/context/WorkbenchProjectsProvider.tsx@@ -160,17 +160,22 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c}, []);const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {- const read = readOwnershipRef.current.beginRead();+ const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);try {const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });- if (!readOwnershipRef.current.isCurrent(read)) return;+ if (!readOwnershipRef.current.isCurrent(read, 'projects')) return;setProjects(result.projects);- applyBootstrapSessions(result.sessions ?? {});+ const pages = Object.fromEntries(+ Object.entries(result.sessions ?? {}).filter(([projectId]) =>+ readOwnershipRef.current.isCurrent(read, `project:${projectId}`),+ ),+ );+ applyBootstrapSessions(pages);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).- if (readOwnershipRef.current.isCurrent(read)) {+ if (readOwnershipRef.current.isCurrent(read, 'projects')) {setProjectsError(errorMessage(err) ?? String(err));}}@@ -196,7 +201,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cconst targetCount = Math.max(sessionsRef.current[projectId]?.sessions?.length ?? 0, minCount);if (targetCount === 0) return; // nothing loaded to reconcileinFlightRef.current.add(projectId);- const read = readOwnershipRef.current.beginRead();+ const read = readOwnershipRef.current.beginRead(`project:${projectId}`);let stale = false;try {const acc: WorkbenchSession[] = [];@@ -211,7 +216,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cbeforeId: before,cache: false,});- if (!readOwnershipRef.current.isCurrent(read)) {+ if (!readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {stale = true;break;}@@ -224,7 +229,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cnextBeforeId = res.next_before_id;before = res.next_before_id ?? undefined;} while (before && acc.length < targetCount);- if (!stale && readOwnershipRef.current.isCurrent(read)) {+ if (!stale && readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {setSessions((prev) => ({...prev,[projectId]: { sessions: acc, cursor: nextBeforeId, loading: false, loadingMore: false, error: false },@@ -244,7 +249,6 @@ 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)) {@@ -263,12 +267,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ cgroup.push(projectId);bootstrapGroups.set(limit, group);}+ const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);try {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);+ if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjects(result.projects);} else {let nextProjects: WorkbenchProject[] | null = null;const pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null }> = {};@@ -279,29 +283,38 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ climit,cache: false,});- if (!readOwnershipRef.current.isCurrent(read)) return;+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;nextProjects = result.projects;for (const [projectId, page] of Object.entries(result.sessions ?? {})) {const currentCount = sessionsRef.current[projectId]?.sessions?.length ?? 0;- if (page && !inFlightRef.current.has(projectId) && currentCount <= limit) {+ if (+ page &&+ !inFlightRef.current.has(projectId) &&+ currentCount <= limit &&+ readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])+ ) {pages[projectId] = page;} else {queueReconcile(projectId, currentCount);}}}- if (!readOwnershipRef.current.isCurrent(read)) return;- if (nextProjects) setProjects(nextProjects);- applyBootstrapSessions(pages);+ if (readOwnershipRef.current.isCurrent(read, 'projects') && nextProjects) setProjects(nextProjects);+ const currentPages = Object.fromEntries(+ Object.entries(pages).filter(([projectId]) =>+ readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]),+ ),+ );+ applyBootstrapSessions(currentPages);}- if (!readOwnershipRef.current.isCurrent(read)) return;- setProjectsError(null);+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;+ if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(null);for (const projectId of largeProjectIds) {void reconcileSessions(projectId);}} catch (err) {- if (!readOwnershipRef.current.isCurrent(read)) return;- setProjectsError(errorMessage(err) ?? String(err));+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) return;+ if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(errorMessage(err) ?? String(err));const projectIds = [...bootstrapGroups.values()].flat();for (const projectId of [...projectIds, ...largeProjectIds]) {void reconcileSessions(projectId);@@ -310,14 +323,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c}, [api, applyBootstrapSessions, queueReconcile, reconcileSessions]);const refreshCachedSessionRow = useCallback(async (sessionId: string) => {- const needsRefresh = Object.values(sessionsRef.current).some((state) =>+ const projectId = Object.entries(sessionsRef.current).find(([, state]) =>state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),- );- if (!needsRefresh) return;- const read = readOwnershipRef.current.beginRead();+ )?.[0];+ if (!projectId) return;+ const read = readOwnershipRef.current.beginRead(`project:${projectId}`);try {const updated = await api.getSession(sessionId, { cache: false });- if (readOwnershipRef.current.isCurrent(read)) {+ if (readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));}} catch {@@ -341,12 +354,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c};});const beforeId = append ? sessionsRef.current[projectId]?.cursor ?? undefined : undefined;- const read = readOwnershipRef.current.beginRead();+ const read = readOwnershipRef.current.beginRead(`project:${projectId}`);try {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)) {+ if (!readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {return {...prev,[projectId]: append ? { ...cur, loadingMore: false } : { ...cur, loading: false },@@ -367,7 +380,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ csetSessions((prev) => {const cur = prev[projectId] ?? EMPTY_SESSIONS;if (!readOwnershipRef.current.isLatestRead(read)) return prev;- if (!readOwnershipRef.current.isCurrent(read)) {+ if (!readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {return append? { ...prev, [projectId]: { ...cur, loadingMore: false } }: { ...prev, [projectId]: { ...cur, loading: false } };diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsxindex 9fb38e9dc..88c5a5bd5 100644--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx@@ -56,6 +56,22 @@ const project = {archived: false,};+const projectB = {+ ...project,+ id: 'proj_b',+ scope_id: 'scope_b',+ display_name: 'Project B',+ folder_path: '/tmp/project-b',+};++const sessionB = {+ ...session,+ id: 'ses_b',+ scope_id: projectB.scope_id,+ project_id: projectB.id,+ title: 'Project B session',+};+const inboxRow = {session_id: session.id,scope_id: session.scope_id,@@ -69,6 +85,7 @@ const inboxRow = {type FakeApi = {getWorkbenchProjectsBootstrap?: () => Promise<unknown>;+ listSessions?: (args: { projectId: string }) => Promise<unknown>;listInbox?: () => Promise<unknown>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;};@@ -145,6 +162,53 @@ describe('Workbench session read ownership', () => {expect(tree?.sessionsOf('proj_a').sessions).toEqual([]);});+ 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 });+ apiRef.current = {+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({+ projects: [project, projectB],+ sessions: {},+ }),+ listSessions: vi.fn(({ projectId }) => (+ projectId === project.id ? projectARead.promise : projectBRead.promise+ )),+ 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?.toggleExpanded(project.id);+ tree?.toggleExpanded(projectB.id);+ });+ await settle();+ await act(async () => {+ projectBRead.resolve({ sessions: [sessionB], next_before_id: null });+ await projectBRead.promise;+ });+ await act(async () => {+ projectARead.resolve({ sessions: [session], next_before_id: null });+ await projectARead.promise;+ });++ expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);+ expect(tree?.sessionsOf(projectB.id).sessions).toEqual([sessionB]);+ });+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;@@ -196,6 +260,55 @@ describe('Workbench session read ownership', () => {expect(inbox?.nextCursor).toBe('cursor_a');});+ it('retries a cold Inbox refresh invalidated by activity', async () => {+ const staleRefresh = deferred({ sessions: [inboxRow], next_cursor: 'stale_cursor', unread_by_session: { [session.id]: 3 } });+ const listInbox = vi.fn()+ .mockReturnValueOnce(staleRefresh.promise)+ .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: 'background',+ });+ });+ 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(2);+ expect(inbox?.inboxSessions).toEqual([]);+ expect(inbox?.unreadBySession).toEqual({});+ expect(inbox?.nextCursor).toBeNull();+ });+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: {} })@@ -231,6 +344,12 @@ describe('Workbench session read ownership', () => {event: 'updated',visibility: 'foreground',});+ handlers?.onSessionActivity?.({+ session_id: session.id,+ scope_id: session.scope_id,+ event: 'created',+ restored: true,+ });});await settle();diff --git a/ui/src/lib/workbenchSessionReadOwnership.test.ts b/ui/src/lib/workbenchSessionReadOwnership.test.tsindex d10d72eff..4380bbb2f 100644--- a/ui/src/lib/workbenchSessionReadOwnership.test.ts+++ b/ui/src/lib/workbenchSessionReadOwnership.test.ts@@ -21,4 +21,27 @@ describe('Workbench session read ownership', () => {expect(ownership.isCurrent(read)).toBe(false);expect(ownership.isLatestRead(read)).toBe(true);});++ it('tracks read generations independently for independent resources', () => {+ const ownership = createWorkbenchSessionReadOwnership();+ const projectA = ownership.beginRead('project:a');+ const projectB = ownership.beginRead('project:b');++ expect(ownership.isCurrent(projectA)).toBe(true);+ expect(ownership.isCurrent(projectB)).toBe(true);++ const newerProjectA = ownership.beginRead('project:a');+ expect(ownership.isCurrent(projectA)).toBe(false);+ expect(ownership.isCurrent(newerProjectA)).toBe(true);+ expect(ownership.isCurrent(projectB)).toBe(true);+ });++ it('lets a broad read and a resource read order their overlapping payload', () => {+ const ownership = createWorkbenchSessionReadOwnership();+ const bootstrap = ownership.beginRead('projects-bootstrap');+ const project = ownership.beginRead('project:a');++ expect(ownership.isCurrent(bootstrap, ['projects-bootstrap', 'project:a'])).toBe(false);+ expect(ownership.isCurrent(project, ['projects-bootstrap', 'project:a'])).toBe(true);+ });});diff --git a/ui/src/lib/workbenchSessionReadOwnership.ts b/ui/src/lib/workbenchSessionReadOwnership.tsindex 077b6d483..f970cadee 100644--- a/ui/src/lib/workbenchSessionReadOwnership.ts+++ b/ui/src/lib/workbenchSessionReadOwnership.ts@@ -1,20 +1,24 @@/*** 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.+ * A response is only allowed to commit when it belongs to the current mutation+ * epoch and has not been superseded for any resource it owns. The shared epoch+ * orders realtime mutations, while resource generations keep independent reads+ * from invalidating one another merely because they completed in another order.*/export type WorkbenchSessionReadStamp = {epoch: number;generation: number;+ resources: string[];};export type WorkbenchSessionReadOwnership = {- beginRead: () => WorkbenchSessionReadStamp;+ beginRead: (resources?: string | readonly string[]) => WorkbenchSessionReadStamp;acceptMutation: () => number;- isCurrent: (stamp: WorkbenchSessionReadStamp) => boolean;+ isCurrent: (+ stamp: WorkbenchSessionReadStamp,+ resources?: string | readonly string[],+ ) => boolean;isLatestRead: (stamp: WorkbenchSessionReadStamp) => boolean;epoch: () => number;};@@ -22,19 +26,32 @@ export type WorkbenchSessionReadOwnership = {export function createWorkbenchSessionReadOwnership(): WorkbenchSessionReadOwnership {let mutationEpoch = 0;let latestGeneration = 0;+ const latestByResource = new Map<string, number>();return {- beginRead: () => {+ beginRead: (resources = 'default') => {+ const resourceList = typeof resources === 'string' ? [resources] : [...resources];+ if (resourceList.length === 0) throw new Error('A session read must own at least one resource');latestGeneration += 1;- return { epoch: mutationEpoch, generation: latestGeneration };+ for (const resource of resourceList) latestByResource.set(resource, latestGeneration);+ return { epoch: mutationEpoch, generation: latestGeneration, resources: resourceList };},acceptMutation: () => {mutationEpoch += 1;return mutationEpoch;},- isCurrent: (stamp) =>- stamp.epoch === mutationEpoch && stamp.generation === latestGeneration,- isLatestRead: (stamp) => stamp.generation === latestGeneration,+ isCurrent: (stamp, resources = stamp.resources) => {+ const resourceList = typeof resources === 'string' ? [resources] : resources;+ return (+ stamp.epoch === mutationEpoch &&+ resourceList.every((resource) => {+ const latest = latestByResource.get(resource);+ return latest === undefined || latest <= stamp.generation;+ })+ );+ },+ isLatestRead: (stamp) =>+ stamp.resources.every((resource) => latestByResource.get(resource) === stamp.generation),epoch: () => mutationEpoch,};}