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): scope session freshness by resource

cyh380522734066
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 6fcbe7a99..2f96fd613 100644
--- a/ui/src/context/WorkbenchInboxProvider.tsx
+++ b/ui/src/context/WorkbenchInboxProvider.tsx
@@ -6,7 +6,10 @@ 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';
+import {
+ createWorkbenchSessionReadOwnership,
+ type WorkbenchSessionReadStamp,
+} from '../lib/workbenchSessionReadOwnership';
const PAGE_SIZE = 30;
@@ -37,7 +40,6 @@ const appendPage = (prev: InboxSession[], page: InboxSession[]): InboxSession[]
type TargetedInboxSnapshot = {
row: InboxSession | null;
- unreadCount: number;
};
/** Provider that owns the Inbox state shared across WorkbenchSidebar + InboxPage.
@@ -91,12 +93,21 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
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.
+ // replacement cannot erase a restored card merely because the row sorts
+ // outside the page.
const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());
- const acceptSessionMutation = useCallback(() => {
- readOwnershipRef.current.acceptMutation();
+ const acceptSessionMutation = useCallback((sessionId: string) => {
+ readOwnershipRef.current.acceptMutation([
+ 'inbox-feed',
+ 'inbox-unread',
+ `inbox-session:${sessionId}`,
+ `inbox-unread-session:${sessionId}`,
+ ]);
+ }, []);
+
+ const acceptUnreadMutation = useCallback(() => {
+ readOwnershipRef.current.acceptMutation(['inbox-unread', 'inbox-unread-all']);
}, []);
// One home for "an authoritative unread map arrived": set the map and flip
@@ -108,18 +119,6 @@ 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) {
@@ -130,13 +129,24 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
return next;
}, []);
+ const acceptFeedRows = useCallback((read: WorkbenchSessionReadStamp, rows: InboxSession[]) => {
+ for (const row of rows) {
+ const resource = `inbox-session:${row.session_id}`;
+ readOwnershipRef.current.claimRead(read, resource);
+ if (readOwnershipRef.current.isCurrent(read, resource)) {
+ targetedSnapshotsRef.current.delete(row.session_id);
+ }
+ }
+ }, []);
+
const refresh = useCallback(async () => {
- const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-refresh']);
+ const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-refresh']);
const loadingGeneration = ++refreshLoadingGenerationRef.current;
setLoading(true);
try {
const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });
- if (!readOwnershipRef.current.isCurrent(read)) {
+ const feedCurrent = readOwnershipRef.current.isCurrent(read, 'inbox-feed');
+ if (!feedCurrent) {
if (!authoritativeFeedLoadedRef.current && !coldRefreshRetryPendingRef.current) {
coldRefreshRetryPendingRef.current = true;
queueMicrotask(() => {
@@ -144,48 +154,59 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (!authoritativeFeedLoadedRef.current) void refresh();
});
}
- return;
+ } else {
+ acceptFeedRows(read, result.sessions);
+ setInboxSessions(() => mergeTargetedSnapshots(result.sessions));
+ setNextCursor(result.next_cursor);
+ authoritativeFeedLoadedRef.current = true;
+ }
+ if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {
+ applyUnreadMap(result.unread_by_session ?? {});
}
- setInboxSessions(() => mergeTargetedSnapshots(result.sessions));
- setNextCursor(result.next_cursor);
- applyFeedUnreadMap(result.unread_by_session ?? {});
- authoritativeFeedLoadedRef.current = true;
} catch (err) {
console.error('[inbox] refresh failed', err);
} finally {
if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);
}
- }, [api, applyFeedUnreadMap, mergeTargetedSnapshots]);
+ }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots]);
- const loadMore = useCallback(async () => {
+ const loadMore = useCallback(async function loadMore() {
const cursor = cursorRef.current;
if (!cursor) return;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-feed-cursor']);
const loadingGeneration = ++loadMoreLoadingGenerationRef.current;
+ let retryAfterInvalidation = false;
setLoadingMore(true);
try {
const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE, before: cursor });
- if (!readOwnershipRef.current.isCurrent(read)) return;
+ if (!readOwnershipRef.current.isCurrent(read, 'inbox-feed')) {
+ retryAfterInvalidation = readOwnershipRef.current.isLatestRead(read);
+ return;
+ }
setInboxSessions((prev) => appendPage(prev, result.sessions));
setNextCursor(result.next_cursor);
} catch (err) {
- console.error('[inbox] load more failed', err);
+ retryAfterInvalidation =
+ !readOwnershipRef.current.isCurrent(read, 'inbox-feed') &&
+ readOwnershipRef.current.isLatestRead(read);
+ if (!retryAfterInvalidation) console.error('[inbox] load more failed', err);
} finally {
if (loadMoreLoadingGenerationRef.current === loadingGeneration) setLoadingMore(false);
+ if (retryAfterInvalidation) queueMicrotask(() => void loadMore());
}
}, [api]);
const markRead = useCallback(
async (sessionId: string, untilMessageId?: string) => {
+ const read = readOwnershipRef.current.beginRead('inbox-unread');
const result = await api.markSessionRead(sessionId, untilMessageId);
- targetedSnapshotsRef.current.delete(sessionId);
- acceptSessionMutation();
+ if (!readOwnershipRef.current.isCurrent(read, 'inbox-unread')) return;
// 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 ?? {});
},
- [acceptSessionMutation, api, applyUnreadMap],
+ [api, applyUnreadMap],
);
// Resume reconcile: re-read the feed WITHOUT collapsing pagination. A
@@ -196,7 +217,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', 'inbox-feed-reconcile']);
+ const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', '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));
@@ -208,15 +229,15 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
cache: false,
handleError: false,
});
- const stale = !readOwnershipRef.current.isCurrent(read) || !readOwnershipRef.current.isLatestRead(read);
- const invalidatedByMutation = readOwnershipRef.current.epoch() !== read.epoch;
+ const feedCurrent = readOwnershipRef.current.isCurrent(read, 'inbox-feed');
+ const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');
const supersededByCursorRead =
(readOwnershipRef.current.latestGeneration('inbox-feed-cursor') ?? 0) > read.generation;
const supersededByReconcileRead =
(readOwnershipRef.current.latestGeneration('inbox-feed-reconcile') ?? 0) > read.generation;
const supersededByRefresh =
(readOwnershipRef.current.latestGeneration('inbox-feed-refresh') ?? 0) > read.generation;
- if (stale || supersededByCursorRead || supersededByReconcileRead) {
+ if (!feedCurrent || supersededByCursorRead || supersededByReconcileRead) {
if (
(invalidatedByMutation || supersededByCursorRead) &&
!supersededByRefresh &&
@@ -229,43 +250,48 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
void reconcile();
});
}
- return;
+ } else {
+ 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);
+ 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 mergeTargetedSnapshots(merged);
+ });
+ authoritativeFeedLoadedRef.current = true;
+ // Cursor: the loaded feed is always a contiguous run from the top, and
+ // this reads the newest `limit` rows. If the read shares ANY row with what
+ // we had (overlap), the two runs are contiguous — no gap below the read —
+ // so the existing cursor still marks the boundary; leave it untouched
+ // (this is what stops a >100-row exhausted feed from resurrecting a
+ // duplicate-page "Load more"). If the read is ENTIRELY new rows (no
+ // overlap), gap arrivals outnumbered the window and there are unseen rows
+ // between this read and the old feed — adopt result.next_cursor so "Load
+ // more" can page through them (loadMore dedupes the overlap).
+ const overlap = result.sessions.some((s) => loadedIds.has(s.session_id));
+ if (!overlap) setNextCursor(result.next_cursor);
+ }
+ if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {
+ applyUnreadMap(result.unread_by_session ?? {});
}
- 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);
- 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 mergeTargetedSnapshots(merged);
- });
- // Whole-account unread map (not paginated) — always authoritative.
- 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
- // we had (overlap), the two runs are contiguous — no gap below the read —
- // so the existing cursor still marks the boundary; leave it untouched
- // (this is what stops a >100-row exhausted feed from resurrecting a
- // duplicate-page "Load more"). If the read is ENTIRELY new rows (no
- // overlap), gap arrivals outnumbered the window and there are unseen rows
- // between this read and the old feed — adopt result.next_cursor so "Load
- // more" can page through them (loadMore dedupes the overlap).
- const overlap = result.sessions.some((s) => loadedIds.has(s.session_id));
- if (!overlap) setNextCursor(result.next_cursor);
} catch (err) {
console.error('[inbox] reconcile failed', err);
}
- }, [api, applyFeedUnreadMap, mergeTargetedSnapshots]);
+ }, [acceptFeedRows, api, applyUnreadMap, mergeTargetedSnapshots]);
// Targeted reconcile for one session (contract A6 foreground restore): fetch
// that exact session by id and upsert its card, so a restored session
// reappears even when its activity sorts past the windowed reconcile()'s
// newest-N rows. The response still carries the pagination-independent
- // whole-account unread map, so refresh that too. Never touches the cursor.
+ // whole-account unread map, but this read owns only this session's count.
+ // Never touches the cursor or replaces unrelated unread state.
const reconcileSession = useCallback(
async (sessionId: string) => {
- const read = readOwnershipRef.current.beginRead(`inbox-session:${sessionId}`);
+ const sessionResource = `inbox-session:${sessionId}`;
+ const unreadResource = `inbox-unread-session:${sessionId}`;
+ const read = readOwnershipRef.current.beginRead([sessionResource, unreadResource]);
try {
const result = await api.listInbox({
platform: 'avibe',
@@ -275,20 +301,32 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
handleError: false,
});
const row = result.sessions.find((s) => s.session_id === sessionId);
- if (!readOwnershipRef.current.isCurrent(read)) return;
- 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 ?? {});
+ if (readOwnershipRef.current.isCurrent(read, sessionResource)) {
+ targetedSnapshotsRef.current.set(sessionId, { row: row ?? null });
+ setInboxSessions((prev) =>
+ row ? upsertSession(prev, row) : prev.filter((candidate) => candidate.session_id !== sessionId),
+ );
+ }
+ const newerWholeUnreadRead =
+ (readOwnershipRef.current.latestGeneration('inbox-unread') ?? 0) > read.generation;
+ if (
+ readOwnershipRef.current.isCurrent(read, unreadResource) &&
+ readOwnershipRef.current.isMutationCurrent(read, 'inbox-unread-all') &&
+ !newerWholeUnreadRead
+ ) {
+ const unreadCount = result.unread_by_session?.[sessionId] ?? 0;
+ setUnreadBySession((prev) => {
+ const next = { ...prev };
+ if (unreadCount > 0) next[sessionId] = unreadCount;
+ else delete next[sessionId];
+ return next;
+ });
+ }
} catch (err) {
console.error('[inbox] reconcileSession failed', err);
}
},
- [api, applyUnreadMap],
+ [api],
);
useEffect(() => {
@@ -307,7 +345,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const disconnect = api.connectWorkbenchEvents({
onInboxSessionUpdated: (row) => {
targetedSnapshotsRef.current.delete(row.session_id);
- acceptSessionMutation();
+ acceptSessionMutation(row.session_id);
setInboxSessions((prev) => upsertSession(prev, row));
setUnreadBySession((prev) => {
if ((prev[row.session_id] ?? 0) === row.unread_count) return prev;
@@ -318,8 +356,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
});
},
onInboxUnreadChanged: (data) => {
- targetedSnapshotsRef.current.clear();
- acceptSessionMutation();
+ acceptUnreadMutation();
if (data?.unread_by_session) {
applyUnreadMap(data.unread_by_session);
}
@@ -333,13 +370,13 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const action = sessionActivityInboxAction(data);
if (action === 'reconcile') {
targetedSnapshotsRef.current.delete(data.session_id);
- acceptSessionMutation();
+ acceptSessionMutation(data.session_id);
void reconcileSession(data.session_id);
return;
}
if (action === 'ignore') return;
targetedSnapshotsRef.current.delete(data.session_id);
- acceptSessionMutation();
+ acceptSessionMutation(data.session_id);
// 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));
@@ -357,7 +394,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
},
});
return disconnect;
- }, [acceptSessionMutation, api, refresh, reconcile, reconcileSession, applyUnreadMap]);
+ }, [acceptSessionMutation, acceptUnreadMutation, 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 64132d02c..3a5aaede9 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -122,6 +122,7 @@ 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());
+ const sessionProjectRef = useRef<Map<string, string>>(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.
@@ -130,8 +131,23 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const bootstrapRetryPendingRef = useRef(false);
const projectTreeRetryPendingRef = useRef(false);
- const acceptSessionMutation = useCallback(() => {
- readOwnershipRef.current.acceptMutation();
+ const acceptSessionMutation = useCallback((projectId?: string | null, sessionId?: string) => {
+ const resources = ['projects-bootstrap'];
+ if (projectId) resources.push(`project:${projectId}`);
+ if (sessionId) resources.push(`project-session:${sessionId}`);
+ readOwnershipRef.current.acceptMutation(resources);
+ }, []);
+
+ const acceptProjectsMutation = useCallback(() => {
+ readOwnershipRef.current.acceptMutation('projects');
+ }, []);
+
+ const projectIdForSession = useCallback((sessionId: string): string | null => {
+ const known = sessionProjectRef.current.get(sessionId);
+ if (known) return known;
+ return Object.entries(sessionsRef.current).find(([, state]) =>
+ state.sessions?.some((session) => session.id === sessionId),
+ )?.[0] ?? null;
}, []);
const queueReconcile = useCallback((projectId: string, minCount = 0) => {
@@ -146,7 +162,23 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
return pending;
}, []);
- const applyBootstrapSessions = useCallback((pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null } | undefined>) => {
+ const acceptProjectRows = useCallback(
+ (read: WorkbenchSessionReadStamp, projectId: string, rows: WorkbenchSession[]) => {
+ for (const session of rows) {
+ readOwnershipRef.current.claimRead(read, `project-session:${session.id}`);
+ sessionProjectRef.current.set(session.id, projectId);
+ }
+ },
+ [],
+ );
+
+ const applyBootstrapSessions = useCallback((
+ read: WorkbenchSessionReadStamp,
+ pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null } | undefined>,
+ ) => {
+ for (const [projectId, page] of Object.entries(pages)) {
+ if (page) acceptProjectRows(read, projectId, page.sessions);
+ }
setSessions((prev) => {
let changed = false;
const next = { ...prev };
@@ -163,14 +195,15 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}
return changed ? next : prev;
});
- }, []);
+ }, [acceptProjectRows]);
const fetchProjects = useCallback(async (options?: { cache?: boolean }) => {
const read = readOwnershipRef.current.beginRead(['projects', 'projects-bootstrap']);
const retryAfterMutation = () => {
if (
authoritativeProjectsLoadedRef.current ||
- readOwnershipRef.current.epoch() === read.epoch ||
+ readOwnershipRef.current.isCurrent(read, 'projects-bootstrap') ||
+ !readOwnershipRef.current.isLatestRead(read) ||
bootstrapRetryPendingRef.current
) {
return;
@@ -183,23 +216,23 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
};
try {
const result = await api.getWorkbenchProjectsBootstrap({ cache: options?.cache });
- if (!readOwnershipRef.current.isCurrent(read, 'projects')) {
+ if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjects(result.projects);
+ if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {
retryAfterMutation();
return;
}
- setProjects(result.projects);
const pages = Object.fromEntries(
Object.entries(result.sessions ?? {}).filter(([projectId]) =>
- readOwnershipRef.current.isCurrent(read, `project:${projectId}`),
+ readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]),
),
);
- applyBootstrapSessions(pages);
- setProjectsError(null);
+ applyBootstrapSessions(read, pages);
+ if (readOwnershipRef.current.isCurrent(read, 'projects')) setProjectsError(null);
authoritativeProjectsLoadedRef.current = true;
} 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, 'projects')) {
+ if (readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) {
setProjectsError(errorMessage(err) ?? String(err));
} else {
retryAfterMutation();
@@ -242,7 +275,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
beforeId: before,
cache: false,
});
- if (!readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {
+ if (!readOwnershipRef.current.isCurrent(read, `project:${projectId}`)) {
stale = true;
break;
}
@@ -255,36 +288,25 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
nextBeforeId = res.next_before_id;
before = res.next_before_id ?? undefined;
} while (before && acc.length < targetCount);
- if (!stale && readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {
+ if (!stale && readOwnershipRef.current.isCurrent(read, `project:${projectId}`)) {
+ acceptProjectRows(read, projectId, acc);
setSessions((prev) => ({
...prev,
[projectId]: { sessions: acc, cursor: nextBeforeId, loading: false, loadingMore: false, error: false },
}));
}
} catch {
- /* keep the current window on a failed reconcile */
+ stale = !readOwnershipRef.current.isCurrent(read, `project:${projectId}`);
+ /* keep the current window on a current failed reconcile */
} finally {
inFlightRef.current.delete(projectId);
}
const pendingMinCount = takePendingReconcile(projectId);
- if (pendingMinCount === null) return;
- minCount = pendingMinCount;
+ if (!stale && pendingMinCount === null) return;
+ minCount = Math.max(targetCount, pendingMinCount ?? 0);
}
},
- [api, queueReconcile, takePendingReconcile],
- );
-
- const queueReconcileForSession = useCallback(
- (sessionId: string) => {
- const entry = Object.entries(sessionsRef.current).find(([, state]) =>
- state.sessions?.some((session) => session.id === sessionId),
- );
- if (!entry) return;
- const [projectId, state] = entry;
- if (!inFlightRef.current.has(projectId)) return;
- queueReconcile(projectId, state.sessions?.length ?? 0);
- },
- [queueReconcile],
+ [acceptProjectRows, api, queueReconcile, takePendingReconcile],
);
const reconcileProjectTree = useCallback(async function reconcileProjectTree() {
@@ -361,7 +383,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`]),
),
);
- applyBootstrapSessions(currentPages);
+ applyBootstrapSessions(read, currentPages);
}
if (!readOwnershipRef.current.isCurrent(read, 'projects-bootstrap')) {
retryAfterInvalidation(read);
@@ -384,19 +406,29 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}
}, [api, applyBootstrapSessions, queueReconcile, reconcileSessions]);
- const refreshCachedSessionRow = useCallback(async (sessionId: string) => {
+ const refreshCachedSessionRow = useCallback(async function refreshCachedSessionRow(sessionId: string) {
const projectId = Object.entries(sessionsRef.current).find(([, state]) =>
state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),
)?.[0];
if (!projectId) return;
- const read = readOwnershipRef.current.beginRead(`project:${projectId}`);
+ const resource = `project-session:${sessionId}`;
+ const read = readOwnershipRef.current.beginRead(resource);
try {
const updated = await api.getSession(sessionId, { cache: false });
- if (readOwnershipRef.current.isCurrent(read, ['projects-bootstrap', `project:${projectId}`])) {
+ if (readOwnershipRef.current.isCurrent(read, resource)) {
+ sessionProjectRef.current.set(updated.id, projectId);
setSessions((prev) => patchSessionRow(prev, sessionId, () => updated));
+ } else if (readOwnershipRef.current.isLatestRead(read)) {
+ queueMicrotask(() => void refreshCachedSessionRow(sessionId));
}
} catch {
- /* best-effort: reconnect reconcile will refresh the row later */
+ if (
+ !readOwnershipRef.current.isCurrent(read, resource) &&
+ readOwnershipRef.current.isLatestRead(read)
+ ) {
+ queueMicrotask(() => void refreshCachedSessionRow(sessionId));
+ }
+ /* best-effort current failures are recovered by reconnect reconcile */
}
}, [api]);
@@ -417,11 +449,12 @@ 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;
+ let retryAfterInvalidation = 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;
+ const currentRead = readOwnershipRef.current.isCurrent(read, `project:${projectId}`);
+ retryAfterInvalidation = !currentRead && readOwnershipRef.current.isLatestRead(read);
+ if (currentRead) acceptProjectRows(read, projectId, res.sessions);
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
if (!currentRead) {
@@ -442,8 +475,8 @@ 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;
+ const currentRead = readOwnershipRef.current.isCurrent(read, `project:${projectId}`);
+ retryAfterInvalidation = !currentRead && readOwnershipRef.current.isLatestRead(read);
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
if (!readOwnershipRef.current.isLatestRead(read)) return prev;
@@ -461,21 +494,18 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
});
} finally {
inFlightRef.current.delete(projectId);
- if (retryFirstPage) {
+ const pendingMinCount = takePendingReconcile(projectId);
+ if (retryAfterInvalidation) {
+ if (pendingMinCount !== null) queueReconcile(projectId, pendingMinCount);
queueMicrotask(() => {
- const current = sessionsRef.current[projectId];
- if (current?.sessions === null && !inFlightRef.current.has(projectId)) {
- void fetchSessions(projectId);
- }
+ if (!inFlightRef.current.has(projectId)) void fetchSessions(projectId, opts);
});
- }
- const pendingMinCount = takePendingReconcile(projectId);
- if (pendingMinCount !== null) {
+ } else if (pendingMinCount !== null) {
void reconcileSessions(projectId, { minCount: pendingMinCount });
}
}
},
- [api, reconcileSessions, takePendingReconcile],
+ [acceptProjectRows, api, queueReconcile, reconcileSessions, takePendingReconcile],
);
// Keep the tree live: patch a row's status dot / title from SSE, and refetch
@@ -488,8 +518,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
void reconcileProjectTree();
},
onSessionActivity: (data) => {
- acceptSessionMutation();
+ const projectId =
+ projectsRef.current?.find((project) => project.scope_id === data.scope_id)?.id ??
+ projectIdForSession(data.session_id);
+ if (projectId) sessionProjectRef.current.set(data.session_id, projectId);
+ acceptSessionMutation(projectId, data.session_id);
if (data.event === 'archived') {
+ sessionProjectRef.current.delete(data.session_id);
// Terminal archive (here or in another tab) — drop the row live.
setSessions((prev) => removeSessionRow(prev, data.session_id));
return;
@@ -517,7 +552,6 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
),
);
if (hasPinned) {
- const projectId = projectsRef.current?.find((project) => project.scope_id === data.scope_id)?.id;
if (projectId) {
const loaded = sessionsRef.current[projectId]?.sessions?.length ?? 0;
void reconcileSessions(projectId, { minCount: loaded });
@@ -526,7 +560,6 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
return;
}
if (!REORDER_ACTIVITY_EVENTS.has(data.event)) return;
- const projectId = projectsRef.current?.find((project) => project.scope_id === data.scope_id)?.id;
if (!projectId) return;
// Grow the window ONLY for a synthesized foreground-restore (`data.restored`,
// set by visibilityActivityEvents on Undo): reconcile one past the loaded
@@ -541,16 +574,14 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
void reconcileSessions(projectId, { minCount });
},
onSessionStatus: ({ session_id, agent_status }) => {
- acceptSessionMutation();
- queueReconcileForSession(session_id);
+ acceptSessionMutation(projectIdForSession(session_id), session_id);
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();
- queueReconcileForSession(session_id);
+ acceptSessionMutation(projectIdForSession(session_id), session_id);
// 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
@@ -562,7 +593,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}, [
acceptSessionMutation,
api,
- queueReconcileForSession,
+ projectIdForSession,
reconcileProjectTree,
reconcileSessions,
refreshCachedSessionRow,
@@ -597,7 +628,8 @@ 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();
+ sessionProjectRef.current.set(session.id, projectId);
+ acceptSessionMutation(projectId, session.id);
if (alreadyLoaded) {
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
@@ -637,13 +669,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
async (projectId: string, name: string) => {
try {
const updated = await api.updateProject(projectId, { display_name: name });
- acceptSessionMutation();
+ acceptProjectsMutation();
setProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
} catch (err) {
console.error('[workbench] rename project failed', err);
}
},
- [acceptSessionMutation, api],
+ [acceptProjectsMutation, api],
);
const forkSession = useCallback(
@@ -655,7 +687,8 @@ 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) sessionProjectRef.current.set(session.id, projectId);
+ acceptSessionMutation(projectId, session.id);
if (projectId == null) return session;
if (alreadyLoaded) {
setSessions((prev) => {
@@ -699,16 +732,18 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
model: route.model,
reasoning_effort: route.reasoning_effort,
});
+ acceptProjectsMutation();
setProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
},
- [api],
+ [acceptProjectsMutation, api],
);
const archiveProject = useCallback(
async (projectId: string) => {
try {
await api.archiveProject(projectId);
- acceptSessionMutation();
+ acceptProjectsMutation();
+ acceptSessionMutation(projectId);
setProjects((prev) => (prev ? prev.filter((p) => p.id !== projectId) : prev));
setExpanded((prev) => {
if (!prev.has(projectId)) return prev;
@@ -720,7 +755,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
console.error('[workbench] archive project failed', err);
}
},
- [acceptSessionMutation, api],
+ [acceptProjectsMutation, acceptSessionMutation, api],
);
const renameSession = useCallback(
@@ -730,7 +765,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();
+ acceptSessionMutation(projectId, sessionId);
setSessions((prev) => {
const state = prev[projectId];
if (!state?.sessions) return prev;
@@ -749,7 +784,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const setSessionPinned = useCallback(
async (projectId: string | null, sessionId: string, pinned: boolean) => {
const updated = await api.updateSession(sessionId, { pinned });
- acceptSessionMutation();
+ acceptSessionMutation(projectId, sessionId);
// 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));
@@ -765,7 +800,8 @@ 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();
+ acceptSessionMutation(projectId, sessionId);
+ sessionProjectRef.current.delete(sessionId);
if (projectId == null) return; // standalone session: no tree row to drop
setSessions((prev) => {
const state = prev[projectId];
@@ -781,6 +817,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const upsertProjectToTop = useCallback(
(project: WorkbenchProject) => {
+ acceptProjectsMutation();
// create_project is find-or-create by path: opening a tracked folder returns
// the existing project, refreshed. Drop any stale copy, hoist to top, expand.
setProjects((prev) => (prev ? [project, ...prev.filter((p) => p.id !== project.id)] : [project]));
@@ -794,7 +831,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const state = sessionsRef.current[project.id];
if (!state || state.sessions === null || state.error) void fetchSessions(project.id);
},
- [fetchSessions],
+ [acceptProjectsMutation, fetchSessions],
);
const sessionsOf = useCallback((projectId: string) => sessions[projectId] ?? EMPTY_SESSIONS, [sessions]);
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 4b61e6e83..92d742b73 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -88,6 +88,7 @@ type FakeApi = {
listSessions?: (args: { projectId: string }) => Promise<unknown>;
getSession?: () => Promise<unknown>;
listInbox?: () => Promise<unknown>;
+ markSessionRead?: () => Promise<unknown>;
connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;
};
@@ -241,7 +242,12 @@ describe('Workbench session read ownership', () => {
});
await settle();
act(() => {
- handlers?.onSessionStatus?.({ session_id: session.id, agent_status: 'idle' });
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ title: 'Fresh title',
+ });
});
await act(async () => {
staleFirstPage.resolve({ sessions: [session], next_before_id: null });
@@ -352,6 +358,115 @@ describe('Workbench session read ownership', () => {
expect(tree?.sessionsOf(project.id).sessions).toEqual([{ ...trackedSession, agent_status: 'idle' }]);
});
+ it('retries a created-session reconcile invalidated before the row is cached', async () => {
+ const staleRead = deferred({ sessions: [], next_before_id: null });
+ const listSessions = vi.fn()
+ .mockReturnValueOnce(staleRead.promise)
+ .mockResolvedValueOnce({ sessions: [session], next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { [project.id]: { sessions: [], next_before_id: null } },
+ }),
+ 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(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'created',
+ });
+ });
+ await settle();
+ act(() => {
+ handlers?.onSessionStatus?.({ session_id: session.id, agent_status: 'idle' });
+ });
+ await act(async () => {
+ staleRead.resolve({ sessions: [], next_before_id: null });
+ await staleRead.promise;
+ });
+ await settle();
+
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ expect(tree?.sessionsOf(project.id).sessions).toEqual([session]);
+ });
+
+ it('retries an invalidated project pagination read', async () => {
+ const pageSession = { ...sessionB, scope_id: project.scope_id, project_id: project.id };
+ const stalePage = deferred({ sessions: [pageSession], next_before_id: null });
+ const listSessions = vi.fn()
+ .mockReturnValueOnce(stalePage.promise)
+ .mockResolvedValueOnce({ sessions: [pageSession], next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { [project.id]: { sessions: [session], next_before_id: 'cursor_a' } },
+ }),
+ 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?.loadMore(project.id);
+ });
+ await settle();
+ act(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ title: 'Fresh title',
+ });
+ });
+ await act(async () => {
+ stalePage.resolve({ sessions: [pageSession], next_before_id: null });
+ await stalePage.promise;
+ });
+ await settle();
+
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ expect(tree?.sessionsOf(project.id).sessions?.map((row) => row.id)).toEqual([session.id, pageSession.id]);
+ expect(tree?.sessionsOf(project.id).cursor).toBeNull();
+ });
+
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' };
@@ -504,6 +619,58 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBeNull();
});
+ it('does not let an older mark-read response restore unread after hide', async () => {
+ const staleMarkRead = deferred({ unread_by_session: { [session.id]: 2 } });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox: vi.fn().mockResolvedValue({
+ sessions: [inboxRow],
+ next_cursor: null,
+ unread_by_session: { [session.id]: 3 },
+ }),
+ markSessionRead: vi.fn().mockReturnValue(staleMarkRead.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?.markRead(session.id);
+ });
+ await settle();
+ act(() => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'background',
+ });
+ });
+ await act(async () => {
+ staleMarkRead.resolve({ unread_by_session: { [session.id]: 2 } });
+ await staleMarkRead.promise;
+ });
+ await settle();
+
+ expect(inbox?.inboxSessions).toEqual([]);
+ expect(inbox?.unreadBySession).toEqual({});
+ });
+
it('retries a resume reconcile invalidated by activity', async () => {
const staleReconcile = deferred({ sessions: [inboxRow], next_cursor: 'stale_cursor', unread_by_session: { [session.id]: 3 } });
const listInbox = vi.fn()
@@ -711,9 +878,9 @@ describe('Workbench session read ownership', () => {
expect(inbox?.nextCursor).toBe('cursor_before_restore');
});
- it('keeps a targeted restore when a newer broad feed read completes first', async () => {
+ 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: {} });
+ const broadRead = deferred({ sessions: [], next_cursor: 'cursor_after_refresh', unread_by_session: { [sessionB.id]: 5 } });
const listInbox = vi.fn()
.mockResolvedValueOnce({ sessions: [], next_cursor: 'cursor_before_restore', unread_by_session: {} })
.mockReturnValueOnce(targetedRead.promise)
@@ -752,7 +919,7 @@ describe('Workbench session read ownership', () => {
});
await settle();
await act(async () => {
- broadRead.resolve({ sessions: [], next_cursor: 'cursor_after_refresh', unread_by_session: {} });
+ broadRead.resolve({ sessions: [], next_cursor: 'cursor_after_refresh', unread_by_session: { [sessionB.id]: 5 } });
await broadRead.promise;
});
await act(async () => {
@@ -762,6 +929,127 @@ describe('Workbench session read ownership', () => {
await settle();
expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);
+ expect(inbox?.unreadBySession).toEqual({ [sessionB.id]: 5 });
+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');
+ });
+
+ it('does not let an older targeted row replace a newer broad row that completed first', async () => {
+ const refreshedRow = {
+ ...inboxRow,
+ title: 'Fresh from broad feed',
+ last_activity_at: '2026-08-11T01:00:00Z',
+ };
+ const targetedRead = deferred({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });
+ const broadRead = deferred({
+ sessions: [refreshedRow],
+ next_cursor: 'cursor_after_refresh',
+ unread_by_session: { [session.id]: 4 },
+ });
+ 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 () => {
+ broadRead.resolve({
+ sessions: [refreshedRow],
+ next_cursor: 'cursor_after_refresh',
+ unread_by_session: { [session.id]: 4 },
+ });
+ await broadRead.promise;
+ });
+ await act(async () => {
+ targetedRead.resolve({ sessions: [inboxRow], next_cursor: null, unread_by_session: { [session.id]: 3 } });
+ await targetedRead.promise;
+ });
+ await settle();
+
+ expect(inbox?.inboxSessions).toEqual([refreshedRow]);
+ expect(inbox?.unreadBySession).toEqual({ [session.id]: 4 });
+ expect(inbox?.nextCursor).toBe('cursor_after_refresh');
+ });
+
+ it('lets a later broad feed replace a targeted session snapshot', async () => {
+ const refreshedRow = {
+ ...inboxRow,
+ title: 'Fresh from broad feed',
+ last_activity_at: '2026-08-11T01:00:00Z',
+ };
+ 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 } })
+ .mockResolvedValueOnce({ sessions: [refreshedRow], next_cursor: 'cursor_after_refresh', unread_by_session: { [session.id]: 4 } });
+ 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();
+ act(() => {
+ void inbox?.refresh();
+ });
+ await settle();
+
+ expect(inbox?.inboxSessions).toEqual([refreshedRow]);
+ expect(inbox?.unreadBySession).toEqual({ [session.id]: 4 });
expect(inbox?.nextCursor).toBe('cursor_after_refresh');
});
@@ -817,7 +1105,7 @@ describe('Workbench session read ownership', () => {
await settle();
expect(inbox?.inboxSessions.map((row) => row.session_id)).toEqual([session.id]);
- expect(inbox?.unreadBySession).toEqual({ [session.id]: 3 });
+ expect(inbox?.unreadBySession).toEqual({});
expect(inbox?.nextCursor).toBe('cursor_after_refresh');
});
});
diff --git a/ui/src/lib/workbenchSessionReadOwnership.test.ts b/ui/src/lib/workbenchSessionReadOwnership.test.ts
index 7caf5bc6d..6cbfa0104 100644
--- a/ui/src/lib/workbenchSessionReadOwnership.test.ts
+++ b/ui/src/lib/workbenchSessionReadOwnership.test.ts
@@ -16,7 +16,6 @@ describe('Workbench session read ownership', () => {
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);
@@ -36,6 +35,39 @@ describe('Workbench session read ownership', () => {
expect(ownership.isCurrent(projectB)).toBe(true);
});
+ it('tracks mutation versions independently for independent resources', () => {
+ const ownership = createWorkbenchSessionReadOwnership();
+ const projectA = ownership.beginRead('project:a');
+ const projectB = ownership.beginRead('project:b');
+
+ ownership.acceptMutation('project:a');
+
+ expect(ownership.isCurrent(projectA)).toBe(false);
+ expect(ownership.isCurrent(projectB)).toBe(true);
+ });
+
+ it('lets a later broad read claim a dynamic row resource', () => {
+ const ownership = createWorkbenchSessionReadOwnership();
+ const targeted = ownership.beginRead('session:a');
+ const broad = ownership.beginRead('feed');
+
+ ownership.claimRead(broad, 'session:a');
+
+ expect(ownership.isCurrent(targeted, 'session:a')).toBe(false);
+ expect(ownership.isCurrent(broad, 'session:a')).toBe(true);
+ });
+
+ it('does not let an older broad read claim over a later targeted read', () => {
+ const ownership = createWorkbenchSessionReadOwnership();
+ const broad = ownership.beginRead('feed');
+ const targeted = ownership.beginRead('session:a');
+
+ ownership.claimRead(broad, 'session:a');
+
+ expect(ownership.isCurrent(broad, 'session:a')).toBe(false);
+ expect(ownership.isCurrent(targeted, 'session:a')).toBe(true);
+ });
+
it('lets a broad read and a resource read order their overlapping payload', () => {
const ownership = createWorkbenchSessionReadOwnership();
const bootstrap = ownership.beginRead('projects-bootstrap');
diff --git a/ui/src/lib/workbenchSessionReadOwnership.ts b/ui/src/lib/workbenchSessionReadOwnership.ts
index 7ae158432..1a0cec206 100644
--- a/ui/src/lib/workbenchSessionReadOwnership.ts
+++ b/ui/src/lib/workbenchSessionReadOwnership.ts
@@ -2,9 +2,9 @@
* Orders asynchronous Workbench reads against accepted session mutations.
*
* 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.
+ * version and has not been superseded for any resource it owns.
+ * Resource-scoped mutation versions and read generations keep independent
+ * projects and data slices from invalidating one another.
*/
export type WorkbenchSessionReadStamp = {
epoch: number;
@@ -14,20 +14,28 @@ export type WorkbenchSessionReadStamp = {
export type WorkbenchSessionReadOwnership = {
beginRead: (resources?: string | readonly string[]) => WorkbenchSessionReadStamp;
- acceptMutation: () => number;
+ claimRead: (
+ stamp: WorkbenchSessionReadStamp,
+ resources: string | readonly string[],
+ ) => void;
+ acceptMutation: (resources?: string | readonly string[]) => number;
+ isMutationCurrent: (
+ stamp: WorkbenchSessionReadStamp,
+ resources?: string | readonly string[],
+ ) => boolean;
isCurrent: (
stamp: WorkbenchSessionReadStamp,
resources?: string | readonly string[],
) => boolean;
isLatestRead: (stamp: WorkbenchSessionReadStamp) => boolean;
latestGeneration: (resource: string) => number | undefined;
- epoch: () => number;
};
export function createWorkbenchSessionReadOwnership(): WorkbenchSessionReadOwnership {
let mutationEpoch = 0;
let latestGeneration = 0;
const latestByResource = new Map<string, number>();
+ const mutationByResource = new Map<string, number>();
return {
beginRead: (resources = 'default') => {
@@ -35,16 +43,39 @@ export function createWorkbenchSessionReadOwnership(): WorkbenchSessionReadOwner
if (resourceList.length === 0) throw new Error('A session read must own at least one resource');
latestGeneration += 1;
for (const resource of resourceList) latestByResource.set(resource, latestGeneration);
- return { epoch: mutationEpoch, generation: latestGeneration, resources: resourceList };
+ return {
+ epoch: mutationEpoch,
+ generation: latestGeneration,
+ resources: resourceList,
+ };
+ },
+ claimRead: (stamp, resources) => {
+ const resourceList = typeof resources === 'string' ? [resources] : resources;
+ if (resourceList.length === 0) throw new Error('A session read must claim at least one resource');
+ for (const resource of resourceList) {
+ const latest = latestByResource.get(resource) ?? 0;
+ if (stamp.generation > latest) latestByResource.set(resource, stamp.generation);
+ }
},
- acceptMutation: () => {
+ acceptMutation: (resources = 'default') => {
+ const resourceList = typeof resources === 'string' ? [resources] : resources;
+ if (resourceList.length === 0) throw new Error('A session mutation must own at least one resource');
mutationEpoch += 1;
+ for (const resource of resourceList) mutationByResource.set(resource, mutationEpoch);
return mutationEpoch;
},
+ isMutationCurrent: (stamp, resources = stamp.resources) => {
+ const resourceList = typeof resources === 'string' ? [resources] : resources;
+ return resourceList.every(
+ (resource) => (mutationByResource.get(resource) ?? 0) <= stamp.epoch,
+ );
+ },
isCurrent: (stamp, resources = stamp.resources) => {
const resourceList = typeof resources === 'string' ? [resources] : resources;
return (
- stamp.epoch === mutationEpoch &&
+ resourceList.every(
+ (resource) => (mutationByResource.get(resource) ?? 0) <= stamp.epoch,
+ ) &&
resourceList.every((resource) => {
const latest = latestByResource.get(resource);
return latest === undefined || latest <= stamp.generation;
@@ -54,6 +85,5 @@ export function createWorkbenchSessionReadOwnership(): WorkbenchSessionReadOwner
isLatestRead: (stamp) =>
stamp.resources.every((resource) => latestByResource.get(resource) === stamp.generation),
latestGeneration: (resource) => latestByResource.get(resource),
- epoch: () => mutationEpoch,
};
}