Skip to content

Commit 832dc48

Browse files
perf(app-shell): a cold Console load asks the app bundle the moment the app list answers (#38252)
Fixes #38170 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在应用页面冷启动时,控制台拿到应用列表的同一刻就去请求应用包,不再等界面重绘一轮;机器忙时页面标题出现的中位时间从约 2.3 秒降到约 2.0 秒,空闲机器上没有可测的变化。 - 为什么做:属于「控制台首屏 2.5 秒内打开」专题,也是端到端测试在忙碌机器上等标题偶发超时的成因之一。 - 出错会怎样:最坏是应用包被多请求一次或晚一点请求,页面仍按原路读取并正常显示;可直接撤回本改动。 - 要你做什么:无。 ## What changes On an app route the console root (`useAppObjectScopePrefetch`) entered the app's metadata bundle from an effect of the render that names the app. On a cold load the app list is still on the wire when that hook mounts, so a full tree re-render (and the effects after it) sat between the `GET /api/v1/meta/app` answer and `GET /api/v1/meta/app/NAME/bundle`. The hook now also asks for the bundle in the app list's own answer: it joins the provider's eager app-list read (`ensureType('app')` never asks again), resolves the route segment against that list exactly as the render does (`matchAppBySegment`: package id first, then name), and enters that app through the same adapter. The render-time effect sees that this visit already entered the app and does not ask again; any other visit (another app, a return after leaving, an app list already in hand) enters as before. Only WHEN changes. The request, its adapter and session, the app it names and the number of requests are the same: - **Same auth/session**: the bundle is still asked through the adapter's own `loadAppBundle` (pinned: `this` is the adapter). - **An app the user cannot see**: the app list is still what names the app. A route naming an app the list does not hold asks no bundle, before or after the list lands (pinned). `AppContent`, which draws the refusal, is untouched. - **Nothing moved ahead of the permission read**: the root's bundle entry never waited on `/auth/me/permissions` (the hook sits above the permission scope by design), and the bundle answer is filtered by the server's own checks. `AppContent`'s entry, below the permission read, is unchanged. - **Same number of requests or fewer**: one bundle request and one app-list read per cold load (pinned); measured API request counts are unchanged (below). ## Why The card's suggested direction was to start the bundle "as soon as the route names the app". On current main the route cannot name the bundle on its own: the `/apps/SEGMENT` segment is the package id (ADR-0048) or the app name, the bundle route is keyed by the app name, a package may ship several apps, and only the app list says whether this user may see the app. Asking by segment would fetch a wrong or refused bundle on most canonical URLs and add a request for apps the user cannot see, so the earliest point that keeps the invariants is the app list's answer. That is what this change does. ## Tests - New top-level `describe` in the shared harness `appObjectScope-12811.test.tsx` (5 tests): the ordering pin (the bundle request lands after the app list answers and before the render that names the app), bundle named by app not by segment through the same adapter, the hidden-app control, the leave-before-answer control, and the list-in-hand control (entered once, from the render). - Ablation, one mutation at a time on the committed fix, restored to the HEAD blob each time (`scripts/ablation-replace.mjs`, `git diff HEAD` empty after restore): - list-answer entry disabled: the ordering pin goes red (`expected 4 to be less than 3`: the bundle comes after `render:named`), the four controls stay green. - render-time de-duplication removed: two tests red (`expected [ 'bundle:crm', 'bundle:crm' ] to deeply equal [ 'bundle:crm' ]`). - The 42 test files that reach the changed hook (`useAppObjectScopePrefetch`, `enterAppBundle`, `loadAppBundle`, `ConsoleShell`, `ConnectedShell`, including the App-level boot-wave and boot-reads-once pins): 42 files, 334 tests passed. The full app-shell package (2445 test files) was not run locally; CI's `Test UI` runs it. ## Acceptance notes - Measured on `e3bdc748` (before) and this branch (after), the card's lane rebuilt locally: backend `objectstack dev --seed-admin --fresh` on examples/app-showcase, Console `vite build` with `VITE_BASE_PATH=/`, `vite preview` proxying to it, Playwright Chromium, a fresh context per load, route `/apps/showcase_app/page/showcase_project_workspace`, heading `New Project + Tasks`. Before and after were served side by side from two `vite preview`s and alternated in blocks, 27 cold loads each, idle and with four CPU-bound processes on a 4-core box. Absolute times are readings on a shared box. - **Hop order** (same in both builds): runtime/config + get-session + discovery, then me/localization, then me/permissions + organization reads + i18n + `meta/app` + preferences, then the bundle. Three serial API hops before the bundle request, before and after. The card's five-hop chain did not reproduce on `e3bdc748`: `me/apps` and `meta/object?package` leave in the same wave as the bundle, not before it. - **What moved** is the render gap inside that last hop: | median over 27 cold loads | idle before | idle after | busy before | busy after | |:---|---:|---:|---:|---:| | bundle request leaves (ms after goto) | 946 | 764 | 1343 | 974 | | bundle request leaves after `meta/app` lands (ms) | 226 | 19 | 378 | 17 | | later of bundle and package list answered (ms, n=12) | 1087 | 1046 | 1557 | 1421 | | heading visible (ms) | 1668 | 1690 | 2300 | 2035 | | heading visible, p90 / max (ms) | 1803 / 2295 | 1892 / 2256 | 2700 / 2745 | 2560 / 2687 | | API requests before the heading | 33 | 33 | 34 | 33 | - **Heading-ready on an idle box did not move outside noise.** A delay probe (1.5 s held on one request family, 3 loads each) puts the heading behind both the bundle and `meta/object?package` (+1.0 to +1.5 s each), and not behind `me/apps`, `meta/view`, the approvals read, settings, agents or the inbox reads. The two critical reads leave within ~60 ms of each other and are answered by the server together, so on an idle box the bundle's earlier start buys about 40 ms of "both in hand". On the busy box the gain is larger because the render gap was larger. - Not reproduced red: the 5 s heading budget held in every load measured here, before and after (worst 2745 ms before, 2687 ms after), so the card's second acceptance line (the busy-runner beforeEach wait) is not shown red-to-green locally; it is the Live E2E UI lane's to confirm. - What remains on the cold path is outside this card's surface: the gate between the session answer and the `meta/app` request (sign-in locale, adapter connect and the route guards in the Console app), the server's time to answer the bundle and the package object list together, and the client render after both land (300 to 1000 ms on the busy box). ## Verification Read first, by risk: 1. `ui/packages/app-shell/src/console/appObjectScope.ts`, the two effects added before the render-time bundle effect, and the `enteredByList` check in it: the de-duplication between the two entry points is the only place a second bundle request could come from. 2. `ui/packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx`, the `objectstack#38170` describe at the end. 3. `.changeset/38170-bundle-on-app-list.md`. Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx` from the repository root prints `Tests 28 passed (28)`. <details><summary>Local gates at 4f299c6: the derived set (38 of 38 run, exit codes captured before any pipe) plus the app-shell type-check and the narrowed suite</summary> - exit 0 · `pnpm --filter @object-ui/app-shell type-check` - exit 0 · `pnpm exec vitest run (the 42 files that reach the changed hook)` - exit 0 · `node scripts/check-adr-0087-registration.mjs --base origin/main` - exit 0 · `node scripts/check-adr-0087-registration.mjs --self-test` - exit 0 · `node scripts/check-changeset-no-major.mjs --base origin/main` - exit 0 · `node scripts/check-closing-keyword-parity.mjs` - exit 0 · `node scripts/check-closing-keyword-parity.mjs --self-test` - exit 0 · `node scripts/check-comment-mask-corpus.mjs` - exit 0 · `node scripts/check-empty-changeset.mjs --base origin/main` - exit 0 · `node scripts/check-empty-changeset.mjs --self-test` - exit 0 · `node scripts/check-sdui-manifest.mjs` - exit 0 · `node scripts/check-sdui-manifest.mjs --self-test` - exit 0 · `node scripts/ci/snapshot-next.mjs --self-test` - exit 0 · `node scripts/pm/check-governed-queue-guard.mjs --self-test` - exit 0 · `node scripts/pm/release-rehearsal-clone.mjs --self-test` - exit 0 · `node scripts/release-pending-publish.mjs --self-test` - exit 0 · `pnpm --dir ui exec vitest run scripts/` - exit 0 · `pnpm --filter @objectstack/spec run check:duration-unit-keys` - exit 0 · `pnpm check:adr-anchors` - exit 0 · `pnpm check:changeset-gate-self-tests` - exit 0 · `pnpm check:closed-ceremony-text` - exit 0 · `pnpm check:cross-package-test-inputs` - exit 0 · `pnpm check:dispatcher-error-vocabulary` - exit 0 · `pnpm check:driver-memory-census` - exit 0 · `pnpm check:engine-double-contract` - exit 0 · `pnpm check:gitlink-declared` - exit 0 · `pnpm check:nul-bytes` - exit 0 · `pnpm check:published-files` - exit 0 · `pnpm check:query-options-erasure` - exit 0 · `pnpm check:refd-timer-probe` - exit 0 · `pnpm check:registry-log-declared` - exit 0 · `pnpm check:rest-log-spy-declared` - exit 0 · `pnpm check:skill-identifier-liveness` - exit 0 · `pnpm check:test-source-alias` - exit 0 · `pnpm check:tier-file-adoption` - exit 0 · `pnpm check:type-check-coverage` - exit 0 · `pnpm check:type-check-debt` - exit 0 · `pnpm check:undeclared-dep-imports` - exit 0 · `pnpm check:watch-hint-literal` - exit 0 · `pnpm check:where-matcher` - `node scripts/pm/dispatch-gates.mjs --ran`: 38 derived families accounted for, 38 run, 0 NOT-MEASURED, 0 UNRUN. - The app-shell `type-check` ran after building its dependency closure (`turbo run build --filter='@object-ui/app-shell^...'`, exit 0); both `tsc` programs exit 0. - `pnpm exec eslint` on the two changed sources: 0 errors; 3 more `no-explicit-any` warnings than base, from the test's `as any` casts on the adapter double, the shape the harness already uses. - CI owns the rest: `Test UI` (the full app-shell package), `Lint UI`, `Type Check UI`, `Build & E2E UI`, `Live E2E UI`. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` is CI's (`Lint UI`); eslint on the changed files reports 0 errors. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcWDb7S8Z7oRDGzvfT2 --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcWDb7S8Z7oRDGzvfT2)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 975e34e commit 832dc48

3 files changed

Lines changed: 210 additions & 2 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
perf(app-shell): on a cold Console load the app bundle request leaves the moment the app list answers
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On an app route the console root asked the app's metadata bundle (`GET /api/v1/meta/app/:name/bundle`) from an effect of the render that names the app, so a whole tree re-render sat between the app list's answer (`GET /api/v1/meta/app`) and the bundle request: 226 ms on an idle box and 378 ms on a busy one (medians over 27 cold loads each). The bundle is now asked in the app list's own answer. The app list still decides which app the route names (the route segment is a package id or an app name) and whether the user may see it, so it is the same request, through the same adapter and session, for the same app, once; a route naming an app the list does not hold still asks no bundle. Measured on the live lane's build (backend `--fresh`, `vite build` with `VITE_BASE_PATH=/`, `vite preview`), the bundle request moved from 946 ms to 764 ms after navigation idle and from 1343 ms to 974 ms with four CPU-bound processes running; the page heading moved from 2300 ms to 2035 ms (median) on the busy box and did not move outside noise on the idle one.

‎ui/packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,3 +617,153 @@ describe('objectstack#35455 — round trips until an app route can render, count
617617
expect(seen).toEqual([['app'], ['page']]);
618618
});
619619
});
620+
621+
/**
622+
* objectstack#38170 — the bundle request leaves the moment the app list lands.
623+
*
624+
* Measured on a cold Console load (backend `--fresh`, `vite build` with
625+
* `VITE_BASE_PATH=/`, `vite preview`): the bundle request left one whole tree
626+
* re-render after the app list answered — 226 ms later idle, 378 ms on a busy
627+
* box (medians) — because it was asked from an effect of the render that
628+
* named the app. It is now asked in the app list's own answer.
629+
*
630+
* The app list is still what names the app — the route carries a package id
631+
* (ADR-0048) or a name, and an app the list does not hold has no bundle
632+
* asked — so the request is the same one, through the same adapter, once.
633+
*/
634+
describe('objectstack#38170 — the console root enters the bundle as the app list lands', () => {
635+
const PACKAGED = [{ name: 'crm', _packageId: CRM, navigation: [] }];
636+
637+
/** An adapter whose app list answers only when the test says so, and which records the order things happen in. */
638+
function makeHeldAdapter(events: string[], apps: unknown[]) {
639+
const calls: string[] = [];
640+
const base = makeAdapter(calls, apps) as any;
641+
let answer!: () => void;
642+
const held = new Promise<void>((resolve) => { answer = resolve; });
643+
const client = base.getClient();
644+
const adapter = {
645+
...base,
646+
getClient: () => ({
647+
meta: {
648+
...client.meta,
649+
getItems: (type: string, options?: Record<string, unknown>) => {
650+
if (type !== 'app' || options) return client.meta.getItems(type, options);
651+
events.push('list:asked');
652+
return held.then(() => {
653+
events.push('list:answered');
654+
return client.meta.getItems(type);
655+
});
656+
},
657+
},
658+
}),
659+
loadAppBundle(this: unknown, app: string) {
660+
events.push(`bundle:${app}${this === adapter ? '' : ':foreign-this'}`);
661+
return Promise.resolve();
662+
},
663+
};
664+
return { adapter: adapter as Parameters<typeof MetadataProvider>[0]['adapter'], answer, calls };
665+
}
666+
667+
/** Records each render's view of the app list, beside the requests. */
668+
function Recorder({ events }: { events: string[] }) {
669+
const { apps } = useMetadata();
670+
useAppObjectScopePrefetch();
671+
const named = Array.isArray(apps) && apps.length > 0;
672+
if (events[events.length - 1] !== `render:${named ? 'named' : 'empty'}`) events.push(`render:${named ? 'named' : 'empty'}`);
673+
return null;
674+
}
675+
676+
function mountHeld(url: string, apps: unknown[] = PACKAGED) {
677+
sessionStorage.clear();
678+
const events: string[] = [];
679+
const held = makeHeldAdapter(events, apps);
680+
const view = render(
681+
<AdapterCtx.Provider value={held.adapter as any}>
682+
<MetadataProvider adapter={held.adapter}>
683+
<MemoryRouter initialEntries={[url]}>
684+
<Recorder events={events} />
685+
</MemoryRouter>
686+
</MetadataProvider>
687+
</AdapterCtx.Provider>,
688+
);
689+
return { events, ...held, view };
690+
}
691+
692+
const bundles = (events: string[]) => events.filter((e) => e.startsWith('bundle:'));
693+
694+
it('asks the bundle in the app list answer, before the render that names the app', async () => {
695+
const { events, answer, calls, adapter } = mountHeld(`/apps/${CRM}/crm_account`);
696+
await waitFor(() => expect(events).toContain('list:asked'));
697+
expect(bundles(events)).toEqual([]);
698+
await act(async () => answer());
699+
await waitFor(() => expect(events).toContain('render:named'));
700+
await new Promise((resolve) => setTimeout(resolve, 50));
701+
// The ordering pin: the request is not sequenced after the render (and
702+
// the boot reads it waits on) any more. Reverting to the render-time
703+
// entry puts `bundle:crm` after `render:named` and turns this red.
704+
const at = events.indexOf('bundle:crm');
705+
expect(at).toBeGreaterThan(events.indexOf('list:answered'));
706+
expect(at).toBeLessThan(events.indexOf('render:named'));
707+
// Same request count: entered once, the app list read once.
708+
expect(bundles(events)).toEqual(['bundle:crm']);
709+
expect(calls.filter((c) => c === 'app')).toEqual(['app']);
710+
// `AppContent` reuses the root's entry: still one bundle request.
711+
enterAppBundle(adapter, 'crm');
712+
expect(bundles(events)).toEqual(['bundle:crm']);
713+
});
714+
715+
it('names the bundle by the app, never by the route segment (ADR-0048), through the same adapter', async () => {
716+
const { events, answer } = mountHeld(`/apps/${CRM}/crm_account`);
717+
await act(async () => answer());
718+
await waitFor(() => expect(events).toContain('render:named'));
719+
await new Promise((resolve) => setTimeout(resolve, 50));
720+
// `app.crm` is the package id the route carries; `crm` is the app it names.
721+
expect(bundles(events)).toEqual(['bundle:crm']);
722+
});
723+
724+
it('CONTROL: an app the list does not hold (one this user may not see) has no bundle asked, before or after the list', async () => {
725+
const { events, answer } = mountHeld('/apps/hr/hr_employee');
726+
await act(async () => answer());
727+
await waitFor(() => expect(events).toContain('render:named'));
728+
await new Promise((resolve) => setTimeout(resolve, 50));
729+
expect(bundles(events)).toEqual([]);
730+
});
731+
732+
it('CONTROL: outside an app, or after leaving before the list lands, nothing is entered', async () => {
733+
const outside = mountHeld('/home');
734+
await act(async () => outside.answer());
735+
await waitFor(() => expect(outside.events).toContain('render:named'));
736+
const left = mountHeld(`/apps/${CRM}/crm_account`);
737+
await waitFor(() => expect(left.events).toContain('list:asked'));
738+
left.view.unmount();
739+
await act(async () => left.answer());
740+
await new Promise((resolve) => setTimeout(resolve, 50));
741+
expect(bundles(outside.events)).toEqual([]);
742+
expect(bundles(left.events)).toEqual([]);
743+
});
744+
745+
it('CONTROL: an app list already in hand enters the bundle from the render, once, as before', async () => {
746+
const calls: string[] = [];
747+
const entered: string[] = [];
748+
// The first mount reads the list into the session; the second answers from it.
749+
const first = mountHeld(`/apps/${CRM}/crm_account`);
750+
await act(async () => first.answer());
751+
await waitFor(() => expect(first.events).toContain('bundle:crm'));
752+
cleanup();
753+
const adapter = Object.assign(makeAdapter(calls, PACKAGED) as object, {
754+
loadAppBundle: (app: string) => { entered.push(app); return Promise.resolve(); },
755+
}) as Parameters<typeof MetadataProvider>[0]['adapter'];
756+
render(
757+
<AdapterCtx.Provider value={adapter as any}>
758+
<MetadataProvider adapter={adapter}>
759+
<MemoryRouter initialEntries={[`/apps/${CRM}/crm_account`]}>
760+
<Prefetch />
761+
</MemoryRouter>
762+
</MetadataProvider>
763+
</AdapterCtx.Provider>,
764+
);
765+
await waitFor(() => expect(entered).toEqual(['crm']));
766+
await new Promise((resolve) => setTimeout(resolve, 50));
767+
expect(entered).toEqual(['crm']);
768+
});
769+
});

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

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888
* permission read rather than after it, as the whole list used to.
8989
*/
9090

91-
import { useEffect } from 'react';
91+
import { useEffect, useRef } from 'react';
9292
import { matchRoutes, useLocation } from 'react-router-dom';
9393
import { isRecordPageOf, useAdapter, useMetadata, type AnsweredLoadFailure, type MetadataContextValue } from '@object-ui/react';
9494
import { defaultRecordPageObject } from '@objectstack/spec/ui';
@@ -926,6 +926,9 @@ function inRelatedOrder(scope: AppObjectScope, relatedNames: readonly string[]):
926926
return { ...scope, objects } as AppObjectScope;
927927
}
928928

929+
/** An app as the app list answers it, read for the route lookup alone. */
930+
type ListedApp = { name?: unknown; _packageId?: unknown } & Record<string, unknown>;
931+
929932
/** An adapter that loads app metadata bundles (`ObjectStackAdapter.loadAppBundle`). */
930933
type BundleHost = { loadAppBundle?: (appName: string) => unknown };
931934

@@ -989,10 +992,55 @@ export function useAppObjectScopePrefetch(): void {
989992
useEffect(() => {
990993
if (recordRoute && ensureType) void ensureType('page');
991994
}, [recordRoute, ensureType]);
995+
// objectstack#38170 — the bundle leaves the moment the app list lands, not
996+
// one render later. The list is what names the app: the route carries a
997+
// package id (ADR-0048) or a name, and only an app the list holds (an app
998+
// this user may see) has its bundle asked at all, so the request is the one
999+
// the effect below would make, from the same adapter, for the same app. On a
1000+
// cold load the list is still on the wire when this mounts, and waiting for
1001+
// the render that names the app put a re-render of the whole tree between
1002+
// the list's answer and the bundle request. `ensureType('app')` joins the
1003+
// provider's eager app-list read: it never asks the list again.
1004+
const routeSegment = segments[0] === 'apps' ? segments[1] : undefined;
1005+
const ensureTypeRef = useRef(ensureType);
1006+
useEffect(() => {
1007+
ensureTypeRef.current = ensureType;
1008+
});
1009+
const listEnteredRef = useRef<string | null>(null);
1010+
useEffect(
1011+
() => () => {
1012+
// The entry belongs to the visit it was made for: leaving the app, or an
1013+
// adapter swap, forgets it, so the next visit enters the app again.
1014+
listEnteredRef.current = null;
1015+
},
1016+
[dataSource, routeSegment],
1017+
);
1018+
useEffect(() => {
1019+
const ensure = ensureTypeRef.current;
1020+
const load = dataSource?.loadAppBundle;
1021+
// Named by the list in hand already: the effect below enters it now.
1022+
if (bundleAppName || !routeSegment || !dataSource || !ensure || typeof load !== 'function') return;
1023+
let live = true;
1024+
void ensure('app').then((list: unknown) => {
1025+
if (!live) return;
1026+
const listed = matchAppBySegment(Array.isArray(list) ? (list as ListedApp[]) : [], routeSegment);
1027+
const name = typeof listed?.name === 'string' && listed.name ? listed.name : undefined;
1028+
if (!name || rootEnteredApps.has(name)) return;
1029+
listEnteredRef.current = name;
1030+
void load.call(dataSource, name);
1031+
});
1032+
return () => {
1033+
live = false;
1034+
};
1035+
}, [dataSource, routeSegment, bundleAppName]);
9921036
useEffect(() => {
9931037
const load = dataSource?.loadAppBundle;
9941038
if (!dataSource || !bundleAppName || typeof load !== 'function') return;
995-
void load.call(dataSource, bundleAppName);
1039+
// Entered when the list landed, in this same visit: that request is the
1040+
// entry, and asking again would revalidate a bundle still on the wire.
1041+
const enteredByList = listEnteredRef.current === bundleAppName;
1042+
listEnteredRef.current = null;
1043+
if (!enteredByList) void load.call(dataSource, bundleAppName);
9961044
rootEnteredApps.add(bundleAppName);
9971045
return () => {
9981046
rootEnteredApps.delete(bundleAppName);

0 commit comments

Comments
 (0)