Skip to content

Commit 1a98520

Browse files
committed
fix(app-shell): a bundle reloading after a refresh pulse keeps the route drawn
The refresh pulse a draft save announces drops the adapter's app bundle (clearCache), which then answers pending until its reload lands. The scope's views answered not settled meanwhile, so AppContent swapped the route for its skeleton and ObjectView mounted again on the published view. viewsForObjects now answers from the bundle that last answered in this world while the reload is on the wire, when it holds every asked object; a world switch forgets it. The refresh contract is unchanged. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgW85kwjGaz7HqsmEuv
1 parent 397893e commit 1a98520

2 files changed

Lines changed: 201 additions & 8 deletions

File tree

‎ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx‎

Lines changed: 176 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,15 @@
2929
* view draws it, without the admin's calculations.
3030
* CONTROL: a whole-type invalidation of `view` (the provider dropping its
3131
* items, not refetching in place) still sends the route back to waiting.
32+
*
33+
* The same, on an app with a bundle (the showcase's path): the provider's
34+
* adapter has `peekAppBundle`, and the refresh pulse's `clearCache()` drops
35+
* the bundle, as `AppBundleStore.clear()` does, so the bundle answers
36+
* `pending` while its reload is on the wire (held here). The cases above read
37+
* an adapter without one, which is why they missed it. Pinned: the pick, two
38+
* picks, and Publish keep one mount and no skeleton. CONTROLS: a first entry
39+
* held on the wire (no bundle has answered yet) still waits, and a whole-type
40+
* `object` invalidation still sends the drawn route back to its skeleton.
3241
*/
3342

3443
import '@testing-library/jest-dom/vitest';
@@ -159,6 +168,16 @@ function resetDataSource() {
159168
listViews: vi.fn(async () => [structuredClone(PUBLISHED_VIEW)]),
160169
updateView: vi.fn(async () => ({})),
161170
invalidateViewKeys: vi.fn(),
171+
// `AppContent` enters the app's bundle through the list's data source, as the console does.
172+
...(appBundle.on
173+
? {
174+
loadAppBundle: () => {
175+
appBundle.entered = true;
176+
if (!appBundle.items) askBundle();
177+
return appBundle.settled ?? Promise.resolve();
178+
},
179+
}
180+
: {}),
162181
});
163182
}
164183

@@ -179,6 +198,7 @@ import '@objectstack/lint';
179198
import '../../views/ObjectView.js';
180199
import { AppContent } from '../AppContent';
181200
import { MetadataProvider, useMetadata } from '../../providers/MetadataProvider';
201+
import { publishRuntimeMetadata } from '../../views/runtime-metadata-persistence.js';
182202

183203
interface Server {
184204
/** Hold every `/meta/view` list read until `releaseViews`, as a request on the wire. */
@@ -187,11 +207,70 @@ interface Server {
187207
}
188208
const server: Server = { holdViews: false, releaseViews: () => {} };
189209

210+
type BundleItems = Map<string, Map<string, { item: unknown; envelope: Record<string, unknown> }>>;
211+
/**
212+
* The adapter's app bundle, as `AppBundleStore` holds it: `items` is the
213+
* answer in hand (`null` before the first one and after `clearCache()`), and
214+
* a load while `hold` is set stays on the wire until `releaseBundle`.
215+
*/
216+
const appBundle = {
217+
/** Whether this boot's adapter has a bundle at all. */
218+
on: false,
219+
entered: false,
220+
hold: false,
221+
items: null as BundleItems | null,
222+
settled: null as Promise<unknown> | null,
223+
waiting: [] as Array<() => void>,
224+
loads: 0,
225+
};
226+
const APPS = [{ name: 'crm', label: 'CRM', _packageId: CRM, navigation: [{ id: 'n1', type: 'object', label: 'Accounts', objectName: OBJECT }] }];
227+
function bundleItems(): BundleItems {
228+
const entry = (item: unknown) => ({ item: structuredClone(item), envelope: {} });
229+
return new Map([
230+
['app', new Map([['crm', entry(APPS[0])]])],
231+
['object', new Map(OBJECTS.map((o) => [o.name, entry(o)]))],
232+
['view', new Map([[VIEW, entry(PUBLISHED_VIEW)]])],
233+
]);
234+
}
235+
function askBundle() {
236+
if (appBundle.settled) return;
237+
appBundle.loads++;
238+
let land: () => void = () => {};
239+
appBundle.settled = new Promise<void>((resolve) => { land = resolve; });
240+
const go = () => {
241+
appBundle.items = bundleItems();
242+
appBundle.settled = null;
243+
land();
244+
};
245+
if (appBundle.hold) appBundle.waiting.push(go);
246+
else queueMicrotask(go);
247+
}
248+
const releaseBundle = () => appBundle.waiting.splice(0).forEach((go) => go());
249+
function resetBundle(on: boolean) {
250+
Object.assign(appBundle, { on, entered: false, hold: false, items: null, settled: null, waiting: [], loads: 0 });
251+
}
252+
190253
function makeAdapter() {
191254
const heldViews: Array<() => void> = [];
192255
server.releaseViews = () => heldViews.splice(0).forEach((go) => go());
256+
const bundleHost = appBundle.on
257+
? {
258+
peekAppBundle: () => {
259+
if (!appBundle.entered) return { status: 'none' };
260+
if (!appBundle.items) {
261+
askBundle();
262+
return { status: 'pending', settled: appBundle.settled! };
263+
}
264+
return { status: 'ready', items: appBundle.items };
265+
},
266+
}
267+
: {};
193268
return {
194-
clearCache: vi.fn(),
269+
...bundleHost,
270+
// `AppBundleStore.clear()`: the bundle's answer is dropped, the app stays entered.
271+
clearCache: vi.fn(() => {
272+
appBundle.items = null;
273+
}),
195274
invalidateCache: vi.fn(),
196275
getObjectSchema(this: { getClient(): any }, name: string) {
197276
return this.getClient()
@@ -205,8 +284,7 @@ function makeAdapter() {
205284
const named = type === 'object' ? OBJECTS.filter((o) => options.names!.includes(o.name)) : [];
206285
return Promise.resolve({ type, items: structuredClone(named) });
207286
}
208-
const apps = [{ name: 'crm', label: 'CRM', _packageId: CRM, navigation: [{ id: 'n1', type: 'object', label: 'Accounts', objectName: OBJECT }] }];
209-
const all: any[] = type === 'object' ? OBJECTS : type === 'app' ? apps : type === 'view' ? [PUBLISHED_VIEW] : [];
287+
const all: any[] = type === 'object' ? OBJECTS : type === 'app' ? APPS : type === 'view' ? [PUBLISHED_VIEW] : [];
210288
const items = options?.packageId ? all.filter((o: any) => o._packageId === options.packageId) : all;
211289
const answer = { type, items: structuredClone(items) };
212290
if (type === 'view' && server.holdViews) return new Promise((resolve) => heldViews.push(() => resolve(answer)));
@@ -249,7 +327,12 @@ function MetadataProbe() {
249327
return null;
250328
}
251329

252-
function boot(admin: boolean) {
330+
function boot(admin: boolean, options: { bundle?: boolean; holdFirstLoad?: boolean } = {}) {
331+
if (options.bundle) {
332+
resetBundle(true);
333+
resetDataSource();
334+
appBundle.hold = options.holdFirstLoad === true;
335+
}
253336
render(
254337
<AuthProvider authUrl="/api/auth" client={authClient(admin)}>
255338
<MetadataProvider adapter={makeAdapter()}>
@@ -292,6 +375,7 @@ beforeEach(() => {
292375
forgetList();
293376
list.mounts = 0;
294377
metadata.current = null;
378+
resetBundle(false);
295379
resetDataSource();
296380
localStorage.clear();
297381
sessionStorage.clear();
@@ -300,6 +384,8 @@ beforeEach(() => {
300384

301385
afterEach(() => {
302386
server.releaseViews();
387+
appBundle.hold = false;
388+
releaseBundle();
303389
cleanup();
304390
ActiveOrganizationStorage.clear();
305391
});
@@ -384,3 +470,89 @@ describe('objectstack#35932 — a shared view\'s draft save keeps the list on sc
384470
await waitFor(() => expect(skeletonUp()).toBe(false));
385471
});
386472
});
473+
474+
describe('objectstack#35932 — the same, on an app with a bundle', () => {
475+
/** Let the pulse run: the save's refresh, the bundle reload put on the wire. */
476+
const settle = () =>
477+
act(async () => {
478+
await new Promise((resolve) => setTimeout(resolve, 50));
479+
});
480+
481+
it('an admin\'s footer pick: the bundle reloading keeps the list, one mount, the pick drawn', async () => {
482+
boot(true, { bundle: true });
483+
await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 });
484+
expect(list.mounts).toBe(1);
485+
const loadsBefore = appBundle.loads;
486+
487+
appBundle.hold = true;
488+
await pick('amount', 'sum');
489+
await settle();
490+
// The pulse dropped the bundle and its reload is on the wire.
491+
expect(appBundle.items).toBeNull();
492+
expect(appBundle.loads).toBe(loadsBefore + 1);
493+
expect(skeletonUp()).toBe(false);
494+
expect(list.mounts).toBe(1);
495+
expect(summaryOf('amount')).toBe('sum');
496+
497+
appBundle.hold = false;
498+
act(() => releaseBundle());
499+
await settle();
500+
expect(skeletonUp()).toBe(false);
501+
expect(list.mounts).toBe(1);
502+
expect(summaryOf('amount')).toBe('sum');
503+
});
504+
505+
it('two successive picks, then Publish: both picks in the second draft, one mount throughout', async () => {
506+
boot(true, { bundle: true });
507+
await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 });
508+
509+
appBundle.hold = true;
510+
await pick('amount', 'sum');
511+
await settle();
512+
await pick('closed_at', 'latest');
513+
await settle();
514+
expect(skeletonUp()).toBe(false);
515+
expect(storedSummaries(saves[0].body)).toEqual({ amount: 'sum' });
516+
expect(storedSummaries(saves[1].body)).toEqual({ amount: 'sum', closed_at: 'latest' });
517+
518+
appBundle.hold = false;
519+
act(() => releaseBundle());
520+
await settle();
521+
522+
// Publish, through the seam the draft bar calls: its pulse drops the bundle again.
523+
appBundle.hold = true;
524+
await act(async () => {
525+
await publishRuntimeMetadata('view', VIEW, { metadataClient: client as any, dataSource: dataSourceStub as any, objectName: OBJECT });
526+
});
527+
await settle();
528+
expect(appBundle.items).toBeNull();
529+
expect(skeletonUp()).toBe(false);
530+
expect(list.mounts).toBe(1);
531+
532+
appBundle.hold = false;
533+
act(() => releaseBundle());
534+
await settle();
535+
expect(skeletonUp()).toBe(false);
536+
expect(list.mounts).toBe(1);
537+
});
538+
539+
it('CONTROL: a first entry on the wire (no bundle has answered) still waits, the list not drawn', async () => {
540+
boot(true, { bundle: true, holdFirstLoad: true });
541+
await waitFor(() => expect(appBundle.waiting.length).toBeGreaterThan(0), { timeout: 5000 });
542+
await settle();
543+
expect(list.mounts).toBe(0);
544+
appBundle.hold = false;
545+
act(() => releaseBundle());
546+
await waitFor(() => expect(list.mounts).toBe(1), { timeout: 5000 });
547+
});
548+
549+
it('CONTROL: a whole-type invalidation of `object` on the bundle route still shows the skeleton', async () => {
550+
boot(true, { bundle: true });
551+
await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 });
552+
act(() => {
553+
metadata.current!.invalidate('object');
554+
});
555+
await waitFor(() => expect(skeletonUp()).toBe(true));
556+
await waitFor(() => expect(skeletonUp()).toBe(false));
557+
});
558+
});

‎ui/packages/app-shell/src/providers/MetadataProvider.tsx‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,8 +1096,17 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }:
10961096
*/
10971097
const dropAdapterWorld = useCallback((): void => {
10981098
adapterObjectNamesRef.current.clear();
1099+
answeredBundleRef.current = null;
10991100
try { adapterRef.current?.clearCache?.(); } catch { /* adapter mid-swap */ }
11001101
}, []);
1102+
/**
1103+
* objectstack#35932 — the items of the last app bundle that answered in this
1104+
* world. A refresh pulse drops the adapter's bundle, which then answers
1105+
* `pending` until its reload lands; the scope's views keep answering from
1106+
* these meanwhile (`viewsForObjects`), as a `/meta/view` list refetching in
1107+
* place does. A world switch forgets them (`dropAdapterWorld`).
1108+
*/
1109+
const answeredBundleRef = useRef<AppBundleItems | null>(null);
11011110

11021111
const [version, setVersion] = useState(0);
11031112
// Defer state bumps so they never occur synchronously during a consumer's
@@ -1145,6 +1154,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }:
11451154
watchedBundleLoadsRef.current.add(peek.settled);
11461155
void peek.settled.then(bump, bump);
11471156
}
1157+
if (peek.status === 'ready') answeredBundleRef.current = peek.items;
11481158
return peek;
11491159
}, [bump]);
11501160
useEffect(() => {
@@ -1914,16 +1924,27 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }:
19141924
* list already in hand, and asks for none: a reader of its views names it.
19151925
* - The bundle still loading, or the app about to be entered in this
19161926
* commit: a list already in hand answers, so a scope never unsettles
1917-
* because an app was entered after it; otherwise the scope waits.
1927+
* because an app was entered after it; so does the bundle that last
1928+
* answered, when it holds every asked name (a reload after a refresh
1929+
* pulse, objectstack#35932); otherwise the scope waits.
19181930
* - No bundle (no app entered, or a host without one): the list, as before.
19191931
*/
19201932
const viewsForObjects = useCallback(
19211933
(asked: readonly string[]): { views: unknown[]; settled: boolean } => {
19221934
const listed = getEntry('view');
19231935
const peek = peekBundle();
1924-
if (peek?.status === 'ready') {
1925-
const bundledObjects = peek.items.get('object');
1926-
const fromBundle = (bundledViews(peek.items) as { value: unknown[] }).value;
1936+
// objectstack#35932 — a bundle reloading after a refresh pulse still
1937+
// answers with the items it last answered (`answeredBundleRef`), so the
1938+
// pulse never sends a drawn route back to its skeleton (which remounts it).
1939+
// Only when those items hold every asked object: one outside them waits
1940+
// for the reload, as before, rather than asking the `/meta/view` list.
1941+
const answered = peek?.status === 'pending' ? answeredBundleRef.current : null;
1942+
const items = peek?.status === 'ready'
1943+
? peek.items
1944+
: answered && asked.every((name) => answered.get('object')?.has(name)) ? answered : null;
1945+
if (items) {
1946+
const bundledObjects = items.get('object');
1947+
const fromBundle = (bundledViews(items) as { value: unknown[] }).value;
19271948
const outside = asked.some((name) => !bundledObjects?.has(name));
19281949
if (!outside) {
19291950
const views = listed.status === 'ready' || (listed.status === 'loading' && listed.answered)

0 commit comments

Comments
 (0)