Skip to content

Commit 3957126

Browse files
perf(console): start an object list's saved-view read with the route, not after its lazy modules (#35579)
Part of #35535 This PR delivers the card's ask for the object LIST page. It leaves open the record page and the card's expected first-data gain; see Acceptance notes. Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在控制台打开对象列表页时,视图定义提前约 0.3 到 0.6 秒发出;本机实测首条数据的发出时间没有可见变化,用户基本无感。 - 为什么做:控制台首屏往返提速专项的一段,去掉列表页加载组件期间没有请求在跑的空等。 - 出错会怎样:仍是同一个请求,只是提前发出,视图和数据都不变;最坏情况是这次读取失败时列表页会再读一次。可直接撤回。 - 要你做什么:无。 ## What changes - `AppContent` (app-shell console) starts an object list's saved-view read in the commit where the route can render: the route is `:objectName` or `:objectName/view/:viewId`, the app's object scope has settled (its views are in hand from the app bundle, or from the `/meta/view` list it waited for), and the route's object is in the objects `ObjectView` is handed. Before this, the read left only when `ObjectView` itself committed. That waits for the list subtree's nested lazy modules (plugin-form, the icon chunks and others), because the subtree's effects run only once nothing in it is suspended. - The early read is the reader's own call, `dataSource.listViewOverrides(objectName)`, not a new request. Outside a draft preview the adapter answers `ObjectView`'s `listViews` and `listViewOverrides` from one stored, shared one-object read (`readObjectViewRows`: `GET /meta/view?object=OBJECT`, or the stored whole list narrowed). So the list joins the early read when it is in flight, or reads what it stored once it has landed. The two helpers (`objectViewRouteObject`, `prefetchObjectViewRows`) live in `console/appObjectScope.ts`, which is not exported from the package. - When no early read is started: under a draft preview (`listViews` reads another request there); on a route whose object the app does not serve; on a pseudo-route with no app named by the URL; with an adapter that lacks either reader. The record page is unchanged. `ObjectView.tsx`, `MetadataProvider.tsx`, spec, server and `ui/apps/console` are untouched. Read first, by risk: 1. `ui/packages/app-shell/src/console/AppContent.tsx`: the new effect beside `routeReadsSettled`. The risk is its gate, because an early read on a route `ObjectView` never mounts on would be an extra request. 2. `ui/packages/app-shell/src/console/appObjectScope.ts`, `prefetchObjectViewRows`: the claim that this is the same request as the reader's. 3. `ui/packages/app-shell/src/views/ObjectView.refreshRereadsViews-13057.test.tsx`: the join pin against a real `ObjectStackAdapter`. Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/console/__tests__/AppContent.routeChunkPreload-12980.test.tsx packages/app-shell/src/views/ObjectView.refreshRereadsViews-13057.test.tsx`. Expected output: `Test Files 2 passed`, `Tests 10 passed`. ## Tests - `AppContent.routeChunkPreload-12980.test.tsx`, a new top-level describe in the existing chunk-gate harness: - (c) The read leaves once the route can render, while the `ObjectView` chunk import is still pending, and is not repeated after the chunk lands. - (d) CONTROL: an object the route does not serve sends no read. - (e) CONTROL: moving to a second object reads that object once. - (f) CONTROL: a page route sends none. - `ObjectView.refreshRereadsViews-13057.test.tsx`, a new top-level describe with the real page and a real adapter: an early read still on the wire is joined, and one that has landed is read back. In both cases there is one `/meta/view` request per open. - Both files have a module-top `import '@objectstack/lint'`, because `check:test-source-alias` flags the dynamic import their source reaches. - Ablation (committed fix first): `scripts/ablation-replace.mjs` replaced the effect's `prefetchObjectViewRows(dataSource, viewReadObject);` with `void 0;`. The anchor went from 1 to 0 hits, blob 93b63bc to ae3386c4d2cd. (c) and (e) failed (2 failed, 4 passed). Restored blob 93b63bc equals `HEAD:` and `git diff HEAD` is empty. <details><summary>Test and gate readings (head 335afc2; the last commit before it changed only the changeset prose)</summary> - Two files: `Test Files 2 passed (2)`, `Tests 10 passed (10)`, os-verify-lock exit 0 (at b1ab94e, which has the same test and source bytes as head). - `pnpm --filter @object-ui/app-shell run type-check`: exit 0, both programs (b1ab94e). - `dispatch-gates --commands`: 38 derived families, all run, all exit 0 except the two below. `--ran` reconciliation: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN. - `check:test-source-alias` was red on the first run, because the two edited test files reach a dynamic `@objectstack/lint` import. Both files were fixed with the module-top import, and the gate then exited 0. - app-shell type-check was first red with TS2493 on the untyped `vi.fn` mock. The mock was typed, and the check then exited 0. - The changeset gates (empty, no-major, ADR-0087 registration, changeset-fixed) and nul-bytes were re-run on 335afc2: all exit 0. - `pnpm check:new-line-citations` (ui): 0 new citations. </details> ## Acceptance notes - The record page's view read is not `ObjectView`'s, and this PR does not change it. On `/apps/APP/OBJECT/record/ID` the request is the WHOLE `/meta/view` list, not `?object=`. `ObjectView` does not mount there. The record's own data read leaves 200-290 ms before it. No early read can be "the same request `ObjectView` sends" on that route, so per the ruling zone it is left alone (readings below: 1 `meta/view` per load, gap unchanged). - The card expected first data to move up with the view read, and that mechanism is refuted. The first list data read is asked when the list mounts, not when the view read answers. Two single-load delay probes on the built console show this: - Holding `meta/view?object=` for 1.5 s did not delay the first `data/showcase_task` read (2562 ms, while the view answered at 3608 ms). A second, identical data read followed the view's answer (3664 ms). - Holding `data/sys_personal_view` for 1.5 s did not delay first data either. - So "data moves up by the same amount" does not hold. In the readings, first data minus bundle is 656-792 ms after vs 714-940 ms before (cold), and 515-1211 ms after vs 760-910 ms before (warm, shared box under load: two after-warm runs were slower). - What the change does give: the saved views are in hand when the list mounts. Per the probe, a view answer landing after the first data read starts a second data read. That second read showed up on 1 of 6 list loads before and 0 of 6 after. The sample is too small to claim more. - Failure path: the adapter stores no rejection. So if the early read fails before the list mounts, the list asks once more (its own `listViews` warning fires once, as before). If the early read is still on the wire, the list joins it and sees the same failure. - Not changed: the package README and `content/docs/frontend`. This adds no prop, export, metadata key or author-visible behaviour, and the claim's file surface excludes both. <details><summary>Layer readings: built console, showcase app, headless Chromium, 3 loads per cell (method of #34211 / #35455)</summary> Tree: objectstack-ai/objectstack. Before = origin/main eed422e; after = this branch at b1b970b, which has the same app-shell source as head. Built console served by `objectstack dev --fresh` (example-showcase) on a private port. cold = cookie only; warm = cookie plus stored Bearer. gap = from the app bundle answering to `meta/view` leaving. Times are shared-box ms. | page / posture | before: max layers · gap · meta/view per load | after: max layers · gap · meta/view per load | |---|---|---| | list cold | 10/12/12 · 725/635/883 · 1/1/1 | 11/13/10 · 251/277/221 · 1/1/1 | | list warm | 10/11/11 · 649/856/772 · 1/1/1 | 9/12/12 · 360/327/363 · 1/1/1 | | record cold (whole list, not ObjectView's) | 13/12/11 · 511/722/551 · 1/1/1 | 13/13/12 · 491/718/607 · 1/1/1 | | record warm (whole list, not ObjectView's) | 13/13/8 · 486/451/709 · 1/1/1 | 8/12/10 · 561/646/650 · 1/1/1 | - On the list, the view read now starts 221-363 ms after the bundle. That remainder is the render of the console chrome in the same commit: the effect fires after the commit. - Before the change, the `ObjectView` chunk itself had loaded before the bundle answered (route chunk preload). What filled the gap was plugin-view, plugins-views, objectViewOptions and plugin-form, plus 25-62 lazy icon and helper chunks. - Max layers stay within noise. On the list, the view read's layer dropped by about one (L9-L10 before, L8-L9 after). The first data read still sits behind the list's mount. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dda665f commit 3957126

5 files changed

Lines changed: 223 additions & 6 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
perf(console): an object list's saved-view read starts with the route, not after the list's lazy modules
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Opening an object's list (`/apps/APP/OBJECT`, or one of its views) read the object's saved views (`GET /api/v1/meta/view?object=OBJECT`) only once the list page had mounted, which waits for the list's lazy modules to load. On the built console that read left 486-883 ms after the app bundle answered, with no request in flight. The console now starts the same read as soon as the route can render (the app's object scope has settled with the route's object in it), so it runs while those modules load, and the list page joins it when it mounts: still one request per open. The list's first data page is still asked when the list mounts; the saved views are now in hand by then.
11+
12+
Not started under a draft preview (`?preview=draft`), whose list read is a different request, nor on a route whose object the app does not serve. A record page is unchanged. No props, exports or metadata change.

‎ui/packages/app-shell/src/console/AppContent.tsx‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ import {
6767
} from '../hooks/useNavMemberGates.js';
6868
import { resolveSetupAppPath } from './ConsoleShell.js';
6969
import { APP_ROUTE_METADATA_READS, collectRoutePaths, metadataReadsForAppRoute, type LazyMetadataType } from './appRouteMetadataReads.js';
70-
import { enterAppBundle, readAppObjectScope } from './appObjectScope.js';
70+
import { enterAppBundle, objectViewRouteObject, prefetchObjectViewRows, readAppObjectScope } from './appObjectScope.js';
7171
import { preferLocal } from '../utils/preferLocal.js';
7272
import {
7373
packagedActionsStudioPath,
@@ -589,6 +589,20 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
589589
].join(',');
590590
const bucketsSettled = useLazyMetadataSettled(routeReadsKey, ensureType, getTypeStatus);
591591
const routeReadsSettled = bucketsSettled && (!objectScope || objectScopeReady);
592+
// objectstack#35535 — an object's list reads its saved views when
593+
// `ObjectView` mounts, which waits for the list's lazy modules. Its read
594+
// starts here instead, in the commit where the route can render: the scope
595+
// has settled with its views in hand (the app bundle, or the `/meta/view`
596+
// list it waited for), so the read joins that and asks nothing new, and the
597+
// route's object is one `ObjectView` draws. Only on an app the URL names, and
598+
// outside a draft preview, whose list read is another request.
599+
const viewReadObject = objectViewRouteObject(appSubPath, hostRoutePaths);
600+
const viewReadReady =
601+
!!viewReadObject && routeReadsSettled && allObjects.some((o) => o?.name === viewReadObject);
602+
useEffect(() => {
603+
if (!viewReadObject || !viewReadReady || !bundleAppName || previewDrafts) return;
604+
prefetchObjectViewRows(dataSource, viewReadObject);
605+
}, [dataSource, viewReadObject, viewReadReady, bundleAppName, previewDrafts]);
592606
// Set once the first frame past the splash has rendered. After it, a route
593607
// waiting on its buckets draws its skeleton inside the console chrome rather
594608
// than taking the whole console back to the splash.

‎ui/packages/app-shell/src/console/__tests__/AppContent.routeChunkPreload-12980.test.tsx‎

Lines changed: 105 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import '@testing-library/jest-dom/vitest';
2727
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2828
import React from 'react';
2929
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
30-
import { MemoryRouter, Routes, Route } from 'react-router-dom';
30+
import { MemoryRouter, Routes, Route, useNavigate, type NavigateFunction } from 'react-router-dom';
3131
import { AuthProvider, ActiveOrganizationStorage } from '@object-ui/auth';
3232
import type { AuthClient, AuthOrganization } from '@object-ui/auth';
3333

@@ -38,7 +38,7 @@ const chunks = vi.hoisted(() => {
3838
const ready = new Promise<void>((r) => { release = r; });
3939
return { requested: false, splashUpWhenRequested: null as boolean | null, ready, release };
4040
};
41-
return { page: gate(), dashboard: gate() };
41+
return { page: gate(), dashboard: gate(), objectView: gate() };
4242
});
4343

4444
const splashUp = () => document.querySelector('[data-boot-splash]') !== null;
@@ -56,6 +56,18 @@ vi.mock('../../views/DashboardView', async () => {
5656
return { DashboardView: () => <div data-testid="dashboard-view" /> };
5757
});
5858

59+
vi.mock('../../views/ObjectView', async () => {
60+
chunks.objectView.requested = true;
61+
await chunks.objectView.ready;
62+
const { useParams } = await import('react-router-dom');
63+
return {
64+
ObjectView: () => {
65+
const { objectName } = useParams();
66+
return <div data-testid={`object-view-${objectName}`} />;
67+
},
68+
};
69+
});
70+
5971
vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({
6072
...(await importOriginal<typeof import('@object-ui/plugin-designer')>()),
6173
CreateAppPage: () => null,
@@ -78,9 +90,16 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({
7890
useObjectLabel: () => ({ objectLabel: ({ label }: { label?: string }) => label, objectPluralLabel: () => '' }),
7991
}));
8092

93+
/** objectstack#35535 — the two saved-view readers `ObjectView` calls on mount. */
94+
const viewReads = vi.hoisted(() => ({
95+
listViews: vi.fn(async (_objectName: string) => [] as unknown[]),
96+
listViewOverrides: vi.fn(async (_objectName: string) => ({}) as Record<string, unknown>),
97+
}));
8198
const dataSourceStub = {
8299
onConnectionStateChange: () => () => {},
83100
getConnectionState: () => 'connected',
101+
listViews: viewReads.listViews,
102+
listViewOverrides: viewReads.listViewOverrides,
84103
};
85104
vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({
86105
...(await importOriginal<Record<string, unknown>>()),
@@ -139,6 +158,10 @@ vi.mock('@object-ui/react', async (importOriginal) => ({
139158
useMutationInvalidationBridge: () => {},
140159
}));
141160

161+
// The source under test reaches `@objectstack/lint` through a dynamic import;
162+
// its first load is paid here, during collection, never inside a case's clocked
163+
// window (`check:test-source-alias`).
164+
import '@objectstack/lint';
142165
import { AppContent } from '../AppContent';
143166

144167
const USER = 'u_12980';
@@ -255,3 +278,83 @@ describe('the route element chunk loads beside the route reads (objectui#12980)'
255278
watch.stop();
256279
});
257280
});
281+
282+
/**
283+
* objectstack#35535 — an object list's saved-view read starts with the route,
284+
* not when `ObjectView` mounts: it is issued in the commit where the route can
285+
* render, while the list's chunk import is still pending, and it is the call
286+
* `ObjectView` makes (`listViewOverrides`), so the list joins it. That the list
287+
* then asks nothing more is pinned against a real adapter in
288+
* `ObjectView.refreshRereadsViews-13057.test.tsx`.
289+
*/
290+
describe('an object list starts its view read beside its chunk (objectstack#35535)', () => {
291+
let navigateTo: NavigateFunction = () => {};
292+
function NavProbe() {
293+
navigateTo = useNavigate();
294+
return null;
295+
}
296+
function bootList(url: string) {
297+
render(
298+
<AuthProvider authUrl="/api/auth" client={createClient()}>
299+
<MemoryRouter initialEntries={[url]}>
300+
<NavProbe />
301+
<Routes>
302+
<Route path="/apps/:appName/*" element={<AppContent />} />
303+
</Routes>
304+
</MemoryRouter>
305+
</AuthProvider>,
306+
);
307+
}
308+
const prefetched = () => viewReads.listViewOverrides.mock.calls.map(([name]) => name);
309+
310+
beforeEach(() => {
311+
viewReads.listViews.mockClear();
312+
viewReads.listViewOverrides.mockClear();
313+
});
314+
315+
it('(c) the read leaves once the route can render, while the list chunk is still pending, and is not repeated', async () => {
316+
bootList('/apps/crm/showcase_task');
317+
await waitFor(() => expect(chunks.objectView.requested).toBe(true));
318+
// The route's object has not landed: nothing is read yet.
319+
expect(prefetched()).toEqual([]);
320+
321+
await settle(['object'], { object: [{ name: 'showcase_task', label: 'Task' }] });
322+
// The chunk import has not answered, and the read is already out.
323+
expect(screen.queryByTestId('object-view-showcase_task')).not.toBeInTheDocument();
324+
expect(prefetched()).toEqual(['showcase_task']);
325+
expect(viewReads.listViews).not.toHaveBeenCalled();
326+
327+
await act(async () => { chunks.objectView.release(); });
328+
await waitFor(() => expect(screen.getByTestId('object-view-showcase_task')).toBeInTheDocument());
329+
expect(prefetched()).toEqual(['showcase_task']);
330+
});
331+
332+
it('(d) CONTROL: an object the route does not serve sends no read', async () => {
333+
bootList('/apps/crm/showcase_secret');
334+
await settle(['object'], { object: [{ name: 'showcase_task', label: 'Task' }] });
335+
await waitFor(() => expect(screen.getByTestId('console-layout')).toBeInTheDocument());
336+
expect(prefetched()).toEqual([]);
337+
});
338+
339+
it('(e) CONTROL: moving to a second object reads that object once', async () => {
340+
bootList('/apps/crm/showcase_task');
341+
await settle(['object'], {
342+
object: [{ name: 'showcase_task', label: 'Task' }, { name: 'showcase_project', label: 'Project' }],
343+
});
344+
await waitFor(() => expect(screen.getByTestId('object-view-showcase_task')).toBeInTheDocument());
345+
await act(async () => { navigateTo('/apps/crm/showcase_project/view/all'); });
346+
await waitFor(() => expect(screen.getByTestId('object-view-showcase_project')).toBeInTheDocument());
347+
expect(prefetched()).toEqual(['showcase_task', 'showcase_project']);
348+
});
349+
350+
it('(f) CONTROL: a route that draws no object list sends none', async () => {
351+
bootList('/apps/crm/page/welcome');
352+
await act(async () => { chunks.page.release(); });
353+
await settle(['page', 'object'], {
354+
page: [{ name: 'welcome', label: 'Welcome' }],
355+
object: [{ name: 'showcase_task', label: 'Task' }],
356+
});
357+
await waitFor(() => expect(screen.getByTestId('page-view')).toBeInTheDocument());
358+
expect(prefetched()).toEqual([]);
359+
});
360+
});

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,51 @@ function matchObjectScopeRoute(
180180
};
181181
}
182182

183+
/** The route paths whose element is `ObjectView`, the list page of an object. */
184+
const OBJECT_VIEW_ROUTES: readonly string[] = [':objectName', ':objectName/view/:viewId'];
185+
186+
/**
187+
* objectstack#35535 — the object whose list `ObjectView` draws on the route at
188+
* `subPath` (below `/apps/:appName`), or `undefined` on every other route.
189+
* Matched against the same table as the scope's routes, so a static or host
190+
* route that shadows `:objectName` (`search`, `reports`) is not one.
191+
*/
192+
export function objectViewRouteObject(subPath: string, hostPaths: readonly string[] = []): string | undefined {
193+
const routes = [...APP_ROUTE_METADATA_READS.map(({ path }) => ({ path })), ...hostPaths.map((path) => ({ path }))];
194+
const matches = matchRoutes(routes, `/${subPath.replace(/^\/+/, '')}`);
195+
const match = matches?.[matches.length - 1];
196+
if (!match || !OBJECT_VIEW_ROUTES.includes(match.route.path)) return undefined;
197+
return match.params.objectName || undefined;
198+
}
199+
200+
/** An adapter that reads an object's saved views (`ObjectStackAdapter`). */
201+
type ObjectViewRowsHost = {
202+
listViews?: unknown;
203+
listViewOverrides?: (objectName: string) => Promise<unknown>;
204+
};
205+
206+
/**
207+
* objectstack#35535 — start the read of `objectName`'s published views that
208+
* `ObjectView` sends when its list mounts, so it runs while the list's lazy
209+
* modules still load instead of after them.
210+
*
211+
* It is the reader's own call, never a second read: `ObjectView` asks
212+
* `listViewOverrides(objectName)` and `listViews(objectName)`, and outside a
213+
* draft preview the adapter answers both from one stored, shared one-object
214+
* read (`GET /meta/view?object=OBJECT`, or the stored `/meta/view` list it
215+
* narrows). A reader asking while this is on the wire joins it; one asking
216+
* after it landed reads what it stored. A failure is not stored, so the
217+
* reader that asks next asks again and sees it, as it did before.
218+
*
219+
* An adapter without both readers is left alone.
220+
*/
221+
export function prefetchObjectViewRows(dataSource: unknown, objectName: string): void {
222+
const host = dataSource as ObjectViewRowsHost | null | undefined;
223+
if (!host || typeof host.listViews !== 'function' || typeof host.listViewOverrides !== 'function') return;
224+
// Nobody waits on it: a failure is the reader's to see when it asks.
225+
host.listViewOverrides.call(host, objectName).catch(() => undefined);
226+
}
227+
183228
function isRecord(value: unknown): value is Record<string, unknown> {
184229
return !!value && typeof value === 'object' && !Array.isArray(value);
185230
}

‎ui/packages/app-shell/src/views/ObjectView.refreshRereadsViews-13057.test.tsx‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,14 @@ vi.mock('./MetadataInspector', () => ({
8080
}));
8181
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));
8282

83+
// The source under test reaches `@objectstack/lint` through a dynamic import;
84+
// its first load is paid here, during collection, never inside a case's clocked
85+
// window (`check:test-source-alias`).
86+
import '@objectstack/lint';
8387
import { ObjectStackAdapter } from '@object-ui/data-objectstack';
8488
import { ObjectView } from './ObjectView';
8589
import { ExpressionProvider } from '../providers/ExpressionProvider';
90+
import { prefetchObjectViewRows } from '../console/appObjectScope';
8691

8792
const OBJECT_NAME = 'duly_task';
8893
const VIEW_URL = '/api/v1/meta/view';
@@ -103,22 +108,27 @@ const json = (body: unknown) =>
103108

104109
let seq = 0;
105110

106-
function makeAdapter() {
111+
function makeAdapter(opts: { holdViews?: boolean } = {}) {
107112
const calls: string[] = [];
113+
let releaseViews: () => void = () => {};
114+
const viewsHeld = new Promise<void>((resolve) => { releaseViews = resolve; });
108115
const adapter = new ObjectStackAdapter({
109116
baseUrl: `http://refresh-views-${(seq += 1)}.test`,
110117
autoReconnect: false,
111118
fetch: (async (input: RequestInfo | URL) => {
112119
const url = new URL(String(input));
113120
if (url.pathname.endsWith('/discovery')) return json({ success: true, data: {} });
114121
calls.push(url.pathname);
115-
if (url.pathname === VIEW_URL) return json({ success: true, data: { type: 'view', items: structuredClone(SAVED) } });
122+
if (url.pathname === VIEW_URL) {
123+
if (opts.holdViews) await viewsHeld;
124+
return json({ success: true, data: { type: 'view', items: structuredClone(SAVED) } });
125+
}
116126
return json({ success: true, data: {} });
117127
}) as typeof fetch,
118128
});
119129
// The record rows are not under test; the page's list query is answered here.
120130
(adapter as unknown as { find: unknown }).find = vi.fn(async () => ({ data: [{ id: 't1', name: 'Task 1' }], total: 1 }));
121-
return { adapter, viewReads: () => calls.filter((c) => c === VIEW_URL).length };
131+
return { adapter, viewReads: () => calls.filter((c) => c === VIEW_URL).length, releaseViews };
122132
}
123133

124134
/** A window long enough for every effect a step schedules to have fired. */
@@ -190,3 +200,36 @@ describe('a refresh of the object page re-reads its saved views (objectui#13057)
190200
expect(viewReads()).toBe(1);
191201
});
192202
});
203+
204+
/**
205+
* objectstack#35535 — the route starts the list's saved-view read before the
206+
* page mounts (`prefetchObjectViewRows`, `AppContent`). The page asks the same
207+
* adapter for its views on mount and must join that read, not send its own:
208+
* one `/meta/view` request per open, whether the early read is still on the
209+
* wire when the page mounts or has already landed.
210+
*/
211+
describe('the page joins the view read its route started (objectstack#35535)', () => {
212+
it('started and still on the wire: the page sends no second view read', async () => {
213+
const { adapter, viewReads, releaseViews } = makeAdapter({ holdViews: true });
214+
prefetchObjectViewRows(adapter, OBJECT_NAME);
215+
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
216+
expect(viewReads()).toBe(1);
217+
const listViews = vi.spyOn(adapter, 'listViews');
218+
const mounted = mountPage(adapter);
219+
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
220+
releaseViews();
221+
await mounted;
222+
// The page did ask (its own reader ran), and the read it joined is the one.
223+
expect(listViews).toHaveBeenCalled();
224+
expect(viewReads()).toBe(1);
225+
});
226+
227+
it('started and landed: the page reads what it stored', async () => {
228+
const { adapter, viewReads } = makeAdapter();
229+
prefetchObjectViewRows(adapter, OBJECT_NAME);
230+
await act(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
231+
expect(viewReads()).toBe(1);
232+
await mountPage(adapter);
233+
expect(viewReads()).toBe(1);
234+
});
235+
});

0 commit comments

Comments
 (0)