Skip to content

studio: carry chat settings across browsers and remote sessions - #8656

Merged
danielhanchen merged 18 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-chat-settings-sync
Aug 14, 2026
Merged

danielhanchen merged 18 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-chat-settings-sync

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

26 chat settings were written only to localStorage, so opening Studio in another browser, a private window, or a remote session started every one of them from defaults:

  • the web search, code, image and web fetch pills
  • MCP for chat
  • deep research and its allowed/blocked website policy
  • artifacts, the canvas menu item, HTML artifact collapsing, artifact network access
  • the permission mode and the legacy confirm-tool-calls toggle
  • all eight RAG knobs (source, mode, top K, auto-inject, min score, OCR, figure captions)
  • the speculative decoding preference and the GPU memory mode
  • the model list quantization and fit-on-device preferences

These describe the installation, not the browser holding them, so they now round-trip through /api/chat/settings alongside the inference params and presets already stored there. API keys (Hugging Face, external providers) and personalization were already server-side and are unchanged.

How it works

saveBool, saveString, saveRagSource, saveResearchWebsitePolicy and savePermissionMode route through one persistSetting, which mirrors a changed value to the backend. localStorage stays the synchronous boot cache:

  • hydration writes the server values back into that cache, so the paths that read storage directly (resolveToolsEnabledOnLoad, loadPermissionMode, the model-load path's speculative type and GPU memory mode) see the installation's values
  • any setting the server has never stored is backfilled from the cache, so an existing install seeds itself on first load instead of waiting for each toggle to be touched again
  • mirror writes are held until hydration has run, otherwise the model-load path would push a fresh browser's defaults over what another browser already saved

Full access stays session-only. The backend rejects permissionMode: "full", savePermissionMode never writes it, and hydration leaves both permissionMode and confirmToolCalls alone while it is active, so a stored level cannot drop a sandbox bypass the user accepted a warning for.

ChatSettingsPayload is extra="forbid" and a single out-of-contract field 400s the whole save, so mirrored-chat-settings.ts re-validates every value against the same literals and ranges before it is sent. The bounds match the backend: ragTopK 1..50 as /api/rag enforces, ragAutoInjectMinScore 0..1, domain names capped at 253 characters.

Testing

  • studio/backend/tests/test_chat_settings_payload.py: 14 tests over the new payload contract, including the rejection of permissionMode: "full", an out-of-range top K, a kb source with no kbId, and an unknown field. All pass.
  • studio/frontend/tests/mirrored-chat-settings.test.ts: 7 tests over the client-side sanitiser, covering the full round trip, the thread source shape, dropped out-of-contract values, and the empty-record check the legacy import depends on.
  • Full frontend suite: 2025 passing.
  • npm run typecheck clean, ruff check clean, biome check unchanged from the pre-change baseline on the touched files.
  • Manually verified in Studio: toggles set in one browser come back set in a second browser and in a remote session.

tsconfig.test.json now includes src/speech-recognition.d.ts; the new test reaches a src module that relies on those ambient globals.

26 chat settings were written only to localStorage, so opening Studio in
another browser, a private window, or a remote session started every one of
them from defaults: the web search, code, image and web fetch pills, MCP, deep
research and its website policy, artifacts and the canvas menu item, the
permission mode and confirm-tool-calls toggle, all eight RAG knobs, the
speculative decoding preference, the GPU memory mode, and the model list
quantization preferences.

These describe the installation, not the browser holding them, so they now
round-trip through /api/chat/settings alongside the inference params and
presets that were already stored there.

saveBool, saveString, saveRagSource, saveResearchWebsitePolicy and
savePermissionMode route through one persistSetting, which mirrors a changed
value to the backend. localStorage stays the synchronous boot cache: hydration
writes the server values back into it, and any setting the server has never
stored is backfilled from it, so an existing install seeds itself on first
load instead of waiting for each toggle to be touched again. Mirror writes are
held until hydration has run, otherwise the model-load path would push a fresh
browser's defaults over what another browser already saved.

Full access stays session-only. The backend rejects permissionMode "full",
savePermissionMode never writes it, and hydration leaves both permissionMode
and confirmToolCalls alone while it is active, so a stored level cannot drop a
sandbox bypass the user accepted a warning for.

ChatSettingsPayload is extra="forbid" and a single out-of-contract field 400s
the whole save, so mirrored-chat-settings.ts re-validates every value against
the same literals and ranges before it is sent. Its bounds match the backend:
ragTopK 1..50 as /api/rag enforces, ragAutoInjectMinScore 0..1, domain names
capped at 253 characters.

tsconfig.test.json now includes src/speech-recognition.d.ts: the new test
reaches a src module that relies on those ambient globals.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: e474c5ddee

ℹ️ 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".

Hydrate speculativeType and gpuMemoryMode into the store, not just the storage
cache. Both are store fields the settings sheet and use-active-model-config
read, so writing only localStorage left a fresh browser showing and applying
auto while the installation had off or manual, until something reread storage.
They join the scalar settings, which removes the storage-only path entirely.

Replay a mirrored edit made before the initial GET lands. The version bump now
happens on the write and the patch is held, then flushed after hydration, so a
toggle flipped during startup is no longer reverted by the arriving server
value and then skipped by the backfill.

Backfill the derived legacy values. A profile predating permission levels holds
only unsloth_chat_confirm_tool_calls, and one predating the three-way RAG
auto-inject control holds "true"/"false"; neither carried, because the backfill
required a raw value under the current key and sent the legacy string as is.
permissionMode now seeds from loadPermissionMode, and the auto-inject codec
runs the same migration loadRagAutoInject does.

Replace ragSource instead of merging it, in both the client patch queue and the
backend deep merge. It is a discriminated union, so switching from a knowledge
base back to the thread source produced {type: "thread", kbId: ...}, which the
payload's thread variant forbids and which the merge would otherwise leave in
the database.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 0a697c3a9c

ℹ️ 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".

A model load that finishes before the initial settings GET calls
saveSpeculativeType and persistGpuMemoryModeOnLoad with whatever the cache
returned. Queuing those as pre-hydration edits bumped their mutation versions,
which blocked a stored ngram or manual value from hydrating, and then replayed
the load's default over the backend. Both now go through
persistLoadDerivedSetting, which writes only the cache until hydration has run.
Every remaining caller of saveString and saveBool is a user action.

hydratePersistedSettings now runs from a root-level mount. Opening Studio
straight at /hub never mounted ChatPage, so the Models page read and wrote
fitOnDeviceOnly, expandQuantizations and showAllQuantizations against a store
that never hydrated: a stored value was not applied, and a toggle only reached
the pre-hydration queue, which the beforeunload flush does not cover.

showCanvasMenuItem joins permissionMode in backfilling a derived legacy value.
A profile predating the visibility flag keeps Canvas shown through an explicit
plus-menu pin, and loadShowCanvasMenuItem reads it, so requiring a raw value
under the new key hid Canvas on every other browser.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 4771162056

ℹ️ 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".

The beforeunload flush covered pendingPatch only, so an edit made while the
initial settings GET was still in flight died with the tab: the next session
hydrated the older server value over the local cache and skipped the backfill,
because the field already existed on the server. drainPreHydrationPatch folds
the held edits onto the outgoing patch first, so the keepalive PUT carries
them. Load-applied writes are unaffected, since persistLoadDerivedSetting never
queues them.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 197ef33702

ℹ️ 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".

The effect that clamps the tool pills to the selected external model writes the
store directly, so it bumps no mutation version. When it ran before a slow
settings GET, hydration then restored the persisted pills over it: Kimi came up
with search on despite the deliberate off default, and a model without a given
builtin could be re-enabled outright.

It now depends on settingsHydrated. Hydration applies the server values and
refreshes the localStorage copies the effect reads, then the effect reruns and
clamps them to the model, so the model-aware result is the one that lands.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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

(nextState as Record<ScalarSettingKey, unknown>)[key] = value;

P2 Badge Reapply the Deep Research model constraint after hydration

When the active checkpoint is a non-Codex external model and the server holds deepResearchEnabled: true, this hydration assignment restores Deep Research after external-model initialization has disabled it. The composer then exposes the active Deep Research pill, but sending enters the research path and fails because chat-adapter.ts accepts only a local model or an openai_codex provider. Fresh evidence after the earlier normalization fix is that the settingsHydrated rerun in chat-page.tsx normalizes reasoning, search, code, image, and fetch state but never clears deepResearchEnabled; clamp this field for the active provider after hydration as well.

ℹ️ 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".

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

On the Deep Research item: not taking it, the premise does not hold at head.

Nothing disables deepResearchEnabled on external-model initialization. The only setDeepResearchEnabled(false) callers are thread.tsx 2074 (research already used on this thread) and chat-adapter.ts 3530 and 3777 (runtime paths). chat-page.tsx has zero references to the field, on this branch and on origin/main.

The flag has also always been restored from localStorage: origin/main line 1593 is deepResearchEnabled: loadBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false) at store construction. So the described state, Deep Research left on, a non-Codex external model selected, the pill rendered by DeepResearchComposerButton whenever enabled is true, is reachable on main today with no hydration involved. Hydration restoring the same value the local cache already restored is not a new defect, and this PR does not widen it.

If the pill should be clamped for non-Codex providers, that is a pre-existing gap worth its own change: thread.tsx already derives researchDisabled from exactly that condition at line 4479, so the fix belongs next to it rather than in the settings mirror.

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 59609879bc

ℹ️ 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 thread studio/backend/storage/studio_db.py Resolved
… repair a corrupt row

setCheckpoint sets deepResearchEnabled false for an external model id
(chat-runtime-store.ts 2301). Restoring the last external checkpoint runs that
clamp during startup, and hydration then landed after it and re-armed the flag
from the server, so the composer showed the pill active and the send failed on
chat-adapter's requirement of a local model or an openai_codex provider. Before
this branch the localStorage value was read at store construction, which is
before setCheckpoint, so the clamp won; hydration is what reordered it.
Hydration now skips a stored true while the active checkpoint is external.

upsert_chat_settings_merge refuses a dict patch aimed at a quarantined key,
because the base it would merge onto is gone. ragSource is an atomic whole-value
replacement, so that guard turned a valid new selection into a 409 and left the
pick unsaved. Atomic keys are exempt; partial patches still conflict.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 6698bf8692

ℹ️ 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".

pre-commit-ci Bot and others added 2 commits August 13, 2026 09:27
The previous clamp keyed on isExternalModelId, which also covers openai_codex.
Codex runs deep research: thread.tsx derives researchDisabled from every
external provider except that one, and chat-adapter accepts its research
requests. Restoring a Codex checkpoint therefore left the store at false while
the cache said true, losing the mirrored preference.

externalCheckpointRefusesDeepResearch resolves the provider behind the
checkpoint and clamps only a known non-Codex one. An unresolved provider is
left alone, since the connection list may not have loaded yet and refusing on
that would drop the preference for the same reason.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 2c83023d24

ℹ️ 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".

A model load captures its settings up front and persists them on success, so
one that started before hydration and finished after it wrote the stale capture
over the preference that had just arrived. saveSpeculativeType and
saveGpuMemoryMode now pass whether the value still matches the live store,
which every path that sets loadSpeculativeType or loadGpuMemoryMode keeps in
step, and a stale write is dropped rather than mirrored.

An explicit write that matched the local cache was recorded nowhere, because
persistSetting compared against storage before deciding to mirror. Before
hydration the cache says nothing about the server, so enabling deep research
turned the tool pills off locally, sent only deepResearchEnabled, and hydration
then restored toolsEnabled: both mutually exclusive modes ended up on. Writes
made before hydration are recorded whether or not they change storage.

resolveVisionOverrides awaits hydration. It reads ragOcrScanned and
ragCaptionFigures for every RAG upload path, and on a fresh browser it returned
undefined before the settings arrived, so the backend ran its default OCR and
caption passes on an ingest that cannot be undone afterwards.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@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: 2b62873cc0

ℹ️ 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".

A local load sets reasoningEnabled from the model's own capability
(use-chat-model-runtime.ts 1404, apply-inference-status-to-store.ts 343), by
writing the store directly, so it bumps no mutation version. A load that
finished before a slow settings GET then had a stored false applied over it,
and the adapter sent a real disabled-thinking request to a model that cannot
honour it. The external normalization effect does not cover this: it returns
for a non-external checkpoint.

Hydration now leaves reasoningEnabled alone while reasoningAlwaysOn is set.
Only a load sets that flag, so the guard cannot fire before a model is known,
which is why it keys on the always-on case rather than on supportsReasoning,
whose default of false says nothing until something has loaded.
@danielhanchen

Copy link
Copy Markdown
Member

Two isolated Studios, merge base b3376300e and head 26d435f0a. Context A flips four switches on Settings > Chat, then a second browser context with an empty localStorage opens the same tab on the same Studio.

before and after

                                  BEFORE   AFTER
fields_matching_context_a         0        3
mirrored_rows_matching_context_a  0        3
mirrored_fields                   []       expandQuantizations, showAllQuantizations, showCanvasMenuItem
payload_field_count               0        3

The fourth switch, Collapse Thinking by default, is the control: it lives in chat-preferences-store, is localStorage only on both sides, and reads back at its default in context B on both halves. So fields_matching_context_a is 3, never 4, and the second browser is not simply inheriting everything for some other reason.

Round-tripping each key on its own, PUT status then read-back:

                             BEFORE                       AFTER
expandQuantizations          400 extra_forbidden          200, survives
showAllQuantizations         400 extra_forbidden          200, survives
showCanvasMenuItem           400 extra_forbidden          200, survives
collapseHtmlArtifacts        200, survives                200, survives
allowArtifactNetworkAccess   200, survives                200, survives

That last pair settles a question that came up in review: collapseHtmlArtifacts and allowArtifactNetworkAccess were said to be in the frontend mirror map but missing from the API payload and the persisted type. They are not missing. They were already on main, so they do not appear in the diff, and they round-trip on both sides. What they are actually absent from is MIRRORED_SETTING_KEYS in the new mirrored-chat-settings.ts, which only feeds hasNoMirroredSettings and assignSanitizedMirroredSettings; the older explicit branch of sanitizeChatSettings handles them instead. mirrored_but_not_persisted is empty on the head. Checking all 26 mirrored fields mechanically against MIRRORED_SETTINGS, PersistedChatSettings, ChatSettingsPayload and the outbound sanitiser: nothing is dropped, the "26 settings" claim is accurate.

One real bug

Late hydration desynchronises speculativeType and gpuMemoryMode from their loaded shadows. Both keys are added to SCALAR_SETTING_KEYS, so getHydratedSettingsState writes them into the store when the GET resolves, writing only the editable field and never the loadedSpeculativeType / loadedGpuMemoryMode shadow. Every other writer sets the pair together and says so.

Repro: on a first-run boot, settings costs two round trips (GET then PUT). Inference status lands first with a resident MTP-speculating model, so speculativeType = loadedSpeculativeType = "mtp". The settings GET then writes speculativeType = "auto" while the shadow stays "mtp". The repair guard in apply-inference-status-to-store.ts:369 is loadedSpeculativeType === null, now false forever, so no later status poll fixes it.

What that costs: use-active-model-config.ts builds the "what is actually running" baseline from the store, and both keys are in loadedConfigSignature, which is the model-config editor's React key, so hydration remounts the editor and discards an in-progress edit. resolveSpeculativeSettingsForLoad then sends the wrong mode on reload. And gpuMemoryEditsPending is literally gpuMemoryMode !== loadedGpuMemoryMode, so hydration synthesises a phantom user edit that the surrounding code then preserves across refreshes.

The store write is not needed: the load path reads these from the localStorage cache, which cacheHydratedSettings already refreshes. Keep both in SCALAR_SETTING_KEYS (removing them makes scalarSettingMutationVersions[field] += 1 produce NaN and permanently break hydration for them) but skip them in the getHydratedSettingsState loop the way permissionMode already is.

Security: no elevation path, and there is a server-side clamp

A client cannot write permissionMode: "full" and have it applied. It is typed Optional[Literal["ask","auto","off"]] on a model with extra="forbid", validated in put_settings before any write, 400 on failure. The client-side setter refuses "full" too. Downgrade is blocked as well: hydration skips permissionMode and confirmToolCalls while the live mode is "full", so it cannot silently drop a sandbox bypass the user accepted a warning for. Auth is a bearer token from localStorage, never a cookie, so CSRF is not a vector.

One design call worth making explicitly rather than by default: PUT /api/chat/settings is guarded only by Depends(get_current_subject), which accepts sk-unsloth-* API keys equally with the UI session. So any issued API key can flip the installation's tool-confirmation policy to "off". Studio is single-subject, so this is capability-scope widening rather than a cross-user leak, but permissionMode: "off" moving from per-browser to per-installation deserves a deliberate yes.

Smaller

beforeunload flush can drop a patch when a PUT is already in flight: inflightFlush = inflightFlush.catch(...).then(() => flushSettingsPatch(true)) chains the keepalive PUT behind a response that will not arrive during unload. Pre-existing machinery, but this PR routes 26 new settings through the same 400 ms debounce, which raises the odds. pagehide would also cover iOS Safari and bfcache, which beforeunload does not.

setCollapseHtmlArtifacts and setAllowArtifactNetworkAccess go through both persistSetting and setScalarSettingVersion, double-bumping the version and queuing the same patch twice. Behaviourally identical thanks to last-write-wins, but the duplicate calls should go.

showCanvasMenuItem now syncs while the plus-menu pin order it is derived from stays local, so the two can disagree across browsers.

Checked and fine

Debounce is a trailing-edge 400 ms coalesce into one pendingPatch, with mergePatch treating ragSource atomically and failures re-queuing with a single toast. The hydration-versus-edit race is handled correctly: mirrorSettingToBackend bumps the version before deciding to hold the patch, and both the hydration and cache paths compare against the snapshot taken at the start, then replay, so the edit wins. Model-capability clamps cannot produce an invalid request, and the absence of a toolsEnabled clamp is safe because the outgoing tool block is gated on capability rather than the toggle. RAG source replacement is atomic on both sides, inside the single BEGIN IMMEDIATE of upsert_chat_settings_merge. No migration is needed: chat_settings is CREATE TABLE IF NOT EXISTS with an upsert, so new settings are new rows and a downgrade leaves them inert. Nothing genuinely per-device is being synced; gpuMemoryMode, speculativeType and fitOnDeviceOnly describe the backend's GPU, so installation scope is right, and LAST_EXTERNAL_CHECKPOINT_KEY is correctly excluded.

Tests

studio/backend  $ python -m pytest tests/test_chat_settings_payload.py -q
18 passed in 5.30s

studio/frontend $ npm test
tests 2026, pass 2026, fail 0        npx tsc -p tsconfig.test.json  exit 0

What I could not check

The hit rate of the hydration race above, as opposed to the code path, which is proven; most likely on a first-run boot. The runtime behaviour of the keepalive flush. And I grepped every mirrored-setter call site and found only user-click handlers, but did not read every useEffect, so I cannot rule out a mount-time effect calling a mirrored setter pre-hydration, which persistSetting would mirror even as a no-op and pin the field permanently.

Solid PR, and the cross-browser behaviour does what it says. The speculativeType / gpuMemoryMode shadow is the one I would fix first.

The migration cases mutate localStorage and reload, which only decides the pill
while the install has never stored a level. Once one is stored, hydration
applies it and rewrites the local copy, so the second reload asserted against
the level the first one seeded and the step failed on Linux, Windows and macOS.

Refuse the hydrating GET for the length of the loop, which is the state the
derivation actually governs, and add the other half of the contract: with a
level stored, a browser holding only the legacy key gets the installation's
level back.

@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: 912f213b66

ℹ️ 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 665 to +666
function saveBool(key: string, value: boolean): void {
if (!canUseStorage()) return;
try {
localStorage.setItem(key, value ? "true" : "false");
} catch {
// ignore
}
persistSetting(key, value ? "true" : "false");

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 Exempt Codex before mirroring the external clamp

Fresh evidence after the earlier hydration-clamp fix is that setCheckpoint still calls saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false) for every external model ID. Because this changed saveBool now mirrors through persistSetting, selecting an openai_codex checkpoint writes deepResearchEnabled: false to the backend and disables the supported Codex preference in every other browser, even though chat-adapter.ts explicitly accepts Codex research requests; restrict that remaining external-model clamp before sending it as an installation-wide setting.

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.

Correct, and this PR is what makes it destructive. Fixed in 876e198.

At the merge base saveBool was a localStorage.setItem, so clamping on every external id cost one browser its preference. At head it goes through persistSetting to mirrorSettingToBackend, so picking a Codex checkpoint now PUTs deepResearchEnabled: false and kills the preference in every browser and remote session, which is the exact failure this PR exists to prevent.

Codex is exempt everywhere else, so the clamp was already inconsistent: thread.tsx:4478 excludes openai_codex from researchDisabled, and chat-adapter.ts:3639 throws only when the provider is not openai_codex.

All three sites now hoist const clampsDeepResearch = externalCheckpointRefusesDeepResearch(modelId), which is the predicate already in this file and resolves the provider's real capability rather than assuming external means incapable.

Mutation-verified: putting isExternalModelId(modelId) back fails selecting a Codex checkpoint keeps deep research.

The cross-browser step runs this block three times against ONE install
(.github/scripts/run-studio-permission-browser.sh wipes auth, not the settings),
so with the level stored per install runs two and three opened on the level run
one left behind and the fresh-profile assertion failed on Linux, Windows and
macOS alike.

Extend the refused hydration back over the opening assertions and clear the
local level first, which together are the state a first-ever browser on a
never-configured install is in.

@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: 9a3f4402d5

ℹ️ 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 (applied) {
cacheHydratedSettings(settings, hydrationVersions);
mirroredSettingsHydrated = true;
backfillMirroredSettings(settings);

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 Backfill only after an authoritative settings read

When the initial GET fails but loadLegacyChatSettings() finds any legacy setting, loadChatSettingsWithLegacyImport() returns that local-only object instead of rejecting. This call then interprets every absent mirrored field as absent on the server and queues all locally cached values for backfill; on a stale browser, the pending patch will overwrite newer settings from another browser once a later write or unload succeeds. Distinguish the GET-fallback result from an authoritative server response and skip mirrored backfill in that case.

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.

Correct. Fixed in 876e198.

loadChatSettingsWithLegacyImport's first catch returns loadLegacyChatSettings() with no server answer at all, and hydration treated it as authoritative: applied = true, then backfillMirroredSettings(settings), which reads a missing field as unset on the server and queues this browser's value for a PUT. Legacy storage carries none of the 26 mirrored keys, so essentially the whole set gets queued, and saveSettingsPatch retries independently of the failed GET. One transient GET failure on a browser with legacy storage therefore backs its stale values over another browser's newer settings.

The function now returns { settings, fromServer } and hydration backfills only when fromServer is true. That flag is false in exactly one branch, the one where the GET did not answer. The other exits keep absence meaningful, including the saveChatSettingsPatch failure where dbSettings was empty but authoritative, so only the one branch changed behaviour.

Mutation-verified two ways: dropping the gate fails hydration backfills only from an authoritative read, and returning fromServer: true from the legacy fallback fails only the legacy-storage fallback is non-authoritative.

danielhanchen pushed a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026
danielhanchen added a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026
@danielhanchen
danielhanchen force-pushed the fix/studio-chat-settings-sync branch from 88b5262 to fd2f075 Compare August 13, 2026 13:36

@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: fd2f075a0a

ℹ️ 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 +1871 to +1872
if (key === "speculativeType" || key === "gpuMemoryMode") {
continue;

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 Apply hydrated load preferences before the next model load

On a fresh browser with a server-side speculativeType: "ngram" or gpuMemoryMode: "manual", this unconditional skip leaves both live store fields at their local defaults even though cacheHydratedSettings updates localStorage. Normal loads capture these values from stateBeforeUnload.speculativeType and stateBeforeUnload.gpuMemoryMode in use-chat-model-runtime.ts, rather than rereading that cache, so the next model is loaded with auto and the successful-load persistence writes auto back over the server preference. Fresh evidence beyond the earlier hydration finding is that this newly added skip reintroduces the desynchronization; only skip hydration while a loaded-model shadow actually owns the field, or make every load path read the hydrated cache.

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.

Right, and it lands against my own commit. Fixed in 876e198.

I skipped both keys unconditionally and justified it by saying the load path reads them from the localStorage cache. That is wrong, and I should have traced it rather than asserted it. use-chat-model-runtime.ts:954 is pendingLoadConfig?.gpuMemoryMode ?? stateBeforeUnload.gpuMemoryMode, and stateBeforeUnload is useChatRuntimeStore.getState(), the store rather than the cache. The one cache read, readPersistedSpeculativeType() at :1158, sits inside if (resetsPerModelSettings), which needs a truthy currentCheckpoint, so on a fresh browser's first load it never runs. For gpuMemoryMode there is no cache read on any load path.

Then the write-back closes the loop: persistGpuMemoryModeOnLoad sees storage manual against the store's auto and PUTs auto, so the server's preference is not just ignored, it is overwritten. My fix traded a desync for a silent revert, which is worse.

The distinction I should have drawn is ownership, not the key name. loadShadowOwnsMirroredSetting(key, state) skips a key only while that key's own loaded* shadow is non-null. With a shadow set the resident model owns the pair and hydration must not split it, which is the case my commit was actually about. With no shadow the store field is what the next load reads and persists back, so the server value has to land there.

Nothing is given up by narrowing it. gpuMemoryEditsPending is already null-guarded in apply-inference-status-to-store.ts:293, and activeModelConfig is null without a checkpoint, so both costs I cited only exist when a shadow is set, which is still skipped. Both keys stay in SCALAR_SETTING_KEYS, so the NaN hazard is untouched.

One residual I will name rather than hide: with a resident non-GGUF model, loadedGpuMemoryMode is null while a checkpoint exists, so hydration can remount the config editor once at boot if the server value differs from the local cache. A non-GGUF model does not own the standing GPU-memory preference, so that is correct ownership, and one remount is a better trade than a permanent silent revert.

Mutation-verified: restoring the unconditional key skip fails hydration defers to the shadow check, not the key name.

studio/frontend $ npm test                                2049 passed, 0 failed
studio/frontend $ npx tsc -p tsconfig.test.json / tsc -b   both exit 0
studio/backend  $ pytest tests/test_chat_settings_payload.py -q   18 passed

@danielhanchen

Copy link
Copy Markdown
Member

Re-shot at the current head fd2f075a0. My earlier pair was taken at 26d435f0a and the branch has moved eight commits since, including the permission-level test change and the shadow fix, so the old picture no longer says anything about what is on the branch now.

Method

BEFORE is the merge base b3376300e, AFTER is head fd2f075a0, each its own install.sh --local build under its own UNSLOTH_STUDIO_HOME, with both chat_settings tables emptied first so each side exercised the write as well as the read. On each side, three Chromium sessions run against that side's Studio one after another:

  • A turns the Search pill on, sets the permission level to "Ask for approval", moves Passages (top K) to 11 and turns "OCR scanned pages" off. Then it closes. All four are driven away from their defaults on purpose: setting ragOcrScanned on, or the level to "Approve for me", writes nothing, and the second browser then shows the right value for the wrong reason.
  • B is a fresh browser holding nothing but the two auth tokens. This is what is photographed.
  • C holds only the legacy unsloth_chat_confirm_tool_calls = "false" key.

The composer, as B renders it:

composer

Run settings -> Retrieval, same browser:

retrieval

Search mode, Auto-retrieve, the 0.70 threshold and "Describe figures & charts" read the same on both halves, which is what says the two sides are comparable.

C, the browser that holds only the legacy key:

legacy

BEFORE derives "Run automatically" from its own key. AFTER shows the installation's "Ask for approval" and rewrites the local cache to ask, which is exactly the contract 912f213b6 added to playwright_chat_ui.py, now with a picture rather than only a test.

Numbers, read from the same servers that were photographed

BEFORE AFTER
GET /api/chat/settings before any edit all four absent all four absent
GET /api/chat/settings after A's edits toolsEnabled, permissionMode, ragTopK, ragOcrScanned all absent true / "ask" / 11 / false (plus confirmToolCalls: true)
B's composer Search off, "Approve for me" Search on, "Ask for approval"
B's Retrieval top K 5, OCR on top K 11, OCR off
C's permission pill "Run automatically" "Ask for approval"
C's unsloth_chat_permission_mode after load null "ask"
B's mirrored localStorage keys at document start all null all null

A's own UI ends at "Ask for approval" / Search on / 11 / OCR off on both sides, so the two sides made the same edit and only the carrying differs. The last row is what keeps this honest: the photographed browser really did boot with no chat settings of its own on both sides.

What I could not photograph

3a899857c bounds the hydration an ingest waits on at 8 seconds. It is not visible against this merge base, because the base does not await hydration in resolveVisionOverrides at all: the unbounded wait was introduced and then bounded inside this branch, so BEFORE and AFTER both drop a file without stalling. Reading it rather than shooting it, the Promise.race takes the local values on timeout, which is the same fallthrough a blocked localStorage already gets.

Otherwise unchanged from my last pass: the cross-browser behaviour does what the description says, and 88b5262b0 is the shadow desync I flagged.

@danielhanchen

Copy link
Copy Markdown
Member

Took this over and pushed a commit. Re-ran the two-install evidence afterwards against the fixed head.

Before and after

Before: chat, RAG, model-load and related preferences lived only in browser localStorage, so a new browser, a private window or a remote session started from defaults.

After, context A flips three mirrored switches on Settings > Chat, then a second browser context with an empty localStorage opens the same tab on the same Studio:

                                  BEFORE   AFTER
fields_matching_context_a         0        3
mirrored_rows_matching_context_a  0        3
payload_field_count               2        5

The control is Collapse Thinking by default, which lives in chat-preferences-store and is localStorage only on both sides. It reads at its default in context B on both halves, so the count is 3 and never 4, and the second browser is not simply inheriting everything for some other reason.

Round-tripping each key on its own, PUT status then read-back:

                             BEFORE                       AFTER
expandQuantizations          400 extra_forbidden          200, survives
showAllQuantizations         400 extra_forbidden          200, survives
showCanvasMenuItem           400 extra_forbidden          200, survives
collapseHtmlArtifacts        200, survives                200, survives
allowArtifactNetworkAccess   200, survives                200, survives

Real issue.

That last pair settles something raised in review: collapseHtmlArtifacts and allowArtifactNetworkAccess were reported as being in the frontend mirror map but missing from the API payload and the persisted type. They are not missing. They were already on main, so they do not appear in the diff, and they round-trip on both sides. What they are absent from is MIRRORED_SETTING_KEYS in the new mirrored-chat-settings.ts, which only feeds hasNoMirroredSettings and assignSanitizedMirroredSettings; the older explicit branch of sanitizeChatSettings handles them. All 26 mirrored fields checked mechanically against MIRRORED_SETTINGS, PersistedChatSettings, ChatSettingsPayload, SCALAR_SETTING_KEYS and the outbound sanitiser: nothing is dropped. The "26 settings" claim is accurate.

What I pushed

Hydration was desyncing speculativeType and gpuMemoryMode from their loaded shadows. Both are in SCALAR_SETTING_KEYS, so getHydratedSettingsState wrote them into the store when the settings GET resolved, writing only the editable field and never the loadedSpeculativeType / loadedGpuMemoryMode shadow. Every other writer sets the pair together.

Repro: first-run boot costs two round trips (GET then PUT). Inference status lands first with a resident MTP-speculating model, so speculativeType = loadedSpeculativeType = "mtp". The settings GET then writes speculativeType = "auto" while the shadow stays "mtp". The repair guard in apply-inference-status-to-store.ts is loadedSpeculativeType === null, now false forever, so no later status poll fixes it.

What that costs: both keys are in loadedConfigSignature, which is the model-config editor's React key, so hydration remounts the editor and discards an in-progress edit. resolveSpeculativeSettingsForLoad then sends the wrong mode on reload. And gpuMemoryEditsPending is literally gpuMemoryMode !== loadedGpuMemoryMode, so hydration synthesises a phantom user edit that the surrounding code preserves across refreshes.

Fix: both keys stay in SCALAR_SETTING_KEYS (removing them makes scalarSettingMutationVersions[field] += 1 produce NaN and permanently break hydration for them) but are skipped in the getHydratedSettingsState loop, the way permissionMode already is. The load path reads them from the localStorage cache, which cacheHydratedSettings refreshes on its own version check, so nothing is lost. That was verified, not assumed.

Also dropped the duplicate setScalarSettingVersion calls in setCollapseHtmlArtifacts and setAllowArtifactNetworkAccess: persistSetting -> mirrorSettingToBackend already bumps the version and queues the patch, so those two were double-bumping and queuing twice. Every other setScalarSettingVersion call site is a non-mirrored key.

Does it break anything, including old installs

The schema is the thing that would hurt, and it does not change. chat_settings is CREATE TABLE IF NOT EXISTS (key TEXT PRIMARY KEY, value_json TEXT, updated_at TEXT) with an upsert, byte-identical between the merge base and the head, so new settings are new rows and no migration exists to go wrong.

I ran the four mixed-version combinations a real install can end up in, each side importing its own checkout in its own interpreter:

1. a database written by the merge base, then read and written by the head
  PASS  base persists its own settings
  PASS  head reads the base's database
  PASS  head adds the new keys as new rows
  PASS  head leaves the pre-existing rows untouched

2. the same database handed back to the merge base, i.e. a downgrade
  PASS  base still opens a database containing keys it does not know
  PASS  base returns the unknown keys rather than dropping them
  PASS  base can still write its own keys afterwards
  PASS  the head's rows survive that write

3. what each side's request validator does with the other side's payload
  PASS  head accepts the new keys
  PASS  base REJECTS the new keys with a 400 rather than silently dropping them
  PASS  head still accepts every key the base accepted
  PASS  head refuses permissionMode full
  PASS  head accepts permissionMode ask / auto / off

4. rows a hand-edit, a half-written flush or an older bug could leave behind
  PASS  head survives a corrupt value_json
  PASS  head can still merge-write past a corrupt row
  PASS  base also survives it

5. schema identity
  PASS  chat_settings schema is unchanged by this PR

0 failing checks

The downgrade row is the one worth knowing: an old backend opens a database full of keys it has never heard of, returns them rather than dropping them, and keeps writing its own. So rolling Studio back does not lose the new settings, and rolling forward again picks them up.

One consequence that is correct but worth naming: a stale cached SPA from a newer Studio talking to an older backend gets a 400 with extra_forbidden per key, not a silent drop. That is the right failure, and chat-settings-api.ts surfaces it rather than swallowing it.

Cross-browser, all three engines, against the real Studio: setting carried into a fresh context in Chromium, Firefox and WebKit alike. WebKit matters twice over, since Tauri uses the platform webview and that is WebKitGTK on Linux and WKWebView on macOS.

Security

A client cannot write permissionMode: "full". It is typed Optional[Literal["ask","auto","off"]] on a model with extra="forbid", validated before any write, 400 on failure, and the client-side setter refuses it too. Downgrade is blocked as well: hydration skips permissionMode and confirmToolCalls while the live mode is "full", so it cannot silently drop a sandbox bypass the user accepted a warning for. Auth is a bearer token from localStorage, never a cookie, so CSRF is not a vector.

Two judgement calls I deliberately did not make for you:

  • PUT /api/chat/settings is guarded only by Depends(get_current_subject), which accepts sk-unsloth-* API keys equally with the UI session. So any issued API key can flip the installation's tool-confirmation policy to "off". Studio is single-subject, so this is capability-scope widening rather than a cross-user leak, but permissionMode: "off" moving from per-browser to per-installation deserves a deliberate yes.
  • The beforeunload flush chains behind an in-flight PUT, so a patch can be lost on unload. Pre-existing machinery, but this PR routes 26 new settings through the same 400 ms debounce, which raises the odds. pagehide would also cover iOS Safari and bfcache.

Tests

studio/backend  $ python -m pytest tests/test_chat_settings_payload.py -q   18 passed
studio/frontend $ npm test                                                  2030 passed, 0 failed
studio/frontend $ npx tsc -p tsconfig.test.json / tsc -b / biome check       all exit 0

The four new tests are source assertions rather than a live hydration run, and that is the weakest part of this work: chat-runtime-store.ts cannot be imported in bare node (ERR_UNSUPPORTED_DIR_IMPORT on a .tsx barrel, which --experimental-strip-types cannot handle at any depth). They are mutation-verified though: reverting the skip, restoring setScalarSettingVersion, and dropping the keys from SCALAR_SETTING_KEYS each fail exactly one test. A real behavioural test needs the store made importable, which is its own change.

Good to merge from my side once CI is green.

The settings queue requeued a failed patch as it stood. /api/chat/settings is
extra="forbid" and refuses the whole body on one bad field, so a patch the server
will never accept came back on every following save and took it down too: after a
single 400 the tab could no longer persist any chat setting, and nothing retries
until the next edit or the tab closes.

Reachable without a bug on either side. A new bundle against a rolled-back
backend has every mirrored field rejected as extra_forbidden, which is exactly
that shape. Measured against a live Studio in Chromium 151, Firefox 153 and
WebKit 26.5: after one rejection every later request still carried the rejected
field and no unrelated edit ever went out clean, in all three.

A failure is now classified before the patch is requeued. 5xx, a network error,
408 and 429 keep the patch. Any other 4xx is the server saying this body is
wrong, so the fields it named in the validation detail are dropped and the rest
of the coalesced patch is kept and rescheduled, which cannot loop because each
round strictly shrinks the patch. An unattributable 4xx drops the patch outright
rather than guessing.

Two smaller ones alongside it, both measured:

A non-finite number reached the database. json.loads accepts bare NaN and
Infinity and pydantic took them for a float, so {"temperature": NaN} was written
into value_json as a bare NaN token. Python reads that back, so the row was never
quarantined, while the response model rendered it as null: the value was silently
lost and the row on disk was not valid JSON for any reader that is not Python.
The settings models refuse non-finite numbers now, the way models/training.py
already does for every numeric training field.

The 400 for one of those was a 500. detail = exc.errors() echoes the offending
input, and Starlette's JSONResponse dumps with allow_nan = False, so a rejected
NaN made the error handler itself unrenderable and the caller got an unhandled
ValueError for a request the validator had correctly refused. This route now uses
safe_validation_errors, which the repo already has for exactly this and which
also bounds a multi-megabyte value being quoted back.

The unload flush also runs on pagehide and on the hidden transition of
visibilitychange. beforeunload is not the end of a page's life on mobile Safari
or a discarded Android tab, and a page restored from the back/forward cache never
unloaded at all. Safe to add rather than replace: the pending patch is swapped out
before the request, so a second call with nothing queued returns immediately.
keepalive is now skipped above 60 KiB, since Fetch caps in-flight keepalive bodies
at 64 KiB and a valid researchWebsitePolicy (2000 domains of 253 characters) is
well past it; over the budget the request fails immediately in all three engines,
where without keepalive it at least has a chance, and on the visibilitychange
flush it simply succeeds.

Tests: 11 new frontend tests over the retry policy and the keepalive budget
(2042 pass), 6 new backend tests over non-finite numbers and the renderable 400
(114 chat backend tests pass), tsc and ruff clean.

@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: 69c9d4d218

ℹ️ 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".


# Discriminated unions, not partial patches: merging a `thread` pick into a stored
# `kb` one keeps `kbId`, which the payload's thread variant forbids.
_ATOMIC_SETTING_KEYS = frozenset({"ragSource"})

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 Let complete website policies repair corrupt rows

When the stored researchWebsitePolicy row contains malformed JSON, saving valid limits from the dialog still fails: the client sends the complete {allowedDomains, blockedDomains} object, but this atomic-key list omits the policy, so the corrupt-partial guard returns 409 after quarantining the row. The settings retry code treats that unattributable 409 as terminal and drops the patch, leaving the user's apparent save absent from the backend until another edit; allow a complete website policy to replace a corrupt row, as is already done for ragSource.

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.

Leaving this one: the prescribed fix costs more than the case it closes.

Adding researchWebsitePolicy to _ATOMIC_SETTING_KEYS silently drops the other domain list on every legitimate partial patch against a healthy row. Measured against the real upsert_chat_settings_merge: with the key made atomic, {"researchWebsitePolicy": {"allowedDomains": ["c.com"]}} over a stored {allowed: [a], blocked: [b]} yields {"allowedDomains": ["c.com"]} with blockedDomains gone, where today it merges to {allowed: [c], blocked: [b]}. model_dump(exclude_unset=True) recurses into the nested model, so a partial nested dict is exactly what the merge receives, and PUT /api/chat/settings is reachable with an sk-unsloth-* key, so partial patches are a real client shape.

ragSource is atomic for a reason that does not transfer: it is a discriminated union, and merging kb into thread would keep a stale kbId. The corrupt-row repair rides along free there. A two-list policy has no such reason.

The 409 also self-heals. _load_chat_settings_for_merge quarantines and deletes the corrupt row, and upsert_chat_settings_merge commits before raising, so an identical second PUT succeeds and stores the full policy. The blast radius is one patch, once, after an external corruption event.

And no writer can produce the precondition. _parse_chat_setting_json only fails on a JSON decode error, every writer goes through json.dumps, and NaN and Infinity round-trip through json.loads, which is why ChatInferenceSettings, ChatPresetLoadConfig and ChatSettingsPayload all carry allow_inf_nan=False. I checked all three and no nested model is missing it. So a corrupt row needs disk corruption or a hand-edited database.

If it is ever worth closing, the right shape is a completeness gate, exempting a corrupt key when the patch supplies every field of that key's model, which preserves partial merges on healthy rows. Not worth it for one lost save after an out-of-band corruption event.

@danielhanchen

Copy link
Copy Markdown
Member

Simulated this one rather than only reading it, since the write path is now a shared resource with a state machine in front of it. Three real defects came out, and I have pushed the fixes to this branch as 69c9d4d21.

Before and after, restated

Before: all 26 settings lived in localStorage, so a second browser, a private window or a remote session started every one of them at its default. After: they round-trip through /api/chat/settings. That part is sound and I have the two-install pair above showing it. Nothing below changes that verdict; it is about what happens off the happy path.

What I fixed

1. One rejected patch stopped every later save, for the life of the tab.

flushSettingsPatch requeued a failed patch as it stood. The endpoint is extra="forbid" and refuses the whole body on one bad field, so a patch the server will never accept came back on every subsequent save and took it down too. Nothing retries on its own, so the queue stayed poisoned until a reload.

Reachable with no bug on either side: a new bundle against a rolled-back backend has every mirrored field rejected as extra_forbidden, which is exactly that shape. I confirmed that direction separately by replaying a head-shaped patch against the merge base, which refuses toolsEnabled, permissionMode and ragTopK and takes the rest of the body down with them.

Measured against a live Studio, rejecting one field forever and then making an unrelated valid edit:

Chromium 151 Firefox 153 WebKit 26.5
before, every later request still carried the rejected field yes yes yes
before, any unrelated edit ever went out clean no no no
after no no no
after, unrelated edit goes out clean yes yes yes

A failure is now classified before the patch is requeued. 5xx, network errors, 408 and 429 keep the patch. Any other 4xx drops the fields the validation detail names, keeps the rest of the coalesced patch and reschedules it, which cannot loop because each round strictly shrinks the patch. An unattributable 4xx drops the patch rather than guessing.

2. A non-finite number reached the database, and its rejection was a 500.

json.loads accepts bare NaN and Infinity and pydantic took them for a float, so {"inferenceParams": {"temperature": NaN}} returned 200 and wrote a bare NaN token into value_json. Python reads that back, so the row was never quarantined, while the response model rendered it as null: the value was silently lost and the row on disk was not valid JSON for any reader that is not Python.

The bounded fields did refuse it, and that was the worse half. detail = exc.errors() echoes the offending input, and Starlette's JSONResponse dumps with allow_nan = False, so {"ragAutoInjectMinScore": NaN}, {"ragTopK": Infinity} and {"ragTopK": 1e400} each made the 400 handler itself unrenderable and answered 500 with an unhandled ValueError, for requests the validator had already correctly refused.

Not reachable from a browser, since JSON.stringify emits null for both, but every other client can send it, including an sk-unsloth-* key. The settings models now refuse non-finite numbers the way models/training.py already does, and the route uses safe_validation_errors, which this repo already has for exactly this failure and which also bounds a multi-megabyte value being quoted back.

3. The unload flush only ran on beforeunload.

That is not the end of a page's life on mobile Safari or a discarded Android tab, and a page restored from the back/forward cache never unloaded at all. It now also runs on pagehide and on the hidden transition of visibilitychange. Additive, not a replacement: the pending patch is swapped out before the request, so a second call with nothing queued returns immediately.

Separately, keepalive is now skipped above 60 KiB. Fetch caps in-flight keepalive bodies at 64 KiB and a valid researchWebsitePolicy is 2000 domains of 253 characters, so it can be an order of magnitude over. Over the budget the request fails immediately in all three engines (Failed to fetch, NetworkError, Load failed); without keepalive it at least has a chance, and on the visibilitychange flush it simply succeeds.

For the record, where beforeunload does fire, the existing keepalive path already worked: closing a tab 50 ms after a pill click landed the edit on all three engines.

What I checked and found correct

  • The contract, both sides of every bound. 80 simulations per interpreter over the real router and real SQLite, on Python 3.10, 3.11, 3.12 and 3.13 and against SQLite 3.45.1 and 3.50.4. ragTopK 0/1/50/51 and fractional, ragAutoInjectMinScore -0.1/0/1/1.1, domains at 253 and 254 characters and lists at 1000 and 1001, kbId at 0/1/256/257, permissionMode: "full", unknown fields at the top level and nested inside ragSource, a rejected patch leaving stored values untouched, a 1 MB policy, and 253 astral-plane characters (Python counts code points and JS counts UTF-16 units, so the client is the stricter of the two, which is the safe direction).
  • Merge semantics. ragSource replaced atomically, inferenceParams still deep-merged, each research-policy list replaced wholesale.
  • Corrupt rows. Quarantined once per write with json_decode_error, a scalar patch repairs the row, an atomic key repairs it, a partial patch onto a corrupt dict still 409s. Worth knowing: list_chat_settings does not quarantine on the read path, so a corrupt row reaches the client as null, which the sanitiser drops.
  • Concurrency. 16 disjoint writers all survive, same-leaf writers are last-writer-wins rather than corruption, and a writer held past the 5 s busy timeout raises a locked error rather than hanging.
  • Old installs. A studio.db written by the merge base in a separate interpreter, then opened by this branch: nothing lost, nothing rewritten, and the new keys land alongside. chat_settings is key/value, so there is genuinely no migration to get wrong, and this is what says so rather than the absence of an ALTER TABLE.
  • Both skew directions. An old bundle's payload is still accepted by this backend. A database this branch has written still opens on the merge base, which reads it, preserves what it does not know, and writes its own keys.
  • Device safety, which is the whole hardware question here. No line of the diff branches on OS or device: no sys.platform, no os.name, no CUDA/ROCm/MPS, no path building. The only device-adjacent settings that became installation-wide are speculativeType and gpuMemoryMode, and both are restricted to machine-independent values on both sides. mtp, mtp+ngram, dspark and dflash are all refused, per-GPU numbers (gpuLayers, nCpuMoe, tensorParallel) are not in the payload at all, and a drift guard now checks the client's list against the payload's Literal so a hardware-specific mode cannot start syncing by accident. That is what makes an NVIDIA box unable to push an unloadable configuration at an AMD or CPU-only one.
  • A wedged endpoint. With the settings GET answering 503, the composer is up in 0.7 to 1.0 seconds on all three engines and falls back to defaults.

Limits of what I ran, stated plainly

  • Linux only, on this box. macOS and Windows are argued from the diff being OS-agnostic plus the existing per-OS smoke workflows, not measured here. Same for AMD and CPU-only hardware: the argument is the enum contract above, not a run on that hardware.
  • Chromium stands in for Chrome and Edge. WebKit is Playwright's build, not branded Safari, so it is the right engine for DOM and storage semantics and the wrong one for Apple's keepalive and ITP policies. The mobile-Safari case behind fix 3 is spec-derived, not measured. Firefox here is 153; the keepalive gap is in Firefox below 133, which I could not test.
  • Studio does not boot at all when localStorage throws (site data blocked, or a hardened private mode): an unhandled SecurityError during boot and the composer never renders. I measured the same failure on the merge base, so it is pre-existing and app-wide rather than anything this PR did, and I have left it alone here. Worth its own issue.
  • PUT /api/chat/settings is still guarded only by Depends(get_current_subject), which accepts an API key equally with a UI session, so any issued key can move the installation's tool-confirmation policy. "full" stays rejected. Unchanged by this PR, and still a deliberate yes worth making explicitly.
  • Backfill is still not compare-and-set and two tabs still do not converge without a reload. Both are known and both are defensible.

Suites, at 69c9d4d21

2042 frontend tests (11 new), 114 backend chat tests (6 new), 80 simulations on each of four Python versions, tsc -b and tsc -p tsconfig.test.json clean, ruff clean, and biome unchanged from the pre-change baseline on every file I touched.

danielhanchen added a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Simulated this one hard before signing off, since it changes a path every browser touches. Three commits are now on the branch: one code fix and two test fixes. Details below.

What changes for a user

Before: the 26 toggles lived only in localStorage, so a second browser, a private window or a remote session opened at defaults, and the composer pills, permission level, RAG knobs and model-list filters had to be set again per browser. After: they round-trip through /api/chat/settings, so they describe the installation. That is a real gap, not a cosmetic one, and the before/after pair I posted earlier shows it directly.

Things I fixed on the branch

1. Unsloth UI CI and Windows Unsloth UI CI were red on this branch, on all three platforms. tests/studio/playwright_chat_ui.py drives the permission migration by mutating localStorage and reloading, which only decides the pill while the install has never stored a level. Once one is stored, hydration applies it and rewrites the local copy, so the second reload asserted against the level the first one had seeded. Reproduced locally, and the request log makes the mechanism unambiguous: the first reload's backfill PUTs {"confirmToolCalls": true, "permissionMode": "ask"}, and every later reload comes back ask no matter what the legacy key says.

The block also runs three times against ONE install in the cross-browser step, since .github/scripts/run-studio-permission-browser.sh wipes auth but not the settings, so runs two and three opened on the level run one left behind and the fresh-profile assertion failed as well.

Fixed by refusing the hydrating GET for the stretch that reads the level, which is the state a first-ever browser on a never-configured install is in, and adding the other half of the contract: with a level stored, a browser holding only the legacy key gets the installation's level back. Verified locally at chromium, firefox and webkit in sequence against one install, with the stored level going into runs two and three as off, plus a full non-permission-only run of the script. Windows and macOS both green on a staging replica afterwards.

2. resolveVisionOverrides now awaits hydration before every upload, and that await had no deadline. authFetch sets no AbortSignal, so a wedged or unreachable server leaves the promise pending as long as the socket does, and an upload that used to read these overrides synchronously would sit there with nothing on screen. Measured both ways against a stubbed store: unbounded on the branch as pushed (still pending at 12s), bounded at 8s with the fix, and the healthy path unaffected at sub-millisecond. Raced against an 8s wait, matching awaitFirstSave in chat-adapter, falling through to the local values the way a blocked localStorage already does.

What the simulations covered, and what held

Backend, in a uv venv holding only fastapi, pydantic, structlog and pyjwt (no torch, no Studio install), run identically against the merge base and the head, on Python 3.10, 3.11, 3.12 and 3.13 with identical results:

  • every merge-base field still accepted and round-tripping unchanged, so an old frontend keeps working
  • a key no version of the payload declares survives a later write, so a row from another build is not dropped
  • inferenceParams still deep-merges while ragSource replaces, and a valid ragSource repairs a quarantined row while a partial patch onto one still 409s
  • 8 concurrent writers x 25 writes: no errors, no lost update, every writer's nested key present
  • 36 bounds and literal cases: permissionMode: "full" refused, top K 0 and 51 refused with 1 and 50 accepted, min score outside 0..1 and NaN refused, a 254-char domain and a 1001-entry list refused, a kb source with no kbId refused, a thread source carrying a kbId refused
  • the rollback direction: a db written by the head build, read by the merge-base build, loads all 34 keys, keeps writing, and preserves all 24 keys it does not know

Browsers, one real Studio driven by Chromium (Chrome and Edge share it), Firefox and WebKit (Safari), 63 assertions with 60 passing and the 3 failures being one pre-existing case described below:

  • the carryover itself, per engine, plus /hub hydrating without Chat ever mounting
  • /login never calls /api/chat/settings, so an unauthenticated route does not 401-loop
  • a full localStorage quota: the toggle still reaches the server
  • the server refusing every PUT: UI stays usable, the value stays applied, nothing wrong is written
  • hydration 500ing: a later edit still persists. Hydration hanging: the chat UI is not blocked
  • an edit made during a slow hydration wins, checked with three distinct values (local default 5, stored 13, typed 6) so it cannot pass by coincidence
  • 30 toggles inside the debounce window: one PUT, no rejects, the server agrees with the pill
  • two tabs of one browser each landing their own setting
  • an edit made 80ms before the tab closes still lands, with beforeunload actually run
  • a browser holding permissionMode: "full" locally never sends it
  • an existing install seeding the server from its own cache, the legacy RAG boolean migrating exactly as the old build did (false to off, anything else to auto), and the legacy confirm toggle deriving the level

Also checked: settings rows holding explicit nulls, which the payload accepts and hydration does not treat as absent, load without a crash. speculativeType and gpuMemoryMode were already persisted locally before this branch, and the manual placement knobs (gpuLayers, nCpuMoe, splitRatio, selectedGpuIds) are not mirrored, so a second browser inheriting manual inherits a mode and not another machine's placement. There is no platform-specific code in the diff and no hardware path in it.

Pre-existing, not from this branch

  • With localStorage denied outright, Studio does not mount at all, because the JWT lives there. Identical on the merge base in all three engines.
  • Firefox only shipped fetch keepalive in 133 and mobile Safari often does not fire beforeunload, so the unload flush is best-effort there. That mechanism predates this branch; it just carries more settings now. A pagehide listener alongside would close it if you want it.
  • setCheckpoint still clears deepResearchEnabled for every external model id including openai_codex, while hydration now exempts Codex. Same line is on the merge base, so it is a pre-existing disagreement rather than a regression here.
  • Two frontend unit tests around HF token hydration fail on upstream main by themselves, and Backend CI fails on the staging replica for a missing unsloth_zoo in its environment. Neither is related to this branch.

Suites

Backend test_chat_settings_payload.py 18 passed, test_chat_history_routes.py plus test_chat_history_storage.py 74 passed. Frontend mirrored-chat-settings.test.ts 8/8 and the full suite 2026/2026 with npm run typecheck clean, before and after the fix. Staging replica after the fixes: Frontend CI, Windows Unsloth UI CI, Mac Studio UI + API + Update CI, Windows and Mac GGUF and API CI, Tauri, Startup profile all green; the Linux UI job keeps getting cancelled by that repo's capacity sweeper, so I ran the same script locally instead and it passes end to end.

@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: 876e1981d5

ℹ️ 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".

const provider = useExternalProvidersStore
.getState()
.providers.find((candidate) => candidate.id === parsed.providerId);
return provider != null && provider.providerType !== "openai_codex";

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 Re-clamp Deep Research after providers hydrate

When the settings GET finishes before credential bootstrap populates useExternalProvidersStore, this helper returns false for a restored non-Codex external checkpoint, so deepResearchEnabled: true is applied. The provider-driven effect in chat-page.tsx reruns when the provider list arrives but only normalizes reasoning and tool fields, leaving Deep Research armed; sending then reaches the adapter's unsupported-external-model error. Fresh evidence beyond the earlier hydration-clamp report is that the new unresolved-provider exemption has no corresponding provider-arrival clamp, so defer this decision or reapply it once the provider is known.

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.

Each observation is right and the chain still does not close, so I am leaving it.

Confirmed at head: externalCheckpointRefusesDeepResearch returns false for an unresolved provider so hydration applies deepResearchEnabled: true; the provider-arrival effect in chat-page.tsx re-normalises the reasoning, tools and search pills and does not touch deep research; and an armed pill on a non-Codex external model throws at send.

The premise is what fails. useExternalProvidersStore is created with providers: loadExternalProviders(), a synchronous localStorage read that zustand runs inline in createStore, with getState a plain closure read and no React involvement, and isCompleteProvider needs only id, name and providerType, so it does not wait on server-side key presence. Meanwhile params.checkpoint can only be external at hydration through loadLastExternalCheckpoint(), the same localStorage, and checkpoint is deliberately not in PERSISTED_INFERENCE_PARAM_KEYS, so the settings GET can never introduce an external checkpoint. At hydration either the provider resolves and the clamp fires, or the checkpoint is not external and the clamp is irrelevant.

The one asynchronous writer, runCredentialBootstrap into setProviders, replaces an already-seeded list rather than filling an empty one, and CredentialBootstrapGate holds all chat content until it resolves. If the backend list omits a provider the browser had, the provider never arrives at all, so there is no arrival to clamp on and the checkpoint is dead regardless.

The one path I could construct is a legacy-shaped localStorage entry dropped by fromUnknownProvider while an old lastExternalCheckpoint survives, with the backend sync re-adding the provider after bootstrap. That is a one-time upgrade artifact, and the outcome is a refused send with an explicit message and a one-click pill toggle: nothing wrong is sent and nothing wrong is persisted.

One thing you are right to key on: the exemption's own comment says "the connection list may not have loaded", which reads as if the lag were real. It is not, the list is seeded synchronously, and the exemption is really about a provider that is gone rather than one that is late. I will tighten that wording.

studio/frontend $ npm test                                       2049 passed, 0 failed
studio/backend  $ pytest tests/test_chat_settings_payload.py -q  28 passed

@danielhanchen

Copy link
Copy Markdown
Member

CI has stopped reporting on this PR: it is CONFLICTING against main, so GitHub cannot build the merge commit and every workflow except pre-commit.ci has dropped off (pre-commit.ci shows "error during mergeable check" rather than a real failure).

Where it came from, since three commits landed close together:

head merges with origin/main
fd2f075a0 clean
69c9d4d21 (mine) clean
876e1981d 1 conflict

So it is 876e1981d against #8665 (0e158a8b7, "run the local tool loop against every capable external provider"), which landed on main this morning and rewrote the same three places in setCheckpoint. Both sides implement the same intent, which is why it conflicts rather than merges.

One thing worth deciding rather than resolving by hand, because taking main's side verbatim would undo 2c83023d2:

main's externalModelSupportsStudioTools returns false when the connection cannot be resolved (if (!provider) return false;), so isExternalModelId(modelId) && !externalModelSupportsStudioTools(modelId) clamps while the provider store is still empty. This branch's externalCheckpointRefusesDeepResearch deliberately does the opposite: provider != null && provider.providerType !== "openai_codex", so an unresolved provider is left alone. That distinction matters more on this branch than it did on main, because saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false) now reaches the backend, so a clamp fired during a startup race writes the preference off for every browser on the installation rather than for one tab.

The combination that keeps both properties is main's capability question with this branch's unresolved guard: clamp only when the provider resolves and is known not to run Studio's tool loop. providerModelSupportsStudioTools already returns boolean | null, so the tri-state is there; it is externalModelSupportsStudioTools collapsing null to false that conflates "cannot" with "not loaded yet". Whichever way it goes, getHydratedSettingsState needs the same predicate as setCheckpoint, otherwise the hydration path and the model-switch path disagree again.

I have left the merge alone: it is a behaviour call on your change, not a mechanical resolution, and my commit is not involved in it.

My own verification of 69c9d4d21 did not depend on this PR's CI. It ran locally against real builds: 2042 frontend tests, 114 backend chat tests, 80 endpoint simulations on each of Python 3.10, 3.11, 3.12 and 3.13, and the three-engine browser matrix against a fresh install.sh --local build of the branch with the fix applied.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@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: 876e1981d5

ℹ️ 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 added a commit to mahiatlinux/unsloth that referenced this pull request Aug 13, 2026

@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: a1deadee0b

ℹ️ 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".

const provider = useExternalProvidersStore
.getState()
.providers.find((candidate) => candidate.id === parsed.providerId);
return provider != null && provider.providerType !== "openai_codex";

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 Restore research for every tool-capable provider

When deepResearchEnabled: true hydrates while the active checkpoint uses a capable non-Codex provider, this condition treats the provider as unsupported and skips restoring the live setting. Fresh evidence beyond the earlier rejected provider-arrival report is that the merge parent generalized Deep Research: chat-adapter.ts lines 3641-3651 now accepts any provider for which providerModelSupportsStudioTools(...) is true, and setCheckpoint lines 2390-2393 uses the corresponding capability helper. A remote or stale browser therefore keeps the pill disabled for supported self-hosted/OpenAI-compatible connections even though hydration caches true; use the Studio-tools capability here instead of the old Codex-only test.

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.

Correct, and it is against this PR's own commit rather than anything upstream. I have the fix ready but cannot push it, see below.

externalCheckpointRefusesDeepResearch gates on the provider type where every other site gates on the capability:

chat-runtime-store.ts:1877   provider != null && provider.providerType !== "openai_codex"
chat-runtime-store.ts:2390   isExternalModelId(modelId) && !externalModelSupportsStudioTools(modelId)
thread.tsx:4662              providerModelSupportsStudioTools(...) !== true
chat-adapter.ts:3641         providerModelSupportsStudioTools(...) !== true

So hydration refuses deep research for every external provider except Codex, while the composer and the adapter allow it for anything with the Studio-tools capability. providers.py declares studio_tools: True for openai, gemini, deepseek, mistral, openrouter, vllm, custom, ollama and llama_cpp, so the pill is enabled, the user turns it on, the PUT stores deepResearchEnabled: true, and the next load drops it and falls back to loadBool(..., false). Silent revert of a legitimately stored setting, and in a second browser, which is what this PR exists for.

The fix keeps the provider != null gate rather than reusing the write site's expression verbatim, because externalModelSupportsStudioTools returns false for an unresolved provider and that would reintroduce the connection-list-not-loaded drop the helper's comment guards against. !== true is safe here because syncExternalProvidersFromBackend writes the capabilities for every registry row before it returns the provider rows that populate the store, so a resolved provider always has its capability resident.

-  return provider != null && provider.providerType !== "openai_codex";
+  return (
+    provider != null &&
+    providerModelSupportsStudioTools(provider.providerType, parsed.modelId) !==
+      true
+  );

Mutation-verified: reverting that hunk with the tests untouched fails a tool-capable non-Codex connection keeps the stored research setting with false !== true.

studio/frontend $ npm test                                       2310 passed, 0 failed
studio/frontend $ npx tsc -p tsconfig.test.json / tsc -b          both exit 0
studio/backend  $ pytest tests/test_chat_settings_payload.py -q   28 passed

The new test is behavioural rather than a source assertion: it drives hydratePersistedSettings for real. That needed a @/features/model-picker stub in store-stub-resolver.mjs, since the store could not previously be imported in a bare node test at all. Re-exporting the real apply-per-model-config.ts does not work, it imports the @/features/chat barrel and cycles back into chat-page.tsx, so the stub is minimal fakes. The second case, a provider with studio_tools: false still refusing, uses autoTitle as a control so it cannot pass vacuously.

One test had to change rather than be added: mirrored-settings-write-authority.test.ts pinned the literal providerType !== "openai_codex" string, so it was encoding the bug. It now pins the capability call.

I cannot push this. maintainer_can_modify is now false on this PR, though it is still true on the other eight in this batch, so my push was rejected with permission denied. The commit is ready on my side. Either re-enable "Allow edits from maintainers" and I will push it, or apply the diff above and I will re-run the checks against your head.

@mahiatlinux
mahiatlinux force-pushed the fix/studio-chat-settings-sync branch from 8d88c45 to 8ce3473 Compare August 13, 2026 22:17
@danielhanchen
danielhanchen merged commit c38daa3 into unslothai:main Aug 14, 2026
43 of 53 checks passed
@mahiatlinux
mahiatlinux deleted the fix/studio-chat-settings-sync branch September 25, 2026 05:33
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