Repository navigation
Fix chat model load switching (clean replacement) - #7405
Imagineer99 wants to merge 38 commits into
Conversation
# Conflicts: # studio/frontend/src/features/chat/api/chat-api.ts # studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts # studio/frontend/src/features/transformers-upgrade/hooks/use-transformers-upgrade-consent.ts # studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 654c18c050
ℹ️ 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 model = run.info; | ||
| const backendLoadModelId = run.backendLoadModelId ?? model.id; | ||
| run.abortController.abort(); | ||
| useHfTokenWarningStore.getState().resolve("cancel", run); |
There was a problem hiding this comment.
Pass the run owner to staged GGUF token preparation
When a GGUF with unknown diffusion metadata encounters an invalid HF token, performLoad calls prepareHfTokenForUse without dialogOwner, so the warning store records an undefined owner. This cancellation then supplies run; the new owner check rejects the resolution, leaving the warning open and run.completionPromise unresolved. Consequently, Cancel or selecting another model remains stuck in “Stopping model load” until the user manually answers the token dialog. Pass the run and abort signal to that earlier token-preparation call as well.
Useful? React with 👍 / 👎.
| // frontend task has observed that outcome. | ||
| await run.completionPromise; | ||
| return true; | ||
| } catch (error) { |
There was a problem hiding this comment.
Keep the load slot until failed cancellation settles
If /unload fails while an owned transformers installation is still running, this catch path skips run.completionPromise, and the subsequent finally clears the shared handle and loading slot even though the aborted load task is still awaiting the installer. Another mounted runtime can then begin a selection while the old installer may still unload the chat model and while the old task can still perform its cleanup. Await the canceled task's completion on the error path before releasing ownership, while still returning false to the attempted replacement.
Useful? React with 👍 / 👎.
| setLoadingModel(null); | ||
| setLoadProgress(null); | ||
| setLoadToastDismissedState(false); | ||
| if (!preserveCheckpoint) clearCheckpoint(); |
There was a problem hiding this comment.
Resync the resident model after standalone cancellation
When the user presses the load toast's Cancel button while a different target is still in validation, token consent, or another preflight step, /unload targets that not-yet-loading model and leaves the previous backend model resident. This line nevertheless clears the checkpoint, and unlike the old cancellation path the successful branch never refreshes inference status, so the UI reports no model while the backend continues serving the old one. Reconcile status after cancellation, or retain the checkpoint when previousCheckpointWasUnloaded is false.
Useful? React with 👍 / 👎.
| (initialInFlightLoad.ggufVariant ?? null) === (ggufVariant ?? null) && | ||
| (initialInFlightLoad.nativePathToken ?? null) === | ||
| (nativePathToken ?? null); | ||
| if (initiallyLoadingSamePick && !initialActiveRun?.cancelPromise) { |
There was a problem hiding this comment.
Requeue same-model picks during shared cancellation
When another mounted useChatModelRuntime owns a load of this pick and that shared run is already being canceled, initialActiveRun is null even though sharedModelLoadHandle.run.cancelPromise is set. This condition therefore treats the old run as an ordinary duplicate and returns. If the user reselects that model from Chat while Hub is canceling it, the cancellation finishes and a competing selection proceeds, so the user's latest same-model choice is silently lost. Check the shared run's cancellation state and enter the replacement loop instead of returning in this case.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ff1049ba36
ℹ️ 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 ( | ||
| !forceReload && | ||
| (!modelId || | ||
| (params.checkpoint === modelId && | ||
| (ggufVariant ?? null) === (currentVariant ?? null))) | ||
| ) { | ||
| restorePreviousConfig(); | ||
| return; |
There was a problem hiding this comment.
Check the in-flight pick before returning for the checkpoint
When model B is loading while model A remains in params.checkpoint, selecting A again hits this early return before the new in-flight-run logic and therefore does not cancel B; B continues and eventually replaces the model the user just selected. This also affects callers outside ChatPage that invoke selectModel directly, so the loaded-model no-op needs to account for a different active/shared load before returning.
Useful? React with 👍 / 👎.
| if (activeRun?.rollbackConfig) { | ||
| previousConfig = activeRun.rollbackConfig; |
There was a problem hiding this comment.
Use the inherited rollback configuration in cleanup
When a B load is superseded by C, this correctly replaces previousConfig with B's rollback target (the configuration for the originally loaded model A), but restorePreviousConfig and previousNParallel still read selection.previousConfig, which was captured while B's configuration was active. If C is declined or fails and A remains resident or is rolled back, the UI restores B's settings—especially its parallel-slot intent—onto A instead of A's inherited rollback configuration.
Useful? React with 👍 / 👎.
| (preserveCheckpoint = false): Promise<boolean> => { | ||
| const localRun = activeLoadRunRef.current; | ||
| if (localRun) return cancelLoadRun(localRun, preserveCheckpoint); | ||
| const shared = sharedModelLoadHandle; | ||
| return shared ? shared.cancel(preserveCheckpoint) : Promise.resolve(false); |
There was a problem hiding this comment.
Wrap cancellation before passing it to the Stop button
The new positional preserveCheckpoint parameter makes cancelLoading unsafe as the existing ModelLoadInlineStatus click callback: React passes its click event to onStop, so the event becomes a truthy preserveCheckpoint value. After the progress toast is dismissed, clicking Stop therefore takes the replacement-only path and skips backend-status reconciliation; expose a zero-argument wrapper for UI handlers or use an options object instead.
Useful? React with 👍 / 👎.
| // A standalone cancellation can race before the target reaches the | ||
| // backend. In that case /unload leaves the resident model untouched, | ||
| // so derive the UI checkpoint from the backend instead of clearing it | ||
| // optimistically. | ||
| if (!preserveCheckpoint) await refresh(); |
There was a problem hiding this comment.
Clear the checkpoint when cancellation leaves no active model
For a standalone cancellation after the pending load has already evicted the previous model, /unload leaves the backend with no active model and this refresh is expected to reconcile the UI. However, syncInferenceStatusToStore only clears capability flags in its !statusRes.active_model branch and never clears params.checkpoint, while this change removed the earlier unconditional clearCheckpoint(). The selector consequently continues to show the old model as loaded and subsequent generation attempts target a model that is no longer resident.
Useful? React with 👍 / 👎.
| const loadIntentId = ++loadIntentRef.current; | ||
| let replacementNeedsRollback = false; |
There was a problem hiding this comment.
Preserve the unloaded rollback marker between pending intents
The rollback marker exists only in this invocation until a run is reserved. If B has already unloaded model A, selecting C cancels B and sets this local flag, but while C awaits the active-generation confirmation a newer selection D sees no active/shared run and initializes its own flag to false; C then exits as superseded. If D fails validation before its preliminary unload, it skips rollback because it believes A is still resident, leaving the UI pinned to A while the backend has no model. The pending replacement intent needs to retain the inherited unloaded state application-wide until the winning run claims it.
Useful? React with 👍 / 👎.
| const preparedToken = await prepareHfTokenForUse( | ||
| useChatRuntimeStore.getState().hfToken || null, | ||
| { dialogOwner: run, signal: abortCtrl.signal }, |
There was a problem hiding this comment.
Pass the abort signal to staged GGUF metadata fetches
For a GGUF selection whose isDiffusion value is unknown, cancellation reaches the token validation here but not the immediately following fetchGgufStagedMetadata request, whose authFetch has no signal. Selecting a replacement while that remote /api/inference/validate request is slow or stalled calls cancelLoadRun, but cancellation then waits on run.completionPromise, so the replacement cannot start until the unabortable metadata request eventually finishes. Thread the run's signal through the staged-metadata API as well.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 49e508136a
ℹ️ 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".
| } else if (!statusRes.active_model && !isExternalSelectionActive) { | ||
| // specFallbackReason survives here, so clearing activeModelIsLocal | ||
| // alone would flip a local model's warning to "download failed". Every | ||
| // load path and clearCheckpoint set it, so leave it consistent. | ||
| useChatRuntimeStore.setState({ | ||
| modelRequiresTrustRemoteCode: false, | ||
| loadedIsMultimodal: false, | ||
| loadedIsDiffusion: false, | ||
| }); | ||
| // The backend is authoritative: cancellation may have evicted the | ||
| // previous model before the pending replacement reached /load. | ||
| useChatRuntimeStore.getState().clearCheckpoint(); |
There was a problem hiding this comment.
Preserve the checkpoint across idle auto-unload
When idle auto-unload is enabled, the backend intentionally reports no active_model while retaining the last model for transparent reload, and other frontend code explicitly relies on the store keeping its checkpoint across that state. Calling clearCheckpoint() here means any later refresh()—for example, opening the model selector after the idle timeout—blanks the selected model and prevents the next chat request from triggering that reload. Only explicit unload/cancellation paths should clear the checkpoint; a status response with no resident model is also the normal idle-unload state.
Useful? React with 👍 / 👎.
| const previousCheckpoint = inheritedPendingRollback | ||
| ? inheritedPendingRollback.checkpoint | ||
| : currentCheckpoint; |
There was a problem hiding this comment.
Carry the rollback model's full state into replacements
If model B's /load has returned and published B's settings/native-path token but its final refresh() is still pending, selecting C cancels B and inherits rollback checkpoint A here while the later stateBeforeUnload snapshot comes from B. If C then fails, the rollback request tries to restore A using B's loaded GPU settings, trust state, and native token; for example, a native-file A can no longer be reloaded once B replaced its token. Preserve the complete snapshot belonging to the inherited rollback checkpoint rather than combining its ID with the current store state.
Useful? React with 👍 / 👎.
| let scan: RemoteCodeScan; | ||
| try { | ||
| scan = await getRemoteCodeScan(modelName, hfToken); | ||
| scan = await getRemoteCodeScan(modelName, hfToken, signal); |
There was a problem hiding this comment.
Retain the scan result long enough to purge aborted downloads
When cancellation occurs after the remote-code scan POST has begun, aborting this fetch discards the response and enters the fallback with scanCreatedRepos: []. The backend scan performs its downloads synchronously and does not observe the client signal, so it can still populate the cache, but the subsequent aborted cleanup has no repository names to send to /discard-remote-code. This leaves custom-code metadata downloaded by an unapproved scan on disk; let the scan response finish before applying cancellation so its cleanup inventory remains available.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a5133a117a
ℹ️ 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".
| setCheckpoint(statusRes.model_identifier, statusRes.gguf_variant); | ||
| applyActiveModelStatusToStore(statusRes, { |
There was a problem hiding this comment.
Clear stale native leases when adopting an idle model
When a stale tab previously selected native-path GGUF A and another client loads and idle-unloads GGUF B, this branch changes the checkpoint to B without clearing A's activeNativePathToken. Fresh evidence on the current head is that setCheckpoint() leaves the token intact and applyActiveModelStatusToStore() clears it only for non-GGUF statuses; consequently, using Apply on B passes A's lease from handleReloadActiveModel(), and the backend resolves that lease to A's file, silently loading the wrong model under B's selection. Clear model-bound native lease state when the checkpoint or variant changes unless the status proves it is re-adopting the same native model.
Useful? React with 👍 / 👎.
| !store.modelLoading && | ||
| !store.loadingModelPick |
There was a problem hiding this comment.
Forward resident reselections to the intent invalidator
When local model B is still awaiting the status lookup or stop-chats confirmation, neither modelLoading nor loadingModelPick has been set yet. If the user reselects the resident model A through the Chat selector during that interval, this condition returns before selectModel(), so the epoch increment added to the hook's resident-model no-op path never runs and B later replaces A despite the newer choice. Fresh evidence beyond the earlier hook-level fix is that this Chat-page guard still intercepts exactly the flagless preflight state; allow the selection to reach the hook whenever a preflight intent may be pending.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23e2250a0d
ℹ️ 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".
| ...(status.is_gguf && | ||
| (!hydratingExistingModel || options.readoptingSameModel) | ||
| ? {} | ||
| : { activeNativePathToken: null, activeNativePathExpiresAtMs: null }), |
There was a problem hiding this comment.
Do not reuse a native lease based only on the display label
When two native GGUF files in different directories share a filename, Tauri gives both the same filename-only display label (native_path_policy.rs derives it from file_name()), so an idle-status adoption of file B can leave hydratingExistingModel false in a tab that previously loaded file A. This condition then preserves A's activeNativePathToken, and Apply/rollback resolves that lease to A, silently loading the wrong file. Fresh evidence beyond the prior native-lease fix is this same-label collision: model ID and variant do not prove native-file identity, so preserve the lease only with a backend-provided identity match.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a483a2c: native loads now carry an opaque token identity hash through load/status/idle state, and the frontend preserves a lease only when that backend identity matches—same-label files in different directories cannot reuse each other's lease.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
|
Confirmed this covers the path in studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts where a mid-load reselection still hits the "Another model is already loading" guard instead of replacing the pending load. The branch also rewrites the hf-auth, remote-code-consent and transformers-upgrade stores, so could you narrow it to the chat load-ownership files and rebase onto current main? |
|
Checked current main and the guard at studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts:884 is still there, so this still has a job, but the branch as it stands still carries the hf-auth, remote-code-consent and transformers-upgrade store rewrites and has not been rebased. Could you drop those three and rebase onto current main so this is just the chat load-ownership change? |
|
Live Studio A/B — defect reproduced on main, head behaves as intended Head
Confirmed; no blockers seen on this head in the live run. |
|
Screenshots for the live A/B above — reselecting a different model mid-load, head main — the reselect is refused, the first model keeps loading: Toasts read head — the in-flight load is stopped and the new pick wins: Toast reads Confirmed on both sides; no blockers seen on this head. |
|
The mid-load reselection guard is still on main at use-chat-model-runtime.ts, so this is still needed, but the branch still carries the hf-auth, remote-code-consent and transformers-upgrade store changes. Could you drop those and keep this to the chat load-ownership files so it can be reviewed on its own? |


Summary
Supersedes #7109 with the same intended change on a clean, current-
mainhistory.Why this replacement exists
The original PR branch accumulated unrelated ancestry while review fixes were being applied. This replacement preserves the audited patch while removing that ancestry and rebasing the work directly onto current
main.Validation
git diff --check