diff --git a/services/platform/app/features/automations/hooks/use-settings-values.ts b/services/platform/app/features/automations/hooks/use-settings-values.ts index 837129ff79..b9d0f8dbf4 100644 --- a/services/platform/app/features/automations/hooks/use-settings-values.ts +++ b/services/platform/app/features/automations/hooks/use-settings-values.ts @@ -7,7 +7,7 @@ import { import { useQuery } from '@tanstack/react-query'; import { useBackendClient } from '@/app/hooks/use-backend-client'; -import { useSessionUser } from '@/app/hooks/use-session-user'; +import { useSessionProbeSignedIn } from '@/app/hooks/use-session-probe'; import { ACTION_QUERY_ADAPTERS } from '@/app/lib/backend/adapters'; /** What each declared settings file currently holds, keyed by file name. A @@ -42,7 +42,8 @@ export function useAutomationSettingsValues( const readAdapted = ACTION_QUERY_ADAPTERS['documents/public_actions:readProjectTextValues'] !== undefined; - const { isAuthenticated } = useSessionUser(); + // The probe gates only the unadapted lane, so only that lane listens. + const isAuthenticated = useSessionProbeSignedIn(!readAdapted); // Only FIELD forms own a YAML file; uploads panels read the folder's // documents through their own query instead. const files = (settings?.forms ?? []) diff --git a/services/platform/app/hooks/session-probe-observers.test.tsx b/services/platform/app/hooks/session-probe-observers.test.tsx new file mode 100644 index 0000000000..bb9ba5f56d --- /dev/null +++ b/services/platform/app/hooks/session-probe-observers.test.tsx @@ -0,0 +1,318 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { + act, + render, + renderHook, + screen, + waitFor, +} from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { describe, expect, it, vi } from 'vitest'; + +import { sessionQueryOptions } from '@/app/lib/auth/session-query'; +import type { CurrentUserView } from '@/app/lib/backend/account'; +import { currentUserQuery } from '@/app/lib/backend/account'; +import type { BackendName, QueryName } from '@/app/lib/backend/contract'; + +// The adapter registries are swapped for one controllable row each, as in +// `use-backend-query.test.ts`, but react-query stays real: these cases count +// the observers mounted reads leave on the two queries every read shares. +// react-query removes an observer in time linear in its query's observer +// count, so one per mounted read made a 2,000-card board's unmount +// quadratic (#4062). +const { readRow, actionRow } = vi.hoisted(() => ({ + readRow: vi.fn(), + actionRow: vi.fn(), +})); +vi.mock('@/app/lib/backend/adapters', () => ({ + READ_ADAPTERS: { 'fake:adapted': readRow }, + ACTION_QUERY_ADAPTERS: { + 'fake:action': actionRow, + // The settings-values hook keys its lane off this row's presence. + 'documents/public_actions:readProjectTextValues': actionRow, + }, + WRITE_ADAPTERS: {}, + activeOrganizationId: () => undefined, + projectAdaptedRead: vi.fn(), + runAdapted: (run: () => Promise) => run(), + retryAdaptedRead: () => false, +})); +// Nothing here may reach Better Auth: its session answer is seeded below. +vi.mock('@/lib/auth-client', () => ({ + authClient: { getSession: () => new Promise(() => {}) }, +})); + +import { useAutomationSettingsValues } from '@/app/features/automations/hooks/use-settings-values'; + +import { useActionQuery } from './use-action-query'; +import { useBackendQuery } from './use-backend-query'; +import { useSessionProbeSignedIn } from './use-session-probe'; +import { useSessionUser } from './use-session-user'; + +const ADAPTED_READ = 'fake:adapted' as QueryName; +const ADAPTED_ACTION = 'fake:action' as BackendName; +/** A name with no row in the stub registries — the gated refusal path. */ +const NO_ROW_READ = 'items:list' as QueryName; +const NO_ROW_ACTION = 'items:walk' as BackendName; + +const READ_KEY = ['backend', 'org-1', 'fake', 'list']; +const ACTION_KEY = ['fake-action', 'org-1']; +const USER: CurrentUserView = { userId: 'user-1' }; + +readRow.mockReturnValue({ + queryKey: READ_KEY, + queryFn: () => Promise.resolve([]), +}); +actionRow.mockReturnValue(() => Promise.resolve([])); + +/** Both shared answers are cached and fresh, so no mount here fetches them. */ +function newClient(user: CurrentUserView | null = USER): QueryClient { + const client = new QueryClient({ + defaultOptions: { queries: { staleTime: Infinity, retry: false } }, + }); + client.setQueryData(currentUserQuery().queryKey, user); + client.setQueryData(sessionQueryOptions.queryKey, { + data: null, + error: null, + }); + return client; +} + +function observers(client: QueryClient, queryKey: readonly unknown[]) { + return ( + client + .getQueryCache() + .find({ queryKey, exact: true }) + ?.getObserversCount() ?? 0 + ); +} + +/** Counts cache listeners from here on: a gate that listened per adapted read + * would call every one of them on each of the board's cache events. */ +function spyCacheListeners(client: QueryClient) { + return vi.spyOn(client.getQueryCache(), 'subscribe'); +} + +function sharedObservers(client: QueryClient) { + return { + probe: observers(client, currentUserQuery().queryKey), + session: observers(client, sessionQueryOptions.queryKey), + }; +} + +function AdaptedRead() { + useBackendQuery(ADAPTED_READ, { organizationId: 'org-1' }); + return null; +} + +function AdaptedAction() { + useActionQuery(ACTION_KEY, ADAPTED_ACTION, {}); + return null; +} + +function Board({ client, cards }: { client: QueryClient; cards: number }) { + return ( + + {Array.from({ length: cards }, (_, index) => ( +
+ + +
+ ))} +
+ ); +} + +/** What a gated read shows: its fetch state and the error it settled on. */ +function GatedRead(props: { requireAuth?: boolean; skip?: boolean }) { + const read = useBackendQuery( + NO_ROW_READ, + props.skip === true ? 'skip' : { organizationId: 'org-1' }, + props.requireAuth === false ? { requireAuth: false } : undefined, + ); + return ( + + {read.fetchStatus} · {read.error?.message ?? 'no error'} + + ); +} + +function wrapperFor(client: QueryClient) { + return function Wrapper({ children }: { children: ReactNode }) { + return ( + {children} + ); + }; +} + +describe('session probe observers (#4062)', () => { + it('adapted reads leave no observer on the probe or the Better Auth session, however many mount', () => { + const client = newClient(); + const listens = spyCacheListeners(client); + const prefetches = vi.spyOn(client, 'prefetchQuery'); + const view = render(); + const oneCard = sharedObservers(client); + + view.rerender(); + + // Every read mounted and subscribed to its own query… + expect(observers(client, READ_KEY)).toBe(60); + expect(observers(client, ACTION_KEY)).toBe(60); + // …and none of them to the two queries all of them share. + expect(sharedObservers(client)).toEqual(oneCard); + expect(oneCard).toEqual({ probe: 0, session: 0 }); + expect(listens).not.toHaveBeenCalled(); + expect(prefetches).not.toHaveBeenCalled(); + + view.unmount(); + expect(observers(client, READ_KEY)).toBe(0); + }); + + it('a read with no adapter row still waits for the probe, then refuses by name once it answers a user', async () => { + const client = newClient(null); + const listens = spyCacheListeners(client); + render(, { wrapper: wrapperFor(client) }); + + expect(screen.getByRole('status')).toHaveTextContent('idle · no error'); + // The gate listens to the probe without joining its observers. + expect(sharedObservers(client)).toEqual({ probe: 0, session: 0 }); + expect(listens).toHaveBeenCalledTimes(1); + + act(() => { + client.setQueryData(currentUserQuery().queryKey, USER); + }); + + await waitFor(() => { + expect(screen.getByRole('status')).toHaveTextContent( + '"items:list" has no 0.5 backend row', + ); + }); + }); + + it('a gated read asks for a probe nothing has fetched yet', () => { + // No seeded answer: the gate itself asks for the probe, as a mounting + // observer would, instead of waiting on whoever else might. + const client = new QueryClient({ + defaultOptions: { queries: { staleTime: Infinity, retry: false } }, + }); + const prefetches = vi + .spyOn(client, 'prefetchQuery') + .mockResolvedValue(undefined); + render(, { wrapper: wrapperFor(client) }); + + expect(prefetches).toHaveBeenCalledWith( + expect.objectContaining({ queryKey: currentUserQuery().queryKey }), + ); + expect(screen.getByRole('status')).toHaveTextContent('idle · no error'); + }); + + it('requireAuth:false and a skipped read take no probe subscription', async () => { + // Separate clients: both reads use the name's one `convex-retired` key, so + // a shared cache would show the skipped read the other one's refusal. + const open = newClient(null); + const openListens = spyCacheListeners(open); + render(, { wrapper: wrapperFor(open) }); + + expect(sharedObservers(open)).toEqual({ probe: 0, session: 0 }); + expect(openListens).not.toHaveBeenCalled(); + // requireAuth:false still runs while signed out, so it refuses at once. + await waitFor(() => { + expect(screen.getByRole('status')).toHaveTextContent( + '"items:list" has no 0.5 backend row', + ); + }); + + const skippedClient = newClient(null); + const skippedListens = spyCacheListeners(skippedClient); + const skipped = renderHook(() => useBackendQuery(NO_ROW_READ, 'skip'), { + wrapper: wrapperFor(skippedClient), + }); + expect(skipped.result.current.fetchStatus).toBe('idle'); + expect(sharedObservers(skippedClient)).toEqual({ probe: 0, session: 0 }); + expect(skippedListens).not.toHaveBeenCalled(); + }); + + it('an action read with no row gates on the probe; an adapted one does not subscribe', async () => { + const client = newClient(null); + const gated = renderHook( + () => useActionQuery(['items-walk'], NO_ROW_ACTION, {}), + { wrapper: wrapperFor(client) }, + ); + + expect(gated.result.current.fetchStatus).toBe('idle'); + expect(sharedObservers(client)).toEqual({ probe: 0, session: 0 }); + + act(() => { + client.setQueryData(currentUserQuery().queryKey, USER); + }); + // The walk retries a plain error, so its first refusal shows as the + // failure reason before any final error. + await waitFor(() => { + expect(gated.result.current.failureReason?.message).toContain( + '"items:walk" has no 0.5 backend row', + ); + }); + + gated.unmount(); + const listens = spyCacheListeners(client); + renderHook(() => useActionQuery(ACTION_KEY, ADAPTED_ACTION, {}), { + wrapper: wrapperFor(client), + }); + expect(sharedObservers(client)).toEqual({ probe: 0, session: 0 }); + expect(listens).not.toHaveBeenCalled(); + }); + + it('the automation settings read takes no probe subscription on its adapted lane', () => { + const client = newClient(null); + const listens = spyCacheListeners(client); + renderHook( + () => useAutomationSettingsValues('org-1', 'project-1', null, null), + { wrapper: wrapperFor(client) }, + ); + + expect(sharedObservers(client)).toEqual({ probe: 0, session: 0 }); + expect(listens).not.toHaveBeenCalled(); + }); + + it('useSessionUser observes the probe alone, not the Better Auth session', () => { + const client = newClient(); + const held = renderHook(() => useSessionUser(), { + wrapper: wrapperFor(client), + }); + + expect(held.result.current).toEqual({ + isAuthenticated: true, + isLoading: false, + }); + expect(sharedObservers(client)).toEqual({ probe: 1, session: 0 }); + }); + + it('useSessionProbeSignedIn follows the probe only when asked', () => { + const client = newClient(null); + const wrapper = wrapperFor(client); + let quietRenders = 0; + const quiet = renderHook( + () => { + quietRenders += 1; + return useSessionProbeSignedIn(false); + }, + { wrapper }, + ); + const asked = renderHook(() => useSessionProbeSignedIn(true), { wrapper }); + expect(asked.result.current).toBe(false); + + act(() => { + client.setQueryData(currentUserQuery().queryKey, USER); + }); + expect(asked.result.current).toBe(true); + act(() => { + client.setQueryData(currentUserQuery().queryKey, null); + }); + expect(asked.result.current).toBe(false); + + // Not asked: it read nothing, and the probe's answers never re-rendered it. + expect(quiet.result.current).toBe(false); + expect(quietRenders).toBe(1); + expect(sharedObservers(client)).toEqual({ probe: 0, session: 0 }); + }); +}); diff --git a/services/platform/app/hooks/use-action-query.ts b/services/platform/app/hooks/use-action-query.ts index c0061d7b1c..4d56c3562d 100644 --- a/services/platform/app/hooks/use-action-query.ts +++ b/services/platform/app/hooks/use-action-query.ts @@ -16,7 +16,7 @@ import type { } from '@/app/lib/backend/contract'; import { MissingBackendRowError } from '@/app/lib/backend/missing-row'; -import { useSessionUser } from './use-session-user'; +import { useSessionProbeSignedIn } from './use-session-probe'; interface ActionQueryOptions { enabled?: boolean; @@ -65,11 +65,12 @@ export function useActionQuery( args: ArgsOf, options?: ActionQueryOptions, ) { - const { isAuthenticated } = useSessionUser(); - // Every shipped walk is served over HTTP (session cookie, no WebSocket-auth // gate) by its adapter row; a name without one has no server left. const adapter = ACTION_QUERY_ADAPTERS[name]; + // Only a name without a row gates on the probe, so only it listens (see + // `useBackendQuery`). + const isAuthenticated = useSessionProbeSignedIn(adapter === undefined); const organizationId = adapter === undefined ? undefined : activeOrganizationId(); const adaptedFetch = diff --git a/services/platform/app/hooks/use-backend-query.test.ts b/services/platform/app/hooks/use-backend-query.test.ts index 6e54c36073..109d357965 100644 --- a/services/platform/app/hooks/use-backend-query.test.ts +++ b/services/platform/app/hooks/use-backend-query.test.ts @@ -15,8 +15,10 @@ const mockUseConvexAuth = vi.fn(() => ({ isAuthenticated: true, isLoading: false, })); -vi.mock('./use-session-user', () => ({ - useSessionUser: () => mockUseConvexAuth(), +// The gate's probe read, answering only for the branch that asks for it. +vi.mock('./use-session-probe', () => ({ + useSessionProbeSignedIn: (when: boolean) => + when && mockUseConvexAuth().isAuthenticated, })); // The adapter seam resolves the function name on every call; the plain mock diff --git a/services/platform/app/hooks/use-backend-query.ts b/services/platform/app/hooks/use-backend-query.ts index 1119d4643b..fb124c2cd2 100644 --- a/services/platform/app/hooks/use-backend-query.ts +++ b/services/platform/app/hooks/use-backend-query.ts @@ -10,18 +10,19 @@ import { import type { ArgsOf, QueryName, ReturnsOf } from '@/app/lib/backend/contract'; import { MissingBackendRowError } from '@/app/lib/backend/missing-row'; -import { useSessionUser } from './use-session-user'; +import { useSessionProbeSignedIn } from './use-session-probe'; interface ConvexQueryOptions { staleTime?: number; gcTime?: number; enabled?: boolean; /** - * Gate the query on the session probe having resolved. Defaults to `true`, + * Gate the query on the session probe holding a user. Defaults to `true`, * so authenticated queries never fire during the cold-load auth gap. Set * `false` only for queries that MUST run before auth — the `getCurrentUser` * probe and genuinely public reads. Adapted reads ignore this gate entirely: - * they authenticate with the session cookie, which the browser sends anyway. + * they authenticate with the session cookie, which the browser sends anyway, + * and do not subscribe to the probe. */ requireAuth?: boolean; /** @@ -58,7 +59,6 @@ export function useBackendQuery( name: Name, ...[args, options]: QueryArgs ): UseQueryResult> { - const { isAuthenticated } = useSessionUser(); // `requireAuth` is our own gate, not a react-query option — peel it off. const { requireAuth = true, ...queryOpts } = options ?? {}; @@ -66,6 +66,12 @@ export function useBackendQuery( // options object every render never refetches. const adapter = READ_ADAPTERS[name]; const skipped = args === 'skip'; + // Only the no-row branch below reads the probe, so only it listens. One + // probe observer per adapted read put an observer per mounted read on the + // probe's shared query, and each removal scans all of them (#4062). + const isAuthenticated = useSessionProbeSignedIn( + adapter === undefined && !skipped && requireAuth, + ); const organizationId = adapter === undefined ? undefined : activeOrganizationId(); const adapterCtx = organizationId !== undefined ? { organizationId } : {}; diff --git a/services/platform/app/hooks/use-session-probe.ts b/services/platform/app/hooks/use-session-probe.ts new file mode 100644 index 0000000000..f98af00540 --- /dev/null +++ b/services/platform/app/hooks/use-session-probe.ts @@ -0,0 +1,49 @@ +import { useQueryClient } from '@tanstack/react-query'; +import { useCallback, useSyncExternalStore } from 'react'; + +import { currentUserQuery } from '@/app/lib/backend/account'; + +const noSubscription = () => () => {}; +const notRead = () => false; + +/** + * Whether the session probe (`currentUser`) holds a user, for a hook that + * gates on it on one branch only: pass that branch's condition as `when`, and + * read the answer on that branch alone (it is `false` when not asked). + * + * It is not an observer on the probe. react-query removes an observer in + * time linear in its query's observer count, so one per mounted read made a + * 2,000-card board take ~20 s to unmount (#4062), and even an unsubscribed + * `useQuery` costs every read an observer object. With `when` false this + * reads, fetches and listens to nothing. With `when` true it reads the cached + * answer, asks for the probe when that answer is missing or stale (as a + * mounting observer would), and re-renders on the probe's cache events + * through a query-cache listener. Joining and leaving that listener set is + * constant time, but every cache event calls every listener, so it suits + * rare callers only: no shipped read lacks an adapter row. + */ +export function useSessionProbeSignedIn(when: boolean): boolean { + const client = useQueryClient(); + const subscribe = useCallback( + (onChange: () => void) => { + const probe = currentUserQuery(); + const probeHash = client.defaultQueryOptions(probe).queryHash; + const stop = client.getQueryCache().subscribe((event) => { + if (event.query.queryHash === probeHash) onChange(); + }); + void client.prefetchQuery(probe); + return stop; + }, + [client], + ); + const read = useCallback( + () => client.getQueryData(currentUserQuery().queryKey) != null, + [client], + ); + const snapshot = when ? read : notRead; + return useSyncExternalStore( + when ? subscribe : noSubscription, + snapshot, + snapshot, + ); +} diff --git a/services/platform/app/hooks/use-session-user.ts b/services/platform/app/hooks/use-session-user.ts index d4155a92be..6e4ae0602f 100644 --- a/services/platform/app/hooks/use-session-user.ts +++ b/services/platform/app/hooks/use-session-user.ts @@ -66,12 +66,15 @@ export function useAuth() { * The auth shape the app's hooks gate on. It used to be Convex's — the * WebSocket handshake's state — and is now the session probe's: the backend * answers `currentUser` on the session cookie alone, so there is nothing to - * hand-shake and nothing to wait for beyond that one request. + * hand-shake and nothing to wait for beyond that one request. It observes + * that probe alone; the Better Auth session `useAuth` also holds answers + * nothing returned here. A hook mounted once per read gates through + * `useSessionProbeSignedIn` instead, which adds no observer (#4062). */ export function useSessionUser(): { isLoading: boolean; isAuthenticated: boolean; } { - const { isLoading, isAuthenticated } = useConvexAuthUser(); - return { isLoading, isAuthenticated }; + const { data: user, isLoading } = useQuery(currentUserQuery()); + return { isLoading, isAuthenticated: !!user }; }