Skip to content

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.

Studio: stop a generalized compare cleanly, cancelling its in-flight model load (#7407)

Lee Jacksona790248204d9
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 09e0db14eae..2ffbf12e57a 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -355,15 +355,18 @@ export async function countChatInputTokens(payload: {
export async function validateModel(
payload: LoadModelRequest,
+ options?: { signal?: AbortSignal },
): Promise<ValidateModelResponse> {
const preparedToken = await prepareHfTokenForUse(payload.hf_token);
if (!preparedToken.proceed)
throw Object.assign(new Error("Model load cancelled."), {
unslothUserCancelled: true,
});
+ options?.signal?.throwIfAborted();
const response = await authFetch("/api/inference/validate", {
method: "POST",
headers: { "Content-Type": "application/json" },
+ signal: options?.signal,
body: JSON.stringify({
model_path: payload.model_path,
native_path_lease: payload.nativePathLease ?? null,
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 2385e4ad79b..070bbe76131 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -1066,6 +1066,7 @@ function GeneralCompareHeader({
onModelsChange,
deleteDisabled,
side,
+ label,
}: {
models: ModelOption[];
loraModels: LoraModelOption[];
@@ -1082,6 +1083,7 @@ function GeneralCompareHeader({
onModelsChange?: (deletedModel?: DeletedModelRef) => void;
deleteDisabled?: boolean;
side: "left" | "right";
+ label?: "Base Model" | "Fine-tuned";
}): ReactElement {
// Controlled so the body-portaled popover cannot linger over another tab off-route.
const active = useChatActive();
@@ -1116,10 +1118,41 @@ function GeneralCompareHeader({
open={active && selectorOpen}
onOpenChange={(open) => setSelectorOpen(active && open)}
/>
+ {label ? (
+ <span
+ className={cn(
+ "pointer-events-none hidden h-[var(--studio-chat-control-height,34px)] shrink-0 items-center text-ui-10 font-semibold uppercase tracking-wider sm:flex",
+ side === "right" && "ml-auto",
+ label === "Fine-tuned" ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ {label}
+ </span>
+ ) : null}
</div>
);
}
+/** Base Model / Fine-tuned labels when one pane is a LoRA trained on the other pane's model. */
+function generalCompareLabels(
+ loraModels: LoraModelOption[],
+ model1: CompareModelSelection,
+ model2: CompareModelSelection,
+): ["Base Model" | "Fine-tuned" | undefined, "Base Model" | "Fine-tuned" | undefined] {
+ const baseOf = (sel: CompareModelSelection) =>
+ sel.isLora
+ ? loraModels.find((lora) => lora.id === sel.id)?.baseModel
+ : undefined;
+ const isTunedFrom = (tuned: CompareModelSelection, base: CompareModelSelection) => {
+ const loraBase = baseOf(tuned);
+ return Boolean(loraBase && base.id) &&
+ normalizeModelRef(loraBase) === normalizeModelRef(base.id);
+ };
+ if (isTunedFrom(model1, model2)) return ["Fine-tuned", "Base Model"];
+ if (isTunedFrom(model2, model1)) return ["Base Model", "Fine-tuned"];
+ return [undefined, undefined];
+}
+
/** General path: any two models, sequential load → generate. */
const GeneralCompareContent = memo(function GeneralCompareContent({
pairId,
@@ -1158,10 +1191,14 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
const anyRunning = useChatRuntimeStore(
(s) => Object.keys(s.runningByThreadId).length > 0,
);
+ // A compare send is idle between the two sequential runs; a re-list there swaps the pane threads mid-send.
+ const [comparing, setComparing] = useState(false);
const listedPairRef = useRef<string | null>(null);
const [model1, setModel1] = useState<CompareModelSelection>({
id: globalCheckpoint || "",
- isLora: false,
+ isLora: loraModels.some(
+ (lora) => lora.id === globalCheckpoint && lora.exportType === "lora",
+ ),
ggufVariant: globalGgufVariant ?? undefined,
isDiffusion: globalIsDiffusion,
});
@@ -1184,7 +1221,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
);
useEffect(() => {
- if (anyRunning && listedPairRef.current === pairId) return;
+ if ((anyRunning || comparing) && listedPairRef.current === pairId) return;
listedPairRef.current = pairId;
let isActive = true;
setThreadsSettled(false);
@@ -1206,7 +1243,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
return () => {
isActive = false;
};
- }, [pairId, anyRunning]);
+ }, [pairId, anyRunning, comparing]);
useEffect(() => {
if (!threadsSettled) return;
@@ -1219,6 +1256,12 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
threadsSettled,
]);
+ const [model1Label, model2Label] = generalCompareLabels(
+ loraModels,
+ model1,
+ model2,
+ );
+
return (
<CompareShell
handlesRef={handlesRef}
@@ -1229,8 +1272,12 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
model1={model1}
model2={model2}
onExitCompare={onExitCompare}
+ onComparingChange={setComparing}
model1ThreadId={model1ThreadId}
model2ThreadId={model2ThreadId}
+ sendUnavailableReason={
+ threadsSettled ? undefined : "Loading comparison history."
+ }
/>
) : (
<></>
@@ -1250,6 +1297,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
header={
<GeneralCompareHeader
side="left"
+ label={model1Label}
models={models}
loraModels={loraModels}
externalModels={externalModels}
@@ -1285,6 +1333,7 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
header={
<GeneralCompareHeader
side="right"
+ label={model2Label}
models={models}
loraModels={loraModels}
externalModels={externalModels}
diff --git a/studio/frontend/src/features/chat/compare-run-ownership.ts b/studio/frontend/src/features/chat/compare-run-ownership.ts
new file mode 100644
index 00000000000..c056b9d59f8
--- /dev/null
+++ b/studio/frontend/src/features/chat/compare-run-ownership.ts
@@ -0,0 +1,83 @@
+// 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 CompareRun<Model> = {
+ readonly id: number;
+ readonly controller: AbortController;
+ loadingModel: Model | null;
+ cleanup: Promise<void> | null;
+};
+
+/** One generalized compare send; a stopped send can unwind after a newer one begins, so late
+ * callbacks check ownership before touching shared state. */
+export class CompareRunOwnership<Model> {
+ private nextId = 1;
+ private activeRun: CompareRun<Model> | null = null;
+
+ begin(): CompareRun<Model> {
+ this.activeRun?.controller.abort();
+ const run: CompareRun<Model> = {
+ id: this.nextId,
+ controller: new AbortController(),
+ loadingModel: null,
+ cleanup: null,
+ };
+ this.nextId += 1;
+ this.activeRun = run;
+ return run;
+ }
+
+ current(): CompareRun<Model> | null {
+ return this.activeRun;
+ }
+
+ owns(run: CompareRun<Model>): boolean {
+ return this.activeRun === run;
+ }
+
+ setLoadingModel(run: CompareRun<Model>, model: Model | null): boolean {
+ if (!this.owns(run)) {
+ return false;
+ }
+ run.loadingModel = model;
+ return true;
+ }
+
+ setCleanup(run: CompareRun<Model>, cleanup: Promise<void>): boolean {
+ if (!this.owns(run)) {
+ return false;
+ }
+ run.cleanup = cleanup;
+ return true;
+ }
+
+ cancelCurrent(): CompareRun<Model> | null {
+ const run = this.activeRun;
+ run?.controller.abort();
+ return run;
+ }
+
+ release(run: CompareRun<Model>): boolean {
+ if (!this.owns(run)) {
+ return false;
+ }
+ this.activeRun = null;
+ return true;
+ }
+}
+
+export function throwIfCompareCancelled(signal: AbortSignal): void {
+ if (signal.aborted) {
+ throw new DOMException("Compare cancelled", "AbortError");
+ }
+}
+
+export function isCompareCancellation(
+ error: unknown,
+ signal: AbortSignal,
+): boolean {
+ return (
+ signal.aborted ||
+ (error instanceof DOMException && error.name === "AbortError")
+ );
+}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 1074dbf9241..4b62be2df3d 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -131,6 +131,7 @@ import { PromptCountBadge } from "./prompt-storage/prompt-count-badge";
import { McpComposerButton } from "./mcp-composer-button";
import { PermissionModeComposerPill } from "./permission-mode-select";
import { reasoningCapsFromLoad } from "./lib/apply-inference-status-to-store";
+import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";
import { KnowledgeBaseComposerButton } from "@/features/rag/components/knowledge-base-composer-button";
import { NewProjectDialog } from "./components/new-project-dialog";
import { ChatSkillsDialog } from "./components/chat-skills-dialog";
@@ -159,9 +160,16 @@ import {
import { prepareHfTokenForUse } from "@/features/hf-auth";
import {
fetchGgufStagedMetadata,
+ getInferenceStatus,
loadModel,
+ unloadModel,
validateModel,
} from "./api/chat-api";
+import {
+ CompareRunOwnership,
+ isCompareCancellation,
+ throwIfCompareCancelled,
+} from "./compare-run-ownership";
import {
loadedContextForParams,
resolveExplicitCtxPin,
@@ -569,11 +577,29 @@ function isPortaledDrop(event: ReactDragEvent): boolean {
return !target?.closest?.(".chat-composer-surface");
}
+const LOAD_SETTLE_POLL_MS = 1000;
+const LOAD_SETTLE_TIMEOUT_MS = 15 * 60_000;
+
+/** Waits for every load, not the target by name: the backend tracks a local GGUF under a path-free id. */
+async function waitForBackendLoadToSettle(): Promise<void> {
+ const deadline = Date.now() + LOAD_SETTLE_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ try {
+ const status = await getInferenceStatus();
+ if (status.loading.length === 0) return;
+ } catch {
+ // Keep polling: an unreachable backend has not proven the load ended.
+ }
+ await new Promise((resolve) => setTimeout(resolve, LOAD_SETTLE_POLL_MS));
+ }
+}
+
export function SharedComposer({
handlesRef,
model1,
model2,
onExitCompare,
+ onComparingChange,
model1ThreadId,
model2ThreadId,
sendUnavailableReason,
@@ -583,6 +609,7 @@ export function SharedComposer({
model1?: CompareModelSelection;
model2?: CompareModelSelection;
onExitCompare?: () => void;
+ onComparingChange?: (comparing: boolean) => void;
model1ThreadId?: string;
model2ThreadId?: string;
sendUnavailableReason?: string;
@@ -672,6 +699,9 @@ export function SharedComposer({
const prevRunningRef = useRef(false);
const prevComparingRef = useRef(false);
const compareStepSucceededRef = useRef(false);
+ const compareRunsRef = useRef(
+ new CompareRunOwnership<{ modelPath: string; requestId: string }>(),
+ );
const sendRef = useRef<(() => void) | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const pendingFixPrompt = useChatArtifactsStore(
@@ -1430,6 +1460,8 @@ export function SharedComposer({
}
audioUpload.cancel();
clearSubmittedDraft();
+ const run = compareRunsRef.current.begin();
+ const compareSignal = run.controller.signal;
// Set when an accepted transformers install unloaded the active model server-side; a later
// failure must then clear the stale checkpoint.
let upgradeUnloadedActive = false;
@@ -1450,6 +1482,7 @@ export function SharedComposer({
async function ensureModelLoaded(
sel: CompareModelSelection,
): Promise<string> {
+ throwIfCompareCancelled(compareSignal);
const currentStore = useChatRuntimeStore.getState();
const config = sel.config ?? null;
// This pane's effective config: an explicit selection config, else the remembered store config
@@ -1669,7 +1702,8 @@ export function SharedComposer({
...serverTuningLoadPayload(ownConfig),
}
: {}),
- });
+ }, { signal: compareSignal });
+ throwIfCompareCancelled(compareSignal);
// Upgrade dialog first (mirrors the primary load path).
if (validation.requires_transformers_upgrade) {
const upgraded = await confirmTransformersUpgradeIfNeeded({
@@ -1715,9 +1749,12 @@ export function SharedComposer({
);
}
}
+ throwIfCompareCancelled(compareSignal);
applyCompareStopDecision();
+ const loadRequestId = crypto.randomUUID();
const resp = await loadModel({
model_path: sel.id,
+ load_request_id: loadRequestId,
hf_token: useChatRuntimeStore.getState().hfToken || null,
max_seq_length: compareMaxSeqLength,
load_in_4bit: true,
@@ -1763,7 +1800,17 @@ export function SharedComposer({
...serverTuningLoadPayload(ownConfig),
}
: {}),
+ }, {
+ signal: compareSignal,
+ onRequestStart: () => {
+ compareRunsRef.current.setLoadingModel(run, {
+ modelPath: sel.id,
+ requestId: loadRequestId,
+ });
+ },
});
+ compareRunsRef.current.setLoadingModel(run, null);
+ throwIfCompareCancelled(compareSignal);
// Keep a compare pane's per-model speculative choice load-local: persist the global preference
// only when it came from global settings.
if (ownConfig.speculativeType == null) {
@@ -1967,6 +2014,7 @@ export function SharedComposer({
const toastId = toast("Comparing models…", { duration: Infinity });
setComparing(true);
+ onComparingChange?.(true);
try {
if (handle1 && model1?.id) {
toast("Loading Model 1…", {
@@ -1975,6 +2023,7 @@ export function SharedComposer({
duration: Infinity,
});
const status1 = await ensureModelLoaded(model1);
+ throwIfCompareCancelled(compareSignal);
releaseCompareModelLifecycle();
toast("Generating with Model 1…", {
id: toastId,
@@ -1984,6 +2033,7 @@ export function SharedComposer({
const done = handle1.waitForRunEnd();
handle1.startRun();
await done;
+ throwIfCompareCancelled(compareSignal);
}
if (handle2 && model2?.id) {
@@ -1998,6 +2048,7 @@ export function SharedComposer({
if (!currentStopDecision.proceed) {
throw new Error("Second comparison model load cancelled.");
}
+ throwIfCompareCancelled(compareSignal);
compareStopDecision = currentStopDecision;
toast("Loading Model 2…", {
id: toastId,
@@ -2006,6 +2057,7 @@ export function SharedComposer({
});
}
const status2 = await ensureModelLoaded(model2);
+ throwIfCompareCancelled(compareSignal);
releaseCompareModelLifecycle();
toast("Generating with Model 2…", {
id: toastId,
@@ -2015,6 +2067,7 @@ export function SharedComposer({
const done = handle2.waitForRunEnd();
handle2.startRun();
await done;
+ throwIfCompareCancelled(compareSignal);
}
compareStepSucceededRef.current = true;
@@ -2022,19 +2075,47 @@ export function SharedComposer({
} catch (err) {
compareStepSucceededRef.current = false;
resetPromptQueue();
+ const cancelled = isCompareCancellation(err, compareSignal);
+ let cleanupError: unknown = null;
+ if (run.cleanup) {
+ cleanupError = await run.cleanup.then(
+ () => null,
+ (error: unknown) => error ?? new Error("Model unload failed"),
+ );
+ // The load keeps running when its cancel failed; resyncing before it settles would pin the
+ // outgoing model while the replacement becomes resident.
+ if (cleanupError) {
+ await waitForBackendLoadToSettle();
+ }
+ // A stopped load may have finished or evicted the previous model: adopt the backend's state.
+ await resyncInferenceStatusAfterServerModelChange();
+ }
// The install already unloaded the previously active model; drop the checkpoint so the UI does
// not keep pointing at it.
if (upgradeUnloadedActive) {
useChatRuntimeStore.getState().clearCheckpoint();
}
- toast.error("Compare failed", {
- id: toastId,
- description: err instanceof Error ? err.message : "Unknown error",
- duration: 4000,
- });
+ if (cancelled && !cleanupError) {
+ toast.info("Compare stopped", { id: toastId, duration: 2000 });
+ return;
+ }
+ const failure = cancelled ? cleanupError : err;
+ toast.error(
+ cancelled
+ ? "Compare stopped, but the model load could not be cancelled"
+ : "Compare failed",
+ {
+ id: toastId,
+ description:
+ failure instanceof Error ? failure.message : "Unknown error",
+ duration: cancelled ? 5000 : 4000,
+ },
+ );
} finally {
+ compareRunsRef.current.release(run);
releaseCompareModelLifecycle();
setComparing(false);
+ onComparingChange?.(false);
}
} else {
const liveRuntime = useChatRuntimeStore.getState();
@@ -2084,6 +2165,18 @@ export function SharedComposer({
function stop() {
if (isDictating) stopDictation();
+ const run = compareRunsRef.current.cancelCurrent();
+ // Aborting the fetch frees only the browser; /unload is what stops the backend load.
+ if (run?.loadingModel && !run.cleanup) {
+ compareRunsRef.current.setCleanup(
+ run,
+ // Scoped to this attempt: never evicts a resident model or another tab's same-named load.
+ unloadModel({
+ model_path: run.loadingModel.modelPath,
+ cancel_load_request_id: run.loadingModel.requestId,
+ }),
+ );
+ }
for (const handle of Object.values(handlesRef.current)) {
handle.cancel();
}
diff --git a/studio/frontend/tests/compare-run-ownership.test.ts b/studio/frontend/tests/compare-run-ownership.test.ts
new file mode 100644
index 00000000000..6c4860e19c8
--- /dev/null
+++ b/studio/frontend/tests/compare-run-ownership.test.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ CompareRunOwnership,
+ isCompareCancellation,
+ throwIfCompareCancelled,
+} from "../src/features/chat/compare-run-ownership.ts";
+
+test("late cleanup from a superseded run cannot release the current run", () => {
+ const ownership = new CompareRunOwnership<string>();
+ const first = ownership.begin();
+ const second = ownership.begin();
+
+ assert.equal(first.controller.signal.aborted, true);
+ assert.equal(ownership.release(first), false);
+ assert.equal(ownership.current(), second);
+ assert.equal(ownership.release(second), true);
+ assert.equal(ownership.current(), null);
+});
+
+test("superseded runs cannot replace the current backend load target", () => {
+ const ownership = new CompareRunOwnership<string>();
+ const first = ownership.begin();
+ assert.equal(ownership.setLoadingModel(first, "model-1"), true);
+
+ const second = ownership.begin();
+ assert.equal(ownership.setLoadingModel(first, null), false);
+ assert.equal(ownership.setLoadingModel(second, "model-2"), true);
+ assert.equal(second.loadingModel, "model-2");
+});
+
+test("cancelCurrent aborts the owner without releasing it early", () => {
+ const ownership = new CompareRunOwnership<string>();
+ const run = ownership.begin();
+
+ assert.equal(ownership.cancelCurrent(), run);
+ assert.equal(run.controller.signal.aborted, true);
+ assert.equal(ownership.current(), run);
+ assert.throws(
+ () => throwIfCompareCancelled(run.controller.signal),
+ (error) =>
+ error instanceof DOMException &&
+ error.name === "AbortError" &&
+ isCompareCancellation(error, run.controller.signal),
+ );
+});
+
+test("cleanup promises are attached only by the current owner", async () => {
+ const ownership = new CompareRunOwnership<string>();
+ const first = ownership.begin();
+ const second = ownership.begin();
+ const firstCleanup = Promise.resolve();
+ const secondCleanup = Promise.resolve();
+
+ assert.equal(ownership.setCleanup(first, firstCleanup), false);
+ assert.equal(ownership.setCleanup(second, secondCleanup), true);
+ assert.equal(second.cleanup, secondCleanup);
+ await second.cleanup;
+});
diff --git a/studio/frontend/tests/project-chat-run-keepalive.test.ts b/studio/frontend/tests/project-chat-run-keepalive.test.ts
index aae81808204..a99bcf849d8 100644
--- a/studio/frontend/tests/project-chat-run-keepalive.test.ts
+++ b/studio/frontend/tests/project-chat-run-keepalive.test.ts
@@ -410,11 +410,11 @@ test("compare lists its threads once before it waits on any run", () => {
assert.equal(localWaits.length, 1, "LoRA Compare waits only on local runs");
const gates =
page.match(
- /if \(anyRunning && listedPairRef\.current === pairId\) return;\s*listedPairRef\.current = pairId;/g,
+ /if \(\(?anyRunning(?: \|\| comparing\))? && listedPairRef\.current === pairId\) return;\s*listedPairRef\.current = pairId;/g,
) ?? [];
assert.equal(gates.length, 2, "both variants must exempt their first list");
assert.equal(
- (page.match(/\}, \[pairId, anyRunning\]\);/g) ?? []).length,
+ (page.match(/\}, \[pairId, anyRunning(?:, comparing)?\]\);/g) ?? []).length,
2,
"the settle edge is what re-lists; without it a fresh pair never learns its ids",
);
diff --git a/tests/studio/test_compare_cancellation_contract.py b/tests/studio/test_compare_cancellation_contract.py
new file mode 100644
index 00000000000..54d8c4bcfff
--- /dev/null
+++ b/tests/studio/test_compare_cancellation_contract.py
@@ -0,0 +1,81 @@
+# 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 for generalized compare cancellation."""
+
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+CHAT = ROOT / "studio" / "frontend" / "src" / "features" / "chat"
+
+
+def _read(name: str) -> str:
+ return (CHAT / name).read_text(encoding = "utf-8")
+
+
+def _between(text: str, start: str, end: str) -> str:
+ return text.split(start, 1)[1].split(end, 1)[0]
+
+
+def test_stop_unloads_only_a_load_already_sent():
+ composer = _read("shared-composer.tsx")
+ stop = _between(composer, " function stop() {", "\n }\n")
+ assert "compareRunsRef.current.cancelCurrent()" in stop
+ assert "cancel_load_request_id: run.loadingModel.requestId" in stop
+ load = _between(composer, "const resp = await loadModel(", "saveSpeculativeType")
+ assert "signal: compareSignal" in load
+ start_hook = _between(load, "onRequestStart: () => {", "},")
+ assert "requestId: loadRequestId" in start_hook
+ assert "load_request_id: loadRequestId" in load
+ assert load.index("setLoadingModel(run, null)") > load.index("onRequestStart")
+
+
+def test_stopped_compare_never_starts_the_next_step():
+ composer = _read("shared-composer.tsx")
+ sequence = _between(composer, "setComparing(true);", "} catch (err) {")
+ steps = [
+ "ensureModelLoaded(model1);",
+ "handle1.startRun();",
+ "ensureModelLoaded(model2);",
+ "handle2.startRun();",
+ "compareStepSucceededRef.current = true;",
+ ]
+ positions = [sequence.index(step) for step in steps]
+ for before, after in zip(positions, positions[1:]):
+ assert "throwIfCompareCancelled(compareSignal);" in sequence[before:after]
+
+
+def test_cancelled_load_waits_for_unload_then_reconciles_checkpoint():
+ composer = _read("shared-composer.tsx")
+ catch = _between(composer, "} catch (err) {\n compareStepSucceededRef", "} finally {")
+ assert catch.index("await run.cleanup") < catch.index(
+ "await resyncInferenceStatusAfterServerModelChange()"
+ )
+ assert 'toast.info("Compare stopped"' in catch
+ assert catch.index("await waitForBackendLoadToSettle(") < catch.index(
+ "await resyncInferenceStatusAfterServerModelChange()"
+ )
+ settle = _between(composer, "async function waitForBackendLoadToSettle(", "\n}\n")
+ assert "LOAD_SETTLE_TIMEOUT_MS" in settle
+ assert "status.loading.length === 0" in settle
+ finally_ = _between(composer, " } finally {\n compareRunsRef", "\n }\n")
+ assert "onComparingChange?.(false);" in finally_
+
+
+def test_generalized_compare_does_not_relist_threads_mid_send():
+ page = _read("chat-page.tsx")
+ general = _between(page, "const GeneralCompareContent = memo(", "return (")
+ assert "(anyRunning || comparing) && listedPairRef.current === pairId" in general
+ assert "onComparingChange={setComparing}" in page
+ body = _between(page, "const GeneralCompareContent = memo(", "\n});")
+ composer = _between(body, "<SharedComposer", "/>")
+ assert 'threadsSettled ? undefined : "Loading comparison history."' in composer
+
+
+def test_auth_layer_carries_no_compare_lifecycle():
+ auth = (ROOT / "studio" / "frontend" / "src" / "features" / "auth" / "api.ts").read_text(
+ encoding = "utf-8"
+ )
+ assert "onRequestStart" not in auth
+ assert "onAuthenticationRequired" not in auth