Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
perf(apps): shared show-pages inventory store — single-flight + stale-while-revalidate (§7.1l) (#929)
Call Whiteac74fe3efbf2
diff --git a/docs/plans/dock-pinned-show-page-apps.md b/docs/plans/dock-pinned-show-page-apps.mdindex bc184d989..cdad9dfa1 100644--- a/docs/plans/dock-pinned-show-page-apps.md+++ b/docs/plans/dock-pinned-show-page-apps.md@@ -735,6 +735,30 @@ press target must remain a filling non-interactive child (icon `<imgdraggable={false}>` without `pointer-events-none`, letter wrapped in a filling `<span>`);see the invariant comment in `showPageAvatarTile.tsx` (§7.1i forensics).+### 7.1l Shared Show-Pages inventory cache (owner 2026-07-17 00:11 — duplicate fetches + icon flash)++Owner-observed symptoms on rc5: opening the Library/Dock fires **two identical+`/api/show-pages` requests**, and app icons **flash** (letter avatar first, real icon after a+delay) on every open. Root cause (code-confirmed): `useShowPageInventory` is per-mount+state — five consumers (Dock, WindowLayer, MobileDockDrawer, ⌘K search, Library) each own an+instance, each fetches on mount AND on events-(re)connect, and each starts from `pages=[]` so+tiles paint letters until the metadata roundtrip completes. The icon FILES are already+strongly cached (content-token + immutable, §7.1f) — the flash is metadata latency, not image+download. This is the shared-inventory-context promotion deferred by rule-of-three at #903;+five consumers now exist.++Fix (structural):+- ONE workbench-wide shared inventory store/provider: single source of truth, ONE+ workbench-events subscription, single-flight fetch dedup (at most one `/api/show-pages`+ in flight, concurrent requesters share the promise).+- Stale-while-revalidate: consumers render the last-known inventory instantly (icons render+ immediately from cached `icon_version` — no flash within a session) and a background+ refresh reconciles. First-ever load still letter→icon (acceptable).+- Consumer hook API stays as-is or shrinks (adapter over the store); mutation helpers+ (mergePage/removePage/replaceTitleIfCurrent/reload) keep their semantics against the+ shared store. ShowPageShareControl's separate usage joins the same store.+- No backend changes; icon endpoint caching unchanged.+### 7.2 Becoming an app: the ladder (owner Q&A 2026-07-13)Pinning **is** installing — no separate ceremony. Two entrances, one action:diff --git a/ui/src/components/useShowPages.ts b/ui/src/components/useShowPages.tsindex 1f3a0fdca..73a3ca026 100644--- a/ui/src/components/useShowPages.ts+++ b/ui/src/components/useShowPages.ts@@ -1,148 +1,46 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';import { useTranslation } from 'react-i18next';import { useApi } from '../context/ApiContext';import { useToast } from '../context/ToastContext';import type { ShowPageLinkInfo } from '../lib/showPageLinks';--export type Visibility = 'private' | 'public' | 'offline';--export interface ShowPage {- session_id: string;- visibility: Visibility;- title: string | null;- platform: string | null;- agent: string | null;- path: string;- /** Opaque cache token for the page's own HTML icon (§7.1f): non-null iff a- * servable icon exists, and it changes when the icon file changes. Doubles as- * the has-icon signal and is appended to the icon URL as `?v=<token>`. */- icon_version: string | null;- active_url: string | null;- private_url: string | null;- public_url: string | null;- url_available: boolean;- share_id: string | null;- offline: boolean;- offline_at: string | null;- created_at: string;- updated_at: string;-}--type ShowPagePatch = Pick<ShowPage, 'session_id'> & Partial<ShowPage>;--export function replaceShowPageTitleIfCurrent(- pages: ShowPage[],- sessionId: string,- expectedTitle: string | null,- nextTitle: string | null,-): ShowPage[] {- const index = pages.findIndex(- (page) => page.session_id === sessionId && page.title === expectedTitle,- );- if (index < 0) return pages;- const next = [...pages];- next[index] = { ...next[index], title: nextTitle };- return next;-}--// Read-side Show Page inventory shared by the Library, Dock, and global search.-// Session-title edits already publish `session.activity`; subscribe here so each-// mounted projection prefers the live title while `title_snapshot` remains only-// an offline/missing-page fallback.+import {+ getShowPagesInventoryStore,+ type ShowPage,+ type Visibility,+} from '../lib/showPagesStore';++export { replaceShowPageTitleIfCurrent } from '../lib/showPagesStore';+export type { ShowPage, Visibility } from '../lib/showPagesStore';++// Stable hook adapter over the workbench-wide external store. The synchronous+// snapshot is what lets a remounted panel paint known icon_version values on its+// first render; activation then performs a shared background revalidation.export function useShowPageInventory(enabled = true) {const api = useApi();- const [pages, setPages] = useState<ShowPage[]>([]);- const [loading, setLoading] = useState(false);- const [loaded, setLoaded] = useState(false);- const [loadRequest, setLoadRequest] = useState(0);- const loadSeqRef = useRef(0);- const revisionRef = useRef(0);- const pagesRef = useRef(pages);- const loadedRef = useRef(loaded);- pagesRef.current = pages;- loadedRef.current = loaded;-- const requestLoad = useCallback(() => setLoadRequest((request) => request + 1), []);-- const mergePage = useCallback((next: ShowPagePatch) => {- revisionRef.current += 1;- setPages((prev) =>- prev.map((page) => (page.session_id === next.session_id ? { ...page, ...next } : page)),- );- }, []);-- const removePage = useCallback((sessionId: string) => {- revisionRef.current += 1;- setPages((prev) => prev.filter((page) => page.session_id !== sessionId));- }, []);-- const replaceTitleIfCurrent = useCallback(- (sessionId: string, expectedTitle: string | null, nextTitle: string | null) => {- revisionRef.current += 1;- setPages((prev) =>- replaceShowPageTitleIfCurrent(prev, sessionId, expectedTitle, nextTitle),- );- },- [],+ const store = useMemo(() => getShowPagesInventoryStore(api), [api]);+ const { pages, loading, loaded } = useSyncExternalStore(+ store.subscribe,+ store.getSnapshot,+ store.getSnapshot,);- const load = useCallback(async () => {- if (!enabled) return;- const seq = (loadSeqRef.current += 1);- const revision = revisionRef.current;- setLoading(true);- try {- const res = (await api.getShowPages()) as { pages?: unknown };- if (seq !== loadSeqRef.current) return;- if (revision !== revisionRef.current) {- requestLoad();- return;- }- setPages(Array.isArray(res.pages) ? (res.pages as ShowPage[]) : []);- setLoaded(true);- } catch {- if (seq === loadSeqRef.current) setLoaded(true);- } finally {- if (seq === loadSeqRef.current) setLoading(false);- }- }, [api, enabled, requestLoad]);-useEffect(() => {- if (enabled) void load();- }, [enabled, load, loadRequest]);-- useEffect(() => {- if (!enabled) return;- return api.connectWorkbenchEvents({- onConnected: requestLoad,- onSessionActivity: (data) => {- if (data.event === 'archived') {- if (pagesRef.current.some((page) => page.session_id === data.session_id)) {- removePage(data.session_id);- } else if (!loadedRef.current) {- requestLoad();- }- return;- }- if (data.event === 'updated' && Object.prototype.hasOwnProperty.call(data, 'title')) {- if (pagesRef.current.some((page) => page.session_id === data.session_id)) {- mergePage({ session_id: data.session_id, title: data.title ?? null });- } else if (!loadedRef.current) {- requestLoad();- }- return;- }- // Runtime Show activity can materialize a page outside this browser.- // Normal session/user-message events do not change this inventory.- if (data.event === 'show_event') requestLoad();- },- });- }, [api, enabled, mergePage, removePage, requestLoad]);-- const reload = requestLoad;-- return { pages, loading, loaded, mergePage, replaceTitleIfCurrent, reload };+ if (enabled) return store.activate();+ }, [enabled, store]);++ const reload = useCallback(() => {+ if (enabled) void store.reload();+ }, [enabled, store]);++ return {+ pages,+ loading,+ loaded,+ mergePage: store.mergePage,+ replaceTitleIfCurrent: store.replaceTitleIfCurrent,+ reload,+ };}// The Show Pages inventory: fetch + the visibility / share-id / rotate mutations,diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex e3f49129a..9af9f24e0 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useRef, useState } from 'react';+import React, { useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Check, Copy, LayoutGrid, Loader2, Plus, Share2 } from 'lucide-react';@@ -13,10 +13,11 @@ import { copyTextToClipboard } from '../../lib/utils';import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';import { ShowPageShareIdField } from './ShowPageShareIdField';+import { useShowPageInventory, type ShowPage } from '../useShowPages';type ShowPagePayload = ShowPageLinkInfo & {url_available: boolean;- url_guidance: string | null;+ url_guidance?: string | null;offline: boolean;// The live session title (joined server-side by ensureShowPage); labels the// pinned-app confirmation. Null for untitled IM-dispatch sessions.@@ -39,8 +40,29 @@ export const ShowPageShareControl: React.FC<{const { t } = useTranslation();const api = useApi();const dock = useDock();+ const { pages, mergePage, reload } = useShowPageInventory();+ const inventoryPage = pages.find((page) => page.session_id === sessionId);const [open, setOpen] = useState(false);- const [payload, setPayload] = useState<ShowPagePayload | null>(null);+ const [localPayload, setLocalPayload] = useState<ShowPagePayload | null>(null);+ const payload = useMemo<ShowPagePayload | null>(() => {+ const local = localPayload?.session_id === sessionId ? localPayload : null;+ if (!inventoryPage) return local;+ if (!local) return inventoryPage as ShowPagePayload;++ // A mutation/ensure response is newer than the retained inventory until its+ // merge reaches this render. Prefer it while the share identity differs so+ // onPayloadChange never re-points ChatPage at a revoked cached URL. Once the+ // shared store catches up, inventory resumes as the live source of truth.+ const inventoryCaughtUp =+ inventoryPage.visibility === local.visibility &&+ inventoryPage.active_url === local.active_url &&+ inventoryPage.share_id === local.share_id &&+ inventoryPage.offline === local.offline &&+ inventoryPage.url_available === local.url_available;+ return (inventoryCaughtUp+ ? { ...local, ...inventoryPage }+ : { ...inventoryPage, ...local }) as ShowPagePayload;+ }, [inventoryPage, localPayload, sessionId]);const [loading, setLoading] = useState(false);const [busy, setBusy] = useState(false);const [copied, setCopied] = useState(false);@@ -49,10 +71,25 @@ export const ShowPageShareControl: React.FC<{// before it resolved. A refresh (read) only applies if no newer request has// superseded it. reqSeq orders the reads; a mutation bumps it on resolve.const reqSeq = useRef(0);+ const hasObservedPayloadRef = useRef(false);++ const applyPayload = (next: ShowPagePayload) => {+ setLocalPayload(next);+ mergePage(next as ShowPage);+ };useEffect(() => {- if (payload) onPayloadChange?.(payload);- }, [payload, onPayloadChange]);+ if (!payload) return;+ const hasFreshLocalPayload = localPayload?.session_id === sessionId;+ if (!hasObservedPayloadRef.current) {+ hasObservedPayloadRef.current = true;+ // ChatPage just resolved ensureShowPage before mounting this control. Do+ // not overwrite that fresh route with the retained inventory's first+ // snapshot; a revalidated store update or local response may notify it.+ if (!hasFreshLocalPayload) return;+ }+ onPayloadChange?.(payload);+ }, [localPayload, onPayloadChange, payload, sessionId]);// If we unmount while open (a route/session change tears down Show Page mode),// Radix won't fire onOpenChange, so report closed here — otherwise the chat@@ -84,7 +121,9 @@ export const ShowPageShareControl: React.FC<{api.ensureShowPage(sessionId).then((res: ShowPagePayload) => {- if (seq === reqSeq.current) setPayload(res);+ if (seq !== reqSeq.current) return;+ applyPayload(res);+ if (!inventoryPage) reload();}).catch(() => undefined).finally(() => setLoading(false));@@ -103,7 +142,7 @@ export const ShowPageShareControl: React.FC<{.then((res: ShowPagePayload) => {// Authoritative server state: always apply it, and invalidate any// in-flight refresh read so a stale read can't revert us afterwards.- setPayload(res);+ applyPayload(res);reqSeq.current += 1;}).catch(() => undefined)@@ -221,7 +260,7 @@ export const ShowPageShareControl: React.FC<{onSaved={(res) => {// Authoritative server state, same handling as a visibility// change: apply it and invalidate any in-flight refresh read.- setPayload(res as ShowPagePayload);+ applyPayload(res as ShowPagePayload);reqSeq.current += 1;}}/>diff --git a/ui/src/lib/showPagesStore.test.ts b/ui/src/lib/showPagesStore.test.tsnew file mode 100644index 000000000..b1f0d5d1e--- /dev/null+++ b/ui/src/lib/showPagesStore.test.ts@@ -0,0 +1,236 @@+import { describe, expect, it, vi } from 'vitest';++import {+ ShowPagesInventoryStore,+ type ShowPage,+ type ShowPagesInventoryApi,+} from './showPagesStore';++const page = (overrides: Partial<ShowPage> = {}): ShowPage => ({+ session_id: 'session-1',+ visibility: 'private',+ title: 'Dashboard',+ platform: null,+ agent: null,+ path: '/tmp/show',+ icon_version: 'icon-v1',+ active_url: '/show/session-1/',+ private_url: '/show/session-1/',+ public_url: null,+ url_available: true,+ share_id: null,+ offline: false,+ offline_at: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ ...overrides,+});++const 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 };+};++type EventHandlers = Parameters<ShowPagesInventoryApi['connectWorkbenchEvents']>[0];++describe('ShowPagesInventoryStore', () => {+ it('single-flights simultaneous consumers and owns one events subscription', async () => {+ const response = deferred<{ pages: ShowPage[] }>();+ const disconnect = vi.fn();+ const api: ShowPagesInventoryApi = {+ getShowPages: vi.fn(() => response.promise),+ connectWorkbenchEvents: vi.fn(() => disconnect),+ };+ const store = new ShowPagesInventoryStore(api);++ const releaseFirst = store.activate();+ const releaseSecond = store.activate();+ const firstFlight = store.reload();++ expect(api.getShowPages).toHaveBeenCalledTimes(1);+ expect(api.connectWorkbenchEvents).toHaveBeenCalledTimes(1);+ expect(store.reload()).toBe(firstFlight);++ response.resolve({ pages: [page()] });+ await firstFlight;+ expect(store.getSnapshot().pages).toHaveLength(1);++ releaseFirst();+ expect(disconnect).not.toHaveBeenCalled();+ releaseSecond();+ expect(disconnect).toHaveBeenCalledTimes(1);+ });++ it('does not refetch when the initial events connection arrives after the activation read', async () => {+ let handlers: EventHandlers | undefined;+ const getShowPages = vi.fn().mockResolvedValue({ pages: [page()] });+ const store = new ShowPagesInventoryStore({+ getShowPages,+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ });++ const release = store.activate();+ await store.reload();+ handlers?.onConnected?.({ sub_id: 1, source: 'browser' });+ await Promise.resolve();+ expect(getShowPages).toHaveBeenCalledTimes(1);++ handlers?.onConnected?.({ sub_id: 2, source: 'browser' });+ await store.reload();+ expect(getShowPages).toHaveBeenCalledTimes(2);+ release();+ });++ it('serves stale icon metadata immediately on reopen and revalidates in the background', async () => {+ const initial = deferred<{ pages: ShowPage[] }>();+ const refresh = deferred<{ pages: ShowPage[] }>();+ const getShowPages = vi+ .fn()+ .mockImplementationOnce(() => initial.promise)+ .mockImplementationOnce(() => refresh.promise);+ const api: ShowPagesInventoryApi = {+ getShowPages,+ connectWorkbenchEvents: vi.fn(() => vi.fn()),+ };+ const store = new ShowPagesInventoryStore(api);++ const close = store.activate();+ const initialFlight = store.reload();+ initial.resolve({ pages: [page({ icon_version: 'cached-icon' })] });+ await initialFlight;+ close();++ const closeReopened = store.activate();+ const reopened = store.getSnapshot();+ expect(reopened.pages[0].icon_version).toBe('cached-icon');+ expect(reopened.loaded).toBe(true);+ expect(reopened.loading).toBe(true);+ expect(getShowPages).toHaveBeenCalledTimes(2);++ const refreshFlight = store.reload();+ refresh.resolve({ pages: [page({ icon_version: 'fresh-icon' })] });+ await refreshFlight;+ expect(store.getSnapshot().pages[0].icon_version).toBe('fresh-icon');+ closeReopened();+ });++ it('fans title, archive, and show events out to every subscriber', async () => {+ let handlers: EventHandlers | undefined;+ const getShowPages = vi+ .fn()+ .mockResolvedValueOnce({ pages: [page()] })+ .mockResolvedValueOnce({ pages: [] });+ const api: ShowPagesInventoryApi = {+ getShowPages,+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ };+ const store = new ShowPagesInventoryStore(api);+ const firstConsumer = vi.fn();+ const secondConsumer = vi.fn();+ store.subscribe(firstConsumer);+ store.subscribe(secondConsumer);+ const release = store.activate();+ await store.reload();+ firstConsumer.mockClear();+ secondConsumer.mockClear();++ handlers?.onSessionActivity?.({+ session_id: 'session-1',+ scope_id: null,+ event: 'updated',+ title: 'Renamed',+ });+ expect(store.getSnapshot().pages[0].title).toBe('Renamed');+ expect(firstConsumer).toHaveBeenCalledTimes(1);+ expect(secondConsumer).toHaveBeenCalledTimes(1);++ handlers?.onSessionActivity?.({+ session_id: 'session-1',+ scope_id: null,+ event: 'archived',+ });+ expect(store.getSnapshot().pages).toEqual([]);+ expect(firstConsumer).toHaveBeenCalledTimes(2);+ expect(secondConsumer).toHaveBeenCalledTimes(2);++ handlers?.onSessionActivity?.({+ session_id: 'session-2',+ scope_id: null,+ event: 'show_event',+ });+ await store.reload();+ expect(getShowPages).toHaveBeenCalledTimes(2);+ release();+ });++ it('queues a show-event reconcile behind an older in-flight read', async () => {+ let handlers: EventHandlers | undefined;+ const stale = deferred<{ pages: ShowPage[] }>();+ const getShowPages = vi+ .fn()+ .mockImplementationOnce(() => stale.promise)+ .mockResolvedValueOnce({ pages: [page({ session_id: 'session-2' })] });+ const store = new ShowPagesInventoryStore({+ getShowPages,+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ });++ const release = store.activate();+ const flight = store.reload();+ handlers?.onSessionActivity?.({+ session_id: 'session-2',+ scope_id: null,+ event: 'show_event',+ });+ expect(store.reload()).toBe(flight);++ stale.resolve({ pages: [] });+ await flight;+ expect(getShowPages).toHaveBeenCalledTimes(2);+ expect(store.getSnapshot().pages[0].session_id).toBe('session-2');+ 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[] }>();+ const getShowPages = vi+ .fn()+ .mockResolvedValueOnce({ pages: [page()] })+ .mockImplementationOnce(() => stale.promise)+ .mockImplementationOnce(() => reconciled.promise);+ const store = new ShowPagesInventoryStore({+ getShowPages,+ connectWorkbenchEvents: vi.fn(() => vi.fn()),+ });++ const release = store.activate();+ await store.reload();+ const refreshFlight = store.reload();+ store.mergePage({ session_id: 'session-1', visibility: 'public' });+ expect(store.getSnapshot().pages[0].visibility).toBe('public');++ stale.resolve({ pages: [page({ visibility: 'private' })] });+ await Promise.resolve();+ expect(getShowPages).toHaveBeenCalledTimes(3);++ reconciled.resolve({ pages: [page({ visibility: 'public' })] });+ await refreshFlight;+ expect(store.getSnapshot().pages[0].visibility).toBe('public');+ release();+ });+});diff --git a/ui/src/lib/showPagesStore.ts b/ui/src/lib/showPagesStore.tsnew file mode 100644index 000000000..a3ec612b1--- /dev/null+++ b/ui/src/lib/showPagesStore.ts@@ -0,0 +1,245 @@+import type { ApiContextType } from '../context/ApiContext';++export type Visibility = 'private' | 'public' | 'offline';++export interface ShowPage {+ session_id: string;+ visibility: Visibility;+ title: string | null;+ platform: string | null;+ agent: string | null;+ path: string;+ /** Opaque cache token for the page's own HTML icon (§7.1f): non-null iff a+ * servable icon exists, and it changes when the icon file changes. Doubles as+ * the has-icon signal and is appended to the icon URL as `?v=<token>`. */+ icon_version: string | null;+ active_url: string | null;+ private_url: string | null;+ public_url: string | null;+ url_available: boolean;+ url_guidance?: string | null;+ share_id: string | null;+ offline: boolean;+ offline_at: string | null;+ created_at: string;+ updated_at: string;+}++export type ShowPagePatch = Pick<ShowPage, 'session_id'> & Partial<ShowPage>;++export interface ShowPagesInventorySnapshot {+ pages: ShowPage[];+ loading: boolean;+ loaded: boolean;+}++export type ShowPagesInventoryApi = Pick<+ ApiContextType,+ 'getShowPages' | 'connectWorkbenchEvents'+>;++type Listener = () => void;++export function replaceShowPageTitleIfCurrent(+ pages: ShowPage[],+ sessionId: string,+ expectedTitle: string | null,+ nextTitle: string | null,+): ShowPage[] {+ const index = pages.findIndex(+ (page) => page.session_id === sessionId && page.title === expectedTitle,+ );+ if (index < 0) return pages;+ const next = [...pages];+ next[index] = { ...next[index], title: nextTitle };+ return next;+}++// One store is shared by every inventory projection under an ApiProvider. It+// retains its last snapshot between panel mounts, while activation only owns one+// workbench-events subscription and every refresh joins the same in-flight work.+export class ShowPagesInventoryStore {+ private readonly api: ShowPagesInventoryApi;+ private snapshot: ShowPagesInventorySnapshot = {+ pages: [],+ loading: false,+ loaded: false,+ };+ private readonly listeners = new Set<Listener>();+ private activeConsumers = 0;+ private disconnectEvents: (() => void) | null = null;+ private inFlight: Promise<void> | null = null;+ private revision = 0;++ constructor(api: ShowPagesInventoryApi) {+ this.api = api;+ }++ getSnapshot = (): ShowPagesInventorySnapshot => this.snapshot;++ subscribe = (listener: Listener): (() => void) => {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ };++ activate = (): (() => void) => {+ this.activeConsumers += 1;+ if (this.activeConsumers === 1) this.connectEvents();++ // Every newly visible projection revalidates, but simultaneous activations+ // share one request. The retained snapshot remains readable while it runs.+ void this.reload();++ let active = true;+ return () => {+ if (!active) return;+ active = false;+ this.activeConsumers -= 1;+ if (this.activeConsumers === 0) {+ this.disconnectEvents?.();+ this.disconnectEvents = null;+ }+ };+ };++ reload = (): Promise<void> => {+ if (this.inFlight) return this.inFlight;+ this.updateSnapshot({ loading: true });+ this.inFlight = this.fetchCurrentRevision();+ return this.inFlight;+ };++ mergePage = (next: ShowPagePatch): void => {+ this.revision += 1;+ this.updateSnapshot({+ pages: this.snapshot.pages.map((page) =>+ page.session_id === next.session_id ? { ...page, ...next } : page,+ ),+ });+ };++ removePage = (sessionId: string): void => {+ this.revision += 1;+ this.updateSnapshot({+ pages: this.snapshot.pages.filter((page) => page.session_id !== sessionId),+ });+ };++ replaceTitleIfCurrent = (+ sessionId: string,+ expectedTitle: string | null,+ nextTitle: string | null,+ ): void => {+ this.revision += 1;+ this.updateSnapshot({+ pages: replaceShowPageTitleIfCurrent(+ this.snapshot.pages,+ sessionId,+ expectedTitle,+ nextTitle,+ ),+ });+ };++ private updateSnapshot(patch: Partial<ShowPagesInventorySnapshot>): void {+ const next = { ...this.snapshot, ...patch };+ if (+ next.pages === this.snapshot.pages &&+ next.loading === this.snapshot.loading &&+ next.loaded === this.snapshot.loaded+ ) {+ return;+ }+ this.snapshot = next;+ this.listeners.forEach((listener) => listener());+ }++ private async fetchCurrentRevision(): Promise<void> {+ try {+ // A mutation that lands during the read invalidates that response. Keep+ // the same single-flight promise alive and reconcile again so no stale+ // response can undo an optimistic or events-driven update.+ while (true) {+ const revision = this.revision;+ try {+ const res = (await this.api.getShowPages()) as { pages?: unknown };+ if (revision !== this.revision) continue;+ this.updateSnapshot({+ pages: Array.isArray(res.pages) ? (res.pages as ShowPage[]) : [],+ loaded: true,+ });+ return;+ } catch {+ if (revision !== this.revision) continue;+ this.updateSnapshot({ loaded: true });+ return;+ }+ }+ } finally {+ this.inFlight = null;+ this.updateSnapshot({ loading: false });+ }+ }++ private invalidateAndReload(): void {+ // An event can arrive after the server produced the response currently in+ // flight. Advancing the revision makes that response retry inside the same+ // single-flight promise instead of either accepting it or starting overlap.+ this.revision += 1;+ void this.reload();+ }++ private connectEvents(): void {+ if (this.disconnectEvents) return;+ let connected = false;+ this.disconnectEvents = this.api.connectWorkbenchEvents({+ onConnected: () => {+ // activate() already revalidates this subscription's initial connection.+ // Only later callbacks are reconnects that may cover a missed event gap.+ if (!connected) {+ connected = true;+ return;+ }+ this.invalidateAndReload();+ },+ onSessionActivity: (data) => {+ const hasPage = this.snapshot.pages.some(+ (page) => page.session_id === data.session_id,+ );+ if (data.event === 'archived') {+ if (hasPage) this.removePage(data.session_id);+ else if (!this.snapshot.loaded) void this.reload();+ return;+ }+ if (+ data.event === 'updated' &&+ Object.prototype.hasOwnProperty.call(data, 'title')+ ) {+ if (hasPage) {+ this.mergePage({+ session_id: data.session_id,+ title: data.title ?? null,+ });+ } else if (!this.snapshot.loaded) {+ void this.reload();+ }+ return;+ }+ // Runtime Show activity can materialize a page outside this browser.+ // Normal session/user-message events do not change this inventory.+ if (data.event === 'show_event') this.invalidateAndReload();+ },+ });+ }+}++const stores = new WeakMap<ApiContextType, ShowPagesInventoryStore>();++export function getShowPagesInventoryStore(api: ApiContextType): ShowPagesInventoryStore {+ let store = stores.get(api);+ if (!store) {+ store = new ShowPagesInventoryStore(api);+ stores.set(api, store);+ }+ return store;+}