Skip to content

Commit 9ba2d4c

Browse files
fix(console): a user with no personal language gets the app's declared default language, not the browser's (#33309)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XFqWUeTvdjtsCuVJwjkdjAS)_ Fixes #33231 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:没设个人语言(`sys_user.locale` 为空)的用户,控制台语言现在按「个人语言 → 应用声明的默认语言(discovery `locale.default`)→ 浏览器语言 → `en`」决定,页面的 `lang` 属性跟着走。做法是控制台问服务端 `/auth/me/localization` 时,把应用默认语言作为 `Accept-Language` 带上(设备上没有手选语言时);服务端不改,个人语言照旧最先生效。 - 为什么改:应用声明 `i18n.defaultLocale: 'zh-CN'` 后,服务端给这类用户发通知用中文,控制台却跟着浏览器显示英文,同一个设置两张脸不一致。 - 风险与回滚:⚠️ discovery 总会给出默认语言,没写 `i18n` 块的应用给的是 `en`。所以**没写 `i18n` 块的应用里、没设个人语言的用户,用中文浏览器现在看到英文**(与服务端通知用的语言一致);用户在语言菜单里选一次就会写入个人语言、从此以个人语言为准。已有设备上缓存的旧语言还会再显示一次页面加载,下一次起按应用默认语言,不会在使用中途突然切换。回滚即 revert,只动控制台两个文件。 - 先看:`ui/apps/console/src/languageSeed.ts` 的 `loadAppDefaultLocale` 与 `fetchAndCacheSeed` 里新增的 `Accept-Language`;`ui/apps/console/src/LocalizationFetchProvider.tsx` 里 `const preference = …` 那一行;`languageSeed.test.ts` 末尾 `objectstack#33231` 的三个用例。 - 两分钟验证:`pnpm --dir ui exec vitest run apps/console/src/languageSeed.test.ts apps/console/src/LocalizationFetchProvider.test.tsx apps/console/src/__tests__/localizationBootDedup.test.tsx`,预期 3 个文件 38 个用例全绿,其中「en-US 浏览器 + 应用默认 zh-CN → 显示 `zh-CN|取消`」。 - 需要你做的:无,席位落地。若不接受「没写 `i18n` 块的应用一律按 `en`」这一后果,请在本 PR 上说,合并前可以改。 ## What changes - **`languageSeed.ts`** (`@object-ui/console`). - New `loadAppDefaultLocale(serverBase)`: reads discovery `locale.default` once per page load through `getSharedDiscovery` (`@object-ui/data-objectstack`), the same shared request the data adapter's `connect()` makes, so it adds no request of its own. It never rejects; a failed or unreadable discovery answers `undefined`. `startedAppDefaultLocale()` hands the started read to the in-app provider. - `seedTenantLanguage` starts that read on every boot with no explicit choice on the device (an explicit choice still returns first, spending nothing). - `fetchAndCacheSeed` (the first-visit race) waits for the read and states the app's default as the `/auth/me/localization` request's `Accept-Language`. The server's rungs are unchanged: `sys_user.locale` answers first, the stated default answers the rung below it. With no default served, no header is stated and the browser's own goes out, as before. - **`LocalizationFetchProvider.tsx`** (`@object-ui/console`). With no explicit choice on the device, the every-boot read states the same app default (it used to send the browser's header). This read is what refreshes the cached language seed, so the next boot's language follows the app default, and the dates and numbers it feeds (`useDisplayLocale`) follow it too. With an explicit choice it still states that choice. Seed and provider state the same header, so on a first visit they still share one request. - **Where each language source sits, measured.** At boot `@object-ui/i18n`'s `resolveBootstrapConfig` reads: the device's explicit choice (`objectui-locale`: the cache of `sys_user.locale` that `useSignedInUserLocale` applies, or a language picked on this device) → the cached seed (`objectui-locale-seed`, the server's answer above) → the browser (`pickInitialLanguage`) → `en`. After first paint `useSignedInUserLocale` applies a set `sys_user.locale`. This PR changes only what the seed holds for a user with no personal locale: the app default instead of the browser. `@object-ui/i18n` is not edited; the browser detection in `i18n.ts` named on the claim's file surface did not need to change. - **Changeset** `.changeset/33231-console-app-default-locale.md`: `@object-ui/console` patch (it ships the built SPA in `dist`), both declaration lines. ## Tests - `languageSeed.test.ts`, new describe `the app's declared default outranks the browser (objectstack#33231)`. A fake server answers `/auth/me/localization` by its three rungs (the user's own locale, else the request's stated `Accept-Language`, else the browser's), and discovery serves a default or a 404. Each case runs the boot as `main.tsx` does (`seedTenantLanguage`, `preloadBootstrapLocale`, then renders `I18nProvider` with a probe) and reads the rendered language, a translated label and the html element's `lang`: - no personal locale, default `zh-CN`, `en-US` browser: `zh-CN|取消`, html `lang` `zh-CN`, seed `zh-CN`, one localization request, nothing written to the explicit-choice slot; - personal `en`, default `zh-CN`, `zh-CN` browser: `en|Cancel`, html `lang` `en`; - no default served, `ja` browser: `ja|キャンセル`, html `lang` `ja`, and the request stated no `Accept-Language`. - `LocalizationFetchProvider.test.tsx` (the `objectstack#27625` describe): with no choice and the app default read started, the read states `zh-CN`, the dates render `2026年10月11日`, and the seed cached is `zh-CN`. The existing "with no choice, the read states nothing" case still holds when no default read was started. - `__tests__/localizationBootDedup.test.tsx`: the three existing request-budget cases now answer the discovery URL as a server with no default and count localization requests only; new case: seed and provider both stating `zh-CN` still share ONE localization request. - Existing `languageSeed.test.ts` cases: helpers answer discovery with a 404 (the browser path the old cases model) and count localization requests; "does not wait when a seed is already cached" now asserts no localization request (the discovery read it starts is the adapter's own). - Ablations through `scripts/ablation-replace.mjs` on head `12260995`, each over the three files (38 tests), restored with blob equal to HEAD and `git diff HEAD` empty: - the seed's stated `Accept-Language` disabled (`languageSeed.ts`, blob `c3685942` to `198db16e`): 2 failed, 36 passed. Red: the zh-CN/en-US boot case (`expected 'en-US|Cancel' to be 'zh-CN|取消'`, the card's symptom) and the one-request case. - the provider's app-default preference disabled (`LocalizationFetchProvider.tsx`, blob `16feb1f7` to `115611f6`): 2 failed, 36 passed. Red: the provider case (`expected null to be 'zh-CN'`) and the one-request case. - The personal-locale and no-default cases stay green under both, as they should: they pin what must not change. Console tests import these modules from source, so no build sat between mutation and run. ## Acceptance notes - **An app with no `i18n` block now gives no-locale users English, whatever the browser.** Discovery's `locale.default` is required in `DiscoverySchema` and is never absent: the dispatcher's floor is `en`, and service-i18n's adapter answers `options.defaultLocale ?? 'en'`. So the console cannot tell a declared `en` from no declaration, and the ruled order makes the browser decide only when discovery answers no default (unreachable, or a server without the field). This is the language the server already writes to these users in. The seat read it as the literal ruling, not a new decision; it is called out here as the maintainer's veto window. - **One page load of delay on devices that already hold a seed.** A device whose cached seed was the browser's language boots in it once more; that boot's provider read refreshes the seed to the app default and the next boot follows it. A true first visit whose discovery-plus-localization reads miss the 500 ms race boots in the browser language and caches the answer for the next boot. Both keep the existing rule that a boot never switches language mid-session. - **Not changed, stated:** the sign-in page on a device that has never had a signed-in user still renders in the browser language (the endpoint answers no locale before sign-in, and the ruling's order is for a user); after a change of owner on a shared browser, `useLanguageResetOnOwnerChange` still resets to the browser language for the rest of that page load, and the next boot follows the app default. - **The discovery read is shared with the adapter** only when the keys agree: the boot keys it by `SERVER_BASE` (`VITE_SERVER_URL` with trailing slashes removed), the adapter by `VITE_SERVER_URL` as written. With a trailing slash configured the two are separate requests on a first visit. - **File surface:** the claim names `languageSeed.ts`, `LocalizationFetchProvider.tsx`, the browser detection in `i18n.ts`, their tests and the changeset. `__tests__/localizationBootDedup.test.tsx` is a test of the two modules (its request count had to separate the discovery read); `i18n.ts` was not touched. - **Declaration lines measured on the diff:** no published export, key or schema arm changes; `@object-ui/console`'s package exports (`plugin.js`) are untouched and `@object-ui/i18n` is not edited. `Clause-②: no`, `Metadata-protocol: none`, as the claim opened. ## Verification Run on head `12260995` (base `origin/main` `d4fbb4db`). <details><summary>Build, tests, type-check and lint</summary> - Build under the verify lock: `pnpm --workspace-concurrency=2 --filter '@objectstack/spec...' --filter '@objectstack/formula...' --filter '@objectstack/client...' --filter '@objectstack/lint...' --filter '@objectstack/sdui-parser...' build`, then `pnpm --workspace-concurrency=2 --filter '@object-ui/console^...' build`: both VERDICT command-exit 0. - `pnpm --filter @object-ui/console run type-check`: exit 0 (both `tsc --noEmit` and `tsc -b tsconfig.node.json`). - The three touched test files: Test Files 3 passed (3), Tests 38 passed (38). - Whole console project, `pnpm --dir ui exec vitest run apps/console/`, on `b3237cdb`: Test Files 310 passed, 1 failed (311); Tests 3191 passed, 1 failed. The red was `localizationBootDedup.test.tsx` counting the new discovery read as a localization request; `12260995` makes that file count localization reads only (and adds the shared-default case), and the file is green above. `12260995` changes no source file, only that test. - eslint on the four changed source and test files: exit 0. `pnpm --dir ui run check:new-line-citations`: 0 new citations, exit 0. </details> <details><summary>Derived gates (36)</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 36 families on this diff (the same 36 on `b3237cdb` and `12260995`). All 36 exited 0 on `b3237cdb`, and again on `12260995`, among them `pnpm --dir ui exec vitest run scripts/`, `pnpm check:type-check-debt`, `pnpm check:test-source-alias` and `pnpm check:published-files`. `--ran` reconciliation on `12260995`: 36 derived, 36 run, 0 NOT-MEASURED, 0 UNRUN. Changed lines: under the 3,000 threshold. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oJs154mFFCPgUmnhE)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5oJs154mFFCPgUmnhE --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent d3ceb1d commit 9ba2d4c

6 files changed

Lines changed: 354 additions & 27 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
fix(console): a user with no personal language gets the app's declared default language, not the browser's
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The Console's language for a signed-in user is now their own `sys_user.locale`, else the app's declared `i18n.defaultLocale` (served as discovery `locale.default`), else the browser language, else `en`. Before, a user with no personal language got the browser's language even when the app declared another default, while the server already wrote to that user in the app's default. `<html lang>` follows the resolved language.
11+
12+
Discovery always serves a default: an app with no `i18n` block is served `en`. So a user with no personal language in such an app now gets English whatever the browser says, the language the server already writes to them in; picking a language from the language menu sets `sys_user.locale` and outranks it. The browser language decides only when discovery serves no default.
13+
14+
A device that already has a cached language from an earlier visit shows it for one more page load, then follows the app's default; the switch is never made mid-session. A language picked on the device or set on the user's profile is unchanged. No server change.

‎ui/apps/console/src/LocalizationFetchProvider.test.tsx‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ import { notifyDataChanged } from '@object-ui/react';
3030
// Test-only and off the `@object-ui/types` barrel; the vitest alias makes this
3131
// the same module instance the provider's `sharedGetJson` uses.
3232
import { resetInflightGetsForTesting } from '../../../packages/types/src/http-inflight';
33+
import { clearSharedDiscoveryCache } from '@object-ui/data-objectstack';
3334
import { LocalizationFetchProvider } from './LocalizationFetchProvider';
35+
import { __resetAppDefaultLocaleForTests, loadAppDefaultLocale } from './languageSeed';
3436
// Not on the `@object-ui/auth` barrel; the vitest alias maps that barrel to
3537
// `packages/auth/src`, so this deep path is the SAME module instance the
3638
// provider's `getSessionOwnerChangeCount` reads.
@@ -401,6 +403,33 @@ describe('LocalizationFetchProvider', () => {
401403
authUser = null;
402404
window.localStorage.clear();
403405
resetInflightGetsForTesting();
406+
__resetAppDefaultLocaleForTests();
407+
clearSharedDiscoveryCache();
408+
});
409+
410+
it("with no choice on this device, the read states the app's declared default (objectstack#33231)", async () => {
411+
// Discovery serves `locale.default: 'zh-CN'`; the server answers the
412+
// `Accept-Language` rung with what it was told, else the browser's en-US.
413+
fetchMock().mockImplementation(async (url: string, init: RequestInit) =>
414+
String(url).endsWith('/api/v1/discovery')
415+
? ok({ success: true, data: { locale: { default: 'zh-CN', supported: ['zh-CN'], timezone: 'UTC' } } })
416+
: ok({
417+
authenticated: true,
418+
currency: null,
419+
locale: (init.headers as Record<string, string>)['Accept-Language'] ?? 'en-US',
420+
timezone: 'UTC',
421+
}),
422+
);
423+
// The boot starts this read before the app mounts (`seedTenantLanguage`).
424+
void loadAppDefaultLocale('');
425+
426+
renderUnderLanguage('zh-CN');
427+
428+
await waitFor(() => expect(screen.getByTestId('display')).toHaveTextContent('zh-CN|2026年10月11日'));
429+
expect(statedOn(1)).toBe('zh-CN');
430+
expect(fetchMock()).toHaveBeenCalledTimes(2);
431+
// The seed the next boot reads is the app's default, not the browser's.
432+
expect(window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('zh-CN');
404433
});
405434

406435
it('a language picked before sign-in is the one the read states, and the dates follow it', async () => {

‎ui/apps/console/src/LocalizationFetchProvider.tsx‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,23 @@
5959
* So when the device holds an explicit language choice, this read states that
6060
* language. The server's rungs are unchanged: a stored `sys_user.locale` still
6161
* answers first, and the header only decides the rung below it. Without a
62-
* choice the browser's header stays: that is exactly the boot on which
62+
* choice, see the next section: that is exactly the boot on which
6363
* `seedTenantLanguage()` asks this endpoint too, and the two share one request
6464
* only while their headers match (objectui#5544). The stated language is part
6565
* of the request, so a change of it reads again, and the new read cannot join
6666
* one still in flight under the old language: the in-flight key includes the
6767
* headers.
68+
*
69+
* ## With no choice, state the app's declared default (objectstack#33231)
70+
*
71+
* The browser's header answered the `Accept-Language` rung for a user with no
72+
* `sys_user.locale`, so both the dates here and the language seed this read
73+
* refreshes followed the browser, never the app's declared default (discovery
74+
* `locale.default`). With no explicit choice on the device, this read states
75+
* that default instead, the same value `seedTenantLanguage()` states, so the
76+
* two still share one request on a first visit. Only when no default is
77+
* served (discovery failed, or never asked, as outside the console's boot)
78+
* does the browser's own header go out.
6879
*/
6980
import { useEffect, useState } from 'react';
7081
import {
@@ -75,6 +86,7 @@ import {
7586
type LocalizationValue,
7687
} from '@object-ui/i18n';
7788
import { getSessionOwnerChangeCount, useAuth } from '@object-ui/auth';
89+
import { startedAppDefaultLocale } from './languageSeed';
7890
import { useDataInvalidation } from '@object-ui/react';
7991
import {
8092
HttpFetchError,
@@ -113,8 +125,9 @@ export function LocalizationFetchProvider({
113125
const userId = user?.id ? String(user.id) : undefined;
114126
// Bumps on every write to the signed-in user's own row (objectstack#27498).
115127
const userRowWrites = useDataInvalidation(userId ? 'sys_user' : undefined, userId);
116-
// The device's chosen UI language, stated as this read's `Accept-Language`;
117-
// none chosen, the browser's own header goes out (objectstack#27625).
128+
// The device's chosen UI language, stated as this read's `Accept-Language`
129+
// (objectstack#27625); none chosen, the app's declared default is stated
130+
// inside the effect (objectstack#33231).
118131
const { language } = useObjectTranslation();
119132
const statedLanguage = readStoredLanguage() ? language : undefined;
120133

@@ -125,7 +138,15 @@ export function LocalizationFetchProvider({
125138
// boot read keeps sharing with `seedTenantLanguage()` (objectui#5544).
126139
const reread = userRowWrites > 0 ? new AbortController() : undefined;
127140

141+
// Read when the effect runs, not at render: `seedTenantLanguage()` starts it
142+
// before the app mounts, and nothing in it is React state.
143+
const appDefaultRead = statedLanguage ? null : startedAppDefaultLocale();
144+
128145
void (async () => {
146+
// No explicit choice ⇒ the app's declared default decides the rung below
147+
// the user's own locale; none served, the browser's own header goes out.
148+
const preference = statedLanguage ?? (appDefaultRead ? await appDefaultRead : undefined);
149+
if (cancelled) return;
129150
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
130151
// Whose answer this attempt will be (objectui#10193). The request
131152
// carries whatever session this browser holds right now; if
@@ -145,7 +166,7 @@ export function LocalizationFetchProvider({
145166
credentials: 'include',
146167
headers: {
147168
Accept: 'application/json',
148-
...(statedLanguage ? { 'Accept-Language': statedLanguage } : {}),
169+
...(preference ? { 'Accept-Language': preference } : {}),
149170
},
150171
signal: reread?.signal,
151172
});

‎ui/apps/console/src/__tests__/localizationBootDedup.test.tsx‎

Lines changed: 64 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,22 @@
1616
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
1717
import { render, screen, waitFor } from '@testing-library/react';
1818
import { useLocalization, readCachedLanguageSeed } from '@object-ui/i18n';
19+
import { clearSharedDiscoveryCache } from '@object-ui/data-objectstack';
1920
import { resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
20-
import { seedTenantLanguage } from '../languageSeed';
21+
import { __resetAppDefaultLocaleForTests, seedTenantLanguage } from '../languageSeed';
2122
import { LocalizationFetchProvider } from '../LocalizationFetchProvider';
2223

2324
const ENDPOINT = '/api/v1/auth/me/localization';
25+
const DISCOVERY = '/api/v1/discovery';
26+
27+
/**
28+
* The boot's discovery read (objectstack#33231) is the data adapter's request,
29+
* not this endpoint's: these answer it as a server serving no default, unless a
30+
* test says otherwise, and count only the localization requests.
31+
*/
32+
const isDiscovery = (url: unknown) => String(url).endsWith(DISCOVERY);
33+
const meCalls = (fetchStub: ReturnType<typeof vi.fn>) =>
34+
fetchStub.mock.calls.filter(([url]) => !isDiscovery(url)).length;
2435

2536
function deferred<T>() {
2637
let resolve!: (value: T) => void;
@@ -48,6 +59,8 @@ function Consumer() {
4859
beforeEach(() => {
4960
resetInflightGetsForTesting();
5061
localStorage.clear();
62+
__resetAppDefaultLocaleForTests();
63+
clearSharedDiscoveryCache();
5164
});
5265

5366
afterEach(() => {
@@ -59,14 +72,16 @@ afterEach(() => {
5972
describe('first-visit localization request budget', () => {
6073
it('serves the seed and the provider from ONE request', async () => {
6174
const gate = deferred<Response>();
62-
const fetchStub = vi.fn(() => gate.promise);
75+
const fetchStub = vi.fn((url: string) =>
76+
isDiscovery(url) ? Promise.resolve(jsonResponse({}, 404)) : gate.promise,
77+
);
6378
vi.stubGlobal('fetch', fetchStub);
6479

6580
// True first visit: no stored choice, no cached seed ⇒ the seed fetches and
6681
// races a timeout. A tiny timeout keeps the test fast; the shape is the same
6782
// one production has at 500 ms — the race resolves while the fetch runs on.
6883
await seedTenantLanguage('', 1);
69-
expect(fetchStub).toHaveBeenCalledTimes(1);
84+
await waitFor(() => expect(meCalls(fetchStub)).toBe(1));
7085

7186
// The provider mounts right after the boot's `Promise.all` resolves — while
7287
// the seed's request is still in flight.
@@ -83,17 +98,49 @@ describe('first-visit localization request budget', () => {
8398
// ── and the seed got the same answer ──
8499
await waitFor(() => expect(readCachedLanguageSeed()).toBe('zh-CN'));
85100
// ── from one network call ──
86-
expect(fetchStub).toHaveBeenCalledTimes(1);
101+
expect(meCalls(fetchStub)).toBe(1);
102+
});
103+
104+
it("still ONE request when both state the app's declared default (objectstack#33231)", async () => {
105+
const gate = deferred<Response>();
106+
const fetchStub = vi.fn((url: string, _init?: RequestInit) =>
107+
isDiscovery(url)
108+
? Promise.resolve(jsonResponse({ locale: { default: 'zh-CN', supported: ['zh-CN'], timezone: 'UTC' } }))
109+
: gate.promise,
110+
);
111+
vi.stubGlobal('fetch', fetchStub);
112+
113+
await seedTenantLanguage('', 1);
114+
await waitFor(() => expect(meCalls(fetchStub)).toBe(1));
115+
render(
116+
<LocalizationFetchProvider endpoint={ENDPOINT}>
117+
<Consumer />
118+
</LocalizationFetchProvider>,
119+
);
120+
121+
gate.resolve(jsonResponse({ authenticated: true, locale: 'zh-CN', currency: 'CNY' }));
122+
123+
await waitFor(() => expect(screen.getByTestId('value').textContent).toBe('zh-CN/CNY'));
124+
await waitFor(() => expect(readCachedLanguageSeed()).toBe('zh-CN'));
125+
// The two state the same `Accept-Language`, so they share the request.
126+
expect(meCalls(fetchStub)).toBe(1);
127+
const stated = fetchStub.mock.calls
128+
.filter(([url]) => !isDiscovery(url))
129+
.map(([, init]) => init?.headers as Record<string, string>);
130+
expect(stated.map((h) => h['Accept-Language'])).toEqual(['zh-CN']);
87131
});
88132

89133
it('passes a shared 503 through to the retry policy rather than resolving it empty', async () => {
90134
const gate = deferred<Response>();
91-
const fetchStub = vi
92-
.fn()
93-
.mockImplementationOnce(() => gate.promise)
94-
.mockImplementation(async () =>
95-
jsonResponse({ authenticated: true, locale: 'ja-JP', currency: 'JPY' }),
96-
);
135+
let first = true;
136+
const fetchStub = vi.fn(async (url: string) => {
137+
if (isDiscovery(url)) return jsonResponse({}, 404);
138+
if (first) {
139+
first = false;
140+
return gate.promise;
141+
}
142+
return jsonResponse({ authenticated: true, locale: 'ja-JP', currency: 'JPY' });
143+
});
97144
vi.stubGlobal('fetch', fetchStub);
98145

99146
await seedTenantLanguage('', 1);
@@ -112,19 +159,21 @@ describe('first-visit localization request budget', () => {
112159
await waitFor(() => expect(screen.getByTestId('value').textContent).toBe('ja-JP/JPY'), {
113160
timeout: 5000,
114161
});
115-
expect(fetchStub.mock.calls.length).toBeGreaterThanOrEqual(2);
162+
expect(meCalls(fetchStub)).toBeGreaterThanOrEqual(2);
116163
});
117164

118165
it('does not share once the request has settled', async () => {
119-
const fetchStub = vi.fn(async () =>
120-
jsonResponse({ authenticated: true, locale: 'en-US', currency: 'USD' }),
166+
const fetchStub = vi.fn(async (url: string) =>
167+
isDiscovery(url)
168+
? jsonResponse({}, 404)
169+
: jsonResponse({ authenticated: true, locale: 'en-US', currency: 'USD' }),
121170
);
122171
vi.stubGlobal('fetch', fetchStub);
123172

124173
// Let the seed's request settle completely before the provider mounts.
125174
await seedTenantLanguage('', 1);
126175
await waitFor(() => expect(readCachedLanguageSeed()).toBe('en-US'));
127-
expect(fetchStub).toHaveBeenCalledTimes(1);
176+
expect(meCalls(fetchStub)).toBe(1);
128177

129178
render(
130179
<LocalizationFetchProvider endpoint={ENDPOINT}>
@@ -134,6 +183,6 @@ describe('first-visit localization request budget', () => {
134183

135184
await waitFor(() => expect(screen.getByTestId('value').textContent).toBe('en-US/USD'));
136185
// Two waves, two requests: this is in-flight sharing, not a cache.
137-
expect(fetchStub).toHaveBeenCalledTimes(2);
186+
expect(meCalls(fetchStub)).toBe(2);
138187
});
139188
});

0 commit comments

Comments
 (0)