Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Replace an in-flight chat model load with the latest pick (#11697)
Wasim Yousef Said466d9c50a60a
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex baa2df7abed..9bb9a093d9c 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2384,6 +2384,12 @@ export function ChatPage({);const {refresh,+ cancelLoadingForReplacement,+ invalidatePendingModelSelection,+ discardExternalReplacement,+ restoreConfigForExternalReplacement,++ isModelSelectionIntentCurrent,selectModel,ejectModel,cancelLoading,@@ -2921,7 +2927,10 @@ export function ChatPage({toast.info("This model is already loading", {description: "It's downloading as part of the load in progress.",});- } else if (wantManagerStaging) {+ // The duplicate click is the only pick this guard refuses.+ return;+ }+ if (wantManagerStaging) {const outcome = await downloadManager.requestStart({kind: DOWNLOAD_KIND.MODEL,repoId: selection.id,@@ -2946,12 +2955,11 @@ export function ChatPage({"Another download for this model is still running. Reselect it once that finishes to load it.",});}- } else {- toast.info("Another model is already loading", {- description: "Wait for it to finish or cancel it first.",- });+ return;}- return;+ // A different pick takes the slot rather than being rejected: fall through to+ // selectModel below, which cancels the pending load and keeps the working+ // checkpoint as the rollback target for the replacement.}if (wantManagerStaging) {setPendingHubAutoLoad((current) =>@@ -3197,13 +3205,56 @@ export function ChatPage({const currentVariant = store.activeGgufVariant;if (!value) return;setPendingHubAutoLoad(null);+ const isExternalSelection =+ meta?.source === "external" || isExternalModelId(value);+ const isActiveModelLoad = modelOperationInProgress || loadingModel;const isSameLoadedModel =value === currentCheckpoint &&(meta?.ggufVariant ?? null) === (currentVariant ?? null);if (isSameLoadedModel && !meta?.forceReload) {- return;+ if (!isExternalSelection) return;+ // A repeated external pick is a no-op unless it supersedes a local load. With only a+ // preflight in flight, invalidate it here even though no loading flag has been published.+ if (!isActiveModelLoad) {+ invalidatePendingModelSelection();+ return;+ }}- if (meta?.source === "external" || isExternalModelId(value)) {+ if (isExternalSelection) {+ // Any pending local preflight is stale now, even before it has published a loading run.+ const externalIntentId = invalidatePendingModelSelection();+ let externalCapabilityPatch: Partial<ReturnType<typeof useChatRuntimeStore.getState>> | null = null;+ // A local load still in flight has to be stopped by this external pick. Leaving it+ // running pins modelLoading true, which makes the composer treat even this external+ // checkpoint as unavailable, and the local run's completion would write the local+ // model's capability fields over the ones set below. The intent is invalidated before+ // the cancellation so a local run still parked in its preflight yields on wakeup+ // instead of adopting its status and starting anyway.+ if (isActiveModelLoad) {+ void cancelLoadingForReplacement(externalIntentId).then((stopped) => {+ // A newer pick already owns the store; this one must not write to it.+ if (!isModelSelectionIntentCurrent(externalIntentId)) return;+ if (!stopped) {+ // The backend is uncertain after a failed stop, so drop the rollback marker a+ // later local pick would otherwise inherit from the run that did not stop.+ discardExternalReplacement(externalIntentId);+ return;+ }+ restoreConfigForExternalReplacement(externalIntentId);+ // The cancelled run's own reconciliation clears the store checkpoint when it had+ // already unloaded the resident. The external pick is still the user's choice, so+ // put it back rather than leaving the bar naming a model that is gone.+ const live = useChatRuntimeStore.getState();+ if (live.params.checkpoint !== value) {+ live.setCheckpoint(value, null);+ }+ // Cancellation can finish after clearCheckpoint reset these fields. Reapply the+ // complete external capability/tool state computed below, not just its checkpoint.+ if (externalCapabilityPatch) {+ useChatRuntimeStore.setState(externalCapabilityPatch);+ }+ });+ }const selectedExternal = parseExternalModelId(value);const selectedProvider = selectedExternal? externalProvidersForChat.find(@@ -3311,7 +3362,7 @@ export function ChatPage({? false: (storedToolsEnabled ?? searchOnByDefault): false;- useChatRuntimeStore.setState({+ externalCapabilityPatch = {activeGgufVariant: null,...loadedContextFields(null),activeNativePathToken: null,@@ -3353,7 +3404,8 @@ export function ChatPage({? (storedWebFetchToolsEnabled ?? false): false,...(stillOnOpenRouterFree ? {} : { lastOpenRouterChosenModel: null }),- });+ };+ useChatRuntimeStore.setState(externalCapabilityPatch);return;}// Local model picked: drop any cached openrouter/free chosen model.@@ -3415,6 +3467,14 @@ export function ChatPage({modelsFromStore,stageOrLoad,view,+ modelOperationInProgress,+ loadingModel,+ cancelLoadingForReplacement,+ invalidatePendingModelSelection,+ discardExternalReplacement,+ restoreConfigForExternalReplacement,++ isModelSelectionIntentCurrent,],);const handleReloadActiveModel = useCallback(diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex 946ea49c840..b2015aaf94e 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -70,6 +70,10 @@ import {validateModel,} from "../api/chat-api";import { formatEta, formatRate } from "../utils/format-transfer";+import {+ ownsModelLoadRun,+ releaseOwnedModelLoadRun,+} from "../utils/model-load-run";import { confirmStopRunningChatsIfNeeded } from "../utils/confirm-stop-running-chats";import {requestLocalPromptQueueStop,@@ -160,6 +164,58 @@ import type {ChatModelRow,} from "../types/runtime";+type LoadingModelState = {+ id: string;+ displayName: string;+ isDownloaded?: boolean;+ isCachedLora?: boolean;+ ggufVariant?: string | null;+ nativePathToken?: string | null;+};++/** One attempt at claiming the single shared load slot. Its token lets late async+ * callbacks prove the slot is still theirs before they touch shared loading state. */+type ActiveModelLoadRun = {+ attemptId: number;+ intentId: number;+ abortController: AbortController;+ /** Stable ID sent as `load_request_id` on this run's /load and matched by+ * `cancel_load_request_id` on /unload, so a cancel binds to this attempt and to+ * no other surface's load. */+ requestId: string;+ /** The exact model_path this run POSTed to /load. /unload must name the same+ * target or the scoped cancel cannot match the registered attempt. */+ loadAttemptPath: string | null;+ cancelPromise: Promise<boolean> | null;+ rollbackCheckpoint: string | null;+ /** The outgoing model's GGUF variant, captured with the checkpoint above. clearCheckpoint()+ * drops activeGgufVariant from the store, so a replacement that has to reload the former+ * resident must carry the variant itself or it would restore the wrong artifact. */+ rollbackVariant: string | null;+ rollbackConfig?: PerModelConfig;+ /** The outgoing model's load identity must survive clearCheckpoint() for compensation. */+ rollbackLoadId: string | null;+ rollbackNativePathToken: string | null;+ rollbackNativePathExpiresAtMs: number | null;+ /** Launch settings from the outgoing resident, retained through checkpoint clearing. */+ rollbackLoadedState: ReturnType<typeof useChatRuntimeStore.getState>;+ /** Set once the preliminary unload has removed the model that was resident before+ * this load. A cancellation before this run POSTs its own /load leaves the backend+ * with nothing, so the store's checkpoint must be reconciled, not preserved. */+ residentModelUnloaded: boolean;+ forceCancelActive: boolean;+ /** Resolves once the coroutine that owns this run has unwound. Cancellation+ * holds the slot until then, so an aborted load cannot apply or restore+ * configuration while the replacement that superseded it owns the slot. */+ settledPromise: Promise<void>;+ markSettled: () => void;+};++/** The selection the user last asked for, so an await can tell it was superseded. */+let modelSelectionIntentEpoch = 0;+let pendingExternalReplacement:+ | { intentId: number; config?: PerModelConfig }+ | null = null;export type SelectedModelInput = {id: string;/** Sent as model_path in place of the id, which stays the identity the UI shows. */@@ -235,7 +291,42 @@ function sameGpuSelection(return a.length === b.length && a.every((id, index) => id === b[index]);}+/** Put the rollback snapshot back before a checkpoint is dropped. clearCheckpoint remembers+ * whatever the store holds under the checkpoint's id, and a run cancelled after its preliminary+ * unload has already applied its target's config: clearing first would persist the cancelled+ * target's settings as the former resident's durable entry. */+function restoreRollbackConfigForClear(run: ActiveModelLoadRun): void {+ if (!run.rollbackConfig) return;+ applyPerModelConfigToRuntime(run.rollbackConfig, {+ isDiffusion: useChatRuntimeStore.getState().loadedIsDiffusion,+ });+}+const approvedRemoteCodeFingerprints = new Map<string, string>();+type PendingReplacementRollback = {+ checkpoint: string | null;+ config?: PerModelConfig;+ /** True when the cancelled run had already removed the resident model with a real /unload+ * and stopped before POSTing its own /load: the cancellation reconciliation clears the store+ * checkpoint for exactly that case, so the replacement has to carry the unloaded state or it+ * would skip its compensating reload and leave nothing resident. */+ residentUnloaded?: boolean;+ /** The outgoing model's GGUF variant at the moment of cancellation, for the same reason as+ * the unloaded flag: clearCheckpoint() has already dropped it from the store. */+ variant?: string | null;+ /** Access identity needed to reload the outgoing resident after clearCheckpoint drops it. */+ loadId?: string | null;+ nativePathToken?: string | null;+ nativePathExpiresAtMs?: number | null;+ loadedState?: ReturnType<typeof useChatRuntimeStore.getState>;+};++// Cancellation can finish after a newer selection intent has already started, so the+// rollback target the replacement inherits is retained until the winner reserves its run.+let pendingReplacementRollback: PendingReplacementRollback | null = null;++/** One bounded lease-wait step: a pick waiting for a preflight holder re-checks this often. */+const PREFLIGHT_LEASE_RETRY_MS = 250;function rememberApprovedRemoteCode(checkpoint: string,fingerprint: string | null,@@ -726,6 +817,9 @@ export function useChatModelRuntime() {const loadToastDismissedRef = useRef(false);const cancelUnloadPendingRef = useRef(false);const loadLifecycleLeaseRef = useRef<ModelLifecycleLease | null>(null);+ // The run that owns the single shared load slot. Async callbacks compare their own+ // token against it, so a superseded run cannot release a newer run's slot.+ const activeLoadRunRef = useRef<ActiveModelLoadRun | null>(null);const setLoadToastDismissedState = useCallback((dismissed: boolean) => {loadToastDismissedRef.current = dismissed;@@ -752,6 +846,21 @@ export function useChatModelRuntime() {}}, [setLoadToastDismissedState]);+ const resetLoadingUiForRun = useCallback(+ (run: ActiveModelLoadRun) => {+ if (!ownsModelLoadRun(activeLoadRunRef.current, run)) return;+ // Cancellation owns the slot until /unload settles. The aborted load's+ // finally block may arrive first, but must not release that slot.+ if (run.cancelPromise) return;+ activeLoadRunRef.current = releaseOwnedModelLoadRun(+ activeLoadRunRef.current,+ run,+ );+ resetLoadingUi();+ },+ [resetLoadingUi],+ );+const renderLoadDescription = useCallback((title: string,@@ -813,48 +922,220 @@ export function useChatModelRuntime() {[refresh],);- const cancelLoading = useCallback(() => {- const model = loadingModelRef.current;- if (!model) return;- notifyLocalPromptQueueLoadFailed(loadLifecycleLeaseRef.current);- loadAbortRef.current?.abort();- loadAbortRef.current = null;- loadingModelRef.current = null;- useChatRuntimeStore.getState().clearLoadingModelPick(pickOf(model));- const tid = loadToastIdRef.current;- loadToastIdRef.current = null;- setLoadingModel(null);- setLoadProgress(null);- setLoadToastDismissedState(false);- clearCheckpoint();- if (tid != null) toast.dismiss(tid);- const isCachedOrLocal = model.isDownloaded || model.isCachedLora;- toast.info("Stopped loading model", {- description: isCachedOrLocal- ? undefined- : "The current download may still finish in the background.",- });- cancelUnloadPendingRef.current = true;- void (async () => {- try {- // Unforced on purpose: a chat may stream on the PREVIOUS model and must not be killed by- // cancelling this load. Nothing to report, since the route runs its stop-loading path first.- await unloadModel({ model_path: model.id }).catch(() => {});- // clearCheckpoint above assumed nothing was left loaded, but a forced switch keeps the previous- // model resident until /load's teardown. Take the answer from the backend.- await syncInferenceStatusToStore().catch(() => {});- } finally {- cancelUnloadPendingRef.current = false;- if (!loadingModelRef.current) {- const lease = loadLifecycleLeaseRef.current;- loadLifecycleLeaseRef.current = null;- if (lease !== null) {- useChatRuntimeStore.getState().endModelLoading(lease);+ /**+ * Stop the run that owns the slot and wait for the backend to acknowledge it.+ *+ * The abort signal alone cannot stop a load that is already POSTing, so /unload+ * is what actually interrupts it. Awaiting that answer is what lets a replacement+ * claim the slot without racing the load it replaces.+ */+ const cancelLoadRun = useCallback(+ async (+ expectedRun?: ActiveModelLoadRun,+ preserveCheckpoint = false,+ ): Promise<boolean> => {+ const run = activeLoadRunRef.current;+ if (!run || (expectedRun && !ownsModelLoadRun(run, expectedRun))) {+ return false;+ }+ if (run.cancelPromise) return run.cancelPromise;++ const model = loadingModelRef.current;+ run.abortController.abort();+ loadAbortRef.current = null;+ loadingModelRef.current = null;+ const tid = loadToastIdRef.current;+ loadToastIdRef.current = null;+ setLoadingModel(null);+ setLoadProgress(null);+ setLoadToastDismissedState(false);+ if (tid != null) toast.dismiss(tid);+ if (model) {+ useChatRuntimeStore.getState().clearLoadingModelPick(pickOf(model));+ }+ const isCachedOrLocal = model?.isDownloaded || model?.isCachedLora;+ toast.info("Stopping model load", {+ description: isCachedOrLocal+ ? undefined+ : "The current download may still finish in the background.",+ });+ const cancelPromise = (async (): Promise<boolean> => {+ try {+ // Unforced on purpose: a chat may stream on the PREVIOUS model and must not+ // be killed by cancelling this load. The route cancels a still-loading+ // model ahead of its active-generation refusal.+ //+ // Scoped to this run, and only once it has actually POSTed /load: the+ // matching cancel_load_request_id binds the unload to this attempt alone,+ // and a load whose registration has not landed yet is replayed from the+ // backend's cancel tombstone. The old second, unscoped /unload is exactly+ // what let cancellation race the load it was meant to stop.+ if (run.loadAttemptPath) {+ await unloadModel({+ model_path: run.loadAttemptPath,+ cancel_load_request_id: run.requestId,+ });+ }+ // A standalone cancellation can race before the target reaches the backend.+ // /unload then leaves the resident model untouched, so derive the UI+ // checkpoint from the backend rather than clearing it optimistically.+ if (!preserveCheckpoint) {+ clearCheckpoint();+ await refresh();+ }+ return true;+ } catch (error) {+ const detail =+ error instanceof Error ? error.message : "Unknown unload error";+ const message = `Failed to stop ${model?.displayName ?? "the model"}`;+ setModelsError(`${message}: ${detail}`);+ toast.error(message, { description: detail });+ // The request failed, so reconcile against the backend before releasing the+ // slot. The caller still receives false and must not start a replacement+ // from an uncertain backend state.+ try {+ // The unabortable /load can still land after this unload failed and make this run's+ // own target resident. Read status only once the run has stopped, or the store keeps+ // naming the old checkpoint while prompts are served by the newly loaded model.+ await run.settledPromise;+ await refresh();+ setModelsError(`${message}: ${detail}`);+ } catch (refreshError) {+ const refreshDetail =+ refreshError instanceof Error+ ? refreshError.message+ : "Unknown status refresh error";+ setModelsError(+ `${message}: ${detail}. Failed to refresh model status: ${refreshDetail}`,+ );+ }+ return false;+ } finally {+ if (ownsModelLoadRun(activeLoadRunRef.current, run)) {+ // The aborted coroutine may still be parked inside an unabortable preflight+ // await (status, a consent dialog, staged metadata). Its own abort checks stop+ // it from touching shared state, but hold the slot until it has actually+ // unwound, or a replacement could overlap the run it just replaced.+ await run.settledPromise;+ if (run.loadAttemptPath && run.forceCancelActive && !run.residentModelUnloaded) {+ try {+ const status = await getInferenceStatus();+ if ((status.loading?.length ?? 0) === 0) {+ run.residentModelUnloaded = !residentModelMatchesPick(status, {+ id: run.rollbackCheckpoint ?? "",+ loadPath: run.rollbackLoadId ?? run.rollbackCheckpoint,+ ggufVariant: run.rollbackVariant,+ });+ }+ } catch {+ // An unavailable status is inconclusive; do not clear a checkpoint blindly.+ }+ }+ // The backend may serve nothing while the store still advertises that checkpoint.+ // Reconcile before releasing the slot. The run's rollback target lives on the run,+ // not in the store, so this cannot lose the replacement's target.+ if (+ (!run.loadAttemptPath && run.residentModelUnloaded) ||+ (run.loadAttemptPath && run.forceCancelActive && run.residentModelUnloaded)+ ) {+ try {+ // The run applied its target's config before the preliminary unload, so the store+ // still names the former resident while holding the cancelled target's settings.+ restoreRollbackConfigForClear(run);+ clearCheckpoint();+ await refresh();+ } catch {+ // The cancel's own error reporting stands; the slot is still released.+ }+ }+ activeLoadRunRef.current = releaseOwnedModelLoadRun(+ activeLoadRunRef.current,+ run,+ );+ const lease = loadLifecycleLeaseRef.current;+ loadLifecycleLeaseRef.current = null;+ if (lease !== null) {+ useChatRuntimeStore.getState().endModelLoading(lease);+ }}}+ })();+ run.cancelPromise = cancelPromise;+ return cancelPromise;+ },+ [clearCheckpoint, refresh, setLoadToastDismissedState, setModelsError],+ );++ const cancelLoadingWithCheckpointPolicy = useCallback(+ (preserveCheckpoint = false): Promise<boolean> => {+ const run = activeLoadRunRef.current;+ return run+ ? cancelLoadRun(run, preserveCheckpoint)+ : Promise.resolve(false);+ },+ [cancelLoadRun],+ );++ const cancelLoading = useCallback(+ (): Promise<boolean> => cancelLoadingWithCheckpointPolicy(false),+ [cancelLoadingWithCheckpointPolicy],+ );+ /**+ * Stop the pending load so a different pick can take the slot. Preserves the+ * working checkpoint, which the replacement needs as its rollback target.+ */+ const cancelLoadingForReplacement = useCallback(+ async (intentId: number): Promise<boolean> => {+ const run = activeLoadRunRef.current;+ pendingExternalReplacement = { intentId, config: run?.rollbackConfig };+ const stopped = await cancelLoadingWithCheckpointPolicy(true);+ // The load can finish after the caller observed its store flags but before+ // cancellation captured the run. With no owner left there is nothing uncertain+ // to stop, so the replacement may proceed.+ if (!stopped && !activeLoadRunRef.current) {+ return true;}- })();- }, [clearCheckpoint, setLoadToastDismissedState]);+ if (!stopped && pendingExternalReplacement?.intentId === intentId) {+ pendingExternalReplacement = null;+ }+ return stopped;+ },+ [cancelLoadingWithCheckpointPolicy],+ );++ const invalidatePendingModelSelection = useCallback((): number => {+ modelSelectionIntentEpoch += 1;+ return modelSelectionIntentEpoch;+ }, []);++ const discardExternalReplacement = useCallback((intentId: number): void => {+ if (pendingExternalReplacement?.intentId === intentId) {+ pendingExternalReplacement = null;+ pendingReplacementRollback = null;+ }+ }, []);++ const restoreConfigForExternalReplacement = useCallback(+ (intentId: number): void => {+ const config =+ (pendingExternalReplacement?.intentId === intentId+ ? pendingExternalReplacement.config+ : undefined) ?? pendingReplacementRollback?.config;+ if (config) {+ applyPerModelConfigToRuntime(config, {+ isDiffusion: useChatRuntimeStore.getState().loadedIsDiffusion,+ });+ }+ discardExternalReplacement(intentId);+ pendingReplacementRollback = null;+ },+ [discardExternalReplacement],+ );++ const isModelSelectionIntentCurrent = useCallback(+ (intentId: number) => modelSelectionIntentEpoch === intentId,+ [],+ );const selectModel = useCallback(async (selection: string | SelectedModelInput) => {@@ -875,9 +1156,11 @@ export function useChatModelRuntime() {typeof selection === "string" ? undefined : selection.isGguf;let isDiffusion =typeof selection === "string" ? undefined : selection.isDiffusion;+ let previousConfigForReplacement =+ typeof selection === "string" ? undefined : selection.previousConfig;const restorePreviousConfig = () => {- if (typeof selection !== "string" && selection.previousConfig) {- applyPerModelConfigToRuntime(selection.previousConfig, {+ if (previousConfigForReplacement) {+ applyPerModelConfigToRuntime(previousConfigForReplacement, {isDiffusion:useChatRuntimeStore.getState().loadedIsDiffusion,});@@ -888,40 +1171,265 @@ export function useChatModelRuntime() {const keepSpeculative =typeof selection === "string" ? false : selection.keepSpeculative ?? false;const currentVariant = useChatRuntimeStore.getState().activeGgufVariant;- if (!forceReload && (!modelId || (params.checkpoint === modelId && (ggufVariant ?? null) === (currentVariant ?? null)))) {+ const initiallyLoadingSamePick =+ loadingModelRef.current?.id === modelId &&+ (loadingModelRef.current?.ggufVariant ?? null) === (ggufVariant ?? null) &&+ (loadingModelRef.current?.nativePathToken ?? null) ===+ (nativePathToken ?? null);+ if (+ !forceReload &&+ (!modelId ||+ (params.checkpoint === modelId &&+ (ggufVariant ?? null) === (currentVariant ?? null) &&+ !loadingModelRef.current &&+ !useChatRuntimeStore.getState().loadingModelPick &&+ !pendingReplacementRollback))+ ) {+ // A resident-model re-selection is still a user intent. Invalidate a local pick+ // that may be awaiting status or a confirmation before it owns a run.+ if (modelId) modelSelectionIntentEpoch += 1;+ restorePreviousConfig();+ return;+ }+ if (+ initiallyLoadingSamePick &&+ !activeLoadRunRef.current?.cancelPromise+ ) {restorePreviousConfig();return;}dismissStartToastsForModelSelection();- // A load is already in flight. If it is this exact pick (id + variant + token), ignore the- // duplicate click. If it is a DIFFERENT model, including a different GGUF variant of the same repo,- // do not start a second concurrent load and do not swallow the request: surface it so the user- // waits or cancels. Centralized here so every entry point is covered.- const bailIfLoadInFlight = (): boolean => {+ // Register the user's intent before awaiting cancellation. A superseded run's+ // error cleanup must not restore its previous config over settings the new+ // caller has already applied.+ const loadIntentId = ++modelSelectionIntentEpoch;+ const activeRunBeforeCredentials = activeLoadRunRef.current;++ const isLocal = isLocalModelPath(modelId);+ let hfToken = useChatRuntimeStore.getState().hfToken || null;+ // Credential prompts must complete before cancelling a pending run: a decline must not+ // strand the resident that run already unloaded while preparing its own Hub load.+ const mayReachHub =+ !isLocal && !isOllamaModelId(modelId) && nativePathToken == null;+ if (mayReachHub) {+ const preparedToken = await prepareHfTokenForUse(hfToken);+ if (!preparedToken.proceed) {+ if (modelSelectionIntentEpoch === loadIntentId) {+ toast.error("Model load cancelled.");+ // This pick invalidated the previous run before opening credentials. If that run+ // fails while the dialog is open, its stale-intent catch cannot restore the config+ // it staged over the still-resident model. Wait until the run settles, then reconcile+ // status if it had already unloaded its resident.+ if (activeRunBeforeCredentials) {+ void activeRunBeforeCredentials.settledPromise.then(async () => {+ if (modelSelectionIntentEpoch !== loadIntentId) return;+ if (!activeRunBeforeCredentials.residentModelUnloaded) {+ const current = useChatRuntimeStore.getState();+ if (+ current.params.checkpoint ===+ activeRunBeforeCredentials.rollbackCheckpoint+ ) {+ restoreRollbackConfigForClear(activeRunBeforeCredentials);+ }+ return;+ }+ if (activeRunBeforeCredentials.residentModelUnloaded) {+ try {+ const status = await getInferenceStatus();+ if (modelSelectionIntentEpoch !== loadIntentId) return;+ if (+ (status.loading?.length ?? 0) === 0 &&+ useChatRuntimeStore.getState().params.checkpoint ===+ activeRunBeforeCredentials.rollbackCheckpoint+ ) {+ if (!status.active_model) {+ restoreRollbackConfigForClear(activeRunBeforeCredentials);+ useChatRuntimeStore.getState().clearCheckpoint();+ } else if (+ residentModelMatchesPick(status, {+ id: activeRunBeforeCredentials.rollbackCheckpoint ?? "",+ loadPath:+ activeRunBeforeCredentials.rollbackLoadId ??+ activeRunBeforeCredentials.rollbackCheckpoint,+ ggufVariant: activeRunBeforeCredentials.rollbackVariant,+ })+ ) {+ restoreRollbackConfigForClear(activeRunBeforeCredentials);+ }+ await refresh();+ }+ } catch {+ // Preserve state when backend status is unavailable; a later refresh can reconcile it.+ }+ return;+ }+ });+ }+ }+ return;+ }+ hfToken = preparedToken.token;+ }+ if (modelSelectionIntentEpoch !== loadIntentId) return;+ // A prior run may have failed while this pick was waiting for Hub credentials. If it+ // never unloaded the resident, it could not restore its staged config after losing intent.+ if (activeRunBeforeCredentials && activeLoadRunRef.current !== activeRunBeforeCredentials) {+ const current = useChatRuntimeStore.getState();+ if (+ !activeRunBeforeCredentials.residentModelUnloaded &&+ !activeRunBeforeCredentials.loadAttemptPath &&+ current.params.checkpoint === activeRunBeforeCredentials.rollbackCheckpoint+ ) {+ if (activeRunBeforeCredentials.rollbackConfig) {+ previousConfigForReplacement = activeRunBeforeCredentials.rollbackConfig;+ restoreRollbackConfigForClear(activeRunBeforeCredentials);+ }+ } else if (+ activeRunBeforeCredentials.loadAttemptPath &&+ current.params.checkpoint != null+ ) {+ if (+ current.params.checkpoint !== activeRunBeforeCredentials.rollbackCheckpoint+ ) {+ // The prior run successfully made its target resident while credentials were open.+ previousConfigForReplacement = currentRuntimePerModelConfig({+ includeMaxSeqLength: true,+ });+ } else if (activeRunBeforeCredentials.residentModelUnloaded) {+ // A failed target load can still settle with a successful compensation reload of the+ // rollback checkpoint. Confirm that resident before snapshotting its effective config;+ // a failed compensation leaves the same checkpoint in the store but no resident.+ try {+ const status = await getInferenceStatus();+ if (+ (status.loading?.length ?? 0) === 0 &&+ residentModelMatchesPick(status, {+ id: activeRunBeforeCredentials.rollbackCheckpoint ?? "",+ loadPath:+ activeRunBeforeCredentials.rollbackLoadId ??+ activeRunBeforeCredentials.rollbackCheckpoint,+ ggufVariant: activeRunBeforeCredentials.rollbackVariant,+ })+ ) {+ previousConfigForReplacement = currentRuntimePerModelConfig({+ includeMaxSeqLength: true,+ });+ }+ } catch {+ // Keep the existing snapshot if backend status is unavailable.+ }+ }+ }+ }+++++ if (pendingReplacementRollback?.config) {+ previousConfigForReplacement = pendingReplacementRollback.config;+ }+ // The cancelled run's own rollback target is the model that was working before+ // it, not the transient state it may already have applied. Adopt that target,+ // or a failed replacement restores the wrong model's runtime settings.+ const inheritCancelledRunRollback = (cancelledRun: ActiveModelLoadRun) => {+ if (cancelledRun.rollbackConfig) {+ previousConfigForReplacement = cancelledRun.rollbackConfig;+ }+ pendingReplacementRollback = {+ checkpoint: cancelledRun.rollbackCheckpoint,+ config: previousConfigForReplacement,+ // The run really removed the resident with its own /unload, so the replacement must be+ // prepared to restore it. A POSTed /load does not undo that: the resident this rolls back+ // to is gone either way, and the cancellation reconciliation only clears the store+ // checkpoint for the pre-POST case. The variant and access identity travel with it because+ // clearCheckpoint() drops them from the store before the replacement reads them.+ residentUnloaded: cancelledRun.residentModelUnloaded,+ variant: cancelledRun.rollbackVariant ?? null,+ loadId: cancelledRun.rollbackLoadId,+ nativePathToken: cancelledRun.rollbackNativePathToken,+ nativePathExpiresAtMs: cancelledRun.rollbackNativePathExpiresAtMs,+ loadedState: cancelledRun.rollbackLoadedState,+ };+ };++ // A different pick supersedes the load in flight. Await its cancellation and the+ // backend unload before claiming the slot, then re-check: the load can settle+ // between the two, and another selection may be waiting on the same run.+ while (true) {+ const activeRun = activeLoadRunRef.current;const inFlightLoad =loadingModelRef.current ??useChatRuntimeStore.getState().loadingModelPick;- if (!inFlightLoad) return false;- // The helper form, not an inline apply: it also carries the loaded diffusion flag, which the- // restored config needs.- restorePreviousConfig();- const loadingSamePick =- inFlightLoad.id === modelId &&- (inFlightLoad.ggufVariant ?? null) === (ggufVariant ?? null) &&- (inFlightLoad.nativePathToken ?? null) === (nativePathToken ?? null);- if (loadingSamePick) return true;- const message =- "Another model is already loading. Wait for it to finish or cancel it first.";- setModelsError(message);- if (throwOnError) throw new Error(message);- toast.info("Another model is already loading", {- description: "Wait for it to finish or cancel it first.",- });- return true;- };- if (bailIfLoadInFlight()) return;+ // Cancellation clears the picker before its unload settles, yet the run keeps+ // the slot and the lifecycle lease until then. Break only when neither is left:+ // a pick arriving mid-cancel would otherwise find the lease held and be dropped.+ if (!inFlightLoad && !activeRun) break;+ if (inFlightLoad) {+ const loadingSamePick =+ inFlightLoad.id === modelId &&+ (inFlightLoad.ggufVariant ?? null) === (ggufVariant ?? null) &&+ (inFlightLoad.nativePathToken ?? null) === (nativePathToken ?? null);+ if (loadingSamePick && !activeRun?.cancelPromise) {+ restorePreviousConfig();+ return;+ }+ if (!activeRun) {+ // Published to the store but no run owns it yet: the other caller is still+ // in preflight, so this pick cannot safely take the slot from it.+ restorePreviousConfig();+ return;+ }+ }+ // Only a run that still owns the slot can be superseded; the picker-only case+ // returned above. This also narrows the run for the cancellation below.+ if (!activeRun) break;+ // Keep the working checkpoint as the rollback target for the replacement.+ // A standalone Stop still clears the selection.+ inheritCancelledRunRollback(activeRun);+ const stopped = await cancelLoadRun(activeRun, true);+ // Cancellation can settle after the slot is released, so adopt the target+ // again from the run the cancel was asked about.+ inheritCancelledRunRollback(activeRun);+ if (modelSelectionIntentEpoch !== loadIntentId) {+ if (throwOnError) {+ throw new Error("Model selection was superseded by a newer choice.");+ }+ return;+ }+ if (!stopped) {+ restorePreviousConfig();+ // The unload failed, so the backend state is uncertain and this run's rollback target+ // no longer describes what is resident. A later selection must derive its rollback from+ // the refreshed store instead of inheriting the failed run's checkpoint and config.+ pendingReplacementRollback = null;+ const message =+ "The current model could not be stopped, so the new model was not loaded.";+ setModelsError(message);+ if (throwOnError) throw new Error(message);+ return;+ }+ }+ // A local pick that is superseded by a later selection must not keep the slot.+ // The replacement loop only judges the load present when it ran. A rival pick can+ // still claim the slot during the awaits below, and it owns the resident model+ // now, so the adopt and confirm paths must yield to it rather than adopt over it.+ const rivalLoadStarted = (): boolean => {+ const rival = useChatRuntimeStore.getState().loadingModelPick;+ if (!rival) return false;+ return !(+ rival.id === modelId &&+ (rival.ggufVariant ?? null) === (ggufVariant ?? null) &&+ (rival.nativePathToken ?? null) === (nativePathToken ?? null)+ );+ };+ if (modelSelectionIntentEpoch !== loadIntentId) {+ if (throwOnError) {+ throw new Error("Model selection was superseded by a newer choice.");+ }+ return;+ }// Ask the backend, not params.checkpoint: an external pick leaves the local model resident, and// a pinned cached row loads under a name its picker row never shows.// A staged config always carries forceReload, so Apply still reloads and prompts.@@ -1032,7 +1540,6 @@ export function useChatModelRuntime() {},parallelSlots: managedFlags?.defaultParallelSlots || null,// Never a config field, so the store is the only place it can come from, and the reset clears it- // before the load reads it.splitRatio: resetsPerModelSettings? null: useChatRuntimeStore.getState().splitRatio,@@ -1061,7 +1568,10 @@ export function useChatModelRuntime() {if (confirmedStatus && adoptable(confirmedStatus)) {// Same window as the confirm below: a rival load may have started during that GET, and it owns// the resident model now.- if (bailIfLoadInFlight()) return;+ if (rivalLoadStarted()) return;+ // Same window as the confirmation below: a newer pick that could not take the+ // lease still supersedes the status this preflight was about to adopt.+ if (modelSelectionIntentEpoch !== loadIntentId) return;// Roll back the config pre-applied for the load that is not happening, before hydrating, so the// resident status wins over the staged snapshot. The helper carries the diffusion flag.restorePreviousConfig();@@ -1114,16 +1624,48 @@ export function useChatModelRuntime() {}// setCheckpoint above blanked the bar, this path returns before the post-load recount, and a// mounted thread does not rerun its history loader, so the bar would stay empty.+ // Adopting the already-resident model completes this replacement without creating a load run.+ // Consume the inherited rollback so a later selection snapshots this model's current state.+ pendingReplacementRollback = null;+void refreshContextUsage({ afterModelLoad: true });return;}}}- // Hold the lifecycle lease through confirmation and loading.- const lifecycleLease = useChatRuntimeStore- .getState()- .beginModelLoading("preparing");+ // Hold the lifecycle lease through confirmation and loading. A PREFLIGHT holder (parked on+ // the stop-running-chats confirmation) owns the lease without having published a run or a+ // picker entry, so a pick arriving now reads null from the gate while the holder later+ // yields the slot as stale -- and both picks are lost. Wait, bounded, for the holder to+ // release the lease, then claim it: the user's latest pick must not be dropped by a lease+ // whose owner is still deciding.+ let lifecycleLease: ModelLifecycleLease | null = null;+ while (lifecycleLease === null) {+ lifecycleLease = useChatRuntimeStore+ .getState()+ .beginModelLoading("preparing");+ if (lifecycleLease !== null) break;+ // This pick was itself superseded while waiting; it must not load.+ if (modelSelectionIntentEpoch !== loadIntentId) return;+ await new Promise<void>((resolve) => {+ let settled = false;+ const unsubscribe = useChatRuntimeStore.subscribe((state) => {+ if (settled || state.modelLoading) return;+ settled = true;+ unsubscribe();+ resolve();+ });+ setTimeout(() => {+ if (settled) return;+ settled = true;+ unsubscribe();+ resolve();+ }, PREFLIGHT_LEASE_RETRY_MS);+ });+ // The holder released the lease; re-claim it, or yield if this pick went stale.+ if (modelSelectionIntentEpoch !== loadIntentId) return;+ }if (lifecycleLease === null) {restorePreviousConfig();toast.info("A model is loading", {@@ -1155,14 +1697,27 @@ export function useChatModelRuntime() {}if (!stopDecision.proceed) {releasePreflightLifecycleLease();- if (typeof selection !== "string" && selection.previousConfig) {- applyPerModelConfigToRuntime(selection.previousConfig);+ // The inherited target, not this pick's own previousConfig: when this pick superseded a+ // load that had already pre-applied its settings, that field holds the superseded target's+ // transient config, and declining here would leave the resident model wearing it.+ restorePreviousConfig();+ // No load will consume this rollback after a declined confirmation. If X+ // is still resident, a later pick must snapshot its current settings instead+ // of inheriting the config captured before this cancelled replacement.+ // Keep the target when A already unloaded X, or when a newer pick owns it.+ if (+ modelSelectionIntentEpoch === loadIntentId &&+ pendingReplacementRollback?.residentUnloaded === false+ ) {+ pendingReplacementRollback = null;}return;}// Re-check the tracked picker for a load that was already starting when this lifecycle lease was acquired.try {- if (bailIfLoadInFlight()) {+ // A newer pick supersedes this preflight even though it could not claim the lease:+ // without this the stale load would start anyway and discard the user's newer choice.+ if (rivalLoadStarted() || modelSelectionIntentEpoch !== loadIntentId) {releasePreflightLifecycleLease();return;}@@ -1193,11 +1748,21 @@ export function useChatModelRuntime() {explicitIsLora ?? model?.isLora ?? loraIsAdapter ?? false;const displayName = model?.name || lora?.name || modelId;const toastDisplayName = shortModelLabel(displayName);- const currentCheckpoint =- useChatRuntimeStore.getState().params.checkpoint;- const previousCheckpoint = currentCheckpoint;- const previousVariant =- useChatRuntimeStore.getState().activeGgufVariant ?? null;+ const currentRollbackState = useChatRuntimeStore.getState();+ const inheritedPendingRollback = pendingReplacementRollback;+ if (inheritedPendingRollback?.config) {+ previousConfigForReplacement = inheritedPendingRollback.config;+ }+ const currentCheckpoint = currentRollbackState.params.checkpoint;+ // A replacement rolls back to the model the cancelled load was replacing, not+ // to whatever the store holds mid-switch.+ const previousCheckpoint = inheritedPendingRollback+ ? inheritedPendingRollback.checkpoint+ : currentCheckpoint;+ // The cancelled run captured the variant before clearCheckpoint() dropped it from the store.+ const previousVariant = inheritedPendingRollback+ ? (inheritedPendingRollback.variant ?? null)+ : (currentRollbackState.activeGgufVariant ?? null);const reloadingSameModel =previousCheckpoint === modelId &&(ggufVariant ?? null) === (previousVariant ?? null);@@ -1209,7 +1774,6 @@ export function useChatModelRuntime() {: undefined;const previousIsLora =previousModel?.isLora ?? (previousLora?.exportType === "lora");- const isLocal = isLocalModelPath(modelId);const isCachedLora = isLora && isLocal;let loadingDescription = [currentCheckpoint ? "Switching models." : null,@@ -1240,7 +1804,50 @@ export function useChatModelRuntime() {loadingModelRef.current = loadInfo;const abortCtrl = new AbortController();loadAbortRef.current = abortCtrl;- let hfToken = useChatRuntimeStore.getState().hfToken || null;+ // Settlement is the last act of this run's coroutine: the resolver is assigned+ // synchronously here, so a cancel can await it even while the run is parked in an+ // unabortable preflight await.+ let markLoadRunSettled = () => {};+ const loadRunSettled = new Promise<void>((resolve) => {+ markLoadRunSettled = resolve;+ });+ // Claim the slot for this attempt. Every late callback below proves it still+ // owns the run before it touches shared loading state.+ const loadRun: ActiveModelLoadRun = {+ attemptId: loadIntentId,+ intentId: loadIntentId,+ abortController: abortCtrl,+ cancelPromise: null,+ rollbackCheckpoint: previousCheckpoint,+ rollbackConfig: previousConfigForReplacement,+ // Carried on the run, not read from the store later: clearCheckpoint() drops the store's+ // activeGgufVariant before a replacement can derive the prior model's variant.+ rollbackVariant: previousVariant,+ // Captured before clearCheckpoint can erase the working model's access identity.+ rollbackLoadId: inheritedPendingRollback+ ? inheritedPendingRollback.loadId ?? null+ : currentRollbackState.activeLoadId ?? null,+ rollbackNativePathToken: inheritedPendingRollback+ ? inheritedPendingRollback.nativePathToken ?? null+ : currentRollbackState.activeNativePathToken ?? null,+ rollbackNativePathExpiresAtMs: inheritedPendingRollback+ ? inheritedPendingRollback.nativePathExpiresAtMs ?? null+ : currentRollbackState.activeNativePathExpiresAtMs ?? null,+ rollbackLoadedState: inheritedPendingRollback?.loadedState ?? currentRollbackState,+ // An inherited rollback target whose model the cancelled run already unloaded: the backend+ // has nothing resident, so a failure below must restore it rather than find it still there.+ residentModelUnloaded: inheritedPendingRollback?.residentUnloaded === true,+ forceCancelActive,+ settledPromise: loadRunSettled,+ markSettled: markLoadRunSettled,++ requestId: crypto.randomUUID(),+ loadAttemptPath: null,+ };+ activeLoadRunRef.current = loadRun;+ // The winning intent reserved the slot, so the inherited rollback target is+ // no longer pending.+ pendingReplacementRollback = null;const postLoadRefresh = { needed: false };let progressModelIds = [modelId];let mlxLoadProgress = false;@@ -1248,25 +1855,13 @@ export function useChatModelRuntime() {let cpuFallbackReason: CpuFallbackReason | null = null;let mmprojFallbackReason: MmprojFallbackReason | null = null;try {- // Hoisted out of performLoad's GGUF branch for the progress pollers, but kept off loads that never- // reach the Hub: it validates over the network and can block on a dialog, and a stale Settings- // token must not gate a local or cached-LoRA load. An Ollama row's id is an opaque- // `ollama-manifest:` reference rather than a path, so isLocalModelPath does not recognise it.- const mayReachHub =- !isLocal && !isOllamaModelId(modelId) && nativePathToken == null;- if (mayReachHub) {- const preparedToken = await prepareHfTokenForUse(hfToken);- if (!preparedToken.proceed) {- // Lands in the outer catch (banner only); no load toast exists yet.- toast.error("Model load cancelled.");- throw new Error("Model load cancelled.");- }- hfToken = preparedToken.token;- }-async function performLoad(): Promise<void> {if (abortCtrl.signal.aborted) throw new Error("Cancelled");- let previousWasUnloaded = false;+ // The cancelled run may already have unloaded the model this load rolls back to, and its+ // cancellation reconciled the store checkpoint to empty for exactly that case. Without+ // this the compensating reload below would be skipped and no model left resident.+ let previousWasUnloaded =+ inheritedPendingRollback?.residentUnloaded === true;const pendingLoadConfig =typeof selection !== "string" ? selection.config : undefined;// The outgoing model's slot INTENT (blank = follow the server default), which the resolved baseline@@ -1274,37 +1869,40 @@ export function useChatModelRuntime() {// read before the staged-metadata await so a change cannot perturb it. Unlike tensorParallel,// vision does NOT survive a model switch: it is per-model config defaulting to vision on, so a// target that saved none gets that default. The dedupe above builds its own view of an- // unconfigured switch from DEFAULT_PER_MODEL_CONFIG, and resetsPerModelSettings cannot repair it.+ // Every rollback read below uses the INHERITED target, never this pick's own+ // `selection.previousConfig`: when this pick superseded a load that had already+ // pre-applied its settings, that field holds the superseded target's transient config,+ // and a rollback would restore the resident model wearing the wrong model's settings.+ // `previousConfigForReplacement` already carries the resident model's own config.+ const rollbackConfig = previousConfigForReplacement;const previousNParallel =- typeof selection !== "string" && selection.previousConfig- ? (selection.previousConfig.nParallel ?? null)+ rollbackConfig+ ? (rollbackConfig.nParallel ?? null): useChatRuntimeStore.getState().nParallel;const previousReasoningBudget =- typeof selection !== "string" && selection.previousConfig- ? selection.previousConfig.reasoningBudget+ rollbackConfig+ ? rollbackConfig.reasoningBudget: useChatRuntimeStore.getState().reasoningBudget;const previousReasoningBudgetMessage =- typeof selection !== "string" && selection.previousConfig- ? selection.previousConfig.reasoningBudgetMessage+ rollbackConfig+ ? rollbackConfig.reasoningBudgetMessage: useChatRuntimeStore.getState().reasoningBudgetMessage;const previousNBatch =- typeof selection !== "string" && selection.previousConfig- ? (selection.previousConfig.nBatch ?? null)+ rollbackConfig+ ? (rollbackConfig.nBatch ?? null): useChatRuntimeStore.getState().nBatch;const previousNUbatch =- typeof selection !== "string" && selection.previousConfig- ? (selection.previousConfig.nUbatch ?? null)+ rollbackConfig+ ? (rollbackConfig.nUbatch ?? null): useChatRuntimeStore.getState().nUbatch;// The outgoing tuning intent, read the same way and for the same reason: a rollback restores the// control, not the echo.const previousServerTuning: ServerTuningValues =- typeof selection !== "string" && selection.previousConfig- ? selection.previousConfig- : useChatRuntimeStore.getState();+ rollbackConfig ?? useChatRuntimeStore.getState();// Same reason: the rollback echo would overwrite an edit staged against it.const previousMlxKvBits =- typeof selection !== "string" && selection.previousConfig- ? (selection.previousConfig.mlxKvBits ?? null)+ rollbackConfig+ ? (rollbackConfig.mlxKvBits ?? null): useChatRuntimeStore.getState().mlxKvBits;if (isGguf && isDiffusion === undefined) {// Prepare the token exactly as validateModel/loadModel do: the Hub rejects an invalid@@ -1319,6 +1917,9 @@ export function useChatModelRuntime() {})).isDiffusion;}+ // The staged-metadata read cannot be aborted, so a replacement picked while it+ // was outstanding would otherwise have this load's config applied over it.+ if (abortCtrl.signal.aborted) throw new Error("Cancelled");const targetIsDiffusion = isDiffusion === true;if (pendingLoadConfig) {applyPerModelConfigToRuntime(pendingLoadConfig, {@@ -1328,6 +1929,7 @@ export function useChatModelRuntime() {const currentCheckpoint =useChatRuntimeStore.getState().params.checkpoint;const stateBeforeUnload = useChatRuntimeStore.getState();+ const rollbackState = inheritedPendingRollback?.loadedState ?? stateBeforeUnload;const platform = usePlatformStore.getState();let trustRemoteCode = stateBeforeUnload.params.trustRemoteCode ?? false;let approvedRemoteCodeFingerprint: string | null = null;@@ -1340,9 +1942,15 @@ export function useChatModelRuntime() {);const maxSeqLength =pinnedMaxSeqLength ?? stateBeforeUnload.params.maxSeqLength;- const previousActiveNativePathToken =- stateBeforeUnload.activeNativePathToken;- const previousActiveLoadId = stateBeforeUnload.activeLoadId;+ const previousActiveNativePathToken = inheritedPendingRollback+ ? inheritedPendingRollback.nativePathToken ?? null+ : stateBeforeUnload.activeNativePathToken;+ const previousActiveLoadId = inheritedPendingRollback+ ? inheritedPendingRollback.loadId ?? null+ : stateBeforeUnload.activeLoadId;+ const previousActiveNativePathExpiresAtMs = inheritedPendingRollback+ ? inheritedPendingRollback.nativePathExpiresAtMs ?? null+ : stateBeforeUnload.activeNativePathExpiresAtMs;const previousIsGguf =previousModel?.isGguf === true|| previousVariant != null@@ -1351,9 +1959,7 @@ export function useChatModelRuntime() {// Roll back to the previous model's own context: previousConfig was snapshotted before this load// pre-applied the next model's config, so params.maxSeqLength may already be the next model's.const previousMaxSeqLength =- (typeof selection !== "string"- ? selection.previousConfig?.maxSeqLength- : null) ?? maxSeqLength;+ previousConfigForReplacement?.maxSeqLength ?? maxSeqLength;// The intent the model had, not the length it ended up at: sending the resolved length would pin a// model nobody pinned. The resident backend's own answer, so a native-audio checkpoint the worker// served off the MLX path does not roll back at the sentinel.@@ -1361,20 +1967,20 @@ export function useChatModelRuntime() {previousIsGguf,platform.deviceType,platform.chatOnlyReason,- stateBeforeUnload.loadedIsMlx,+ rollbackState.loadedIsMlx,);// What the outgoing model loaded with, not the control's value: a pin typed// and never applied would change a window the failed switch never touched.- const previousPin = stateBeforeUnload.loadedCustomContextLength;+ const previousPin = rollbackState.loadedCustomContextLength;// It reloads at the pin it loaded with, whichever backend served it; only// llama.cpp's placement rules override that, where they own sizing.const rollbackMaxSeqLength = previousIsGguf? resolveFitMaxSeqLength(previousIsGguf,- stateBeforeUnload.loadedGpuMemoryMode ?? "auto",- stateBeforeUnload.loadedGpuLayers ?? GPU_LAYERS_AUTO,- stateBeforeUnload.loadedCustomContextLength,- stateBeforeUnload.loadedContextLength ?? 0,+ rollbackState.loadedGpuMemoryMode ?? "auto",+ rollbackState.loadedGpuLayers ?? GPU_LAYERS_AUTO,+ rollbackState.loadedCustomContextLength,+ rollbackState.loadedContextLength ?? 0,): (previousPin ??unpinnedLoadContext(false, previousIsMlx, previousMaxSeqLength));@@ -1383,8 +1989,6 @@ export function useChatModelRuntime() {// would shadow it and undo the preparation for every load below.const previousModelRequiresTrustRemoteCode =stateBeforeUnload.modelRequiresTrustRemoteCode;- const previousActiveNativePathExpiresAtMs =- stateBeforeUnload.activeNativePathExpiresAtMs;// Snapshot the load settings at click time, before the awaits below. When the picker staged a// config payload, prefer it over the store: React may not have flushed NumericValueInput's// blur commit yet. Per-model, since a template is written against one model's tokens.@@ -1607,6 +2211,9 @@ export function useChatModelRuntime() {: {}),});isLora = validation.is_lora ?? isLora;+ // validateModel cannot be aborted either, and everything below writes shared+ // state, so stop here if a replacement superseded this load meanwhile.+ if (abortCtrl.signal.aborted) throw new Error("Cancelled");if (validation.mlx_loads_base_model) {mlxLoadProgress = true;const mlxBaseDescription = isLora@@ -1651,6 +2258,10 @@ export function useChatModelRuntime() {.consumeServerUnloadedChat()&& currentCheckpoint) {+ // The installer may unload the prior resident independently of the ordinary+ // preliminary unload. Cancellation uses the run-level marker to clear its stale+ // checkpoint and transfer the unloaded state to the replacement.+ loadRun.residentModelUnloaded = true;previousWasUnloaded = true;}if (!upgraded) {@@ -1691,6 +2302,9 @@ export function useChatModelRuntime() {// unload first and free VRAM early.if (!forceCancelActive) {await unloadModel({ model_path: currentCheckpoint });+ // Only a real /unload removes the resident model. The forced path leaves+ // it to /load, so cancellation must not treat it as gone.+ loadRun.residentModelUnloaded = true;}// Set either way: /load can still leave no model resident, and an unneeded rollback hits// already_loaded before the gate.@@ -1834,8 +2448,13 @@ export function useChatModelRuntime() {if (lifecycleLease !== null) {chatModelLifecycleGate.markLoading(lifecycleLease);}+ // Bind this attempt to its request ID before the POST, so a cancel that+ // arrives first lands as a backend tombstone the load replays against.+ loadRun.loadAttemptPath = loadPath;+const loadResponse = await loadModel({model_path: loadPath,+ load_request_id: loadRun.requestId,nativePathLease: loadNativePathLease,hf_token: hfToken,max_seq_length: loadMaxSeqLength,@@ -2220,52 +2839,52 @@ export function useChatModelRuntime() {approved_remote_code_fingerprint:approvedRemoteCodeFingerprints.get(previousCheckpoint) ?? null,chat_template_override:- stateBeforeUnload.loadedChatTemplateOverride,- cache_type_kv: stateBeforeUnload.loadedKvCacheDtype,- mlx_kv_bits: stateBeforeUnload.loadedMlxKvBitsRequested,+ rollbackState.loadedChatTemplateOverride,+ cache_type_kv: rollbackState.loadedKvCacheDtype,+ mlx_kv_bits: rollbackState.loadedMlxKvBitsRequested,speculative_type:- stateBeforeUnload.loadedSpeculativeType,+ rollbackState.loadedSpeculativeType,spec_draft_n_max:- stateBeforeUnload.loadedSpecDraftNMax,- n_parallel: stateBeforeUnload.loadedNParallel,+ rollbackState.loadedSpecDraftNMax,+ n_parallel: rollbackState.loadedNParallel,reasoning_budget:- stateBeforeUnload.loadedReasoningBudgetRequested ?? -1,+ rollbackState.loadedReasoningBudgetRequested ?? -1,reasoning_budget_message:- stateBeforeUnload.loadedReasoningBudgetMessageRequested ?? "",+ rollbackState.loadedReasoningBudgetMessageRequested ?? "",// omit unset fields: a null counts as set and would strip the previous server's extras- ...(stateBeforeUnload.loadedNBatch != null- ? { n_batch: stateBeforeUnload.loadedNBatch }+ ...(rollbackState.loadedNBatch != null+ ? { n_batch: rollbackState.loadedNBatch }: {}),- ...(stateBeforeUnload.loadedNUbatch != null- ? { n_ubatch: stateBeforeUnload.loadedNUbatch }+ ...(rollbackState.loadedNUbatch != null+ ? { n_ubatch: rollbackState.loadedNUbatch }: {}),...serverTuningLoadPayload({- loadMode: stateBeforeUnload.loadedLoadMode,+ loadMode: rollbackState.loadedLoadMode,specDraftCacheDtype:- stateBeforeUnload.loadedSpecDraftCacheDtype,- ctxCheckpoints: stateBeforeUnload.loadedCtxCheckpoints,- cacheRam: stateBeforeUnload.loadedCacheRam,+ rollbackState.loadedSpecDraftCacheDtype,+ ctxCheckpoints: rollbackState.loadedCtxCheckpoints,+ cacheRam: rollbackState.loadedCacheRam,}),// Explicit, unlike the batch pair above: the failed switch left the TARGET resident, so an// omitted field here inherits across models, which the route refuses.- ...(stateBeforeUnload.loadedLlamaExtraArgs != null- ? { llama_extra_args: stateBeforeUnload.loadedLlamaExtraArgs }+ ...(rollbackState.loadedLlamaExtraArgs != null+ ? { llama_extra_args: rollbackState.loadedLlamaExtraArgs }: {}),// Restore the previous model in the split mode it was running, not the default layer split.- tensor_parallel: stateBeforeUnload.loadedTensorParallel ?? false,+ tensor_parallel: rollbackState.loadedTensorParallel ?? false,// What the PREVIOUS server was loaded with. Not the control field, which// applyPerModelConfigToRuntime has already overwritten with the TARGET's setting, and not// loadedVisionDisabledByUser, which is narrowed to models that can do images.- disable_vision: stateBeforeUnload.loadedDisableVision ?? false,+ disable_vision: rollbackState.loadedDisableVision ?? false,// Restore the previous model's GPU Memory placement, not backend defaults.- gpu_memory_mode: stateBeforeUnload.loadedGpuMemoryMode ?? "auto",- gpu_layers: stateBeforeUnload.loadedGpuLayers ?? GPU_LAYERS_AUTO,+ gpu_memory_mode: rollbackState.loadedGpuMemoryMode ?? "auto",+ gpu_layers: rollbackState.loadedGpuLayers ?? GPU_LAYERS_AUTO,// A recovered Vulkan model needs its staged CPU-only runtime back after the failed target load// unloaded the live server.- cpu_fallback: stateBeforeUnload.loadedCpuFallback,- n_cpu_moe: stateBeforeUnload.loadedNCpuMoe ?? 0,- tensor_split: stateBeforeUnload.loadedSplitRatio ?? undefined,- gpu_ids: stateBeforeUnload.loadedGpuIds ?? undefined,+ cpu_fallback: rollbackState.loadedCpuFallback,+ n_cpu_moe: rollbackState.loadedNCpuMoe ?? 0,+ tensor_split: rollbackState.loadedSplitRatio ?? undefined,+ gpu_ids: rollbackState.loadedGpuIds ?? undefined,// The failed swap already unloaded the server those runs used.force_cancel_active: true,});@@ -2283,11 +2902,11 @@ export function useChatModelRuntime() {: null,// Restore the editable speculative knobs to the rolled-back model's; the loaded baselines come// from its reload echo.- speculativeType: stateBeforeUnload.loadedSpeculativeType ?? null,- specDraftNMax: stateBeforeUnload.loadedSpecDraftNMax ?? null,+ speculativeType: rollbackState.loadedSpeculativeType ?? null,+ specDraftNMax: rollbackState.loadedSpecDraftNMax ?? null,// Control keeps its intent; only the baseline takes the echo.nParallel: previousNParallel,- loadedNParallel: stateBeforeUnload.loadedNParallel ?? null,+ loadedNParallel: rollbackState.loadedNParallel ?? null,reasoningBudget: previousReasoningBudget,loadedReasoningBudget:rollbackResponse.reasoning_budget ?? -1,@@ -2296,29 +2915,29 @@ export function useChatModelRuntime() {rollbackResponse.reasoning_budget_message ?? "",loadedReasoningBudgetRequested:rollbackResponse.requested_reasoning_budget ??- stateBeforeUnload.loadedReasoningBudgetRequested ??+ rollbackState.loadedReasoningBudgetRequested ??-1,loadedReasoningBudgetMessageRequested:rollbackResponse.requested_reasoning_budget_message ??- stateBeforeUnload.loadedReasoningBudgetMessageRequested ??+ rollbackState.loadedReasoningBudgetMessageRequested ??"",nBatch: previousNBatch,- loadedNBatch: stateBeforeUnload.loadedNBatch ?? null,+ loadedNBatch: rollbackState.loadedNBatch ?? null,nUbatch: previousNUbatch,- loadedNUbatch: stateBeforeUnload.loadedNUbatch ?? null,+ loadedNUbatch: rollbackState.loadedNUbatch ?? null,// Same split: the controls keep the outgoing model's intent and the baselines come from what// that model was launched with.loadMode: previousServerTuning.loadMode ?? null,- loadedLoadMode: stateBeforeUnload.loadedLoadMode ?? null,+ loadedLoadMode: rollbackState.loadedLoadMode ?? null,specDraftCacheDtype:previousServerTuning.specDraftCacheDtype ?? null,loadedSpecDraftCacheDtype:- stateBeforeUnload.loadedSpecDraftCacheDtype ?? null,+ rollbackState.loadedSpecDraftCacheDtype ?? null,ctxCheckpoints: previousServerTuning.ctxCheckpoints ?? null,loadedCtxCheckpoints:- stateBeforeUnload.loadedCtxCheckpoints ?? null,+ rollbackState.loadedCtxCheckpoints ?? null,cacheRam: previousServerTuning.cacheRam ?? null,- loadedCacheRam: stateBeforeUnload.loadedCacheRam ?? null,+ loadedCacheRam: rollbackState.loadedCacheRam ?? null,loadedSpeculativeType: rollbackSpeculativeType,loadedSpecDraftNMax:rollbackResponse.spec_draft_n_max ?? null,@@ -2328,7 +2947,7 @@ export function useChatModelRuntime() {// nParallel above.mlxKvBits: previousMlxKvBits,loadedChatTemplateOverride:- stateBeforeUnload.loadedChatTemplateOverride,+ rollbackState.loadedChatTemplateOverride,...loadedGpuMemoryFields(rollbackResponse),tensorParallel: rollbackResponse.tensor_parallel ?? false,loadedTensorParallel:@@ -2337,13 +2956,13 @@ export function useChatModelRuntime() {rollbackResponse.disable_vision ?? false,// The rolled-back model's own loaded value, matching the request above field for field. Not// stateBeforeUnload.disableVision, which holds the TARGET's value by now, and not the echo either.- disableVision: stateBeforeUnload.loadedDisableVision ?? false,+ disableVision: rollbackState.loadedDisableVision ?? false,loadedVisionDisabledByUser:rollbackResponse.vision_disabled_by_user ?? false,customContextLength:- stateBeforeUnload.loadedCustomContextLength,+ rollbackState.loadedCustomContextLength,loadedCustomContextLength:- stateBeforeUnload.loadedCustomContextLength,+ rollbackState.loadedCustomContextLength,});await refresh();} catch {@@ -2661,7 +3280,7 @@ export function useChatModelRuntime() {try {const reading = await getDownloadProgress(modelId, hfToken);// Re-read AFTER the await, as pollDownload does: the load can finish or be- // cancelled in flight, and `finally` then calls resetLoadingUi().+ // cancelled in flight, and `finally` then calls resetLoadingUiForRun().if (abortCtrl.signal.aborted || !loadingModelRef.current) return false;const verdict = watchCacheMissDownload(cacheMissWatch, reading);cacheMissWatch = verdict.watch;@@ -2751,15 +3370,18 @@ export function useChatModelRuntime() {throw err;} finally {if (progressInterval) clearInterval(progressInterval);- resetLoadingUi();+ resetLoadingUiForRun(loadRun);if (postLoadRefresh.needed && !abortCtrl.signal.aborted) {void refreshContextUsage({ afterModelLoad: true });}}} catch (error) {- restorePreviousConfig();+ // A superseded run must not restore its config over the replacement's: the newer+ // selection inherited this run's rollback target and owns restoration from here.+ // Standalone cancellations keep restoring.+ if (modelSelectionIntentEpoch === loadIntentId) restorePreviousConfig();if (abortCtrl.signal.aborted) return; // User cancelled, nothing to report- resetLoadingUi();+ resetLoadingUiForRun(loadRun);const message =error instanceof Error ? error.message : "Failed to load model";setModelsError(message);@@ -2767,6 +3389,9 @@ export function useChatModelRuntime() {if (throwOnError) {throw error instanceof Error ? error : new Error(message);}+ } finally {+ // Last act of this run's coroutine: unblocks a cancellation holding the slot.+ markLoadRunSettled();}},[@@ -2776,7 +3401,7 @@ export function useChatModelRuntime() {params.checkpoint,refresh,renderLoadDescription,- resetLoadingUi,+ resetLoadingUiForRun,setLoadToastDismissedState,setModelsError,setLastModelLoadError,@@ -2859,6 +3484,11 @@ export function useChatModelRuntime() {selectModel,ejectModel,cancelLoading,+ cancelLoadingForReplacement,+ invalidatePendingModelSelection,+ discardExternalReplacement,+ restoreConfigForExternalReplacement,+ isModelSelectionIntentCurrent,loadingModel,loadProgress,loadToastDismissed,diff --git a/studio/frontend/src/features/chat/utils/model-load-run.ts b/studio/frontend/src/features/chat/utils/model-load-run.tsnew file mode 100644index 00000000000..e8f79b07833--- /dev/null+++ b/studio/frontend/src/features/chat/utils/model-load-run.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type ModelLoadRunToken = {+ attemptId: number;+};++/**+ * Async load callbacks may finish after a replacement run has started. Only+ * the run that still owns the slot may update or clear shared loading state.+ */+export function ownsModelLoadRun(+ active: ModelLoadRunToken | null,+ candidate: ModelLoadRunToken,+): boolean {+ return active?.attemptId === candidate.attemptId;+}++export function releaseOwnedModelLoadRun<T extends ModelLoadRunToken>(+ active: T | null,+ candidate: ModelLoadRunToken,+): T | null {+ return ownsModelLoadRun(active, candidate) ? null : active;+}diff --git a/studio/frontend/tests/chat-model-load-replacement.test.ts b/studio/frontend/tests/chat-model-load-replacement.test.tsnew file mode 100644index 00000000000..793acdaf154--- /dev/null+++ b/studio/frontend/tests/chat-model-load-replacement.test.ts@@ -0,0 +1,287 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Source contracts cover decisions inside a React hook whose awaits span dialogs,+// backend unload and load. Keep each regression named; share only its assertion runner.+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++const RUNTIME = fileURLToPath(new URL("../src/features/chat/hooks/use-chat-model-runtime.ts", import.meta.url));+const CHAT_PAGE = fileURLToPath(new URL("../src/features/chat/chat-page.tsx", import.meta.url));+const read = (path: string) => readFileSync(path, "utf8");+const section = (source: string, start: string, end: string) => {+ const from = source.indexOf(start);+ assert.notEqual(from, -1, `expected to find ${start}`);+ const to = source.indexOf(end, from + start.length);+ assert.notEqual(to, -1, `expected to find ${end} after ${start}`);+ return source.slice(from, to);+};+const runtime = read(RUNTIME);+const page = read(CHAT_PAGE);+const blocks = {+ runtime,+ page,+ loop: section(runtime, "// A different pick supersedes the load in flight.", "// A local pick that is superseded by a later selection must not keep the slot."),+ cancel: section(runtime, "const cancelLoadRun = useCallback(", "const cancelLoadingWithCheckpointPolicy = useCallback("),+ inherit: section(runtime, "const inheritCancelledRunRollback = (", "// A different pick supersedes the load in flight."),+ registration: section(runtime, "const loadRun: ActiveModelLoadRun = {", "activeLoadRunRef.current = loadRun;"),+ external: section(page, "if (isExternalSelection) {", "const selectedExternal = parseExternalModelId(value);"),+ picker: section(page, "if (store.modelLoading) {", "if (wantManagerStaging) {\n setPendingHubAutoLoad("),+ selection: section(runtime, "const loadIntentId = ++modelSelectionIntentEpoch;", "if (!stopped) {"),+ credentialDecline: section(runtime, "if (!preparedToken.proceed) {", "hfToken = preparedToken.token;"),+ rollbackReads: section(runtime, "// Every rollback read below uses the INHERITED target, never this pick's own", "if (isGguf && isDiffusion === undefined)"),+ rollbackReadsCode: section(runtime, "// Every rollback read below uses the INHERITED target, never this pick's own", "if (isGguf && isDiffusion === undefined)")+ .split("\n").filter((line) => !line.trimStart().startsWith("//")).join("\n"),+ loadingUiReset: section(runtime, "const resetLoadingUiForRun = useCallback(", "const renderLoadDescription = useCallback("),+ nativePathPayload: section(runtime, "const previousActiveNativePathToken =", "const previousIsGguf ="),+ credentialPostAdoption: section(+ section(runtime, "const loadIntentId = ++modelSelectionIntentEpoch;", "if (!stopped) {"),+ "activeLoadRunRef.current !== activeRunBeforeCredentials",+ "if (pendingReplacementRollback?.config)",+ ),+ rollbackClear: section(runtime, "function restoreRollbackConfigForClear(", "const approvedRemoteCodeFingerprints"),+ preliminaryUnload: section(runtime, "if (!forceCancelActive) {", "// Set either way: /load can still leave no model resident"),+ preflightLease: section(runtime, "// Hold the lifecycle lease through confirmation and loading.", "if (lifecycleLease === null) {"),+ loadGate: section(runtime, "async function performLoad(): Promise<void> {", "const pendingLoadConfig ="),+ stagedMetadata: section(runtime, "if (isGguf && isDiffusion === undefined) {", "const targetIsDiffusion = isDiffusion === true;"),+ validation: section(runtime, "const validation = await validateModel({", "if (validation.mlx_loads_base_model) {"),+ recheck: section(runtime, "// Re-check the tracked picker for a load that was already starting", "const forceCancelActive = stopDecision.forceCancelActive;"),+ terminal: section(runtime, "await performLoad();", "// Last act of this run's coroutine"),+ failedCancel: section(section(runtime, "const cancelLoadRun = useCallback(", "const cancelLoadingWithCheckpointPolicy = useCallback("), "// The request failed, so reconcile against the backend before releasing the", "return false;"),+ cancelReconcile: section(section(runtime, "const cancelLoadRun = useCallback(", "const cancelLoadingWithCheckpointPolicy = useCallback("), "if (\n (!run.loadAttemptPath", "activeLoadRunRef.current = releaseOwnedModelLoadRun("),+ externalSelection: section(page, "const isExternalSelection =", "if (isExternalSelection) {"),+ leaseWait: section(runtime, "// Hold the lifecycle lease through confirmation", "loadLifecycleLeaseRef.current = lifecycleLease;"),+ upgrade: section(runtime, "if (validation.requires_transformers_upgrade) {", "if (!upgraded) {"),+ adoption: section(runtime, "if (confirmedStatus && adoptable(confirmedStatus)) {", "// Hold the lifecycle lease through confirmation"),+ discardExternal: section(runtime, "const discardExternalReplacement =", "const restoreConfigForExternalReplacement ="),+ forcedCancel: section(runtime, "await run.settledPromise;", "activeLoadRunRef.current = releaseOwnedModelLoadRun("),+ successfulCredentialRefresh: section(runtime, "// A prior run may have failed while this pick was waiting for Hub credentials.", "if (pendingReplacementRollback?.config)"),+ externalFailure: section(page, "if (!stopped) {", "return;"),+};+type Check = readonly [keyof typeof blocks, RegExp];+type Contract = { name: string; match?: Check[]; absent?: Check[]; order?: readonly [keyof typeof blocks, ...string[]][] };+const contracts: Contract[] = [+ { name: "a different pick supersedes the pending load instead of being rejected",+ match: [["loop", /while \(true\) \{/],+ ["loop", /const stopped = await cancelLoadRun\(activeRun, true\);/],+ ["loop", /if \(!stopped\) \{/], ["loop", /if \(!inFlightLoad && !activeRun\) break;/]] },+ { name: "the pending load is stopped at the backend before the replacement claims the slot",+ match: [["cancel", /await unloadModel\(\{/],+ ["cancel", /model_path: run\.loadAttemptPath,/],+ ["cancel", /const cancelPromise = \(async \(\): Promise<boolean> => \{/], ["cancel", /return false;/],+ ["cancel", /run\.cancelPromise = cancelPromise;/],+ ["cancel", /ownsModelLoadRun\(activeLoadRunRef\.current, run\)/], ["cancel", /releaseOwnedModelLoadRun\(/]] },+ { name: "the matching request ID is threaded to both /load and its cancel",+ match: [["registration", /requestId: crypto\.randomUUID\(\),/],+ ["runtime", /load_request_id: loadRun\.requestId,/],+ ["cancel", /cancel_load_request_id: run\.requestId,/], ["cancel", /model_path: run\.loadAttemptPath,/],+ ["runtime", /loadRun\.loadAttemptPath = loadPath;/]],+ absent: [["cancel", /await unloadModel\(\{ model_path: backendLoadModelId \}\)/]] },+ { name: "the winning selection reserves the slot for its own run",+ match: [["runtime", /const activeLoadRunRef = useRef<ActiveModelLoadRun \| null>\(null\)/],+ ["runtime", /const loadIntentId = \+\+modelSelectionIntentEpoch;/], ["registration", /abortController: abortCtrl,/],+ ["registration", /cancelPromise: null,/],+ ["runtime", /activeLoadRunRef\.current = loadRun;/], ["runtime", /modelSelectionIntentEpoch !== loadIntentId/]] },+ { name: "a superseded run cannot clear a newer run's loading state",+ match: [["runtime", /resetLoadingUiForRun\(loadRun\);/],+ ["loadingUiReset", /ownsModelLoadRun\(activeLoadRunRef\.current, run\)/],+ ["loadingUiReset", /if \(run\.cancelPromise\) return;/]] , absent: [["runtime", /\n\s{10}resetLoadingUi\(\);/]] },+ { name: "rollback state is inherited from the run being replaced",+ match: [["inherit", /cancelledRun: ActiveModelLoadRun/], ["inherit", /cancelledRun\.rollbackConfig/],+ ["inherit", /pendingReplacementRollback = \{/],+ ["inherit", /checkpoint: cancelledRun\.rollbackCheckpoint/], ["runtime", /inheritCancelledRunRollback\(activeRun\);/],+ ["runtime", /inheritedPendingRollback\?\.config/],+ ["runtime", /previousCheckpoint = inheritedPendingRollback\n\s*\? inheritedPendingRollback\.checkpoint/]] },+ { name: "cacheRam stays in the load tuning snapshot",+ match: [["runtime", /cacheRam: pendingLoadConfig\?\.cacheRam \?\? stateBeforeUnload\.cacheRam,/]] },+ { name: "a pick arriving mid-cancel waits for the run that still holds the slot",+ match: [["loop", /if \(!inFlightLoad && !activeRun\) break;/], ["loop", /if \(inFlightLoad\) \{/],+ ["loop", /const stopped = await cancelLoadRun\(activeRun, true\);/]],+ absent: [["loop", /if \(!inFlightLoad\) break;/]] },+ { name: "cancelling during the preliminary unload reconciles the removed resident model",+ match: [["runtime", /residentModelUnloaded: boolean;/],+ ["runtime", /residentModelUnloaded: inheritedPendingRollback\?\.residentUnloaded === true,/], ["preliminaryUnload", /await unloadModel\(\{ model_path: currentCheckpoint \}\);/],+ ["preliminaryUnload", /loadRun\.residentModelUnloaded = true;/],+ ["cancel", /if \([\s\S]*?!run\.loadAttemptPath && run\.residentModelUnloaded[\s\S]*?clearCheckpoint\(\);[\s\S]*?await refresh\(\);/], ["cancel", /run\.residentModelUnloaded/],+ ["cancel", /activeLoadRunRef\.current = releaseOwnedModelLoadRun\(/]],+ order: [["preliminaryUnload", "await unloadModel({ model_path: currentCheckpoint });", "loadRun.residentModelUnloaded = true;"],+ ["cancel", "run.residentModelUnloaded", "activeLoadRunRef.current = releaseOwnedModelLoadRun("]] },+ { name: "a cancelled preflight keeps the slot until its coroutine unwinds",+ match: [["runtime", /settledPromise: Promise<void>;/], ["runtime", /markLoadRunSettled = resolve;/],+ ["runtime", /settledPromise: loadRunSettled,/],+ ["runtime", /markSettled: markLoadRunSettled,/], ["runtime", /\} finally \{\n\s*\/\/ Last act of this run's coroutine[\s\S]*?markLoadRunSettled\(\);/],+ ["cancel", /if \(ownsModelLoadRun\(activeLoadRunRef\.current, run\)\) \{[\s\S]*?await run\.settledPromise;/]] },+ { name: "the cancelled coroutine stops applying config after its preflight awaits",+ match: [["stagedMetadata", /await fetchGgufStagedMetadata\(/],+ ["stagedMetadata", /if \(abortCtrl\.signal\.aborted\) throw new Error\("Cancelled"\);/], ["validation", /if \(abortCtrl\.signal\.aborted\) throw new Error\("Cancelled"\);/]],+ order: [["stagedMetadata", "await fetchGgufStagedMetadata(", 'if (abortCtrl.signal.aborted) throw new Error("Cancelled");']] },+ { name: "a superseded preflight yields instead of starting the stale load",+ match: [["recheck", /if \(rivalLoadStarted\(\) \|\| modelSelectionIntentEpoch !== loadIntentId\) \{/],+ ["recheck", /releasePreflightLifecycleLease\(\);/]] },+ { name: "a superseded run does not restore its config over the replacement",+ match: [["terminal", /if \(modelSelectionIntentEpoch === loadIntentId\) restorePreviousConfig\(\);/]] },+ { name: "a failed unload reconciles only after the cancelled run has settled",+ match: [["failedCancel", /await run\.settledPromise;/],+ ["failedCancel", /await refresh\(\);/]],+ absent: [["cancel", /toast\.error\(message, \{ description: detail \}\);\s*\/\/[^\n]*\n[\s\S]{0,200}?try \{\n\s*await refresh\(\);/]],+ order: [["failedCancel", "await run.settledPromise;", "await refresh();"]] },+ { name: "clearing a cancelled run's checkpoint restores its rollback config first",+ match: [["rollbackClear", /applyPerModelConfigToRuntime\(run\.rollbackConfig,/], ["cancelReconcile", /restoreRollbackConfigForClear\(run\);/],+ ["cancelReconcile", /clearCheckpoint\(\);/]],+ order: [["cancelReconcile", "restoreRollbackConfigForClear(run);", "clearCheckpoint();"]] },+ { name: "an inherited rollback carries the already-unloaded state into the replacement",+ match: [["runtime", /residentUnloaded\?: boolean;/],+ ["inherit", /residentUnloaded: cancelledRun\.residentModelUnloaded,/], ["registration", /residentModelUnloaded: inheritedPendingRollback\?\.residentUnloaded === true,/],+ ["loadGate", /let previousWasUnloaded =\n\s*inheritedPendingRollback\?\.residentUnloaded === true;/],+ ["runtime", /if \(previousWasUnloaded && previousCheckpoint\) \{/]] },+ { name: "a failed cancellation clears the rollback the replacement would inherit",+ match: [["loop", /pendingReplacementRollback = null;/], ["loop", /if \(throwOnError\) throw new Error\(message\);/]],+ order: [["loop", "pendingReplacementRollback = null;", "if (throwOnError) throw new Error(message);"]] },+ { name: "a pick parked on a preflight lease waits for the holder instead of being lost",+ match: [["preflightLease", /beginModelLoading\("preparing"\)/],+ ["preflightLease", /if \(modelSelectionIntentEpoch !== loadIntentId\) return;/],+ ["preflightLease", /if \(settled \|\| state\.modelLoading\) return;/], ["runtime", /restorePreviousConfig\(\);\n\s*toast\.info\("A model is loading"/]],+ absent: [["preflightLease", /leaseWaitDeadline|PREFLIGHT_LEASE_WAIT_MS|Date\.now\(\) >=/]] },+ { name: "the cancelled run's GGUF variant survives into the replacement's rollback",+ match: [["inherit", /variant: cancelledRun\.rollbackVariant \?\? null,/],+ ["runtime", /rollbackVariant: string \| null;/],+ ["runtime", /inheritedPendingRollback\.variant \?\? null/], ["registration", /rollbackVariant: previousVariant,/]] },+ { name: "an unload that survived the load POST still counts as unloaded",+ match: [["inherit", /residentUnloaded: cancelledRun\.residentModelUnloaded,/]],+ absent: [["inherit", /loadAttemptPath === null/]] },+ { name: "every rollback path reads the inherited config, not this pick's own previousConfig",+ match: [["rollbackReads", /const rollbackConfig = previousConfigForReplacement;/],+ ["runtime", /previousConfigForReplacement\?\.maxSeqLength \?\? maxSeqLength;/],+ ["runtime", /restorePreviousConfig\(\);/]],+ absent: [["rollbackReadsCode", /selection\.previousConfig/]] },+ { name: "an external pick cancels the local load it replaces",+ match: [["external", /if \(isActiveModelLoad\) \{/], ["external", /if \(!isModelSelectionIntentCurrent\(externalIntentId\)\) return;/],+ ["external", /live\.setCheckpoint\(value, null\);/],+ ["external", /if \(!stopped\) \{[\s\S]*?discardExternalReplacement\(externalIntentId\);[\s\S]*?return;[\s\S]*?\}\s*restoreConfigForExternalReplacement\(externalIntentId\);/], ["external", /discardExternalReplacement\(externalIntentId\);/],+ ["page", /isModelSelectionIntentCurrent,/]],+ order: [["external", "invalidatePendingModelSelection()", "cancelLoadingForReplacement(externalIntentId)"]] },+ { name: "Hub credential cancellation cannot strand an inherited unloaded resident",+ match: [["selection", /await prepareHfTokenForUse\(/],+ ["selection", /const stopped = await cancelLoadRun\(activeRun, true\);/], ["selection", /if \(!preparedToken\.proceed\) \{[\s\S]*?return;/]],+ order: [["selection", "await prepareHfTokenForUse(", "const stopped = await cancelLoadRun(activeRun, true);"]] },+ { name: "inherited rollback preserves the resident's pin and native-path lease",+ match: [["inherit", /loadId: cancelledRun\.rollbackLoadId,/],+ ["inherit", /nativePathToken: cancelledRun\.rollbackNativePathToken,/],+ ["inherit", /nativePathExpiresAtMs: cancelledRun\.rollbackNativePathExpiresAtMs,/], ["registration", /rollbackLoadId:/],+ ["registration", /rollbackNativePathToken:/],+ ["registration", /rollbackNativePathExpiresAtMs:/], ["nativePathPayload", /inheritedPendingRollback\s*\?\s*inheritedPendingRollback\.nativePathToken/],+ ["nativePathPayload", /inheritedPendingRollback\s*\?\s*inheritedPendingRollback\.loadId/],+ ["nativePathPayload", /inheritedPendingRollback\s*\?\s*inheritedPendingRollback\.nativePathExpiresAtMs/]] },+ { name: "external picks invalidate every pending local preflight and restore full external capabilities",+ match: [["external", /invalidatePendingModelSelection\(\)/], ["page", /externalCapabilityPatch = \{/],+ ["page", /useChatRuntimeStore\.setState\(externalCapabilityPatch\);/],+ ["external", /if \(externalCapabilityPatch\) \{[\s\S]*?setState\(externalCapabilityPatch\)/]],+ order: [["external", "invalidatePendingModelSelection()", "if (isActiveModelLoad)"]] },+ { name: "latest model pick remains queued until the preflight lifecycle lease is released",+ match: [["leaseWait", /while \(lifecycleLease === null\)/], ["leaseWait", /PREFLIGHT_LEASE_RETRY_MS/]],+ absent: [["leaseWait", /leaseWaitDeadline|PREFLIGHT_LEASE_WAIT_MS|Date\.now\(\) >=/]] },+ { name: "inherited rollback carries loaded launch settings into compensating reload",+ match: [["runtime", /rollbackLoadedState: inheritedPendingRollback\?\.loadedState \?\? currentRollbackState/],+ ["runtime", /loadedState: cancelledRun\.rollbackLoadedState/],+ ["runtime", /rollbackState\.loadedGpuMemoryMode/], ["runtime", /rollbackState\.loadedSpeculativeType/],+ ["runtime", /rollbackState\.loadedGpuLayers/]] },+ { name: "a Transformers upgrade unload is recorded on the active run for cancellation reconciliation",+ match: [["upgrade", /\.consumeServerUnloadedChat\(\)/],+ ["upgrade", /loadRun\.residentModelUnloaded = true;/], ["upgrade", /previousWasUnloaded = true;/]],+ order: [["upgrade", ".consumeServerUnloadedChat()", "loadRun.residentModelUnloaded = true;", "previousWasUnloaded = true;"]] },+ { name: "declined Hub credentials restore a failed superseded run's resident config",+ match: [["selection", /const activeRunBeforeCredentials = activeLoadRunRef\.current;/],+ ["credentialDecline", /activeRunBeforeCredentials\.settledPromise\.then\(/],+ ["credentialDecline", /modelSelectionIntentEpoch !== loadIntentId/], ["credentialDecline", /if \(!activeRunBeforeCredentials\.residentModelUnloaded\)/],+ ["credentialDecline", /current\.params\.checkpoint ===\s*activeRunBeforeCredentials\.rollbackCheckpoint/],+ ["credentialDecline", /restoreRollbackConfigForClear\(activeRunBeforeCredentials\)/]],+ order: [["selection", "const activeRunBeforeCredentials =", "await prepareHfTokenForUse(hfToken)"]] },+ { name: "reselecting the resident external model invalidates a pending local preflight",+ match: [["externalSelection", /const isExternalSelection =/], ["externalSelection", /if \(isSameLoadedModel && !meta\?\.forceReload\) \{/],+ ["externalSelection", /if \(!isExternalSelection\) return;/],+ ["externalSelection", /if \(!isActiveModelLoad\) \{\s*invalidatePendingModelSelection\(\);\s*return;/]] },+ { name: "status adoption consumes the inherited rollback after hydrating the resident model",+ match: [["adoption", /syncModelCapabilities\(modelId, confirmedStatus\);/], ["adoption", /pendingReplacementRollback = null;/],+ ["adoption", /void refreshContextUsage\(\{ afterModelLoad: true \}\);/]],+ order: [["adoption", "syncModelCapabilities(modelId, confirmedStatus);", "pendingReplacementRollback = null;", "void refreshContextUsage({ afterModelLoad: true });"]] },+ { name: "successful external replacement discards inherited rollback",+ match: [["discardExternal", /pendingExternalReplacement = null;\s*pendingReplacementRollback = null;/]] },+ { name: "forced cancellation reconciles resident status before preserving rollback",+ match: [["forcedCancel", /run\.forceCancelActive/],+ ["forcedCancel", /await getInferenceStatus\(\)/], ["forcedCancel", /residentModelMatchesPick\(status/],+ ["forcedCancel", /status\.loading\?\.length/]] },+ { name: "approved Hub credentials inherit a settled run rollback before replacement",+ match: [["selection", /!activeRunBeforeCredentials\.loadAttemptPath/],+ ["selection", /current\.params\.checkpoint ===\s*activeRunBeforeCredentials\.rollbackCheckpoint/]],+ order: [["selection", "await prepareHfTokenForUse(hfToken)", "activeLoadRunRef.current !== activeRunBeforeCredentials"], ["credentialPostAdoption", "previousConfigForReplacement = activeRunBeforeCredentials.rollbackConfig;", "restoreRollbackConfigForClear(activeRunBeforeCredentials);"]] },+ { name: "failed external stop discards rollback without restoring stale resident config",+ match: [["externalFailure", /discardExternalReplacement\(externalIntentId\)/]],+ absent: [["externalFailure", /restoreConfigForExternalReplacement\(externalIntentId\)/]] },+ { name: "approved Hub credentials snapshot config from a successfully settled prior load",+ match: [["successfulCredentialRefresh", /activeLoadRunRef\.current !== activeRunBeforeCredentials/],+ ["successfulCredentialRefresh", /activeRunBeforeCredentials\.loadAttemptPath/],+ ["successfulCredentialRefresh", /current\.params\.checkpoint !==\s*activeRunBeforeCredentials\.rollbackCheckpoint/], ["successfulCredentialRefresh", /previousConfigForReplacement = currentRuntimePerModelConfig\(\{\s*includeMaxSeqLength: true/]] },+ { name: "declining Hub credentials reconciles an unloaded predecessor after it settles",+ match: [["credentialDecline", /activeRunBeforeCredentials\.settledPromise\.then\(async\s*\(\)\s*=>/],+ ["credentialDecline", /if \(activeRunBeforeCredentials\.residentModelUnloaded\)/],+ ["credentialDecline", /await getInferenceStatus\(\)/], ["credentialDecline", /status\.loading\?\.length[\s\S]*?!status\.active_model[\s\S]*?clearCheckpoint\(\)/]] },+ { name: "approved Hub credentials resnapshot a successfully compensated resident",+ match: [["successfulCredentialRefresh", /activeRunBeforeCredentials\.residentModelUnloaded/],+ ["successfulCredentialRefresh", /await getInferenceStatus\(\)/],+ ["successfulCredentialRefresh", /residentModelMatchesPick\(status/], ["successfulCredentialRefresh", /previousConfigForReplacement = currentRuntimePerModelConfig\(\{\s*includeMaxSeqLength: true/]] },+];+for (const { name, match = [], absent = [], order = [] } of contracts) {+ test(name, () => {+ for (const [block, pattern] of match) assert.match(blocks[block], pattern);+ for (const [block, pattern] of absent) assert.doesNotMatch(blocks[block], pattern);+ for (const [block, ...needles] of order) {+ const offsets = needles.map((needle) => blocks[block].indexOf(needle));+ assert.ok(offsets.every((offset) => offset !== -1), `missing ordered assertion: ${needles.join(" → ")}`);+ assert.ok(offsets.every((offset, i) => i === 0 || offsets[i - 1] < offset), `incorrect order: ${needles.join(" → ")}`);+ }+ });+}++test("only the run that owns the slot may update or clear it", async () => {+ const { ownsModelLoadRun, releaseOwnedModelLoadRun } = await import("../src/features/chat/utils/model-load-run.ts");+ const run = { attemptId: 7 }, other = { attemptId: 9, label: "newer" };+ assert.equal(ownsModelLoadRun(run, { attemptId: 7 }), true);+ assert.equal(ownsModelLoadRun(run, { attemptId: 8 }), false);+ assert.equal(ownsModelLoadRun(null, { attemptId: 7 }), false);+ assert.equal(releaseOwnedModelLoadRun(other, { attemptId: 7 }), other);+ assert.equal(releaseOwnedModelLoadRun(other, { attemptId: 9 }), null);+});++test("a downloaded replacement pick falls through to selectModel", () => {+ const guard = blocks.picker;+ assert.equal((guard.match(/\breturn;/g) ?? []).length, 2, "only duplicate-click and manager-handoff returns remain");+ assert.match(guard, /The duplicate click is the only pick this guard refuses/);+ assert.doesNotMatch(guard, /Another model is already loading/);+ assert.match(page, /await selectModel\(\{/);+ assert.doesNotMatch(guard, /return;\s*\}\s*$/);+});++test("declining B before A unloads X lets C inherit X's newly edited settings", () => {+ const decline = section(runtime, "if (!stopDecision.proceed) {", "// Re-check the tracked picker for a load");+ const chooseC = section(runtime, "if (pendingReplacementRollback?.config) {", "// The cancelled run's own rollback target");+ const declineB = new Function("state", `let pendingReplacementRollback = state.pending;+ const modelSelectionIntentEpoch = state.epoch, loadIntentId = 2, stopDecision = { proceed: false };+ const releasePreflightLifecycleLease = () => { state.released = true; };+ const restorePreviousConfig = () => { state.restored = true; };+ try { ${decline} } finally { state.pending = pendingReplacementRollback; }`) as (state: { pending: { checkpoint: string; config: string; residentUnloaded: boolean } | null; epoch: number; released?: boolean; restored?: boolean }) => void;+ const selectC = new Function("state", `let pendingReplacementRollback = state.pending;+ let previousConfigForReplacement = state.fresh; ${chooseC} return previousConfigForReplacement;`) as (state: { pending: { config: string } | null; fresh: string }) => string;+ const beforeUnload = { pending: { checkpoint: "X", config: "X-old", residentUnloaded: false }, epoch: 2, released: false, restored: false };+ declineB(beforeUnload);+ assert.equal(beforeUnload.released, true);+ assert.equal(beforeUnload.restored, true);+ assert.equal(selectC({ pending: beforeUnload.pending, fresh: "X-edited" }), "X-edited");+ const afterUnload = { pending: { checkpoint: "X", config: "X-old", residentUnloaded: true }, epoch: 2 };+ declineB(afterUnload);+ assert.equal(selectC({ pending: afterUnload.pending, fresh: "no-resident" }), "X-old");+ const superseded = { pending: { checkpoint: "X", config: "X-old", residentUnloaded: false }, epoch: 3 };+ declineB(superseded);+ assert.equal(selectC({ pending: superseded.pending, fresh: "X-edited" }), "X-old");+});diff --git a/studio/frontend/tests/context-pin-survives-load.test.ts b/studio/frontend/tests/context-pin-survives-load.test.tsindex 9552cbf6203..9d4bb3e9f93 100644--- a/studio/frontend/tests/context-pin-survives-load.test.ts+++ b/studio/frontend/tests/context-pin-survives-load.test.ts@@ -536,6 +536,6 @@ test("a failed switch rolls back on the backend that served the outgoing model",// back at the auto-size sentinel, losing the context it was actually serving.assert.match(RUNTIME,- /const previousIsMlx = residentIsServedByMlx\(\s*\n\s*previousIsGguf,\s*\n\s*platform\.deviceType,\s*\n\s*platform\.chatOnlyReason,\s*\n\s*stateBeforeUnload\.loadedIsMlx,\s*\n\s*\);/,+ /const previousIsMlx = residentIsServedByMlx\(\s*\n\s*previousIsGguf,\s*\n\s*platform\.deviceType,\s*\n\s*platform\.chatOnlyReason,\s*\n\s*rollbackState\.loadedIsMlx,\s*\n\s*\);/,);});diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.tsindex 543134ec17d..999385a2db1 100644--- a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts@@ -794,7 +794,7 @@ test("a rollback restores the previous model with its arguments", () => {// without the arguments it had been running.assert.match(runtime,- /stateBeforeUnload\.loadedLlamaExtraArgs != null \? \{ llama_extra_args: stateBeforeUnload\.loadedLlamaExtraArgs \}/,+ /rollbackState\.loadedLlamaExtraArgs != null \? \{ llama_extra_args: rollbackState\.loadedLlamaExtraArgs \}/,);// And the snapshot is kept on every successful load, not only an explicit one,// taken from the server's own echo first: a reload that omits the field but setsdiff --git a/studio/frontend/tests/llama-extra-args-status-hydration.test.ts b/studio/frontend/tests/llama-extra-args-status-hydration.test.tsindex 5dfe6e8d05d..8bc59b1a052 100644--- a/studio/frontend/tests/llama-extra-args-status-hydration.test.ts+++ b/studio/frontend/tests/llama-extra-args-status-hydration.test.ts@@ -68,7 +68,7 @@ test("the baseline follows a same-model reload from elsewhere", () => {test("the rollback still resends that baseline explicitly", () => {assert.match(RUNTIME,- /stateBeforeUnload\.loadedLlamaExtraArgs != null\s*\n?\s*\? \{ llama_extra_args: stateBeforeUnload\.loadedLlamaExtraArgs \}/,+ /rollbackState\.loadedLlamaExtraArgs != null\s*\n?\s*\? \{ llama_extra_args: rollbackState\.loadedLlamaExtraArgs \}/,);});diff --git a/studio/frontend/tests/reasoning-budget-rollback.test.ts b/studio/frontend/tests/reasoning-budget-rollback.test.tsindex b1151e0bcf8..2bb18ff3f94 100644--- a/studio/frontend/tests/reasoning-budget-rollback.test.ts+++ b/studio/frontend/tests/reasoning-budget-rollback.test.ts@@ -32,12 +32,12 @@ const hydrate = new Function(const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const rollbackStart = runtime.indexOf(- "n_parallel: stateBeforeUnload.loadedNParallel,",+ "n_parallel: rollbackState.loadedNParallel,",);const rollbackEnd = runtime.indexOf("// omit unset fields:", rollbackStart);assert.ok(rollbackStart >= 0 && rollbackEnd > rollbackStart);const rollback = new Function(- "stateBeforeUnload",+ "rollbackState",`return { ${runtime.slice(rollbackStart, rollbackEnd)} };`,) as (state: State) => {reasoning_budget: number;diff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.tsindex cb48ff7c193..ba4f3f1d64e 100644--- a/studio/frontend/tests/resident-config-match.test.ts+++ b/studio/frontend/tests/resident-config-match.test.ts@@ -399,14 +399,27 @@ test("selectModel weighs the config and the lease before confirming a reload", (// written only by a completed load, so this path must not adopt one.// Widened as the gate's preamble grows: what matters is that the guard opens the block// the identity check sits in, not how many reads it makes first.+ // Scoped to the adoption short-circuit: the runtime also checks residency while+ // cancelling a superseded run, and adopting an earlier occurrence would read this+ // guard as missing.const guard = USE_CHAT_MODEL_RUNTIME.lastIndexOf("if (!forceReload && !nativePathToken) {",- identityCheck,+ confirmPrompt,);assert.ok(guard > 0,"the resident short-circuit no longer excludes native-lease picks",);+ // Scoped past the guard: the runtime also checks residency when it reconciles a+ // cancelled run, and reading the first occurrence would measure the wrong block.+ const adoptionIdentityCheck = USE_CHAT_MODEL_RUNTIME.indexOf(+ "residentModelMatchesPick(status",+ guard,+ );+ assert.ok(+ adoptionIdentityCheck > guard && adoptionIdentityCheck < confirmPrompt,+ "the resident short-circuit no longer wraps the identity check",+ );});/**diff --git a/studio/frontend/tests/vision-toggle-gating.test.ts b/studio/frontend/tests/vision-toggle-gating.test.tsindex 33c2e4719f9..5e7892c2791 100644--- a/studio/frontend/tests/vision-toggle-gating.test.ts+++ b/studio/frontend/tests/vision-toggle-gating.test.ts@@ -184,14 +184,14 @@ test("every other refusal is untouched by the new branch", () => {test("the rollback replays the loaded vision baseline, not the control or the gate", () => {const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");const replay = runtime.slice(- runtime.indexOf("tensor_parallel: stateBeforeUnload.loadedTensorParallel"),+ runtime.indexOf("tensor_parallel: rollbackState.loadedTensorParallel"),);const line = replay.slice(replay.indexOf("disable_vision:"),replay.indexOf("gpu_memory_mode:"),);assert.ok(- line.includes("stateBeforeUnload.loadedDisableVision"),+ line.includes("rollbackState.loadedDisableVision"),`rollback must replay the loaded baseline, got: ${line.trim()}`,);assert.ok(@@ -221,7 +221,7 @@ test("the rollback seeds the Vision control from the restored model, not the tarassignment.indexOf("loadedVisionDisabledByUser:"),);assert.ok(- line.includes("stateBeforeUnload.loadedDisableVision"),+ line.includes("rollbackState.loadedDisableVision"),`the control must be seeded from the restored model's loaded value, got: ${line.trim()}`,);assert.ok(diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 4a46570bdef..0885b0976d3 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -200,6 +200,26 @@ def _brace_matched_body(text: str, declaration: str) -> str:raise AssertionError(f"unbalanced braces reading {declaration!r}")+def _braced_block(text: str, declaration: str) -> str:+ """The ``{...}`` block for a declaration that is not an arrow function.++ Same reason as ``_brace_matched_body``: splitting on the declaration and keeping the+ remainder runs to end of file, so an ordering assertion inside it stays satisfied by code+ that has been moved out of the block entirely.+ """+ start = text.index(declaration)+ open_brace = text.index("{", start)+ depth = 0+ for i in range(open_brace, len(text)):+ if text[i] == "{":+ depth += 1+ elif text[i] == "}":+ depth -= 1+ if depth == 0:+ return text[open_brace : i + 1]+ raise AssertionError(f"unbalanced braces reading {declaration!r}")++def _override_lookup_candidates(*args, **kwargs) -> list[str]:"""The real override-key ladder, imported rather than grepped out of inference.py: #8702 movedit to another module unchanged and took four contract tests red with it. The module is@@ -1335,7 +1355,19 @@ def test_chat_load_prepares_hf_token_before_gguf_metadata_preflight():assert ("hf_token: useChatRuntimeStore.getState().hfToken" not in runtime), "GGUF metadata preflight must not send the unprepared stored token"- assert 'throw new Error("Model load cancelled.")' in runtime+ # A declined prompt no longer throws: it returns, and it must do so before the prepared token is+ # adopted, or a cancelled load would be counted as a Hub failure and would send the token the+ # user just refused. Brace-matched, and anchored on the branch's own LAST statement, so an early+ # return buried in the nested reconciliation callback cannot stand in for the pick's return.+ decline = _braced_block(runtime, "if (!preparedToken.proceed) {")+ assert 'toast.error("Model load cancelled.");' in decline+ assert "throw" not in decline, "a declined pick is a cancellation, not a failed load"+ body = decline.rstrip()+ assert body.endswith("}"), decline[-80:]+ assert (+ body[:-1].rstrip().endswith("return;")+ ), "the decline branch must end by returning, not by falling through to the load"+ assert runtime.index("hfToken = preparedToken.token") > runtime.index(decline) + len(decline)def test_chat_autoload_prepares_hf_token_before_gguf_metadata_preflight():@@ -2173,7 +2205,7 @@ def test_parallel_slots_setting_wired_end_to_end():assert "n_parallel: isGguf ? loadNParallel : null," in runtimeassert "n_parallel: validateNParallel," in runtimeassert "loadNParallel = pendingLoadConfig?.nParallel ?? null;" in runtime- assert "n_parallel: stateBeforeUnload.loadedNParallel," in runtime+ assert "n_parallel: rollbackState.loadedNParallel," in runtimechat_api = _read("features/chat/api/chat-api.ts")assert "n_parallel: payload.n_parallel," in chat_apicomposer = _read("features/chat/shared-composer.tsx")@@ -2426,8 +2458,11 @@ def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count(preset capture pins."""runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())assert (- 'const previousNParallel = typeof selection !== "string" && '- "selection.previousConfig ? (selection.previousConfig.nParallel ?? null) "+ # The inherited replacement's config, not this pick's own `selection.previousConfig`:+ # a superseded load's field holds its own transient target config, and restoring that+ # on the resident model's slot control would pin another model's count. Falls back to+ # the live store when no replacement was inherited.+ "const previousNParallel = rollbackConfig ? (rollbackConfig.nParallel ?? null) "": useChatRuntimeStore.getState().nParallel;" in runtime)# Matched on the call prefix, not the whole call: the staged apply also@@ -2452,8 +2487,8 @@ def test_failed_switch_rollback_restores_the_slot_intent_not_the_resolved_count(assert "nParallel: previousNParallel," in rollback# Baseline and reload payload keep the resolved count, or the rollback# recreates the previous model at a different slot count.- assert "loadedNParallel: stateBeforeUnload.loadedNParallel ?? null," in rollback- assert "n_parallel: stateBeforeUnload.loadedNParallel," in runtime+ assert "loadedNParallel: rollbackState.loadedNParallel ?? null," in rollback+ assert "n_parallel: rollbackState.loadedNParallel," in runtimedef test_batch_sizes_setting_wired_end_to_end():@@ -2486,9 +2521,9 @@ def test_batch_sizes_setting_wired_end_to_end():assert "loadNBatch = pendingLoadConfig?.nBatch ?? null;" in runtimeassert "loadNUbatch = pendingLoadConfig?.nUbatch ?? null;" in runtime# rollback re-sends a baseline only when one was asked, for the same reason- assert "{ n_batch: stateBeforeUnload.loadedNBatch }" in runtime- assert "{ n_ubatch: stateBeforeUnload.loadedNUbatch }" in runtime- assert "n_batch: stateBeforeUnload.loadedNBatch," not in runtime+ assert "{ n_batch: rollbackState.loadedNBatch }" in runtime+ assert "{ n_ubatch: rollbackState.loadedNUbatch }" in runtime+ assert "n_batch: rollbackState.loadedNBatch," not in runtimechat_api = " ".join(_read("features/chat/api/chat-api.ts").split())assert "...(payload.n_batch != null ? { n_batch: payload.n_batch } : {})," in chat_apiassert "...(payload.n_ubatch != null ? { n_ubatch: payload.n_ubatch } : {})," in chat_apidiff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.pyindex 2573e621a3b..4bbbceab2f7 100644--- a/tests/studio/test_multi_chat_prompt_queue_contract.py+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py@@ -651,10 +651,22 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():assert failure.index("if (abortCtrl.signal.aborted)") < failure.index("const rollbackResponse = await loadModel(")- cancellation = MODEL_RUNTIME.split("const cancelLoading = useCallback(", 1)[1]- assert cancellation.index("notifyLocalPromptQueueLoadFailed(") < cancellation.index(- "loadAbortRef.current?.abort()"+ # Cancellation no longer notifies from the picker's own path: it aborts the controller the run+ # owns, which sends the load coroutine into the failure handler above. That handler is the only+ # place the local queue learns the model went away, so the abort target is the contract.+ cancellation = _between(+ MODEL_RUNTIME,+ "const cancelLoading = useCallback(",+ "const cancelLoadingForReplacement = useCallback(",+ )+ assert "cancelLoadingWithCheckpointPolicy(false)" in cancellation+ cancel_run = _between(+ MODEL_RUNTIME,+ "const cancelLoadRun = useCallback(",+ "const cancelLoadingWithCheckpointPolicy = useCallback(",)+ assert "run.abortController.abort();" in cancel_run+ assert "abortCtrl.signal.aborted" in failureassert "endModelLoading(compareLifecycleLease)" in SHARED_COMPOSERassert SHARED_COMPOSER.count("releaseCompareModelLifecycle();") >= 3compare_upgrade = _between(diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.pyindex 328bef40d43..1d65c3e3679 100644--- a/tests/studio/test_new_chat_context_recount.py+++ b/tests/studio/test_new_chat_context_recount.py@@ -148,7 +148,10 @@ def _resident_fast_path() -> str:return slice_between(read(RUNTIME)," const confirmedStatus = await getInferenceStatus().catch(() => null);",- " const lifecycleLease = useChatRuntimeStore",+ # The lease claim, which the tail must not run into: the pick here never starts a load.+ # `lifecycleLease` sits inside a bounded retry loop, so its own declaration is the first+ # line that is about the load this tail does not start rather than about the adoption.+ " let lifecycleLease: ModelLifecycleLease | null = null;",)@@ -512,7 +515,12 @@ export async function adoptResidentModel(props: any): Promise<void> {// The residency decision, which this file does not measure: the caller seeds the// status it wants adopted. resident-model-match.test.ts covers the real predicate.const adoptable = (_status: any): boolean => true;- const bailIfLoadInFlight = (): boolean => false;+ // The superseded-pick guards the tail sits behind: nothing here supersedes the pick, so the+ // epoch still matches the id it was minted with and no rival holds the picker entry.+ let modelSelectionIntentEpoch = 0;+ const loadIntentId = 0;+ const rivalLoadStarted = (): boolean => false;+ let pendingReplacementRollback: any = null;const restorePreviousConfig = (): void => {};const getInferenceStatus = async (): Promise<any> => props.residentStatus;const reconcilePersistedGpuIds = (ids: any): any => ids;