Skip to content

Commit ac36606

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgUVVocvc9dVySV9DVf
1 parent 9a8bb83 commit ac36606

6 files changed

Lines changed: 360 additions & 6 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
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
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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:
11+
12+
- 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.
13+
- `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.
14+
- New `whenQuiet(quietMs, maxMs)` in the settle signal; it resolves at once where no data layer counts requests.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#35416 — the console root starts a record route's reads.
5+
*
6+
* `AppContent` mounts below the session's permission read (`/auth/me/permissions`),
7+
* so the page list and the package object list a record route waits for used
8+
* to leave one round trip after that read answered. The root's prefetch
9+
* (`useAppObjectScopePrefetch`, mounted beside the permission read) now asks
10+
* them as soon as the app list names the app: the page list on every record
11+
* route, and the package list beside it under the same rule `AppContent`
12+
* follows (objectstack#35455: not when the bundle answers a miss).
13+
*
14+
* Only the root's prefetch is mounted here, so every read below is one the
15+
* root asked before `AppContent` exists.
16+
*
17+
* CONTROLs: an object's list route asks no page list; a bundle that is a miss
18+
* starts no package list beside the page list.
19+
*/
20+
21+
import { describe, it, expect, vi, afterEach } from 'vitest';
22+
import { act, cleanup, render } from '@testing-library/react';
23+
import { MemoryRouter } from 'react-router-dom';
24+
import { MetadataProvider } from '../../providers/MetadataProvider';
25+
import { useAppObjectScopePrefetch } from '../appObjectScope';
26+
27+
const CRM = 'app.crm';
28+
const APPS = [{ name: 'crm', _packageId: CRM, navigation: [] }];
29+
const OBJECTS = [{ name: 'crm_account', _packageId: CRM, fields: {} }];
30+
31+
type Adapter = Parameters<typeof MetadataProvider>[0]['adapter'];
32+
33+
/** Every metadata read is held until `release`; `pending` names the held ones. */
34+
function makeHeldAdapter(options: { bundleOnTheWire: boolean }) {
35+
const held: Array<{ label: string; go: () => void }> = [];
36+
const hold = <T,>(label: string, answer: () => T) =>
37+
new Promise<T>((resolve) => held.push({ label, go: () => resolve(answer()) }));
38+
const list = (type: string, packageId?: string) => {
39+
const all: any[] = type === 'app' ? APPS : type === 'object' ? OBJECTS : [];
40+
return { type, items: structuredClone(packageId ? all.filter((o) => o._packageId === packageId) : all) };
41+
};
42+
const adapter = {
43+
clearCache: vi.fn(),
44+
invalidateCache: vi.fn(),
45+
getObjectSchema: (name: string) => hold(`object/${name}`, () => OBJECTS.find((o) => o.name === name)),
46+
getClient: () => ({
47+
meta: {
48+
getItems: (type: string, opts?: { packageId?: string; names?: readonly string[] }) =>
49+
hold(
50+
opts?.names ? `${type}?names=${opts.names.join(',')}` : opts?.packageId ? `${type}?package=${opts.packageId}` : type,
51+
() => list(type, opts?.packageId),
52+
),
53+
getItem: (type: string, name: string) => hold(`${type}/${name}`, () => ({ item: undefined })),
54+
},
55+
}),
56+
// A bundle still on the wire: the provider answers its reads `pending`.
57+
...(options.bundleOnTheWire
58+
? { peekAppBundle: () => ({ status: 'loading', settled: new Promise(() => undefined) }) }
59+
: {}),
60+
} as unknown as Adapter;
61+
return { adapter, pending: () => held.map((h) => h.label).sort(), release: () => held.splice(0).forEach((h) => h.go()) };
62+
}
63+
64+
function RootPrefetch() {
65+
useAppObjectScopePrefetch();
66+
return null;
67+
}
68+
69+
const settle = async () => {
70+
for (let i = 0; i < 6; i++) await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
71+
};
72+
73+
/** The reads the root asks in each wave, for `waveCount` waves. */
74+
async function rootWaves(url: string, bundleOnTheWire: boolean, waveCount = 2): Promise<string[][]> {
75+
sessionStorage.clear();
76+
const transport = makeHeldAdapter({ bundleOnTheWire });
77+
render(
78+
<MetadataProvider adapter={transport.adapter}>
79+
<MemoryRouter initialEntries={[url]}>
80+
<RootPrefetch />
81+
</MemoryRouter>
82+
</MetadataProvider>,
83+
);
84+
const seen: string[][] = [];
85+
await settle();
86+
for (let i = 0; i < waveCount; i++) {
87+
seen.push(transport.pending());
88+
transport.release();
89+
await settle();
90+
}
91+
return seen;
92+
}
93+
94+
afterEach(() => cleanup());
95+
96+
describe('objectstack#35416 — the console root starts a record route\'s reads', () => {
97+
it('a record route: the app list, then the page list and the package list together, before AppContent mounts', async () => {
98+
const [first, second] = await rootWaves('/apps/crm/crm_account/record/r1', true);
99+
expect(first).toEqual(['app']);
100+
expect(second).toEqual(expect.arrayContaining(['page', `object?package=${CRM}`]));
101+
});
102+
103+
it("CONTROL: a bundle that is a miss starts the page list alone, as AppContent's rule says (objectstack#35455)", async () => {
104+
const [first, second] = await rootWaves('/apps/crm/crm_account/record/r1', false);
105+
expect(first).toEqual(['app']);
106+
expect(second).toContain('page');
107+
expect(second).not.toContain(`object?package=${CRM}`);
108+
});
109+
110+
it("CONTROL: an object's list route asks no page list at the root", async () => {
111+
const waves = await rootWaves('/apps/crm/crm_account', true, 3);
112+
expect(waves.flat()).not.toContain('page');
113+
expect(waves[1]).toContain(`object?package=${CRM}`);
114+
});
115+
});

‎ui/packages/app-shell/src/console/appObjectScope.ts‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ import { APP_ROUTE_METADATA_READS } from './appRouteMetadataReads.js';
9191
import { matchAppBySegment } from '../utils/appRoute.js';
9292
import { COMMAND_PALETTE_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_PARAM } from '../urlParams.js';
9393
import type { ReadNamesWithoutViews } from '../hooks/useObjectPresence.js';
94-
import type { BundledRead } from '../providers/bundledReads.js';
94+
import { BUNDLE_MISS, useBundledReads, type BundledRead } from '../providers/bundledReads.js';
9595

9696
type ReadObjectScope = NonNullable<MetadataContextValue['readObjectScope']>;
9797
export type AppObjectScope = ReturnType<ReadObjectScope>;
@@ -947,14 +947,31 @@ export function enterAppBundle(dataSource: unknown, appName: string | undefined)
947947
* scope composes its views from the bundle instead of reading the
948948
* `/meta/view` list before the app was entered. Leaving the app ends the
949949
* entry, so coming back revalidates the bundle as entering it always has.
950+
*
951+
* objectstack#35416 — on a record route it also starts the page list, and
952+
* hands {@link readAppObjectScope} the same page-list and bundle readers
953+
* `AppContent` does, so the record route's reads leave beside the permission
954+
* read instead of one wave after it.
950955
*/
951956
export function useAppObjectScopePrefetch(): void {
952-
const { apps, readObjectScope } = useMetadata();
957+
const metadata = useMetadata();
958+
const { apps, readObjectScope, ensureType, getTypeStatus } = metadata;
959+
const bundledReads = useBundledReads();
953960
const dataSource = useAdapter() as BundleHost | null;
954961
const { pathname, search } = useLocation();
955962
const segments = pathname.split('/').filter(Boolean);
956963
const app = segments[0] === 'apps' && segments[1] ? matchAppBySegment(apps, segments[1]) : undefined;
957964
const bundleAppName = typeof app?.name === 'string' && app.name ? app.name : undefined;
965+
const subPath = segments.slice(2).join('/');
966+
// objectstack#35416 — a record route's page list, asked here rather than
967+
// when `AppContent` mounts below the session's permission read: the route
968+
// asks it on every record route (`APP_ROUTE_METADATA_READS`), so this is
969+
// the same request one wave earlier, and the scope read below can start
970+
// the package object list beside it.
971+
const recordRoute = !!app && !!readObjectScope && matchObjectScopeRoute(subPath, [])?.recordId !== undefined;
972+
useEffect(() => {
973+
if (recordRoute && ensureType) void ensureType('page');
974+
}, [recordRoute, ensureType]);
958975
useEffect(() => {
959976
const load = dataSource?.loadAppBundle;
960977
if (!dataSource || !bundleAppName || typeof load !== 'function') return;
@@ -964,5 +981,27 @@ export function useAppObjectScopePrefetch(): void {
964981
rootEnteredApps.delete(bundleAppName);
965982
};
966983
}, [dataSource, bundleAppName]);
967-
if (app && readObjectScope) readAppObjectScope(readObjectScope, app, segments.slice(2).join('/'), search);
984+
if (!app || !readObjectScope) return;
985+
// The record route's readers, as `AppContent` hands them: the page list and
986+
// its status, and the objects the app bundle says point at the record's.
987+
readAppObjectScope(
988+
readObjectScope,
989+
app,
990+
subPath,
991+
search,
992+
[],
993+
undefined,
994+
() => {
995+
// Read only when the record route asks: the provider's `pages` starts
996+
// the page list when read.
997+
const status = getTypeStatus?.('page');
998+
const pages = metadata.pages;
999+
return {
1000+
pages: Array.isArray(pages) ? (pages as unknown[]) : [],
1001+
settled: status === undefined || status === 'ready' || status === 'error',
1002+
};
1003+
},
1004+
undefined,
1005+
(objectName) => (bundledReads && bundleAppName ? bundledReads.objectsReferencing(bundleAppName, objectName) : BUNDLE_MISS),
1006+
);
9681007
}

‎ui/packages/app-shell/src/observability/settleSignal.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
type Listener = (pending: number) => void;
2323

2424
let pending = 0;
25+
/** Whether any request was ever counted: a data layer wraps its `fetch` here. */
26+
let counted = false;
2527
const listeners = new Set<Listener>();
2628
let idleWaiters: Array<() => void> = [];
2729

@@ -48,6 +50,7 @@ function notify(): void {
4850

4951
/** Mark one request as in-flight. Pair with {@link endRequest}. */
5052
export function beginRequest(): void {
53+
counted = true;
5154
pending += 1;
5255
notify();
5356
}
@@ -100,6 +103,36 @@ export function whenIdle(timeoutMs = 10_000): Promise<void> {
100103
});
101104
}
102105

106+
/**
107+
* objectstack#35416 — resolve once no counted request has been in flight for
108+
* `quietMs` in a row, or after `maxMs` whatever is in flight. A read that is
109+
* not the page's own (the app bar's package list) waits on this so it does
110+
* not share the link with the page's requests while they load.
111+
*
112+
* Resolves at once where nothing was ever counted (no data layer wraps its
113+
* `fetch` here, as in a host or a test without one): there is no page load
114+
* to wait for.
115+
*/
116+
export function whenQuiet(quietMs: number, maxMs: number): Promise<void> {
117+
if (!counted || typeof setTimeout === 'undefined') return Promise.resolve();
118+
return new Promise<void>((resolve) => {
119+
let quietTimer: ReturnType<typeof setTimeout> | undefined;
120+
const finish = () => {
121+
if (quietTimer !== undefined) clearTimeout(quietTimer);
122+
clearTimeout(capTimer);
123+
listeners.delete(onChange);
124+
resolve();
125+
};
126+
const onChange = (now: number) => {
127+
if (quietTimer !== undefined) clearTimeout(quietTimer);
128+
quietTimer = now === 0 ? setTimeout(finish, quietMs) : undefined;
129+
};
130+
const capTimer = setTimeout(finish, maxMs);
131+
listeners.add(onChange);
132+
onChange(pending);
133+
});
134+
}
135+
103136
/**
104137
* Wrap a `fetch` so each call increments the in-flight counter before the
105138
* request and decrements it when the promise settles (success or failure).

‎ui/packages/app-shell/src/views/studio-design/packages-io.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
validateObjectNamespacePrefix,
3939
} from '@objectstack/spec/kernel';
4040
import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js';
41+
import { whenQuiet } from '../../observability/settleSignal.js';
4142

4243
export interface PkgEntry {
4344
id: string;
@@ -449,6 +450,14 @@ interface HeldPackageList {
449450

450451
const heldPackageLists = new WeakMap<typeof fetch, HeldPackageList>();
451452

453+
/**
454+
* objectstack#35416 — how long the page's counted requests must stay quiet
455+
* before {@link fetchSessionPackages} starts its read, and the longest it
456+
* waits for that (a page that never goes quiet still gets its entries).
457+
*/
458+
export const SESSION_PACKAGE_READ_QUIET_MS = 750;
459+
export const SESSION_PACKAGE_READ_MAX_WAIT_MS = 8_000;
460+
452461
/** Bumped by every forget, so a read asked before a write never becomes the hold. */
453462
let heldPackageListEpoch = 0;
454463

@@ -465,9 +474,23 @@ function forgetHeldPackageList(): void {
465474
*/
466475
export async function fetchSessionPackages(session: string, packageId: string): Promise<PkgEntry[]> {
467476
const transport = globalThis.fetch;
468-
const held = heldPackageLists.get(transport);
469-
if (held && held.session === session && (held.listed.has(packageId) || held.unlisted.has(packageId))) {
470-
return parsePackages(held.payload);
477+
const heldAnswer = (): PkgEntry[] | null => {
478+
const held = heldPackageLists.get(transport);
479+
return held && held.session === session && (held.listed.has(packageId) || held.unlisted.has(packageId))
480+
? parsePackages(held.payload)
481+
: null;
482+
};
483+
const fromHold = heldAnswer();
484+
if (fromHold) return fromHold;
485+
// objectstack#35416 — the list is the largest response an app page reads
486+
// (megabytes unpacked), and the entries it gates are a shortcut, absent
487+
// while it is unread. So a read it starts waits until the page's own
488+
// requests have gone quiet, instead of sharing the link with the record
489+
// or list the page is opening. A read already on the wire is joined at once.
490+
if (!pendingPackageReads.has(transport)) {
491+
await whenQuiet(SESSION_PACKAGE_READ_QUIET_MS, SESSION_PACKAGE_READ_MAX_WAIT_MS);
492+
const heldSince = heldAnswer();
493+
if (heldSince) return heldSince;
471494
}
472495
const epoch = heldPackageListEpoch;
473496
const payload = await readPackagesPayload();

0 commit comments

Comments
 (0)