diff --git a/.changeset/28085-home-boot-reads-once.md b/.changeset/28085-home-boot-reads-once.md new file mode 100644 index 00000000000..0ae321cdd06 --- /dev/null +++ b/.changeset/28085-home-boot-reads-once.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +--- + +fix(app-shell): Home sends the deployment notice, authorized-clients and API-key reads once per load + +Clause-②: no +Metadata-protocol: none + +On a built Console, a cold load of Home sent `GET /api/settings/deployment/notice` twice and `GET /api/v1/auth/authorized-clients` and the `sys_api_key` list three times each. The repeats were not concurrent, so sharing an in-flight request could not remove them. Each had its own cause: + +- **Home was mounted twice.** Home waits on the launcher's `pending` flag so that it never draws an app tile that `/me/apps` then hides. The `LauncherAppsProvider` set that flag from its effect, which runs after the first commit. So the first frame had nothing pending and nothing narrowed: Home drew its page, then switched to its loading state, then drew the page again. Everything inside it mounted twice, and the deployment notice and the Connect an AI Assistant card sent their reads twice. The first read is now `pending` from the render that makes it due. Home draws its page once, after the answer, and a hidden app's tile is never drawn in that first frame. +- **Two readers of one answer.** Home draws the Connect an AI Assistant card and the administrator's first-run checklist together. Both read "has this person connected an assistant" through `useConnectedAccess`, and each sent its own two requests. Every reader mounted at the same time now shares one pair of reads. A change to either record re-reads it once for all of them. The shared answer is dropped with its last reader, so a page mounted later reads afresh. + +A list page load already read every URL once on a built Console, so nothing changes there. diff --git a/ui/apps/console/src/__tests__/App.listPageBootReadsOnce-28085.test.tsx b/ui/apps/console/src/__tests__/App.listPageBootReadsOnce-28085.test.tsx new file mode 100644 index 00000000000..ded3cd9372a --- /dev/null +++ b/ui/apps/console/src/__tests__/App.listPageBootReadsOnce-28085.test.tsx @@ -0,0 +1,181 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#28085 — a console list page load asks `auth/get-session`, + * `meta/app`, `auth/me/permissions` and `me/apps` once each. + * + * ## What is real here + * + * The boot order `main.tsx` runs: the pre-React `preflightAuth` validating the + * stored Bearer, then `App` — the real `AuthProvider` with its own better-auth + * client, `AuthGuard`, `ProtectedRoute`, `ConsoleShell`, `ConnectedShell` with + * the real `ObjectStackAdapter` and `MetadataProvider`, `RequireOrganization`, + * `ConsolePermissionsScope` (the `/me/permissions` provider) and the console's + * `LauncherAppsProvider` (`/me/apps`). The network is one stubbed global + * `fetch` that records every URL and answers it, so a count is of requests that + * would reach the wire. No `React.StrictMode`: a built console does not replay + * effects, and the doubling this card was filed on was that replay behind the + * Vite dev server. + * + * The app's own content is a stub: the four reads under test are the shell's, + * which every list page shares, not the list view's. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor, act } from '@testing-library/react'; +import type { ReactNode } from 'react'; +// Paid at collection, not inside the mock factory's clocked first call. +import '@object-ui/react'; +import '@object-ui/app-shell'; + +const ORG = { id: 'org_1', name: 'Acme', slug: 'acme' }; +const USER = { id: 'u1', name: 'Ada', email: 'ada@example.test' }; +const TOKEN = 'tok_valid'; +const SESSION_BODY = { + user: USER, + session: { id: 's_1', userId: USER.id, token: TOKEN, activeOrganizationId: ORG.id, expiresAt: '2099-01-01T00:00:00.000Z' }, +}; + +/** The one app the deployment serves; the list page under test is one of its objects. */ +const APPS = [{ name: 'crm', label: 'CRM', active: true, isDefault: true }]; +const LIST_PAGE = '/apps/crm/crm_contact'; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); +} + +const urlOf = (input: RequestInfo | URL): string => + typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + +const calls: string[] = []; +const fetchStub = vi.fn(async (input: RequestInfo | URL) => { + const url = urlOf(input); + calls.push(url); + if (url.includes('/auth/get-session')) return json(SESSION_BODY); + if (url.includes('/auth/organization/list')) return json([ORG]); + if (url.includes('/auth/organization/get-active-member')) { + return json({ id: 'm_1', organizationId: ORG.id, userId: USER.id, role: 'member' }); + } + if (url.includes('/auth/me/permissions')) { + return json({ + authenticated: true, userId: USER.id, tenantId: ORG.id, positions: [], permissionSets: [], objects: {}, fields: {}, hasAnyQueue: false, + }); + } + if (url.includes('/auth/')) return json({}); + if (url.includes('/api/v1/discovery')) { + return json({ + success: true, + data: { version: '1.0.0', apiName: 'v1', routes: { data: '/api/v1/data', metadata: '/api/v1/meta' }, services: {} }, + }); + } + if (url.includes('/me/apps')) return json({ apps: APPS }); + if (/\/api\/v1\/meta\/app(\?|$)/.test(url)) return json({ success: true, data: { type: 'app', items: APPS } }); + if (url.includes('/api/v1/meta/')) return json({ success: true, data: { items: [] } }); + if (url.includes('/api/v1/data/')) return json({ success: true, data: { records: [], total: 0 } }); + return json({ success: true, data: {} }); +}); + +vi.mock('@object-ui/app-shell', async (importOriginal) => ({ + ...(await importOriginal>()), + ConsoleToaster: () => null, + DefaultHomeLayout: ({ children }: { children?: ReactNode }) => <>{children}, + DefaultHomePage: () =>
, + DefaultAppContent: () =>
, +})); + +vi.mock('../LocalizationFetchProvider', () => ({ + LocalizationFetchProvider: ({ children }: { children?: ReactNode }) => <>{children}, +})); +vi.mock('../pages/settings/FirstRunChecklist', () => ({ FirstRunChecklist: () => null })); +vi.mock('../components/SetupRoute', () => ({ SetupRoute: () => null })); +vi.mock('../components/FormPage', () => ({ FormPage: () => null })); +vi.mock('../components/InternalFormRoute', () => ({ InternalFormRoute: () => null, InAppFormRoute: () => null })); +vi.mock('../components/MetadataHmrReloader', () => ({ MetadataHmrReloader: () => null })); +vi.mock('../components/FaviconSync', () => ({ FaviconSync: () => null })); +vi.mock('../pages/SharedRecordPage', () => ({ default: () => null })); +vi.mock('../pages/auth/LoginPage', () => ({ LoginPage: () =>
})); +vi.mock('../pages/auth/RegisterPage', () => ({ RegisterPage: () => null })); +vi.mock('../pages/auth/ForgotPasswordPage', () => ({ ForgotPasswordPage: () => null })); +vi.mock('../pages/auth/ResetPasswordPage', () => ({ ResetPasswordPage: () => null })); +vi.mock('../pages/auth/SetPasswordPage', () => ({ SetPasswordPage: () => null })); +vi.mock('../pages/auth/VerifyEmailPage', () => ({ VerifyEmailPage: () => null })); +vi.mock('../pages/auth/VerifyEmailPromptPage', () => ({ VerifyEmailPromptPage: () => null })); +vi.mock('../pages/auth/OAuthConsentPage', () => ({ OAuthConsentPage: () => null })); +vi.mock('../pages/auth/DeviceAuthPage', () => ({ DeviceAuthPage: () => null })); +vi.mock('../dev/DevMasterDetail', () => ({ DevMasterDetail: () => null })); +vi.mock('../dev/DevLists', () => ({ DevLists: () => null })); +vi.mock('../dev/DevModal', () => ({ DevModal: () => null })); +vi.mock('../dev/DevLookup', () => ({ DevLookup: () => null })); +vi.mock('../dev/DevRowActions', () => ({ DevRowActions: () => null })); + +import { App } from '../App'; +import { preflightAuth } from '../lib/auth-preflight'; + +const pathOf = (url: string) => { + try { + return new URL(url, 'http://console.test').pathname; + } catch { + return url; + } +}; +const readsOf = (test: (path: string) => boolean) => calls.filter((u) => test(pathOf(u))); +const FOUR = { + 'auth/get-session': (p: string) => p.endsWith('/api/v1/auth/get-session'), + 'meta/app': (p: string) => p.endsWith('/api/v1/meta/app'), + 'auth/me/permissions': (p: string) => p.endsWith('/api/v1/auth/me/permissions'), + 'me/apps': (p: string) => p.endsWith('/api/v1/me/apps'), +} as const; +const countFour = () => + Object.fromEntries(Object.entries(FOUR).map(([name, test]) => [name, readsOf(test).length])); + +/** Let the effects and the answers they await run out (a count of one needs it). */ +async function settle() { + for (let i = 0; i < 10; i++) { + await act(async () => { + await new Promise((r) => setTimeout(r, 10)); + }); + } +} + +/** The boot `main.tsx` runs, landing on a list page. */ +async function openListPage() { + localStorage.setItem('auth-session-token', TOKEN); + window.history.pushState({}, '', LIST_PAGE); + await preflightAuth('/api/v1/auth'); + render(); + await waitFor(() => expect(screen.getByTestId('app-content')).toBeInTheDocument(), { timeout: 5000 }); + // Each read is sent from an effect, which a busy run can flush after the DOM + // shows the page: wait until all four have gone out, then let the load run out. + await waitFor(() => { + for (const test of Object.values(FOUR)) expect(readsOf(test).length).toBeGreaterThan(0); + }); + await settle(); +} + +beforeEach(() => { + calls.length = 0; + fetchStub.mockClear(); + vi.stubGlobal('fetch', fetchStub); + localStorage.clear(); + sessionStorage.clear(); + delete (globalThis as unknown as Record)[Symbol.for('objectui.authPreflightSession')]; +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + window.history.pushState({}, '', '/'); +}); + +describe('a console list page load asks each of its four boot reads once (objectstack#28085)', () => { + it('get-session, meta/app, me/permissions and me/apps go out once each', async () => { + await openListPage(); + expect(window.location.pathname).toBe(LIST_PAGE); + expect(countFour()).toEqual({ + 'auth/get-session': 1, + 'meta/app': 1, + 'auth/me/permissions': 1, + 'me/apps': 1, + }); + }); +}); diff --git a/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.connected-30898.test.tsx b/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.connected-30898.test.tsx index 747e4b58857..f37ec389ed3 100644 --- a/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.connected-30898.test.tsx +++ b/ui/packages/app-shell/src/console/connect/ConnectAgentWidget.connected-30898.test.tsx @@ -26,7 +26,7 @@ import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), @@ -60,7 +60,7 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ import { notifyDataChanged } from '@object-ui/react'; import { ConnectAgent } from './ConnectAgentWidget'; -import { combineConnectedReads, type ConnectedEntry } from './connectedAccess'; +import { combineConnectedReads, useConnectedAccess, type ConnectedEntry } from './connectedAccess'; type Row = Record; type Client = { @@ -303,3 +303,58 @@ describe('§6 combineConnectedReads', () => { expect(result.state === 'ready' && result.entries.map((e) => e.id)).toEqual(['d', 'b', 'a', 'c']); }); }); + +/** + * objectstack#28085 — Home mounts more than one reader of this answer (the + * Connect an AI Assistant card and the administrator's checklist), and they + * mount at different moments of one load. Every reader mounted at the same + * time shares one pair of reads; a page mounted after the last reader left + * reads afresh. + */ +describe('§7 one pair of reads per page, however many readers', () => { + function Reader({ id }: { id: string }) { + const access = useConnectedAccess(); + return
{access.state === 'ready' ? String(access.connected) : access.state}
; + } + + it('two readers mounted together send each request once', async () => { + granted = [DESKTOP]; + render(<>); + await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('true')); + expect(screen.getByTestId('b')).toHaveTextContent('true'); + expect(listMock).toHaveBeenCalledTimes(1); + expect(findMock).toHaveBeenCalledTimes(1); + }); + + it('a reader mounting after the answer landed joins it instead of asking again', async () => { + granted = [DESKTOP]; + const { rerender } = render(); + await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('true')); + rerender(<>); + expect(screen.getByTestId('late')).toHaveTextContent('true'); + expect(listMock).toHaveBeenCalledTimes(1); + expect(findMock).toHaveBeenCalledTimes(1); + }); + + it('a change to either record re-reads it once for every reader', async () => { + render(<>); + await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('false')); + keyRows = [{ ...LIVE_KEY }]; + act(() => notifyDataChanged({ objectName: 'sys_api_key' })); + await waitFor(() => expect(screen.getByTestId('b')).toHaveTextContent('true')); + expect(screen.getByTestId('a')).toHaveTextContent('true'); + expect(findMock).toHaveBeenCalledTimes(2); + expect(listMock).toHaveBeenCalledTimes(1); + }); + + it('a page mounted after every reader left reads afresh', async () => { + const first = render(); + await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('false')); + first.unmount(); + granted = [DESKTOP]; + render(); + await waitFor(() => expect(screen.getByTestId('again')).toHaveTextContent('true')); + expect(listMock).toHaveBeenCalledTimes(2); + expect(findMock).toHaveBeenCalledTimes(2); + }); +}); diff --git a/ui/packages/app-shell/src/console/connect/connectedAccess.ts b/ui/packages/app-shell/src/console/connect/connectedAccess.ts index 62fa2247afe..856f461fa93 100644 --- a/ui/packages/app-shell/src/console/connect/connectedAccess.ts +++ b/ui/packages/app-shell/src/console/connect/connectedAccess.ts @@ -35,9 +35,9 @@ * assistants list's withdraw, which announces `sys_oauth_consent`. */ -import { useEffect, useState } from 'react'; +import { useSyncExternalStore } from 'react'; import { useAuth } from '@object-ui/auth'; -import { useAdapter, useDataInvalidation } from '@object-ui/react'; +import { dataChangeMatches, subscribeDataChanges, useAdapter } from '@object-ui/react'; import { API_KEY_LIST_FIELDS, isExpired, @@ -115,62 +115,175 @@ export function combineConnectedReads( return { state: 'loading' }; } +/** The two reads one answer is built from. */ +interface ConnectedReads { + assistants: Read; + keys: Read; +} + +const NOT_READ: ConnectedReads = { assistants: { state: 'loading' }, keys: { state: 'loading' } }; + +/** + * One person's two reads, shared by every consumer mounted at the same time. + * + * Several surfaces ask this question on one page (Home draws the Connect an AI + * Assistant card and the administrator's checklist together), and each + * consumer owning its own effect sent the same two requests once per consumer. + * The entry lives while at least one consumer is subscribed: a consumer that + * mounts while it lives joins its answer (or its reads in flight) instead of + * asking again, and the entry is dropped with its last consumer, so a page + * mounted later reads afresh. A change to either record re-reads it for every + * consumer at once. + */ +interface SharedReads { + reads: ConnectedReads; + listeners: Set<() => void>; + /** Bumped per read started; an answer for an older read is dropped. */ + assistantsRun: number; + keysRun: number; + stopListening: (() => void) | null; +} + +/** Keyed by the adapter, then the person: two adapters never share a read. */ +const sharedByAdapter = new WeakMap>(); + +type AccessAdapter = NonNullable>; + +function publish(entry: SharedReads, next: Partial): void { + entry.reads = { ...entry.reads, ...next }; + for (const listener of Array.from(entry.listeners)) listener(); +} + +function readAssistants(adapter: AccessAdapter, entry: SharedReads): void { + const run = ++entry.assistantsRun; + // Through a promise, so an adapter without the auth client is a failed + // read rather than a throw. + Promise.resolve() + .then(() => adapter.getClient().oauth.authorizedClients.list()) + .then( + (value) => { + if (run === entry.assistantsRun) { + publish(entry, { assistants: { state: 'ready', value: value.clients.map(assistantEntry) } }); + } + }, + () => { + if (run === entry.assistantsRun) publish(entry, { assistants: { state: 'failed' } }); + }, + ); +} + +function readKeys(adapter: AccessAdapter, entry: SharedReads, userId: string): void { + const run = ++entry.keysRun; + Promise.resolve() + .then(() => + adapter.find('sys_api_key', { + $filter: { user_id: userId }, + $select: [...API_KEY_LIST_FIELDS], + }), + ) + .then( + (res) => { + if (run !== entry.keysRun) return; + const readAt = Date.now(); + const rows = (res?.data ?? []) as ApiKeyRow[]; + publish(entry, { + keys: { + state: 'ready', + value: rows.filter((k) => !k.revoked && !isExpired(k, readAt)).map(keyEntry), + }, + }); + }, + () => { + if (run === entry.keysRun) publish(entry, { keys: { state: 'failed' } }); + }, + ); +} + +function subscribeShared(adapter: AccessAdapter, userId: string, listener: () => void): () => void { + let byUser = sharedByAdapter.get(adapter as object); + if (!byUser) { + byUser = new Map(); + sharedByAdapter.set(adapter as object, byUser); + } + let entry = byUser.get(userId); + if (!entry) { + entry = { reads: NOT_READ, listeners: new Set(), assistantsRun: 0, keysRun: 0, stopListening: null }; + byUser.set(userId, entry); + } + const shared = entry; + shared.listeners.add(listener); + if (!shared.stopListening) { + // The first consumer: read both records, and re-read whichever changes. + shared.stopListening = subscribeDataChanges((change) => { + if (dataChangeMatches(change, 'sys_oauth_consent')) readAssistants(adapter, shared); + if (dataChangeMatches(change, 'sys_api_key')) readKeys(adapter, shared, userId); + }); + readAssistants(adapter, shared); + readKeys(adapter, shared, userId); + } + return () => { + shared.listeners.delete(listener); + if (shared.listeners.size > 0) return; + shared.stopListening?.(); + shared.stopListening = null; + if (byUser?.get(userId) === shared) byUser.delete(userId); + }; +} + +function sharedSnapshot(adapter: AccessAdapter, userId: string): ConnectedReads { + return sharedByAdapter.get(adapter as object)?.get(userId)?.reads ?? NOT_READ; +} + +/** What `useSyncExternalStore` is handed for one adapter and person. */ +interface StoreDoor { + subscribe: (listener: () => void) => () => void; + getSnapshot: () => ConnectedReads; +} + +const NO_STORE: StoreDoor = { subscribe: () => () => {}, getSnapshot: () => NOT_READ }; + +/** + * One door per adapter and person, held outside React: `useSyncExternalStore` + * re-subscribes whenever the `subscribe` it is handed changes identity, and a + * re-subscribe that empties the entry would read again, so the identity is + * keyed on the inputs themselves rather than on a memoised callback. + */ +const doorsByAdapter = new WeakMap>(); + +function storeDoor(adapter: AccessAdapter | null | undefined, userId: string | null): StoreDoor { + if (!adapter || !userId) return NO_STORE; + let byUser = doorsByAdapter.get(adapter as object); + if (!byUser) { + byUser = new Map(); + doorsByAdapter.set(adapter as object, byUser); + } + let door = byUser.get(userId); + if (!door) { + door = { + subscribe: (listener) => subscribeShared(adapter, userId, listener), + getSnapshot: () => sharedSnapshot(adapter, userId), + }; + byUser.set(userId, door); + } + return door; +} + /** * `enabled: false` reads nothing and answers `unknown`: a caller that may not * need the answer (a dismissed Home card, a member's Home with no checklist) * costs no request. Hooks cannot be called conditionally, so this is how a * caller skips the read. + * + * Every consumer of one adapter and person mounted at the same time shares + * one pair of reads (see {@link SharedReads}). */ export function useConnectedAccess({ enabled = true }: { enabled?: boolean } = {}): ConnectedAccess { const adapter = useAdapter(); const { user } = useAuth(); const userId = enabled ? user?.id ?? null : null; - const consentsNonce = useDataInvalidation('sys_oauth_consent'); - const keysNonce = useDataInvalidation('sys_api_key'); - - const [assistants, setAssistants] = useState>({ state: 'loading' }); - const [keys, setKeys] = useState>({ state: 'loading' }); - - useEffect(() => { - if (!adapter || !userId) return; - let live = true; - // Through a promise, so an adapter without the auth client is a failed - // read rather than a throw out of the effect. - Promise.resolve() - .then(() => adapter.getClient().oauth.authorizedClients.list()) - .then( - (value) => live && setAssistants({ state: 'ready', value: value.clients.map(assistantEntry) }), - () => live && setAssistants({ state: 'failed' }), - ); - return () => { - live = false; - }; - }, [adapter, userId, consentsNonce]); - useEffect(() => { - if (!adapter || !userId) return; - let live = true; - adapter - .find('sys_api_key', { - $filter: { user_id: userId }, - $select: [...API_KEY_LIST_FIELDS], - }) - .then( - (res) => { - if (!live) return; - const readAt = Date.now(); - const rows = (res?.data ?? []) as ApiKeyRow[]; - setKeys({ - state: 'ready', - value: rows.filter((k) => !k.revoked && !isExpired(k, readAt)).map(keyEntry), - }); - }, - () => live && setKeys({ state: 'failed' }), - ); - return () => { - live = false; - }; - }, [adapter, userId, keysNonce]); + const door = storeDoor(adapter, userId); + const { assistants, keys } = useSyncExternalStore(door.subscribe, door.getSnapshot, door.getSnapshot); if (!adapter || !userId) return { state: 'unknown' }; return combineConnectedReads(assistants, keys); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useLauncherApps-26838.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useLauncherApps-26838.test.tsx index 598c8e3698c..67c27a4ef03 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useLauncherApps-26838.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useLauncherApps-26838.test.tsx @@ -186,3 +186,72 @@ describe('useLauncherApps narrows by /me/apps (objectstack#26838)', () => { expect(fetcher).not.toHaveBeenCalled(); }); }); + +/** + * objectstack#28085 — a surface that waits on `pending` (Home) must not draw + * its page for one frame before the first read starts: that frame mounts the + * page's children, `pending` then takes them away, and the answer mounts them + * again, so every read a child makes on mount goes out twice per load. + */ +describe('the first /me/apps read is pending from the first render (objectstack#28085)', () => { + /** Home's gate, reduced: the page, and a child that reads once on mount. */ + function GatedPage({ childRead }: { childRead: () => void }) { + const { pending } = useLauncherApps(state.apps); + if (pending) return
loading
; + return ; + } + function PageChild({ childRead }: { childRead: () => void }) { + React.useEffect(() => childRead(), [childRead]); + return
page
; + } + + it('a page behind the gate mounts once, so its child reads once per load', async () => { + const childRead = vi.fn(); + let answer!: (res: Response) => void; + const fetcher = vi.fn(() => new Promise((resolve) => (answer = resolve))); + renderWith(fetcher as unknown as typeof fetch, ); + await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1)); + await act(async () => { + answer(new Response(JSON.stringify({ apps: [{ name: 'crm' }] }), { status: 200 })); + }); + // The page in the DOM is not its effect having run: a commit outside `act` + // flushes passive effects on a later task, so wait for the read itself, + // then let the load run out before counting. + await waitFor(() => expect(screen.getByTestId('page')).toBeInTheDocument()); + await waitFor(() => expect(childRead).toHaveBeenCalled()); + await act(async () => { + await new Promise((r) => setTimeout(r, 20)); + }); + expect(childRead).toHaveBeenCalledTimes(1); + }); + + it('is pending in the very first render when a read is due', () => { + const fetcher = vi.fn(() => new Promise(() => {})); + const firstRender: boolean[] = []; + function First() { + const { pending } = useLauncherApps(state.apps); + if (firstRender.length === 0) firstRender.push(pending); + return null; + } + renderWith(fetcher as unknown as typeof fetch, ); + expect(firstRender).toEqual([true]); + }); + + it('is not pending in the first render when no read is due', () => { + for (const setup of [ + () => (state.userId = null), + () => (state.loading = true), + () => (state.apps = []), + ]) { + setup(); + const fetcher = meApps(['crm']); + const { unmount } = renderWith(fetcher as unknown as typeof fetch); + expect(screen.getByTestId('probe')).toHaveAttribute('data-pending', 'false'); + expect(fetcher).not.toHaveBeenCalled(); + unmount(); + state.userId = 'u1'; + state.loading = false; + state.apps = [SETUP, ACCOUNT, CRM, SHOWCASE]; + } + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useLauncherApps.tsx b/ui/packages/app-shell/src/hooks/useLauncherApps.tsx index 5f6988898a8..e12565782fe 100644 --- a/ui/packages/app-shell/src/hooks/useLauncherApps.tsx +++ b/ui/packages/app-shell/src/hooks/useLauncherApps.tsx @@ -72,7 +72,9 @@ interface HeldAnswer { state: LauncherAppsState; } -const NOTHING_HELD: HeldAnswer = { owner: null, state: { status: 'idle' } }; +const IDLE: LauncherAppsState = { status: 'idle' }; +const PENDING: LauncherAppsState = { status: 'pending' }; +const NOTHING_HELD: HeldAnswer = { owner: null, state: IDLE }; /** A non-2xx answer, kept apart so `404` (route not served) reads as absence. */ class LauncherAppsReadError extends Error { @@ -178,7 +180,20 @@ export function LauncherAppsProvider({ children, endpoint, fetcher }: LauncherAp }; }, [owner, loading, namesKey, endpoint, fetcher]); - const state: LauncherAppsState = held.owner === owner ? held.state : { status: 'idle' }; + const heldState: LauncherAppsState = held.owner === owner ? held.state : IDLE; + // The first read is pending from the render that makes it due, not from the + // effect that starts it. The effect runs after the commit, so answering + // `idle` here would hand every consumer one frame with nothing narrowed and + // nothing pending: Home would draw its page, swap it for its loading state + // once the effect publishes `pending`, then draw it again, mounting + // everything inside twice (and reading what those children read twice). + const firstReadDue = + heldState.status === 'idle' && + owner !== null && + !loading && + namesKey !== '[]' && + !notServed.current.has(owner); + const state = firstReadDue ? PENDING : heldState; return {children}; }