Skip to content

Commit 121017b

Browse files
fix(app-shell): Home sends its deployment-notice, authorized-clients and API-key reads once per load (#34097)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9W6PBGd35eGZ3aW4WwdNVYk)_ Fixes #28085 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:首页冷加载时,部署提示、已授权 AI 助手、API 密钥这三个读取各只发一次(之前在打包后的控制台上分别是 2 次、3 次、3 次);列表页本来就每个 URL 只读一次,不变,现在由一个新的请求计数测试钉住(带消融)。 - 为什么改:首页先画一帧完整页面、再切成"加载中"、再画一遍,里面的组件被挂载两次;另外"连接 AI 助手"卡片和管理员首次使用清单各自读同一份数据。每次打开首页白白多 5 次请求。 - 风险与回滚:产品代码只动 `@object-ui/app-shell` 两个文件(另加一个控制台测试文件);首页现在在 `/me/apps` 回答之前显示"加载中"(这本来就是该标志声明的行为)。回滚即 revert 本 PR。 - 先看:`ui/packages/app-shell/src/hooks/useLauncherApps.tsx`(`firstReadDue`)、`ui/packages/app-shell/src/console/connect/connectedAccess.ts`(共享读取的生命周期)。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/hooks/__tests__/useLauncherApps-26838.test.tsx packages/app-shell/src/console/connect/ConnectAgentWidget.connected-30898.test.tsx`,预期 29 个用例全绿;列表页钉子:`pnpm --dir ui exec vitest run apps/console/src/__tests__/App.listPageBootReadsOnce-28085.test.tsx`,预期 1 个用例绿。 - 需要你做的:无,席位落地。 ## What changes Step 0 measured the card on a **production** console build (`pnpm console:build`, served by `objectstack dev --ui --fresh` from `examples/app-showcase`, seeded admin, headless Chromium 1440×900, a fresh page per load after sign-in, GETs under `/api/` counted from navigation to network idle plus 3 s), on `main` `bc6b7ffd`: - **List page** (`showcase_task` ×4, `showcase_account` ×1): every URL is read once. `auth/get-session`, `meta/app`, `auth/me/permissions` and `me/apps` read 1 each, and `meta/object?package`, `sys_user_preference` and `me/localization` read 1 each too. The doubling the card names is still React.StrictMode's development replay, which this PR does not touch. - **Home** (×1, then ×2 with response times): `GET /api/settings/deployment/notice` ×2, `GET /api/v1/auth/authorized-clients` ×3, and the `sys_api_key` list ×3. **None of them overlapped**: each repeat started after the previous one had answered. So sharing an in-flight request (the card's "Wanted") could not remove them. The causes, traced on the Console dev server with StrictMode turned off locally (a local edit, restored) and a React DevTools hook recording mounts: 1. **Home mounted its children twice.** `HomePage` waits on `useLauncherApps().pending` so it never draws a tile `/me/apps` then hides. `LauncherAppsProvider` set `pending` only from its effect, after the first commit, so the first frame had nothing pending and nothing narrowed. Home drew its page (mounting `DeploymentNotice` and `ConnectAssistantCard`, which read on mount), switched to its loading state when the effect published `pending`, then drew the page again when the answer came. Now the provider answers `pending` from the render that makes the first read due. Home draws the page once, after the answer. This also removes the first frame that drew a hidden app's tile, which the hook's own doc says never happens. 2. **Two readers of one answer.** Home draws the Connect an AI Assistant card and, for an administrator, the first-run checklist. Both call `useConnectedAccess`, and each owned its own effects, so each sent `authorized-clients` and the `sys_api_key` list. The checklist's reader enables later (after the settings read), so its requests came after the card's had answered. `useConnectedAccess` now reads through a store shared by every reader mounted at the same time, keyed by adapter and person. A reader that mounts while the entry lives joins its answer or its reads in flight. A change to `sys_api_key` or `sys_oauth_consent` re-reads that record once for all readers. The entry is dropped with its last reader, so a page mounted later reads afresh, as it did before. The store's subscribe/getSnapshot pair is keyed on the adapter and person outside React, not on a memoised callback (ui `AGENTS.md` #10). Both are one-place fixes at the source of each repeat. Neither is a per-call-site guard. <details><summary>Readings: production console, before and after</summary> Before (`main` `bc6b7ffd`), Home, one load: 35 GETs; repeated URLs `deployment/notice` ×2, `authorized-clients` ×3, `sys_api_key` list ×3. Timeline of the repeats (ms from navigation, start → end): ``` deployment/notice 977 → 1075 1116 → 1305 authorized-clients 979 → 1098 1117 → 1335 1375 → 1430 sys_api_key list 979 → 1109 1119 → 1342 1376 → 1433 ``` After (head of this PR, console rebuilt), Home ×3: 30 GETs each, no URL repeated; `deployment/notice` 1, `authorized-clients` 1, `sys_api_key` list 1, `me/apps` 1, `meta/app` 1, `me/permissions` 1, `get-session` 1. List page, before ×5 and after ×3 (`showcase_task`, `showcase_account`): 26 GETs each, no URL repeated; the card's four reads 1 each (`meta/app` and `meta/app/showcase_app/bundle` are two different URLs). Dev server, StrictMode off, mounts recorded through a React DevTools hook (before the fix): `DeploymentNotice` and `ConnectAssistantCard` mounted twice under the same `HomePage` element, each mount followed by its reads; after fix 1, once; after fix 2, `authorized-clients` and the `sys_api_key` list are sent once, with the checklist mounted. </details> ## Tests - `useLauncherApps-26838.test.tsx`, new top-level describe `the first /me/apps read is pending from the first render`: a page behind Home's gate mounts once, so a child that reads on mount reads once per load (a request count); `pending` is true in the very first render when a read is due; and false when none is due (no user, metadata loading, no apps). - `ConnectAgentWidget.connected-30898.test.tsx`, new `§7 one pair of reads per page, however many readers`: two readers mounted together send each request once; a reader mounting after the answer joins it; a `sys_api_key` change re-reads that record once for both; a page mounted after every reader left reads afresh. - `ui/apps/console/src/__tests__/App.listPageBootReadsOnce-28085.test.tsx` (new, the card's acceptance pin): a list page (`/apps/crm/crm_contact`) loads through the real route tree with the boot `main.tsx` runs, the real `preflightAuth`, then `App` with the real `AuthProvider`, `AuthGuard`, `ConnectedShell` (real `ObjectStackAdapter` and `MetadataProvider`), `RequireOrganization`, the `/me/permissions` scope and `LauncherAppsProvider`, over one stubbed global `fetch` that records every URL. `auth/get-session`, `meta/app`, `auth/me/permissions` and `me/apps` are counted at exactly one request each. Only the app's own content and the pages off the route are stubbed, as in the sibling `App.rootLandingReadsOnce-32633`. No `React.StrictMode`, since a built console does not replay effects. - No existing test was edited. <details><summary>Ablations (mutation through scripts/ablation-replace.mjs, restored to HEAD, git diff HEAD empty)</summary> - `useLauncherApps.tsx`: `const state = firstReadDue ? PENDING : heldState;` → `const state = heldState;` — 2 failed / 9 passed: `a page behind the gate mounts once…` ("expected vi.fn() to be called 1 times, but got 2 times") and `is pending in the very first render…` ("expected [ false ] to deeply equal [ true ]"). - `connectedAccess.ts`: `let entry = byUser.get(userId);` → `let entry: SharedReads | undefined = undefined;` (one entry per reader) — 3 failed / 15 passed: two readers together, the late reader, and the re-read on change. - List-page pin, `ui/packages/auth/src/createAuthClient.ts` (`takePreflightSession`, the handoff that keeps the boot at one `get-session`): ` if (!slot || slot.taken) return null;` → ` if (!slot || slot.taken || true) return null;` — 1 failed / 0 passed: `expected { 'auth/get-session': 2, …(3) } to deeply equal { 'auth/get-session': 1, …(3) }`. Restored: blob == HEAD (`ab510ed0c019`), `git diff HEAD` empty. </details> ## Acceptance notes - The card's acceptance, "a list page load makes one request per URL for the four reads", held on a built console without a product change, as the 2026-10-31 reading (6538476483) found. The four doubled only behind the Vite dev server with StrictMode, and the order for this card says not to "fix" that. It is now pinned by `App.listPageBootReadsOnce-28085.test.tsx` with the ablation above (the card's claim amendment widened the surface to that one file). - The QA reading on the card (6765285185) also named `sys_audit_log` and `sys_user` ×2 on a record page. Not measured here (record page outside this card's step 0). - `me/localization`, which that reading saw ×2 on the list page, read once on the built console; its files are held for #33985 and are untouched. ## Verification All on head `1feba497` (merge base `bc6b7ffd`), after the last commit. The product files are unchanged since `76497be1`; that round's app-shell checks (`pnpm --filter @object-ui/app-shell type-check` exit 0; `cd ui && pnpm exec vitest run packages/app-shell/ --maxWorkers=2` under the verify lock, Test Files 2270 passed / 1 skipped, Tests 21007 passed / 9 skipped, exit 0) stand for them. - `cd ui && pnpm exec vitest run apps/console/src/__tests__/App.listPageBootReadsOnce-28085.test.tsx apps/console/src/__tests__/App.rootLandingReadsOnce-32633.test.tsx`, twice: 2 files, 3 tests passed each time (the new pin also passed alone once before the ablation). - `pnpm --filter @object-ui/console type-check` (covers the new test file) — exit 0. - Consumers of the two hooks (round 1, unchanged files): `FirstRunChecklist.test.tsx` and the console `App.permissionsWave-29114`, `App.homePermissions-12700`, `App.rootLandingReadsOnce-32633`, `App.linkRefusalLanding-33063` suites — green. - `node scripts/pm/dispatch-gates.mjs --ran` on `1feba497` — 37 derived (the same 37 as round 1), 37 run, 0 NOT-MEASURED, 0 UNRUN; the whole round under the verify lock, every family exit 0 on the first run. - `pnpm check:new-line-citations` (ui) — 0 new citations. - Dogfood battery: not run — no `!` in the title and no `(narrowing)` arm. - The CI families (Lint & Repo Gates, Type Check UI, Test UI, Build & E2E UI, the rest of the required set) are this PR's check-runs. <details><summary>Derived gate ledger on 1feba49 (CMD :: exit)</summary> ``` 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: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 :: exit 0 ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPiLw38ErmCpnkcQvh)_ <!-- signed: domain:ui#2 · os-steve · session_01ADHkmSzhXR4yUAgwq1bQRi --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 27298b8 commit 121017b

6 files changed

Lines changed: 500 additions & 51 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/console': patch
4+
---
5+
6+
fix(app-shell): Home sends the deployment notice, authorized-clients and API-key reads once per load
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
On a built Console, a cold load of Home sent `GET /api/settings/deployment/notice` twice and `GET /api/v1/auth/authorized-clients` and the `sys_api_key` list three times each. The repeats were not concurrent, so sharing an in-flight request could not remove them. Each had its own cause:
12+
13+
- **Home was mounted twice.** Home waits on the launcher's `pending` flag so that it never draws an app tile that `/me/apps` then hides. The `LauncherAppsProvider` set that flag from its effect, which runs after the first commit. So the first frame had nothing pending and nothing narrowed: Home drew its page, then switched to its loading state, then drew the page again. Everything inside it mounted twice, and the deployment notice and the Connect an AI Assistant card sent their reads twice. The first read is now `pending` from the render that makes it due. Home draws its page once, after the answer, and a hidden app's tile is never drawn in that first frame.
14+
- **Two readers of one answer.** Home draws the Connect an AI Assistant card and the administrator's first-run checklist together. Both read "has this person connected an assistant" through `useConnectedAccess`, and each sent its own two requests. Every reader mounted at the same time now shares one pair of reads. A change to either record re-reads it once for all of them. The shared answer is dropped with its last reader, so a page mounted later reads afresh.
15+
16+
A list page load already read every URL once on a built Console, so nothing changes there.
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#28085 — a console list page load asks `auth/get-session`,
5+
* `meta/app`, `auth/me/permissions` and `me/apps` once each.
6+
*
7+
* ## What is real here
8+
*
9+
* The boot order `main.tsx` runs: the pre-React `preflightAuth` validating the
10+
* stored Bearer, then `App` — the real `AuthProvider` with its own better-auth
11+
* client, `AuthGuard`, `ProtectedRoute`, `ConsoleShell`, `ConnectedShell` with
12+
* the real `ObjectStackAdapter` and `MetadataProvider`, `RequireOrganization`,
13+
* `ConsolePermissionsScope` (the `/me/permissions` provider) and the console's
14+
* `LauncherAppsProvider` (`/me/apps`). The network is one stubbed global
15+
* `fetch` that records every URL and answers it, so a count is of requests that
16+
* would reach the wire. No `React.StrictMode`: a built console does not replay
17+
* effects, and the doubling this card was filed on was that replay behind the
18+
* Vite dev server.
19+
*
20+
* The app's own content is a stub: the four reads under test are the shell's,
21+
* which every list page shares, not the list view's.
22+
*/
23+
24+
import '@testing-library/jest-dom/vitest';
25+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
26+
import { render, screen, cleanup, waitFor, act } from '@testing-library/react';
27+
import type { ReactNode } from 'react';
28+
// Paid at collection, not inside the mock factory's clocked first call.
29+
import '@object-ui/react';
30+
import '@object-ui/app-shell';
31+
32+
const ORG = { id: 'org_1', name: 'Acme', slug: 'acme' };
33+
const USER = { id: 'u1', name: 'Ada', email: 'ada@example.test' };
34+
const TOKEN = 'tok_valid';
35+
const SESSION_BODY = {
36+
user: USER,
37+
session: { id: 's_1', userId: USER.id, token: TOKEN, activeOrganizationId: ORG.id, expiresAt: '2099-01-01T00:00:00.000Z' },
38+
};
39+
40+
/** The one app the deployment serves; the list page under test is one of its objects. */
41+
const APPS = [{ name: 'crm', label: 'CRM', active: true, isDefault: true }];
42+
const LIST_PAGE = '/apps/crm/crm_contact';
43+
44+
function json(body: unknown, status = 200): Response {
45+
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
46+
}
47+
48+
const urlOf = (input: RequestInfo | URL): string =>
49+
typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
50+
51+
const calls: string[] = [];
52+
const fetchStub = vi.fn(async (input: RequestInfo | URL) => {
53+
const url = urlOf(input);
54+
calls.push(url);
55+
if (url.includes('/auth/get-session')) return json(SESSION_BODY);
56+
if (url.includes('/auth/organization/list')) return json([ORG]);
57+
if (url.includes('/auth/organization/get-active-member')) {
58+
return json({ id: 'm_1', organizationId: ORG.id, userId: USER.id, role: 'member' });
59+
}
60+
if (url.includes('/auth/me/permissions')) {
61+
return json({
62+
authenticated: true, userId: USER.id, tenantId: ORG.id, positions: [], permissionSets: [], objects: {}, fields: {}, hasAnyQueue: false,
63+
});
64+
}
65+
if (url.includes('/auth/')) return json({});
66+
if (url.includes('/api/v1/discovery')) {
67+
return json({
68+
success: true,
69+
data: { version: '1.0.0', apiName: 'v1', routes: { data: '/api/v1/data', metadata: '/api/v1/meta' }, services: {} },
70+
});
71+
}
72+
if (url.includes('/me/apps')) return json({ apps: APPS });
73+
if (/\/api\/v1\/meta\/app(\?|$)/.test(url)) return json({ success: true, data: { type: 'app', items: APPS } });
74+
if (url.includes('/api/v1/meta/')) return json({ success: true, data: { items: [] } });
75+
if (url.includes('/api/v1/data/')) return json({ success: true, data: { records: [], total: 0 } });
76+
return json({ success: true, data: {} });
77+
});
78+
79+
vi.mock('@object-ui/app-shell', async (importOriginal) => ({
80+
...(await importOriginal<Record<string, unknown>>()),
81+
ConsoleToaster: () => null,
82+
DefaultHomeLayout: ({ children }: { children?: ReactNode }) => <>{children}</>,
83+
DefaultHomePage: () => <div data-testid="home-page" />,
84+
DefaultAppContent: () => <div data-testid="app-content" />,
85+
}));
86+
87+
vi.mock('../LocalizationFetchProvider', () => ({
88+
LocalizationFetchProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
89+
}));
90+
vi.mock('../pages/settings/FirstRunChecklist', () => ({ FirstRunChecklist: () => null }));
91+
vi.mock('../components/SetupRoute', () => ({ SetupRoute: () => null }));
92+
vi.mock('../components/FormPage', () => ({ FormPage: () => null }));
93+
vi.mock('../components/InternalFormRoute', () => ({ InternalFormRoute: () => null, InAppFormRoute: () => null }));
94+
vi.mock('../components/MetadataHmrReloader', () => ({ MetadataHmrReloader: () => null }));
95+
vi.mock('../components/FaviconSync', () => ({ FaviconSync: () => null }));
96+
vi.mock('../pages/SharedRecordPage', () => ({ default: () => null }));
97+
vi.mock('../pages/auth/LoginPage', () => ({ LoginPage: () => <div data-testid="login-page" /> }));
98+
vi.mock('../pages/auth/RegisterPage', () => ({ RegisterPage: () => null }));
99+
vi.mock('../pages/auth/ForgotPasswordPage', () => ({ ForgotPasswordPage: () => null }));
100+
vi.mock('../pages/auth/ResetPasswordPage', () => ({ ResetPasswordPage: () => null }));
101+
vi.mock('../pages/auth/SetPasswordPage', () => ({ SetPasswordPage: () => null }));
102+
vi.mock('../pages/auth/VerifyEmailPage', () => ({ VerifyEmailPage: () => null }));
103+
vi.mock('../pages/auth/VerifyEmailPromptPage', () => ({ VerifyEmailPromptPage: () => null }));
104+
vi.mock('../pages/auth/OAuthConsentPage', () => ({ OAuthConsentPage: () => null }));
105+
vi.mock('../pages/auth/DeviceAuthPage', () => ({ DeviceAuthPage: () => null }));
106+
vi.mock('../dev/DevMasterDetail', () => ({ DevMasterDetail: () => null }));
107+
vi.mock('../dev/DevLists', () => ({ DevLists: () => null }));
108+
vi.mock('../dev/DevModal', () => ({ DevModal: () => null }));
109+
vi.mock('../dev/DevLookup', () => ({ DevLookup: () => null }));
110+
vi.mock('../dev/DevRowActions', () => ({ DevRowActions: () => null }));
111+
112+
import { App } from '../App';
113+
import { preflightAuth } from '../lib/auth-preflight';
114+
115+
const pathOf = (url: string) => {
116+
try {
117+
return new URL(url, 'http://console.test').pathname;
118+
} catch {
119+
return url;
120+
}
121+
};
122+
const readsOf = (test: (path: string) => boolean) => calls.filter((u) => test(pathOf(u)));
123+
const FOUR = {
124+
'auth/get-session': (p: string) => p.endsWith('/api/v1/auth/get-session'),
125+
'meta/app': (p: string) => p.endsWith('/api/v1/meta/app'),
126+
'auth/me/permissions': (p: string) => p.endsWith('/api/v1/auth/me/permissions'),
127+
'me/apps': (p: string) => p.endsWith('/api/v1/me/apps'),
128+
} as const;
129+
const countFour = () =>
130+
Object.fromEntries(Object.entries(FOUR).map(([name, test]) => [name, readsOf(test).length]));
131+
132+
/** Let the effects and the answers they await run out (a count of one needs it). */
133+
async function settle() {
134+
for (let i = 0; i < 10; i++) {
135+
await act(async () => {
136+
await new Promise((r) => setTimeout(r, 10));
137+
});
138+
}
139+
}
140+
141+
/** The boot `main.tsx` runs, landing on a list page. */
142+
async function openListPage() {
143+
localStorage.setItem('auth-session-token', TOKEN);
144+
window.history.pushState({}, '', LIST_PAGE);
145+
await preflightAuth('/api/v1/auth');
146+
render(<App />);
147+
await waitFor(() => expect(screen.getByTestId('app-content')).toBeInTheDocument(), { timeout: 5000 });
148+
// Each read is sent from an effect, which a busy run can flush after the DOM
149+
// shows the page: wait until all four have gone out, then let the load run out.
150+
await waitFor(() => {
151+
for (const test of Object.values(FOUR)) expect(readsOf(test).length).toBeGreaterThan(0);
152+
});
153+
await settle();
154+
}
155+
156+
beforeEach(() => {
157+
calls.length = 0;
158+
fetchStub.mockClear();
159+
vi.stubGlobal('fetch', fetchStub);
160+
localStorage.clear();
161+
sessionStorage.clear();
162+
delete (globalThis as unknown as Record<symbol, unknown>)[Symbol.for('objectui.authPreflightSession')];
163+
});
164+
afterEach(() => {
165+
cleanup();
166+
vi.unstubAllGlobals();
167+
window.history.pushState({}, '', '/');
168+
});
169+
170+
describe('a console list page load asks each of its four boot reads once (objectstack#28085)', () => {
171+
it('get-session, meta/app, me/permissions and me/apps go out once each', async () => {
172+
await openListPage();
173+
expect(window.location.pathname).toBe(LIST_PAGE);
174+
expect(countFour()).toEqual({
175+
'auth/get-session': 1,
176+
'meta/app': 1,
177+
'auth/me/permissions': 1,
178+
'me/apps': 1,
179+
});
180+
});
181+
});

‎ui/packages/app-shell/src/console/connect/ConnectAgentWidget.connected-30898.test.tsx‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
import '@testing-library/jest-dom/vitest';
2828
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
29-
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
29+
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
3030

3131
vi.mock('@object-ui/i18n', async (importOriginal) => ({
3232
...(await importOriginal<Record<string, unknown>>()),
@@ -60,7 +60,7 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({
6060

6161
import { notifyDataChanged } from '@object-ui/react';
6262
import { ConnectAgent } from './ConnectAgentWidget';
63-
import { combineConnectedReads, type ConnectedEntry } from './connectedAccess';
63+
import { combineConnectedReads, useConnectedAccess, type ConnectedEntry } from './connectedAccess';
6464

6565
type Row = Record<string, unknown>;
6666
type Client = {
@@ -303,3 +303,58 @@ describe('§6 combineConnectedReads', () => {
303303
expect(result.state === 'ready' && result.entries.map((e) => e.id)).toEqual(['d', 'b', 'a', 'c']);
304304
});
305305
});
306+
307+
/**
308+
* objectstack#28085 — Home mounts more than one reader of this answer (the
309+
* Connect an AI Assistant card and the administrator's checklist), and they
310+
* mount at different moments of one load. Every reader mounted at the same
311+
* time shares one pair of reads; a page mounted after the last reader left
312+
* reads afresh.
313+
*/
314+
describe('§7 one pair of reads per page, however many readers', () => {
315+
function Reader({ id }: { id: string }) {
316+
const access = useConnectedAccess();
317+
return <div data-testid={id}>{access.state === 'ready' ? String(access.connected) : access.state}</div>;
318+
}
319+
320+
it('two readers mounted together send each request once', async () => {
321+
granted = [DESKTOP];
322+
render(<><Reader id="a" /><Reader id="b" /></>);
323+
await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('true'));
324+
expect(screen.getByTestId('b')).toHaveTextContent('true');
325+
expect(listMock).toHaveBeenCalledTimes(1);
326+
expect(findMock).toHaveBeenCalledTimes(1);
327+
});
328+
329+
it('a reader mounting after the answer landed joins it instead of asking again', async () => {
330+
granted = [DESKTOP];
331+
const { rerender } = render(<Reader id="a" />);
332+
await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('true'));
333+
rerender(<><Reader id="a" /><Reader id="late" /></>);
334+
expect(screen.getByTestId('late')).toHaveTextContent('true');
335+
expect(listMock).toHaveBeenCalledTimes(1);
336+
expect(findMock).toHaveBeenCalledTimes(1);
337+
});
338+
339+
it('a change to either record re-reads it once for every reader', async () => {
340+
render(<><Reader id="a" /><Reader id="b" /></>);
341+
await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('false'));
342+
keyRows = [{ ...LIVE_KEY }];
343+
act(() => notifyDataChanged({ objectName: 'sys_api_key' }));
344+
await waitFor(() => expect(screen.getByTestId('b')).toHaveTextContent('true'));
345+
expect(screen.getByTestId('a')).toHaveTextContent('true');
346+
expect(findMock).toHaveBeenCalledTimes(2);
347+
expect(listMock).toHaveBeenCalledTimes(1);
348+
});
349+
350+
it('a page mounted after every reader left reads afresh', async () => {
351+
const first = render(<Reader id="a" />);
352+
await waitFor(() => expect(screen.getByTestId('a')).toHaveTextContent('false'));
353+
first.unmount();
354+
granted = [DESKTOP];
355+
render(<Reader id="again" />);
356+
await waitFor(() => expect(screen.getByTestId('again')).toHaveTextContent('true'));
357+
expect(listMock).toHaveBeenCalledTimes(2);
358+
expect(findMock).toHaveBeenCalledTimes(2);
359+
});
360+
});

0 commit comments

Comments
 (0)