Repository navigation
studio: carry chat settings across browsers and remote sessions - #8656
Conversation
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.
|
@codex review |
There was a problem hiding this comment.
💡 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.
|
@codex review |
There was a problem hiding this comment.
💡 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.
|
@codex review |
There was a problem hiding this comment.
💡 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.
|
@codex review |
There was a problem hiding this comment.
💡 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.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
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".
|
On the Deep Research item: not taking it, the premise does not hold at head. Nothing disables The flag has also always been restored from localStorage: origin/main line 1593 is If the pill should be clamped for non-Codex providers, that is a pre-existing gap worth its own change: thread.tsx already derives |
|
@codex review |
There was a problem hiding this comment.
💡 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".
… 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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
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.
|
@codex review |
There was a problem hiding this comment.
💡 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.
|
@codex review |
There was a problem hiding this comment.
💡 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.
|
Two isolated Studios, merge base The fourth switch, Collapse Thinking by default, is the control: it lives in Round-tripping each key on its own, PUT status then read-back: That last pair settles a question that came up in review: One real bugLate hydration desynchronises 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 What that costs: The store write is not needed: the load path reads these from the localStorage cache, which Security: no elevation path, and there is a server-side clampA client cannot write One design call worth making explicitly rather than by default: Smaller
Checked and fineDebounce is a trailing-edge 400 ms coalesce into one TestsWhat I could not checkThe 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 Solid PR, and the cross-browser behaviour does what it says. The |
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.
There was a problem hiding this comment.
💡 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".
| function saveBool(key: string, value: boolean): void { | ||
| if (!canUseStorage()) return; | ||
| try { | ||
| localStorage.setItem(key, value ? "true" : "false"); | ||
| } catch { | ||
| // ignore | ||
| } | ||
| persistSetting(key, value ? "true" : "false"); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
88b5262 to
fd2f075
Compare
There was a problem hiding this comment.
💡 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".
| if (key === "speculativeType" || key === "gpuMemoryMode") { | ||
| continue; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
Re-shot at the current head MethodBEFORE is the merge base
The composer, as B renders it: Run settings -> Retrieval, same browser: 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: BEFORE derives "Run automatically" from its own key. AFTER shows the installation's "Ask for approval" and rewrites the local cache to Numbers, read from the same servers that were photographed
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
Otherwise unchanged from my last pass: the cross-browser behaviour does what the description says, and |
|
Took this over and pushed a commit. Re-ran the two-install evidence afterwards against the fixed head. Before and afterBefore: 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: The control is Collapse Thinking by default, which lives in Round-tripping each key on its own, PUT status then read-back: Real issue. That last pair settles something raised in review: What I pushedHydration was desyncing Repro: first-run boot costs two round trips (GET then PUT). Inference status lands first with a resident MTP-speculating model, so What that costs: both keys are in Fix: both keys stay in Also dropped the duplicate Does it break anything, including old installsThe schema is the thing that would hurt, and it does not change. I ran the four mixed-version combinations a real install can end up in, each side importing its own checkout in its own interpreter: 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 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. SecurityA client cannot write Two judgement calls I deliberately did not make for you:
TestsThe four new tests are source assertions rather than a live hydration run, and that is the weakest part of this work: 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.
There was a problem hiding this comment.
💡 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"}) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
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 Before and after, restatedBefore: all 26 settings lived in What I fixed1. One rejected patch stopped every later save, for the life of the tab.
Reachable with no bug on either side: a new bundle against a rolled-back backend has every mirrored field rejected as Measured against a live Studio, rejecting one field forever and then making an unrelated valid edit:
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.
The bounded fields did refuse it, and that was the worse half. Not reachable from a browser, since 3. The unload flush only ran on 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 Separately, For the record, where What I checked and found correct
Limits of what I ran, stated plainly
Suites, at
|
|
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 userBefore: the 26 toggles lived only in Things I fixed on the branch1. The block also runs three times against ONE install in the cross-browser step, since 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 2. What the simulations covered, and what heldBackend, 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:
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:
Also checked: settings rows holding explicit nulls, which the payload accepts and hydration does not treat as absent, load without a crash. Pre-existing, not from this branch
SuitesBackend |
There was a problem hiding this comment.
💡 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"; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
CI has stopped reporting on this PR: it is Where it came from, since three commits landed close together:
So it is One thing worth deciding rather than resolving by hand, because taking main's side verbatim would undo main's 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. 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 |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 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"; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
8d88c45 to
8ce3473
Compare




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:These describe the installation, not the browser holding them, so they now round-trip through
/api/chat/settingsalongside 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,saveResearchWebsitePolicyandsavePermissionModeroute through onepersistSetting, which mirrors a changed value to the backend.localStoragestays the synchronous boot cache:resolveToolsEnabledOnLoad,loadPermissionMode, the model-load path's speculative type and GPU memory mode) see the installation's valuesFull access stays session-only. The backend rejects
permissionMode: "full",savePermissionModenever writes it, and hydration leaves bothpermissionModeandconfirmToolCallsalone while it is active, so a stored level cannot drop a sandbox bypass the user accepted a warning for.ChatSettingsPayloadisextra="forbid"and a single out-of-contract field 400s the whole save, somirrored-chat-settings.tsre-validates every value against the same literals and ranges before it is sent. The bounds match the backend:ragTopK1..50 as/api/ragenforces,ragAutoInjectMinScore0..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 ofpermissionMode: "full", an out-of-range top K, akbsource with nokbId, 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.npm run typecheckclean,ruff checkclean,biome checkunchanged from the pre-change baseline on the touched files.tsconfig.test.jsonnow includessrc/speech-recognition.d.ts; the new test reaches asrcmodule that relies on those ambient globals.