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.

perf(ui): bootstrap shell data on first consumer, not on mount (#1532)

Call White41c2ec792111
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index ec995d7ab..9c5720719 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -7,11 +7,12 @@ import type { ReactNode } from 'react';
import { AppShell } from './AppShell';
-vi.hoisted(() => {
+const viewport = vi.hoisted(() => {
+ const state = { isDesktop: false };
vi.stubGlobal(
'matchMedia',
vi.fn().mockImplementation((query: string) => ({
- matches: false,
+ matches: state.isDesktop,
media: query,
onchange: null,
addListener: vi.fn(),
@@ -21,6 +22,7 @@ vi.hoisted(() => {
dispatchEvent: vi.fn(),
})),
);
+ return state;
});
const api = vi.hoisted(() => ({
@@ -80,7 +82,9 @@ vi.mock('./apps/WindowLayer', () => ({ WindowLayer: () => <div data-testid="wind
vi.mock('./workbench/NewSessionSheet', () => ({
NewSessionSheet: () => null,
}));
-vi.mock('./workbench/WorkbenchSidebar', () => ({ WorkbenchSidebar: () => <div /> }));
+vi.mock('./workbench/WorkbenchSidebar', () => ({
+ WorkbenchSidebar: () => <div data-testid="workbench-sidebar" />,
+}));
vi.mock('./workbench/search/SearchPalette', () => ({ SearchPalette: () => null }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -94,6 +98,7 @@ vi.mock('react-i18next', () => ({
}));
beforeEach(() => {
+ viewport.isDesktop = false;
instanceAuth.instanceKind = null;
instanceAuth.capabilities.can_manage_instance = true;
instanceAuth.capabilities.can_chat = true;
@@ -129,6 +134,35 @@ describe('AppShell setup recovery', () => {
});
});
+describe('AppShell workbench sidebar', () => {
+ // The sidebar's own container is hidden below md by CSS, which does not
+ // unmount it. Its consumers fetch the inbox feed and the project tree on
+ // mount, so a demand gate keyed on mounting is only true if mounting means
+ // visible — the mount site owns that, not the sidebar's callers.
+ it.each([
+ [false, 0],
+ [true, 1],
+ ])('mounts only where it is visible (desktop: %s)', async (isDesktop, expectedMounts) => {
+ viewport.isDesktop = isDesktop;
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench-surface" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByTestId('workbench-surface')).toBeTruthy();
+ expect(screen.queryAllByTestId('workbench-sidebar')).toHaveLength(expectedMounts);
+ // The surrounding chrome is unaffected: only the data-reading member of the
+ // desktop-only container is gated, not the container.
+ expect(screen.getAllByText('appShell.title').length).toBeGreaterThan(0);
+ });
+});
+
describe('AppShell Permissions navigation', () => {
it.each([
['personal', 2],
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 44d566368..c774822f4 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -32,6 +32,7 @@ import { InstallHint } from './InstallHint';
import logoImg from '../assets/logo.png';
import { getEnabledPlatforms, platformSupportsChannels } from '../lib/platforms';
import { useViewportHeightVar } from '../lib/useViewportHeightVar';
+import { useIsDesktop } from '../lib/useIsDesktop';
import {
adminLandingPath,
isAdvancedSettingsPath,
@@ -257,7 +258,13 @@ const ConfigRecoveryNotice: React.FC<{ config: ConfigRecoveryProjection | null }
export const AppShell: React.FC = () => {
const { t } = useTranslation();
const { status } = useStatus();
- const { totalUnread } = useWorkbenchInbox();
+ // Badge only — the shell is mounted on every route and renders no feed.
+ const { totalUnread } = useWorkbenchInbox({ feed: false });
+ // The sidebar's own <aside> is hidden below md by CSS, which hides it without
+ // unmounting it — so its inbox-feed and project-tree consumers would still
+ // fetch on a phone. A demand gate keyed on mounting is only honest if mounting
+ // implies visible, so the mount site has to carry the viewport too.
+ const isDesktop = useIsDesktop();
const {
capabilities,
remote,
@@ -612,7 +619,9 @@ export const AppShell: React.FC = () => {
</nav>
</div>
)}
- {shellMode === 'workbench' && <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />}
+ {shellMode === 'workbench' && isDesktop && (
+ <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />
+ )}
</div>
{/* Bottom (design.pen NbPMq): row 1 = [Apps | Settings] two equal
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index 6e8139a54..beeedee4e 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -74,9 +74,17 @@ export const WindowLayer: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { order, pins } = useDock();
- const { pages } = useShowPageInventory();
const { windows, close, focus, minimize, openApp, restore, setParams, setTitle, confirmClose } =
useWindowManager();
+ // The layer is mounted shell-wide so a window survives navigation, but it only
+ // reads the inventory once a window exists. Every other reader (Dock,
+ // MobileDockDrawer, app search) already gates on its own open state, so an
+ // empty layer is the last thing making /api/show-pages a per-document load.
+ // Both reads self-heal when the inventory lands: `icon_version` comes from a
+ // reactive snapshot, and the ⌘-number title falls back to the dock pin's
+ // `title_snapshot` exactly as it already does while the first fetch is in
+ // flight.
+ const { pages } = useShowPageInventory(windows.length > 0);
// Any window open and NOT minimized — drives the layer's aria-hidden AND the
// beforeunload guard (§7.1g).
const anyShown = shouldGuardUnload(windows);
diff --git a/ui/src/components/apps/windowLayerInventory.test.tsx b/ui/src/components/apps/windowLayerInventory.test.tsx
new file mode 100644
index 000000000..8f3e470e4
--- /dev/null
+++ b/ui/src/components/apps/windowLayerInventory.test.tsx
@@ -0,0 +1,126 @@
+/** @vitest-environment jsdom */
+
+// The window layer is mounted shell-wide so a window survives navigation, which
+// made it the last unconditional reader of /api/show-pages: every document paid
+// for the inventory, including the ones that never open a window. Same class as
+// the demand-driven providers in ``src/context/shellBootstrapDemand.test.tsx`` —
+// what the document renders decides what is fetched.
+
+import { createInstance } from 'i18next';
+import { cleanup, render } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import type { ShowPage } from '../../lib/showPagesStore';
+import type { WindowInstance } from '../../context/WindowManagerContext';
+import { WindowLayer } from './WindowLayer';
+
+const windowsRef = { current: [] as WindowInstance[] };
+
+vi.mock('../../context/DockContext', () => ({
+ useDock: () => ({ order: [], pins: [] }),
+}));
+
+vi.mock('../../context/WindowManagerContext', () => ({
+ useWindowManager: () => ({
+ windows: windowsRef.current,
+ close: vi.fn(),
+ focus: vi.fn(),
+ minimize: vi.fn(),
+ openApp: vi.fn(),
+ restore: vi.fn(),
+ setParams: vi.fn(),
+ setTitle: vi.fn(),
+ confirmClose: () => true,
+ }),
+}));
+
+vi.mock('../../context/StandaloneAppTabContext', () => ({
+ useStandaloneAppTab: () => false,
+}));
+
+// Every window body is an app of its own (iframe, terminal, editor); the layer's
+// own fetch decision is what is under test, so the frame is stubbed out.
+vi.mock('./AppWindow', () => ({
+ AppWindow: () => <div data-testid="app-window" />,
+}));
+vi.mock('../workbench/ShowPageAnnotationHost', () => ({
+ ShowPageAnnotationHost: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
+const api = vi.hoisted(() => ({
+ getShowPages: vi.fn(),
+ getSessionResult: vi.fn(),
+ connectWorkbenchEvents: vi.fn(),
+}));
+
+vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const appWindow = (): WindowInstance =>
+ ({
+ id: 'win_1',
+ appId: 'files',
+ title: 'Files',
+ x: 0,
+ y: 0,
+ w: 800,
+ h: 600,
+ z: 1,
+ minimized: false,
+ maximized: false,
+ params: {},
+ }) as unknown as WindowInstance;
+
+const renderLayer = () =>
+ render(
+ <I18nextProvider i18n={i18n}>
+ <WindowLayer />
+ </I18nextProvider>,
+ );
+
+describe('WindowLayer show-pages inventory', () => {
+ beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ windowsRef.current = [];
+ api.getShowPages.mockReset();
+ api.getShowPages.mockResolvedValue([] as ShowPage[]);
+ api.getSessionResult.mockReset();
+ api.getSessionResult.mockResolvedValue({ status: null, session: null });
+ api.connectWorkbenchEvents.mockReset();
+ api.connectWorkbenchEvents.mockReturnValue(vi.fn());
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('leaves the inventory unfetched while no window is open', async () => {
+ renderLayer();
+ await vi.waitFor(() => expect(api.connectWorkbenchEvents).toHaveBeenCalled());
+
+ expect(api.getShowPages).not.toHaveBeenCalled();
+ });
+
+ it('reads the inventory once a window exists', async () => {
+ windowsRef.current = [appWindow()];
+ renderLayer();
+
+ await vi.waitFor(() => expect(api.getShowPages).toHaveBeenCalledTimes(1));
+ });
+});
diff --git a/ui/src/components/useShowPages.ts b/ui/src/components/useShowPages.ts
index 2f7038713..f94c0f6ff 100644
--- a/ui/src/components/useShowPages.ts
+++ b/ui/src/components/useShowPages.ts
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
import {
+ commitShowPagesInventoryStore,
getShowPagesInventoryStore,
type ShowPage,
} from '../lib/showPagesStore';
@@ -23,6 +24,14 @@ export function useShowPageInventory(enabled = true) {
store.getSnapshot,
);
+ // The tree has now committed to this identity's store, which is what makes the
+ // one a previous identity handed out unreachable and its retained
+ // subscription a leak. Runs whether or not this consumer activates: holding
+ // the store is what supersedes, reading it is a separate question.
+ useEffect(() => {
+ commitShowPagesInventoryStore(api);
+ }, [api]);
+
useEffect(() => {
if (enabled) return store.activate();
}, [enabled, store]);
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 0555ed79f..40f89c815 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -241,7 +241,10 @@ export const ChatPage: React.FC = () => {
canManageShowPageAsInstance,
showPageAccess,
);
- const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox();
+ // This session's own unread state, plus the mark-read write. Neither needs the
+ // feed page, so this component never asks for one; whether the document loads
+ // one at all is decided by the sidebar, which mounts on desktop only.
+ const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox({ feed: false });
const { focusedId: foregroundAppWindowId, focusCanvas } = useWindowManager();
const isDesktop = useIsDesktop();
const pageActive = usePageActive();
diff --git a/ui/src/components/workbench/NewProjectDialog.tsx b/ui/src/components/workbench/NewProjectDialog.tsx
index 2c9010514..d435bb507 100644
--- a/ui/src/components/workbench/NewProjectDialog.tsx
+++ b/ui/src/components/workbench/NewProjectDialog.tsx
@@ -2,8 +2,8 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Folder, FolderOpen, Loader2, X } from 'lucide-react';
-import { useApi } from '../../context/ApiContext';
import type { WorkbenchProject } from '../../context/ApiContext';
+import { useWorkbenchProjectsActions } from '../../context/WorkbenchProjectsContext';
import { DirectoryBrowser } from '../ui/directory-browser';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
@@ -11,6 +11,11 @@ import { errorMessage } from '@/lib/errorMessage';
interface NewProjectDialogProps {
onClose: () => void;
+ /** The project is already in the shared tree by the time this fires — the
+ * provider owns that commit so it can fence it against an authorization
+ * change landing mid-request. Use it only for what is local to the caller
+ * (close the modal, select the row). It does NOT fire when the commit was
+ * refused, because there is then no row for the caller to point at. */
onCreated: (project: WorkbenchProject) => void;
}
@@ -20,7 +25,7 @@ interface NewProjectDialogProps {
// basename — keep the input empty to accept that default.
export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onCreated }) => {
const { t } = useTranslation();
- const api = useApi();
+ const { createProject } = useWorkbenchProjectsActions();
const [phase, setPhase] = useState<'pick' | 'confirm'>('pick');
const [folderPath, setFolderPath] = useState<string>('');
const [displayName, setDisplayName] = useState<string>('');
@@ -46,10 +51,16 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({ onClose, onC
setSubmitting(true);
setError(null);
try {
- const project = await api.createProject({
+ const project = await createProject({
folder_path: folderPath,
display_name: displayName.trim() || undefined,
});
+ // null = created, but an authorization change landed while we waited, so
+ // this document no longer holds a tree to place it in. Just close.
+ if (!project) {
+ onClose();
+ return;
+ }
onCreated(project);
} catch (err) {
setError(errorMessage(err) ?? String(err));
diff --git a/ui/src/components/workbench/ProjectSettingsDialog.tsx b/ui/src/components/workbench/ProjectSettingsDialog.tsx
index f876bbaae..6036f8483 100644
--- a/ui/src/components/workbench/ProjectSettingsDialog.tsx
+++ b/ui/src/components/workbench/ProjectSettingsDialog.tsx
@@ -6,7 +6,7 @@ import { FileText } from 'lucide-react';
import { useApi } from '../../context/ApiContext';
import type { ProjectDefaultAgent, VibeAgentBrief, WorkbenchProject } from '../../context/ApiContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
-import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { useWorkbenchProjectsActions } from '../../context/WorkbenchProjectsContext';
import { Button } from '../ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { InfoHint } from '../ui/info-hint';
@@ -29,7 +29,7 @@ export const ProjectSettingsDialog: React.FC<{
}> = ({ project, open, onClose }) => {
const { t } = useTranslation();
const api = useApi();
- const { setProjectDefaultAgent } = useWorkbenchProjectsTree();
+ const { setProjectDefaultAgent } = useWorkbenchProjectsActions();
const { capabilities } = useInstanceAuthorization();
const canManageProjects = capabilities.can_manage_projects;
const canEditAgentsMd = canManageProjects;
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index 33cb7e503..9396ae9bf 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -20,7 +20,7 @@ import type { LucideIcon } from 'lucide-react';
import clsx from 'clsx';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
-import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { useWorkbenchProjectsActions, useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
@@ -85,7 +85,7 @@ const MobileProjectRow: React.FC<{
const canManageProjects = capabilities.can_manage_projects;
const canArchive = canManageProjects;
const canEditAgentsMd = canManageProjects;
- const { renameProject, archiveProject, createSessionForProject } = useWorkbenchProjectsTree();
+ const { renameProject, archiveProject, createSessionForProject } = useWorkbenchProjectsActions();
const [menuOpen, setMenuOpen] = useState(false);
// Guards against a double-tap creating two sessions before navigation unmounts.
const creatingSessionRef = useRef(false);
@@ -264,7 +264,7 @@ const MobileSessionRow: React.FC<{
onOpen: () => void;
}> = ({ projectId, session, unread, canChat, canManageMetadata, onOpen }) => {
const { t } = useTranslation();
- const { renameSession } = useWorkbenchProjectsTree();
+ const { renameSession } = useWorkbenchProjectsActions();
const navigate = useNavigate();
const [menuOpen, setMenuOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
@@ -382,7 +382,8 @@ export const ProjectsPage: React.FC = () => {
capabilities,
} = useInstanceAuthorization();
const canCreateProject = canCreateLocalProject(capabilities);
- const { unreadBySession } = useWorkbenchInbox();
+ // Per-session dots only; the feed list itself lives in the sidebar / Inbox.
+ const { unreadBySession } = useWorkbenchInbox({ feed: false });
const {
projects,
projectsError,
@@ -392,7 +393,6 @@ export const ProjectsPage: React.FC = () => {
toggleExpanded,
loadMore,
reloadSessions,
- upsertProjectToTop,
} = useWorkbenchProjectsTree();
const [showNewProject, setShowNewProject] = useState(false);
const [visibleSessionCounts, setVisibleSessionCounts] = useState<Record<string, number>>({});
@@ -516,10 +516,7 @@ export const ProjectsPage: React.FC = () => {
{showNewProject && canCreateProject && (
<NewProjectDialog
onClose={() => setShowNewProject(false)}
- onCreated={(project) => {
- setShowNewProject(false);
- upsertProjectToTop(project);
- }}
+ onCreated={() => setShowNewProject(false)}
/>
)}
</div>
diff --git a/ui/src/components/workbench/WorkbenchSidebar.sessionRow.test.tsx b/ui/src/components/workbench/WorkbenchSidebar.sessionRow.test.tsx
index 2a55bb4e2..dc94417fd 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.sessionRow.test.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.sessionRow.test.tsx
@@ -22,7 +22,7 @@ vi.mock('../../context/ApiContext', async (importOriginal) => ({
}));
vi.mock('../../context/WorkbenchProjectsContext', async (importOriginal) => ({
...(await importOriginal<typeof import('../../context/WorkbenchProjectsContext')>()),
- useWorkbenchProjectsTree: () => ({
+ useWorkbenchProjectsActions: () => ({
renameSession: vi.fn(),
forkSession: vi.fn(),
setSessionPinned: vi.fn(),
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index d72611eb2..b2ab0b533 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -27,7 +27,7 @@ import clsx from 'clsx';
import type { LucideIcon } from 'lucide-react';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
-import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { useWorkbenchProjectsActions, useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
@@ -217,7 +217,7 @@ export const SessionRow: React.FC<{
}> = ({ projectId, session, unread, canChat, canManageMetadata }) => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { renameSession } = useWorkbenchProjectsTree();
+ const { renameSession } = useWorkbenchProjectsActions();
const location = useLocation();
const active = location.pathname === `/chat/${session.id}`;
const [menuOpen, setMenuOpen] = useState(false);
@@ -685,7 +685,6 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
createSessionForProject,
renameProject,
archiveProject,
- upsertProjectToTop,
} = useWorkbenchProjectsTree();
const [popoverOpen, setPopoverOpen] = useState(false);
const closeTimer = useRef<number | null>(null);
@@ -940,10 +939,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
{showNewProject && canCreateProject && (
<NewProjectDialog
onClose={() => setShowNewProject(false)}
- onCreated={(project) => {
- setShowNewProject(false);
- upsertProjectToTop(project);
- }}
+ onCreated={() => setShowNewProject(false)}
/>
)}
</div>
diff --git a/ui/src/components/workbench/useSessionActions.test.tsx b/ui/src/components/workbench/useSessionActions.test.tsx
index de8b626f8..1ea8d8cb2 100644
--- a/ui/src/components/workbench/useSessionActions.test.tsx
+++ b/ui/src/components/workbench/useSessionActions.test.tsx
@@ -26,7 +26,7 @@ vi.mock('../../context/ApiContext', () => ({
vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mocks.showToast }) }));
vi.mock('../../context/ComposerBridgeContext', () => ({ useComposerInsertTarget: () => null }));
vi.mock('../../context/WorkbenchProjectsContext', () => ({
- useWorkbenchProjectsTree: () => ({
+ useWorkbenchProjectsActions: () => ({
forkSession: mocks.forkSession,
setSessionPinned: mocks.setSessionPinned,
archiveSession: mocks.archiveSession,
diff --git a/ui/src/components/workbench/useSessionActions.tsx b/ui/src/components/workbench/useSessionActions.tsx
index 97b9c997d..6e613e6d7 100644
--- a/ui/src/components/workbench/useSessionActions.tsx
+++ b/ui/src/components/workbench/useSessionActions.tsx
@@ -6,7 +6,7 @@ import { Archive, EyeOff, GitFork, Hash, Pencil, Pin, PinOff } from 'lucide-reac
import { useApi } from '../../context/ApiContext';
import type { WorkbenchSession } from '../../context/ApiContext';
import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';
-import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { useWorkbenchProjectsActions } from '../../context/WorkbenchProjectsContext';
import { useToast } from '../../context/ToastContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';
@@ -78,7 +78,7 @@ export const useSessionActions = ({
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const { forkSession, setSessionPinned, archiveSession } = useWorkbenchProjectsTree();
+ const { forkSession, setSessionPinned, archiveSession } = useWorkbenchProjectsActions();
// Owned HERE, not passed in per surface: the unsaved-changes blocker is mounted on
// the ROUTER, so any surface that navigates after a write — sidebar, mobile row,
// chat header — is prompted only once the fork already exists, and cancelling
diff --git a/ui/src/context/WorkbenchInboxContext.ts b/ui/src/context/WorkbenchInboxContext.ts
index 2d9b4d088..cfcd2e11a 100644
--- a/ui/src/context/WorkbenchInboxContext.ts
+++ b/ui/src/context/WorkbenchInboxContext.ts
@@ -1,4 +1,4 @@
-import { createContext, useContext } from 'react';
+import { createContext, useContext, useEffect } from 'react';
import type { InboxSession } from './ApiContext';
@@ -25,12 +25,31 @@ export interface InboxState {
refresh: () => Promise<void>;
loadMore: () => Promise<void>;
markRead: (sessionId: string, untilMessageId?: string) => Promise<void>;
+ /** Refcounted activation for the FEED (see ``useConsumerActivation``). The
+ * unread map is unconditional — it badges the favicon and the app icon on
+ * every route — but ``inboxSessions`` is only rendered by the sidebar and the
+ * Inbox page, so the paged read waits for one of them. Consumers get this for
+ * free from ``useWorkbenchInbox``. */
+ activateFeed: () => () => void;
}
export const WorkbenchInboxContext = createContext<InboxState | undefined>(undefined);
-export const useWorkbenchInbox = (): InboxState => {
+/** Read the shared Inbox state.
+ *
+ * Pass ``feed: false`` when the component only reads the unread map (badges,
+ * a session's own dot) and never renders ``inboxSessions``. That is what keeps
+ * the 30-row page off routes that show no feed; declaring what you read, rather
+ * than which route you are on, is what keeps the rule true for a route added
+ * later. */
+export const useWorkbenchInbox = (options?: { feed?: boolean }): InboxState => {
const ctx = useContext(WorkbenchInboxContext);
+ const feed = options?.feed ?? true;
+ const activateFeed = ctx?.activateFeed;
+ useEffect(() => {
+ if (!feed || !activateFeed) return;
+ return activateFeed();
+ }, [activateFeed, feed]);
if (ctx === undefined) {
throw new Error('useWorkbenchInbox must be used inside <WorkbenchInboxProvider>');
}
diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsx
index 28288d215..4ea7d0434 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 { useConsumerActivation } from '../lib/useConsumerActivation';
import { onPageReactivated } from '../lib/pageActivity';
import {
createWorkbenchSessionReadOwnership,
@@ -57,6 +58,12 @@ type TargetedInboxSnapshot = {
* depend on context functions don't re-fire on every parent render. */
export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) => {
const api = useApi();
+ // Two different appetites behind one provider: the unread map badges the
+ // favicon and the app icon on every route, while the paged feed is rendered
+ // only by the sidebar and the Inbox page. Splitting them is what lets an admin
+ // route keep its badge without paying for 30 rows of feed it never shows.
+ const { active: feedActive, isActive: isFeedActive, activate: activateFeed } =
+ useConsumerActivation();
const [inboxSessions, setInboxSessions] = useState<InboxSession[]>([]);
const [unreadBySession, setUnreadBySession] = useState<Record<string, number>>({});
// Becomes true the first time the server hands us an authoritative whole-account
@@ -111,6 +118,37 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// windowed feed. Keep their latest committed values so a later whole-feed
// replacement cannot erase a restored card merely because the row sorts
// outside the page; a later broad omission revalidates them by exact id.
+ // Counts-only reads own no feed state, so they never join the feed read
+ // intents above. They still serialize against themselves: a resume fires
+ // visibilitychange, focus and online together, and one map is enough.
+ const unreadReadInFlightRef = useRef(false);
+ const unreadReadPendingRef = useRef(false);
+ const unreadReadRunnerRef = useRef<() => void>(() => {});
+ // Every read currently in flight that would commit a WHOLE account map: the two
+ // broad feed reads and the counts-only read. Membership alone proves nothing —
+ // what makes one a payer is that it is still current for ``inbox-unread``, which
+ // is exactly what raising the debt takes away. Kept as stamps rather than a
+ // counter for that reason.
+ const wholeUnreadReadsInFlightRef = useRef<Set<WorkbenchSessionReadStamp>>(new Set());
+ // ``flushFeedReadIntent`` is the one place a scheduled payer can disappear, and it
+ // is defined above the settle it then has to re-run. Same runner-ref shape as the
+ // reads below.
+ const settleWholeUnreadRef = useRef<() => void>(() => {});
+ // "No whole-account map currently describes this account." The unread map is the
+ // one thing here with no demand gate at all — every route badges it — so this is
+ // the debt that keeps it live independently of which read was supposed to pay it:
+ // true until one arrives, true again whenever something voids the scope the current
+ // map described or moves counts it cannot describe (see ``oweWholeUnread`` for the
+ // edges). Every read that can deliver a whole map is allowed to fail, be
+ // invalidated, or be dropped by the demand gate; what must not happen is the debt
+ // being forgotten with it. Distinct from ``unreadLoaded``, which is one-way and
+ // answers a different question (may this document touch the OS badge at all).
+ //
+ // A ref and not state, because it is read where it is spent: ``settleWholeUnread``
+ // runs from the producers as well as from an effect, so it cannot wait a render to
+ // learn whether anything is still owed — and once the producers pay it themselves,
+ // a re-render on the same fact would be a second owner of that payment.
+ const wholeUnreadOwedRef = useRef(true);
const targetedSnapshotsRef = useRef<Map<string, TargetedInboxSnapshot>>(new Map());
const targetedReadInFlightRef = useRef<Set<string>>(new Set());
const targetedReadPendingRef = useRef<Set<string>>(new Set());
@@ -118,6 +156,32 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
const flushFeedReadIntent = useCallback(() => {
if (broadReadInFlightRef.current || cursorReadsInFlightRef.current > 0) return;
+ // Every intent queued here reads the FEED, so the demand gate applies to it
+ // exactly as it applies to a first read: with no feed consumer left, a
+ // 30-row page would be fetched for a document that renders a badge. Dropping
+ // it loses nothing, because activation re-reads unconditionally (page one
+ // when nothing was loaded, reconcile otherwise) — the same argument that
+ // lets ``onConnected`` return early. It matters most right after
+ // ``discardAuthorizedFeed``: invalidating the read in flight is itself what
+ // queues a replacement refresh, which would repopulate the rows that branch
+ // just dropped, off-route and in parallel with the counts-only read.
+ //
+ // That argument covers the FEED half of the dropped read. The whole-account
+ // unread map it was also carrying is a different matter, because no route is
+ // exempt from badging that — the debt is ``wholeUnreadOwedRef``, and the demand
+ // edge that caused this drop is what makes the counts effect pay it.
+ if (!isFeedActive()) {
+ const droppedWholeMapRead = refreshPendingRef.current || reconcilePendingRef.current;
+ refreshPendingRef.current = false;
+ reconcilePendingRef.current = false;
+ loadMorePendingRef.current = false;
+ // A queued refresh/reconcile was ALSO the scheduled payment for the unread
+ // debt, and dropping it here is the moment that payment stops existing.
+ // Re-settling is what turns the drop into the counts-only read the debt is
+ // still owed, instead of a silently unpaid one.
+ if (droppedWholeMapRead) settleWholeUnreadRef.current();
+ return;
+ }
if (refreshPendingRef.current) {
refreshPendingRef.current = false;
// A replacement refresh owns the same top-of-feed recovery as a pending
@@ -135,7 +199,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
loadMorePendingRef.current = false;
loadMoreRunnerRef.current();
}
- }, []);
+ }, [isFeedActive]);
const queueRefreshIntent = useCallback(() => {
refreshPendingRef.current = true;
@@ -165,14 +229,67 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
readOwnershipRef.current.acceptMutation(['inbox-unread', 'inbox-unread-all']);
}, []);
+ // One owner of "pay the debt", because recording it does not schedule anything.
+ // Raising a debt that is already outstanding is not an edge at all, and the fence
+ // only re-arms a read that is still in flight — so a counts read that FAILED and
+ // settled leaves a debt no later signal could pay, and the badge would keep
+ // revoked counts until some unrelated focus or reconnect. Every producer of the
+ // debt calls this instead, and it declines whenever a payment is already on the
+ // way:
+ // * a feed consumer exists, so the feed read carries the whole map;
+ // * a counts read is in flight, and the fence its producer just applied is what
+ // makes that read re-read rather than commit pre-change counts.
+ // Deferred by a microtask, because a scope restore raises the debt once per
+ // restored session: paying on the first of them would have the rest fence the
+ // read it just started, turning one burst into a read per event. Same reason
+ // ``queueRefreshIntent`` and its siblings defer.
+ const settleWholeUnread = useCallback(() => {
+ queueMicrotask(() => {
+ if (!wholeUnreadOwedRef.current) return;
+ // Being in flight is not being a payer. The call that raises the debt fences
+ // the reads that started before it, so those will refuse their own unread map
+ // — declining on their mere presence is how a debt ends up with nobody left
+ // to pay it. Only a read still current for the map can settle this one.
+ for (const read of wholeUnreadReadsInFlightRef.current) {
+ if (readOwnershipRef.current.isMutationCurrent(read, 'inbox-unread')) return;
+ }
+ // A queued read is a payment already scheduled: it has not been issued yet, so
+ // it will be stamped after this debt and will commit its map.
+ if (refreshPendingRef.current || reconcilePendingRef.current || unreadReadPendingRef.current) return;
+ // With a feed consumer the whole map rides on the feed read this queues, so the
+ // badge is paid without a second request. If demand disappears before it
+ // flushes, the gate drops it and re-enters here with no consumer — the branch
+ // below. Without one, the counts-only read is the only thing that can pay.
+ if (isFeedActive()) {
+ queueReconcileIntent();
+ return;
+ }
+ unreadReadRunnerRef.current();
+ });
+ }, [isFeedActive, queueReconcileIntent]);
+
+ // The mirror of ``applyUnreadMap``: one home for "no whole map describes this
+ // account any more". Recording the debt alone is not enough, because a whole-map
+ // read that left the server BEFORE this moment cannot describe the counts it is
+ // about to commit — and committing it would PAY the debt without satisfying it.
+ // So the fence, the debt, and its payment have one owner.
+ const oweWholeUnread = useCallback(() => {
+ acceptUnreadMutation();
+ wholeUnreadOwedRef.current = true;
+ settleWholeUnread();
+ }, [acceptUnreadMutation, settleWholeUnread]);
+
// 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
// write (refresh / reconcile / unread.changed) goes through here; targeted
// reads and mark-read responses merge one session without claiming completeness.
- // stable identity, so it never churns the memoized context value.
+ // stable identity, so it never churns the memoized context value. Paying the
+ // ``wholeUnreadOwedRef`` debt belongs here for the same reason: this is the only
+ // place a whole map is adopted, so no producer has to remember to clear it.
const applyUnreadMap = useCallback((map: Record<string, number>) => {
setUnreadBySession(map);
setUnreadLoaded(true);
+ wholeUnreadOwedRef.current = false;
}, []);
const applyWholeUnreadRead = useCallback((
@@ -240,6 +357,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
refreshPendingRef.current = false;
reconcilePendingRef.current = false;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-refresh']);
+ wholeUnreadReadsInFlightRef.current.add(read);
const loadingGeneration = ++refreshLoadingGenerationRef.current;
const retryAfterInvalidation = () => {
const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');
@@ -279,6 +397,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
if (!retryAfterInvalidation()) console.error('[inbox] refresh failed', err);
} finally {
if (refreshLoadingGenerationRef.current === loadingGeneration) setLoading(false);
+ wholeUnreadReadsInFlightRef.current.delete(read);
broadReadInFlightRef.current = false;
flushFeedReadIntent();
}
@@ -374,6 +493,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
broadReadInFlightRef.current = true;
reconcilePendingRef.current = false;
const read = readOwnershipRef.current.beginRead(['inbox-feed', 'inbox-unread', 'inbox-feed-reconcile']);
+ wholeUnreadReadsInFlightRef.current.add(read);
const retryAfterInvalidation = () => {
const invalidatedByMutation = !readOwnershipRef.current.isMutationCurrent(read, 'inbox-feed');
const supersededByCursorRead =
@@ -440,11 +560,98 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
} catch (err) {
if (!retryAfterInvalidation()) console.error('[inbox] reconcile failed', err);
} finally {
+ wholeUnreadReadsInFlightRef.current.delete(read);
broadReadInFlightRef.current = false;
flushFeedReadIntent();
}
}, [acceptFeedRows, api, applyNextCursor, applyWholeUnreadRead, flushFeedReadIntent, mergeTargetedSnapshots, queueReconcileIntent]);
+ // Counts-only read for routes that render no feed. Same endpoint and the same
+ // pagination-independent unread map as refresh()/reconcile(), with the row
+ // window collapsed to the smallest the API accepts — it claims only the unread
+ // resource, discards the row it is handed, and never touches the feed or the
+ // cursor, so activating the feed later still starts from a real first page.
+ // (The server clamps `limit` to at least 1; a true zero-row read would need an
+ // API change, deliberately out of scope here.)
+ const refreshUnread = useCallback(async function refreshUnread() {
+ if (unreadReadInFlightRef.current) {
+ unreadReadPendingRef.current = true;
+ return;
+ }
+ unreadReadInFlightRef.current = true;
+ // A mid-flight mutation invalidates this response, and unlike the feed path
+ // nothing else is queued to replace it: the ``inbox.session.updated`` handler
+ // merges one session's count and never claims an authoritative whole map, so
+ // silently discarding would leave every other session's count — and the
+ // favicon/PWA badge — missing until some later focus or reconnect. Re-read,
+ // exactly as ``refresh`` does. A newer read of the same resource is a
+ // different case: it owns the map now and will apply its own, so stepping
+ // aside is correct and keeps this terminating.
+ const staleReadNeedsReread = (read: WorkbenchSessionReadStamp) =>
+ !readOwnershipRef.current.isMutationCurrent(read, 'inbox-unread') &&
+ (readOwnershipRef.current.latestGeneration('inbox-unread') ?? 0) <= read.generation;
+ try {
+ do {
+ unreadReadPendingRef.current = false;
+ const read = readOwnershipRef.current.beginRead(['inbox-unread']);
+ wholeUnreadReadsInFlightRef.current.add(read);
+ try {
+ const result = await api.listInbox({
+ platform: 'avibe',
+ limit: 1,
+ cache: false,
+ handleError: false,
+ });
+ if (readOwnershipRef.current.isCurrent(read, 'inbox-unread')) {
+ applyWholeUnreadRead(read, result.unread_by_session ?? {});
+ } else if (staleReadNeedsReread(read)) {
+ unreadReadPendingRef.current = true;
+ }
+ } catch (err) {
+ if (staleReadNeedsReread(read)) unreadReadPendingRef.current = true;
+ else console.error('[inbox] refreshUnread failed', err);
+ } finally {
+ wholeUnreadReadsInFlightRef.current.delete(read);
+ }
+ } while (unreadReadPendingRef.current);
+ } finally {
+ unreadReadInFlightRef.current = false;
+ }
+ }, [api, applyWholeUnreadRead]);
+
+ // Same rule as the projects tree: a reconnect is revalidation and may wait for
+ // a consumer, but an authorization change is invalidation and cannot. The feed's
+ // resumption path merges rather than replaces — ``reconcile`` deliberately keeps
+ // rows the response omitted — so rows loaded before the change would survive the
+ // trip back, and a failed reconcile would keep them indefinitely. Drop them and
+ // reset ``initialFetched`` so the next feed consumer takes the authoritative
+ // page-one path instead.
+ //
+ // The unread map is deliberately NOT dropped here: the counts read that follows
+ // replaces it whole, and blanking it first would clear a badge the push service
+ // worker may legitimately own while this document was never authoritative (the
+ // ``unreadLoaded`` invariant). A count is a number for a session id the user
+ // already had; a feed row is its title and preview.
+ const discardAuthorizedFeed = useCallback(() => {
+ const cachedSessionIds = new Set([
+ ...inboxSessionsRef.current.map((row) => row.session_id),
+ ...targetedSnapshotsRef.current.keys(),
+ ...targetedReadInFlightRef.current,
+ ]);
+ // Fence the reads already in flight: a response that left the server before
+ // the change must not repopulate what we are dropping.
+ readOwnershipRef.current.acceptMutation([
+ 'inbox-feed',
+ ...[...cachedSessionIds].map((sessionId) => `inbox-session:${sessionId}`),
+ ]);
+ initialFetched.current = false;
+ inboxSessionsRef.current = [];
+ targetedSnapshotsRef.current.clear();
+ targetedReadPendingRef.current.clear();
+ setInboxSessions([]);
+ applyNextCursor(null);
+ }, [applyNextCursor]);
+
// 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
@@ -461,6 +668,25 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
try {
while (true) {
targetedReadPendingRef.current.delete(sessionId);
+ // The demand gate belongs HERE rather than at the events that call this:
+ // every trigger of a request-backed revalidation would otherwise have to
+ // remember it, and this provider has more triggers than guards. With no
+ // feed consumer the card this upserts is not rendered and the next
+ // activation reconciles the window anyway — the same argument that lets a
+ // queued feed intent be dropped. What is NOT droppable is the other half
+ // of this read: it owns this session's unread count, which every route
+ // badges. So declining hands the whole-account map the debt instead of
+ // dropping the obligation with the request, and a burst of foreground
+ // restores costs one coalesced counts read instead of one targeted read
+ // each.
+ //
+ // Asked per REQUEST rather than on the way in, because this is a loop:
+ // an entry gate answers for the pass that queued a retry, and the retry
+ // runs later — after the navigation that removed the card it upserts.
+ if (!isFeedActive()) {
+ oweWholeUnread();
+ return;
+ }
const sessionResource = `inbox-session:${sessionId}`;
const unreadResource = `inbox-unread-session:${sessionId}`;
const read = readOwnershipRef.current.beginRead([sessionResource, unreadResource]);
@@ -504,29 +730,92 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
targetedReadInFlightRef.current.delete(sessionId);
}
},
- [api, applySessionUnread],
+ [api, applySessionUnread, isFeedActive, oweWholeUnread],
);
+ settleWholeUnreadRef.current = settleWholeUnread;
+ unreadReadRunnerRef.current = () => void refreshUnread();
refreshRunnerRef.current = () => void refresh();
reconcileRunnerRef.current = () => void reconcile();
loadMoreRunnerRef.current = () => void loadMore();
reconcileSessionRef.current = (sessionId) => void reconcileSession(sessionId);
- useEffect(() => {
- // First mount loads page one; every later rerun reconciles the loaded window
- // instead when an ``api`` identity change rebuilds the value — so
- // a non-resume rerun never collapses a multi-page feed back to page one. The
- // broker fans events out live with no replay (sse_broker.py ``/api/events``),
- // so anything missed while the socket was down must be re-read; plain HTTP,
- // independent of whether the SSE stream itself comes back up.
+ // The feed's first read waits for a consumer that renders it. ``feedActive`` is
+ // state, so it flips one render after the activation and this effect is what
+ // runs the read — both for a workbench document's first paint and for a later
+ // /admin → /chat navigation, which finds ``initialFetched`` still false and
+ // loads page one exactly as a direct load would.
+ //
+ // First read loads page one; every later rerun reconciles the loaded window
+ // instead when an ``api`` identity change rebuilds the value — so a non-resume
+ // rerun never collapses a multi-page feed back to page one. The broker fans
+ // events out live with no replay (sse_broker.py ``/api/events``), so anything
+ // missed while the socket was down must be re-read; plain HTTP, independent of
+ // whether the SSE stream itself comes back up.
+ //
+ // One owner for that choice, because activation is not its only caller: an
+ // authorization change re-reads for an active consumer too, and it drops the
+ // window first — so the answer comes from the cache as it is at that moment
+ // rather than from which event asked.
+ const readFeedForActiveConsumer = useCallback(() => {
if (!initialFetched.current) {
initialFetched.current = true;
void refresh();
- } else {
- void reconcile();
+ return;
}
+ void reconcile();
+ }, [reconcile, refresh]);
+
+ useEffect(() => {
+ if (!feedActive) return;
+ readFeedForActiveConsumer();
+ }, [feedActive, readFeedForActiveConsumer]);
+
+ // The badges are shell-wide, so the unread map is loaded on every route — but on
+ // a route with no feed consumer, only the map. The decision itself belongs to
+ // ``settleWholeUnread``, which every producer of the debt also calls; this effect
+ // adds the two moments no producer of the debt can observe. Mount is one: it is
+ // the first time the map is owed. A change in DEMAND is the other, and it is not
+ // the same event as the debt being owed — it changes WHICH read can pay, so a
+ // debt whose payer failed is re-tested by the route the user moved to rather than
+ // by a retry. Nothing else would notice it, because the refcount function has
+ // stable identity by design. ``isFeedActive()`` is then read synchronously inside
+ // the settle rather than from ``feedActive`` here, because consumers activate in
+ // their own effects, which React runs before this one.
+ //
+ // The debt itself is deliberately NOT a dependency, and that is the round-8 rule
+ // rather than an optimization: re-running on the level would re-enter on the very
+ // thing a failed pass leaves behind, so it would never terminate. A demand edge is
+ // an event, so it re-enters a bounded number of times — once per navigation.
+ useEffect(() => {
+ settleWholeUnread();
+ }, [feedActive, settleWholeUnread]);
+
+ useEffect(() => {
const disconnect = api.connectWorkbenchEvents({
onAuthorizationChanged: () => {
- void refresh();
+ // A permission change invalidates whatever is loaded. Demand decides only
+ // whether a replacement READ follows — never whether the voided cache is
+ // dropped, which is why the drop cannot sit in the no-consumer branch.
+ // With a consumer this used to merely re-read, and ``reconcile``
+ // deliberately KEEPS the rows a response omits, so revoked titles and
+ // previews survived a slow read and outlived a failed one entirely. Worse,
+ // the replacement is queued when a read is already in flight, and the
+ // demand gate in ``flushFeedReadIntent`` drops it if the last consumer
+ // leaves first — leaving the pre-change response free to repopulate rows
+ // the change had voided, with nothing left to correct them.
+ //
+ // No committed whole map describes the new scope, so owe one rather than
+ // naming the read that pays it: with a feed consumer the read below
+ // carries it, without one the counts effect runs on this very state
+ // change, and if that read is later dropped or fails the debt is still
+ // outstanding when the last consumer leaves. Owing also fences the
+ // pre-change counts read that may be in flight — which is the whole reason
+ // that fence lives with the debt and not at this call site.
+ oweWholeUnread();
+ discardAuthorizedFeed();
+ // Dropping the window is also what makes this the authoritative page-one
+ // read rather than a reconcile onto rows that are no longer there.
+ if (isFeedActive()) readFeedForActiveConsumer();
},
onInboxSessionUpdated: (row) => {
targetedSnapshotsRef.current.delete(row.session_id);
@@ -541,10 +830,16 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
});
},
onInboxUnreadChanged: (data) => {
- acceptUnreadMutation();
if (data?.unread_by_session) {
+ // The event IS the newest whole map: fence the reads in flight, then adopt it.
+ acceptUnreadMutation();
applyUnreadMap(data.unread_by_session);
+ return;
}
+ // The counts changed and the event did not say how, so nothing here can
+ // adopt a map: owe one, which invalidates the reads that started before the
+ // change and would otherwise settle the debt with pre-change counts.
+ oweWholeUnread();
},
onSessionActivity: (data) => {
// Contract A6: react to visibility/scope changes carried on the event.
@@ -579,7 +874,17 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
},
});
return disconnect;
- }, [acceptSessionMutation, acceptUnreadMutation, api, refresh, reconcile, reconcileSession, applyUnreadMap]);
+ }, [
+ acceptSessionMutation,
+ acceptUnreadMutation,
+ api,
+ applyUnreadMap,
+ discardAuthorizedFeed,
+ isFeedActive,
+ oweWholeUnread,
+ readFeedForActiveConsumer,
+ reconcileSession,
+ ]);
// 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;
@@ -589,7 +894,9 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
// never gate data freshness.
useEffect(() => {
const resync = () => {
- if (document.visibilityState === 'visible') void reconcile();
+ if (document.visibilityState !== 'visible') return;
+ if (isFeedActive()) void reconcile();
+ else void refreshUnread();
};
const stopReactivation = onPageReactivated(resync);
window.addEventListener('online', resync);
@@ -597,7 +904,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
stopReactivation();
window.removeEventListener('online', resync);
};
- }, [reconcile]);
+ }, [isFeedActive, reconcile, refreshUnread]);
const totalUnread = useMemo(
() => Object.values(unreadBySession).reduce((sum, n) => sum + (n || 0), 0),
@@ -649,8 +956,10 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>
refresh,
loadMore,
markRead,
+ activateFeed,
}),
[
+ activateFeed,
inboxSessions,
unreadBySession,
totalUnread,
diff --git a/ui/src/context/WorkbenchProjectsContext.ts b/ui/src/context/WorkbenchProjectsContext.ts
index c3a3a6c6a..3bf241e9b 100644
--- a/ui/src/context/WorkbenchProjectsContext.ts
+++ b/ui/src/context/WorkbenchProjectsContext.ts
@@ -1,4 +1,4 @@
-import { createContext, useContext } from 'react';
+import { createContext, useContext, useEffect } from 'react';
import type { ProjectDefaultAgent, WorkbenchProject, WorkbenchSession, WorkbenchSessionCreate } from './ApiContext';
@@ -19,20 +19,21 @@ export interface ProjectSessionsState {
error: boolean;
}
-export interface WorkbenchProjectsTree {
- projects: WorkbenchProject[] | null;
- projectsError: string | null;
- refreshProjects: () => Promise<void>;
-
- sessionsOf: (projectId: string) => ProjectSessionsState;
- expanded: ReadonlySet<string>;
- isExpanded: (projectId: string) => boolean;
- toggleExpanded: (projectId: string) => void;
- loadMore: (projectId: string) => void;
- /** Re-fetch the first page (mobile retry button / programmatic reload). */
- reloadSessions: (projectId: string) => void;
-
- creatingSession: (projectId: string) => boolean;
+/** The WRITE half of the tree, split out so that reading it and writing it are
+ * different requests to make of this provider.
+ *
+ * A surface can be permanently mounted and still only ever write: `ChatPage`
+ * mounts `useSessionActions` on every `/chat/:id` for fork / pin / archive, and
+ * a session row mounts it for its rename menu. None of them render a project,
+ * so activating the bootstrap for them would fetch a tree nobody displays —
+ * the same waste this PR removed from `/admin`, arriving through a consumer
+ * instead of through a route.
+ *
+ * Typing the halves apart is what makes that structural rather than a boolean
+ * each new call site has to remember: a writer reaches for
+ * ``useWorkbenchProjectsActions`` and *cannot* read `projects`, and a reader
+ * cannot compile against it and must take the activating hook below. */
+export interface WorkbenchProjectsActions {
/** Creates a session under a project (optimistic prepend + expand) and RETURNS it;
* the caller navigates (this provider is mounted outside the router). null on failure.
* `overrides` lets the create surfaces pin an agent/backend; omit for the server default. */
@@ -62,14 +63,68 @@ export interface WorkbenchProjectsTree {
* tasks/watches/runs) then drops the row from the tree. Throws on failure.
* `null` project = standalone session (nothing to drop from the tree). */
archiveSession: (projectId: string | null, sessionId: string) => Promise<void>;
- /** After NewProjectDialog: dedup-by-id, hoist to top, expand, fetch sessions if not loaded. */
- upsertProjectToTop: (project: WorkbenchProject) => void;
+ /** Create a project AND place it in the shared tree (dedup-by-id, hoist to top,
+ * expand, fetch sessions), then return it so the caller can navigate/select.
+ *
+ * The commit lives here rather than at the call site because a write is the
+ * other way a row reaches the cache: the request is stamped before it leaves
+ * and the response is refused if an authorization change landed meanwhile, so
+ * a create begun under the old gate cannot re-seed a tree that was dropped.
+ * `null` means exactly that — the project exists on the server, this document
+ * may no longer be allowed to show it, and the next activation will decide. */
+ createProject: (payload: { folder_path: string; display_name?: string }) => Promise<WorkbenchProject | null>;
+}
+
+export interface WorkbenchProjectsTree extends WorkbenchProjectsActions {
+ projects: WorkbenchProject[] | null;
+ projectsError: string | null;
+ refreshProjects: () => Promise<void>;
+ /** Refcounted activation (see ``useConsumerActivation``). The provider is
+ * mounted above the router, so it only bootstraps the tree while a consumer
+ * that renders it is mounted — an admin route mounts none. Consumers get
+ * this for free from ``useWorkbenchProjectsTree``. */
+ activate: () => () => void;
+
+ sessionsOf: (projectId: string) => ProjectSessionsState;
+ expanded: ReadonlySet<string>;
+ isExpanded: (projectId: string) => boolean;
+ toggleExpanded: (projectId: string) => void;
+ loadMore: (projectId: string) => void;
+ /** Re-fetch the first page (mobile retry button / programmatic reload). */
+ reloadSessions: (projectId: string) => void;
+
+ creatingSession: (projectId: string) => boolean;
}
export const WorkbenchProjectsContext = createContext<WorkbenchProjectsTree | null>(null);
-export function useWorkbenchProjectsTree(): WorkbenchProjectsTree {
+/** Read the shared projects/sessions tree.
+ *
+ * Reading it is what makes the provider fetch it: every consumer activates by
+ * default, so the tree loads for whoever renders it and for nobody else. Pass
+ * ``active: false`` from a surface that is permanently mounted but only reads
+ * the tree while open (``NewSessionSheet`` via ``useNewSession``) — otherwise
+ * its mere presence would re-eagerize the bootstrap on every route. */
+export function useWorkbenchProjectsTree(options?: { active?: boolean }): WorkbenchProjectsTree {
const ctx = useContext(WorkbenchProjectsContext);
+ const active = options?.active ?? true;
+ const activate = ctx?.activate;
+ useEffect(() => {
+ if (!active || !activate) return;
+ return activate();
+ }, [active, activate]);
if (!ctx) throw new Error('useWorkbenchProjectsTree must be used within a WorkbenchProjectsProvider');
return ctx;
}
+
+/** Write to the shared tree without reading it.
+ *
+ * Deliberately does NOT activate: a rename, fork, pin or archive needs the
+ * cache patched if it happens to be loaded, and needs nothing fetched if it is
+ * not. The writes themselves are unconditional — they patch whatever is
+ * cached — so a document that only mutates issues no bootstrap at all. */
+export function useWorkbenchProjectsActions(): WorkbenchProjectsActions {
+ const ctx = useContext(WorkbenchProjectsContext);
+ if (!ctx) throw new Error('useWorkbenchProjectsActions must be used within a WorkbenchProjectsProvider');
+ return ctx;
+}
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 7603b58eb..2f6a4b299 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 { useConsumerActivation } from '@/lib/useConsumerActivation';
import {
createWorkbenchSessionReadOwnership,
type WorkbenchSessionReadStamp,
@@ -104,6 +105,10 @@ const REORDER_ACTIVITY_EVENTS = new Set(['created', 'user_message', 'show_event'
// WorkbenchInboxContext (both consumers read it directly).
export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const api = useApi();
+ // The tree is workbench-only data behind an app-level provider. Nothing under
+ // /admin renders a project, so nothing there should pay for the bootstrap —
+ // neither on load nor on an SSE reconnect.
+ const { active, isActive, activate } = useConsumerActivation();
const [projects, setProjects] = useState<WorkbenchProject[] | null>(null);
const [projectsError, setProjectsError] = useState<string | null>(null);
const [expanded, setExpanded] = useState<Set<string>>(new Set());
@@ -112,8 +117,11 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// Stale-closure-safe mirrors so the SSE (re)connect reconcile reads the current
// expanded set + loaded window without re-subscribing the stream on every change.
+ // ``projectsRef`` is deliberately NOT assigned on render like the two below:
+ // the reads consult it BEFORE issuing a request (see ``canIssueRead``), so it has
+ // to be true when a write returns rather than one render later. ``commitProjects``
+ // owns it together with the state; nothing else writes either half.
const projectsRef = useRef<WorkbenchProject[] | null>(null);
- projectsRef.current = projects;
const sessionsRef = useRef<Record<string, ProjectSessionsState>>({});
sessionsRef.current = sessions;
const expandedRef = useRef<Set<string>>(new Set());
@@ -133,24 +141,94 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// global resources. Serialize them and retain trailing intents so a later
// failed recovery cannot invalidate an earlier successful snapshot.
const bootstrapReadInFlightRef = useRef(false);
+ // Whether this document has ever loaded the tree, which is what decides the
+ // read a returning consumer takes (see the activation effect below).
+ const treeInitialFetched = useRef(false);
const fetchProjectsPendingRef = useRef<{ cache?: boolean } | null>(null);
const projectTreePendingRef = useRef(false);
const fetchProjectsRunnerRef = useRef<(options?: { cache?: boolean }) => void>(() => {});
const projectTreeRunnerRef = useRef<() => void>(() => {});
+ // The list and its mirror move together. The mirror used to be written on render,
+ // so after a write that added a project it stayed one render behind — which is why
+ // the reads below could only check "does the tree still hold this project?" AFTER
+ // their request and discard the response, and why asking beforehand would have
+ // dropped the window a just-created project needs. A read cannot decline a request
+ // on an answer it can only trust afterwards.
+ const commitProjects = useCallback(
+ (
+ next:
+ | WorkbenchProject[]
+ | null
+ | ((prev: WorkbenchProject[] | null) => WorkbenchProject[] | null),
+ ) => {
+ const resolved = typeof next === 'function' ? next(projectsRef.current) : next;
+ projectsRef.current = resolved;
+ setProjects(resolved);
+ },
+ [],
+ );
+
+ // ── One question, asked immediately before every read request ────────────────
+ // Every read this provider owns commits into a cache, and two things can make
+ // that commit impossible or pointless before the response even arrives. There may
+ // be no reader: a REVALIDATION is by definition a read the next activation would
+ // redo, so with nothing rendering the tree it is dropped (a POPULATING read
+ // produces what nothing else will and is exempt by declaration — see
+ // ``fetchSessions``). Or there may be no address: an authorization change, an
+ // archive, or a document that never loaded the tree leaves the project's window
+ // with nowhere to land, which every read already detects by discarding its own
+ // response.
+ //
+ // Both used to be answered somewhere other than the moment of asking — the first
+ // at the call sites that triggered a read, the second after the request had
+ // already been paid for — and each new trigger or each extra page then had to
+ // remember. So it is ONE predicate, evaluated per REQUEST rather than per read: a
+ // paging read asks it before every page, and a read that loops to retry asks it
+ // again before the retry.
+ const projectIsInTree = useCallback(
+ (projectId: string) => projectsRef.current?.some((project) => project.id === projectId) ?? false,
+ [],
+ );
+
+ const canIssueRead = useCallback(
+ (kind: 'revalidation' | 'population', projectId?: string) => {
+ if (kind === 'revalidation' && !isActive()) return false;
+ // A tree-wide read is its own address: the bootstrap is what CREATES the list
+ // a per-project read is checked against.
+ return projectId === undefined || projectIsInTree(projectId);
+ },
+ [isActive, projectIsInTree],
+ );
+
const flushBootstrapReadIntent = useCallback(() => {
if (bootstrapReadInFlightRef.current) return;
const pendingFetch = fetchProjectsPendingRef.current;
if (pendingFetch) {
fetchProjectsPendingRef.current = null;
- fetchProjectsRunnerRef.current(pendingFetch);
- return;
+ // ``fetchProjects`` is a POPULATING read and therefore exempt from the gate
+ // the reads apply to themselves (see ``fetchSessions``) — a window a write
+ // just expanded must not stay empty. A retry queued because a mutation
+ // invalidated the read in flight has no such window to fill once the last
+ // reader has detached, because activation re-reads unconditionally. So the
+ // one read that cannot state demand for itself states it here, where its
+ // retry is spent: keeping it would issue a bootstrap on a route that
+ // renders no project, and after an authorization change it would repopulate
+ // the tree ``discardAuthorizedTree`` just dropped, since invalidating the
+ // read in flight is itself what queues the retry.
+ if (canIssueRead('revalidation')) {
+ fetchProjectsRunnerRef.current(pendingFetch);
+ return;
+ }
}
if (projectTreePendingRef.current) {
+ // Ungated on purpose: this retry runs ``reconcileProjectTree``, a
+ // revalidation that declines itself while nothing reads the tree — and
+ // takes the window-preserving path if demand returned in the meantime.
projectTreePendingRef.current = false;
projectTreeRunnerRef.current();
}
- }, []);
+ }, [canIssueRead]);
const queueFetchProjectsIntent = useCallback((options?: { cache?: boolean }) => {
const pending = fetchProjectsPendingRef.current;
@@ -187,8 +265,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const applyProjectsSnapshot = useCallback((nextProjects: WorkbenchProject[]) => {
const accessibleIds = new Set(nextProjects.map((project) => project.id));
- projectsRef.current = nextProjects;
- setProjects(nextProjects);
+ commitProjects(nextProjects);
setSessions((prev) =>
Object.fromEntries(
Object.entries(prev).filter(([projectId]) => accessibleIds.has(projectId)),
@@ -199,19 +276,96 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
for (const projectId of [...pendingReconcileRef.current.keys()]) {
if (!accessibleIds.has(projectId)) pendingReconcileRef.current.delete(projectId);
}
- }, []);
+ }, [commitProjects]);
+
+ // A reconnect and an authorization change are not the same kind of signal. A
+ // reconnect says "you may have missed events", so deferring it while nothing
+ // reads the tree costs nothing — activation re-reads anyway. An authorization
+ // change says "what you already hold may no longer be authorized", and that
+ // cannot wait for a consumer: the cache outlives the gate, and every recovery
+ // path here deliberately PRESERVES what it has (``fetchProjects`` keeps the old
+ // list when the read fails), so a tree loaded before the change would render
+ // revoked rows on the way back. Dropping it returns this provider to exactly
+ // its pre-mount state — which is what every document that never read the tree
+ // already has — so the next activation bootstraps as a fresh load.
+ const discardAuthorizedTree = useCallback(() => {
+ // Fence the reads already in flight first: a response that left the server
+ // before the change must not repopulate the cache we are dropping.
+ const cachedProjectIds = new Set([
+ ...Object.keys(sessionsRef.current),
+ ...(projectsRef.current ?? []).map((project) => project.id),
+ ]);
+ readOwnershipRef.current.acceptMutation([
+ 'projects',
+ 'projects-bootstrap',
+ // A read is not the only producer of a cached row: a create commits one
+ // too, and it is in flight across exactly the same window. This resource
+ // is bumped ONLY here, so an unrelated rename or archive cannot refuse a
+ // create that authorization never touched.
+ 'projects-authorization',
+ ...[...cachedProjectIds].map((projectId) => `project:${projectId}`),
+ ...[...sessionProjectRef.current.keys()].map((sessionId) => `project-session:${sessionId}`),
+ ]);
+ commitProjects(null);
+ sessionsRef.current = {};
+ expandedRef.current = new Set();
+ sessionProjectRef.current.clear();
+ pendingReconcileRef.current.clear();
+ pendingCachedRowRefreshRef.current.clear();
+ // Pre-mount state includes "never loaded": the next activation must take the
+ // authoritative first-page bootstrap, not a reconcile onto a dropped window.
+ treeInitialFetched.current = false;
+ setProjectsError(null);
+ setSessions({});
+ setExpanded(new Set());
+ setCreating(new Set());
+ }, [commitProjects]);
+ // ── An outstanding window width is a DEBT, not a queued read ────────────────
+ // A foreground restore asks for one row more than is loaded, because the row it
+ // restored ranks just past the window. That minimum is the only record of it:
+ // every other path sizes a project's window from the rows already cached, so a
+ // read carrying the minimum that is then dropped — by the demand gate, by a
+ // navigation, by a mutation — takes the restored row with it, and no later
+ // revalidation puts it back.
+ //
+ // So the minimum is cleared by the commit that SATISFIES it, never by the attempt
+ // that carries it, and every read that sizes a window takes its target from
+ // ``windowTarget``. A refused request leaves the debt outstanding, which is what
+ // makes the next activation rebuild the width the restore asked for instead of
+ // the width the cache happens to hold.
+ //
+ // That makes it a LEVEL, so it is also the wrong thing for the reconcile loop to
+ // re-enter on: it says work is owed, never that another attempt could pay it, and
+ // a read that keeps failing would keep re-reading the same unpayable debt. The
+ // loop re-enters on the ordering fence instead — see the tail of ``reconcileSessions``.
const queueReconcile = useCallback((projectId: string, minCount = 0) => {
const pending = pendingReconcileRef.current.get(projectId) ?? 0;
pendingReconcileRef.current.set(projectId, Math.max(pending, minCount));
}, []);
- const takePendingReconcile = useCallback((projectId: string): number | null => {
- const pending = pendingReconcileRef.current.get(projectId);
- if (pending === undefined) return null;
- pendingReconcileRef.current.delete(projectId);
- return pending;
- }, []);
+ const windowTarget = useCallback(
+ (projectId: string) =>
+ Math.max(
+ sessionsRef.current[projectId]?.sessions?.length ?? 0,
+ pendingReconcileRef.current.get(projectId) ?? 0,
+ ),
+ [],
+ );
+
+ // Only a read that sized itself to the debt may settle it. ``fetchSessions``
+ // deliberately does not: it pages, it does not widen, so the reconcile it hands
+ // the project to afterwards is what pays.
+ const settlePendingReconcile = useCallback(
+ (projectId: string, committedCount: number, exhausted: boolean) => {
+ const pending = pendingReconcileRef.current.get(projectId);
+ if (pending === undefined) return;
+ // A wider minimum queued while this read was in flight is a different debt,
+ // and it outlives a window that was already sized for the smaller one.
+ if (exhausted || pending <= committedCount) pendingReconcileRef.current.delete(projectId);
+ },
+ [],
+ );
const acceptProjectRows = useCallback(
(read: WorkbenchSessionReadStamp, projectId: string, rows: WorkbenchSession[]) => {
@@ -293,10 +447,6 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}
}, [api, applyBootstrapSessions, applyProjectsSnapshot, flushBootstrapReadIntent, queueFetchProjectsIntent]);
- useEffect(() => {
- void fetchProjects();
- }, [fetchProjects]);
-
// (Re)connect reconcile: rebuild a project's ALREADY-paged-in window (not just
// page 1) so a transient SSE reconnect / controller restart doesn't truncate an
// expanded project back to the first page. Pages in chunks because the server
@@ -304,13 +454,31 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// windows >200 rows. Silent (no loading flag) so visible rows don't flicker.
const reconcileSessions = useCallback(
async (projectId: string, opts?: { minCount?: number }) => {
+ // The demand gate belongs to the READS, not to the events that trigger them.
+ // Guarding the paths this provider happened to know about — activation, a
+ // reconnect, a queued retry — left every other trigger of a request-backed
+ // revalidation to remember it, and there are more triggers than guards:
+ // session activity, a pin re-order, a status or turn-end row refresh, a
+ // trailing reconcile from a failed bootstrap. Stated at the read it becomes a
+ // property of the read instead, and a long-lived admin tab stops paging in a
+ // window it never shows. This read asks it per REQUEST (``canIssueRead``,
+ // below) rather than on the way in, because it is a LOOP: an entry gate that
+ // has already passed keeps rebuilding a multi-page window across the
+ // navigation that removed its last reader.
+ // Only the width is carried here. Whether the in-flight read must run again
+ // is the fence's answer, not this guard's: every trigger that can arrive
+ // mid-read accepts its mutation first (``acceptSessionMutation`` fences
+ // ``project:<id>``), so the read in flight is already stale and its own tail
+ // re-enters. A second record of that decision would be a second owner.
if (inFlightRef.current.has(projectId)) {
queueReconcile(projectId, opts?.minCount ?? 0);
return;
}
- let minCount = opts?.minCount ?? 0;
+ // Recorded before the first request, so a gate refusal on page one loses the
+ // width no more than a refusal between pages does.
+ if (opts?.minCount) queueReconcile(projectId, opts.minCount);
while (true) {
- const targetCount = Math.max(sessionsRef.current[projectId]?.sessions?.length ?? 0, minCount);
+ const targetCount = windowTarget(projectId);
if (targetCount === 0) return; // nothing loaded to reconcile
inFlightRef.current.add(projectId);
const read = readOwnershipRef.current.beginRead(`project:${projectId}`);
@@ -321,6 +489,9 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
let before: string | undefined;
let nextBeforeId: string | null = null;
do {
+ // Both loops pass through here: the next page of this window, and the
+ // fresh read the outer retry starts after a mutation refused this one.
+ if (!canIssueRead('revalidation', projectId)) return;
const res = await api.listSessions({
projectId,
status: 'active',
@@ -328,7 +499,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
beforeId: before,
cache: false,
});
- if (!projectsRef.current?.some((project) => project.id === projectId)) return;
+ if (!projectIsInTree(projectId)) return;
if (!readOwnershipRef.current.isCurrent(read, `project:${projectId}`)) {
stale = true;
break;
@@ -348,6 +519,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
...prev,
[projectId]: { sessions: acc, cursor: nextBeforeId, loading: false, loadingMore: false, error: false },
}));
+ settlePendingReconcile(projectId, acc.length, nextBeforeId === null);
}
} catch {
stale = !readOwnershipRef.current.isCurrent(read, `project:${projectId}`);
@@ -355,15 +527,25 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
} finally {
inFlightRef.current.delete(projectId);
}
- const pendingMinCount = takePendingReconcile(projectId);
- if (!stale && pendingMinCount === null) return;
- minCount = Math.max(targetCount, pendingMinCount ?? 0);
+ // Re-enter on evidence THIS pass produced, and nothing else: a mutation
+ // arrived that its response can no longer describe. A failed request is not
+ // that evidence — it says the attempt could not be made, so retrying it here
+ // is an unbounded retry of whatever just failed. The width it could not pay
+ // stays outstanding for the next activation or event to pay instead, which
+ // is exactly what a debt is for. Testing the debt here is what would spin.
+ if (!stale) return;
+ // Carry the width forward as the debt itself: ``setSessions`` has not
+ // rendered yet, so the next pass cannot read it back off the cache.
+ queueReconcile(projectId, targetCount);
}
},
- [acceptProjectRows, api, queueReconcile, takePendingReconcile],
+ [acceptProjectRows, api, canIssueRead, projectIsInTree, queueReconcile, settlePendingReconcile, windowTarget],
);
const reconcileProjectTree = useCallback(async function reconcileProjectTree() {
+ // Revalidation: dropped while nothing reads the tree (see ``reconcileSessions``).
+ // Also a loop — one bootstrap per window-size group — so the question is asked
+ // before each of them rather than once on the way in.
if (bootstrapReadInFlightRef.current) {
queueProjectTreeIntent();
return;
@@ -377,12 +559,15 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
const largeProjectIds: string[] = [];
for (const [projectId, state] of Object.entries(sessionsRef.current)) {
if (!state || state.sessions === null) continue;
- const loadedCount = state.sessions.length;
+ // The width to rebuild is the cached one, or the wider one an undelivered
+ // restore is still owed — this is where a debt the demand gate declined to
+ // pay while nothing read the tree is finally honoured.
+ const loadedCount = windowTarget(projectId);
if (inFlightRef.current.has(projectId)) {
queueReconcile(projectId, loadedCount);
continue;
}
- if (state.sessions.length > RECONNECT_SESSIONS_PAGE_SIZE) {
+ if (loadedCount > RECONNECT_SESSIONS_PAGE_SIZE) {
largeProjectIds.push(projectId);
continue;
}
@@ -395,12 +580,16 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
try {
const groups = Array.from(bootstrapGroups.entries());
if (groups.length === 0) {
+ if (!canIssueRead('revalidation')) return;
const result = await api.getWorkbenchProjectsBootstrap({ cache: false });
if (readOwnershipRef.current.isCurrent(read, 'projects')) applyProjectsSnapshot(result.projects);
} else {
let nextProjects: WorkbenchProject[] | null = null;
const pages: Record<string, { sessions: WorkbenchSession[]; next_before_id: string | null }> = {};
for (const [limit, projectIds] of groups) {
+ // A window-size group per request: leaving the workbench between two of
+ // them stops the rest, rather than finishing a rebuild nobody reads.
+ if (!canIssueRead('revalidation')) return;
const result = await api.getWorkbenchProjectsBootstrap({
projectIds,
status: 'active',
@@ -435,6 +624,9 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
),
);
applyBootstrapSessions(read, currentPages);
+ for (const [projectId, page] of Object.entries(currentPages)) {
+ settlePendingReconcile(projectId, page.sessions.length, page.next_before_id === null);
+ }
}
if (!readOwnershipRef.current.isCurrent(read, ['projects', 'projects-bootstrap'])) {
retryAfterInvalidation(read);
@@ -458,12 +650,46 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
bootstrapReadInFlightRef.current = false;
flushBootstrapReadIntent();
}
- }, [api, applyBootstrapSessions, applyProjectsSnapshot, flushBootstrapReadIntent, queueProjectTreeIntent, queueReconcile, reconcileSessions]);
+ }, [api, applyBootstrapSessions, applyProjectsSnapshot, canIssueRead, flushBootstrapReadIntent, queueProjectTreeIntent, queueReconcile, reconcileSessions, settlePendingReconcile, windowTarget]);
fetchProjectsRunnerRef.current = (options) => void fetchProjects(options);
projectTreeRunnerRef.current = () => void reconcileProjectTree();
+ // Bootstrap on the first active consumer rather than on mount, and revalidate
+ // whenever the tree goes from unread to read again — the same contract as
+ // ``ShowPagesInventoryStore.activate()``. WHICH read that is depends on what is
+ // already cached, because ``applyBootstrapSessions`` REPLACES each project's
+ // window with page one: a user who paged past the first eight sessions, stepped
+ // onto an admin route (detaching the last reader) and came back would watch
+ // those rows disappear and have to page through them again.
+ // ``reconcileProjectTree`` is the window-preserving read, and it is already the
+ // resumption path for the other signal that can arrive at a loaded tree — a
+ // reconnect — so a returning consumer takes it too. The first-page bootstrap is
+ // reserved for a tree that has none of this to preserve.
+ //
+ // One owner for that choice, because activation is not the only caller: an
+ // authorization change re-reads for an active consumer too, and it drops the
+ // window first — so "which read" has to be answered from the cache as it is at
+ // that moment, not from which event asked.
+ const readTreeForActiveConsumer = useCallback(() => {
+ if (!treeInitialFetched.current) {
+ treeInitialFetched.current = true;
+ void fetchProjects();
+ return;
+ }
+ void reconcileProjectTree();
+ }, [fetchProjects, reconcileProjectTree]);
+
+ useEffect(() => {
+ if (!active) return;
+ readTreeForActiveConsumer();
+ }, [active, readTreeForActiveConsumer]);
+
const refreshCachedSessionRow = useCallback(async function refreshCachedSessionRow(sessionId: string) {
+ // Revalidation: dropped while nothing reads the tree (see ``reconcileSessions``).
+ // The binding this refreshes gates an action on a row nobody is rendering, and
+ // the reconcile on the next activation re-reads the row anyway. Asked inside the
+ // loop, because another event landing mid-flight makes this read go round again.
if (cachedRowRefreshInFlightRef.current.has(sessionId)) {
pendingCachedRowRefreshRef.current.add(sessionId);
return;
@@ -476,6 +702,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
state.sessions?.some((session) => session.id === sessionId && !session.native_session_id),
)?.[0];
if (!projectId) return;
+ if (!canIssueRead('revalidation', projectId)) return;
const resource = `project-session:${sessionId}`;
const read = readOwnershipRef.current.beginRead(resource);
let stale = false;
@@ -500,14 +727,31 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
queueMicrotask(() => void refreshCachedSessionRow(sessionId));
}
}
- }, [api]);
+ }, [api, canIssueRead]);
// Load the first page (append=false) or the next page (append=true) of a
// project's sessions, with dedupe + per-project serialisation.
+ //
+ // Deliberately NOT demand-gated, unlike the reconciles above: this read POPULATES
+ // a window, so nothing else will produce what it fetches. Its readers reach it
+ // only while they render the tree (``toggleExpanded`` / ``loadMore`` /
+ // ``reloadSessions``), and its remaining callers are writes that just created a
+ // session or a project and expanded it — dropping those would leave the group the
+ // user opened rendering empty until they collapsed it, which is a worse trade than
+ // the one request. Same for ``fetchProjects``: the authoritative first load, whose
+ // only droppable path is the queued retry ``flushBootstrapReadIntent`` already gates.
+ //
+ // Exempt from the DEMAND half only. A populating read still has to have somewhere
+ // to land, and this one already knows the answer — the membership check below
+ // discards every response that arrives for a project the tree does not hold. A
+ // cold /chat/:id visit that forks a session reaches this with a tree it never
+ // loaded, so that request was paid for and thrown away; asking first is the same
+ // question, one round-trip earlier.
const fetchSessions = useCallback(
async function fetchSessions(projectId: string, opts?: { append?: boolean }) {
const append = opts?.append ?? false;
if (append && !sessionsRef.current[projectId]?.cursor) return; // nothing more to load
+ if (!canIssueRead('population', projectId)) return;
if (inFlightRef.current.has(projectId)) return; // serialise per project
inFlightRef.current.add(projectId);
setSessions((prev) => {
@@ -522,7 +766,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
let retryAfterInvalidation = false;
try {
const res = await api.listSessions({ projectId, status: 'active', limit: SESSIONS_PAGE_SIZE, beforeId });
- if (!projectsRef.current?.some((project) => project.id === projectId)) return;
+ if (!projectIsInTree(projectId)) return;
const currentRead = readOwnershipRef.current.isCurrent(read, `project:${projectId}`);
retryAfterInvalidation = !currentRead && readOwnershipRef.current.isLatestRead(read);
if (currentRead) acceptProjectRows(read, projectId, res.sessions);
@@ -565,18 +809,23 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
});
} finally {
inFlightRef.current.delete(projectId);
- const pendingMinCount = takePendingReconcile(projectId);
if (retryAfterInvalidation) {
- if (pendingMinCount !== null) queueReconcile(projectId, pendingMinCount);
queueMicrotask(() => {
+ // The retry a refused response queues is a REVALIDATION wearing this
+ // read's name: with no reader left there is no window to keep filled,
+ // because activation re-reads unconditionally. Same asymmetry, and the
+ // same place it is spent, as ``flushBootstrapReadIntent``.
+ if (!canIssueRead('revalidation', projectId)) return;
if (!inFlightRef.current.has(projectId)) void fetchSessions(projectId, opts);
});
- } else if (pendingMinCount !== null) {
- void reconcileSessions(projectId, { minCount: pendingMinCount });
+ } else if (pendingReconcileRef.current.has(projectId)) {
+ // The debt stays in the map either way; the reconcile reads it back
+ // through ``windowTarget`` instead of being handed a copy.
+ void reconcileSessions(projectId);
}
}
},
- [acceptProjectRows, api, queueReconcile, reconcileSessions, takePendingReconcile],
+ [acceptProjectRows, api, canIssueRead, projectIsInTree, reconcileSessions],
);
// Keep the tree live: patch a row's status dot / title from SSE, and refetch
@@ -585,11 +834,27 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
// broadcast to, so listSessions is the authoritative source on reconnect).
useEffect(() => {
const disconnect = api.connectWorkbenchEvents({
+ // A reconnect only has a tree to recover when one was being read; while no
+ // consumer reads it, activation is what fetches a fresh one. That is the
+ // read's own rule now (``reconcileSessions``), so this handler — like every
+ // other trigger below — states the intent and lets the read decide.
onConnected: () => {
void reconcileProjectTree();
},
+ // An authorization change is invalidation rather than revalidation, and the
+ // two answer different questions. Demand decides whether a replacement READ
+ // is worth issuing; it never decides whether the cache the change voided is
+ // dropped. Putting the drop in the no-consumer branch reads as "nothing is
+ // watching, so let it go" when the actual reason is that these rows may no
+ // longer be authorized — so with a consumer the tree merely revalidated, and
+ // ``fetchProjects`` deliberately KEEPS the old list when a read fails.
+ // Revoked projects would stay on screen for as long as the replacement took,
+ // and indefinitely if it never landed. Drop at the edge, then re-read only
+ // for a consumer — which, the window having gone with the cache, is the
+ // authoritative first load rather than a reconcile of nothing.
onAuthorizationChanged: () => {
- void reconcileProjectTree();
+ discardAuthorizedTree();
+ if (isActive()) readTreeForActiveConsumer();
},
onSessionActivity: (data) => {
const projectId =
@@ -667,7 +932,10 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
}, [
acceptSessionMutation,
api,
+ discardAuthorizedTree,
+ isActive,
projectIdForSession,
+ readTreeForActiveConsumer,
reconcileProjectTree,
reconcileSessions,
refreshCachedSessionRow,
@@ -744,12 +1012,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
try {
const updated = await api.updateProject(projectId, { display_name: name });
acceptProjectsMutation();
- setProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
+ commitProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
} catch (err) {
console.error('[workbench] rename project failed', err);
}
},
- [acceptProjectsMutation, api],
+ [acceptProjectsMutation, api, commitProjects],
);
const forkSession = useCallback(
@@ -807,9 +1075,9 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
reasoning_effort: route.reasoning_effort,
});
acceptProjectsMutation();
- setProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
+ commitProjects((prev) => (prev ? prev.map((p) => (p.id === projectId ? updated : p)) : prev));
},
- [acceptProjectsMutation, api],
+ [acceptProjectsMutation, api, commitProjects],
);
const archiveProject = useCallback(
@@ -818,7 +1086,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
await api.archiveProject(projectId);
acceptProjectsMutation();
acceptSessionMutation(projectId);
- setProjects((prev) => (prev ? prev.filter((p) => p.id !== projectId) : prev));
+ commitProjects((prev) => (prev ? prev.filter((p) => p.id !== projectId) : prev));
setExpanded((prev) => {
if (!prev.has(projectId)) return prev;
const next = new Set(prev);
@@ -829,7 +1097,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
console.error('[workbench] archive project failed', err);
}
},
- [acceptProjectsMutation, acceptSessionMutation, api],
+ [acceptProjectsMutation, acceptSessionMutation, api, commitProjects],
);
const renameSession = useCallback(
@@ -894,7 +1162,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
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]));
+ commitProjects((prev) => (prev ? [project, ...prev.filter((p) => p.id !== project.id)] : [project]));
setExpanded((prev) => {
const next = new Set(prev);
next.add(project.id);
@@ -905,7 +1173,30 @@ 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);
},
- [acceptProjectsMutation, fetchSessions],
+ [acceptProjectsMutation, commitProjects, fetchSessions],
+ );
+
+ // ── A write is the OTHER producer of a cached row ───────────────────────────
+ // ``discardAuthorizedTree`` fences the reads in flight, because a read is how
+ // rows normally arrive. But a create carries a row too, over the same await,
+ // and it was issued under the gate that just changed — so leaving the commit
+ // at the call site put the one path that can SEED a dropped tree outside the
+ // fence: the response lands, `prev` is null, and `[project]` re-creates the
+ // cache from an authorization the document no longer has.
+ //
+ // Owning the request here is what makes the stamp unforgeable by a caller: the
+ // epoch is taken before the request leaves and spent before the commit, and no
+ // call site can hold a row without one. `null` is not a failure — the project
+ // was created — it means this document must not paint it.
+ const createProject = useCallback(
+ async (payload: { folder_path: string; display_name?: string }): Promise<WorkbenchProject | null> => {
+ const write = readOwnershipRef.current.beginRead('projects-authorization');
+ const project = await api.createProject(payload);
+ if (!readOwnershipRef.current.isMutationCurrent(write, 'projects-authorization')) return null;
+ upsertProjectToTop(project);
+ return project;
+ },
+ [api, upsertProjectToTop],
);
const sessionsOf = useCallback((projectId: string) => sessions[projectId] ?? EMPTY_SESSIONS, [sessions]);
@@ -919,6 +1210,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
projects,
projectsError,
refreshProjects: fetchProjects,
+ activate,
sessionsOf,
expanded,
isExpanded,
@@ -934,12 +1226,13 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
renameSession,
setSessionPinned,
archiveSession,
- upsertProjectToTop,
+ createProject,
}),
[
projects,
projectsError,
fetchProjects,
+ activate,
sessionsOf,
expanded,
isExpanded,
@@ -955,7 +1248,7 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
renameSession,
setSessionPinned,
archiveSession,
- upsertProjectToTop,
+ createProject,
],
);
diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
index 4cba755fd..1f4f56919 100644
--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx
@@ -292,6 +292,7 @@ describe('Workbench session read ownership', () => {
getWorkbenchProjectsBootstrap,
listSessions: vi.fn().mockResolvedValue({ sessions: [session], next_before_id: null }),
connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ createProject: vi.fn().mockResolvedValue(project),
};
let tree: ReturnType<typeof useWorkbenchProjectsTree> | null = null;
const Probe = () => {
@@ -308,8 +309,8 @@ describe('Workbench session read ownership', () => {
</WorkbenchProjectsProvider>,
);
await settle();
- act(() => {
- tree?.upsertProjectToTop(project);
+ await act(async () => {
+ await tree?.createProject({ folder_path: '/tmp/a' });
});
await settle();
await act(async () => {
@@ -345,6 +346,7 @@ describe('Workbench session read ownership', () => {
let handlers: WorkbenchEventHandlers | null = null;
apiRef.current = {
getWorkbenchProjectsBootstrap,
+ createProject: vi.fn().mockResolvedValue(localProject),
connectWorkbenchEvents: vi.fn((next) => {
handlers = next;
return vi.fn();
@@ -370,8 +372,8 @@ describe('Workbench session read ownership', () => {
});
await settle();
expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);
- act(() => {
- tree?.upsertProjectToTop(localProject);
+ await act(async () => {
+ await tree?.createProject({ folder_path: '/tmp/local' });
});
await act(async () => {
staleReconnect.resolve({
diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsx
new file mode 100644
index 000000000..5195e62dd
--- /dev/null
+++ b/ui/src/context/shellBootstrapDemand.test.tsx
@@ -0,0 +1,2611 @@
+// @vitest-environment jsdom
+
+// One class: a provider mounted ABOVE the router bootstraps on its first real
+// consumer, not on mount. The providers below are shared by every route, so a
+// mount-time read makes every route pay for data it may never render — the
+// project tree on /admin, thirty rows of inbox feed on a page that shows only a
+// badge. These tests state the property (what the document actually reads
+// decides what is fetched) rather than enumerating which routes are exempt, so a
+// route added later inherits the rule.
+
+import { act, cleanup, render } from '@testing-library/react';
+import { useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkbenchInboxProvider } from './WorkbenchInboxProvider';
+import { useWorkbenchInbox, type InboxState } from './WorkbenchInboxContext';
+import { WorkbenchProjectsProvider } from './WorkbenchProjectsProvider';
+import {
+ useWorkbenchProjectsActions,
+ useWorkbenchProjectsTree,
+ type WorkbenchProjectsActions,
+ type WorkbenchProjectsTree,
+} from './WorkbenchProjectsContext';
+import type { WorkbenchEventHandlers } from './ApiContext';
+
+const project = {
+ id: 'proj_a',
+ scope_id: 'scope_a',
+ display_name: 'Project A',
+ folder_path: '/tmp/project-a',
+ created_at: '2026-08-18T00:00:00Z',
+ last_active_at: null,
+ archived: false,
+};
+
+const session = {
+ id: 'ses_a',
+ scope_id: 'scope_a',
+ project_id: 'proj_a',
+ title: 'A session',
+ 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-18T00:00:00Z',
+ updated_at: '2026-08-18T00:00:00Z',
+ last_active_at: '2026-08-18T00:00:00Z',
+ metadata: {},
+};
+
+const bootstrapPayload = {
+ projects: [project],
+ sessions: { proj_a: { sessions: [session], next_before_id: null } },
+};
+
+const inboxRow = {
+ session_id: session.id,
+ scope_id: session.scope_id,
+ title: session.title,
+ preview: 'A feed row',
+ preview_message_id: 'msg_a',
+ last_activity_at: session.last_active_at,
+ unread_count: 3,
+ visibility: 'foreground' as const,
+};
+
+// Every read of /api/inbox answers with a feed row AND a cursor alongside the
+// unread map, exactly as the server does. A counts-only read must discard both.
+const inboxPayload = {
+ sessions: [inboxRow],
+ next_cursor: 'cursor_1',
+ unread_by_session: { [session.id]: 3 },
+};
+
+type ListInboxArgs = { platform: string; limit: number; before?: string; onlySession?: string };
+
+type FakeApi = {
+ getWorkbenchProjectsBootstrap?: () => Promise<unknown>;
+ listSessions?: () => Promise<unknown>;
+ getSession?: () => Promise<unknown>;
+ updateSession?: () => Promise<unknown>;
+ createSession?: () => Promise<unknown>;
+ forkSession?: (sessionId: string) => Promise<unknown>;
+ listInbox?: (args: ListInboxArgs) => Promise<unknown>;
+ markSessionRead?: () => 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();
+ });
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+// `active={false}` is the real opt-out a tree reader has (a surface that renders
+// from provider state without being the reason it loads). Here it doubles as an
+// observer that can watch provider state across a navigation that removes every
+// activating consumer.
+const TreeProbe = ({
+ active = true,
+ onState,
+}: { active?: boolean; onState?: (tree: WorkbenchProjectsTree) => void } = {}) => {
+ const tree = useWorkbenchProjectsTree({ active });
+ useEffect(() => {
+ onState?.(tree);
+ }, [onState, tree]);
+ return null;
+};
+
+// A write-only surface (new-session dialogs, rename, archive) reaches the
+// provider through the mutation half of the contract, which cannot read
+// `projects` and must not make the document load them.
+const ActionsProbe = ({ onState }: { onState?: (actions: WorkbenchProjectsActions) => void }) => {
+ const actions = useWorkbenchProjectsActions();
+ useEffect(() => {
+ onState?.(actions);
+ }, [actions, onState]);
+ return null;
+};
+
+const InboxProbe = ({
+ feed,
+ onState,
+}: {
+ feed: boolean;
+ onState?: (state: InboxState) => void;
+}) => {
+ const state = useWorkbenchInbox({ feed });
+ useEffect(() => {
+ onState?.(state);
+ }, [onState, state]);
+ return null;
+};
+
+// A resume is an EDGE, and ``onPageReactivated`` deliberately refuses to read a
+// bare ``focus`` as one: focus moving between elements of a page that never left
+// is the common case, and treating it as a return is what made the old listener
+// over-fire. So drive the transition the sampler actually reads — system focus
+// lost, then regained — rather than the event that used to stand in for it.
+const resumePage = async () => {
+ await act(async () => {
+ document.hasFocus = () => false;
+ window.dispatchEvent(new Event('blur'));
+ document.hasFocus = () => true;
+ window.dispatchEvent(new Event('focus'));
+ });
+};
+
+describe('Demand-driven shell bootstrap', () => {
+ beforeEach(() => {
+ apiRef.current = null;
+ });
+
+ afterEach(() => {
+ cleanup();
+ apiRef.current = null;
+ // Own property, so the prototype's real implementation comes back for tests
+ // that never resume.
+ Reflect.deleteProperty(document, 'hasFocus');
+ });
+
+ describe('projects tree', () => {
+ it('stays unfetched while the document renders no project', async () => {
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <div />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ expect(bootstrap).not.toHaveBeenCalled();
+ });
+
+ it('bootstraps once for a document that reads the tree', async () => {
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ });
+
+ // Demand is a property of what a consumer ASKS FOR, not of which route it sits
+ // on: a permanently mounted write-only surface (fork, pin, rename, archive)
+ // would otherwise re-eagerize the bootstrap on every route through the back
+ // door. The mutation half of the contract cannot read `projects`, so it has
+ // nothing to load.
+ it('leaves the tree unfetched for a document whose only consumer mutates it', async () => {
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ let actions: WorkbenchProjectsActions | null = null;
+ const capture = (next: WorkbenchProjectsActions) => {
+ actions = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <ActionsProbe onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ expect(bootstrap).not.toHaveBeenCalled();
+ // The writes are live regardless — they patch whatever is cached.
+ expect(actions?.createSessionForProject).toBeTypeOf('function');
+
+ // Non-activating is not inert: the same document loads the tree the moment
+ // something actually renders it.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <ActionsProbe onState={capture} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ });
+
+ // Activation has two cases, and they are not interchangeable: the first load
+ // builds the tree, a return REVALIDATES whatever the tree already holds. A
+ // consumer that paged a project in has a window wider than page one, so
+ // resuming through the first-load path would silently truncate it — the same
+ // defect the reconnect reconcile exists to prevent, arriving through
+ // navigation instead of through the stream.
+ it('revalidates a paged-in window when a consumer returns, instead of truncating it', async () => {
+ const secondSession = { ...session, id: 'ses_b', title: 'Older session' };
+ const bootstrap = vi.fn(async (args?: { projectIds?: string[] }) => ({
+ projects: [project],
+ sessions: {
+ proj_a: args?.projectIds
+ ? { sessions: [session, secondSession], next_before_id: null }
+ : { sessions: [session], next_before_id: session.id },
+ },
+ }));
+ const listSessions = vi
+ .fn()
+ .mockResolvedValue({ sessions: [secondSession], next_before_id: null });
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const capture = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={capture} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(1);
+
+ await act(async () => {
+ tree?.loadMore(project.id);
+ });
+ await settle();
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(2);
+
+ // Navigate away from every surface that renders the tree, then back.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={capture} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ const returningRead = bootstrap.mock.calls.at(-1)?.[0] as
+ | { projectIds?: string[]; limit?: number; cache?: boolean }
+ | undefined;
+ expect(returningRead).toMatchObject({ projectIds: [project.id], cache: false });
+ expect(returningRead?.limit).toBeGreaterThanOrEqual(2);
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(2);
+ });
+
+ it('does not re-bootstrap on a reconnect while nothing reads the tree', async () => {
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <div />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ // A long-lived tab sees the shared stream flap and re-authorize; neither is
+ // a reason to load a tree the document does not render.
+ await act(async () => {
+ handlers?.onConnected?.();
+ handlers?.onAuthorizationChanged?.();
+ });
+ await settle();
+
+ expect(bootstrap).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('inbox', () => {
+ it('reads only the unread map for a document that renders no feed', async () => {
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };
+ let state: InboxState | null = null;
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe
+ feed={false}
+ onState={(next) => {
+ state = next;
+ }}
+ />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(1);
+ expect(listInbox.mock.calls[0][0]).toMatchObject({ platform: 'avibe', limit: 1 });
+ // The badge is live; the feed and its cursor are untouched, so activating
+ // the feed later still starts from a real first page.
+ expect(state?.totalUnread).toBe(3);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3 });
+ expect(state?.inboxSessions).toEqual([]);
+ expect(state?.nextCursor).toBeNull();
+ });
+
+ it('reads the feed page instead of the counts when the document renders a feed', async () => {
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };
+ let state: InboxState | null = null;
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe
+ feed
+ onState={(next) => {
+ state = next;
+ }}
+ />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+
+ // One read, not two: a feed consumer activates from its own effect, which
+ // React runs before the provider's, so the counts-only read is skipped in
+ // favour of the feed read that supersedes it.
+ expect(listInbox).toHaveBeenCalledTimes(1);
+ expect(listInbox.mock.calls[0][0]).toMatchObject({ platform: 'avibe', limit: 30 });
+ expect(state?.inboxSessions).toHaveLength(1);
+ expect(state?.nextCursor).toBe('cursor_1');
+ });
+
+ it('loads page one when a later navigation brings a feed consumer in', async () => {
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(listInbox.mock.calls[1][0]).toMatchObject({ platform: 'avibe', limit: 30 });
+ expect(listInbox.mock.calls[1][0]).not.toHaveProperty('before');
+ expect(state?.inboxSessions).toHaveLength(1);
+ });
+ });
+
+ // The demand gate decides what is READ. It must not also decide what stays
+ // cached: a reconnect says "you may have missed events" and can wait for a
+ // consumer, but an authorization change says "what you hold may no longer be
+ // authorized", and both providers' resumption paths deliberately preserve rows
+ // (the projects list survives a failed retry; the inbox reconcile keeps rows the
+ // response omitted). These pin the drop WITHOUT letting any response resolve, so
+ // they hold for a revalidation that is slow, failing, or never arrives.
+ describe('authorization changes invalidate what nothing is reading', () => {
+ it('drops the cached project tree rather than keeping it for the way back', async () => {
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const capture = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toHaveLength(1);
+
+ // Navigate to a route that renders no project, then lose access there.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <div />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ bootstrap.mockReturnValue(deferred<typeof bootstrapPayload>().promise);
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+
+ // Nothing re-reads the tree here, and nothing needs to: coming back must not
+ // be able to render a project that was authorized before the change.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toBeNull();
+ expect(tree?.sessionsOf(project.id).sessions).toBeNull();
+ expect(tree?.isExpanded(project.id)).toBe(false);
+ });
+
+ // Invalidating a read that is already in flight is itself what queues its
+ // replacement, so the drop above has a second half: that retry must not
+ // survive the last reader. Otherwise the invalidation repopulates exactly what
+ // it just dropped — off-route, and with a snapshot the server produced BEFORE
+ // the authorization change.
+ it('drops the tree retry the invalidation itself queues', async () => {
+ const stale = deferred<typeof bootstrapPayload>();
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const capture = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={capture} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toHaveLength(1);
+
+ // A reconnect reconcile is in flight when the user navigates away.
+ bootstrap.mockReturnValue(stale.promise);
+ await act(async () => {
+ handlers?.onConnected?.();
+ });
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+ expect(tree?.projects).toBeNull();
+
+ // The pre-change response now arrives and is correctly refused. What it
+ // queues in its place has no reader, so it is dropped rather than issued.
+ await act(async () => {
+ stale.resolve(bootstrapPayload);
+ });
+ await settle();
+
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ expect(tree?.projects).toBeNull();
+ });
+
+ it('drops cached inbox rows and makes the next feed read authoritative', async () => {
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(state?.inboxSessions).toHaveLength(1);
+
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ listInbox.mockReturnValue(deferred<typeof inboxPayload>().promise);
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+
+ expect(state?.inboxSessions).toEqual([]);
+ expect(state?.nextCursor).toBeNull();
+
+ // Returning to a feed must reload page one destructively, not reconcile onto
+ // a window whose rows were just invalidated.
+ listInbox.mockResolvedValue({ sessions: [], next_cursor: null, unread_by_session: {} });
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+
+ const feedRead = listInbox.mock.calls.at(-1)?.[0];
+ expect(feedRead).toMatchObject({ platform: 'avibe', limit: 30 });
+ expect(feedRead).not.toHaveProperty('before');
+ // reconcile() re-reads with cache disabled; page one does not.
+ expect(feedRead).not.toHaveProperty('cache');
+ expect(state?.inboxSessions).toEqual([]);
+ });
+
+ it('drops the feed retry the invalidation itself queues', async () => {
+ const stale = deferred<typeof inboxPayload>();
+ const countsOnly = { sessions: [], next_cursor: null, unread_by_session: { [session.id]: 3 } };
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const feedReads = () => listInbox.mock.calls.filter(([args]) => args.limit > 1).length;
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(state?.inboxSessions).toHaveLength(1);
+ expect(feedReads()).toBe(1);
+
+ // A resume reconcile is in flight when the user navigates away. The
+ // counts-only read stays live throughout — it is what the remaining route
+ // legitimately reads.
+ listInbox.mockImplementation((args: ListInboxArgs) =>
+ args.limit > 1 ? stale.promise : Promise.resolve(countsOnly),
+ );
+ await resumePage();
+ expect(feedReads()).toBe(2);
+
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+ expect(state?.inboxSessions).toEqual([]);
+
+ await act(async () => {
+ stale.resolve(inboxPayload);
+ });
+ await settle();
+
+ expect(feedReads()).toBe(2);
+ expect(state?.inboxSessions).toEqual([]);
+ expect(state?.nextCursor).toBeNull();
+ });
+
+ it('re-reads the unread map when a mutation invalidates the counts read', async () => {
+ const first = deferred<typeof inboxPayload>();
+ const second = deferred<typeof inboxPayload>();
+ const listInbox = vi
+ .fn()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe
+ feed={false}
+ onState={(next) => {
+ state = next;
+ }}
+ />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ // A live event lands while the counts read is in flight, so that response is
+ // no longer authoritative — and the event itself only carries one session's
+ // count. Discarding it silently would leave every other session's badge
+ // missing until some later focus or reconnect.
+ await act(async () => {
+ handlers?.onInboxSessionUpdated?.(inboxRow);
+ });
+ await act(async () => {
+ first.resolve({ ...inboxPayload, unread_by_session: { [session.id]: 3, ses_b: 5 } });
+ });
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(listInbox.mock.calls[1][0]).toMatchObject({ platform: 'avibe', limit: 1 });
+
+ await act(async () => {
+ second.resolve({ ...inboxPayload, sessions: [], unread_by_session: { ses_b: 7 } });
+ });
+ await settle();
+
+ expect(state?.unreadBySession).toEqual({ ses_b: 7 });
+ expect(state?.totalUnread).toBe(7);
+ });
+ });
+
+ // The one thing in this provider that NO route is exempt from: every document
+ // badges the unread total on its favicon and app icon. So the demand gate may
+ // decide whether the 30-row feed is read, but never whether the whole-account
+ // map is — and the feed read is the one that usually carries it. These state that
+ // as a debt rather than as a list of reads: whichever read was supposed to
+ // deliver the map may fail, be invalidated, or be dropped by the gate, and the
+ // badge still ends up with one.
+ describe('the unread map no route gates', () => {
+ it('reads the counts a dropped feed read was carrying', async () => {
+ const feedRead = deferred<typeof inboxPayload>();
+ const countsOnly = {
+ sessions: [inboxRow],
+ next_cursor: 'cursor_1',
+ unread_by_session: { [session.id]: 3, ses_b: 5 },
+ };
+ const listInbox = vi.fn((args: ListInboxArgs) =>
+ args.limit > 1 ? feedRead.promise : Promise.resolve(countsOnly),
+ );
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const feedReads = () => listInbox.mock.calls.filter(([args]) => args.limit > 1).length;
+ const countsReads = () => listInbox.mock.calls.filter(([args]) => args.limit === 1).length;
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(feedReads()).toBe(1);
+ expect(countsReads()).toBe(0);
+
+ // A live event invalidates that first page while it is still in flight, and
+ // carries only its own session's count — so no whole-account map has arrived.
+ await act(async () => {
+ handlers?.onInboxSessionUpdated?.(inboxRow);
+ });
+ // The user reaches a feedless route before it settles, so the replacement it
+ // queues is dropped: correct for the rows, and the map is now owed to nobody.
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ await act(async () => {
+ feedRead.resolve(inboxPayload);
+ });
+ await settle();
+
+ // No 30-row read is re-issued for a document that renders no feed...
+ expect(feedReads()).toBe(1);
+ // ...and the badge does not wait for a later focus, reconnect or permission
+ // change to learn every other session's count.
+ expect(countsReads()).toBe(1);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3, ses_b: 5 });
+ expect(state?.totalUnread).toBe(8);
+ });
+
+ it('leaves the counts alone when a healthy feed consumer detaches', async () => {
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ apiRef.current = { listInbox, connectWorkbenchEvents: vi.fn(() => vi.fn()) };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ // Workbench → admin. The feed read already delivered a whole map, so the
+ // demand edge owes nothing: re-reading here would put back exactly the
+ // per-navigation traffic this provider exists to avoid.
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(1);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3 });
+ });
+
+ it('reads the counts an authorization change left owing', async () => {
+ const stale = deferred<typeof inboxPayload>();
+ const postChange = { sessions: [], next_cursor: null, unread_by_session: { ses_b: 5 } };
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const feedReads = () => listInbox.mock.calls.filter(([args]) => args.limit > 1).length;
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ // A whole map HAS arrived, so "have we ever loaded one" is already satisfied
+ // here — and is the wrong question, because the map it describes is about to
+ // stop describing this account.
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3 });
+
+ listInbox.mockImplementation((args: ListInboxArgs) =>
+ args.limit > 1 ? stale.promise : Promise.resolve(postChange),
+ );
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+ expect(feedReads()).toBe(2);
+ // That refresh is invalidated mid-flight, and its replacement is dropped when
+ // the user leaves the feed behind — so the read that owed the new scope's map
+ // never delivers one.
+ await act(async () => {
+ handlers?.onInboxSessionUpdated?.(inboxRow);
+ });
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ await act(async () => {
+ stale.resolve(inboxPayload);
+ });
+ await settle();
+
+ expect(feedReads()).toBe(2);
+ expect(state?.unreadBySession).toEqual({ ses_b: 5 });
+ expect(state?.totalUnread).toBe(5);
+ });
+ });
+
+ // The gate is a property of the READ, not of the events that trigger it. Written
+ // at call sites it has to be remembered by each of them, and these providers have
+ // more triggers than any list of guards would cover — a reconnect, session
+ // activity, a pin re-order, a status or turn-end row refresh, a foreground
+ // restore. So these seed one of every request-issuing shape and assert the
+ // property (a revalidation the next activation would redo costs nothing while
+ // nothing reads it) rather than enumerating the triggers that were remembered.
+ describe('the demand gate belongs to the reads, not to their triggers', () => {
+ it('drops every revalidation a stream event or a write triggers while nothing reads the tree', async () => {
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ const listSessions = vi.fn().mockResolvedValue({ sessions: [session], next_before_id: null });
+ const getSession = vi.fn().mockResolvedValue(session);
+ const updateSession = vi.fn().mockResolvedValue({ ...session, pinned: true });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ getSession,
+ updateSession,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ let actions: WorkbenchProjectsActions | null = null;
+ const captureTree = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+ const captureActions = (next: WorkbenchProjectsActions) => {
+ actions = next;
+ };
+ const reads = () =>
+ bootstrap.mock.calls.length + listSessions.mock.calls.length + getSession.mock.calls.length;
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <ActionsProbe onState={captureActions} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(1);
+
+ // Workbench → /admin/settings/messaging. The write-only surface stays mounted
+ // (a settings page can still rename or pin), so the provider keeps its cache
+ // and its stream — it simply has no reader left.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <ActionsProbe onState={captureActions} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ const before = reads();
+
+ await act(async () => {
+ handlers?.onConnected?.({ sub_id: 1 });
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'created',
+ restored: true,
+ });
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ pinned: true,
+ });
+ handlers?.onSessionStatus?.({ session_id: session.id, agent_status: 'idle' });
+ handlers?.onTurnEnd?.({ session_id: session.id });
+ await actions?.setSessionPinned(project.id, session.id, true);
+ });
+ await settle();
+
+ // The gate drops revalidations, never mutations: the write still reaches the
+ // server and still patches the cache the way back will render.
+ expect(updateSession).toHaveBeenCalledTimes(1);
+ expect(tree?.sessionsOf(project.id).sessions?.[0]?.pinned).toBe(true);
+ expect(reads()).toBe(before);
+
+ // And nothing is lost by dropping them, which is what makes it a revalidation:
+ // the returning consumer re-reads the window once.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <ActionsProbe onState={captureActions} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ });
+
+ // The boundary that scopes the rule: a revalidation is a read the next activation
+ // would redo, so dropping it costs nothing. A POPULATING read produces something
+ // nothing else will produce — gating it would leave the group the write just
+ // expanded rendering empty on the way back, because the reconcile skips projects
+ // whose window was never loaded. So the exemption is a property of the read too,
+ // not a call site that forgot the gate.
+ it('still populates a window a write just created, with nothing reading the tree', async () => {
+ const projectB = { ...project, id: 'proj_b', scope_id: 'scope_b', display_name: 'Project B' };
+ const createdSession = { ...session, id: 'ses_new', project_id: projectB.id, scope_id: projectB.scope_id };
+ const bootstrap = vi.fn().mockResolvedValue({
+ projects: [project, projectB],
+ sessions: { proj_a: { sessions: [session], next_before_id: null } },
+ });
+ const listSessions = vi
+ .fn()
+ .mockResolvedValue({ sessions: [createdSession], next_before_id: null });
+ const createSession = vi.fn().mockResolvedValue(createdSession);
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ createSession,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ let actions: WorkbenchProjectsActions | null = null;
+ const captureTree = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+ const captureActions = (next: WorkbenchProjectsActions) => {
+ actions = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <ActionsProbe onState={captureActions} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.sessionsOf(projectB.id).sessions).toBeNull();
+
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <ActionsProbe onState={captureActions} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ await actions?.createSessionForProject(projectB.id);
+ });
+ await settle();
+
+ expect(listSessions).toHaveBeenCalledTimes(1);
+ expect(listSessions.mock.calls[0][0]).toMatchObject({ projectId: projectB.id });
+ expect(tree?.sessionsOf(projectB.id).sessions).toEqual([createdSession]);
+ });
+
+ // Exempting the populating reads at the read leaves exactly one demand
+ // decision the reads cannot make for themselves: a populating read whose
+ // response was refused re-queues ITSELF, and that retry is a revalidation
+ // wearing the populating read's name. So the intent flush keeps the gate for
+ // that one case and no other — the queued tree reconcile below it is gated by
+ // the read it runs, and double-gating it would give one property two owners.
+ it('drops the first load a mutation refused once its reader is gone', async () => {
+ const firstLoad = deferred<typeof bootstrapPayload>();
+ const bootstrap = vi.fn().mockReturnValue(firstLoad.promise);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const captureTree = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+
+ // A turn ends while the first load is still in flight, which invalidates it.
+ await act(async () => {
+ handlers?.onTurnEnd?.({ session_id: session.id });
+ });
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ firstLoad.resolve(bootstrapPayload);
+ });
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+
+ // Dropping it lost nothing: a returning consumer re-reads unconditionally.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ expect(tree?.projects).toHaveLength(1);
+ });
+
+ // The inbox's targeted restore read is the one revalidation that is only HALF
+ // droppable: the card it upserts is not rendered, but the same response owns that
+ // session's unread count, and `unreadBySession` holds only foreground sessions —
+ // so a restore genuinely moves the badge total. Declining the request therefore
+ // has to hand the obligation to the whole-account map instead of dropping it.
+ it('owes the whole map for a foreground restore instead of reading one session', async () => {
+ const beforeRestore = { sessions: [], next_cursor: null, unread_by_session: {} };
+ const afterRestore = {
+ sessions: [],
+ next_cursor: null,
+ unread_by_session: { [session.id]: 3, ses_b: 5 },
+ };
+ const listInbox = vi.fn().mockResolvedValueOnce(beforeRestore).mockResolvedValue(afterRestore);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const wholeCountsReads = () =>
+ listInbox.mock.calls.filter(([args]) => args.limit === 1 && !args.onlySession).length;
+ const targetedReads = () => listInbox.mock.calls.filter(([args]) => args.onlySession).length;
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(wholeCountsReads()).toBe(1);
+ expect(state?.totalUnread).toBe(0);
+
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'foreground',
+ });
+ });
+ await settle();
+
+ // No card work for a document that renders no card...
+ expect(targetedReads()).toBe(0);
+ // ...and the badge still learns the count the restore brought back, which a
+ // plain skip would have left out until some later focus or reconnect.
+ expect(wholeCountsReads()).toBe(2);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3, ses_b: 5 });
+ expect(state?.totalUnread).toBe(8);
+ });
+
+ it('coalesces a burst of restores into one counts read', async () => {
+ const listInbox = vi.fn().mockResolvedValue({
+ sessions: [],
+ next_cursor: null,
+ unread_by_session: { [session.id]: 1, ses_b: 2, ses_c: 3 },
+ });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ // Restoring a scope restores its sessions together. Owing one map is what
+ // makes that cost one read rather than one read per session — the reason the
+ // obligation is state and not a per-event request.
+ await act(async () => {
+ for (const sessionId of [session.id, 'ses_b', 'ses_c']) {
+ handlers?.onSessionActivity?.({
+ session_id: sessionId,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'foreground',
+ });
+ }
+ });
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(listInbox.mock.calls[1][0]).toMatchObject({ platform: 'avibe', limit: 1 });
+ expect(state?.totalUnread).toBe(6);
+ });
+
+ // Owing the map and fencing the reads that could pay it are one act. A read that
+ // left the server before the change cannot describe the counts it is about to
+ // commit, and committing it would pay the debt without satisfying it — the case a
+ // bare `setWholeUnreadOwed(true)` cannot even schedule work for, because the debt
+ // was already outstanding. Stated over every edge that voids the current map
+ // rather than for one of them, because the property belongs to owing the map.
+ const mapVoidingEdges: Array<[string, (handlers: WorkbenchEventHandlers | null) => void]> = [
+ ['an authorization change', (handlers) => handlers?.onAuthorizationChanged?.({})],
+ ['unread counts moving without a map', (handlers) => handlers?.onInboxUnreadChanged?.({ unread_counts: {} })],
+ ];
+ for (const [edge, fire] of mapVoidingEdges) {
+ it(`invalidates the counts read ${edge} left unable to describe the account`, async () => {
+ const preChange = deferred<typeof inboxPayload>();
+ const listInbox = vi
+ .fn()
+ .mockReturnValueOnce(preChange.promise)
+ .mockResolvedValue({ sessions: [], next_cursor: null, unread_by_session: { ses_b: 5 } });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ fire(handlers);
+ });
+ await act(async () => {
+ preChange.resolve({ ...inboxPayload, unread_by_session: { [session.id]: 3 } });
+ });
+ await settle();
+
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(state?.unreadBySession).toEqual({ ses_b: 5 });
+ expect(state?.totalUnread).toBe(5);
+ });
+ }
+ });
+
+ // Round 5 moved the demand decision into the reads; this states WHEN each read
+ // asks it. Two things can make a response impossible or pointless to commit —
+ // no reader left, and nowhere to put it — and both used to be answered somewhere
+ // other than the moment of asking: the first once on the way into a read that
+ // then issues many requests, the second only after a request had been paid for.
+ // A read is not one request. `reconcileSessions` pages a window, the tree rebuild
+ // issues one bootstrap per window size, and both go round again on a refused
+ // response. So the property is per REQUEST: every request is preceded by the same
+ // predicate, and a read that cannot commit anything issues nothing at all.
+ describe('every request is preceded by the question, not every read', () => {
+ it('stops paging a window between pages when its last reader leaves', async () => {
+ const sessionB = { ...session, id: 'ses_b' };
+ const bootstrap = vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { proj_a: { sessions: [session, sessionB], next_before_id: null } },
+ });
+ const firstPage = deferred<{ sessions: Array<typeof session>; next_before_id: string | null }>();
+ const listSessions = vi
+ .fn()
+ .mockReturnValueOnce(firstPage.promise)
+ .mockResolvedValue({ sessions: [sessionB], next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const captureTree = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(2);
+
+ // Activity on a two-row window starts a reconcile that needs two pages.
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'user_message',
+ });
+ });
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // Workbench → /admin between page one and page two.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ firstPage.resolve({ sessions: [session], next_before_id: 'cursor_2' });
+ });
+ await settle();
+
+ // An entry gate passed before the navigation would have finished rebuilding a
+ // window nobody renders, one page at a time.
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // And the abandoned half costs nothing: the window is still what it was, and
+ // the returning consumer re-reads it.
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(2);
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops rebuilding the tree between window-size groups', async () => {
+ // The rebuild batches projects by how much of each window has to come back,
+ // so it is one request per distinct size — a loop like any other.
+ const projectWide = { ...project, id: 'proj_wide', scope_id: 'scope_wide', display_name: 'Wide' };
+ const wideWindow = Array.from({ length: 10 }, (_, index) => ({
+ ...session,
+ id: `ses_wide_${index}`,
+ project_id: projectWide.id,
+ scope_id: projectWide.scope_id,
+ }));
+ const treePayload = {
+ projects: [project, projectWide],
+ sessions: {
+ [project.id]: { sessions: [session], next_before_id: null },
+ [projectWide.id]: { sessions: wideWindow, next_before_id: null },
+ },
+ };
+ const firstGroup = deferred<typeof treePayload>();
+ const bootstrap = vi
+ .fn()
+ .mockResolvedValueOnce(treePayload)
+ .mockReturnValueOnce(firstGroup.promise)
+ .mockResolvedValue(treePayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions: vi.fn().mockResolvedValue({ sessions: [], next_before_id: null }),
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ handlers?.onConnected?.({ sub_id: 1 });
+ });
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ expect(bootstrap.mock.calls[1][0]).toMatchObject({ projectIds: [project.id] });
+
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ firstGroup.resolve(treePayload);
+ });
+ await settle();
+
+ // The ten-row group is never asked for.
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ });
+
+ it('stops a row refresh that a mid-flight event sent round again', async () => {
+ // This read loops in place: an event landing while it is in flight refuses the
+ // response and makes it read the row again. The second read is a request of
+ // its own and asks the question of its own.
+ const unbound = { ...session, native_session_id: null };
+ const bootstrap = vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { proj_a: { sessions: [unbound], next_before_id: null } },
+ });
+ const firstRead = deferred<typeof unbound>();
+ const getSession = vi.fn().mockReturnValueOnce(firstRead.promise).mockResolvedValue(unbound);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ getSession,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ handlers?.onTurnEnd?.({ session_id: session.id });
+ });
+ expect(getSession).toHaveBeenCalledTimes(1);
+
+ // A second turn-end refuses the read in flight and queues another pass.
+ await act(async () => {
+ handlers?.onTurnEnd?.({ session_id: session.id });
+ });
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ firstRead.resolve(unbound);
+ });
+ await settle();
+
+ expect(getSession).toHaveBeenCalledTimes(1);
+ });
+
+ // The other half of the question. A populating read is exempt from demand, but
+ // it still has to have somewhere to land — and it already knew the answer, since
+ // it discarded every response that came back for a project the tree does not
+ // hold. Asking first is the same question one round-trip earlier.
+ it('issues no window read for a fork on a document that never loaded the tree', async () => {
+ const forked = { ...session, id: 'ses_forked' };
+ const forkSession = vi.fn().mockResolvedValue(forked);
+ const listSessions = vi.fn().mockResolvedValue({ sessions: [forked], next_before_id: null });
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ forkSession,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ };
+ let actions: WorkbenchProjectsActions | null = null;
+ const captureActions = (next: WorkbenchProjectsActions) => {
+ actions = next;
+ };
+
+ // /chat/:id renders one session, never the tree — but it does fork.
+ render(
+ <WorkbenchProjectsProvider>
+ <ActionsProbe onState={captureActions} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ await actions?.forkSession(project.id, session.id);
+ });
+ await settle();
+
+ // The write is untouched; only the read that had nowhere to commit is gone.
+ expect(forkSession).toHaveBeenCalledTimes(1);
+ expect(listSessions).not.toHaveBeenCalled();
+ expect(bootstrap).not.toHaveBeenCalled();
+ });
+
+ // The boundary that makes asking first safe. A write can CREATE the address in
+ // the same tick it asks for the window, so membership has to be true when the
+ // write returns rather than one render later — the list and its mirror are
+ // committed together for exactly this.
+ it('loads the window of a project the write it followed just added', async () => {
+ const newProject = { ...project, id: 'proj_new', scope_id: 'scope_new', display_name: 'New' };
+ const newSession = { ...session, id: 'ses_new', project_id: newProject.id, scope_id: newProject.scope_id };
+ const bootstrap = vi.fn().mockResolvedValue({ projects: [project], sessions: {} });
+ const listSessions = vi.fn().mockResolvedValue({ sessions: [newSession], next_before_id: null });
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ createProject: vi.fn().mockResolvedValue(newProject),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const captureTree = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toEqual([project]);
+
+ // Opening a tracked folder hoists the project and asks for its sessions in the
+ // same statement.
+ await act(async () => {
+ await tree?.createProject({ folder_path: newProject.folder_path });
+ });
+ await settle();
+
+ expect(listSessions).toHaveBeenCalledTimes(1);
+ expect(listSessions.mock.calls[0][0]).toMatchObject({ projectId: newProject.id });
+ expect(tree?.sessionsOf(newProject.id).sessions).toEqual([newSession]);
+ });
+
+ // The window read's own copy of the one demand decision a read cannot make for
+ // itself: a populating read whose response a mutation refused re-queues ITSELF,
+ // and that retry is a revalidation wearing the populating read's name. Same rule
+ // as ``flushBootstrapReadIntent``, one level down.
+ it('drops the window retry a mutation refused, once its reader is gone', async () => {
+ const bootstrap = vi.fn().mockResolvedValue({ projects: [project], sessions: {} });
+ const firstLoad = deferred<{ sessions: Array<typeof session>; next_before_id: string | null }>();
+ const listSessions = vi
+ .fn()
+ .mockReturnValueOnce(firstLoad.promise)
+ .mockResolvedValue({ sessions: [session], next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const captureTree = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ // Expanding a group populates its window — exempt from demand, and in flight.
+ await act(async () => {
+ tree?.toggleExpanded(project.id);
+ });
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // Activity invalidates that read, so its response can no longer be committed.
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ title: 'Fresh title',
+ });
+ });
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ firstLoad.resolve({ sessions: [session], next_before_id: null });
+ });
+ await settle();
+
+ // With a reader still there this retries (see WorkbenchSessionReadOrdering);
+ // with none, the window it would keep filled has nobody to fill it for.
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} onState={captureTree} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ // Gating the reads makes requests refusable, and a refusable request cannot be
+ // where an obligation lives: a debt is a LEVEL, cleared only by the commit that
+ // satisfies it, so whatever discharges it must be driven by the level rather
+ // than by the attempt carrying it or by the state edge that created it. Both
+ // members below record what is owed at one moment and pay it at another, with a
+ // demand gate, a navigation or a failure in between.
+ describe('a debt outlives the read that was carrying it', () => {
+ it('rebuilds the width a restore asked for after the gate declined to pay it', async () => {
+ const wideWindow = Array.from({ length: 10 }, (_, index) => ({
+ ...session,
+ id: `ses_wide_${index}`,
+ }));
+ const treePayload = {
+ projects: [project],
+ sessions: { [project.id]: { sessions: wideWindow, next_before_id: null } },
+ };
+ // The rebuild that honours the debt comes back one row short of it: first
+ // with more rows behind a cursor, then from a source that says there are
+ // none. Only the second can settle a minimum it did not reach.
+ const shortOfTheDebt = {
+ projects: [project],
+ sessions: { [project.id]: { sessions: wideWindow, next_before_id: 'cursor_2' } },
+ };
+ const inFlightPage = deferred<{ sessions: typeof wideWindow; next_before_id: string | null }>();
+ const bootstrap = vi
+ .fn()
+ .mockResolvedValueOnce(treePayload)
+ .mockResolvedValueOnce(shortOfTheDebt)
+ .mockResolvedValue(treePayload);
+ const listSessions = vi
+ .fn()
+ .mockReturnValueOnce(inFlightPage.promise)
+ .mockResolvedValue({ sessions: wideWindow, next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ const { rerender } = render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+
+ // A reconcile of the ten-row window is in flight...
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: wideWindow[0].id,
+ scope_id: project.scope_id,
+ event: 'user_message',
+ });
+ });
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // ...when Undo restores a session ranked just past it. One row more than is
+ // loaded is the only record of that restore: every other path sizes this
+ // project's window from the rows already cached.
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: 'ses_restored',
+ scope_id: project.scope_id,
+ event: 'created',
+ restored: true,
+ });
+ });
+
+ // Workbench → /admin, and the page lands with no reader left to widen for.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ await act(async () => {
+ inFlightPage.resolve({ sessions: wideWindow, next_before_id: 'cursor_2' });
+ });
+ await settle();
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // Back on the workbench the rebuild asks for eleven rows, not the ten the
+ // cache holds: refusing a request declines to pay the debt, it does not
+ // discharge it, and no later revalidation would put the restored row back.
+ rerender(
+ <WorkbenchProjectsProvider>
+ <TreeProbe active={false} />
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ expect(bootstrap.mock.calls[1][0]).toMatchObject({ projectIds: [project.id], limit: 11 });
+
+ // That rebuild committed ten rows with a cursor behind them, so it did not
+ // reach the minimum and does not get to clear it either: the reconnect
+ // still asks for eleven. Paying part of a debt is not paying it.
+ await act(async () => {
+ handlers?.onConnected?.({ sub_id: 1 });
+ });
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(3);
+ expect(bootstrap.mock.calls[2][0]).toMatchObject({ projectIds: [project.id], limit: 11 });
+
+ // This one commits the same ten rows with nothing behind them. A source
+ // that says there is no eleventh row settles the debt as surely as one
+ // that produces it — otherwise a restore later undone would widen every
+ // rebuild of this project forever.
+ await act(async () => {
+ handlers?.onConnected?.({ sub_id: 1 });
+ });
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(4);
+ expect(bootstrap.mock.calls[3][0]).toMatchObject({ projectIds: [project.id], limit: 10 });
+ });
+
+ it('re-reads the counts a failed read left owing', async () => {
+ const listInbox = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('counts read failed'))
+ .mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+ expect(state?.unreadBySession).toEqual({});
+
+ // The counts changed and the event did not say how, so all it can do is owe a
+ // whole map — one that is already owed, by a read that failed and is no longer
+ // in flight. There is no state edge for an effect to run on and no in-flight
+ // read for the fence to re-arm, so nothing but the level itself can reach this
+ // debt, and the badge would keep counts nothing describes until some unrelated
+ // focus or reconnect.
+ await act(async () => {
+ handlers?.onInboxUnreadChanged?.({ unread_counts: {} });
+ });
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3 });
+ expect(state?.totalUnread).toBe(3);
+ logged.mockRestore();
+ });
+ });
+
+ // Every read in this shell that loops in place re-enters on evidence its own
+ // pass produced: a mutation that invalidated the response, or a trigger the
+ // in-flight guard turned away and now owes a pass. An outstanding obligation is
+ // not that evidence — it is the reason the work exists, and it says nothing
+ // about whether another attempt can discharge it. A loop that re-enters on the
+ // obligation alone spins for as long as it keeps being refused.
+ //
+ // Each loop asserts it here rather than being correct by construction, so the
+ // next change to any of them fails a test instead of costing a review round.
+ describe('a read loop retries only on evidence its own pass produced', () => {
+ // Twenty rejections then a success: an escape hatch turns a retry loop into a
+ // countable assertion instead of a test that hangs on its own microtasks.
+ function failingReads<T>(value: T) {
+ let attempts = 0;
+ return vi.fn(async () => {
+ attempts += 1;
+ if (attempts <= 20) throw new Error('read failed');
+ return value;
+ });
+ }
+
+ it('honours a trigger the in-flight guard turned away, exactly once', async () => {
+ // The positive half of the rule. This trigger has no other payer: the guard
+ // sent its caller home, so unless the read in flight goes round again the
+ // event is simply lost — and it must go round ONCE, not for as long as the
+ // record of it survives.
+ const windowPage = { sessions: [session], next_before_id: null };
+ const bootstrap = vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { [project.id]: windowPage },
+ });
+ const inFlight = deferred<typeof windowPage>();
+ let laterReads = 0;
+ const listSessions = vi.fn().mockReturnValueOnce(inFlight.promise).mockImplementation(async () => {
+ laterReads += 1;
+ // An escape hatch again: an empty window has nothing left to reconcile, so
+ // a loop that never consumes the trigger it honoured is a count rather
+ // than a hung suite.
+ return laterReads >= 20 ? { sessions: [], next_before_id: null } : windowPage;
+ });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: project.scope_id,
+ event: 'user_message',
+ });
+ });
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // A second event lands while that read is in flight and is turned away.
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: project.scope_id,
+ event: 'user_message',
+ });
+ });
+ await act(async () => {
+ inFlight.resolve(windowPage);
+ });
+ await settle();
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves the debt its own failed window read could not pay to the next trigger', async () => {
+ const wideWindow = Array.from({ length: 10 }, (_, index) => ({
+ ...session,
+ id: `ses_wide_${index}`,
+ }));
+ const bootstrap = vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { [project.id]: { sessions: wideWindow, next_before_id: null } },
+ });
+ const listSessions = failingReads({ sessions: wideWindow, next_before_id: null });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ listSessions,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+
+ // Undo restores a session ranked just past the window, so this reconcile
+ // carries a minimum of eleven — and its first request fails.
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: 'ses_restored',
+ scope_id: project.scope_id,
+ event: 'created',
+ restored: true,
+ });
+ });
+ await settle();
+ // A failed request is not evidence that another one would land. Demand is
+ // still here and the debt is still owed, and neither says this pass can pay
+ // it: retrying on the debt alone is an unbounded loop against a failing API.
+ expect(listSessions).toHaveBeenCalledTimes(1);
+
+ // The debt is untouched, so the next trigger asks for eleven rows: the
+ // failure declined to pay it, exactly as a refusal does.
+ await act(async () => {
+ handlers?.onConnected?.({ sub_id: 1 });
+ });
+ await settle();
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ expect(bootstrap.mock.calls[1][0]).toMatchObject({ projectIds: [project.id], limit: 11 });
+ });
+
+ it('stops a row refresh whose read failed instead of reading the row again', async () => {
+ const unbound = { ...session, native_session_id: null };
+ const bootstrap = vi.fn().mockResolvedValue({
+ projects: [project],
+ sessions: { proj_a: { sessions: [unbound], next_before_id: null } },
+ });
+ const getSession = failingReads(unbound);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ getSession,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+
+ await act(async () => {
+ handlers?.onTurnEnd?.({ session_id: session.id });
+ });
+ await settle();
+ // The next turn-end re-reads this row anyway; a failed one has no reason of
+ // its own to go round again.
+ expect(getSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops a targeted card read whose request failed', async () => {
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const feedPage = { sessions: [inboxRow], next_cursor: null, unread_by_session: {} };
+ const listInbox = vi.fn(async (args: ListInboxArgs) => {
+ if (!args.onlySession) return feedPage;
+ throw new Error('targeted read failed');
+ });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ const targetedReads = () => listInbox.mock.calls.filter(([args]) => args.onlySession).length;
+
+ await act(async () => {
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'foreground',
+ });
+ });
+ await settle();
+ expect(targetedReads()).toBe(1);
+ logged.mockRestore();
+ });
+ });
+
+ // An authorization change is an INVALIDATION. Demand decides only whether a
+ // replacement READ follows it — never whether the cache it voids is dropped.
+ // Reading the two as one question is what puts the drop in the no-consumer
+ // branch, which says "nothing is reading, so let it go" when the actual reason
+ // is that the change made the rows unauthorized. With a consumer the caches
+ // then merely revalidate, and every one of them deliberately PRESERVES what it
+ // holds when a read fails, so a revoked row stays rendered for as long as the
+ // replacement takes and indefinitely if it never lands.
+ describe('an authorization change invalidates whether or not anyone is reading', () => {
+ it('drops the project tree at the edge, then re-reads it as a first load', async () => {
+ const replacement = deferred<typeof bootstrapPayload>();
+ const bootstrap = vi.fn().mockResolvedValue(bootstrapPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const capture = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toHaveLength(1);
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(1);
+
+ bootstrap.mockReturnValue(replacement.promise);
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+
+ // Asserted while the replacement read is still in flight: the edge is what
+ // drops it, not the response.
+ expect(tree?.projects).toBeNull();
+ expect(tree?.sessionsOf(project.id).sessions).toBeNull();
+
+ // And what follows is the authoritative first load, not a reconcile of the
+ // window this same edge just dropped — a reconcile would re-read only the
+ // projects it still had cached, which is now none of them.
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+ expect(bootstrap.mock.calls.at(-1)?.[0]).not.toHaveProperty('projectIds');
+
+ await act(async () => {
+ replacement.resolve(bootstrapPayload);
+ });
+ await settle();
+ expect(tree?.projects).toHaveLength(1);
+ expect(tree?.sessionsOf(project.id).sessions).toHaveLength(1);
+ });
+
+ it('refuses a tree response the server produced before the change', async () => {
+ const stale = deferred<typeof bootstrapPayload>();
+ const pending = deferred<typeof bootstrapPayload>();
+ const bootstrap = vi
+ .fn()
+ .mockResolvedValueOnce(bootstrapPayload)
+ .mockReturnValueOnce(stale.promise)
+ .mockReturnValue(pending.promise);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const capture = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toHaveLength(1);
+
+ // A reconnect reconcile is in flight when access changes under it.
+ await act(async () => {
+ handlers?.onConnected?.();
+ });
+ expect(bootstrap).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+ expect(tree?.projects).toBeNull();
+
+ // The pre-change snapshot now arrives. Fencing belongs to the edge for the
+ // same reason the drop does: this response describes the authorization the
+ // change replaced, whether or not a consumer is waiting for it.
+ await act(async () => {
+ stale.resolve(bootstrapPayload);
+ });
+ await settle();
+ expect(tree?.projects).toBeNull();
+ });
+
+ it('drops the inbox feed at the edge, not only when nothing reads it', async () => {
+ const replacement = deferred<typeof inboxPayload>();
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const feedReads = () => listInbox.mock.calls.filter(([args]) => args.limit > 1);
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(state?.inboxSessions).toHaveLength(1);
+ expect(state?.nextCursor).toBe('cursor_1');
+
+ listInbox.mockReturnValue(replacement.promise);
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+
+ // Asserted before the replacement read settles, and the cursor goes with
+ // the rows: a cursor is a position in a list this document may no longer be
+ // allowed to page through.
+ expect(state?.inboxSessions).toEqual([]);
+ expect(state?.nextCursor).toBeNull();
+
+ // The consumer is still reading, so a replacement follows the drop — and
+ // having dropped the window is what makes it the authoritative page one
+ // rather than a reconcile onto rows that are no longer there.
+ expect(feedReads()).toHaveLength(2);
+ expect(feedReads().at(-1)?.[0]).toMatchObject({ platform: 'avibe', limit: 30 });
+ expect(feedReads().at(-1)?.[0]).not.toHaveProperty('cache');
+
+ await act(async () => {
+ replacement.resolve({ sessions: [], next_cursor: null, unread_by_session: {} });
+ });
+ await settle();
+ expect(state?.inboxSessions).toEqual([]);
+ });
+
+ it('refuses a feed response the change outran, even when its replacement is dropped', async () => {
+ const stale = deferred<typeof inboxPayload>();
+ const countsOnly = { sessions: [], next_cursor: null, unread_by_session: { [session.id]: 3 } };
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(state?.inboxSessions).toHaveLength(1);
+
+ // A resume reconcile is in flight when access changes under it.
+ listInbox.mockImplementation((args: ListInboxArgs) =>
+ args.limit > 1 ? stale.promise : Promise.resolve(countsOnly),
+ );
+ await resumePage();
+
+ // The change lands while the feed still has a reader, so a replacement read
+ // is queued behind the one in flight...
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+ expect(state?.inboxSessions).toEqual([]);
+
+ // ...and then the reader leaves, which drops that queued read. Nothing is
+ // left to replace the rows, so the edge itself has to have refused the
+ // response that is about to arrive.
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ await act(async () => {
+ stale.resolve(inboxPayload);
+ });
+ await settle();
+
+ expect(state?.inboxSessions).toEqual([]);
+ expect(state?.nextCursor).toBeNull();
+ });
+
+ // A straggler of the same rule that moved the gate onto the reads: this loop
+ // asks once on the way in, so a retry queued while a card was rendered still
+ // runs after the last feed consumer left.
+ it('stops a queued targeted retry whose feed consumer left, and owes the map instead', async () => {
+ const inFlight = deferred<typeof inboxPayload>();
+ const countsOnly = { sessions: [], next_cursor: null, unread_by_session: { [session.id]: 7 } };
+ const listInbox = vi.fn().mockImplementation((args: ListInboxArgs) => {
+ if (args.onlySession) return inFlight.promise;
+ return Promise.resolve(args.limit > 1 ? inboxPayload : countsOnly);
+ });
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const targetedReads = () => listInbox.mock.calls.filter(([args]) => args.onlySession).length;
+ const wholeCountsReads = () =>
+ listInbox.mock.calls.filter(([args]) => args.limit === 1 && !args.onlySession).length;
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+
+ const restore = () =>
+ handlers?.onSessionActivity?.({
+ session_id: session.id,
+ scope_id: session.scope_id,
+ event: 'updated',
+ visibility: 'foreground',
+ });
+ await act(async () => {
+ restore();
+ });
+ expect(targetedReads()).toBe(1);
+ // A second restore lands mid-read, so the loop owes itself another pass.
+ await act(async () => {
+ restore();
+ });
+ expect(targetedReads()).toBe(1);
+
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ const countsBefore = wholeCountsReads();
+
+ await act(async () => {
+ inFlight.resolve(inboxPayload);
+ });
+ await settle();
+
+ // The card that pass would upsert is not rendered anywhere, so the request
+ // is declined — but its other half is the session's unread count, which
+ // every route badges, so the obligation moves to the whole-account map.
+ expect(targetedReads()).toBe(1);
+ expect(wholeCountsReads()).toBeGreaterThan(countsBefore);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 7 });
+ });
+ });
+
+ // A guard that declines on a CORRELATE of the thing it needs is right until the
+ // two come apart. "A feed consumer exists" correlates with "the feed read will
+ // carry the map", and "this is a read" correlates with "this is how a row reaches
+ // the cache" — both hold in the common case and both have an edge where they do
+ // not, and on that edge the guard silently drops what it was protecting.
+ describe('a guard names the invariant, not something that usually travels with it', () => {
+ it('reads the map a live feed consumer left owing, without reading it twice', async () => {
+ const listInbox = vi.fn().mockResolvedValue(inboxPayload);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 3 });
+
+ // The counts moved and the event did not say how, so the map this document
+ // holds no longer describes the account. Nothing is in flight to replace it:
+ // the feed read that would normally carry one already finished.
+ listInbox.mockResolvedValue({ ...inboxPayload, unread_by_session: { [session.id]: 9 } });
+ await act(async () => {
+ handlers?.onInboxUnreadChanged?.({});
+ });
+ await settle();
+
+ // Having a feed consumer is not having a payment scheduled. The debt is paid
+ // by ASKING for the read that carries the map...
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(state?.unreadBySession).toEqual({ [session.id]: 9 });
+
+ // ...and by asking once: the read this queued is the payment, so the counts
+ // effect that also observes the debt must not add a second request.
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ });
+
+ it('pays a debt raised over the very read that debt just fenced', async () => {
+ const feedRead = deferred<typeof inboxPayload>();
+ const listInbox = vi.fn((args: ListInboxArgs) =>
+ args.limit > 1 && listInbox.mock.calls.length === 1
+ ? feedRead.promise
+ : Promise.resolve({ ...inboxPayload, unread_by_session: { ses_b: 5 } }),
+ );
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ // Raising the debt fences the reads that started before it — including this
+ // one. It is in flight AND it is guaranteed not to pay.
+ await act(async () => {
+ handlers?.onInboxUnreadChanged?.({});
+ });
+ await act(async () => {
+ feedRead.resolve(inboxPayload);
+ });
+ await settle();
+
+ // Its rows are still current and commit; its map is refused, exactly as the
+ // fence intends. Something else therefore has to carry one.
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(state?.unreadBySession).toEqual({ ses_b: 5 });
+ });
+
+ it('re-owes the map when the gate drops the read that was going to carry it', async () => {
+ const feedRead = deferred<typeof inboxPayload>();
+ const listInbox = vi.fn((args: ListInboxArgs) =>
+ args.limit > 1
+ ? feedRead.promise
+ : Promise.resolve({ sessions: [], next_cursor: null, unread_by_session: { ses_b: 5 } }),
+ );
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+ const feedReads = () => listInbox.mock.calls.filter(([args]) => args.limit > 1).length;
+ const countsReads = () => listInbox.mock.calls.filter(([args]) => args.limit === 1).length;
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ <InboxProbe feed />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(feedReads()).toBe(1);
+
+ // The debt is raised while a feed consumer is mounted, so the payment it
+ // schedules is a feed read — which cannot start until the one in flight ends.
+ await act(async () => {
+ handlers?.onInboxUnreadChanged?.({});
+ });
+
+ // The user leaves for a feedless route first. The demand edge is observed
+ // while that payment is still only queued, so the settle it triggers sees a
+ // payment scheduled and correctly stands aside...
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(countsReads()).toBe(0);
+
+ await act(async () => {
+ feedRead.resolve(inboxPayload);
+ });
+ await settle();
+
+ // ...which makes the gate's drop the moment that payment stops existing, and
+ // therefore the moment the debt has to be owed again. No 30-row read for a
+ // feedless document, and no badge left describing counts that already moved.
+ expect(feedReads()).toBe(1);
+ expect(countsReads()).toBe(1);
+ expect(state?.unreadBySession).toEqual({ ses_b: 5 });
+ });
+
+ it('re-tests a debt its only payer failed to pay, at the next demand edge', async () => {
+ const reconcileRead = deferred<typeof inboxPayload>();
+ const listInbox = vi.fn((args: ListInboxArgs) => {
+ if (args.limit === 1) {
+ return Promise.resolve({ sessions: [], next_cursor: null, unread_by_session: { ses_b: 5 } });
+ }
+ return listInbox.mock.calls.filter(([a]) => a.limit > 1).length === 1
+ ? Promise.resolve(inboxPayload)
+ : reconcileRead.promise;
+ });
+ const feedReads = () => listInbox.mock.calls.filter(([args]) => args.limit > 1).length;
+ const countsReads = () => listInbox.mock.calls.filter(([args]) => args.limit === 1).length;
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ const { rerender } = render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(feedReads()).toBe(1);
+
+ // The debt is raised with a feed consumer mounted, so the payment it
+ // schedules is a feed read — and that read is the only payer there is.
+ await act(async () => {
+ handlers?.onInboxUnreadChanged?.({});
+ });
+ await settle();
+ expect(feedReads()).toBe(2);
+
+ // It fails. Re-asking here would re-enter on the debt itself, which is the
+ // one thing that cannot decide when to retry: it is still owed precisely
+ // because the last attempt failed, so the loop would never end.
+ await act(async () => {
+ reconcileRead.reject(new Error('offline'));
+ });
+ await settle();
+ expect(countsReads()).toBe(0);
+
+ // A demand edge is a real event rather than a level, and it changes which
+ // read can pay: leaving the feed makes the counts-only read the one that
+ // can, so the badge recovers there instead of on a timer.
+ rerender(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(feedReads()).toBe(2);
+ expect(countsReads()).toBe(1);
+ expect(state?.unreadBySession).toEqual({ ses_b: 5 });
+ });
+
+ it('collapses a burst of debts into one re-read rather than one read each', async () => {
+ const firstRead = deferred<typeof inboxPayload>();
+ const listInbox = vi.fn(() =>
+ listInbox.mock.calls.length === 1
+ ? firstRead.promise
+ : Promise.resolve({ sessions: [], next_cursor: null, unread_by_session: { ses_b: 5 } }),
+ );
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ listInbox,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let state: InboxState | null = null;
+ const capture = (next: InboxState) => {
+ state = next;
+ };
+
+ render(
+ <WorkbenchInboxProvider>
+ <InboxProbe feed={false} onState={capture} />
+ </WorkbenchInboxProvider>,
+ );
+ await settle();
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ // Three events land while that read is in flight. Each one voids the map the
+ // read is carrying, so each one genuinely re-owes it — what they must not do
+ // is each buy their own request for the same answer.
+ for (let i = 0; i < 3; i += 1) {
+ await act(async () => {
+ handlers?.onInboxUnreadChanged?.({});
+ });
+ }
+ expect(listInbox).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ firstRead.resolve(inboxPayload);
+ });
+ await settle();
+
+ // The read in flight is what makes the debt a flag instead of a fan-out: it
+ // absorbs the burst, and the one re-read it owes afterwards answers all three.
+ expect(listInbox).toHaveBeenCalledTimes(2);
+ expect(state?.unreadBySession).toEqual({ ses_b: 5 });
+ });
+
+ it('refuses a project a create wrote after the change that dropped the tree', async () => {
+ const created = deferred<typeof project>();
+ // The re-read the change triggers stays in flight, so the tree observed below
+ // is the one the drop left behind rather than a fresh authorized load.
+ const reload = deferred<typeof bootstrapPayload>();
+ const bootstrap = vi
+ .fn()
+ .mockResolvedValueOnce(bootstrapPayload)
+ .mockReturnValue(reload.promise);
+ let handlers: WorkbenchEventHandlers | null = null;
+ apiRef.current = {
+ getWorkbenchProjectsBootstrap: bootstrap,
+ createProject: vi.fn(() => created.promise),
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ };
+ let tree: WorkbenchProjectsTree | null = null;
+ const capture = (next: WorkbenchProjectsTree) => {
+ tree = next;
+ };
+
+ render(
+ <WorkbenchProjectsProvider>
+ <TreeProbe onState={capture} />
+ </WorkbenchProjectsProvider>,
+ );
+ await settle();
+ expect(tree?.projects).toHaveLength(1);
+
+ // The user creates a project, and access changes while that write is in
+ // flight. The tree is dropped — including the row the create was going to
+ // land next to.
+ let placed: unknown;
+ let writing: Promise<void> | undefined;
+ await act(async () => {
+ writing = tree!.createProject({ folder_path: '/tmp/new' }).then((result) => {
+ placed = result;
+ });
+ });
+ await act(async () => {
+ handlers?.onAuthorizationChanged?.();
+ });
+ expect(tree?.projects).toBeNull();
+
+ await act(async () => {
+ created.resolve({ ...project, id: 'proj_new' });
+ await writing;
+ });
+ await settle();
+
+ // A write is the other way a row reaches this cache, and it is the only one
+ // that can SEED it: committing here would rebuild the tree from an
+ // authorization this document no longer holds, out of a single row. The
+ // project exists on the server; the next activation is what decides whether
+ // this document may see it.
+ expect(tree?.projects).toBeNull();
+ expect(placed).toBeNull();
+ });
+ });
+});
diff --git a/ui/src/lib/showPagesStore.test.ts b/ui/src/lib/showPagesStore.test.ts
index f8bf85aa2..43705dc07 100644
--- a/ui/src/lib/showPagesStore.test.ts
+++ b/ui/src/lib/showPagesStore.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
+import type { ApiContextType } from '../context/ApiContext';
import {
+ commitShowPagesInventoryStore,
+ getShowPagesInventoryStore,
ShowPagesInventoryStore,
type ShowPage,
type ShowPagesInventoryApi,
@@ -43,7 +46,7 @@ const deferred = <T,>() => {
type EventHandlers = Parameters<ShowPagesInventoryApi['connectWorkbenchEvents']>[0];
describe('ShowPagesInventoryStore', () => {
- it('single-flights simultaneous consumers and owns one events subscription', async () => {
+ it('single-flights simultaneous consumers and keeps one events subscription', async () => {
const response = deferred<{ pages: ShowPage[] }>();
const disconnect = vi.fn();
const api: ShowPagesInventoryApi = {
@@ -66,8 +69,164 @@ describe('ShowPagesInventoryStore', () => {
releaseFirst();
expect(disconnect).not.toHaveBeenCalled();
+ // The last consumer leaving does not end the subscription: the snapshot it
+ // leaves behind is what an authorization change has to be able to reach.
releaseSecond();
+ expect(disconnect).not.toHaveBeenCalled();
+ expect(api.connectWorkbenchEvents).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops a retained snapshot when access changes with nothing reading it', async () => {
+ let handlers: EventHandlers | undefined;
+ const disconnect = vi.fn();
+ const revalidation = deferred<{ pages: ShowPage[] }>();
+ const getShowPages = vi
+ .fn()
+ .mockResolvedValueOnce({ pages: [page({ share_id: 'share-1' })] })
+ .mockImplementationOnce(() => revalidation.promise);
+ const store = new ShowPagesInventoryStore({
+ getShowPages,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return disconnect;
+ }),
+ });
+
+ const close = store.activate();
+ await store.reload();
+ handlers?.onConnected?.({ sub_id: 1, source: 'browser' });
+ expect(store.getSnapshot().pages).toHaveLength(1);
+ close();
+
+ // Still subscribed, but invalidation-only: a reconnect or a session event
+ // with nobody reading must not put a request on a route that renders none.
+ handlers?.onConnected?.({ sub_id: 2, source: 'browser' });
+ handlers?.onSessionActivity?.({
+ session_id: 'session-1',
+ scope_id: null,
+ event: 'show_event',
+ });
+ await Promise.resolve();
+ expect(getShowPages).toHaveBeenCalledTimes(1);
+
+ handlers?.onAuthorizationChanged?.({
+ project_ids: [],
+ resource_kinds: ['show_page'],
+ });
+
+ // Asserted before any re-read resolves: the property must hold for a
+ // revalidation that is slow, failing, or never issued at all, because the
+ // next consumer renders this snapshot synchronously on its first frame.
+ expect(store.getSnapshot().pages).toEqual([]);
+ expect(store.getSnapshot().loaded).toBe(false);
+ // Nothing left to protect and nobody reading, so the subscription ends too.
+ expect(disconnect).toHaveBeenCalledTimes(1);
+ expect(getShowPages).toHaveBeenCalledTimes(1);
+
+ const reopened = store.activate();
+ expect(store.getSnapshot().pages).toEqual([]);
+ revalidation.resolve({ pages: [] });
+ await store.reload();
+ expect(getShowPages).toHaveBeenCalledTimes(2);
+ reopened();
+ });
+
+ it('fences a read already in flight when access changes with nothing reading it', async () => {
+ let handlers: EventHandlers | undefined;
+ const stale = deferred<{ pages: ShowPage[] }>();
+ const getShowPages = vi
+ .fn()
+ .mockImplementationOnce(() => stale.promise)
+ .mockResolvedValueOnce({ pages: [] });
+ const store = new ShowPagesInventoryStore({
+ getShowPages,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ });
+
+ const close = store.activate();
+ const flight = store.reload();
+ close();
+ handlers?.onAuthorizationChanged?.({
+ project_ids: [],
+ resource_kinds: ['show_page'],
+ });
+
+ // The response left the server before the change, so it cannot repopulate
+ // what was just dropped; the same single-flight promise reconciles instead.
+ stale.resolve({ pages: [page({ share_id: 'share-1' })] });
+ await flight;
+ expect(getShowPages).toHaveBeenCalledTimes(2);
+ expect(store.getSnapshot().pages).toEqual([]);
+ });
+
+ it('leaves one live subscription however often the API identity changes', async () => {
+ let connected = 0;
+ let disconnected = 0;
+ const identityCount = 3;
+ const identities = Array.from({ length: identityCount }, () => ({
+ getShowPages: vi.fn().mockResolvedValue({ pages: [page()] }),
+ connectWorkbenchEvents: vi.fn(() => {
+ connected += 1;
+ return () => {
+ disconnected += 1;
+ };
+ }),
+ }) as unknown as ApiContextType);
+
+ // Each identity gets a consumer that reads, retains a snapshot, and leaves:
+ // exactly the state the invalidation-only subscription is kept alive for, and
+ // therefore the state in which a superseded store would strand one.
+ for (const api of identities) {
+ const store = getShowPagesInventoryStore(api);
+ commitShowPagesInventoryStore(api);
+ const close = store.activate();
+ await store.reload();
+ expect(store.getSnapshot().pages).toHaveLength(1);
+ close();
+ }
+
+ // The count is the property: whatever the number of switches, one document
+ // watches once. Asserted as a difference so it cannot be satisfied by never
+ // subscribing in the first place.
+ expect(connected).toBe(identityCount);
+ expect(connected - disconnected).toBe(1);
+
+ // ...and it is the current one that survives, still loaded and still able to
+ // serve the snapshot its consumers render synchronously.
+ const live = getShowPagesInventoryStore(identities[identityCount - 1]);
+ expect(live.getSnapshot().pages).toHaveLength(1);
+ const reopened = live.activate();
+ await live.reload();
+ expect(live.getSnapshot().pages).toHaveLength(1);
+ reopened();
+ });
+
+ it('abandons the read a retired store had in flight', async () => {
+ const stale = deferred<{ pages: ShowPage[] }>();
+ const disconnect = vi.fn();
+ const connectWorkbenchEvents = vi.fn(() => disconnect);
+ const store = new ShowPagesInventoryStore({
+ getShowPages: vi.fn(() => stale.promise),
+ connectWorkbenchEvents,
+ });
+
+ const close = store.activate();
+ const flight = store.reload();
+ close();
+ store.retire();
expect(disconnect).toHaveBeenCalledTimes(1);
+
+ // Retirement fences the read with the same revision bump a mutation uses, so
+ // the response must be abandoned rather than retried: repopulating would
+ // restore a snapshot nothing can render, and the settling read would
+ // resubscribe on its way out.
+ stale.resolve({ pages: [page()] });
+ await flight;
+ expect(store.getSnapshot().pages).toEqual([]);
+ expect(connectWorkbenchEvents).toHaveBeenCalledTimes(1);
});
it('does not refetch when the initial events connection arrives after the activation read', async () => {
@@ -251,6 +410,72 @@ describe('ShowPagesInventoryStore', () => {
release();
});
+ // Same class as the workbench caches: the authorization change IS the
+ // invalidation, and demand decides only whether a replacement read follows it.
+ // Revalidating instead keeps revoked titles, paths and share URLs on screen for
+ // as long as the re-read takes — and indefinitely when it fails, because
+ // ``fetchCurrentRevision`` deliberately preserves the pages it could not replace.
+ it('drops revoked pages at the edge even while a consumer is reading them', async () => {
+ let handlers: EventHandlers | undefined;
+ const getShowPages = vi
+ .fn()
+ .mockResolvedValueOnce({ pages: [page({ share_id: 'share-1' })] })
+ .mockRejectedValueOnce(new Error('read failed'));
+ const store = new ShowPagesInventoryStore({
+ getShowPages,
+ connectWorkbenchEvents: vi.fn((next) => {
+ handlers = next;
+ return vi.fn();
+ }),
+ });
+
+ const release = store.activate();
+ await store.reload();
+ expect(store.getSnapshot().pages).toHaveLength(1);
+
+ handlers?.onAuthorizationChanged?.({
+ project_ids: [],
+ resource_kinds: ['show_page'],
+ });
+
+ // Asserted before the replacement read settles.
+ expect(store.getSnapshot().pages).toEqual([]);
+ expect(store.getSnapshot().loaded).toBe(false);
+ // A consumer is reading, so the drop is followed by a replacement read.
+ expect(getShowPages).toHaveBeenCalledTimes(2);
+
+ // Which fails — and the pages stay dropped, because the drop never depended
+ // on it. ``reload()`` joins that same single-flight rather than starting one.
+ await store.reload();
+ expect(getShowPages).toHaveBeenCalledTimes(2);
+ expect(store.getSnapshot().pages).toEqual([]);
+ release();
+ });
+
+ // Same rule as the workbench providers' looping reads: this one goes round again
+ // only on evidence its own pass produced — a mutation that bumped the revision
+ // under it. A failed request produced none, so it settles and waits for the next
+ // trigger instead of retrying itself against a failing API.
+ it('stops a read whose request failed instead of reading again', async () => {
+ let attempts = 0;
+ const getShowPages = vi.fn(async () => {
+ attempts += 1;
+ if (attempts <= 20) throw new Error('read failed');
+ return { pages: [page()] };
+ });
+ const store = new ShowPagesInventoryStore({
+ getShowPages,
+ connectWorkbenchEvents: vi.fn(() => vi.fn()),
+ });
+
+ const release = store.activate();
+ await store.reload();
+
+ expect(getShowPages).toHaveBeenCalledTimes(1);
+ expect(store.getSnapshot().loaded).toBe(true);
+ release();
+ });
+
it('reconciles after a mutation instead of letting an older read overwrite it', async () => {
const stale = deferred<{ pages: ShowPage[] }>();
const reconciled = deferred<{ pages: ShowPage[] }>();
diff --git a/ui/src/lib/showPagesStore.ts b/ui/src/lib/showPagesStore.ts
index 07fda778a..538920370 100644
--- a/ui/src/lib/showPagesStore.ts
+++ b/ui/src/lib/showPagesStore.ts
@@ -74,6 +74,7 @@ export class ShowPagesInventoryStore {
private disconnectEvents: (() => void) | null = null;
private inFlight: Promise<void> | null = null;
private revision = 0;
+ private retired = false;
constructor(api: ShowPagesInventoryApi) {
this.api = api;
@@ -88,7 +89,7 @@ export class ShowPagesInventoryStore {
activate = (): (() => void) => {
this.activeConsumers += 1;
- if (this.activeConsumers === 1) this.connectEvents();
+ this.syncEventSubscription();
// Every newly visible projection revalidates, but simultaneous activations
// share one request. The retained snapshot remains readable while it runs.
@@ -99,13 +100,55 @@ export class ShowPagesInventoryStore {
if (!active) return;
active = false;
this.activeConsumers -= 1;
- if (this.activeConsumers === 0) {
- this.disconnectEvents?.();
- this.disconnectEvents = null;
- }
+ this.syncEventSubscription();
};
};
+ // The subscription is keyed on whether there is anything to protect, not on
+ // whether anyone is reading. Those are different questions: a consumer needs
+ // revalidation, but a RETAINED snapshot needs invalidation — and a store that
+ // unsubscribed when its last window closed cannot hear the revocation it would
+ // have to act on. Reopening then renders the retained pages synchronously
+ // (titles, paths, share URLs) while ``activate()``'s reload is still in flight,
+ // and ``fetchCurrentRevision`` keeps them when that reload fails, so revoked
+ // metadata can stay on screen indefinitely.
+ //
+ // A read in flight counts: it will produce a snapshot, so the invalidation
+ // window has to stay open across it. This adds no request on any route — while
+ // no consumer reads the inventory the subscription handles invalidation only
+ // (below), and the shared events stream is already open for the shell-wide
+ // badges wherever a snapshot can exist.
+ private shouldWatchEvents(): boolean {
+ return this.activeConsumers > 0 || this.snapshot.pages.length > 0 || this.inFlight !== null;
+ }
+
+ private syncEventSubscription(): void {
+ if (!this.retired && this.shouldWatchEvents()) {
+ this.connectEvents();
+ return;
+ }
+ this.disconnectEvents?.();
+ this.disconnectEvents = null;
+ }
+
+ // A newer ApiContext identity has superseded this store (see the factory
+ // below). "Temporarily unread" and "unreachable" are different states, and
+ // only the retained-snapshot rule above makes the difference matter: keeping a
+ // subscription alive to protect a snapshot is right while a consumer can still
+ // render it, and a leak once none can — the registration is what keeps the
+ // store, its pages and the old api value alive, so every later identity change
+ // would strand another one.
+ //
+ // The consumers that could reach it are switching to the new store in this same
+ // commit, so there is nothing left to protect now rather than later. Fencing
+ // the read in flight matters as much as the disconnect: without it the response
+ // would repopulate `pages` and resubscribe through the ``finally`` below.
+ retire = (): void => {
+ this.retired = true;
+ this.revision += 1;
+ this.syncEventSubscription();
+ };
+
reload = (): Promise<void> => {
if (this.inFlight) return this.inFlight;
this.updateSnapshot({ loading: true });
@@ -145,6 +188,18 @@ export class ShowPagesInventoryStore {
});
};
+ // Access to Show Pages was revoked or re-granted. Advancing the revision fences
+ // any read already in flight — the single-flight loop discards that response and
+ // reconciles again — and the snapshot drops to pre-first-read state, so neither
+ // the consumer reading it now nor the next one to reopen can render revoked
+ // titles, paths or share URLs while a replacement read is slow, or after one
+ // fails. Stronger than revalidating, which depended on a fetch succeeding.
+ private discardAuthorizedPages(): void {
+ this.revision += 1;
+ this.updateSnapshot({ pages: [], loaded: false });
+ this.syncEventSubscription();
+ }
+
private updateSnapshot(patch: Partial<ShowPagesInventorySnapshot>): void {
const next = { ...this.snapshot, ...patch };
if (
@@ -167,6 +222,10 @@ export class ShowPagesInventoryStore {
const revision = this.revision;
try {
const res = (await this.api.getShowPages()) as { pages?: unknown };
+ // Retirement fences the read through the same revision bump a mutation
+ // uses, so it has to be distinguished here: a mutation wants the read
+ // repeated, a disposal wants it abandoned.
+ if (this.retired) return;
if (revision !== this.revision) continue;
this.updateSnapshot({
pages: Array.isArray(res.pages) ? (res.pages as ShowPage[]) : [],
@@ -174,6 +233,7 @@ export class ShowPagesInventoryStore {
});
return;
} catch {
+ if (this.retired) return;
if (revision !== this.revision) continue;
this.updateSnapshot({ loaded: true });
return;
@@ -182,6 +242,9 @@ export class ShowPagesInventoryStore {
} finally {
this.inFlight = null;
this.updateSnapshot({ loading: false });
+ // A consumer may have detached mid-read; now that the snapshot is settled
+ // it is decidable whether anything is left to keep watching for.
+ this.syncEventSubscription();
}
}
@@ -204,9 +267,15 @@ export class ShowPagesInventoryStore {
connected = true;
return;
}
+ // Revalidation, so it may wait for a consumer: activation re-reads
+ // anyway. Only invalidation has to act with nobody reading.
+ if (this.activeConsumers === 0) return;
this.invalidateAndReload();
},
onSessionActivity: (data) => {
+ // Same rule: keeping a retained snapshot merged is revalidation, and the
+ // reload below would be a request on a route that reads nothing.
+ if (this.activeConsumers === 0) return;
const hasPage = this.snapshot.pages.some(
(page) => page.session_id === data.session_id,
);
@@ -233,13 +302,28 @@ export class ShowPagesInventoryStore {
// Normal session/user-message events do not change this inventory.
if (data.event === 'show_event') this.invalidateAndReload();
},
- onAuthorizationChanged: () => this.invalidateAndReload(),
+ // Invalidation, so unlike the two above it is not the consumer count that
+ // decides whether it acts — only whether a replacement READ follows.
+ // Revalidating for an active consumer left the revoked pages in the
+ // snapshot until the re-read landed, and ``fetchCurrentRevision``
+ // deliberately keeps them when it fails, so a failed replacement kept
+ // revoked titles, paths and share URLs readable indefinitely.
+ onAuthorizationChanged: () => {
+ this.discardAuthorizedPages();
+ if (this.activeConsumers > 0) void this.reload();
+ },
});
}
}
const stores = new WeakMap<ApiContextType, ShowPagesInventoryStore>();
+// The store the mounted tree has committed to. One slot, because a document has
+// one ``ApiProvider``: a new context identity (its value is memoized on ``t``, so
+// a locale switch rebuilds it) means the previous store became unreachable, not
+// that a second one went live.
+let committed: { api: ApiContextType; store: ShowPagesInventoryStore } | null = null;
+
export function getShowPagesInventoryStore(api: ApiContextType): ShowPagesInventoryStore {
let store = stores.get(api);
if (!store) {
@@ -248,3 +332,26 @@ export function getShowPagesInventoryStore(api: ApiContextType): ShowPagesInvent
}
return store;
}
+
+/** Record the identity the tree has committed to, retiring the store a previous
+ * identity handed out.
+ *
+ * Disposal belongs to the commit phase, not to the render that creates the new
+ * store: a re-render can be double-invoked or discarded, and closing the
+ * subscription of a store the mounted tree is still reading would lose the
+ * invalidation it is kept open for. Every consumer of a changed context value
+ * re-renders in one commit, so by the time any of their effects runs, all of
+ * them hold this store — which makes the call idempotent and its ordering among
+ * them irrelevant. A document with no inventory consumer never calls it and
+ * never needs to: nothing was created, so nothing was superseded.
+ */
+export function commitShowPagesInventoryStore(api: ApiContextType): void {
+ if (committed?.api === api) return;
+ if (committed) {
+ // Dropping the WeakMap entry with it keeps the factory from ever handing a
+ // retired store to a consumer, should an identity somehow come back.
+ stores.delete(committed.api);
+ committed.store.retire();
+ }
+ committed = { api, store: getShowPagesInventoryStore(api) };
+}
diff --git a/ui/src/lib/useConsumerActivation.ts b/ui/src/lib/useConsumerActivation.ts
new file mode 100644
index 000000000..356fae632
--- /dev/null
+++ b/ui/src/lib/useConsumerActivation.ts
@@ -0,0 +1,66 @@
+import { useCallback, useMemo, useRef, useState } from 'react';
+
+export interface ConsumerActivation {
+ /** True while at least one consumer has declared it actually reads this data.
+ * This is React state, so it lands one render AFTER the activation — which is
+ * what makes it usable as an effect dependency. */
+ active: boolean;
+ /** The same answer read straight from the counter, for code running outside
+ * render: effects, event listeners, SSE callbacks.
+ *
+ * Consumers activate from their own effects, and React runs child effects
+ * before the provider's, so this is already accurate in the provider's mount
+ * effect while ``active`` is still false. Which one to reach for follows from
+ * what the code has to decide:
+ *
+ * * skip a request → ``active`` is enough; the second render triggers it.
+ * * CHOOSE between two requests → ``isActive()``, because the choice is made
+ * in the first commit and ``active`` is still false there.
+ * * react to the demand EDGE (demand appearing, and especially demand going
+ * away) → BOTH: ``active`` in the dependency list, since a stable function
+ * identity never re-runs an effect, and ``isActive()`` in the body to keep
+ * that first commit correct. An effect that only closes over ``isActive``
+ * silently answers "was there demand when I mounted", which reads as
+ * correct for as long as nobody navigates. */
+ isActive: () => boolean;
+ /** Effect body: call from a consumer's ``useEffect`` and return the result as
+ * its cleanup. Balanced activate/release pairs in one commit batch to a net
+ * no-op, so a consumer whose deps churn doesn't re-trigger a bootstrap. */
+ activate: () => () => void;
+}
+
+/** Refcounted "someone is actually reading this" signal for a provider mounted
+ * ABOVE the router.
+ *
+ * Such a provider is mounted once per document and never remounts on
+ * navigation — which is what makes its cache worth having, and also what makes
+ * a mount-time bootstrap fire on every route, including the routes that never
+ * read it. Counting active consumers turns that mount-driven fetch into a
+ * demand-driven one without moving the provider into the router or splitting
+ * its cache per route.
+ *
+ * Same contract as ``ShowPagesInventoryStore.activate()``, expressed for a
+ * provider that keeps its state in React rather than in an external store. */
+export function useConsumerActivation(): ConsumerActivation {
+ const [consumers, setConsumers] = useState(0);
+ // The same count, committed synchronously by activate() so an effect or a
+ // listener can read it before the state update renders. Both are updated
+ // together and never diverge by more than that one render.
+ const consumersRef = useRef(0);
+ const activate = useCallback(() => {
+ consumersRef.current += 1;
+ setConsumers((count) => count + 1);
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ consumersRef.current = Math.max(0, consumersRef.current - 1);
+ setConsumers((count) => Math.max(0, count - 1));
+ };
+ }, []);
+ const isActive = useCallback(() => consumersRef.current > 0, []);
+ return useMemo(
+ () => ({ active: consumers > 0, isActive, activate }),
+ [activate, consumers, isActive],
+ );
+}
diff --git a/ui/src/lib/useNewSession.ts b/ui/src/lib/useNewSession.ts
index 7f13a675a..0fe57452d 100644
--- a/ui/src/lib/useNewSession.ts
+++ b/ui/src/lib/useNewSession.ts
@@ -128,7 +128,14 @@ export function createLatestAgentProjectionLoader(
// in the consumer.
export function useNewSession({ active = true, loadErrorText, createFailedText }: UseNewSessionOptions): NewSessionState {
const api = useApi();
- const { projects: rawProjects, projectsError, createSessionForProject, upsertProjectToTop } = useWorkbenchProjectsTree();
+ // `active` already gates the agent projection below; pass it to the tree too.
+ // NewSessionSheet is mounted shell-wide, so an unconditional read would make
+ // the tree bootstrap on every route again — exactly what activation prevents.
+ const {
+ projects: rawProjects,
+ projectsError,
+ createSessionForProject,
+ } = useWorkbenchProjectsTree({ active });
const [selectedId, setSelectedId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [sending, setSending] = useState(false);
@@ -309,13 +316,11 @@ export function useNewSession({ active = true, loadErrorText, createFailedText }
[sending, loaded, target, routeForCreate, agents, createSessionForProject, createFailedText],
);
- const upsertSelectProject = useCallback(
- (project: WorkbenchProject) => {
- upsertProjectToTop(project); // updates the shared tree (sidebar + Projects page) too
- setSelectedId(project.id);
- },
- [upsertProjectToTop],
- );
+ // The dialog already committed the row through the provider (fenced against a
+ // concurrent authorization change); this only points the sheet at it.
+ const upsertSelectProject = useCallback((project: WorkbenchProject) => {
+ setSelectedId(project.id);
+ }, []);
// Surface a project-load failure (provider-level) when we have no list, plus any
// create error raised here.