Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/35416-record-open-boot-waves.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<typeof MetadataProvider>[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 = <T,>(label: string, answer: () => T) =>
new Promise<T>((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<string[][]> {
sessionStorage.clear();
const transport = makeHeldAdapter({ bundleOnTheWire });
render(
<MetadataProvider adapter={transport.adapter}>
<MemoryRouter initialEntries={[url]}>
<RootPrefetch />
</MemoryRouter>
</MetadataProvider>,
);
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}`);
});
});
45 changes: 42 additions & 3 deletions ui/packages/app-shell/src/console/appObjectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<MetadataContextValue['readObjectScope']>;
export type AppObjectScope = ReturnType<ReadObjectScope>;
Expand Down Expand Up @@ -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;
Expand All @@ -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),
);
}
34 changes: 34 additions & 0 deletions ui/packages/app-shell/src/observability/settleSignal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Listener>();
let idleWaiters: Array<() => void> = [];

Expand All @@ -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();
}
Expand Down Expand Up @@ -100,6 +103,36 @@ export function whenIdle(timeoutMs = 10_000): Promise<void> {
});
}

/**
* 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<void> {
if (!counted || typeof setTimeout === 'undefined') return Promise.resolve();
return new Promise<void>((resolve) => {
let quietTimer: ReturnType<typeof setTimeout> | 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).
Expand Down Expand Up @@ -145,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 = [];
}
29 changes: 26 additions & 3 deletions ui/packages/app-shell/src/views/studio-design/packages-io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -449,6 +450,14 @@ interface HeldPackageList {

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

/**
* 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;

Expand All @@ -465,9 +474,23 @@ function forgetHeldPackageList(): void {
*/
export async function fetchSessionPackages(session: string, packageId: string): Promise<PkgEntry[]> {
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();
Expand Down
Loading
Loading