Skip to content

Studio: optimize startup with on-demand language catalogs - #8623

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
oobabooga:audit/studio-lazy-locales
Aug 14, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
oobabooga:audit/studio-lazy-locales

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Every Studio startup downloads and parses all 12 language catalogs even though the interface displays only one language. On the test machine, the unused catalogs add about 1 MB of decoded resources and 300 KB to the production language bundle.

What changed

  • Keep English available synchronously and split the other 11 catalogs into separate files.
  • Load a saved or browser-detected non-English catalog before the first render, with a 2-second English fallback so a stalled request cannot leave the page blank indefinitely.
  • Preserve the selected language while that English fallback is rendered, so a temporary catalog failure cannot overwrite the synchronized preference.
  • Fetch later language selections only when they are chosen, show the requested language with a loading indicator, and save the selection only after its catalog loads successfully.
  • Share concurrent requests for the same catalog and prevent slower requests from replacing a newer language selection.
  • Keep the active and saved language unchanged when an in-session catalog load fails.

Results

Measurements are medians from 10 interleaved fresh Chromium contexts against production builds with the browser cache disabled.

Scenario Metric Main This change Improvement
English startup Decoded resources 9,562 KB 8,628 KB 935 KB less
English startup Transferred resources 4,378 KB 4,110 KB 268 KB less
English startup First contentful paint 518 ms 470 ms 48 ms sooner
English startup Largest contentful paint 744 ms 706 ms 38 ms sooner
Saved German startup Decoded resources 9,562 KB 8,703 KB 859 KB less
Saved German startup Transferred resources 4,378 KB 4,134 KB 244 KB less
Saved German startup First contentful paint 526 ms 484 ms 42 ms sooner
Saved German startup Largest contentful paint 760 ms 720 ms 40 ms sooner

With the German catalog deliberately delayed by 4 seconds, the previous implementation did not paint until 4.52 seconds. The bounded initialization path painted the English fallback at 2.50 seconds, then applied German when its catalog arrived.

Switching from English to German in the live UI remained effectively unchanged at 591 ms on main and 583 ms with this change. The switch fetched only the German catalog, 75 KB decoded and 25 KB transferred.

Testing

  • npm test (2,017 passed)
  • Focused lazy locale loading coverage (10 passed)
  • npm run i18n:check
  • npm run typecheck
  • npm run build
  • Focused ESLint checks and git diff --check
  • Live production-build comparisons for English startup, saved German startup, delayed initial and in-session catalog responses, and an English-to-German language switch

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Thanks, the bundle saving is real and reproduces here. I built both sides and drove a Studio with the catalog held back 4s: startup JS on the wire 6,727,410 -> 5,846,945 bytes, and eager JS in a production build 6,566 KB -> 5,632 KB, which matches your 935 KB. The pending spinner in the Select shows up cleanly. Full suite 2,030 passed, typecheck, i18n:check and build all pass on my side too.

I pushed da025009a to this branch with two fixes, both in the same six lines of the hydration effect in use-personalization-sync.ts.

A failed catalog disabled the whole personalization sync for the session. The early return on "failed" exits before setHydratedGeneration(generation) at the end of the same block, and the outbound save effect gates on exactly that value while the hydration effect only re-runs on [enabled]. So the gate never opened again. The comment frames it as pausing the language, but payload() also carries profile, avatar, theme, palette and the whole sidebar customization, and none of it was pushed afterwards, with nothing surfacing that to the user.

It is reachable rather than theoretical: /assets is served immutable-cached while index.html is no-store, so a tab left open across an in-place update asks for a hashed catalog chunk the new build no longer has, gets a 404, and the fetch rejects. That is a new failure mode this PR introduces, since before it there was no per-locale request to fail.

"superseded" was treated as success. If the remote language load is superseded by the user picking another language, and that newer request then fails, the hook recorded the remote language as the synchronized baseline and the debounced save pushed the stale local preference back over the server's.

The fix adds an adoptOnFailure option to setLocale, used only by hydration, that routes a failed load through the commitFallbackLocale you already wrote for the init timeout: the preference is adopted and the messages fall back to English. The preference hydration is applying is already the server's stored truth, so adopting it keeps the local value equal to the remote one and the baseline honest, and everything else keeps syncing. A user's own failed pick is unchanged: still not adopted, still not persisted. Neither path writes storage on failure.

I also fixed a smaller one found alongside: applyPreference's synchronous-throw path called failPreference before this request had become the pending one, clearing the marker an unrelated in-flight request was relying on and blanking its spinner.

Four tests added to lazy-locale-loading.test.ts, 17 passing.

One thing I did not change, for you to decide on. main.tsx now holds root.render until locale init settles, up to LOCALE_INITIALIZATION_TIMEOUT_MS, and index.html has no splash markup, only theme-boot.js setting the theme class. With the catalog delayed the measured first paint went 1.29s -> 3.14s, and at 1.2s the page is a correctly themed but completely empty window where it previously showed the full UI. Screenshot below, same moment on both sides.

The part worth weighing is who sees it. DEFAULT_LOCALE_PREFERENCE is AUTO_LOCALE and resolvePreference reads navigator.language, so any first visit from a browser set to one of the 11 non-English locales takes the async path, not only users who explicitly saved a language. English browsers render synchronously, which is why local testing does not show it. Either rendering immediately and letting the store swap the catalog in when it arrives, or adding a minimal themed splash so the window reads as loading, would close it. Your call on which.

BEFORE and AFTER at 1.2s into startup, German preference, catalog delayed 4s

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da025009ac

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +219 to +220
pendingPreference = previousPending;
pendingPreferenceShouldPersist = previousPendingPersist;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the restored pending request's revision valid

When one locale request is pending and a subsequent setLocale loader throws synchronously, this catch restores the earlier pending marker but leaves preferenceRevision incremented for the failed request. When the earlier load later resolves, commitPreference therefore reports it as superseded and cannot clear the restored marker, leaving the language selector busy forever and never applying that catalog. Restore the earlier revision along with its pending state, or clear the pending state instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mechanically true, and I checked it: the pending marker does stay stuck and the earlier request does come back superseded. But it needs loadMessages to throw synchronously, and the production loader is import()-based, so it always returns a promise and rejects asynchronously. Only an injected test loader can reach this. Leaving it as is rather than adding a rollback for a path no caller can take.

Comment on lines +63 to +64
if (typeof localeInitialization !== "string") {
localeInitialization.then(renderApp);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Listen for locale changes during catalog initialization

When initialization waits for a non-English catalog, the app does not render here until the request finishes or times out, while the locale store only installs its storage listener when a rendered component first calls subscribeLocale. If another tab changes the persisted locale during that window, the event is lost and initialization later commits its previously captured preference; mounting the listener does not reread storage, so this tab can remain on the stale language until another storage event or reload. Start the listeners before awaiting initialization or reconcile the stored preference before rendering.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. It needs a second tab to write the locale inside the sub-2s window before the first render, and nothing is corrupted if it happens: initializeLocale commits with persist = false, so the stored preference is untouched and the tab picks it up on the next storage event or reload. Adding a listener around initialization buys a self-correcting case a narrower race.

danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…#8623

Showing the in-effect locale only when it differs from the preference left auto
as the one preference a user could not retry: a failed auto still reads as auto,
and its fallback locale is indistinguishable from a successful detection that
landed on the same language. Radix holds auto, so picking Auto-detect again
fires nothing and the app looks like it ignored the click.

The store now records why the preference and the locale diverge.
commitFallbackLocale sets the flag, commitPreference clears it, and
failPreference sets it only when the standing preference was refreshed onto a
locale the app is not showing: a rejected pick leaves the standing preference
serving its own catalog and must stay named.

The failed chunk is not negatively cached (messages.ts deletes the in-flight
entry in .finally), so a re-pick genuinely re-issues the import.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f4a0d66367

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (nextLanguage !== latestLanguageRef.current)
setLocale(nextLanguage);
if (nextLanguage !== latestLanguageRef.current) {
const localeResult = await setLocale(nextLanguage, {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the locale hydration request

When a signed-in profile has a different non-English language and its dynamic catalog request remains pending—for example, because a proxy or service worker accepts the chunk request but never responds—this await never reaches either adoptOnFailure handling or setHydratedGeneration. The save effect remains gated by hydratedGeneration !== authGenerationRef.current, so unrelated profile and appearance changes cannot sync for as long as the chunk is stalled. Apply a timeout similar to startup initialization so hydration can adopt the fallback and open the save gate even when the loader neither resolves nor rejects.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This raced 76a45c6, which landed the bounded hydration before the review was posted. The path described here is already awaited with a bound on head.

danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
… PR unslothai#8623

Two things a stalled or failed catalog could still do.

A catalog request that is accepted and then never completes rejects
nothing, so personalization hydration awaited setLocale forever: the save
gate never opened again and every later edit to display name, nickname,
avatar, theme, palette, sidebar or greeting sloth stayed local for the
session. setLocale now takes the same bounded fallback initializeLocale
uses at startup, and hydration asks for it; a late catalog still commits
over the fallback.

And the retry itself did not re-request. Chrome, Edge and Firefox before
155 keep a failed module in the module map keyed by URL, so dropping our
own promise only made the store willing to ask again. A retry now
re-imports the chunk with a one-off query, taken from the URL the browser
reports in the failure. Only a retry carries it, so the first load of a
hashed catalog keeps its normal caching.
@danielhanchen

Copy link
Copy Markdown
Member

Two more defects closed in 76a45c6bd, and the second one shows my earlier retry fix was necessary but not sufficient.

A catalog that never settles blocked every personalization save. Hydration awaited setLocale(...) and setHydratedGeneration only ran after it, with the save effect gated on that. applyPreference had no bound at all, so a request that neither resolves nor rejects (stalled CDN, proxy, service worker) left the promise pending for the session and the gate shut. Display name, nickname, avatar, theme, palette, sidebar customization and greeting sloth all updated locally and were silently never sent, then reverted on reload. A settled 404 was fine; this needed a hang. initializeLocale was the only bounded path in the file.

SetLocaleOptions gains timeoutMs. applyPreference races the settle against a timer and on expiry takes exactly the branch a rejection would (commitFallbackLocale under adoptOnFailure, else failPreference), resolving failed, and leaves the load alone so a late arrival still commits over the fallback. Hydration passes LOCALE_INITIALIZATION_TIMEOUT_MS, the same 2s bound startup already uses. Because the store adopts the preference on expiry, the baseline written just below stays honest and the debounced push still cannot overwrite the remote language.

The retry did not actually re-request. Deleting our entry from localeLoads only makes the store willing to ask again; the module map caches the failed fetch by URL, so the same import("./locales/de") resolves to the stored failure with no network request. That is the still-open spec bug (whatwg/html#6768, fix proposed in whatwg/html#10327 and unshipped in Chromium). Firefox fixed it in 155 (bug 2055211) and Safari is the exception. So the affordance I restored in the previous two commits was real but inert on Chrome and Edge.

A failed load now records a retry URL and the next loadLocaleMessages imports that instead, with one ?catalogRetry=<n>. The URL comes out of the browser own message (Failed to fetch dynamically imported module: <url>), which is the only place a built chunk URL is exposed to us.

I did not use vite:preloadError: it carries no more information than the error we already catch and cannot itself re-request, and preventDefault() would only swallow the throw. A whole-page reload handler is the documented deploy-rotation answer, not a language-picker answer.

On hashing and cache headers: the query is appended only on a retry, so the first load of de-BfPWv64n.js is byte-identical to today and keeps its immutable caching. The retry differs in both module-map key and HTTP cache key, which is the point, and the path is unchanged so the dev server, vite preview and any static host resolve the same file, since queries are ignored for file lookup. searchParams.set replaces rather than appends so repeated failures cannot grow the URL, and .css URLs are rejected because a preload failure names the stylesheet rather than the module.

7 tests. The retry ones assert a SECOND importer invocation with a DIFFERENT URL and the same hashed path, not merely that the store tried again. 6 fail pre-fix. Suite 2039 to 2046, typecheck clean, i18n:check 0 missing keys, build emits all 11 locale chunks.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…ai#8623

A catalog request that is accepted and then never completes rejects
nothing, so the language menu, a storage event and a languagechange
refresh all had nothing to settle them: the pending marker stayed set for
the rest of the session, the menu spun on a language it would never
reach, and because a never-settling load also never runs the finally that
clears the in-flight map, every later pick of that language was handed
the same dead promise. Reloading the app was the only way out.

Startup and hydration already pass their own bound, so give every other
path the store's. It is longer than startup's, because this one is a
deliberate download rather than the render everything else is waiting on,
and the load is still left alone, so a slow catalog commits over the
fallback rather than being lost.

Before the lazy catalogs every language was in the bundle and a pick
could not wait on the network at all, so this is the one shape that was
strictly worse than the old behaviour.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
@danielhanchen
danielhanchen force-pushed the audit/studio-lazy-locales branch from 5fa4b3a to 2ff877e Compare August 13, 2026 14:13
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…#8623

Showing the in-effect locale only when it differs from the preference left auto
as the one preference a user could not retry: a failed auto still reads as auto,
and its fallback locale is indistinguishable from a successful detection that
landed on the same language. Radix holds auto, so picking Auto-detect again
fires nothing and the app looks like it ignored the click.

The store now records why the preference and the locale diverge.
commitFallbackLocale sets the flag, commitPreference clears it, and
failPreference sets it only when the standing preference was refreshed onto a
locale the app is not showing: a rejected pick leaves the standing preference
serving its own catalog and must stay named.

The failed chunk is not negatively cached (messages.ts deletes the in-flight
entry in .finally), so a re-pick genuinely re-issues the import.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
… PR unslothai#8623

Two things a stalled or failed catalog could still do.

A catalog request that is accepted and then never completes rejects
nothing, so personalization hydration awaited setLocale forever: the save
gate never opened again and every later edit to display name, nickname,
avatar, theme, palette, sidebar or greeting sloth stayed local for the
session. setLocale now takes the same bounded fallback initializeLocale
uses at startup, and hydration asks for it; a late catalog still commits
over the fallback.

And the retry itself did not re-request. Chrome, Edge and Firefox before
155 keep a failed module in the module map keyed by URL, so dropping our
own promise only made the store willing to ask again. A retry now
re-imports the chunk with a one-off query, taken from the URL the browser
reports in the failure. Only a retry carries it, so the first load of a
hashed catalog keeps its normal caching.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…ai#8623

A catalog request that is accepted and then never completes rejects
nothing, so the language menu, a storage event and a languagechange
refresh all had nothing to settle them: the pending marker stayed set for
the rest of the session, the menu spun on a language it would never
reach, and because a never-settling load also never runs the finally that
clears the in-flight map, every later pick of that language was handed
the same dead promise. Reloading the app was the only way out.

Startup and hydration already pass their own bound, so give every other
path the store's. It is longer than startup's, because this one is a
deliberate download rather than the render everything else is waiting on,
and the load is still left alone, so a slow catalog commits over the
fallback rather than being lost.

Before the lazy catalogs every language was in the bundle and a pick
could not wait on the network at all, so this is the one shape that was
strictly worse than the old behaviour.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
A load that never settles never clears its own entry in the in-flight map, so
the pick that timed out kept being handed back to every later attempt and the
language could not be retried without reloading the app. The selection timeout
now forgets the load it gave up on, identified by promise so a newer attempt is
never evicted, while leaving the load itself running so a late catalog still
commits.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…#8623

Showing the in-effect locale only when it differs from the preference left auto
as the one preference a user could not retry: a failed auto still reads as auto,
and its fallback locale is indistinguishable from a successful detection that
landed on the same language. Radix holds auto, so picking Auto-detect again
fires nothing and the app looks like it ignored the click.

The store now records why the preference and the locale diverge.
commitFallbackLocale sets the flag, commitPreference clears it, and
failPreference sets it only when the standing preference was refreshed onto a
locale the app is not showing: a rejected pick leaves the standing preference
serving its own catalog and must stay named.

The failed chunk is not negatively cached (messages.ts deletes the in-flight
entry in .finally), so a re-pick genuinely re-issues the import.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: edf2e041d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// entry, so leaving it there would hand every later pick of this
// language the same dead promise and time out again without ever
// asking for the catalog a second time.
forgetLocaleLoad(locale, pending);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry stalled catalogs with a fresh module URL

When the timeout fires while the browser's dynamic import is still pending, deleting localeLoads only removes the application's wrapper promise; a subsequent import() of the same module URL is still coalesced with the pending browser module load, so choosing the language again does not issue the intended recovery request and can time out repeatedly. The fresh evidence beyond the earlier eviction issue is that production importCatalog uses the unchanged static loader whenever no rejection populated catalogRetryUrls; the new test's injected importer counts function calls but does not model browser-level module deduplication. The timeout path needs to make the next attempt use a distinct module URL as the rejection retry path does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is right and there is no fix for it on this path, so I have left the limitation stated rather than adding one that cannot work.

A stall never rejects, so nothing produces the "Failed to fetch dynamically imported module: " text that catalogRetryUrl reads, and that message is the only place the built chunk's URL is exposed to us: Vite bakes the hashed specifier into the chunk at build time, and a variable specifier is not analyzable, so we cannot construct it (https://vite.dev/guide/features#dynamic-import). The one other source would be Vite's own __vitePreload modulepreload links, which is a build internal the i18n store should not depend on. Without a distinct URL the next import() is keyed on the same module map entry, which the standard holds at the "fetching" placeholder for the life of the request so a second fetch waits on the first instead of starting its own (https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import).

So the eviction is necessary and not sufficient, and agreed that the injected importer only proves the in-flight map is no longer the blocker. What it buys: the case that rejects gets a real re-request from a fresh URL, and a stall no longer hands every later pick the same dead promise, so once the original fetch settles the next pick works. A fetch that stalls forever cannot be re-requested by any code in this file.

@danielhanchen
danielhanchen force-pushed the audit/studio-lazy-locales branch from edf2e04 to 2cc51da Compare August 13, 2026 15:42
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…#8623

Showing the in-effect locale only when it differs from the preference left auto
as the one preference a user could not retry: a failed auto still reads as auto,
and its fallback locale is indistinguishable from a successful detection that
landed on the same language. Radix holds auto, so picking Auto-detect again
fires nothing and the app looks like it ignored the click.

The store now records why the preference and the locale diverge.
commitFallbackLocale sets the flag, commitPreference clears it, and
failPreference sets it only when the standing preference was refreshed onto a
locale the app is not showing: a rejected pick leaves the standing preference
serving its own catalog and must stay named.

The failed chunk is not negatively cached (messages.ts deletes the in-flight
entry in .finally), so a re-pick genuinely re-issues the import.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
… PR unslothai#8623

Two things a stalled or failed catalog could still do.

A catalog request that is accepted and then never completes rejects
nothing, so personalization hydration awaited setLocale forever: the save
gate never opened again and every later edit to display name, nickname,
avatar, theme, palette, sidebar or greeting sloth stayed local for the
session. setLocale now takes the same bounded fallback initializeLocale
uses at startup, and hydration asks for it; a late catalog still commits
over the fallback.

And the retry itself did not re-request. Chrome, Edge and Firefox before
155 keep a failed module in the module map keyed by URL, so dropping our
own promise only made the store willing to ask again. A retry now
re-imports the chunk with a one-off query, taken from the URL the browser
reports in the failure. Only a retry carries it, so the first load of a
hashed catalog keeps its normal caching.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
…ai#8623

A catalog request that is accepted and then never completes rejects
nothing, so the language menu, a storage event and a languagechange
refresh all had nothing to settle them: the pending marker stayed set for
the rest of the session, the menu spun on a language it would never
reach, and because a never-settling load also never runs the finally that
clears the in-flight map, every later pick of that language was handed
the same dead promise. Reloading the app was the only way out.

Startup and hydration already pass their own bound, so give every other
path the store's. It is longer than startup's, because this one is a
deliberate download rather than the render everything else is waiting on,
and the load is still left alone, so a slow catalog commits over the
fallback rather than being lost.

Before the lazy catalogs every language was in the bundle and a pick
could not wait on the network at all, so this is the one shape that was
strictly worse than the old behaviour.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
A load that never settles never clears its own entry in the in-flight map, so
the pick that timed out kept being handed back to every later attempt and the
language could not be retried without reloading the app. The selection timeout
now forgets the load it gave up on, identified by promise so a newer attempt is
never evicted, while leaving the load itself running so a late catalog still
commits.
danielhanchen added a commit to oobabooga/unsloth that referenced this pull request Aug 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

oobabooga and others added 10 commits August 14, 2026 07:23
…ization sync

Two problems in the same six lines of the hydration effect.

The early return on a failed catalog exits before setHydratedGeneration(generation)
at the end of the same block, and the outbound save effect gates on exactly that
value while the hydration effect only re-runs on [enabled]. So the gate never opened
again for the session. The comment frames this as pausing the language, but payload()
also carries profile, avatar, theme, palette and the whole sidebar customization, none
of which was pushed afterwards, with nothing surfacing it to the user.

It is reachable: /assets is served immutable-cached while index.html is no-store, so a
tab left open across an in-place update asks for a hashed catalog chunk the new build
no longer has, gets a 404, and the fetch rejects.

Second, 'superseded' was treated as success. If the remote language load is superseded
by a user picking another language, and that newer request then fails, the hook
recorded the remote language as the synchronized baseline and the debounced save
pushed the stale local preference back over the server's.

setLocale takes an adoptOnFailure option, used only by hydration, that routes a failed
load through commitFallbackLocale: the preference is adopted and the messages fall back
to English. The preference hydration applies is already the server's stored truth, so
adopting it keeps the local value equal to the remote one and the baseline honest,
while a user's own failed pick is still not adopted and still not persisted. Neither
path writes storage on failure, so nothing records a choice that did not work.

Also fixes a smaller one found alongside: applyPreference's synchronous-throw path
called failPreference before this request had become the pending one, clearing the
marker an unrelated in-flight request was relying on and blanking its spinner.
…#8623

Showing the in-effect locale only when it differs from the preference left auto
as the one preference a user could not retry: a failed auto still reads as auto,
and its fallback locale is indistinguishable from a successful detection that
landed on the same language. Radix holds auto, so picking Auto-detect again
fires nothing and the app looks like it ignored the click.

The store now records why the preference and the locale diverge.
commitFallbackLocale sets the flag, commitPreference clears it, and
failPreference sets it only when the standing preference was refreshed onto a
locale the app is not showing: a rejected pick leaves the standing preference
serving its own catalog and must stay named.

The failed chunk is not negatively cached (messages.ts deletes the in-flight
entry in .finally), so a re-pick genuinely re-issues the import.
… PR unslothai#8623

Two things a stalled or failed catalog could still do.

A catalog request that is accepted and then never completes rejects
nothing, so personalization hydration awaited setLocale forever: the save
gate never opened again and every later edit to display name, nickname,
avatar, theme, palette, sidebar or greeting sloth stayed local for the
session. setLocale now takes the same bounded fallback initializeLocale
uses at startup, and hydration asks for it; a late catalog still commits
over the fallback.

And the retry itself did not re-request. Chrome, Edge and Firefox before
155 keep a failed module in the module map keyed by URL, so dropping our
own promise only made the store willing to ask again. A retry now
re-imports the chunk with a one-off query, taken from the URL the browser
reports in the failure. Only a retry carries it, so the first load of a
hashed catalog keeps its normal caching.
…ai#8623

A catalog request that is accepted and then never completes rejects
nothing, so the language menu, a storage event and a languagechange
refresh all had nothing to settle them: the pending marker stayed set for
the rest of the session, the menu spun on a language it would never
reach, and because a never-settling load also never runs the finally that
clears the in-flight map, every later pick of that language was handed
the same dead promise. Reloading the app was the only way out.

Startup and hydration already pass their own bound, so give every other
path the store's. It is longer than startup's, because this one is a
deliberate download rather than the render everything else is waiting on,
and the load is still left alone, so a slow catalog commits over the
fallback rather than being lost.

Before the lazy catalogs every language was in the bundle and a pick
could not wait on the network at all, so this is the one shape that was
strictly worse than the old behaviour.
A load that never settles never clears its own entry in the in-flight map, so
the pick that timed out kept being handed back to every later attempt and the
language could not be retried without reloading the app. The selection timeout
now forgets the load it gave up on, identified by promise so a newer attempt is
never evicted, while leaving the load itself running so a late catalog still
commits.
@danielhanchen
danielhanchen force-pushed the audit/studio-lazy-locales branch from 2cc51da to 19db867 Compare August 14, 2026 07:24

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 19db867669

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +133 to +137
(error: unknown) => {
const nextUrl = catalogRetryUrl(error, retryUrl);
if (nextUrl === null) catalogRetryUrls.delete(locale);
else catalogRetryUrls.set(locale, nextUrl);
throw error;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor catalogs completed by an older timed-out request

When a timed-out load is evicted and retried, the original request can resolve first and populate loadedMessages[locale], while its locale change is correctly superseded by the retry's newer revision. If the retry then rejects, this handler still propagates that rejection, so the newer selection fails and leaves the previous language active even though the requested catalog is now loaded; the user must select the language a third time. Before recording or propagating a retry failure, treat an already-populated catalog from another in-flight attempt as success.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not reachable in the built app, so I have left it.

Two loads for one locale that are in flight at the same time always carry the same module URL. catalogRetryUrls is written only in the rejection handler, so a newer load can get a different URL only after the older one has settled; while the older one is still pending, the newer one reads the same entry (or none). Same URL means the same module map key, and the map holds the "fetching" placeholder until the request completes, so the second import() joins the first fetch and settles identically (https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import). The split this needs, an older attempt resolving while a newer one rejects, takes an injected importer that models two independent requests.

Recovery does not depend on it either: whichever attempt populates loadedMessages makes loadLocaleMessages return undefined, so the next pick commits synchronously with no load at all.

Comment on lines +364 to +366
const effectivePreference = pendingPreference ?? currentPreference;
if (effectivePreference !== AUTO_LOCALE) return;
void applyPreference(effectivePreference, pendingPreferenceShouldPersist);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist a hydrated auto preference after automatic recovery

When profile hydration adopts auto after its detected catalog fails, the fallback path intentionally does not write that preference to local storage and clears pendingPreferenceShouldPersist. If a later browser languagechange successfully re-applies auto, this call therefore commits with persist = false, leaving any previous pinned local preference in storage even though auto is now working and shown as active. A subsequent signed-out or offline reload then restores the stale pinned language instead of the recovered preference; retain the hydration persistence intent until the automatic retry succeeds.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accurate about the code, but the fix would not fix the state it describes, so I have left it.

The divergence is created earlier: hydration adopts a preference whose catalog failed, and commitFallbackLocale deliberately writes nothing, because a catalog that never loaded is not recorded as a choice that worked. From that moment storage holds the old pinned language, and a signed-out reload restores it whether or not a later languagechange ever succeeds. Persisting only on the automatic retry narrows one branch of a state we accept, and pays for it by carrying a hydration persistence intent across an unrelated browser event, where the next failPreference or commitPreference clears it again anyway.

Where the value is authoritative nothing is lost: the server still holds the preference, and the next signed-in load re-hydrates it. The chain needed for the stale read is a local pin that already disagrees with the server, plus a hydration catalog failure, plus a successful browser language change, plus a signed-out or offline reload before the next hydration.

…selectable for PR unslothai#8623

A storage event carries a preference another tab has already written to the
shared store, so treat it like hydration: adopt it even when its catalog will
not load here. Refusing it left this tab holding the preference the user had
just replaced, disagreeing with storage until a reload, and the next
personalization save uploaded that stale language over the cross-tab choice.

A controlled Select never fires onValueChange for the value it already holds,
so whichever entry the language menu names is the one entry that cannot be
picked. After a catalog failure both are needed: the failed preference is the
retry, and the fallback in effect is how a user accepts English as a real
preference instead of retrying a chunk that will not load. Name neither, which
is what an empty value means to Radix, and show the language in effect as the
placeholder.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 02f311a6bf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit eb869b8 into unslothai:main Aug 14, 2026
33 of 41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants