Skip to content

studio: stop prompting to stop chats for a model already loaded - #8943

Merged
danielhanchen merged 37 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-model-switch-loaded-check
Aug 17, 2026
Merged

danielhanchen merged 37 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-model-switch-loaded-check

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

Fixes #8893.

Picking the model that is already loaded raised "Stop N running chat?" and reloaded it, killing a reply that was still streaming in another chat.

selectModel in studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts decided whether a pick needed a load by comparing the picker row id against status.model_identifier, and only when the current checkpoint was an external provider. Those two strings name the same model but need not be equal: a cached row pinned to a snapshot dir loads by path (_repo_gguf_load_id in studio/backend/routes/models.py sets load_id whenever the repo id will not resolve on its own) while its picker row keeps the repo id, and /api/inference/status publishes the clean public id next to the raw load identifier. The resident model therefore read as a different one, and the confirmation fired for a load that /load would have answered already_loaded without touching llama-server.

What changed

residentModelMatchesPick in the new studio/frontend/src/features/chat/lib/resident-model-match.ts answers whether the resident model is the one a pick names. It matches on either name each side holds, using the comparators studio/frontend/src/features/hub/lib/model-identity.ts already exports and that hub-page.tsx compares a resident model with:

  • residentModelIdMatches(status.active_model, pick.id, pick.loadPath), which also collapses a snapshot path onto its repo id through publicModelId
  • modelIdsMatch(status.model_identifier, ...) for the raw load identifier
  • ggufVariantsMatch, so a quant switch within one repo stays a real reload

A standalone .gguf is exempt from the variant comparison. A direct path load derives hf_variant from the filename and /status echoes it, while the picker row deliberately carries none (settingsGgufVariantForRow), so comparing the two answered "not resident" for the exact file that was loaded.

selectModel now runs the residency check for any pick that does not set forceReload, instead of only when the checkpoint is an external provider. Applying settings still reloads and still prompts, because a staged config always carries forceReload.

Before and after

Re-picking the loaded model while another chat is generating:

before

after

Picking a genuinely different model still prompts:

different model still prompts

Checks

Verified end to end against a running Studio with mlx-community/Qwen3-0.6B-4bit loaded from a cache whose repo id does not resolve, so the row id and the load path differ the way the report requires. /api/inference/status reported model_identifier as the snapshot path.

  • re-picking the resident model mid-generation: dialog raised and a second POST /api/inference/load sent before the change, neither after, with the reply running to completion. active-generations confirmed at 1 at the moment of the pick in both runs.
  • picking a different model mid-generation: dialog still raised.
  • node --experimental-strip-types --test "tests/**/*.test.ts": 2711 pass, 0 fail.
  • tsc -b and tsc -p tsconfig.test.json: clean.
  • biome format and eslint on the changed files: clean.

No Python changed, so ruff and pytest do not apply. GPU-specific checks were not run: this is a frontend change, exercised on Apple Silicon MLX inference.

Picking the model that is already resident raised "Stop N running chat?" and reloaded it.
selectModel decided whether a pick needed a load by comparing the picker row id against
status.model_identifier, and only when the current checkpoint was an external provider. A
cached row pinned to a snapshot dir loads by path while its row keeps the repo id, so the
two sides hold different strings for one model and the resident model read as a different
one. /load answers already_loaded ahead of its cancel hook, so nothing was ever going to be
stopped.

residentModelMatchesPick matches a pick against the resident model on either name each side
holds (id / load path against active_model / model_identifier), normalized through
normalizeModelIdentity so Windows paths compare by case and separator, and gated on the GGUF
variant so a quant switch stays a real reload. The residency check now runs for any pick that
does not force a reload, not only when the checkpoint is external.

Verified end to end against a Studio instance with an MLX model loaded by snapshot path:
re-picking it mid-generation raised the dialog before the change and adopts silently after,
with the chat running to completion.

Fixes unslothai#8893
residentModelMatchesPick hand-rolled the comparison that model-identity.ts already exports.
It now uses residentModelIdMatches, modelIdsMatch and ggufVariantsMatch, the same pair
hub-page.tsx compares a resident model with, which also collapses a snapshot path onto its
repo id through publicModelId.

A standalone .gguf is exempt from the variant comparison. The backend derives hf_variant from
the filename for a direct path load and /status echoes it, while the picker row deliberately
carries none (settingsGgufVariantForRow), so comparing the two left unslothai#8893 unfixed for On
Device files: the variant alone answered "not resident" for the file that was loaded.

The source-scan test now asserts the residency check is not gated on an external checkpoint
again, which is the shape the bug had. Verified it fails against that shape and passes here.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Matching the pick against status.active_model treated any snapshot of a cached repo as the
resident one. The public id is the same for every snapshot, while _repo_gguf_load_id repoints
load_id at the newest by mtime, so a repo that advanced under a resident older snapshot read
as resident and selectModel skipped a load that would have replaced stale weights.

LlamaCppBackend.matches_load_source settles it on the raw identifiers, so residentModelMatchesPick
now does the same: when status reports a model_identifier it has to equal what this pick would
send as model_path, and the public-id alias is left for a native-lease load, which withholds the
raw path and reports only its display label.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

if (useChatRuntimeStore.getState().activeLoadId !== modelId) {
useChatRuntimeStore.setState({ activeLoadId: null });

P1 Badge Preserve the verified snapshot load path

When switching back from an external provider to a resident cached repo whose loadPath is a pinned snapshot, activeLoadId contains that snapshot while modelId is the public repo ID, so this condition always clears the valid pin immediately after residentModelMatchesPick verified it. For repos outside the active cache, the public ID deliberately does not resolve; a subsequent Reload/Apply reads the now-null activeLoadId and sends the unusable repo ID instead of the snapshot path. Compare the stored pin with loadPath, preserving it when it names the resident snapshot.


useChatRuntimeStore
.getState()
.setCheckpoint(modelId, residentStatus.gguf_variant);

P2 Badge Keep standalone GGUF picks variantless

When re-adopting a standalone .gguf after an external-provider selection, the new matcher intentionally accepts the picker’s null variant against the quant derived by the backend, but this call then stores that derived residentStatus.gguf_variant. Standalone files are deliberately keyed as <path> rather than <path>:<quant>; after this return, the picker no longer considers its null-variant row the same loaded selection and per-model config resolution can use the wrong variant-qualified identity. Set the checkpoint variant from the pick (ggufVariant) for this path rather than reintroducing the backend-only label.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

The adopt path cleared activeLoadId behind a condition that could never be false: both writers
store the pin only when it differs from the id it was recorded against, so activeLoadId is
either null or never equal to modelId. A pinned cached row therefore lost its snapshot pin the
moment the pick was recognised as resident.

Write the pin a completed load writes instead. The stale-pin case the old comment describes is
still covered, since a pin taken for an earlier resident is overwritten either way.
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

Fixed in e8c3f9b.

The condition was vacuous: both writers store activeLoadId only when it differs from the id it was recorded against (use-chat-model-runtime.ts:1508, chat-adapter.ts:2924), so it is either null or never equal to modelId, and the branch was an unconditional clear. The adopt path now writes the pin a completed load writes, loadPath === modelId ? null : loadPath, which still overwrites a pin taken for an earlier resident.

One correction on the stated impact: a later Apply did not send the repo id. applyActiveModelStatusToStore runs immediately after and rewrites params.checkpoint through mergeBackendRecommendedInference({ modelId: checkpointId }) to resolveInferenceCheckpointId(status), so handleReloadActiveModel already had a loadable identifier. Verified on a running Studio with a snapshot-pinned MLX model: the send payload after the adopt carried the snapshot path, matching the state after a real load. The pin is worth keeping regardless, so the change stands.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e8c3f9b641

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

… model

Adopting on identity alone dropped a remembered config. The chat picker and
Hub's Run button both pass one WITHOUT forceReload (chat-page.tsx stageOrLoad,
hub-page.tsx handleRun), selection.config is only read inside performLoad, and
the short-circuit returns before it. llama-server would have reloaded for any
of those settings, so a remembered context length, KV dtype, drafter, slots,
batch size, placement or extra arg silently did nothing, and the rollback to
previousConfig made the panel agree with the server either way, so there was
nothing on screen to say so.

residentRuntimeMatchesConfig compares a pick's config against the invocation
/status echoes, over the fields LlamaCppBackend._runtime_matches_intent
reloads for plus the MLX pair _mlx_runtime_settings_match compares. A field
the config leaves unset expresses no opinion, so a model the user never
configured still adopts the resident copy and 8893 stays fixed; one the user
did configure adopts it whenever the two already agree. Anything the status
cannot report counts as a difference: answering "differs" costs one reload,
which is what happened before any of this existed, while a wrong "matches"
loses a setting invisibly.

Three smaller ones on the same path:

- a native pick no longer takes the short-circuit. It names its file by a bare
  label two different files can share, and the lease is written only by a
  completed load (activeNativePathToken, beside the pin), so adopting here
  would have kept a stale token. Every native call site forces a reload
  already; this pins the invariant where it can be seen.
- the rollback uses restorePreviousConfig() rather than an inline apply, so it
  carries the loadedIsDiffusion flag the helper passes. Without it a resident
  image model restored its config through the wrong branch of
  applyPerModelConfigToRuntime.
- the pin comment claimed applyActiveModelStatusToStore rewrites
  params.checkpoint. It writes residentCheckpoint; the caller sets the
  checkpoint one line earlier. The pin change itself stands.

Tests: resident-config-match covers every compared field in matching,
differing and not-reported form, plus the three states of llamaExtraArgs and
the ordering rules (GPU ids are a set, argv is not). resident-model-match-matrix
runs the identity comparator over Linux, macOS, Windows drive, UNC, WSL,
relative, tilde, rooted, Unicode and spaced path shapes, against current,
older and native-lease status shapes, and pins the /mnt/<letter> case fold as
a known WSL-shaped limit.
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this end to end and reproduced the report first, so the fix is anchored to something real.

The bug reproduces exactly as described

On a build of this PR's own merge base (6f443b5cc), with unsloth/Qwen3-0.6B-GGUF cached outside the active hub cache so its picker row is pinned to a snapshot dir, and one reply streaming:

row_load_id_is_snapshot:      True     (load_id != repo_id)
status_model_identifier:      == row_load_id
active_generations_at_pick:   1
dialog_shown:                 True
dialog_title:                 "Stop 1 running chat?"
row_aria_current_after_pick:  False    (the pick was never adopted)

Two things make it fire, and the PR is right about both. The pinned row loads by path, so /status reports the path as model_identifier and params.checkpoint becomes the path while the row keeps the repo id. And the old gate only ran the residency check when the current checkpoint was an external id, so a local checkpoint skipped it entirely.

One real regression, now fixed in 0c0013b

Widening isExternalModelId(selectedCheckpoint) to every non-forced pick pulled a second class of caller into the short-circuit: ones that carry a remembered per-model config.

stageOrLoad passes config: selection.config ?? rememberedConfigFor(selection) with no forceReload (chat-page.tsx:2537-2543), and handleRun does the same (hub-page.tsx:1329-1342). selection.config is read only inside performLoad (use-chat-model-runtime.ts:838), which the short-circuit returns before. So a remembered context length, KV dtype, drafter, slot count, batch size, GPU placement or extra llama arg was dropped. llama-server would have reloaded for every one of those (_runtime_matches_intent), and the failure is invisible: the same path rolls the panel back to previousConfig, so the UI agrees with the server and the user has nothing to notice. Hub's own comment at that call site says the runtime store is not enough because /load only inherits launch flags from the same resident model, which is precisely the path being skipped.

residentRuntimeMatchesConfig now compares the pick's config against the invocation /status echoes, over the fields the backend reloads for. A field the config leaves unset expresses no opinion, so an unconfigured model still adopts the resident copy and 8893 stays fixed; a configured one adopts it whenever the two already agree. Anything the status cannot report counts as a difference, because answering "differs" only costs the reload that happened before any of this existed, while a wrong "matches" loses a setting silently.

Three smaller ones on the same path:

  • a native pick no longer takes the short-circuit. It is named by a bare label two files can share, and activeNativePathToken is written only by a completed load, beside the pin, so adopting here would keep a stale token. Every native call site forces a reload already; this just pins the invariant.
  • the rollback now calls restorePreviousConfig() instead of the inline apply, so it carries loadedIsDiffusion, which the identical call 60 lines above passes and this one did not.
  • one comment correction: applyActiveModelStatusToStore writes residentCheckpoint, not params.checkpoint (apply-inference-status-to-store.ts:149); the caller sets the checkpoint a line earlier. The pin change itself is a clear improvement over the old conditional clear, which was vacuous.

What I checked

identity matrix, 73 cases Linux, macOS, Windows drive, UNC, WSL, relative, tilde, rooted, Unicode and spaced paths, against current, older and native-lease status shapes
settings comparator, 60 cases every compared field in matching, differing and not-reported form, plus the three states of llamaExtraArgs
full frontend suite 2845 pass, 0 fail. tsc -b and tsc -p tsconfig.test.json clean
engine parity the two comparators run inside Chromium 151, Firefox 153 and WebKit 26.5 against a node reference: 642/642 identical. Only post-ES2020 builtin on the path is replaceAll (Safari 13.1+), below the project's own floor and pre-existing
node 20.19.5 and 22.12.0 typecheck and production build pass on both, so the declared engines range still holds
blast radius no Python, CUDA, C++ or shell file changes, and _resolve_model_identifier_for_request returns request.model_path verbatim, so the comparison is identical on NVIDIA, AMD and CPU-only

Known limit, pinned in a test rather than left to be rediscovered: normalizeModelIdentity folds case under /mnt/<single letter>/ because that is where WSL mounts a Windows drive, so a Linux host with a single-letter mount point compares two case-different files as one. It needs a platform signal the browser does not have, the comparator is shared with the Hub, and the cost is one skipped reload for a path shape Studio never creates itself.

Before and after screenshots to follow.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Shot this before/after from two isolated installs, head 0c0013b34 against the merge base 6f443b5cc, one Playwright scene driven against both.

re-picking the resident model mid-generation

The moment is a new chat re-picking unsloth/Qwen3-0.6B-GGUF Q4_K_M while the first chat is still generating on it. BEFORE raises Stop 1 running chat?, AFTER raises nothing and adopts the resident model.

Staging, because the pair is worthless without it. The repo is seeded under the legacy HF root while HF_HOME names an empty active one, so _repo_gguf_load_id pins the row, and both sides report the same thing:

  • row_id unsloth/Qwen3-0.6B-GGUF, row_load_id the snapshot dir
  • /api/inference/status: active_model the repo id, model_identifier that same snapshot path, gguf_variant Q4_K_M

That is the mismatch the report needs, and the scene refuses to run if the row comes back unpinned, since an unpinned row makes both sides agree for a reason that has nothing to do with this change.

Measured at the pick, one active generation on both sides:

BEFORE AFTER
dialog Stop 1 running chat? none
POST /api/inference/load 0 0
generations still running after the pick 1 1

The load count matters as much as the dialog: AFTER neither prompted nor reloaded, so the absence of the dialog is a skipped load rather than a silent one.

Control, same still-generating state, both sides: picking a different cached repo (unsloth/Qwen3-1.7B-GGUF) still raises Stop 1 running chat?. So the confirmation is intact for a real reload.

Two notes on how it was run. The model is loaded with gpu_layers 0 and --threads 1: on the GPU this box decodes 0.6B at ~640 tok/s and the model does not honour "repeat it 800 times", so an earlier run had the generation finish before the pick and neither side had anything to stop. That changes only where the weights run, not the resident identity the check reads. And the composite is cropped to the header and dialog band; at full frame the dialog renders about 12px in a comment.

@danielhanchen

Copy link
Copy Markdown
Member

Before and after, from two isolated install.sh --local builds: merge base 6f443b5cc vs head 0c0013b34 (so the AFTER half includes the settings fix I pushed earlier).

before and after

unsloth/Qwen3-0.6B-GGUF seeded into each side's own non-active HF cache so its picker row is pinned to a snapshot dir, one reply streaming, then the resident row re-picked. BEFORE raises the dialog over the still-streaming column; AFTER the same stream just carries on.

fact BEFORE AFTER
dialog_shown true false
dialog_title "Stop 1 running chat?" null
status_gets_at_pick 0 1
active_generations_at_pick 1 1
generation_survived true true
load_posts 0 0
row_load_id_is_snapshot true true
status_model_identifier == row_load_id true true
status_gguf_variant Q4_K_M Q4_K_M
seconds_send_to_pick 1.4 1.4

status_gets_at_pick is what proves the click landed on both sides rather than missing on one, and it is worth reading as its own result: the two builds take different paths and each leaves its own trace. BEFORE's params.checkpoint is the snapshot path, isExternalModelId rejects it, so it asks the backend nothing and goes straight to the confirmation. AFTER asks once, recognises the pick and returns. load_posts is 0 on both because BEFORE was declined with "Keep generating", so the reload it offered is proven by the prompt rather than by a POST.

Same flow in all three engines

Driven live against the head build, each with a positive control:

engine resident re-pick different model
Chromium 151 (Chrome, Edge) no dialog, 0 loads, 1 status read "Stop 1 running chat?"
Firefox 153 no dialog, 0 loads, 1 status read "Stop 1 running chat?"
WebKit 26.5 (Safari) no dialog, 0 loads, 1 status read "Stop 1 running chat?"

The control matters as much as the pass: without it, an engine where the click silently missed would look identical to one where the fix worked.

Two things I got wrong building this, worth knowing

Neither was a defect in the PR, and both had me briefly believing there was one.

The picker's "Loaded" tag is not a signal of adoption. I first asserted that only AFTER would wear it after the pick, and that assertion failed a build that was behaving perfectly. Adoption does set it, since loadedModelId follows params.checkpoint (pickers.tsx:2410-2419) and the short-circuit writes the repo id there. But the next status refresh sees checkpointId (the snapshot path) differ from selectedCheckpoint (the repo id) and rewrites the checkpoint back to the raw path (use-chat-model-runtime.ts:337-346), un-marking the row a second or two later. So the tag is a race, not a verdict. Not a bug, but if anything ever wants to show "this row is the resident one" durably, params.checkpoint is the wrong thing to hang it on.

Nothing caps a chat reply. mergeBackendRecommendedInference sets maxTokens = response.context_length (preset-policy.ts:287) and the local send path passes it through unclamped (chat-adapter.ts:5276), so the live request body carries max_tokens: 40960. A reply that stops early stopped because the model emitted EOS, which for a 0.6B is non-deterministic: a counting prompt measured 113.9 / 39.0 / 38.5 / 7.3 s over four runs. Only mentioning it because it is easy to misread a short reply as truncation.

residentModelMatchesPick settles residency on status.model_identifier, which
names one revision. When the status carries no raw identifier it falls through
to residentModelIdMatches, and that collapses a snapshot dir onto its repo id.
Every snapshot of one repo publishes the same public id, so a pick pinned to a
different revision read as already resident and the load was skipped, leaving
the user on the weights that were there. This file's own docstring names that
hazard for the arm above it; the arm below still had it.

Two shapes reach it. A backend old enough to predate model_identifier, and a
native-lease load, which withholds the raw path on every version by design.

A literal match on the name the pick would load by still settles it, so an
older backend that put the raw path in active_model keeps adopting. What is
refused is only the collapse, and only for a pick naming a cache snapshot,
which is where the id cannot distinguish revisions. A native lease, a
standalone .gguf and an unpinned repo id are unaffected.

Found by fuzzing the function against LlamaCppBackend.matches_load_source over
the cache layouts of each supported host: across 355 pairs these rows were the
only ones the frontend adopted and the server would have reloaded.
… fields

residentRuntimeMatchesConfig reads the GPU fields, so the host it runs on is a
real axis even though it compares no paths: CUDA and ROCm report a placement
pool and an offload mode, a CPU-only host reports manual with zero layers, and
an MLX server reports none of them and a KV width instead. Each accelerator is
crossed with every setting a remembered config can pin, in all three states
that matter: the resident load already runs it, it runs something else, and
the status cannot report it at all. The last one is the direction that must
never read as agreement.

Also covers config blobs written by older Studio versions, which simply lack
the keys a newer field uses, and asserts placement compares as a set rather
than an order.

The structural test is the one that lasts. It parses PerModelConfig and fails
when a field is added without being either compared or listed as deliberately
excluded, so a new setting cannot be silently dropped by an adopted pick.
@danielhanchen

Copy link
Copy Markdown
Member

Ran this one hard before merging and pushed two commits: one fix, one test sweep. Everything below is against head 0c0013b34 and merge base 6f443b5cc.

The one real defect

residentModelMatchesPick settles residency on status.model_identifier, which names one revision. When the status carries no raw identifier it fell through to residentModelIdMatches, and that collapses a snapshot dir onto its repo id. Every snapshot of one repo publishes the same public id, so a pick pinned to a different revision read as already resident, the load was skipped, and the user stayed on the weights that were already there. The file's own docstring names that hazard for the arm above it; the arm below still had it.

Two shapes reach it: a backend old enough to predate model_identifier, and a native-lease load, which withholds the raw path on every version by design.

Fixed in fe6a30995. A literal match on the name the pick would load by still settles it, so an older backend that put the raw path in active_model keeps adopting; only the collapse is refused, and only for a pick naming a cache snapshot. Native leases, standalone .gguf files and unpinned repo ids are untouched. The regression test fails 14 of its 32 cases without the fix.

How it was found

Fuzzed residentModelMatchesPick against LlamaCppBackend.matches_load_source, the server's own already-loaded test, over 355 identifier pairs covering the cache layouts of Linux, macOS, WSL, Windows drive paths, UNC shares and a Linux disk mounted at /mnt/<letter>, crossed with quant switches, near-miss snapshots and awkward names. The frontend deciding to skip a load is only safe while it is never looser than the server.

After the fix: 0 pairs adopted that must not be, 0 pairs looser than the backend beyond separator style and trailing separators (which name one file), 41 stricter (all of them a quant change or a case-differing POSIX path, where reloading is the safe answer), and 0 drift between publicModelId and public_model_id.

Worth recording, since it looks alarming and is not: normalizeModelIdentity case-folds /mnt/<letter> paths, so a Linux box with a disk mounted there folds case the way WSL does. matches_load_source lowercases unconditionally, so the server folds it too. The frontend agrees with what /load would have answered.

What was tested

  • The repo's own suite: 2845 pass at head, 3067 with the two new files, 0 fail. tsc -b and tsc -p tsconfig.test.json clean, biome clean on the changed files. The one formatter complaint in model-identity.ts is pre-existing at head, not from this change.
  • a2619c2c3 adds the accelerator sweep: [NVIDIA CUDA, AMD ROCm, CPU-only, Apple MLX] crossed with every field a remembered config can pin, in all three states (the resident load already runs it, it runs something else, the status cannot report it at all). The last one is the direction that must never read as agreement, and it holds. 190 cases.
  • Old installs. Config blobs written before a field existed simply lack the key, which the sweep covers; the optional ones express no opinion and adopt, tensorParallel has no unset state so an old blob missing it reloads. Conservative, and the direction that cannot lose a setting. The PR adds no persisted state: activeLoadId is in-memory, so there is nothing to migrate.
  • The 15 status fields the config gate reads were checked against a running Studio, not against the type: all 15 are present and echo what was requested. A field the status omitted would have made the gate reload forever for anyone pinning it.
  • Browsers. The before/after scene was driven end to end against a build made from the fixed tree on Chromium, Firefox and WebKit, which is the engine Safari ships. All three agree: no dialog, POST /api/inference/load 0, the running chat survives, and the control still prompts. Chrome and Edge are Chromium. The app targets ES2022 and the change adds no runtime built-in beyond what the file already used.

Does it break the old paths

No, and the shape of the change is why. Every arm can only answer "reload" more often than before, which is exactly the behaviour that existed before any of this. forceReload still skips the check, so Apply reloads and prompts. nativePathToken still skips it. A quant switch inside one repo is still a reload. Picking a different model mid-generation still raises the dialog, confirmed live on all three engines.

No hardware path changed: this is frontend TypeScript, and the GPU fields it reads are compared, never driven. The accelerator axis is covered above as data rather than as hardware, because that is all the function sees.

One thing left as a note, not a change

residentRuntimeMatchesConfig compares gpuLayers and nCpuMoe whenever the config carries them, while _runtime_matches_intent only compares them when gpu_memory_mode is manual. So a config carrying a stale layer count under Automatic reloads where the server would have said already-loaded. That is the safe direction and I could not build a live repro, so I have not touched it. Mirroring the backend there would make the fix apply slightly more often, and it is a small change if you want it.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

residentRuntimeMatchesConfig treated speculativeType, gpuMemoryMode,
gpuLayers and nCpuMoe as unpinned when the remembered config left them
unset. applyPerModelConfigToRuntime resolves all four before the load
runs (readPersistedSpeculativeType, readPersistedGpuMemoryMode,
GPU_LAYERS_AUTO, 0), and selectModel sends the resolved value, so an
unset field is not silence: a real /load would have carried the standing
preference and could differ from the resident server.

Compare the resolved value on both sides instead. The caller supplies
the four defaults plus normalizeSpeculativeType, so the module stays a
leaf the node suite can drive.
Same code, fewer lines of prose: the four 150 to 200 char single-line
comments in selectModel are wrapped, and the docblocks that restated the
same point twice say it once. 62 fewer comment lines across the seven
files this PR touches.

Verified by AST comparison rather than by eye: each file is parsed with
the TypeScript compiler and reprinted with removeComments, and every one
of the seven is identical to its previous revision. Suite still 3067
pass / 0 fail, tsc clean, and no new biome findings (the two in
use-chat-model-runtime.ts are pre-existing at head).
residentRuntimeMatchesConfig treated an unset customContextLength,
kvCacheDtype, mlxKvBits, specDraftNMax, nParallel, nBatch, nUbatch,
chatTemplateOverride or selectedGpuIds as no opinion. It is one:
applyModelLoadConfigToRuntime writes the config over the runtime store
before selectModel runs (chat-page.tsx:3242, hub-page.tsx:1329) and
resolves each of these with ?? null, so the snapshot performLoad takes
reads null rather than inheriting the resident model's value. A real
/load would send null and the backend would size the model from
scratch, which is a different invocation from a server pinned to an
explicit context, KV dtype, slot count, batch size, template or GPU.

llamaExtraArgs stays conditionally pinned: it is the one field with no
?? null fallback, so undefined really does mean this copy never read it.

The accelerator fixtures move with it. A default load requests no
particular GPU and no MLX KV width, so those bases echo null; a pinned
pool and a pinned width are swept as fields like everything else.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two things the resident shortcut let slip.

maxSeqLength is a client-side generation cap that no status field
echoes, so applyActiveModelStatusToStore cannot correct it and the
rollback that makes the panel agree with the resident server has the
last word. That rollback carries the OUTGOING model's cap, so
re-picking a resident model after an external provider silently changed
truncation. Re-apply the pick's own cap after the rollback.

_runtime_matches_intent deliberately answers False for a retryable
drafter failure so the next identical load repairs it. Skipping the
load suppressed that and left speculation off with nothing to retry it.
residentSpeculativeNeedsRepair declines the shortcut for the reasons
the backend actually retries, drafter_not_found and the two binary
stand-downs, and only when the pick asks for a drafter at all. The
Auto-mode policy downgrades are excluded on purpose: they never repair,
so treating them as retryable would prompt to stop running chats on
every re-pick, which is the bug this PR fixes.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…s for PR unslothai#8943

Two ways the resident shortcut could skip a load the backend was going
to perform.

performLoad sends reconcilePersistedGpuIds(selectedGpuIds,
selectedGpuIndexKind), not the saved pick: a selection saved in another
index namespace, or naming GPUs that are gone, becomes Automatic before
/load. The residency comparison read the raw ids, so a saved physical
[1] adopted a server pinned to Vulkan device 1, and an unreconcilable
pick reloaded where the load would have agreed. The reconciler is passed
in with the device cache warmed first, since load-on-selection can run
before any GPU hook mounted and a cold cache passes the pick through
unvalidated.

adopt_load_intent_if_matched forces a reload when
memory_state_satisfies_settings fails or the launched VRAM fraction
differs from the active one. Both are server-wide, so a Model Memory or
budget save between two picks of one model leaves the pick, its config
and the status identical, and the setting never reached the child. The
gate now reads both reload_required flags, and only an explicit true
declines, so a failed read or a backend without the endpoints keeps the
shortcut exactly as it was.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

…8943

_reuse_loaded_gguf refuses its own already-loaded answer while
_audio_probed is false, so load_model reaches its fast path and re-probes
there. Nothing else re-probes, so a shortcut that skips /load leaves the
model's audio capabilities undetected for as long as the server runs.
That is a silent loss rather than one extra reload, which is why it is
worth a status field.

audio_probe_pending is reported with the same True default the route
reads it with, so a backend that never tracked the probe is not mistaken
for one with an outstanding probe, and only an explicit true declines the
shortcut. The check sits inside the residency verdict, so the re-read
before adopting judges it again.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to mahiatlinux/unsloth that referenced this pull request Aug 16, 2026
…r PR unslothai#8943

The two failures are not symmetric, which is what my original wording
missed. One extra reload costs the prompt this PR removes; adopting on a
read that failed right after the user changed the Model Memory policy or
the VRAM budget leaves the child on the old one with nothing on screen to
say so.

An absent route is still not a failed read, so a backend too old to serve
either keeps the shortcut. Both fetchers now raise
SettingsRouteAbsentError on a 404, and the budget reader gained a rethrow
option for the one caller that has to tell them apart: it answers null for
both, which every other caller is right to treat alike, since they paint
rather than decide. The predicate takes three states now instead of a
nullable one.

Two source-shape tests move with it. The VRAM one pinned the catch as
having no binding; the residency one anchored its slice on the first
 in the file, which is above that branch now.
…r PR unslothai#8943

The two failures are not symmetric, which is what my original wording
missed. One extra reload costs the prompt this PR removes; adopting on a
read that failed right after the user changed the Model Memory policy or
the VRAM budget leaves the child on the old one with nothing on screen to
say so.

An absent route is still not a failed read, so a backend too old to serve
either keeps the shortcut. Both fetchers now raise
SettingsRouteAbsentError on a 404, and the budget reader gained a rethrow
option for the one caller that has to tell them apart: it answers null for
both, which every other caller is right to treat alike, since they paint
rather than decide. The predicate takes three states now instead of a
nullable one.

Two source-shape tests move with it. The VRAM one pinned the catch as
having no binding; the residency one anchored its slice on the first
catch-with-binding in the file, which is above that branch now.
@danielhanchen
danielhanchen force-pushed the fix/studio-model-switch-loaded-check branch from d5ba940 to 6b94038 Compare August 16, 2026 13:56
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…nslothai#8943

The drafter_not_found arm of _runtime_matches_intent is guarded on
intent.gguf_path being None, and the route derives that field from the
identifier alone, so a directly loaded file dedupes rather than retrying
the fetch. Declining the shortcut for it reproduced the prompt this PR
removes.

The caller now tells the repair check whether the pick sends a path,
using the same endswith(".gguf") test the route uses rather than the
stricter isStandaloneGgufPath, which also demands a path-like shape. Only
this arm is excused: a binary stand-down, a DFlash retry and the
capability probe all repair whatever the pick names.

I recorded this one as remaining looseness when the rest of the arm was
mirrored, so this closes it.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… dropped for PR unslothai#8943

Two consequences of adopting where the backend would, without the side
effects the backend performs while adopting.

adopt_load_intent_if_matched records the incoming pool when it accepts a
fitted subset (_record_matching_gpu_request), so the user's narrower pick
becomes the request. Skipping /load skips that, and the hydration then
put the status's wider pool back, restoring a GPU the user had removed.
The pick's own reconciled selection is re-applied after the hydration,
in the same place and for the same reason the sequence cap already is.

diffusion_requested_ngl retains the request even when an older shim
ignored the split, so once the installed shim gains --ngl support the
same request has to go through and finally apply it.
_runtime_matches_intent rejects it for exactly that window, and the
comparison saw only the retained value. diffusion_split_supported is
published for it, answered only for a diffusion runner, since off one
there is no split to apply and False would claim the question was asked.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…i#8943

The tensor-parallel arch-gate excuse read the raw tensorParallel toggle while
the backend's comparator reads resolve_tensor_parallel, so a config asking for
a split through --split-mode tensor missed the excuse it exists for.

parse_gpu_layers_override now reports absent, a value, and malformed as three
states. The backend raises on a malformed override, so the load fails and says
so; folding it into "no override" stripped the token, found the rest agreeable
and adopted, losing the saved setting in silence.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The rollback before hydration restores the outgoing model's config, so the slot
and batch controls in the store belong to the model the tab just left. The
adopt path suppressed the model-change reseed, so a resident model running 4
slots could show the outgoing count, and the next Apply saved that over it.

Every other load parameter at that call site already treats a changed
checkpoint or variant as a model change, and the slot pair now does too.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 6327dec335

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Heads up: this merged with Repo tests (CPU) red on its own checks, and it is now failing on main, so every open PR that rebases onto main goes red with it. Three of mine are red on it right now (9019, 9058, 9062).

The failing assertion is tests/studio/test_model_picker_contracts.py:1912, in test_hydration_keeps_the_slot_control_when_readopting_the_running_model:

assert (
    "const slotsModelChanged = hydratingExistingModel && !options.readoptingSameModel;"
    in status
)

This PR changed that line to:

const slotsModelChanged = hydratingExistingModel;

and removed readoptingSameModel?: boolean; from the options type, but the contract test was not updated, so it still expects the guard.

The reason I am not just pushing a fix is that I cannot tell from here which way you want it, and the two answers are materially different:

  1. The guard is obsolete. If re-adopting a model this tab never lost should now hydrate like any other status change, then the test is stale and should be updated or removed, and the docstring on it needs rewriting since it currently describes the old rule.
  2. The guard still matters. The test's stated purpose is that re-adopting the running model must not reseed the slot control, because the controls in the store still belong to that same model. If that is still true, dropping the guard reintroduces the clobber it was added to prevent, and the fix is in the source rather than the test.

Given the PR is about not prompting to stop chats for a model that is already loaded, option 1 looks likely, but the slot-control reseed is a separate user-visible behaviour from the prompt, and I would rather ask than guess at someone else's intent.

Happy to push whichever you prefer, or leave it with you. The only thing I would ask is that it lands soon, since main being red blocks the whole queue.

One process note, said neutrally: this is the second stale source-shape contract test to reach main this week, after the prompt-queue one that #9026 repaired. These tests assert exact source strings, so any reformat or refactor of the line breaks them without the behaviour changing, and the failure gives no hint which of the two it is. Worth a separate look at whether they should assert behaviour rather than text.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Unsloth Studio doesn't keep track of locally loaded model, thinks I have to stop generation to load the model that is loaded

2 participants