From ac36606305edb2a2b83f0afce9a10dd54a1b07dd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:17:02 +0000 Subject: [PATCH 1/2] perf(console): a full-page record open asks its page list and object scope beside the permission read, and the app bar's package list after the page The console root's prefetch now starts a record route's /meta/page read and the package object list (under AppContent's own rule) as soon as the app list names the app, instead of when AppContent mounts after /auth/me/permissions. fetchSessionPackages waits until the page's counted requests stay quiet for 750 ms (at most 8 s) before reading GET /api/v1/packages, so that response no longer downloads beside the record. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUVVocvc9dVySV9DVf --- .changeset/35416-record-open-boot-waves.md | 14 ++ ...ObjectScope.rootRecordRoute-35416.test.tsx | 115 ++++++++++++++++ .../app-shell/src/console/appObjectScope.ts | 45 +++++- .../src/observability/settleSignal.ts | 33 +++++ .../src/views/studio-design/packages-io.ts | 29 +++- ...essionPackagesAfterPageQuiet-35416.test.ts | 130 ++++++++++++++++++ 6 files changed, 360 insertions(+), 6 deletions(-) create mode 100644 .changeset/35416-record-open-boot-waves.md create mode 100644 ui/packages/app-shell/src/console/__tests__/appObjectScope.rootRecordRoute-35416.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/sessionPackagesAfterPageQuiet-35416.test.ts diff --git a/.changeset/35416-record-open-boot-waves.md b/.changeset/35416-record-open-boot-waves.md new file mode 100644 index 00000000000..4a0f7ccdf64 --- /dev/null +++ b/.changeset/35416-record-open-boot-waves.md @@ -0,0 +1,14 @@ +--- +'@object-ui/app-shell': patch +--- + +perf(console): a full-page record open asks its page list and object scope beside the permission read, and the app bar's package list after the page + +Clause-②: no +Metadata-protocol: none + +Opening a record page by its URL (a reload, a pasted link) waited one more round trip than it needed to, and shared the link with the largest response an app page reads: + +- The console root's prefetch (`useAppObjectScopePrefetch`) now starts a record route's page list (`/meta/page`) and, under the same rule `AppContent` follows, the app package's object list, as soon as the app list names the app. Before, both left only once `AppContent` mounted, which is after `/auth/me/permissions` answers. +- `fetchSessionPackages` (the read behind the app bar's and the sidebar's Studio entries) waits until the page's own requests have stayed quiet for 750 ms (at most 8 s) before it reads `GET /api/v1/packages`, so that response no longer downloads beside the record. The entries it gates stay absent until it answers, as they already did while it was on the wire. Studio's own package reads are unchanged. +- New `whenQuiet(quietMs, maxMs)` in the settle signal; it resolves at once where no data layer counts requests. diff --git a/ui/packages/app-shell/src/console/__tests__/appObjectScope.rootRecordRoute-35416.test.tsx b/ui/packages/app-shell/src/console/__tests__/appObjectScope.rootRecordRoute-35416.test.tsx new file mode 100644 index 00000000000..792ce3b2e53 --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/appObjectScope.rootRecordRoute-35416.test.tsx @@ -0,0 +1,115 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35416 — the console root starts a record route's reads. + * + * `AppContent` mounts below the session's permission read (`/auth/me/permissions`), + * so the page list and the package object list a record route waits for used + * to leave one round trip after that read answered. The root's prefetch + * (`useAppObjectScopePrefetch`, mounted beside the permission read) now asks + * them as soon as the app list names the app: the page list on every record + * route, and the package list beside it under the same rule `AppContent` + * follows (objectstack#35455: not when the bundle answers a miss). + * + * Only the root's prefetch is mounted here, so every read below is one the + * root asked before `AppContent` exists. + * + * CONTROLs: an object's list route asks no page list; a bundle that is a miss + * starts no package list beside the page list. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { act, cleanup, render } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataProvider } from '../../providers/MetadataProvider'; +import { useAppObjectScopePrefetch } from '../appObjectScope'; + +const CRM = 'app.crm'; +const APPS = [{ name: 'crm', _packageId: CRM, navigation: [] }]; +const OBJECTS = [{ name: 'crm_account', _packageId: CRM, fields: {} }]; + +type Adapter = Parameters[0]['adapter']; + +/** Every metadata read is held until `release`; `pending` names the held ones. */ +function makeHeldAdapter(options: { bundleOnTheWire: boolean }) { + const held: Array<{ label: string; go: () => void }> = []; + const hold = (label: string, answer: () => T) => + new Promise((resolve) => held.push({ label, go: () => resolve(answer()) })); + const list = (type: string, packageId?: string) => { + const all: any[] = type === 'app' ? APPS : type === 'object' ? OBJECTS : []; + return { type, items: structuredClone(packageId ? all.filter((o) => o._packageId === packageId) : all) }; + }; + const adapter = { + clearCache: vi.fn(), + invalidateCache: vi.fn(), + getObjectSchema: (name: string) => hold(`object/${name}`, () => OBJECTS.find((o) => o.name === name)), + getClient: () => ({ + meta: { + getItems: (type: string, opts?: { packageId?: string; names?: readonly string[] }) => + hold( + opts?.names ? `${type}?names=${opts.names.join(',')}` : opts?.packageId ? `${type}?package=${opts.packageId}` : type, + () => list(type, opts?.packageId), + ), + getItem: (type: string, name: string) => hold(`${type}/${name}`, () => ({ item: undefined })), + }, + }), + // A bundle still on the wire: the provider answers its reads `pending`. + ...(options.bundleOnTheWire + ? { peekAppBundle: () => ({ status: 'loading', settled: new Promise(() => undefined) }) } + : {}), + } as unknown as Adapter; + return { adapter, pending: () => held.map((h) => h.label).sort(), release: () => held.splice(0).forEach((h) => h.go()) }; +} + +function RootPrefetch() { + useAppObjectScopePrefetch(); + return null; +} + +const settle = async () => { + for (let i = 0; i < 6; i++) await act(() => new Promise((resolve) => setTimeout(resolve, 0))); +}; + +/** The reads the root asks in each wave, for `waveCount` waves. */ +async function rootWaves(url: string, bundleOnTheWire: boolean, waveCount = 2): Promise { + sessionStorage.clear(); + const transport = makeHeldAdapter({ bundleOnTheWire }); + render( + + + + + , + ); + const seen: string[][] = []; + await settle(); + for (let i = 0; i < waveCount; i++) { + seen.push(transport.pending()); + transport.release(); + await settle(); + } + return seen; +} + +afterEach(() => cleanup()); + +describe('objectstack#35416 — the console root starts a record route\'s reads', () => { + it('a record route: the app list, then the page list and the package list together, before AppContent mounts', async () => { + const [first, second] = await rootWaves('/apps/crm/crm_account/record/r1', true); + expect(first).toEqual(['app']); + expect(second).toEqual(expect.arrayContaining(['page', `object?package=${CRM}`])); + }); + + it("CONTROL: a bundle that is a miss starts the page list alone, as AppContent's rule says (objectstack#35455)", async () => { + const [first, second] = await rootWaves('/apps/crm/crm_account/record/r1', false); + expect(first).toEqual(['app']); + expect(second).toContain('page'); + expect(second).not.toContain(`object?package=${CRM}`); + }); + + it("CONTROL: an object's list route asks no page list at the root", async () => { + const waves = await rootWaves('/apps/crm/crm_account', true, 3); + expect(waves.flat()).not.toContain('page'); + expect(waves[1]).toContain(`object?package=${CRM}`); + }); +}); diff --git a/ui/packages/app-shell/src/console/appObjectScope.ts b/ui/packages/app-shell/src/console/appObjectScope.ts index 219b3a559b2..beb89395b68 100644 --- a/ui/packages/app-shell/src/console/appObjectScope.ts +++ b/ui/packages/app-shell/src/console/appObjectScope.ts @@ -91,7 +91,7 @@ import { APP_ROUTE_METADATA_READS } from './appRouteMetadataReads.js'; import { matchAppBySegment } from '../utils/appRoute.js'; import { COMMAND_PALETTE_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_PARAM } from '../urlParams.js'; import type { ReadNamesWithoutViews } from '../hooks/useObjectPresence.js'; -import type { BundledRead } from '../providers/bundledReads.js'; +import { BUNDLE_MISS, useBundledReads, type BundledRead } from '../providers/bundledReads.js'; type ReadObjectScope = NonNullable; export type AppObjectScope = ReturnType; @@ -947,14 +947,31 @@ export function enterAppBundle(dataSource: unknown, appName: string | undefined) * scope composes its views from the bundle instead of reading the * `/meta/view` list before the app was entered. Leaving the app ends the * entry, so coming back revalidates the bundle as entering it always has. + * + * objectstack#35416 — on a record route it also starts the page list, and + * hands {@link readAppObjectScope} the same page-list and bundle readers + * `AppContent` does, so the record route's reads leave beside the permission + * read instead of one wave after it. */ export function useAppObjectScopePrefetch(): void { - const { apps, readObjectScope } = useMetadata(); + const metadata = useMetadata(); + const { apps, readObjectScope, ensureType, getTypeStatus } = metadata; + const bundledReads = useBundledReads(); const dataSource = useAdapter() as BundleHost | null; const { pathname, search } = useLocation(); const segments = pathname.split('/').filter(Boolean); const app = segments[0] === 'apps' && segments[1] ? matchAppBySegment(apps, segments[1]) : undefined; const bundleAppName = typeof app?.name === 'string' && app.name ? app.name : undefined; + const subPath = segments.slice(2).join('/'); + // objectstack#35416 — a record route's page list, asked here rather than + // when `AppContent` mounts below the session's permission read: the route + // asks it on every record route (`APP_ROUTE_METADATA_READS`), so this is + // the same request one wave earlier, and the scope read below can start + // the package object list beside it. + const recordRoute = !!app && !!readObjectScope && matchObjectScopeRoute(subPath, [])?.recordId !== undefined; + useEffect(() => { + if (recordRoute && ensureType) void ensureType('page'); + }, [recordRoute, ensureType]); useEffect(() => { const load = dataSource?.loadAppBundle; if (!dataSource || !bundleAppName || typeof load !== 'function') return; @@ -964,5 +981,27 @@ export function useAppObjectScopePrefetch(): void { rootEnteredApps.delete(bundleAppName); }; }, [dataSource, bundleAppName]); - if (app && readObjectScope) readAppObjectScope(readObjectScope, app, segments.slice(2).join('/'), search); + if (!app || !readObjectScope) return; + // The record route's readers, as `AppContent` hands them: the page list and + // its status, and the objects the app bundle says point at the record's. + readAppObjectScope( + readObjectScope, + app, + subPath, + search, + [], + undefined, + () => { + // Read only when the record route asks: the provider's `pages` starts + // the page list when read. + const status = getTypeStatus?.('page'); + const pages = metadata.pages; + return { + pages: Array.isArray(pages) ? (pages as unknown[]) : [], + settled: status === undefined || status === 'ready' || status === 'error', + }; + }, + undefined, + (objectName) => (bundledReads && bundleAppName ? bundledReads.objectsReferencing(bundleAppName, objectName) : BUNDLE_MISS), + ); } diff --git a/ui/packages/app-shell/src/observability/settleSignal.ts b/ui/packages/app-shell/src/observability/settleSignal.ts index 4de9070b953..304d3863415 100644 --- a/ui/packages/app-shell/src/observability/settleSignal.ts +++ b/ui/packages/app-shell/src/observability/settleSignal.ts @@ -22,6 +22,8 @@ type Listener = (pending: number) => void; let pending = 0; +/** Whether any request was ever counted: a data layer wraps its `fetch` here. */ +let counted = false; const listeners = new Set(); let idleWaiters: Array<() => void> = []; @@ -48,6 +50,7 @@ function notify(): void { /** Mark one request as in-flight. Pair with {@link endRequest}. */ export function beginRequest(): void { + counted = true; pending += 1; notify(); } @@ -100,6 +103,36 @@ export function whenIdle(timeoutMs = 10_000): Promise { }); } +/** + * objectstack#35416 — resolve once no counted request has been in flight for + * `quietMs` in a row, or after `maxMs` whatever is in flight. A read that is + * not the page's own (the app bar's package list) waits on this so it does + * not share the link with the page's requests while they load. + * + * Resolves at once where nothing was ever counted (no data layer wraps its + * `fetch` here, as in a host or a test without one): there is no page load + * to wait for. + */ +export function whenQuiet(quietMs: number, maxMs: number): Promise { + if (!counted || typeof setTimeout === 'undefined') return Promise.resolve(); + return new Promise((resolve) => { + let quietTimer: ReturnType | undefined; + const finish = () => { + if (quietTimer !== undefined) clearTimeout(quietTimer); + clearTimeout(capTimer); + listeners.delete(onChange); + resolve(); + }; + const onChange = (now: number) => { + if (quietTimer !== undefined) clearTimeout(quietTimer); + quietTimer = now === 0 ? setTimeout(finish, quietMs) : undefined; + }; + const capTimer = setTimeout(finish, maxMs); + listeners.add(onChange); + onChange(pending); + }); +} + /** * Wrap a `fetch` so each call increments the in-flight counter before the * request and decrements it when the promise settles (success or failure). diff --git a/ui/packages/app-shell/src/views/studio-design/packages-io.ts b/ui/packages/app-shell/src/views/studio-design/packages-io.ts index ebede3dcb1b..cab957e3f6c 100644 --- a/ui/packages/app-shell/src/views/studio-design/packages-io.ts +++ b/ui/packages/app-shell/src/views/studio-design/packages-io.ts @@ -38,6 +38,7 @@ import { validateObjectNamespacePrefix, } from '@objectstack/spec/kernel'; import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; +import { whenQuiet } from '../../observability/settleSignal.js'; export interface PkgEntry { id: string; @@ -449,6 +450,14 @@ interface HeldPackageList { const heldPackageLists = new WeakMap(); +/** + * objectstack#35416 — how long the page's counted requests must stay quiet + * before {@link fetchSessionPackages} starts its read, and the longest it + * waits for that (a page that never goes quiet still gets its entries). + */ +export const SESSION_PACKAGE_READ_QUIET_MS = 750; +export const SESSION_PACKAGE_READ_MAX_WAIT_MS = 8_000; + /** Bumped by every forget, so a read asked before a write never becomes the hold. */ let heldPackageListEpoch = 0; @@ -465,9 +474,23 @@ function forgetHeldPackageList(): void { */ export async function fetchSessionPackages(session: string, packageId: string): Promise { const transport = globalThis.fetch; - const held = heldPackageLists.get(transport); - if (held && held.session === session && (held.listed.has(packageId) || held.unlisted.has(packageId))) { - return parsePackages(held.payload); + const heldAnswer = (): PkgEntry[] | null => { + const held = heldPackageLists.get(transport); + return held && held.session === session && (held.listed.has(packageId) || held.unlisted.has(packageId)) + ? parsePackages(held.payload) + : null; + }; + const fromHold = heldAnswer(); + if (fromHold) return fromHold; + // objectstack#35416 — the list is the largest response an app page reads + // (megabytes unpacked), and the entries it gates are a shortcut, absent + // while it is unread. So a read it starts waits until the page's own + // requests have gone quiet, instead of sharing the link with the record + // or list the page is opening. A read already on the wire is joined at once. + if (!pendingPackageReads.has(transport)) { + await whenQuiet(SESSION_PACKAGE_READ_QUIET_MS, SESSION_PACKAGE_READ_MAX_WAIT_MS); + const heldSince = heldAnswer(); + if (heldSince) return heldSince; } const epoch = heldPackageListEpoch; const payload = await readPackagesPayload(); diff --git a/ui/packages/app-shell/src/views/studio-design/sessionPackagesAfterPageQuiet-35416.test.ts b/ui/packages/app-shell/src/views/studio-design/sessionPackagesAfterPageQuiet-35416.test.ts new file mode 100644 index 00000000000..1d50b2ef016 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/sessionPackagesAfterPageQuiet-35416.test.ts @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35416 — the app bar's package list read leaves after the page's. + * + * `fetchSessionPackages` (the read behind the app → Studio entries) reads + * `GET /api/v1/packages`, the largest response an app page reads. Started in + * the commit that drew the app bar, it shared the link with the record or list + * the page was opening. It now waits until the page's counted requests + * (`settleSignal`, the data layer's in-flight count) have stayed at zero for + * `SESSION_PACKAGE_READ_QUIET_MS`, at most `SESSION_PACKAGE_READ_MAX_WAIT_MS`. + * + * CONTROLs: with nothing ever counted (no data layer, a host without one) it + * reads at once; a read already on the wire is joined at once; a held list + * answers with no read and no wait. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const PAYLOAD = { success: true, data: { packages: [{ manifest: { id: 'app.crm', name: 'CRM' }, writable: true }] } }; + +type SettleModule = typeof import('../../observability/settleSignal'); +type PackagesModule = typeof import('./packages-io'); + +let settle: SettleModule; +let io: PackagesModule; +let fetchMock: ReturnType; + +beforeEach(async () => { + vi.useFakeTimers(); + // Fresh modules per case: the in-flight count, its "ever counted" flag and + // the held list are module state. + vi.resetModules(); + settle = await import('../../observability/settleSignal'); + io = await import('./packages-io'); + fetchMock = vi.fn(async () => new Response(JSON.stringify(PAYLOAD), { status: 200 })); + vi.stubGlobal('fetch', fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.useRealTimers(); +}); + +const packagesReads = () => fetchMock.mock.calls.filter(([url]) => String(url).endsWith('/api/v1/packages')).length; + +describe('objectstack#35416 — the session package list waits for the page to go quiet', () => { + it('waits while a page request is in flight, then for the quiet window, then reads once', async () => { + settle.beginRequest(); // the record page's own read, on the wire + const answer = io.fetchSessionPackages('s1', 'app.crm'); + await vi.advanceTimersByTimeAsync(2_000); + expect(packagesReads()).toBe(0); + + settle.endRequest(); + await vi.advanceTimersByTimeAsync(io.SESSION_PACKAGE_READ_QUIET_MS - 1); + expect(packagesReads()).toBe(0); + await vi.advanceTimersByTimeAsync(1); + expect(packagesReads()).toBe(1); + await expect(answer).resolves.toEqual([expect.objectContaining({ id: 'app.crm', writable: true })]); + }); + + it('a request that starts inside the quiet window starts the window again', async () => { + settle.beginRequest(); + void io.fetchSessionPackages('s1', 'app.crm'); + settle.endRequest(); + await vi.advanceTimersByTimeAsync(io.SESSION_PACKAGE_READ_QUIET_MS - 100); + settle.beginRequest(); // the page's next wave (its related lists) + await vi.advanceTimersByTimeAsync(50); + settle.endRequest(); + await vi.advanceTimersByTimeAsync(io.SESSION_PACKAGE_READ_QUIET_MS - 1); + expect(packagesReads()).toBe(0); + await vi.advanceTimersByTimeAsync(1); + expect(packagesReads()).toBe(1); + }); + + it('a page that never goes quiet still gets its list after the longest wait', async () => { + settle.beginRequest(); // a request that never ends + void io.fetchSessionPackages('s1', 'app.crm'); + await vi.advanceTimersByTimeAsync(io.SESSION_PACKAGE_READ_MAX_WAIT_MS - 1); + expect(packagesReads()).toBe(0); + await vi.advanceTimersByTimeAsync(1); + expect(packagesReads()).toBe(1); + }); + + it('readers asked in one commit share the one read after the wait', async () => { + settle.beginRequest(); + const a = io.fetchSessionPackages('s1', 'app.crm'); + const b = io.fetchSessionPackages('s1', 'app.crm'); + settle.endRequest(); + await vi.advanceTimersByTimeAsync(io.SESSION_PACKAGE_READ_QUIET_MS); + await Promise.all([a, b]); + expect(packagesReads()).toBe(1); + }); + + it('CONTROL: with nothing ever counted it reads at once', async () => { + void io.fetchSessionPackages('s1', 'app.crm'); + await vi.advanceTimersByTimeAsync(0); + expect(packagesReads()).toBe(1); + }); + + it('CONTROL: a read already on the wire is joined at once, not waited behind', async () => { + let answerWire: () => void = () => undefined; + fetchMock.mockImplementationOnce( + () => new Promise((resolve) => { + answerWire = () => resolve(new Response(JSON.stringify(PAYLOAD), { status: 200 })); + }), + ); + settle.beginRequest(); // the page is still loading, and never goes quiet here + const listed = io.fetchListedPackageIds(); // a Studio-side read, which does not wait + await vi.advanceTimersByTimeAsync(0); + expect(packagesReads()).toBe(1); + const answer = io.fetchSessionPackages('s1', 'app.crm'); + answerWire(); + await vi.advanceTimersByTimeAsync(0); + await expect(answer).resolves.toEqual([expect.objectContaining({ id: 'app.crm' })]); + await listed; + expect(packagesReads()).toBe(1); + }); + + it('CONTROL: a held list answers with no read and no wait', async () => { + void io.fetchSessionPackages('s1', 'app.crm'); + await vi.advanceTimersByTimeAsync(0); + expect(packagesReads()).toBe(1); + settle.beginRequest(); + const again = io.fetchSessionPackages('s1', 'app.crm'); + await vi.advanceTimersByTimeAsync(0); + await expect(again).resolves.toEqual([expect.objectContaining({ id: 'app.crm' })]); + expect(packagesReads()).toBe(1); + }); +}); From 1e33395d81e6a13dc833a248ca5759d11494331d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:56:20 +0000 Subject: [PATCH 2/2] fix(console): the settle signal's test reset also clears its counted flag Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgUVVocvc9dVySV9DVf --- ui/packages/app-shell/src/observability/settleSignal.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ui/packages/app-shell/src/observability/settleSignal.ts b/ui/packages/app-shell/src/observability/settleSignal.ts index 304d3863415..3f496680bff 100644 --- a/ui/packages/app-shell/src/observability/settleSignal.ts +++ b/ui/packages/app-shell/src/observability/settleSignal.ts @@ -178,6 +178,7 @@ export function installSettleSignalGlobal(): void { /** Test-only: reset the counter and listeners to a clean state. */ export function __resetSettleSignal(): void { pending = 0; + counted = false; listeners.clear(); idleWaiters = []; }