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.

Chat: preserve saved model comparisons when reopening with a LoRA active (#9908)

Shubhankar Tripathy14c480e37813
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index dce46c789e6..e9572becba8 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -66,6 +66,7 @@ import {
INVENTORY_FRESHNESS_WINDOW_MS,
useDeviceInventorySources,
} from "@/features/hub/inventory";
+import { modelIdsMatch } from "@/features/hub/lib/model-identity";
import { DeleteChatFilesSwitch } from "./components/delete-chat-files-switch";
import { chatLocalModelOptions } from "./local-model-options";
import {
@@ -219,6 +220,12 @@ import { useResearchRunStore } from "./stores/research-run-store";
import { useExternalProvidersStore } from "./stores/external-providers-store";
import { buildChatTourSteps } from "./tour";
import type { ChatView, MessageRecord } from "./types";
+import {
+ type ComparePairReadState,
+ checkpointCompareClass,
+ comparePairReadState,
+ resolveComparePaneThreadIds,
+} from "./utils/compare-pane-threads";
import { clearNewChatDraft } from "./utils/composer-draft";
import { isChatThreadDeleted } from "./utils/chat-thread-tombstones";
import {
@@ -543,12 +550,95 @@ function modelMatchesDeleted(
* True when the loaded checkpoint is a LoRA, meaning a base-vs-fine-tuned
* compare that uses the fast simultaneous adapter-toggle path.
*/
-function useIsLoraCompare(): boolean {
- return useChatRuntimeStore((s) => {
- const cp = s.params.checkpoint;
- const selected = cp ? s.loras.find((l) => l.id === cp) : undefined;
- return selected?.exportType === "lora";
- });
+function useIsLoraCompare(): boolean | null {
+ return useChatRuntimeStore((s) =>
+ checkpointCompareClass({
+ checkpoint: s.params.checkpoint,
+ isExternal: isExternalModelId(s.params.checkpoint),
+ residentUnknown: s.residentCheckpoint === undefined,
+ models: s.models,
+ loras: s.loras,
+ inventorySettled: s.loraInventorySettled,
+ }),
+ );
+}
+
+/** `pending` while the pair is still being read, so neither component hydrates first. */
+function useCompareVariant(pairId: string): {
+ state: ComparePairReadState;
+ retry: () => void;
+} {
+ const checkpointIsLora = useIsLoraCompare();
+ const [read, setRead] = useState<{
+ pairId: string;
+ state: ComparePairReadState;
+ }>();
+ const [storageRetry, setStorageRetry] = useState<{
+ pairId: string;
+ count: number;
+ }>();
+ const settled = read?.pairId === pairId ? read.state : undefined;
+ const retryCount = storageRetry?.pairId === pairId ? storageRetry.count : 0;
+
+ useEffect(() => {
+ if (settled) return;
+ let isActive = true;
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
+ const settle = (state: ComparePairReadState) => {
+ if (!isActive || state.status === "pending") return;
+ if (state.status === "retry") {
+ retryTimer = setTimeout(() => {
+ if (isActive) setStorageRetry({ pairId, count: retryCount + 1 });
+ }, 250);
+ return;
+ }
+ setRead({ pairId, state });
+ };
+ listStoredChatThreads({ pairId })
+ .then((threads) =>
+ settle(comparePairReadState({ threads }, checkpointIsLora, retryCount)),
+ )
+ .catch((error) => {
+ if (!isExpectedBackgroundChatStorageError(error)) {
+ console.error("Could not read a comparison's stored threads", error);
+ }
+ settle(
+ comparePairReadState({ failed: true }, checkpointIsLora, retryCount),
+ );
+ });
+ return () => {
+ isActive = false;
+ if (retryTimer !== null) clearTimeout(retryTimer);
+ };
+ }, [pairId, checkpointIsLora, retryCount, settled]);
+
+ const retry = useCallback(() => {
+ setRead(undefined);
+ setStorageRetry({ pairId, count: 0 });
+ }, [pairId]);
+
+ return { state: settled ?? { status: "pending" }, retry };
+}
+
+/**
+ * The pair read failed. Its persisted shape is unknown, and picking a renderer from the
+ * loaded checkpoint would relabel existing histories, so offer the read again instead.
+ */
+function CompareUnreadable({
+ onRetry,
+}: {
+ onRetry: () => void;
+}): ReactElement {
+ return (
+ <div className="flex min-h-0 min-w-0 flex-1 basis-0 flex-col items-center justify-center gap-3 p-6 text-center">
+ <p className="text-sm text-muted-foreground">
+ Could not load this comparison's history.
+ </p>
+ <Button variant="outline" size="sm" onClick={onRetry}>
+ Try again
+ </Button>
+ </div>
+ );
}
const CompareContent = memo(function CompareContent({
@@ -574,9 +664,15 @@ const CompareContent = memo(function CompareContent({
deleteDisabled?: boolean;
onExitCompare?: () => void;
}): ReactElement {
- const isLoraCompare = useIsLoraCompare();
+ const { state: compareRead, retry: retryCompareRead } =
+ useCompareVariant(pairId);
- return isLoraCompare ? (
+ if (compareRead.status === "unreadable") {
+ return <CompareUnreadable onRetry={retryCompareRead} />;
+ }
+ if (compareRead.status !== "ready") return <></>;
+
+ return compareRead.variant === "lora" ? (
<LoraCompareContent
pairId={pairId}
onExitCompare={onExitCompare}
@@ -739,9 +835,12 @@ const LoraCompareContent = memo(function LoraCompareContent({
const handlesRef = useRef<Record<string, CompareHandle>>({});
const [baseThreadId, setBaseThreadId] = useState<string>();
const [loraThreadId, setLoraThreadId] = useState<string>();
+ const [pairLoraModelId, setPairLoraModelId] = useState<string>();
const [threadsSettled, setThreadsSettled] = useState(false);
const markInitialHistoryReady = useCompareReloadReadiness(pairId);
const active = useChatActive();
+ const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
+ const checkpointIsLora = useIsLoraCompare();
// Global on purpose: a first compare run starts before either thread exists, so there is
// no pair id to scope BY -- it files its handles under "__default" until initialize()
@@ -749,7 +848,7 @@ const LoraCompareContent = memo(function LoraCompareContent({
// `initialThreadId`, so learning them mid-run points ThreadAutoSwitch at a thread that is
// still generating.
const anyRunning = useChatRuntimeStore(
- (s) => Object.keys(s.runningByThreadId).length > 0,
+ (s) => Object.keys(s.localRunByThreadId).length > 0,
);
// ...but only RE-lists wait. The shared provider (#8908) keeps a base chat's run alive
// across the switch into compare, so `anyRunning` is true on arrival for a reason that has
@@ -765,8 +864,16 @@ const LoraCompareContent = memo(function LoraCompareContent({
listStoredChatThreads({ pairId })
.then((threads) => {
if (!isActive) return;
- setBaseThreadId(threads.find((t) => t.modelType === "base")?.id);
- setLoraThreadId(threads.find((t) => t.modelType === "lora")?.id);
+ // No model1/model2 fallback: useCompareVariant never routes a generalized
+ // pair here, so adopting one could only mislabel it and write adapter
+ // answers into its histories.
+ const baseThread = threads.find((t) => t.modelType === "base");
+ const loraThread = threads.find((t) => t.modelType === "lora");
+ setBaseThreadId(baseThread?.id);
+ setLoraThreadId(loraThread?.id);
+ setPairLoraModelId(
+ loraThread?.modelId?.trim() || baseThread?.modelId?.trim() || undefined,
+ );
})
.catch((error) => {
if (!isExpectedBackgroundChatStorageError(error)) {
@@ -792,6 +899,16 @@ const LoraCompareContent = memo(function LoraCompareContent({
threadsSettled,
]);
+ const sendUnavailableReason = !threadsSettled
+ ? "Loading comparison history."
+ : checkpointIsLora === null
+ ? "Checking the loaded model."
+ : !checkpointIsLora ||
+ (pairLoraModelId !== undefined &&
+ !modelIdsMatch(pairLoraModelId, checkpoint))
+ ? "Load the LoRA saved with this comparison before sending."
+ : undefined;
+
return (
<CompareShell
handlesRef={handlesRef}
@@ -802,6 +919,8 @@ const LoraCompareContent = memo(function LoraCompareContent({
onExitCompare={onExitCompare}
model1ThreadId={baseThreadId}
model2ThreadId={loraThreadId}
+ sendUnavailableReason={sendUnavailableReason}
+ requireStableCheckpoint={true}
/>
) : (
<></>
@@ -993,16 +1112,9 @@ const GeneralCompareContent = memo(function GeneralCompareContent({
listStoredChatThreads({ pairId })
.then((threads) => {
if (!isActive) return;
- setModel1ThreadId(
- threads.find(
- (t) => t.modelType === "model1" || t.modelType === "base",
- )?.id,
- );
- setModel2ThreadId(
- threads.find(
- (t) => t.modelType === "model2" || t.modelType === "lora",
- )?.id,
- );
+ const pair = resolveComparePaneThreadIds(threads);
+ setModel1ThreadId(pair.first);
+ setModel2ThreadId(pair.second);
})
.catch((error) => {
if (!isExpectedBackgroundChatStorageError(error)) {
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.ts
index d88da4bf7bb..59b3f44b927 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
@@ -383,6 +383,7 @@ function getTransformersUpgradeRequiredMessage(modelName: string): string {
// last and re-pin the model the newer one had just seen released, leaving chat
// claiming a model that 400s on send until the load finally settled.
let syncGeneration = 0;
+let loraSyncGeneration = 0;
let lastIdleUnloadArmed = false;
async function readIdleUnloadArmed(): Promise<boolean> {
@@ -404,15 +405,36 @@ async function syncInferenceStatusToStore(options?: {
const includeLoras = options?.includeLoras ?? true;
// Last issued wins: it read the freshest status, whichever answers first.
const generation = ++syncGeneration;
+ const loraGeneration = includeLoras ? ++loraSyncGeneration : null;
const superseded = () => generation !== syncGeneration;
+ const loraSuperseded = () =>
+ loraGeneration !== null && loraGeneration !== loraSyncGeneration;
const { setModels, setLoras, setCheckpoint, setModelsError } =
useChatRuntimeStore.getState();
setModelsError(null);
try {
- const [listRes, statusRes, lorasRes, idleUnloadArmed] = await Promise.all([
+ const [listRes, statusRes, , idleUnloadArmed] = await Promise.all([
listModels(),
getInferenceStatus(),
- includeLoras ? listLoras() : Promise.resolve(null),
+ // Settled from this request alone. Read out of the aggregate below, a sibling
+ // rejection discarded a good list yet still marked the inventory settled, so a
+ // resident LoRA classified as a base model and pinned a new pair generalized.
+ includeLoras
+ ? listLoras().then(
+ (lorasRes) => {
+ if (!signal?.aborted && !loraSuperseded()) {
+ setLoras(lorasRes.loras.map(toLoraSummary));
+ }
+ return lorasRes;
+ },
+ (error) => {
+ if (!signal?.aborted && !loraSuperseded()) {
+ useChatRuntimeStore.setState({ loraInventorySettled: true });
+ }
+ throw error;
+ },
+ )
+ : Promise.resolve(null),
options?.preserveIdleUnloaded
? readIdleUnloadArmed()
: Promise.resolve(false),
@@ -425,9 +447,6 @@ async function syncInferenceStatusToStore(options?: {
if (signal?.aborted || superseded()) return;
setModels(listRes.models.map(toChatModelRow));
- if (lorasRes) {
- setLoras(lorasRes.loras.map(toLoraSummary));
- }
const selectedCheckpoint = useChatRuntimeStore.getState().params.checkpoint;
const isExternalSelectionActive = isExternalModelId(selectedCheckpoint);
@@ -515,7 +534,8 @@ async function syncInferenceStatusToStore(options?: {
}
} catch (error) {
// A superseded refresh reports nothing, or a stale failure would raise a
- // toast about a read whose answer would have been discarded anyway.
+ // toast about a read whose answer would have been discarded anyway. The LoRA
+ // inventory settles from its own request above, never from a sibling's failure.
if (signal?.aborted || superseded()) return;
const message =
error instanceof Error ? error.message : "Failed to load models";
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 6cf37b2c0b5..13d98bb26ac 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -52,11 +52,16 @@ import { isVideoFile } from "@/lib/video-utils";
import { isDownloadCancelled } from "@/lib/native-files";
import { isMultimodalResponse } from "./types/api";
import { getImageInputUnavailableReason } from "./utils/image-input-support";
+import { modelIdsMatch } from "@/features/hub/lib/model-identity";
import { CONVERSATION_MARKDOWN_LABEL } from "./utils/conversation-markdown";
import { pasteClipboardFiles } from "./utils/clipboard-files";
import { confirmStopRunningChatsIfNeeded } from "./utils/confirm-stop-running-chats";
import { requestLocalPromptQueueStop } from "./utils/prompt-queue-boundary";
-import { cancelPreStreamRunReservations } from "./utils/pre-stream-run-reservation";
+import {
+ cancelPreStreamRunReservations,
+ releasePreStreamRunReservation,
+ reservePreStreamRun,
+} from "./utils/pre-stream-run-reservation";
import type { ModelLifecycleLease } from "./utils/model-lifecycle-gate";
import { useAui } from "@assistant-ui/react";
import {
@@ -191,6 +196,7 @@ export interface CompareHandle {
startRun: () => void;
cancel: () => void;
isRunning: () => boolean;
+ threadIds: () => string[];
/** Returns a promise that resolves when the current or next run finishes. */
waitForRunEnd: () => Promise<void>;
}
@@ -388,6 +394,16 @@ export function RegisterCompareHandle({
return;
}
const currentHandles = handlesRef.current;
+ const getThreadIds = () => {
+ const itemState = aui.threadListItem().getState();
+ return Array.from(
+ new Set(
+ [itemState.id, itemState.remoteId].filter(
+ (id): id is string => Boolean(id),
+ ),
+ ),
+ );
+ };
currentHandles[name] = {
// fixes occasional reorder on reload.
append: (content) =>
@@ -410,18 +426,12 @@ export function RegisterCompareHandle({
},
cancel: () => aui.thread().cancelRun(),
isRunning: () => aui.thread().getState().isRunning,
+ threadIds: getThreadIds,
waitForRunEnd: () =>
new Promise<void>((resolve, reject) => {
const runtime =
aui.threads().__internal_getAssistantRuntime?.();
- const itemState = aui.threadListItem().getState();
- const threadIds = Array.from(
- new Set(
- [itemState.id, itemState.remoteId].filter(
- (id): id is string => Boolean(id),
- ),
- ),
- );
+ const threadIds = getThreadIds();
let thread = null;
for (const threadId of threadIds) {
try {
@@ -537,6 +547,8 @@ export function SharedComposer({
onExitCompare,
model1ThreadId,
model2ThreadId,
+ sendUnavailableReason,
+ requireStableCheckpoint = false,
}: {
handlesRef: CompareHandles;
model1?: CompareModelSelection;
@@ -544,6 +556,8 @@ export function SharedComposer({
onExitCompare?: () => void;
model1ThreadId?: string;
model2ThreadId?: string;
+ sendUnavailableReason?: string;
+ requireStableCheckpoint?: boolean;
}): ReactElement {
const navigate = useNavigate();
// Exit compare: parent's restore handler, or fresh chat if opened by URL.
@@ -1072,12 +1086,22 @@ export function SharedComposer({
resetPromptQueue();
return;
}
+ if (sendUnavailableReason) {
+ resetPromptQueue();
+ toast.error("Compare unavailable", {
+ description: sendUnavailableReason,
+ });
+ return;
+ }
const hasCompareHandles = Boolean(
handlesRef.current["model1"] || handlesRef.current["model2"],
);
const isGeneralizedCompare =
hasCompareHandles && Boolean(model1?.id && model2?.id);
+ const submittedCompareCheckpoint = requireStableCheckpoint
+ ? useChatRuntimeStore.getState().params.checkpoint
+ : undefined;
// Generalized compare requires both panes to have a model. A half-
// selected send either races to an empty bubble with bogus tok/s (#5569)
@@ -1837,8 +1861,44 @@ export function SharedComposer({
}
} else {
// Original behavior: fire all handles simultaneously
+ const liveRuntime = useChatRuntimeStore.getState();
+ if (
+ requireStableCheckpoint &&
+ (liveRuntime.modelLoading ||
+ !modelIdsMatch(
+ submittedCompareCheckpoint,
+ liveRuntime.params.checkpoint,
+ ))
+ ) {
+ resetPromptQueue();
+ toast.error("Compare unavailable", {
+ description: "The loaded model changed while preparing the message.",
+ });
+ return;
+ }
+ const handles = Object.values(handlesRef.current);
+ const reservations: symbol[] = [];
+ if (requireStableCheckpoint) {
+ for (const handle of handles) {
+ const token = reservePreStreamRun(handle.threadIds(), {
+ usesLocalModel: true,
+ cancel: () => handle.cancel(),
+ });
+ if (!token) {
+ for (const reservation of reservations) {
+ releasePreStreamRunReservation(reservation);
+ }
+ resetPromptQueue();
+ toast.error("Compare unavailable", {
+ description: "A comparison run is already starting.",
+ });
+ return;
+ }
+ reservations.push(token);
+ }
+ }
clearSubmittedDraft();
- for (const handle of Object.values(handlesRef.current)) {
+ for (const handle of handles) {
handle.append(content);
}
}
@@ -1894,7 +1954,8 @@ export function SharedComposer({
pendingAudio !== null) &&
!busy &&
!isComposing &&
- !isDictating;
+ !isDictating &&
+ !sendUnavailableReason;
// Compare mode swaps this composer in for the single-chat one, and only one
// of the two is ever on screen, so the chords register in both. Both gate on
@@ -2797,7 +2858,7 @@ export function SharedComposer({
</Button>
) : (
<TooltipIconButton
- tooltip="Send message"
+ tooltip={sendUnavailableReason ?? "Send message"}
side="bottom"
variant="default"
size="icon"
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 231295bd15e..b90525cce2a 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -2446,6 +2446,7 @@ type ChatRuntimeStore = {
activePresetSource: ChatPresetSource;
models: ChatModelRow[];
loras: ChatLoraSummary[];
+ loraInventorySettled: boolean;
runningByThreadId: Record<string, boolean>;
/**
* The subset of `runningByThreadId` decoding on the local llama-server. Swapping the local
@@ -3719,6 +3720,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
activePresetSource: getPresetSource("Default"),
models: [],
loras: [],
+ loraInventorySettled: false,
runningByThreadId: {},
localRunByThreadId: {},
runOwnerByThreadId: {},
@@ -4088,7 +4090,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return { activePresetSource };
}),
setModels: (models) => set({ models }),
- setLoras: (loras) => set({ loras }),
+ setLoras: (loras) => set({ loras, loraInventorySettled: true }),
setThreadRunning: (threadId, running, options) =>
set((state) => {
const next = { ...state.runningByThreadId };
diff --git a/studio/frontend/src/features/chat/utils/compare-pane-threads.ts b/studio/frontend/src/features/chat/utils/compare-pane-threads.ts
new file mode 100644
index 00000000000..ef6f95933a1
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/compare-pane-threads.ts
@@ -0,0 +1,120 @@
+// 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 { modelIdsMatch } from "../../hub/lib/model-identity.ts";
+import type { ThreadRecord } from "../types";
+
+export type CompareVariant = "general" | "lora";
+export type CompareThreadShape = CompareVariant;
+
+export type ComparePaneThreadIds = {
+ shape: CompareThreadShape | null;
+ first: string | undefined;
+ second: string | undefined;
+};
+
+function threadId(
+ threads: ThreadRecord[],
+ modelType: string,
+): string | undefined {
+ return threads.find((thread) => thread.modelType === modelType)?.id;
+}
+
+/** Pick one persisted shape for both panes so interrupted writes cannot splice pairs. */
+export function resolveComparePaneThreadIds(
+ threads: ThreadRecord[],
+): ComparePaneThreadIds {
+ const model1 = threadId(threads, "model1");
+ const model2 = threadId(threads, "model2");
+ const base = threadId(threads, "base");
+ const lora = threadId(threads, "lora");
+
+ if ((model1 && model2) || ((model1 || model2) && !(base && lora))) {
+ return { shape: "general", first: model1, second: model2 };
+ }
+ if (base || lora) {
+ return { shape: "lora", first: base, second: lora };
+ }
+ return { shape: null, first: undefined, second: undefined };
+}
+
+/**
+ * A persisted shape owns the renderer. Reclassifying it from the loaded checkpoint
+ * relabels existing histories and can write the other comparison mode into them.
+ */
+export function compareVariantForPair(
+ threads: ThreadRecord[],
+ checkpointIsLora: boolean | null,
+): CompareVariant | null {
+ const { shape } = resolveComparePaneThreadIds(threads);
+ if (shape) return shape;
+ if (checkpointIsLora === null) return null;
+ return checkpointIsLora ? "lora" : "general";
+}
+
+export type CheckpointCompareClassInput = {
+ checkpoint: string | null | undefined;
+ /** External providers have no local adapter, so they are never a LoRA compare. */
+ isExternal: boolean;
+ /** `residentCheckpoint === undefined`: no status read has landed yet. */
+ residentUnknown: boolean;
+ models: readonly { id: string; isLora?: boolean }[];
+ loras: readonly { id: string; exportType?: string }[];
+ inventorySettled: boolean;
+};
+
+/**
+ * Is the loaded checkpoint a LoRA, meaning a base-vs-fine-tuned compare on the fast
+ * simultaneous adapter-toggle path? `null` only while it is genuinely unclassified,
+ * because that blanks the compare view.
+ */
+export function checkpointCompareClass(
+ input: CheckpointCompareClassInput,
+): boolean | null {
+ if (input.isExternal) return false;
+ if (input.residentUnknown && !input.inventorySettled) return null;
+ const checkpoint = input.checkpoint;
+ if (!checkpoint) return false;
+ const row = input.models.find((model) => modelIdsMatch(model.id, checkpoint));
+ if (row?.isLora) return true;
+ if (
+ input.loras.find((lora) => modelIdsMatch(lora.id, checkpoint))
+ ?.exportType === "lora"
+ ) {
+ return true;
+ }
+ if (input.inventorySettled) return false;
+ // An explicit catalog row answers on its own. The deferred inventory could only add
+ // an adapter row, which this one rules out, and chat defers it by 1.2s, so waiting
+ // rendered a new pair blank for at least that long.
+ return row ? false : null;
+}
+
+export type ComparePairReadOutcome =
+ | { threads: ThreadRecord[] }
+ | { failed: true };
+
+export type ComparePairReadState =
+ | { status: "pending" }
+ | { status: "retry" }
+ | { status: "unreadable" }
+ | { status: "ready"; variant: CompareVariant };
+
+/**
+ * Every outcome of the pair read reaches a rendered state. A failure retries once and
+ * then asks for a visible surface: leaving it unsettled renders nothing at all, and
+ * settling it as an empty pair picks a renderer for a pair whose shape is unknown.
+ */
+export function comparePairReadState(
+ outcome: ComparePairReadOutcome,
+ checkpointIsLora: boolean | null,
+ attempt: number,
+): ComparePairReadState {
+ if ("failed" in outcome) {
+ return attempt === 0 ? { status: "retry" } : { status: "unreadable" };
+ }
+ const variant = compareVariantForPair(outcome.threads, checkpointIsLora);
+ return variant === null
+ ? { status: "pending" }
+ : { status: "ready", variant };
+}
diff --git a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts b/studio/frontend/tests/chat-status-refresh-sequencing.test.ts
index 109eb5af507..8f1a1457b79 100644
--- a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts
+++ b/studio/frontend/tests/chat-status-refresh-sequencing.test.ts
@@ -29,18 +29,25 @@ const SYNC = SOURCE.slice(
SOURCE.indexOf("/**\n * Reconcile the UI after the SERVER unloaded"),
);
+/** The lora slot of that function's Promise.all, both handlers included. */
+const LORA_REQUEST = SYNC.slice(
+ SYNC.indexOf("listLoras().then("),
+ SYNC.indexOf("options?.preserveIdleUnloaded"),
+);
+
test("every refresh takes a generation, and the newest one wins", () => {
assert.match(SOURCE, /let syncGeneration = 0;/);
+ assert.match(SOURCE, /let loraSyncGeneration = 0;/);
assert.match(SYNC, /const generation = \+\+syncGeneration;/);
assert.match(SYNC, /const superseded = \(\) => generation !== syncGeneration;/);
});
-test("a superseded refresh writes nothing back to the store", () => {
+test("a superseded refresh writes no stale model or status state", () => {
const guard = SYNC.slice(0, SYNC.indexOf("setModels("));
assert.match(
guard,
/if \(signal\?\.aborted \|\| superseded\(\)\) return;/,
- "the check must sit between the await and the first write",
+ "the check must sit before model and status writes",
);
});
@@ -54,6 +61,21 @@ test("a superseded refresh does not report its failure either", () => {
);
});
+test("the lora inventory settles from its own request, not from a sibling's", () => {
+ assert.match(
+ SYNC,
+ /const loraGeneration = includeLoras \? \+\+loraSyncGeneration : null;/,
+ );
+ // Both outcomes hang off listLoras() itself. Read out of the shared Promise.all, a
+ // sibling rejection discarded a good list and still marked the inventory settled,
+ // which classified a resident LoRA as a base model and pinned a new pair generalized.
+ assert.match(LORA_REQUEST, /setLoras\(lorasRes\.loras\.map\(toLoraSummary\)\)/);
+ assert.match(LORA_REQUEST, /loraInventorySettled: true/);
+ assert.match(LORA_REQUEST, /!loraSuperseded\(\)/);
+ const catchBlock = SYNC.slice(SYNC.indexOf("} catch (error) {"));
+ assert.doesNotMatch(catchBlock, /loraInventorySettled|setLoras/);
+});
+
test("the eviction branch is behind the same guard", () => {
// This is the branch that clears residency and drops the pick, so a stale
// answer reaching it is the expensive case.
diff --git a/studio/frontend/tests/compare-pane-thread-shapes.test.ts b/studio/frontend/tests/compare-pane-thread-shapes.test.ts
new file mode 100644
index 00000000000..0c4e47cd74a
--- /dev/null
+++ b/studio/frontend/tests/compare-pane-thread-shapes.test.ts
@@ -0,0 +1,346 @@
+// 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 { readFileSync } from "node:fs";
+import test from "node:test";
+import type { ModelType, ThreadRecord } from "../src/features/chat/types.ts";
+import {
+ type CheckpointCompareClassInput,
+ checkpointCompareClass,
+ comparePairReadState,
+ compareVariantForPair,
+ resolveComparePaneThreadIds,
+} from "../src/features/chat/utils/compare-pane-threads.ts";
+
+const chatPageSource = readFileSync(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+);
+const sharedComposerSource = readFileSync(
+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),
+ "utf8",
+);
+
+const LORA_PANE_SOURCE = chatPageSource.slice(
+ chatPageSource.indexOf("const LoraCompareContent"),
+ chatPageSource.indexOf("function GeneralCompareHeader"),
+);
+
+const ADOPTS_GENERALIZED = /modelType === "model[12]"/;
+const CHECKPOINT_PICKS_RENDERER = /const isLoraCompare = useIsLoraCompare\(\)/;
+
+/** One pair as `listStoredChatThreads({ pairId })` hands it over: updatedAt descending. */
+function storedPair(rows: [ModelType, number][]): ThreadRecord[] {
+ return rows
+ .map(([modelType, updatedAt]) => ({
+ id: `${modelType}-thread`,
+ title: modelType,
+ modelType,
+ pairId: "pair-1",
+ archived: false,
+ createdAt: updatedAt,
+ updatedAt,
+ }))
+ .sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
+}
+
+test("a generalized pair never reaches the adapter-toggle path", () => {
+ const threads = storedPair([
+ ["model1", 20],
+ ["model2", 10],
+ ]);
+ // Loading model 2, a LoRA export, is what used to swap the component mid-session.
+ assert.equal(compareVariantForPair(threads, true), "general");
+ assert.equal(compareVariantForPair(threads, false), "general");
+ assert.equal(compareVariantForPair(threads, null), "general");
+});
+
+test("a LoRA pair keeps its renderer across checkpoint changes", () => {
+ const threads = storedPair([
+ ["base", 20],
+ ["lora", 10],
+ ]);
+ assert.equal(compareVariantForPair(threads, true), "lora");
+ assert.equal(compareVariantForPair(threads, false), "lora");
+ assert.equal(compareVariantForPair(threads, null), "lora");
+});
+
+test("a pair with no threads yet follows the loaded checkpoint", () => {
+ assert.equal(compareVariantForPair([], true), "lora");
+ assert.equal(compareVariantForPair([], false), "general");
+ assert.equal(compareVariantForPair([], null), null);
+});
+
+test("the resolver recognizes a LoRA pair", () => {
+ const threads = storedPair([
+ ["base", 20],
+ ["lora", 10],
+ ]);
+ assert.deepEqual(resolveComparePaneThreadIds(threads), {
+ shape: "lora",
+ first: "base-thread",
+ second: "lora-thread",
+ });
+});
+
+test("a pair holding both shapes resolves from its own shape, not the freshest row", () => {
+ // Reachable: the pre-fix blank LoRA panes wrote base/lora into a model1/model2 pair.
+ const threads = storedPair([
+ ["model2", 40],
+ ["lora", 30],
+ ["base", 20],
+ ["model1", 10],
+ ]);
+ assert.deepEqual(resolveComparePaneThreadIds(threads), {
+ shape: "general",
+ first: "model1-thread",
+ second: "model2-thread",
+ });
+ assert.equal(compareVariantForPair(threads, true), "general");
+ assert.equal(compareVariantForPair(threads, false), "general");
+});
+
+test("a complete LoRA shape wins over an interrupted generalized write", () => {
+ const threads = storedPair([
+ ["model1", 30],
+ ["base", 20],
+ ["lora", 10],
+ ]);
+ assert.deepEqual(resolveComparePaneThreadIds(threads), {
+ shape: "lora",
+ first: "base-thread",
+ second: "lora-thread",
+ });
+ assert.equal(compareVariantForPair(threads, true), "lora");
+});
+
+test("two partial shapes never splice into a complete comparison", () => {
+ const threads = storedPair([
+ ["model1", 20],
+ ["lora", 10],
+ ]);
+ assert.deepEqual(resolveComparePaneThreadIds(threads), {
+ shape: "general",
+ first: "model1-thread",
+ second: undefined,
+ });
+});
+
+test("one surviving legacy pane stays in its persisted shape", () => {
+ assert.deepEqual(resolveComparePaneThreadIds(storedPair([["base", 10]])), {
+ shape: "lora",
+ first: "base-thread",
+ second: undefined,
+ });
+ assert.equal(
+ compareVariantForPair(storedPair([["base", 10]]), false),
+ "lora",
+ );
+ assert.deepEqual(resolveComparePaneThreadIds(storedPair([["lora", 10]])), {
+ shape: "lora",
+ first: undefined,
+ second: "lora-thread",
+ });
+ assert.equal(
+ compareVariantForPair(storedPair([["lora", 10]]), false),
+ "lora",
+ );
+ assert.deepEqual(resolveComparePaneThreadIds(storedPair([["model2", 10]])), {
+ shape: "general",
+ first: undefined,
+ second: "model2-thread",
+ });
+ assert.equal(
+ compareVariantForPair(storedPair([["model2", 10]]), null),
+ "general",
+ );
+});
+
+test("the freshest row wins only within the selected shape", () => {
+ const [model2] = storedPair([["model2", 10]]);
+ const threads: ThreadRecord[] = [
+ {
+ ...model2,
+ id: "fresh-model1",
+ modelType: "model1",
+ updatedAt: 30,
+ },
+ {
+ ...model2,
+ id: "old-model1",
+ modelType: "model1",
+ updatedAt: 20,
+ },
+ model2,
+ ];
+ assert.deepEqual(resolveComparePaneThreadIds(threads), {
+ shape: "general",
+ first: "fresh-model1",
+ second: "model2-thread",
+ });
+});
+
+test("the LoRA panes adopt no generalized thread", () => {
+ assert.ok(
+ LORA_PANE_SOURCE.includes('threads.find((t) => t.modelType === "base")'),
+ );
+ assert.ok(
+ LORA_PANE_SOURCE.includes('threads.find((t) => t.modelType === "lora")'),
+ );
+ // Adopting one is what mislabelled it and wrote adapter answers into its history.
+ assert.doesNotMatch(LORA_PANE_SOURCE, ADOPTS_GENERALIZED);
+});
+
+/** The store fields `useIsLoraCompare` reads, with the unclassified defaults. */
+function classInput(
+ overrides: Partial<CheckpointCompareClassInput>,
+): CheckpointCompareClassInput {
+ return {
+ checkpoint: "outputs/my-lora",
+ isExternal: false,
+ residentUnknown: false,
+ models: [],
+ loras: [],
+ inventorySettled: false,
+ ...overrides,
+ };
+}
+
+test("an external selection is never an adapter-toggle compare", () => {
+ assert.equal(checkpointCompareClass(classInput({ isExternal: true })), false);
+ assert.equal(checkpointCompareClass(classInput({ checkpoint: "" })), false);
+});
+
+test("a checkpoint the catalog calls a base model does not wait for the inventory", () => {
+ // Chat defers /api/models/loras by 1.2s, so waiting rendered a new pair blank for it.
+ assert.equal(
+ checkpointCompareClass(
+ classInput({
+ models: [{ id: "outputs/my-lora", isLora: false }],
+ inventorySettled: false,
+ }),
+ ),
+ false,
+ );
+});
+
+test("an unclassified checkpoint still waits for the inventory", () => {
+ assert.equal(checkpointCompareClass(classInput({})), null);
+ assert.equal(
+ checkpointCompareClass(classInput({ residentUnknown: true })),
+ null,
+ );
+ // A failed inventory answers too, rather than blanking the view forever.
+ assert.equal(
+ checkpointCompareClass(classInput({ inventorySettled: true })),
+ false,
+ );
+});
+
+test("either inventory naming the checkpoint a LoRA wins", () => {
+ assert.equal(
+ checkpointCompareClass(
+ classInput({ models: [{ id: "outputs/MY-LORA", isLora: true }] }),
+ ),
+ true,
+ );
+ // Ordering guard: the base-model shortcut above must not shadow this lookup.
+ assert.equal(
+ checkpointCompareClass(
+ classInput({
+ models: [{ id: "outputs/my-lora", isLora: false }],
+ loras: [{ id: "outputs/my-lora", exportType: "lora" }],
+ }),
+ ),
+ true,
+ );
+ assert.equal(
+ checkpointCompareClass(
+ classInput({ loras: [{ id: "outputs/my-lora", exportType: "merged" }] }),
+ ),
+ null,
+ );
+});
+
+test("a failed pair read reaches a rendered state, never a blank one", () => {
+ // The first failure buys one quiet retry; the second has to surface, because
+ // `pending` renders nothing at all and no later edge comes back for it.
+ assert.deepEqual(comparePairReadState({ failed: true }, null, 0), {
+ status: "retry",
+ });
+ assert.deepEqual(comparePairReadState({ failed: true }, null, 1), {
+ status: "unreadable",
+ });
+ // ...and it never guesses a renderer for a pair whose shape it could not read.
+ for (const checkpointIsLora of [true, false, null]) {
+ for (const attempt of [0, 1, 2]) {
+ const state = comparePairReadState(
+ { failed: true },
+ checkpointIsLora,
+ attempt,
+ );
+ assert.notEqual(state.status, "ready");
+ assert.notEqual(state.status, "pending");
+ }
+ }
+});
+
+test("a pair that reads cleanly settles on its own shape", () => {
+ assert.deepEqual(
+ comparePairReadState(
+ {
+ threads: storedPair([
+ ["base", 20],
+ ["lora", 10],
+ ]),
+ },
+ false,
+ 0,
+ ),
+ { status: "ready", variant: "lora" },
+ );
+ assert.deepEqual(comparePairReadState({ threads: [] }, true, 0), {
+ status: "ready",
+ variant: "lora",
+ });
+ assert.deepEqual(comparePairReadState({ threads: [] }, null, 0), {
+ status: "pending",
+ });
+});
+
+test("the renderer is chosen from the pair, not straight from the checkpoint", () => {
+ assert.ok(
+ chatPageSource.includes(
+ "const { state: compareRead, retry: retryCompareRead } =",
+ ),
+ );
+ assert.ok(
+ chatPageSource.includes(
+ "return <CompareUnreadable onRetry={retryCompareRead} />;",
+ ),
+ );
+ assert.ok(
+ chatPageSource.includes(
+ 'if (compareRead.status !== "ready") return <></>;',
+ ),
+ );
+ assert.ok(
+ chatPageSource.includes('return compareRead.variant === "lora" ? ('),
+ );
+ assert.doesNotMatch(chatPageSource, CHECKPOINT_PICKS_RENDERER);
+ // Per visit: re-picking the renderer mid-session is what swapped it under a run.
+ assert.ok(chatPageSource.includes("if (settled) return;"));
+ assert.doesNotMatch(chatPageSource, /settle\(\[\]\)/);
+ assert.ok(LORA_PANE_SOURCE.includes("sendUnavailableReason"));
+ assert.ok(
+ LORA_PANE_SOURCE.includes("!modelIdsMatch(pairLoraModelId, checkpoint)"),
+ );
+ assert.ok(LORA_PANE_SOURCE.includes("loraThread?.modelId?.trim() ||"));
+ assert.ok(LORA_PANE_SOURCE.includes("s.localRunByThreadId"));
+ assert.ok(LORA_PANE_SOURCE.includes("requireStableCheckpoint={true}"));
+ assert.ok(sharedComposerSource.includes("submittedCompareCheckpoint"));
+ assert.ok(sharedComposerSource.includes("liveRuntime.modelLoading"));
+ assert.ok(sharedComposerSource.includes("reservePreStreamRun(handle.threadIds()"));
+ assert.ok(sharedComposerSource.includes("threadIds: getThreadIds"));
+});
diff --git a/studio/frontend/tests/project-chat-run-keepalive.test.ts b/studio/frontend/tests/project-chat-run-keepalive.test.ts
index 54ba53f11f3..ee6c182574b 100644
--- a/studio/frontend/tests/project-chat-run-keepalive.test.ts
+++ b/studio/frontend/tests/project-chat-run-keepalive.test.ts
@@ -411,18 +411,17 @@ test("a delayed first send keeps the creation inputs it was sent under", () => {
});
test("compare lists its threads once before it waits on any run", () => {
- // Two constraints one boolean cannot carry. The wait has to be GLOBAL, because a first
- // compare run starts before either thread exists and files its handles under "__default";
- // and it has to exist at all, because these ids feed ComparePane's `initialThreadId`, so
- // learning them mid-run points ThreadAutoSwitch at a generating thread. But the shared
- // provider keeps a base chat's run alive across the switch into compare, so a global wait
- // on the FIRST list left an existing compare on blank runtimes with no later edge to
- // recover on. That list has nothing to clobber, so only re-lists wait.
- const waits =
+ // general compare can run external panes, while lora compare only uses the local runtime.
+ const globalWaits =
page.match(
/const anyRunning = useChatRuntimeStore\(\s*\(s\) => Object\.keys\(s\.runningByThreadId\)\.length > 0,\s*\);/g,
) ?? [];
- assert.equal(waits.length, 2, "both compare variants share the global wait");
+ assert.equal(globalWaits.length, 1, "General Compare waits on every pane run");
+ const localWaits =
+ page.match(
+ /const anyRunning = useChatRuntimeStore\(\s*\(s\) => Object\.keys\(s\.localRunByThreadId\)\.length > 0,\s*\);/g,
+ ) ?? [];
+ 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,