Repository navigation
studio: keep each chat's sampling params and system prompt with the chat - #9055
Conversation
The composer pills, permission level and retrieval controls already travel with the thread. The sampling params and the system prompt did not, so returning to a chat started under one prompt showed whichever prompt the last chat had, and every chat shared one set of sliders. Those eight join the snapshot: temperature, top P, top K, min P, the two penalties, the system prompt and its variables. They are the only thread-scoped settings that live under params rather than as store fields of their own, so the read and apply paths route them through there and the whole snapshot is still one object on the thread row. An edit made with a chat open lands on that chat; with no chat open it moves the installation defaults, as before. A model's own recommendation is not an edit: both paths that apply one now say so, or loading a model while a chat was open would pin that chat to the model's sampling. Context and checkpoint stay out. They describe the model that loaded rather than the conversation, and a chat restoring a budget the current model cannot hold is the failure that exclusion exists to prevent.
Three follow-ups from review on the per-chat sampling change. A model's recommendation still landed in the live params: fromModelDefaults only moved where the value was persisted. A chat with stored sampling ran the model's instead, and the next unrelated edit snapshotted that over what the chat had. setParams now puts back the keys the chat holds; one it never set still follows the model. The Qwen mode table is the model's recommendation, not a value the user picked, so both paths that apply it are marked. Loading the model and toggling Think reach the same table, so marking one and not the other pinned the chat by the other route. The held-edit flush read the sampling keys as store fields. They sit under params, so it read undefined, the sanitizer dropped them, and an edit made while the chat's snapshot was in flight was lost when the user navigated away.
|
Pushed 212914e for all three review comments. Each one was right, and each was verified against the source before changing anything rather than taken on trust. What the three had in common The eight keys this PR adds are the only thread-scoped settings without a store field of their own, so every generic path that walks the key list has to be told to look under Fixes
I also swept the other four Verification
Standing caveat unchanged: none of this has been checked in a browser, so the user-visible behaviour is verified by test and by reading only. |
Restoring the chat's values before the diff made every pinned key equal on both sides, so it dropped out of changedParams and never reached the installation defaults. One chat pinning temperature left every later new chat on whatever model loaded before it. The restore is a live-store concern only. Persistence diffs the model's own object again, as it did before the restore existed, so the recommendation reaches the defaults while the open chat keeps what it stored. getChangedInferenceParams bumps the mutation versions, so it stays a single call rather than one diff per purpose.
|
Pushed a4f9fef. The comment was right, and it caught a regression I introduced in 212914e rather than anything from the original change. Restoring the chat's sampling before the diff made every pinned key equal on both sides, so it dropped out of The separation was the missing piece: Also recorded in the code: Verification
Still not verified in a browser, so the user-visible behaviour rests on the tests and on reading. |
…apshot Per-model memory (#8757) landed in setParams, so the two layers are composed rather than stacked: the replay lays a model's remembered settings over its defaults, and the open chat goes on top of that. A chat is more specific than either. A captured sampling edit now stays out of the per-model memory as well as the installation defaults, since both are shared with every other chat, and remembering one chat's temperature against the model leaked it to every new chat opened on that model. Main independently marked the load-time Qwen block and the status poll as model defaults, so those edits are dropped in favour of main's, which also carry maxTokensCap. Toggling Think applies its mode params again. A pinned chat stores every sampling key, so marking the toggle as a model default meant the restore put all of them back and the mode changed while temperature and top-p stayed on the previous mode's values. The user asked for the mode in that chat, so the values land and belong to the chat after. The load-time path applies the same table unasked and stays marked. The in-memory copy of the installation defaults follows what a model default write just persisted. applyThreadScopedSettings falls back to it for a chat with no snapshot, so leaving it stale meant a chat opened after a model load ran the sampling of whichever model was loaded before it, until a reload. top-k accepts -1, which disables it. ChatCompletionRequest allows -1 to 100 and default.yaml falls back to -1, so the old floor of 0 dropped a value whole model families run with and the chat could not keep it.
|
Pushed 0a91537. All three comments were right. One of them caught a mistake I made last round rather than anything in the original change, and I have said so on the thread. Rebased on main first. #8756 and #8757 both merged, and #8757 rewrote
That surfaced something the reviews did not raise. A sampling edit captured to a chat was still being remembered against the model, so opening a new chat on that model inherited it. Per-model memory is shared with every other chat exactly as the installation defaults are, so a captured edit now stays out of both. Main had also marked the load-time Qwen block and the status poll as model defaults on its own, with The three fixes
Verification
Unchanged caveat: no browser verification has been possible in this session, so the user-visible behaviour rests on the tests and on reading. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0a91537b9d
ℹ️ 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 effective = replayed | ||
| ? restoreThreadScopedParams(nextParams) | ||
| : nextParams; |
There was a problem hiding this comment.
Restore chat overrides in every checkpoint replay
Fresh evidence after the earlier hydration fix is that setCheckpoint has a separate replay path: when an active chat switches to a model with remembered parameters, the call to getReplayedParams around line 3891 is committed directly as nextParams without passing through restoreThreadScopedParams. This is especially visible for external-model switches that have no subsequent local-model hydration call: the active chat immediately inherits that model's remembered system prompt and sampling values instead of retaining its thread snapshot. Apply the thread override to this replay path as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 32f6c8a.
Confirmed by reading the path: baseParams comes back from getReplayedParams, nextParams spreads it with the new checkpoint and clamped maxTokens, and that object is committed as params without the restore. Your point about external switches is the sharp end of it. A local switch is followed by a load that calls setParams with fromModelDefaults, which restores; an external one has no such call, so the chat keeps the model's prompt and sampling indefinitely.
The restore now runs on that path, gated on checkpointChanged to match the replay it is undoing:
const restoredParams = checkpointChanged
? restoreThreadScopedParams(nextParams)
: nextParams;getReplayStatePatch is deliberately still passed the unrestored nextParams, so persistReplayedParams writes the model's own values to the installation defaults. That is the same split as setParams: the chat keeps its values in the live store, the model's still reach the defaults.
While there I gave that write the same in-memory defaults sync the setParams write got, since it lands in the same place and would otherwise go stale in the same way.
There was a problem hiding this comment.
Right, and fixed. Worth recording that this fix is what turned Repo tests (CPU) red: tests/studio/test_new_chat_context_recount.py slices the setCheckpoint body verbatim and executes it against hand-written stubs, so the added call to a module-private function landed outside the slice as ReferenceError: restoreThreadScopedParams is not defined. Reproduced at pristine head as 2 failed / 51 passed against 53 passed at the merge base. Stub added in 95e4520; the identity is faithful because that file seeds no thread-scoped snapshot.
| const paramsByModel = getParamsByModelAfterEdit( | ||
| state, | ||
| outgoing, | ||
| nextParams, | ||
| changedParams, | ||
| sharedParams, |
There was a problem hiding this comment.
Exclude thread values from outgoing model snapshots
When switching away from a model while a saved chat is active, rememberOutgoingModel(state, state.params) has already copied the chat's live sampling and system-prompt values into the outgoing model's shared memory before this filtered sharedParams is used. Consequently, reopening that model in a new or snapshot-less chat can replay another chat's prompt and sampling; if the model had no entry, rememberOutgoingModel also persists that full snapshot. Filtering only the incoming change set cannot undo the outgoing snapshot, so the outgoing memory must be built without active thread-owned values.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 32f6c8a. This is the same leak I found last round in getParamsByModelAfterEdit, reached by the other path, and your point that filtering the incoming change set cannot undo it is exactly why the earlier fix missed it.
Verified end to end. REMEMBERED_INFERENCE_PARAM_KEYS is every persisted param except maxSeqLength, so all eight thread-scoped keys are remembered per model; rememberOutgoingModel snapshots state.params, which inside a chat holds that chat's values; and getRememberedParamsPatch writes the whole snapshot as the model's entry, so it replaces rather than merges. On a model with no entry the seeding branch also persists it to the server.
withoutActiveThreadParams now takes the chat's values back out before the snapshot is picked. Two details worth flagging:
- The precedence is
remembered?.[key] ?? globalThreadScopedDefaults?.[key]. Substituting the installation value unconditionally would have clobbered a preference the model was given outside any chat, since the patch replaces the entry wholesale. - It sits inside
rememberOutgoingModelrather than at the call sites, so bothsetParamsandsetCheckpointare covered by construction.
One related path I have deliberately left alone: setRememberParamsPerModel adopts state.params for the active model when the toggle is switched on, which inside a chat is that chat's values. That one is an explicit user action whose stated meaning is to adopt the settings on screen, so changing what it adopts is a product decision rather than a bug fix. Happy to change it if you would rather it took the installation values.
There was a problem hiding this comment.
Right, and partly live: rememberOutgoingModel was fixed but pickRememberedParams had two other unfiltered call sites, so editing a non-thread remembered key snapshotted the open chat's temperature and system prompt against the model and replayed them into the next chat on it. Fixed in 95e4520.
setCheckpoint replays the destination model's remembered params itself, without going through setParams, so the restore never ran there. An external switch has no load after it to correct the result, so the chat adopted that model's prompt and sampling and kept them. The restore now runs on that path too, and persistence still reads the unrestored object so the model's own values reach the installation defaults. The other direction leaked the same way. rememberOutgoingModel snapshots the live params, which inside a chat are that chat's, and on a model with no entry it persists that snapshot whole. Filtering the incoming edit cannot undo a write that already happened, so the outgoing snapshot is now built without the values the open chat owns. What the model already remembered wins over the installation copy, so stepping off a model inside a chat does not flatten a preference the model was given outside one. persistReplayedParams writes the installation defaults on the setCheckpoint path, so it keeps the in-memory copy level the same way setParams does.
|
Pushed 32f6c8a. Both comments were right, and both are the same theme: the per-chat layer and the per-model memory from #8757 meet in more places than Switching into a model ( Switching out of a model leaked the other way. Putting that filter inside One path left alone, on purpose. Verification
Caveat unchanged for the whole of this PR: no browser verification has been possible, so the user-visible behaviour rests on the tests and on reading the code. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 32f6c8a753
ℹ️ 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 (isThreadScopedParamKey(key)) { | ||
| paramsPatch[key] = value; |
There was a problem hiding this comment.
Backfill sampling keys in legacy thread snapshots
When opening a thread created by an earlier Studio version, stored is non-null but lacks the newly introduced sampling and prompt keys. This branch applies installation defaults for those missing keys, but the later write is scheduled only when stored === null or an edit was held, so the augmented snapshot is never persisted. After another model or global-default change, reopening that existing thread therefore changes its sampling and system prompt instead of retaining the values established on its first post-upgrade open.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this one closely and it is pre-existing design rather than a regression: the write gate and the defaults fallback are byte-identical at the merge base. Nothing the user chose is lost, because in the legacy-snapshot case they chose nothing, and the first edit pins all eight keys so the drift stops there.
| const sharedParams = persistingGlobally | ||
| ? withoutCapturedThreadEdits(changedParams, fromModelDefaults) | ||
| : changedParams; |
There was a problem hiding this comment.
Capture sampling edits before settings hydration
If a user changes a sampling value or system prompt while the initial /api/chat/settings request is still pending, the composer is interactive and thread pairing has already begun, but settingsHydrated === false selects changedParams here without ever calling withoutCapturedThreadEdits and thus captureThreadScopedEdit. The arriving hydration/thread snapshot can consequently overwrite the edit, or the pairing path can mistake it for an installation default and leak it to other chats; thread capture needs to occur independently of whether the global HTTP write is currently allowed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine and reproduced on the real store: an edit made before hydration is wiped by the arriving snapshot and also leaks onto the next chat. Fixed in 95e4520, with the pre-hydration case pinned by a new test.
…bered-params writes
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 95e4520105
ℹ️ 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".
| state: ChatRuntimeStore, | ||
| params: InferenceParams, | ||
| ): InferenceParams { | ||
| if (threadScopedSettingsThreadId === null) return params; |
There was a problem hiding this comment.
Strip pending chat edits from outgoing model memory
Fresh evidence after the earlier outgoing-snapshot fix is the pending-pairing path: while a saved chat's settings read is outstanding, applyThreadScopedSettings(null, null) leaves threadScopedSettingsThreadId null even though heldThreadScopedEdits contains the chat's new sampling values or system prompt. If a model switch/load occurs in that window, this early return lets rememberOutgoingModel snapshot those live chat-only values into the outgoing model's shared memory; with the default per-model memory enabled, switching back to that model from another chat can replay the first chat's prompt and sampling, and a previously unseen model entry is also persisted. Pending held fields must be stripped just like fields from an already paired chat.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in e6756be. Reproduced by driving the real store rather than reading the branch: hydrate, set the checkpoint, open chat A, begin pairing, edit temperature and the system prompt, then switch model. Chat A own sentinel string landed in paramsByModel against the outgoing model, which is the leak invariant the existing simulation harness already encodes.
The asymmetry was visible once you put the two functions side by side: restoreThreadScopedParams reads the held value first and falls back to the override, while withoutActiveThreadParams consulted only the override and returned early whenever the thread-scoped id was still null, which is precisely the pending-read window. It now considers the held value too, with the pairing-window sample as the last fallback because on the first pairing of a session the global defaults are still null and the pre-edit value is no longer in the store. The three-term chain is nullish rather than truthy, so a legitimate temperature 0, topK -1, minP 0 or empty system prompt still survives.
Mutation-checked: reverting the source fails the new test with the leaked 1.37 still in place.
| ); | ||
| // Level with what was just written, or a chat opened later in the same | ||
| // session falls back to the sampling from before this model loaded. | ||
| noteThreadScopedDefaults(sharedParams); |
There was a problem hiding this comment.
Preserve model defaults updated during pairing
Fresh evidence after the earlier in-memory-default refresh fix is a race with pairing cleanup: if the user edits temperature while a thread read is pending and model B publishes its defaults before that read finishes, this call correctly caches B's temperature, but applyThreadScopedSettings later treats the same held field as contaminated and replaces it with pairingWindowDefaults from model A. The backend retains B's default while the in-memory fallback reverts to A, so a new or snapshot-less chat opened in the same session is pinned with the stale temperature until reload. The pairing cleanup needs to retain defaults updated after the window opened rather than blindly restoring its pre-window sample.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in e6756be. Reproduced: with chat T read still out, a model publishing temperature 0.31 as a default put 0.31 on the wire to the settings route, then the pairing cleanup restored the pre-window sample in memory, so a chat opened afterwards with no snapshot of its own came up on 0.6 while the server held 0.31. Session and server disagreeing about the installation default is the part that matters, since the next snapshot-less chat inherits the stale one.
Two things had to change. noteThreadScopedDefaults returned early when the global defaults were still null, which is the common case here because nothing had been applied yet, so the published value had nowhere to land at all. And the held-field escape hatch only covered the hydration source, not a default published mid-window. Both are recorded now, with the map documented as having two writers rather than renamed, which would have churned five source assertions for no behaviour change.
Mutation-checked: removing just the record fails the new test with 0.6 against 0.31. Full suite 3530 passed, 0 failed, typecheck clean. The three source-shape assertions in thread-scoped-pairing-invariants that pinned the old lines are realigned and two more added, so the invariants are stronger rather than relaxed.
Review summaryVerdict: useful. Real issue, and one CI break plus three sampling-loss bugs fixed in 95e4520. Before / afterBefore, sampling parameters and the system prompt were remembered per model, so two chats on the same checkpoint shared one set of values and each one's edits overwrote the other's. After, a chat carries its own sampling and system prompt, and the model's remembered defaults are only applied where the chat has not chosen. Losing a user's saved sampling settings is data loss, so this sits squarely in scope rather than being a preference nicety. On the 11 Codex itemsNine were written against earlier commits and the author had already fixed them; every one of those claims was valid when filed, so they are thumbed up with the fixing state named in the thread. Two were still partly live at head and are fixed here. One is rejected: the legacy-backfill item describes a write gate and defaults fallback that are byte-identical at the merge base, so it is pre-existing design rather than a regression - and nothing the user chose is lost, because in that case they chose nothing, and the first edit pins all eight keys. The CI failure was this PR's, and it is fixed
Reproduced cleanly: pristine head gives Worth flagging for the future: a test that slices and Three further bugs fixed
That fix relaxes two regexes in this PR's own tests, which is a thing worth justifying rather than slipping past: both widen to permit an extra argument while adding a stricter assertion, SimulationThe store was driven as a state machine rather than reasoned about: 1328 generated orderings of {load chat, hydrate model, apply Qwen post-load defaults, user edits sampling, switch model, switch chat, checkpoint replay, reload from persisted snapshot} with roughly 10,000 invariant checkpoints, asserting no user-set value is ever lost or leaked between threads, plus 16 compatibility fixtures. Persisted-snapshot compatibility in both directions: an upgrading user has thread snapshots written by the old schema with no per-chat sampling keys, and a downgrading user has snapshots carrying them. Both load without crashing or zeroing settings, via Browsers: nothing here is engine-dependent, so I am not claiming a matrix. Zero browser-dependent constructs are added - no Note for anyone running these locally: the frontend runner is Reported, not fixed
|
UI evidenceTwo isolated Studio installs, BEFORE at the merge base Facts that moved, read from the same servers that were photographed:
The eight keys the thread row gains are Controls held on both sides: nothing loaded (the model selector reads "Select model" on both), two sidebar rows, and the side that typed a value holds it on both builds. What this pair does NOT cover:
Useful: the round trip is exactly the reported behaviour, and both halves of it move the way the PR says. |
…ublished mid-pairing withoutActiveThreadParams returned early while a chat's read was still out, so switching model in that window snapshotted the open chat's temperature and system prompt into the outgoing model's shared memory. The sibling restore path already read the held value first; this one consulted only the override. Driving the real store put a chat's own sentinel straight into paramsByModel, which the simulation harness already treats as a leak. Second, a model default published inside the pairing window was sent to the settings route but then rolled back in memory from the pre-window sample, so the session and the server disagreed and the stale value was pinned onto the next chat with no snapshot. noteThreadScopedDefaults also returned early when nothing had been applied yet, which is the common case, so the value had nowhere to land.
|
@codex review |
|
@codex review |
|
@codex review |
|
@codex review |
|
Confirmed main's ThreadScopedSettings in studio/frontend/src/features/chat/utils/thread-scoped-settings.ts still omits the sampling params and the system prompt, so reopening a chat runs it with whichever prompt was last edited. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 21ae550d6d
ℹ️ 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 source: Record<string, unknown> = {}; | ||
| for (const key of THREAD_SCOPED_SETTING_KEYS) { | ||
| source[key] = state[key]; | ||
| source[key] = readThreadScopedValue(state, key); |
There was a problem hiding this comment.
Keep held edits out of the next chat's defaults
When the user leaves chat A while its settings read is still pending, commitHeldThreadScopedEditsToTheirThread clears the pending pairing but intentionally leaves A's edited params in the live store. Opening a new or snapshot-less chat B then samples readThreadScopedSettings as B's installation defaults, and this new params-aware read copies A's temperature and system prompt into B before permanently pinning them to B's row. Restore the actual installation defaults before beginning B's pairing rather than treating the held values left in state.params as global.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 7f5515b. Reproduced in the store: edit temperature while chat A's read is still out, leave for chat B, and B captured 1.37 as the installation default and was pinned with it. The commit now puts the pre-window values back over the fields it has just written to A, and only when the chat is actually being left, so a retry after a failed read and a fork both leave the edit on screen. New test in thread-scoped-commit-restores-defaults.test.ts fails without the fix.
Leaving a chat while its settings read is still out writes the edits made in it to that chat's row, but the store kept showing them, so the next chat took them: a snapshot-less chat captured the store as the installation defaults and was pinned with the previous chat's temperature and system prompt. Restore the pre-window values over the committed fields, and only when the chat is actually being left, so a retry after a failed read and a fork both leave the edit on screen.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7f5515b99f
ℹ️ 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 effective = replayed | ||
| ? restoreThreadScopedParams(nextParams) | ||
| : nextParams; |
There was a problem hiding this comment.
Diff model defaults against installation defaults
When an open chat pins a sampling value that happens to equal the newly loaded model's recommendation, effective correctly preserves that value, but changedParams still compares nextParams with the chat-overridden state.params. The key is therefore considered unchanged even when globalThreadScopedDefaults holds a different value, so the model default is neither persisted nor passed to noteThreadScopedDefaults; a later new or snapshot-less chat continues using the previous installation default. For model-derived updates, compare thread-scoped keys against the installation-default snapshot rather than the live chat params.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I built the suggested change (diff thread-scoped keys against the installation-default snapshot instead of state.params when fromModelDefaults) and it is not safe: both callers pass mergeBackendRecommendedInference({ current: store.params, ... }), so a chat's own held systemPrompt rides along inside nextParams, and re-baselining makes it look changed. Since withoutCapturedThreadEdits deliberately does not filter when fromModelDefaults, that value then goes straight out in the settings PUT, which the simulation suite flags as chat-private data reaching the installation across 175 orderings in A4 alone. The store has no way to tell "the model recommends 0.7" from "0.7 came from the open chat" once the caller has merged them, so the general case stays handled by diffing the unrestored nextParams, and closing the equal-value residual needs the merge helper to report which keys the backend actually supplied rather than a change here.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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: bbe6ed92ed
ℹ️ 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".
| for (let round = 0; round < 3; round += 1) { | ||
| tick(1000); | ||
| for (let i = 0; i < 6; i += 1) { | ||
| await new Promise((resolve) => setImmediate(resolve)); | ||
| } |
There was a problem hiding this comment.
Await snapshot writes instead of polling the event loop
These fixed timer ticks and 18 setImmediate turns do not guarantee that the snapshot writer's promise chain and first-time dynamic import have completed. Running node --experimental-strip-types --test --test-name-pattern='C1c' tests/thread-scoped-sampling-compat.test.ts in isolation fails because the assertion reads threadRows after writeThreadScopedSettings has started but before updateStoredChatThread finishes; the full npm test run consequently reports 12 failures. Await awaitThreadScopedSettingsWrite(threadId) or an equivalent deterministic completion condition here and in the simulation helper's drain instead of relying on a fixed number of event-loop turns.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Neither reproduction holds here. The exact isolated command in this comment passes (pass 1, fail 0), the compat file is stable at 16/16 over five consecutive runs, the thread-scoped glob is 107/107, and the full npm test command node --experimental-strip-types --test "tests/**/*.test.ts" reports tests 3880, pass 3880, fail 0, exit 0, not 12 failures. settle() drives a fake clock, so the tick plus setImmediate rounds drain the write chain the store actually queues rather than racing it.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
Comments only. Collapses the multi-line explanations in the thread-scoped sampling path to their shortest clear form and drops the restatements, keeping the reasons behind the pairing window, the held-edit capture and the outgoing-model filter.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bd1cfb940c
ℹ️ 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".
| !fromModelDefaults && | ||
| // By value: this runs inside the updater, so the store still holds the pre-edit | ||
| // value, and a load in the same pairing window is what a read-back would find. | ||
| captureThreadScopedEdit(key, null, value) |
There was a problem hiding this comment.
Persist held sampling edits when the thread row is absent
When an authoritative thread read returns no row after the user moves a sampling slider during pairing, releaseHeldThreadScopedEdits() is supposed to turn the held edit into an installation-default change. This capture records a null writeGlobal, however, so release has nothing to invoke: the value remains only in state.params and is lost on reload without reaching global settings or per-model memory. Preserve a callback that performs the filtered global/model persistence for this no-row path.
Useful? React with 👍 / 👎.
| threadId: string, | ||
| held: { field: string }[], | ||
| ): void { | ||
| if (useChatRuntimeStore.getState().activeThreadId === threadId) return; |
There was a problem hiding this comment.
Restore defaults after thread-read retries are exhausted
When a user edits sampling or the system prompt while a saved thread read is pending and every read retry fails, the first commitHeldThreadScopedEditsToTheirThread() call takes this early return because that thread is still active, while also clearing the pending pairing association. The eventual give-up path calls applyThreadScopedSettings(null, null), which then has neither a paired nor pending thread to restore and leaves the chat-only value live; opening another chat can consequently sample and pin that value as an installation default. Retain enough state to restore the pre-window defaults when the retry loop finally gives up.
Useful? React with 👍 / 👎.
Frontend CI has been red on main since unslothai#9055, not intermittently: eight consecutive main runs failed at `Unit tests`, every one on node v22.23.2. The three suites from unslothai#9055 wait for a debounced write with a fixed drain -- three rounds of tick(1000) plus six setImmediate turns -- and then assert. Three rounds is enough on node 24, which is what a dev box happens to have, and is not enough on node 22, which `setup-node: 22` resolves to. The same chain drains far fewer continuations per round there, so the write had not landed when the assertion ran. Reproduced by downloading node 22.23.2 and running the suites against both. Measured on the compat suite: rounds 3 10 30 60 failing 7 5 1 0 The compat suite reported it as a missing value (expected 1.37, actual undefined). The simulation suite reported it as an ORDERING violation -- "chat A temperature: owed 0.6, shows 1.37" -- because a scenario whose write has not landed looks exactly like one that wrote the wrong value, which is why this read as a feature bug rather than a slow test. There were three copies of the drain: one per suite plus the shared thread-sampling-world helper the simulations run through. Fixing only the two suites left the simulations red, since their scenarios drain through the helper. The bound is 200, generous rather than tuned to the observed 60, and settle() now takes an optional `until` predicate: it returns as soon as the caller can see the work, and throws naming itself if the condition never holds, so the next slow runtime reports "settle gave up" instead of an assertion on a missing value. Verified: node 22.23.2 compat 16/16 and simulation 18/18 (both were failing); node 24 full frontend suite 4060/4060. Only the simulation suite imports the helper, and no fixed three-round drain remains in tests/.
…unslothai#9332) * Stop Frontend CI installing Chromium's system libraries through apt every run `playwright install --with-deps chromium` runs its own `apt-get update` inside itself, so it bypassed everything CI has learned about apt: the shared retry helper's 20s transfer cap, APT_ACQUIRE_RETRIES: '0', and the archive cache. The job failed 3 of 8 runs on main. Job 96072994354 (main, 2026-08-19): 9 packages, 21.1 MB, and `fonts-wqy-zenhei [7472 kB]` alone took 5m50s off azure.archive.ubuntu.com. Both 420s attempts died mid-download. That is the same mirror and the same package that took the webkit shards down in unslothai#9289. Attempt 2 logged "Need to get 8833 kB/21.1 MB", so apt does resume partials across attempts and still could not finish. Split the way studio-ui-smoke.yml splits it: download the engine, launch it to find out whether the system libraries are actually missing, and run `install-deps` only if they are. ubuntu-latest is a browser-testing image and usually ships them, so the common path now runs no apt at all. The browser and apt-archive cache keys are deliberately identical to the chromium-only shards in studio-ui-smoke.yml (engine token `c`): same image, same Playwright version, same single engine, so the entry is shared rather than duplicated against a budget measured at 99.3% full. The step's authorised worst case doubles with the second helper call, to 2 x (2 x 420s + 125s) = 1930s, so its timeout goes 17m -> 33m and stays under the job's 40m. Both guarded calls are skipped on the common path. Guard: tests/studio/test_playwright_install_avoids_with_deps.py fails the build if `--with-deps` returns to any workflow, and is wired into workflow-trigger-lint, the only job with no paths filter. * Drain the sampling debounce long enough for the node CI actually runs Frontend CI has been red on main since unslothai#9055, not intermittently: eight consecutive main runs failed at `Unit tests`, every one on node v22.23.2. The three suites from unslothai#9055 wait for a debounced write with a fixed drain -- three rounds of tick(1000) plus six setImmediate turns -- and then assert. Three rounds is enough on node 24, which is what a dev box happens to have, and is not enough on node 22, which `setup-node: 22` resolves to. The same chain drains far fewer continuations per round there, so the write had not landed when the assertion ran. Reproduced by downloading node 22.23.2 and running the suites against both. Measured on the compat suite: rounds 3 10 30 60 failing 7 5 1 0 The compat suite reported it as a missing value (expected 1.37, actual undefined). The simulation suite reported it as an ORDERING violation -- "chat A temperature: owed 0.6, shows 1.37" -- because a scenario whose write has not landed looks exactly like one that wrote the wrong value, which is why this read as a feature bug rather than a slow test. There were three copies of the drain: one per suite plus the shared thread-sampling-world helper the simulations run through. Fixing only the two suites left the simulations red, since their scenarios drain through the helper. The bound is 200, generous rather than tuned to the observed 60, and settle() now takes an optional `until` predicate: it returns as soon as the caller can see the work, and throws naming itself if the condition never holds, so the next slow runtime reports "settle gave up" instead of an assertion on a missing value. Verified: node 22.23.2 compat 16/16 and simulation 18/18 (both were failing); node 24 full frontend suite 4060/4060. Only the simulation suite imports the helper, and no fixed three-round drain remains in tests/. * Raise the scenario drain to 600: 200 was marginal, and Windows needed more At 200 the simulations were 0 failing on one run and 1 on the next on the same machine, and the Windows runner -- slower again -- still had 2 of 120 orderings short. 600 is 0 failing across three consecutive runs, at 107s against 52s. Also records the adaptive version that was tried and is wrong here, so it is not tried again: the rows only change WHEN the write lands, so 'rows have stopped changing' is precisely the pending state being waited through. Quiescence on that observable stops early by construction and scored 4 failures where the fixed bound scored 0. * Stop the settings smoke asserting a tab count a new page invalidates Unskipping the browser smokes surfaced this immediately: the blocked-panel run failed with 'blocking the data panel took the dialog down' while its own report said dialog: True. Nothing had taken the dialog down. The check was if not state["dialog"] or state["nav"] != 12: and the keyboard-shortcuts page had made the nav 13. A stale constant, reading as an error-handling regression. The nav size is now read before the panel is blocked and compared against itself, which is the invariant that was meant: blocking a panel must not collapse the dialog, whatever size the dialog is. The same drift had a quieter half. The smoke's TABS list still had twelve entries, so keyboard-shortcuts had no browser coverage at all and the smoke stayed green without it. It is added here, and tests/studio/test_settings_smoke_covers_every_tab.py pins both directions against settings-dialog.tsx so the next page cannot go uncovered silently. It also checks the workflow's PW_CHUNK_FAIL names a tab that exists -- that value lives in studio-frontend-ci.yml, not in the smoke, and a rename would leave the run blocking nothing while still reporting PASS. Wired into workflow-trigger-lint, the only job with no paths filter, because it reads a workflow. Mutation-tested both ways: dropping the tab from TABS and restoring the literal count each turn it red. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Drain the sampling suites on the loader too, and fail loudly when it gives up The fixed round count in the previous commit was still a guess, and the Windows job proved it: the SAME commit at 600 rounds passed one run and failed the next with "A1: 2 violation(s) across 120 orderings", reporting stale reads as lost edits. Raising the number again was not the answer. The pending work has a second half nothing was waiting on. The store's thread-scoped write ends in `await import("../utils/chat-history-storage")` (chat-runtime-store.ts:1326 and :1754), and these suites register() a resolver hook, which routes that import through the hooks thread. Three repeat imports of an already-loaded module: v24.14.0 no hook 1, 1, 1 turns hook registered 1, 1, 1 v22.23.2 no hook 1, 1, 1 turns hook registered 6, 3, 35 That is the whole green-locally / red-on-CI split, and it is why a loaded Windows runner fails what the same commit passed an hour earlier: the pending work is a message to another thread, so its cost is scheduling latency, not instructions. No round count is correct for that. Counting the mocked timers alone does not cover it either, which is worth recording since it is the obvious next idea. With the counter installed and 25 consecutive quiet rounds per drain, 150 macrotask turns of nothing, v22.23.2 still lost 7 orderings across A1 and A3, every one a write that had not landed. So drain on both observables. tests/helpers/mock-timer-drain.ts wraps the MOCKED setTimeout with a counter, giving an exact count of timers scheduled and not yet fired or cleared, and each round also issues its own import and waits for it, so the wait scales with the loader instead of guessing at it. The drain returns when no timer is outstanding and three consecutive rounds neither scheduled nor fired one. With the probe, three quiet rounds is green on v22 and v24 alike. The generous bound stays as a BACKSTOP that THROWS and names what was still outstanding, which is the change that matters most here. An under-drain used to be indistinguishable from the store losing an edit, so it sent the investigation into the store for two rounds. Now it says so: settle: drain exhausted after 2 rounds, with no timer pending but work still scheduling or firing within the last 3 rounds. Nothing read after this point is trustworthy: a queued write has not landed, so the store still shows the PREVIOUS value, which reads as a wrong value rather than a missing one. Fix the work or raise the backstop; do not read this as the store losing an edit. It is also much faster, because it stops when the work is done rather than after 600 rounds regardless. A typical drain now takes 4 rounds; instrumented over 840 drains in A1 the maximum was 4. simulation v24 101.7s -> 30s v22.23.2 106.5s -> 29s compat v24 0.54s -> 0.46s v22.23.2 0.61s -> 0.52s The three copies of the drain shape, one in the world helper and one in each test file, are now one helper. The dead end already recorded is kept next to the new measurements: quiescence on the store ROWS is still wrong, because the rows only change WHEN the write lands. Verified: both suites green twice each on v24.14.0 and on v22.23.2, the version setup-node 22 resolves to. Full frontend suite 4080 passed, 0 failed. The exhaustion throw was confirmed by forcing the backstop to 2, which produces the message above and no wrong-value violation. A deliberately broken sanitizeThreadScopedSettings still produces a real ordering violation on both runtimes, so the drain is not exiting early. Test files only. * Read the workflow and the dialog as UTF-8, not as the platform default test_source_read_encoding caught four read_text() calls this PR added with no encoding. It is right and they are a real defect: the guard reads settings-dialog.tsx, playwright_settings_tabs.py and studio-frontend-ci.yml, and on a Windows runner Path.read_text() uses the ANSI code page, so any non-ASCII byte in any of them raises UnicodeDecodeError. The whole point of this guard is that a settings page can be added without anyone noticing; a guard that cannot be collected on Windows fails the same way. Repo tests (CPU) was otherwise clean: 1 failed, 8781 passed. * Tell a pwsh crash apart from install.ps1 losing its exit code test_the_pwsh_filter_keeps_the_log_clean_and_the_exit_code_intact went red on a hosted ubuntu runner with completely empty stdout and pwsh's own banner: "An error has occurred that was not properly handled. Additional information is shown below. The PowerShell process will exit." The interpreter died; the script never ran. Workflow trigger lint is green on the last 8 main runs and this PR touches no PowerShell, so it is the runner, not the repo. Read as an ordinary failure it says "$LASTEXITCODE did not survive the added pipeline stages, so a failing install.ps1 would leave its step green" -- an accusation against the installer, raised by a run that produced no evidence either way. That is the same shape as the drain in this PR: an environment shortfall wearing the costume of a product regression. _run_pwsh retries only that case, and the distinction is what keeps it honest: a run that reaches the `RC=` line is returned on the first attempt whatever the value, so a genuine regression can never be retried into green. Only a run with no RC= AND the crash banner is retried, because it carries no verdict to preserve. If both attempts crash it fails with a message naming the interpreter, not install.ps1. 17 passed. Exercised _run_pwsh against a script that prints the banner and no RC=: it raises, so the branch is not vacuous. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Three resolutions, all "both sides added here": `core/inference/tools.py` -- main added the synthetic-search-exchange builders next to where this branch added the pre-retrieval check. Both are kept; `build_rag_autoinject` already calls the check and needed no further change. `chat-adapter.ts` -- main added a `preserveThinking` field to the runtime snapshot in the same five places this branch renamed `ggufContextLength` to `loadedContextLength`. Each resolution keeps main's new field beside the renamed one. `thread-scoped-pairing-invariants.test.ts` -- main's new case (unslothai#9055) pins that `mergeBackendRecommendedInference` is accompanied by `fromModelDefaults: true`, bounded by a 700-character proximity window. The loaded context window joining that call site pushed the two further apart, so the bound is widened. The property it pins is unchanged; the number was only ever proximity.
Three resolutions, all "both sides added here": `core/inference/tools.py` -- main added the synthetic-search-exchange builders next to where this branch added the pre-retrieval check. Both are kept; `build_rag_autoinject` already calls the check and needed no further change. `chat-adapter.ts` -- main added a `preserveThinking` field to the runtime snapshot in the same five places this branch renamed `ggufContextLength` to `loadedContextLength`. Each resolution keeps main's new field beside the renamed one. `thread-scoped-pairing-invariants.test.ts` -- main's new case (unslothai#9055) pins that `mergeBackendRecommendedInference` is accompanied by `fromModelDefaults: true`, bounded by a 700-character proximity window. The loaded context window joining that call site pushed the two further apart, so the bound is widened. The property it pins is unchanged; the number was only ever proximity.

What
#8686 made sixteen chat settings travel with the thread: the composer pills, the permission level and the retrieval controls. The sampling params and the system prompt were left on the installation-wide set, so they still leak between conversations.
This adds the remaining eight to the same snapshot:
Why
Reported by a user who moved over from Ollama, LM Studio, Msty, AnythingLLM and Jan:
That is the one behaviour keeping them from making Studio their default, and it is the half of per-chat settings #8686 did not cover.
How
These are the only thread-scoped settings that do not have a store field of their own: they live under
params. Rather than flatten them, the read and apply paths learn where to look, so the snapshot on the thread row stays a single flat object and the rest of the pairing machinery is untouched.Applying goes the other way: the sampling keys are gathered into one
paramspatch rather than set as fields, so a restore is a single update rather than eight.An edit with a chat open lands on that chat, and with no chat open it moves the installation defaults, exactly as the existing sixteen behave.
A model's recommendation is not an edit. A load applies the model's own sampling through the same setter, and storing that would pin whichever chat was open to whichever model happened to load. Both paths that do it now say so, and only what the chat does not take goes to the installation defaults:
What is deliberately not per-chat
maxSeqLength,maxTokensandcheckpoint. Those describe the model that loaded rather than the conversation, and a chat restoring a budget the current model cannot hold is exactly the failure that exclusion prevents. There is a test pinning it.Contract
ChatThreadSettingsgains the eight fields with the ranges the sliders already enforce (temperature 0 to 2, top P and min P 0 to 1, top K 0 to 100, repetition penalty 1 to 2, presence penalty 0 to 2), andallow_inf_nan = Falsefor the same reasonChatInferenceSettingscarries it: a bare NaN is accepted by bothjson.loadsand pydantic, and stored as a token no strict reader can parse back.The prompt fields are not length-capped, matching the installation-wide copy. Truncating would silently change what the chat runs with.
readable_thread_settingsalready drops what a build cannot validate, so an older Studio opening a newer database keeps the rest of the snapshot and leaves the row alone.Tests
Frontend, 2942 passing:
Backend, 127 passing across the chat-history suites:
extra="forbid"alone would refuse the out-of-range value for the wrong reason)Every new test was checked against the previous commit: thirteen backend and five frontend fail there. The sixth frontend test guards the exclusions and passes either way by design.
npm run typecheckandnpm run buildare clean, and per-file biome error counts are unchanged against main.Not verified
No browser verification. This is checked through the contract, the store wiring and both test suites.