// 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 { ChevronDownStandardIcon } from "@/lib/chevron-icons"; import { DEFAULT_ENGINE_LAUNCH_FIELDS, engineLaunchFieldsFrom, engineLaunchFieldsFromParams, } from "./lib/engine-launch-fields"; import { useChatArtifactsStore } from "./artifacts/store"; import { MemoryMenuItem } from "./memory-menu-item"; import { mlxRuntimeStateFrom } from "./lib/mlx-runtime-state"; import { offloadCountsFrom, offloadWarning } from "./lib/partial-offload"; import { llamaServerLoadFields } from "./lib/load-request"; import { clearedServerTuningState, committedMlxServerTuningState, committedServerTuningState, } from "./lib/server-tuning-fields"; import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button"; import { useTextareaSkillMentions } from "@/components/assistant-ui/skill-mentions"; import { thinkEffortAriaLabel, thinkToggleAriaLabel, } from "@/components/assistant-ui/think-aria-label"; import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-preview"; import { useExpandedComposerFill } from "@/components/assistant-ui/use-expanded-composer-fill"; import { useChatPreferencesStore } from "./stores/chat-preferences-store"; import { composerSubmitIntent, composerShortcutLabels, composerKeyEventForImeSubmit, imeKeydownBlocksComposerSubmit, } from "./utils/composer-preferences"; import { Button } from "@/components/ui/button"; import { Spinner } from "@/components/ui/spinner"; import { BulbIcon } from "@/lib/bulb-icon"; import { AiSpeechIcon, BookmarkIcon, FileSearchIcon } from "@/lib/hugeicons-derived"; import { InternetGlyph } from "@/lib/internet-icon"; import { MicIcon } from "@/lib/mic-icon"; import { MenuTickIcon, Tick02Icon } from "@/lib/tick-icon"; import { BrowserAgentMenuItem, BrowserAgentPill } from "@/features/browser/agent/lazy-composer-toggle"; import { ComputerUseMenuItem, ComputerUsePill } from "@/features/computer-use/lazy-composer-toggle"; import { markComposerScrollEdges } from "@/lib/composer-scroll-fade"; import { useSurfaceRef } from "@/lib/surface-registry"; import { cn } from "@/lib/utils"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu"; import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params"; import { resolveQwenThinkingParams } from "./utils/qwen-sampling-table"; import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page"; import { DRAFT_N_MAX_SPEC_TYPES, resolveSpeculativeType, } from "@/lib/speculative-modes"; import { StudioDictationAdapter, isStudioDictationAvailable, notifyStudioDictationUnavailable, } from "@/features/chat/adapters/studio-dictation-adapter"; import type { StudioDictationSession } from "@/features/chat/adapters/studio-web-speech-dictation-adapter"; import { COMPOSER_INPUT_SELECTOR, isSurfaceInForeground, useShortcut, useSettingsDialogStore, isMacPlatform, } from "@/features/settings"; import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store"; import { AUDIO_PICKER_ACCEPT, isAudioAttachmentFile, fileToBase64, getAudioAddError, } from "@/lib/audio-utils"; import { isTauri } from "@/lib/api-base"; import { classifiedAttachmentFiles, isVideoFile } from "@/lib/video-utils"; import { newAttachmentId } from "./audio-attachment-adapter"; import { isDownloadCancelled } from "@/lib/native-files"; import { isMultimodalResponse, type LoadModelRequest } from "./types/api"; import { getImageInputUnavailableReason } from "./utils/image-input-support"; import { CHAT_IMAGE_ACCEPT, getChatImageSizeError, isChatImageFile, normalizeChatImage, } from "./image-normalize"; import { modelIdsMatch } from "@/features/hub/lib/model-identity"; import { CONVERSATION_MARKDOWN_LABEL } from "./utils/conversation-markdown"; import { CONVERSATION_HTML_LABEL, CONVERSATION_PDF_LABEL, } from "./utils/conversation-html-format"; import { pasteClipboardFiles } from "./utils/clipboard-files"; import { insertAtCaret, richPasteMarkdown } from "./utils/rich-paste"; import { isPlainPasteChord, plainPasteStillCounts } from "./utils/pasted-text"; import { composerDraftKey, flushComposerDraft, latestDraft, NEW_COMPARE_DRAFT_ID, stageComposerDraft, publishDraft, subscribeDraft, writeComposerDraft, } from "./utils/composer-draft"; import { confirmStopRunningChatsIfNeeded } from "./utils/confirm-stop-running-chats"; import { requestLocalPromptQueueStop } from "./utils/prompt-queue-boundary"; 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 { ArrowUpIcon, } from "lucide-react"; import { Attachment01Icon, CodeIcon, Download01Icon, ImageIcon, LayoutTwoColumnIcon, McpServerIcon, Scroll01Icon, MoreHorizontalIcon, PlusSignIcon, SlidersHorizontalIcon, Cancel01Icon, } from "@hugeicons/core-free-icons"; import { FolderAddIcon } from "@/lib/folder-icons"; import { StopIcon } from "@/lib/media-control-icons"; import { useNavigate } from "@tanstack/react-router"; import { useChatActive } from "./runtime-provider"; import { useChatProjectScope } from "./chat-project-scope"; import { claimThreadCreation } from "./utils/chat-thread-creation-claim"; import { HugeiconsIcon } from "@hugeicons/react"; import { ProjectIcon } from "@/lib/project-icon"; import { toast } from "@/lib/toast"; import { PromptStorageDialog, exportConversationShareGPT, exportConversationRawJsonl, exportConversationMessagesJsonl, exportConversationCsv, exportConversationMarkdown, exportConversationHtml, exportConversationPdf, } from "./prompt-storage/prompt-storage-dialog"; import { ExportFormatItems } from "./components/export-format-items"; import { listPromptEntries, listPromptLists, type PromptEntry, type PromptListEntry, } from "./api/prompts-api"; import { PromptCountBadge } from "./prompt-storage/prompt-count-badge"; import { insertSavedPrompt } from "./prompt-storage/insert-prompt"; import { McpComposerButton } from "./mcp-composer-button"; import { SkillsComposerButton, useSkillsSwitch } from "./skills-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 { ChatAudioUploadMount } from "./components/chat-audio-upload-mount"; import { useChatProjects } from "./hooks/use-chat-projects"; import { useChatAudioUpload } from "./hooks/use-chat-audio-upload"; import { currentDictationEntryMode } from "./utils/dictation-entry"; import { confirmRemoteCodeIfNeeded } from "@/features/security"; import { DEFAULT_MAX_SEQ_LENGTH, DEFAULT_PER_MODEL_CONFIG, confirmManagedEngineIfNeeded, isServedByMlx, savedContextPin, resolveResidentInitialConfig, type PerModelConfig, loadedContextFields, } from "@/features/model-picker"; import { managedEngineFailureLogsAction } from "@/features/settings/lib/view-logs-action"; import { loadManagedLlamaFlags } from "@/features/model-picker/api/llama-flags"; import { fetchLoadExtraArgs } from "@/features/model-picker/api/model-overrides"; import { sanitizeStoredExtraArgs } from "@/features/model-picker/model-config/llama-extra-args"; import { usePlatformStore } from "@/config/env"; import { confirmTransformersUpgradeIfNeeded, useTransformersUpgradeDialogStore, } from "@/features/transformers-upgrade"; import { prepareHfTokenForUse } from "@/features/hf-auth"; import { fetchGgufStagedMetadata, getInferenceStatus, LoadModelError, loadModel, unloadModel, validateModel, } from "./api/chat-api"; import { CompareRunOwnership, isCompareCancellation, throwIfCompareCancelled, } from "./compare-run-ownership"; import { loadedContextForParams, mergeBackendRecommendedInference, recommendedValuesForPick, resolveExplicitCtxPin, resolveFitMaxSeqLength, retainedContextPin, unpinnedLoadContext, replayMaxTokensCap, } from "./presets/preset-policy"; import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info"; import { isExternalModelId, parseExternalModelId, providerModelSupportsVision, providerModelSupportsStudioTools, isGeminiApiProviderType, } from "./external-providers"; import { compareModelDisplayName } from "./lib/external-model-label"; import { useExternalProvidersStore } from "./stores/external-providers-store"; import { useComposerPillFit } from "@/hooks/use-composer-pill-fit"; import { useComposerMaxRows } from "@/hooks/use-composer-rows"; import { useUiSpaceScale } from "@/hooks/use-ui-space-scale"; import { useIsMobile } from "@/hooks/use-mobile"; import { useT } from "@/i18n"; import { splitPlusMenuItems, type PlusMenuItemId, usePlusMenuPrefsStore, } from "./stores/plus-menu-prefs-store"; import { resolveComparePlacement, shouldPinDiffusionPlacement, } from "./lib/gpu-placement"; import { loadedGpuMemoryFields, type ReasoningEffort, reconcilePersistedGpuIds, resolveLoadedSpeculativeSettings, resolvePreserveThinkingOnLoad, resolveToolsEnabledOnLoad, persistGpuMemoryModeOnLoad, resolveSpeculativeSettingsForLoad, saveSpeculativeType, codeToolsOn, localImagePillCount, localImageTool, useChatRuntimeStore, } from "./stores/chat-runtime-store"; import { clampReasoningEffortToLevels, getExternalReasoningCapabilities, kimiSearchExcludesThinking, providerHostsCodeExecution, providerSupportsBuiltinCodeExecution, providerSupportsBuiltinImageGeneration, providerSupportsBuiltinWebFetch, } from "./provider-capabilities"; import { codeToolCanRun } from "./api/code-tool-placement"; import { modelCatalogVersion, subscribeModelCatalog } from "./model-catalog"; import { type CompositionEvent, type ClipboardEvent, type DragEvent as ReactDragEvent, type KeyboardEvent, type CSSProperties, type MutableRefObject, type ReactElement, type ReactNode, Fragment, createContext, useCallback, useContext, useEffect, useId, useRef, useState, useSyncExternalStore, } from "react"; export type CompareMessagePart = | { type: "text"; text: string } | { type: "image"; image: string } | { type: "audio"; audio: string; name: string }; export interface CompareHandle { append: (content: CompareMessagePart[]) => void; appendMessage: ( content: CompareMessagePart[], model: CompareModelSelection | undefined, ) => Promise; startRun: () => void; cancel: () => void; isRunning: () => boolean; threadIds: () => string[]; waitForRunEnd: () => Promise; } // Inlined to avoid a new icon dep. Kept in sync with the main composer. // Built on call, like chatExportOptions, so an import cycle cannot leave an exporter undefined. function composerExportFormats() { return [ { label: "Training JSONL", fn: exportConversationRawJsonl }, { label: "Message JSONL", fn: exportConversationMessagesJsonl }, { label: "CSV", fn: exportConversationCsv }, { label: "ShareGPT JSONL", fn: exportConversationShareGPT }, { label: CONVERSATION_MARKDOWN_LABEL, fn: exportConversationMarkdown }, { label: CONVERSATION_HTML_LABEL, fn: exportConversationHtml }, { label: CONVERSATION_PDF_LABEL, fn: exportConversationPdf }, ]; } function isNativeComposing(event: Event) { return "isComposing" in event && (event as InputEvent).isComposing === true; } // Mirrors thread.tsx: Chrome on WSL may never fire compositionend after IME commit. const IME_STUCK_TIMEOUT_MS = 2500; function fileToBase64DataURL(file: File): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result as string); reader.onerror = () => reject(new Error("Failed to read image file")); reader.readAsDataURL(file); }); } function formatReasoningEffortLabel( level: ReasoningEffort, modelId?: string, ): string { if (level === "max") return "Max"; if (level === "xhigh") { const normalized = modelId?.trim().toLowerCase() ?? ""; if ( normalized.startsWith("claude-opus-4-6") || normalized.startsWith("claude-sonnet-4-6") ) { return "Max"; } return "Extra High"; } return level.charAt(0).toUpperCase() + level.slice(1); } function formatReasoningDisabledLabel( supportsReasoningOff: boolean, isExternalOpenAIReasoning: boolean, modelId?: string, ): string { const normalized = modelId?.trim().toLowerCase() ?? ""; if (normalized.includes("magistral-medium-latest")) return "Medium"; return supportsReasoningOff && isExternalOpenAIReasoning ? "None" : "Off"; } function useDictation( setText: (value: string | ((prev: string) => string)) => void, ) { const dictationEngine = useVoiceSettingsStore((s) => s.dictationEngine); const [isDictating, setIsDictating] = useState(false); const [isFinalizing, setIsFinalizing] = useState(false); const sessionRef = useRef(null); const startingRef = useRef(false); const finalizingRef = useRef(false); const start = useCallback(async () => { if (startingRef.current || sessionRef.current) return; if (!isStudioDictationAvailable()) { notifyStudioDictationUnavailable(); return; } startingRef.current = true; let session: StudioDictationSession; try { // Compare feeds two panes, so dictations must not link the single-chat active thread. session = new StudioDictationAdapter({ chatId: null }).listen(); } catch { startingRef.current = false; notifyStudioDictationUnavailable(); return; } sessionRef.current = session; setIsDictating(true); session.onSpeech((result) => { if (!result.isFinal) return; const transcript = result.transcript?.trim() ?? ""; if (transcript) { setText((prev) => (prev ? `${prev} ${transcript}` : transcript)); } }); session.onEnd?.(() => { if (sessionRef.current === session) sessionRef.current = null; finalizingRef.current = false; setIsFinalizing(false); setIsDictating(false); }); startingRef.current = false; }, [setText]); const stop = useCallback(() => { const session = sessionRef.current; if (!session) return; if (finalizingRef.current) { session.cancel(); if (sessionRef.current === session) sessionRef.current = null; finalizingRef.current = false; setIsFinalizing(false); setIsDictating(false); return; } finalizingRef.current = true; setIsFinalizing(true); // Keep the session alive while the final segment transcribes; onEnd clears it. void session.stop().catch((error) => { console.error("Could not stop dictation:", error); session.cancel(); if (sessionRef.current === session) sessionRef.current = null; finalizingRef.current = false; setIsFinalizing(false); setIsDictating(false); }); }, []); useEffect(() => { return () => { sessionRef.current?.cancel(); sessionRef.current = null; }; }, []); const supported = StudioDictationAdapter.isSupported(dictationEngine); return { isDictating, isFinalizing, start, stop, supported }; } export type CompareHandles = MutableRefObject>; const CompareHandlesContext = createContext(null); export function CompareHandlesProvider({ handlesRef, children, }: { handlesRef: CompareHandles; children: ReactNode; }): ReactElement { return ( {children} ); } export function RegisterCompareHandle({ name, }: { name: string; }): ReactElement | null { const handlesRef = useContext(CompareHandlesContext); const aui = useAui(); const projectScope = useChatProjectScope(); useEffect(() => { if (!handlesRef) { 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] = { append: (content) => aui .thread() .append({ role: "user", content, createdAt: new Date() } as never), appendMessage: (content, model) => { if (model?.id) { claimThreadCreation(getThreadIds(), { projectId: projectScope, incognito: useChatRuntimeStore.getState().incognito, modelId: model.id, modelGgufVariant: model.ggufVariant ?? null, createdAt: Date.now(), }); } const count = aui.thread().getState().messages.length; aui.thread().append({ role: "user", content, createdAt: new Date(), startRun: false, } as never); return new Promise((resolve) => { const landed = () => aui.thread().getState().messages.length > count; if (landed()) return resolve(); const unsubscribe = aui.subscribe(() => { if (!landed()) return; unsubscribe(); resolve(); }); }); }, startRun: () => { const msgs = aui.thread().getState().messages; const lastId = msgs.length > 0 ? msgs[msgs.length - 1].id : null; aui.thread().startRun({ parentId: lastId }); }, cancel: () => aui.thread().cancelRun(), isRunning: () => aui.thread().getState().isRunning, threadIds: getThreadIds, waitForRunEnd: () => new Promise((resolve, reject) => { const runtime = aui.threads().__internal_getAssistantRuntime?.(); const threadIds = getThreadIds(); let thread = null; for (const threadId of threadIds) { try { thread = runtime?.threads.getById(threadId) ?? null; if (thread) break; } catch { // Thread hydration can retire an alias; try the next one. } } if (!thread) { reject(new Error("Comparison thread is unavailable")); return; } let wasRunning = thread.getState().isRunning; let unsubscribe = () => {}; unsubscribe = thread.subscribe(() => { const isRunning = thread.getState().isRunning; if (isRunning) wasRunning = true; if (wasRunning && !isRunning) { unsubscribe(); resolve(); } }); }), }; return () => { delete currentHandles[name]; }; }, [handlesRef, name, aui, projectScope]); return null; } type PendingImage = { id: string; file: File }; function PendingImageThumb({ file, onRemove, }: { file: File; onRemove: () => void; }): ReactElement { const [src, setSrc] = useState(null); useEffect(() => { const url = URL.createObjectURL(file); setSrc(url); return () => URL.revokeObjectURL(url); }, [file]); if (!src) return
; return (
{file.name}
); } type CompareModelSelection = { id: string; isLora: boolean; ggufVariant?: string; isDiffusion?: boolean; config?: PerModelConfig; }; function cleanCompareChatTemplate( value: string | null | undefined, ): string | null { return value?.trim() ? value : null; } function resolveCompareSpecDraftNMax( speculativeType: string | null, value: number | null, ): number | null { return speculativeType != null && DRAFT_N_MAX_SPEC_TYPES.has(speculativeType) ? value : null; } function PillGlyph({ children }: { children: ReactNode }) { return ( {children} ); } /** A drop from a portaled child (dialog) that React routes through here but it owns. */ function isPortaledDrop(event: ReactDragEvent): boolean { const target = event.target as Element | null; return !target?.closest?.(".unsloth-composer-surface"); } const LOAD_SETTLE_POLL_MS = 1000; const LOAD_SETTLE_TIMEOUT_MS = 15 * 60_000; /** Waits for every load: the backend tracks a local GGUF under a path-free id. */ async function waitForBackendLoadToSettle(): Promise { const deadline = Date.now() + LOAD_SETTLE_TIMEOUT_MS; while (Date.now() < deadline) { try { const status = await getInferenceStatus(); if (status.loading.length === 0) return; } catch { // An unreachable backend has not proven the load ended. } await new Promise((resolve) => setTimeout(resolve, LOAD_SETTLE_POLL_MS)); } } export function SharedComposer({ draftId, pairSaved, pairSubmitted, onPairSubmitted, handlesRef, model1, model2, onExitCompare, onComparingChange, model1ThreadId, model2ThreadId, sendUnavailableReason, requireStableCheckpoint = false, }: { draftId: string; pairSaved?: boolean; pairSubmitted: boolean; onPairSubmitted: () => void; handlesRef: CompareHandles; model1?: CompareModelSelection; model2?: CompareModelSelection; onExitCompare?: () => void; onComparingChange?: (comparing: boolean) => void; model1ThreadId?: string; model2ThreadId?: string; sendUnavailableReason?: string; requireStableCheckpoint?: boolean; }): ReactElement { const t = useT(); const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut); const richTextPaste = useChatPreferencesStore((s) => s.richTextPaste); const navigate = useNavigate(); const handleExitCompare = useCallback(() => { if (onExitCompare) { onExitCompare(); return; } navigate({ to: "/chat" }); }, [navigate, onExitCompare]); const incognito = useChatRuntimeStore((s) => s.incognito); const shareDraft = useChatPreferencesStore((s) => s.shareComposerDraft); const syncDraft = shareDraft && !incognito; const unsentPair = pairSaved === false && !pairSubmitted; const draftKey = composerDraftKey(unsentPair ? NEW_COMPARE_DRAFT_ID : draftId, shareDraft); const draftScope = incognito ? null : draftKey; const [text, setText] = useState(() => incognito ? "" : latestDraft(draftKey), ); const [draftSource] = useState(() => Symbol("compare composer")); // Text that came from the chat composer, so it isn't published back. const remoteDraftRef = useRef(null); const unsavedDraftRef = useRef<{ key: string; text: string } | null>(null); const draftScopeBeforeRef = useRef(draftScope); const draftOwnerBeforeRef = useRef({ draftId, shareDraft, draftKey }); useEffect(() => { if (draftScopeBeforeRef.current !== draftScope) { draftScopeBeforeRef.current = draftScope; const before = draftOwnerBeforeRef.current; draftOwnerBeforeRef.current = { draftId, shareDraft, draftKey }; let next = incognito ? "" : latestDraft(draftKey); if (!incognito && before.draftId === draftId && before.shareDraft === shareDraft && text) { // Same pair, slot decided by its history: what was typed while it loaded wins. writeComposerDraft(before.draftKey, ""); writeComposerDraft(draftKey, text); next = text; } if (!incognito && !shareDraft) stageComposerDraft(draftKey, next); remoteDraftRef.current = next; setText(next); return; } if (incognito || text === remoteDraftRef.current) return; remoteDraftRef.current = null; if (shareDraft) publishDraft(text, draftSource); // Emptied (a send, or cleared by hand): gone at once, so a reload can't bring back a sent prompt. if (text === "") { writeComposerDraft(draftKey, ""); unsavedDraftRef.current = null; return; } unsavedDraftRef.current = { key: draftKey, text }; stageComposerDraft(draftKey, text); const timer = setTimeout(() => { writeComposerDraft(draftKey, text); unsavedDraftRef.current = null; }, 300); return () => clearTimeout(timer); }, [text, draftScope, draftKey, incognito, shareDraft, draftSource]); useEffect( () => () => { if (unsavedDraftRef.current !== null) { flushComposerDraft(unsavedDraftRef.current.key, unsavedDraftRef.current.text); unsavedDraftRef.current = null; } }, [draftScope], ); const shortcutLabels = composerShortcutLabels(sendShortcut, isMacPlatform(), text); const [running, setRunning] = useState(false); const [comparing, setComparing] = useState(false); const [pendingImages, setPendingImages] = useState([]); const [convertingImages, setConvertingImages] = useState(0); const [pendingAudio, setPendingAudio] = useState< { id: string; name: string; base64: string; contentType: string; size: number; }[] >([]); const textRef = useRef(text); const pendingImagesRef = useRef(pendingImages); const pendingAudioRef = useRef(pendingAudio); const readingAudioRef = useRef(new Map()); const setCurrentText = useCallback( (value: string | ((previous: string) => string)) => { const next = typeof value === "function" ? value(textRef.current) : value; textRef.current = next; setText(next); }, [], ); useEffect(() => { if (!syncDraft) return; return subscribeDraft(draftSource, (next) => { unsavedDraftRef.current = null; remoteDraftRef.current = next; setCurrentText(next); }); }, [syncDraft, draftSource, setCurrentText]); // Attachments still classifying or converting; a ref so runPromptList reads it synchronously. const attachingRef = useRef(0); useEffect(() => { textRef.current = text; pendingImagesRef.current = pendingImages; pendingAudioRef.current = pendingAudio; }, [text, pendingImages, pendingAudio]); const [dragging, setDragging] = useState(false); const [isComposing, setIsComposing] = useState(false); const [newProjectOpen, setNewProjectOpen] = useState(false); const [skillsOn, setSkillsOn] = useSkillsSwitch(); const [promptStorageOpen, setPromptStorageOpen] = useState(false); const [recentPrompts, setRecentPrompts] = useState([]); const [recentLists, setRecentLists] = useState([]); const recentSeqRef = useRef(0); const refreshRecentPrompts = useCallback(async () => { recentSeqRef.current += 1; const seq = recentSeqRef.current; try { const rows = await listPromptEntries(); if (seq !== recentSeqRef.current) return; const byRecent = [...rows].sort((a, b) => b.updatedAt - a.updatedAt); const pinnedIds = usePlusMenuPrefsStore.getState().pinnedPromptIds; const pinned = byRecent.filter((p) => pinnedIds.includes(p.id)); setRecentPrompts(pinned.length > 0 ? pinned : byRecent.slice(0, 3)); } catch { // Clear, don't keep: a stale list row would run its cached items. if (seq === recentSeqRef.current) setRecentPrompts([]); } try { const rows = await listPromptLists(); if (seq !== recentSeqRef.current) return; const pinnedIds = usePlusMenuPrefsStore.getState().pinnedListIds; setRecentLists(rows.filter((l) => pinnedIds.includes(l.id))); } catch { if (seq === recentSeqRef.current) setRecentLists([]); } }, []); const plusPins = usePlusMenuPrefsStore((s) => s.pins); const plusOrder = usePlusMenuPrefsStore((s) => s.order); const [isQueueRunning, setIsQueueRunning] = useState(false); const [queueProgress, setQueueProgress] = useState({ current: 0, total: 0 }); const queueRef = useRef([]); const queueIndexRef = useRef(0); const isQueueRunningRef = useRef(false); 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(null); const composerSurfaceRef = useSurfaceRef(COMPOSER_INPUT_SELECTOR, textareaRef); const pendingFixPrompt = useChatArtifactsStore( (state) => state.pendingFixPrompt, ); useEffect(() => { if (!pendingFixPrompt) return; useChatArtifactsStore.getState().clearFixPrompt(); setCurrentText((current) => current.trim().length > 0 ? `${current}\n\n${pendingFixPrompt}` : pendingFixPrompt, ); // Not the selector: a hidden single-chat composer stays mounted ahead of this one. window.setTimeout(() => textareaRef.current?.focus(), 0); }, [pendingFixPrompt, setCurrentText]); const composingRef = useRef(false); const imeSessionOpenRef = useRef(false); const compositionEndedAtRef = useRef(-Infinity); const stuckImeTimerRef = useRef | null>(null); const fileInputRef = useRef(null); const audioInputRef = useRef(null); const activeModel = useChatRuntimeStore((s) => { const checkpoint = s.params.checkpoint; return s.models.find((m) => m.id === checkpoint); }); const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint); const connectionsEnabled = useExternalProvidersStore( (s) => s.connectionsEnabled, ); const externalProvidersAll = useExternalProvidersStore((s) => s.providers); const externalProviders = connectionsEnabled ? externalProvidersAll : []; const modelLoaded = useChatRuntimeStore( (s) => !!s.params.checkpoint && !s.modelLoading, ); const lastModelLoadError = useChatRuntimeStore((s) => s.lastModelLoadError); const loadedIsMultimodal = useChatRuntimeStore((s) => s.loadedIsMultimodal); const loadedVisionDisabledByUser = useChatRuntimeStore( (s) => s.loadedVisionDisabledByUser, ); const mmprojFallbackReason = useChatRuntimeStore( (s) => s.mmprojFallbackReason, ); const supportsReasoning = useChatRuntimeStore((s) => s.supportsReasoning); const reasoningAlwaysOn = useChatRuntimeStore((s) => s.reasoningAlwaysOn); const reasoningEnabled = useChatRuntimeStore((s) => s.reasoningEnabled); const setReasoningEnabled = useChatRuntimeStore((s) => s.setReasoningEnabled); const reasoningStyle = useChatRuntimeStore((s) => s.reasoningStyle); const reasoningEffort = useChatRuntimeStore((s) => s.reasoningEffort); const supportsReasoningOff = useChatRuntimeStore( (s) => s.supportsReasoningOff, ); const reasoningEffortLevels = useChatRuntimeStore( (s) => s.reasoningEffortLevels, ); const setReasoningEffort = useChatRuntimeStore((s) => s.setReasoningEffort); const supportsPreserveThinking = useChatRuntimeStore( (s) => s.supportsPreserveThinking, ); const preserveThinking = useChatRuntimeStore((s) => s.preserveThinking); const setPreserveThinking = useChatRuntimeStore((s) => s.setPreserveThinking); const supportsTools = useChatRuntimeStore((s) => s.supportsTools); const [skillsSwitchOn] = useSkillsSwitch(); const mentionOpenRef = useRef(false); const skillMentions = useTextareaSkillMentions({ text, setText: setCurrentText, inputRef: textareaRef, composingRef, enabled: supportsTools && skillsSwitchOn, }); mentionOpenRef.current = skillMentions.inputProps["aria-expanded"]; const supportsBuiltinWebSearch = useChatRuntimeStore( (s) => s.supportsBuiltinWebSearch, ); const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled); const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled); const codeToolsEnabled = useChatRuntimeStore(codeToolsOn); const setCodeToolsEnabled = useChatRuntimeStore((s) => s.setCodeToolsEnabled); const imageToolsEnabled = useChatRuntimeStore((s) => s.imageToolsEnabled); const setImageToolsEnabled = useChatRuntimeStore( (s) => s.setImageToolsEnabled, ); const mcpEnabledForChat = useChatRuntimeStore((s) => s.mcpEnabledForChat); const setMcpEnabledForChat = useChatRuntimeStore( (s) => s.setMcpEnabledForChat, ); const { projects } = useChatProjects(); const recentProjects = [...projects] .sort((a, b) => b.updatedAt - a.updatedAt) .slice(0, 3); const openProject = (projectId: string) => { useChatRuntimeStore.getState().setActiveProjectId(projectId); navigate({ to: "/chat", search: { project: projectId } }); }; const webFetchToolsEnabled = useChatRuntimeStore( (s) => s.webFetchToolsEnabled, ); const setWebFetchToolsEnabled = useChatRuntimeStore( (s) => s.setWebFetchToolsEnabled, ); const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled); const setRagEnabled = useChatRuntimeStore((s) => s.setRagEnabled); const exportThreadIds = [model1ThreadId, model2ThreadId].filter( (id): id is string => Boolean(id), ); const lastOpenRouterChosenModel = useChatRuntimeStore( (s) => s.lastOpenRouterChosenModel, ); useSyncExternalStore(subscribeModelCatalog, modelCatalogVersion); const externalSelection = parseExternalModelId(checkpoint); const isExternalModel = externalSelection !== null; const selectedExternalProvider = externalSelection != null ? externalProviders.find((p) => p.id === externalSelection.providerId) : undefined; const imageUnavailableReason = getImageInputUnavailableReason({ activeModel, isExternalModel, externalSupportsVision: providerModelSupportsVision( selectedExternalProvider?.providerType, externalSelection?.modelId, ), externalModelLabel: externalSelection?.modelId ?? null, loadedIsMultimodal, modelLoaded, loadError: lastModelLoadError, visionDisabledByUser: loadedVisionDisabledByUser, mmprojFallbackReason, }); const isCompareMode = Boolean(model1?.id || model2?.id); // Compare defers the image check to send: the catalog can lag real capabilities. const attachUnavailableReason = isCompareMode ? null : imageUnavailableReason; const effectiveExternalModelId = selectedExternalProvider?.providerType === "openrouter" && externalSelection?.modelId === "openrouter/free" && lastOpenRouterChosenModel ? lastOpenRouterChosenModel : externalSelection?.modelId; const externalReasoningCaps = externalSelection != null ? getExternalReasoningCapabilities( selectedExternalProvider?.providerType, externalSelection?.modelId, { isReasoningProvider: selectedExternalProvider?.isReasoningModel === true, baseUrl: selectedExternalProvider?.baseUrl ?? null, apiType: selectedExternalProvider?.apiType, reasoningConfig: selectedExternalProvider?.reasoningConfig, }, ) : null; const isExternalOpenAIReasoning = externalReasoningCaps?.supportsReasoning === true && externalReasoningCaps.reasoningStyle === "reasoning_effort"; const effectiveReasoningStyle = externalReasoningCaps?.reasoningStyle ?? reasoningStyle; const effectiveReasoningAlwaysOn = externalReasoningCaps?.reasoningAlwaysOn ?? reasoningAlwaysOn; const effectiveSupportsReasoningOff = externalReasoningCaps?.supportsReasoningOff ?? supportsReasoningOff; const effectiveReasoningEffortLevels = externalReasoningCaps?.reasoningEffortLevels ?? reasoningEffortLevels; const effectiveSupportsReasoning = externalReasoningCaps?.supportsReasoning ?? supportsReasoning; const reasoningLockedOn = effectiveSupportsReasoning && (effectiveReasoningAlwaysOn || !effectiveSupportsReasoningOff); // Kimi's $web_search builtin mandates thinking=disabled // (https://platform.kimi.ai/docs/guide/use-web-search). Both pills stay clickable, but turning // one on flips the other off, so the visible state matches what the backend sends. const isKimiExternal = kimiSearchExcludesThinking( selectedExternalProvider?.providerType, externalSelection?.modelId, ); const effectiveReasoningEnabled = reasoningLockedOn ? true : reasoningEnabled; // Show the stored effort clamped to the current ladder without overwriting the choice. const displayedEffort = effectiveReasoningEffortLevels.length > 0 ? clampReasoningEffortToLevels(reasoningEffort, effectiveReasoningEffortLevels) : reasoningEffort; const effectiveReasoningVisualEnabled = effectiveReasoningEnabled && displayedEffort !== "none"; const reasoningDisabled = !modelLoaded || !(effectiveSupportsReasoning || supportsPreserveThinking); const showReasoningControl = effectiveSupportsReasoning || effectiveReasoningAlwaysOn || supportsPreserveThinking; const isEffort = effectiveReasoningStyle === "reasoning_effort" || effectiveReasoningStyle === "enable_thinking_effort"; const narrowEffortMenu = effectiveReasoningStyle === "enable_thinking_effort" && !supportsPreserveThinking; const thinkingActiveLook = !effectiveSupportsReasoning ? preserveThinking && !reasoningDisabled : isEffort ? reasoningLockedOn || (effectiveReasoningVisualEnabled && !reasoningDisabled) : reasoningLockedOn || (effectiveReasoningEnabled && !reasoningDisabled); // Code never falls back to local execution when a hosted model lacks code support. const supportsBuiltinCodeExecution = providerSupportsBuiltinCodeExecution( selectedExternalProvider?.providerType, effectiveExternalModelId, selectedExternalProvider?.baseUrl, selectedExternalProvider?.apiType, ); const supportsBuiltinImageGeneration = providerSupportsBuiltinImageGeneration( selectedExternalProvider?.providerType, effectiveExternalModelId, selectedExternalProvider?.baseUrl, selectedExternalProvider?.apiType, ); const supportsBuiltinWebFetch = providerSupportsBuiltinWebFetch( selectedExternalProvider?.providerType, ); // Gemini rejects codeExecution alongside image modalities. const isExternalGemini = isGeminiApiProviderType(selectedExternalProvider?.providerType); // The image or video model loaded in Unsloth, reached through generate_image / generate_video. const localImageToolHere = useChatRuntimeStore((s) => localImageTool({ ...s, supportsBuiltinImageGeneration }), ); const localImagePills = useChatRuntimeStore((s) => localImagePillCount({ ...s, supportsBuiltinImageGeneration }), ); const imageDisabled = !modelLoaded || !(supportsBuiltinImageGeneration || localImageToolHere); const imageModeDisablesCode = isExternalGemini && imageToolsEnabled && modelLoaded && supportsBuiltinImageGeneration; // Image-tier Gemini models always reject codeExecution and reject web_search on older ids, so gate // strictly on provider builtin support: local `supportsTools` must not re-enable a pill the // Gemini backend silently drops. const isGeminiImageTier = isExternalGemini && supportsBuiltinImageGeneration; const searchDisabled = modelLoaded && (isGeminiImageTier ? !supportsBuiltinWebSearch : !(supportsTools || supportsBuiltinWebSearch)); const externalUsesStudioTools = providerModelSupportsStudioTools( selectedExternalProvider?.providerType, externalSelection?.modelId, ) === true; const canRunCode = isExternalModel ? codeToolCanRun({ hostedCodeExecutionForThisTurn: supportsBuiltinCodeExecution, providerHostsCodeExecution: providerHostsCodeExecution( selectedExternalProvider?.providerType, selectedExternalProvider?.baseUrl, selectedExternalProvider?.apiType, ), supportsStudioTools: externalUsesStudioTools, }) : supportsTools; const codeDisabled = (modelLoaded && (isGeminiImageTier || !canRunCode)) || imageModeDisablesCode; // Images pill: the provider's own image generation on OpenAI cloud Responses-API models and the // Gemini Nano Banana family, else the image or video model loaded in Unsloth when the chat // model calls Unsloth tools. const showImagePill = supportsBuiltinImageGeneration || localImageToolHere; // Fetch pill: Anthropic-only (web_fetch_20250910 / web_fetch_20260209). const webFetchDisabled = !modelLoaded || !supportsBuiltinWebFetch; const showWebFetchPill = supportsBuiltinWebFetch; const ragDisabled = modelLoaded && ((!externalUsesStudioTools && isExternalModel) || !supportsTools); const showRagPill = !isExternalModel || externalUsesStudioTools; // Above 4 pills, collapse to icons only. Compare, Search, Tools and permissions always show. // Narrow viewports collapse too: the labelled row is wider than a phone-width composer. const isMobile = useIsMobile(); const pillCount = 4 + (supportsBuiltinImageGeneration ? 1 : 0) + localImagePills + (showRagPill && ragEnabled ? 1 : 0) + (showWebFetchPill ? 1 : 0) + (mcpEnabledForChat ? 1 : 0); const { pillRowRef, pillCompact } = useComposerPillFit( isMobile || pillCount > 4, ); const toolsDisabled = codeDisabled; const setPendingAudioStore = useChatRuntimeStore((s) => s.setPendingAudio); const clearPendingAudioStore = useChatRuntimeStore( (s) => s.clearPendingAudio, ); const mirroredAudioRef = useRef(false); useEffect(() => { const [first] = pendingAudio; if (first) { setPendingAudioStore(first.base64, first.name); mirroredAudioRef.current = true; } else if (mirroredAudioRef.current) { clearPendingAudioStore(); mirroredAudioRef.current = false; } }, [pendingAudio, setPendingAudioStore, clearPendingAudioStore]); const { isDictating, isFinalizing: isDictationFinalizing, start: startDictationSession, stop: stopDictation, } = useDictation(setCurrentText); const chatActive = useChatActive(); const compareUploadInstanceId = useId(); const audioUploadOwner = `${compareUploadInstanceId}:${model1?.id ?? ""}:${model2?.id ?? ""}`; const readAudioUploadDraft = useCallback(() => textRef.current, []); const writeAudioUploadDraft = useCallback( (value: string) => setCurrentText(value), [setCurrentText], ); const focusAudioUploadDraft = useCallback(() => { textareaRef.current?.focus({ preventScroll: true }); }, []); const audioUpload = useChatAudioUpload({ owner: audioUploadOwner, chatId: null, disabled: isDictating || !chatActive, readDraft: readAudioUploadDraft, writeDraft: writeAudioUploadDraft, focusDraft: focusAudioUploadDraft, }); const startDictation = useCallback(() => { if (audioUpload.busy || !chatActive) return; if (currentDictationEntryMode() === "recording-file") { audioUpload.openDialog(); return; } startDictationSession(); }, [audioUpload, chatActive, startDictationSession]); useEffect(() => { const id = setInterval(() => { const handles = handlesRef.current; const any = Object.values(handles).some((h) => h.isRunning()); setRunning(any); }, 200); return () => clearInterval(id); }, [handlesRef]); function resetPromptQueue() { if (!isQueueRunningRef.current && queueRef.current.length === 0) { return; } isQueueRunningRef.current = false; setIsQueueRunning(false); queueRef.current = []; queueIndexRef.current = 0; setQueueProgress({ current: 0, total: 0 }); } function advanceQueue() { const nextIndex = queueIndexRef.current + 1; if (nextIndex >= queueRef.current.length) { resetPromptQueue(); toast.success("Prompt queue complete"); return; } queueIndexRef.current = nextIndex; setQueueProgress({ current: nextIndex + 1, total: queueRef.current.length }); const next = queueRef.current[nextIndex]; toast(`Prompt ${nextIndex + 1} / ${queueRef.current.length}`, { description: next.length > 80 ? next.slice(0, 80) + "…" : next, }); setCurrentText(next); setTimeout(() => { sendRef.current?.(); }, 100); } // Stop on a failed step so queued prompts are not burned on incomplete results. useEffect(() => { const wasComparing = prevComparingRef.current; prevComparingRef.current = comparing; if (!isQueueRunningRef.current || !wasComparing || comparing) return; if (!compareStepSucceededRef.current) { resetPromptQueue(); toast.error("Prompt queue stopped", { description: "A compare step failed; remaining prompts were not sent.", }); return; } prevRunningRef.current = false; advanceQueue(); }, [comparing]); useEffect(() => { const wasRunning = prevRunningRef.current; prevRunningRef.current = running; if (!isQueueRunningRef.current || !wasRunning || running || comparing) return; advanceQueue(); }, [running, comparing]); // The single composer's editor frame (animated height), measured by hand: no autosize here. const inputId = useId(); const uiSpaceScale = useUiSpaceScale(); const minEditorHeight = Math.round((16 + 24) * uiSpaceScale); const maxRows = useComposerMaxRows(24 * uiSpaceScale); const maxRowsRef = useRef(maxRows); maxRowsRef.current = maxRows; const [editorHeight, setEditorHeight] = useState(40); const [editorRows, setEditorRows] = useState(1); const [isWritingExpanded, setIsWritingExpanded] = useState(false); const editorRef = useRef(null); const measureEditor = useCallback(() => { const ta = textareaRef.current; if (!ta) return; // The frame clamps the textarea; lift that while measuring its content. ta.style.setProperty("max-height", "none", "important"); ta.style.setProperty("min-height", "0", "important"); ta.style.height = "auto"; const styles = window.getComputedStyle(ta); const lineHeight = parseFloat(styles.lineHeight) || 24; const paddingY = parseFloat(styles.paddingTop) + parseFloat(styles.paddingBottom); const maxHeight = lineHeight * maxRowsRef.current + paddingY; const content = ta.scrollHeight; const next = Math.min(content, maxHeight); ta.style.height = ""; ta.style.removeProperty("max-height"); ta.style.removeProperty("min-height"); ta.style.overflowY = content > maxHeight ? "auto" : "hidden"; setEditorHeight(next); setEditorRows(Math.round((next - paddingY) / lineHeight)); }, []); useEffect(measureEditor, [text, maxRows]); // Width only: wrapping follows it, while the height is the frame's own animation. useEffect(() => { const editor = editorRef.current; if (!editor) return; let width = editor.clientWidth; const observer = new ResizeObserver(() => { if (editor.clientWidth === width) return; width = editor.clientWidth; measureEditor(); }); observer.observe(editor); return () => observer.disconnect(); }, [measureEditor]); // Window capture: runs before the mention popover's own Escape closes it. useEffect(() => { const collapseOnEscape = (event: globalThis.KeyboardEvent) => { if ( event.key === "Escape" && !event.isComposing && !mentionOpenRef.current && event.target instanceof Node && editorRef.current?.contains(event.target) ) { setIsWritingExpanded(false); } }; window.addEventListener("keydown", collapseOnEscape, true); return () => window.removeEventListener("keydown", collapseOnEscape, true); }, []); const showWritingToggle = text.includes("\n") || editorRows > 3; const toggleWritingExpanded = () => { setIsWritingExpanded((expanded) => !expanded); textareaRef.current?.focus({ preventScroll: true }); }; useExpandedComposerFill(editorRef, isWritingExpanded, true); const addFilesUntracked = useCallback( async (input: FileList | readonly File[] | null) => { if (!input?.length) return; // Classify first so an audio-only 3GP is not refused as video by extension. const files = await classifiedAttachmentFiles(input); const next: PendingImage[] = []; let droppedImageForUnavailable = false; let audioAddError: string | null = null; let videoUnsupported = false; let conversionError: string | null = null; for (let i = 0; i < files.length; i++) { const file = files[i]; if (!file) continue; if (isAudioAttachmentFile(file)) { const counted = [ ...pendingAudioRef.current.map((clip) => clip.size), ...readingAudioRef.current.values(), ]; const addError = getAudioAddError( counted.length, counted.reduce((total, size) => total + size, 0), file.size, ); if (addError) { audioAddError ??= addError; continue; } const clip = { id: newAttachmentId(), name: file.name, base64: "", contentType: file.type, size: file.size, }; readingAudioRef.current.set(clip.id, clip.size); try { clip.base64 = await fileToBase64(file); } catch { toast.error("Could not read that audio file."); continue; } finally { readingAudioRef.current.delete(clip.id); } // Updated now, not on commit, so the next check already counts it. pendingAudioRef.current = [...pendingAudioRef.current, clip]; setPendingAudio((prev) => [...prev, clip]); continue; } // video_base64 targets one loaded GGUF, so only one compare side could answer. if (isVideoFile(file)) { videoUnsupported = true; continue; } if (!isChatImageFile(file)) continue; if (attachUnavailableReason) { droppedImageForUnavailable = true; continue; } const sizeError = getChatImageSizeError(file); if (sizeError) { toast.error(sizeError); continue; } let image: File; setConvertingImages((count) => count + 1); try { image = await normalizeChatImage(file); } catch (error) { conversionError ??= error instanceof Error ? error.message : String(error); continue; } finally { setConvertingImages((count) => count - 1); } next.push({ id: crypto.randomUUID(), file: image }); } if (droppedImageForUnavailable && attachUnavailableReason) { toast.error(attachUnavailableReason); } if (audioAddError) { toast.error(audioAddError); } if (conversionError) { toast.error(conversionError); } if (videoUnsupported) { toast.error("Video can't be attached in compare mode", { description: "Open a single chat with a video-capable model instead.", }); } setPendingImages((prev) => [...prev, ...next]); }, [attachUnavailableReason], ); const [addingFiles, setAddingFiles] = useState(0); const trackAttaching = useCallback(async (work: () => Promise) => { attachingRef.current += 1; setAddingFiles((count) => count + 1); try { await work(); } finally { attachingRef.current -= 1; setAddingFiles((count) => count - 1); } }, []); const addFiles = useCallback( (input: FileList | readonly File[] | null) => trackAttaching(() => addFilesUntracked(input)), [trackAttaching, addFilesUntracked], ); // Plain paste: a paste event carries no modifiers, so the chord is read from the keydown before it. const plainPasteAtRef = useRef(0); const handleFilePaste = useCallback( (event: ClipboardEvent) => { const plainPaste = plainPasteStillCounts(plainPasteAtRef.current, performance.now()); plainPasteAtRef.current = 0; pasteClipboardFiles( event, (pasted) => trackAttaching(async () => { // Classify first so a pasted audio-only 3GP is not rejected by extension. const files = await classifiedAttachmentFiles(pasted); // Let addFiles report audio and image size errors. const supported = files.some( (file) => isAudioAttachmentFile(file) || isChatImageFile(file), ); if (!supported) throw new Error("Unsupported compare attachment"); await addFilesUntracked(files); }), () => toast.error("Could not paste files.", { description: "Compare supports images and audio within the attachment size limits.", }), ); if (event.defaultPrevented || !richTextPaste || plainPaste) return; const markdown = richPasteMarkdown(event.clipboardData); if (markdown === null) return; event.preventDefault(); const input = event.currentTarget; insertAtCaret(input, markdown, (next, caret) => { setCurrentText(next); requestAnimationFrame(() => input.setSelectionRange(caret, caret)); }); }, [trackAttaching, addFilesUntracked, richTextPaste, setCurrentText], ); const removePendingImage = useCallback((id: string) => { setPendingImages((prev) => prev.filter((p) => p.id !== id)); }, []); function clearStuckImeTimer() { if (stuckImeTimerRef.current) { clearTimeout(stuckImeTimerRef.current); stuckImeTimerRef.current = null; } } function setCompositionState(next: boolean) { composingRef.current = next; setIsComposing(next); clearStuckImeTimer(); if (next) { stuckImeTimerRef.current = setTimeout(() => { stuckImeTimerRef.current = null; composingRef.current = false; setIsComposing(false); }, IME_STUCK_TIMEOUT_MS); } } function refreshStuckImeTimer() { if (!composingRef.current) { return; } clearStuckImeTimer(); stuckImeTimerRef.current = setTimeout(() => { stuckImeTimerRef.current = null; composingRef.current = false; setIsComposing(false); }, IME_STUCK_TIMEOUT_MS); } useEffect(() => () => clearStuckImeTimer(), []); async function send() { if (composingRef.current || convertingImages > 0 || addingFiles > 0) { resetPromptQueue(); return; } const submittedText = text; const submittedImages = pendingImages; const submittedAudio = pendingAudio; const msg = submittedText.trim(); if (!msg && submittedImages.length === 0 && submittedAudio.length === 0) { 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; // Both panes need a model: a half-selected send races to an empty bubble. if (hasCompareHandles && !isGeneralizedCompare) { toast.error("Pick a model in each pane to compare", { description: "Use the model dropdown above each pane, then send your prompt.", }); resetPromptQueue(); return; } if ( submittedImages.length > 0 && !isGeneralizedCompare && imageUnavailableReason ) { toast.error(imageUnavailableReason); resetPromptQueue(); return; } const content: CompareMessagePart[] = []; for (const { file } of submittedImages) { try { const image = await fileToBase64DataURL(file); content.push({ type: "image", image }); } catch { } } for (const clip of submittedAudio) { content.push({ type: "audio", name: clip.name, audio: `data:${clip.contentType};base64,${clip.base64}`, }); } if (msg) { content.push({ type: "text", text: msg }); } if (content.length === 0) { resetPromptQueue(); return; } let compareLifecycleLease: ModelLifecycleLease | null = null; if (isGeneralizedCompare) { compareLifecycleLease = useChatRuntimeStore .getState() .beginModelLoading("preparing"); if (compareLifecycleLease === null) { toast.info("A model is loading", { description: "Wait for it to finish or cancel it first.", }); resetPromptQueue(); return; } } const releaseCompareModelLifecycle = () => { if (compareLifecycleLease === null) { return; } useChatRuntimeStore.getState().endModelLoading(compareLifecycleLease); compareLifecycleLease = null; }; const acquireCompareModelLifecycle = () => { if (compareLifecycleLease !== null) { return; } compareLifecycleLease = useChatRuntimeStore .getState() .beginModelLoading("preparing"); if (compareLifecycleLease === null) { throw new Error("Another model load started during comparison"); } }; const submittedDraftIsCurrent = () => textRef.current === submittedText && pendingImagesRef.current === submittedImages && pendingAudioRef.current === submittedAudio; const keepChangedDraft = () => { releaseCompareModelLifecycle(); resetPromptQueue(); toast.info("Message changed while preparing", { description: "Your updated draft was kept. Send it again when ready.", }); }; const clearSubmittedDraft = () => { if (unsentPair) { unsavedDraftRef.current = null; if (!shareDraft) writeComposerDraft(draftKey, ""); } onPairSubmitted(); setCurrentText(""); setIsWritingExpanded(false); setPendingImages([]); setPendingAudio([]); clearPendingAudioStore(); textareaRef.current?.focus(); }; let compareStopDecision: Awaited< ReturnType > | null = null; if (isGeneralizedCompare) { try { compareStopDecision = await confirmStopRunningChatsIfNeeded( "Loading models for comparison", "reload", ); } catch (error) { releaseCompareModelLifecycle(); resetPromptQueue(); toast.error("Compare failed", { description: error instanceof Error ? error.message : "Unknown error", }); return; } if (!compareStopDecision.proceed) { releaseCompareModelLifecycle(); resetPromptQueue(); return; } } if (!submittedDraftIsCurrent()) { keepChangedDraft(); return; } if (isGeneralizedCompare) { const store = useChatRuntimeStore.getState(); const trustRemoteCode = store.params.trustRemoteCode ?? false; const fallbackTensorParallel = store.tensorParallel; const specSettings = resolveSpeculativeSettingsForLoad({ usePersistedPreference: true, }); let loadedFromConfig = false; // Warm the device cache first: on a cold cache the reconcile passes a stale GPU pick. try { if (store.selectedGpuIds != null) { await ensureGpuDeviceCache(); } } catch (error) { releaseCompareModelLifecycle(); resetPromptQueue(); toast.error("Compare failed", { description: error instanceof Error ? error.message : "Unknown error", }); return; } // Snapshot at Send: the first load's echo rewrites the live store before model 2 loads. const compareLoadKnobs = { gpuMemoryMode: store.gpuMemoryMode, gpuLayers: store.gpuLayers, nCpuMoe: store.nCpuMoe, splitRatio: store.splitRatio, selectedGpuIds: store.selectedGpuIds, selectedGpuIndexKind: store.selectedGpuIndexKind, }; if (!submittedDraftIsCurrent()) { keepChangedDraft(); return; } audioUpload.cancel(); clearSubmittedDraft(); const run = compareRunsRef.current.begin(); const compareSignal = run.controller.signal; let upgradeUnloadedActive = false; const compareSelectionNeedsLoad = (sel: CompareModelSelection) => { if (isExternalModelId(sel.id)) return false; const currentStore = useChatRuntimeStore.getState(); const isAlreadyActive = currentStore.params.checkpoint === sel.id && (currentStore.activeGgufVariant ?? null) === (sel.ggufVariant ?? null); return !isAlreadyActive || sel.config != null || loadedFromConfig; }; const applyCompareStopDecision = () => { cancelPreStreamRunReservations( compareStopDecision?.preStreamRunTokens ?? [], ); requestLocalPromptQueueStop(compareStopDecision?.promptQueueThreadIds); }; async function ensureModelLoaded( sel: CompareModelSelection, ): Promise { throwIfCompareCancelled(compareSignal); // Connected models run at the provider; /load would start the torch loader. const selectedId: string = sel.id; if (isExternalModelId(selectedId)) { const live = useChatRuntimeStore.getState(); if (live.params.checkpoint !== selectedId) live.setCheckpoint(selectedId, null); return "connected"; } const currentStore = useChatRuntimeStore.getState(); const config = sel.config ?? null; // Never the other pane's config; no saved config means all-null defaults. const resolved = config ? { config, remembered: true } : resolveResidentInitialConfig(sel.id, sel.ggufVariant ?? null); const ownConfig = resolved.config; const ownRemembered = resolved.remembered; const isAlreadyActive = currentStore.params.checkpoint === sel.id && (currentStore.activeGgufVariant ?? null) === (sel.ggufVariant ?? null); if (isAlreadyActive && !config && !loadedFromConfig) { applyCompareStopDecision(); return "ready"; } const targetIsGguf = (sel.ggufVariant ?? null) != null || sel.id.toLowerCase().endsWith(".gguf"); const platform = usePlatformStore.getState(); let resolvedIsDiffusion = sel.isDiffusion; let diffusionUnknown = false; if (targetIsGguf && resolvedIsDiffusion === undefined) { const preparedToken = await prepareHfTokenForUse( currentStore.hfToken, ); if (!preparedToken.proceed) { throw new Error("Model load cancelled."); } const staged = await fetchGgufStagedMetadata({ model_path: sel.id, gguf_variant: sel.ggufVariant ?? null, hf_token: preparedToken.token, }); resolvedIsDiffusion = staged.isDiffusion; diffusionUnknown = staged.diffusionUnknown; } // /load inherits pass-through args from a resident instance, which a cold pane lacks. if ( targetIsGguf && resolvedIsDiffusion !== true ) { try { // Sanitised because explicit /load args are validated strictly; denied flags would 400. const managed = await loadManagedLlamaFlags(); const clean = (tokens: readonly string[]) => sanitizeStoredExtraArgs( tokens, managed?.managed ?? new Set(), { maxBytes: managed?.maxBytes, windowsCommandBudget: managed?.windowsCommandBudget, }, ); const local = ownConfig.llamaExtraArgs; if (local === undefined) { const resolvedArgs = await fetchLoadExtraArgs( sel.id, sel.id, sel.ggufVariant ?? null, ); const cleaned = clean(resolvedArgs.tokens); if (cleaned.length > 0) { ownConfig.llamaExtraArgs = cleaned; } else if (resolvedArgs.explicit) { // Send an explicit empty list, or /load carries the resident model's args over. ownConfig.llamaExtraArgs = []; } } else if (local !== null && local.length > 0) { const cleaned = clean(local); if (cleaned.length !== local.length) { ownConfig.llamaExtraArgs = cleaned.length > 0 ? cleaned : []; } } } catch { // The load still works; a real overrides outage surfaces there. } } // Without explicit context, let the local backend size it; else the app default, not 128K. const effectiveMaxSeqLength = savedContextPin(ownConfig) ?? unpinnedLoadContext( targetIsGguf, isServedByMlx( targetIsGguf, platform.deviceType, platform.chatOnlyReason, platform.mlxInference, ), DEFAULT_MAX_SEQ_LENGTH, ); const effectiveChatTemplateOverride = cleanCompareChatTemplate( ownConfig.chatTemplateOverride, ); const targetIsMlx = isServedByMlx( targetIsGguf, platform.deviceType, platform.chatOnlyReason, platform.mlxInference, ); const effectiveSpeculativeType = resolveSpeculativeType( ownConfig.speculativeType, specSettings.speculativeType ?? "auto", targetIsMlx, ); const effectiveSpecDraftNMax = ownRemembered ? resolveCompareSpecDraftNMax( effectiveSpeculativeType, ownConfig.specDraftNMax, ) : specSettings.specDraftNMax; const effectiveTensorParallel = resolvedIsDiffusion ? false : ownRemembered ? ownConfig.tensorParallel : fallbackTensorParallel; // Unconfigured panes get the per-model default (vision on), not the store's value. const effectiveDisableVision = resolvedIsDiffusion ? false : ownRemembered ? ownConfig.disableVision : DEFAULT_PER_MODEL_CONFIG.disableVision; if (ownConfig.selectedGpuIds != null) { await ensureGpuDeviceCache(); } // A pane's own split is sent; the shared snapshot is not, as it is bounded by another GGUF. const { gpuMemoryMode: effectiveGpuMemoryMode, gpuLayers: effectiveGpuLayers, } = resolveComparePlacement( ownConfig, compareLoadKnobs, shouldPinDiffusionPlacement( targetIsGguf, resolvedIsDiffusion, diffusionUnknown, ), ); const effectiveNCpuMoe = resolvedIsDiffusion ? 0 : (ownConfig.nCpuMoe ?? compareLoadKnobs.nCpuMoe); const effectiveSelectedGpuIds = ownConfig.selectedGpuIds !== undefined ? reconcilePersistedGpuIds( ownConfig.selectedGpuIds, ownConfig.selectedGpuIndexKind, resolvedIsDiffusion === true, ) : reconcilePersistedGpuIds( compareLoadKnobs.selectedGpuIds, compareLoadKnobs.selectedGpuIndexKind, resolvedIsDiffusion === true, ); // Own config only: inheriting the shared snapshot would be treated as a pin. const effectiveCustomContextLength = ownConfig.customContextLength; const paneEngine = targetIsGguf ? "auto" : (ownConfig.engine ?? "auto"); let paneEngineFields = { engine: paneEngine, engine_precision: ownConfig.enginePrecision ?? "auto", engine_parallelism: ownConfig.engineParallelism ?? "tensor", ...engineLaunchFieldsFromParams(ownConfig), load_in_4bit: paneEngine === "auto" && ownConfig.loadIn4bit !== false, ...(paneEngine !== "auto" && ownConfig.selectedGpuIds !== undefined ? { gpu_ids: reconcilePersistedGpuIds( ownConfig.selectedGpuIds, ownConfig.selectedGpuIndexKind, false, ) ?? undefined, } : {}), }; let loadTrustRemoteCode = trustRemoteCode; let approvedRemoteCodeFingerprint: string | null = null; const compareMaxSeqLength = resolveFitMaxSeqLength( targetIsGguf, effectiveGpuMemoryMode, effectiveGpuLayers, effectiveCustomContextLength, effectiveMaxSeqLength, ); // Build lazily: the engine offer can replace paneEngineFields before revalidation. const panePayload = (): LoadModelRequest => ({ model_path: sel.id, hf_token: currentStore.hfToken || null, max_seq_length: compareMaxSeqLength, ...paneEngineFields, is_lora: sel.isLora, gguf_variant: sel.ggufVariant ?? null, trust_remote_code: loadTrustRemoteCode, chat_template_override: effectiveChatTemplateOverride, cache_type_kv: ownConfig.kvCacheDtype ?? null, mlx_kv_quant: ownConfig.mlxKvQuant ?? null, mlx_int8_prefill: ownConfig.mlxInt8Prefill ?? false, mlx_ane_prefill: ownConfig.mlxAnePrefill ?? false, mlx_fast_verify: ownConfig.mlxFastVerify ?? false, mlx_preserve_dtype: ownConfig.mlxPreserveDtype ?? false, mlx_ple_offload: ownConfig.mlxPleOffload ?? null, mlx_expert_offload: ownConfig.mlxExpertOffload ?? null, speculative_type: effectiveSpeculativeType, spec_draft_n_max: effectiveSpecDraftNMax, ...(targetIsMlx ? { spec_draft_model: ownConfig.specDraftModel ?? null } : {}), tensor_parallel: effectiveTensorParallel, disable_vision: effectiveDisableVision, n_parallel: ownConfig.nParallel ?? null, ...llamaServerLoadFields(ownConfig, { isGguf: targetIsGguf, isDiffusion: resolvedIsDiffusion === true, isMlx: targetIsMlx, }), // GGUF-only: a non-GGUF target must not inherit a hidden GGUF GPU pick. A manual DiffusionGemma // split keeps its layer count, or it is judged a full-GGUF occupant. ...(targetIsGguf ? { gpu_memory_mode: effectiveGpuMemoryMode, gpu_layers: effectiveGpuLayers, n_cpu_moe: effectiveNCpuMoe, tensor_split: compareLoadKnobs.splitRatio ?? undefined, gpu_ids: effectiveSelectedGpuIds ?? undefined, } : {}), }); const validation = await validateModel(panePayload(), { signal: compareSignal, }); throwIfCompareCancelled(compareSignal); // Same offer as the primary picker: the default engine cannot run it (#8861). const engineOffer = paneEngine === "auto" ? validation.managed_engine_offer : null; if (engineOffer) { const engine = await confirmManagedEngineIfNeeded( sel.id, engineOffer, compareSignal, ); throwIfCompareCancelled(compareSignal); if (!engine) { throw new Error( `${compareModelDisplayName(sel.id)} is quantized with ${engineOffer.quantization}, which the default engine cannot run. Set Inference engine to ${engineOffer.engines[0] === "sglang" ? "SGLang" : "vLLM"} in its run settings to load it.`, ); } paneEngineFields = { engine, engine_precision: "auto", engine_parallelism: "tensor", ...DEFAULT_ENGINE_LAUNCH_FIELDS, load_in_4bit: false, ...(ownConfig.selectedGpuIds !== undefined ? { gpu_ids: reconcilePersistedGpuIds( ownConfig.selectedGpuIds, ownConfig.selectedGpuIndexKind, false, ) ?? undefined, } : {}), }; Object.assign( validation, await validateModel(panePayload(), { signal: compareSignal }), ); throwIfCompareCancelled(compareSignal); } // Upgrade dialog first (mirrors the primary load path). if (validation.requires_transformers_upgrade) { const upgraded = await confirmTransformersUpgradeIfNeeded({ modelName: sel.id, upgrade: validation.transformers_upgrade, trustRemoteCodeFallback: validation.requires_trust_remote_code, forceCancelActive: compareStopDecision?.forceCancelActive ?? false, }); // Unloads the active model even if the swap fails; a later cancel must stop the UI pointing at it. if ( useTransformersUpgradeDialogStore .getState() .consumeServerUnloadedChat() && currentStore.params.checkpoint ) { upgradeUnloadedActive = true; } if (!upgraded) { throw new Error( `${compareModelDisplayName(sel.id)} needs a newer transformers release to load.`, ); } } if ( validation.requires_trust_remote_code || validation.requires_security_review ) { const approved = await confirmRemoteCodeIfNeeded({ modelName: sel.id, hfToken: currentStore.hfToken || null, requiresTrustRemoteCode: true, onApprove: (fp) => { loadTrustRemoteCode = true; approvedRemoteCodeFingerprint = fp; }, }); if (!approved) { throw new Error( `${compareModelDisplayName(sel.id)} needs custom code approval to load.`, ); } } throwIfCompareCancelled(compareSignal); applyCompareStopDecision(); const loadRequestId = crypto.randomUUID(); const resp = await loadModel({ ...panePayload(), hf_token: useChatRuntimeStore.getState().hfToken || null, alongside: useChatRuntimeStore.getState().keepModelsLoaded, load_request_id: loadRequestId, approved_remote_code_fingerprint: approvedRemoteCodeFingerprint, force_cancel_active: compareStopDecision?.forceCancelActive ?? false, }, { 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, and never from MLX, which only reads it. if (ownConfig.speculativeType == null && !targetIsMlx) { saveSpeculativeType(effectiveSpeculativeType); } persistGpuMemoryModeOnLoad(resp, effectiveGpuMemoryMode); const compareOffload = offloadWarning(offloadCountsFrom(resp)); if (compareOffload) { toast.warning( `${compareModelDisplayName(sel.id)} loaded${compareOffload.titleSuffix}`, { description: compareOffload.description, duration: 8000 }, ); } upgradeUnloadedActive = false; const store = useChatRuntimeStore.getState(); const paneMaxTokensCap = replayMaxTokensCap( loadedContextFields(resp).loadedContextLength ?? (!resp.is_gguf && effectiveMaxSeqLength > 0 ? effectiveMaxSeqLength : null), ); store.setCheckpoint( resp.model, resp.is_gguf ? (sel.ggufVariant ?? undefined) : null, { maxTokensCap: paneMaxTokensCap }, ); const paneState = useChatRuntimeStore.getState(); const paneParams = paneState.params; const paneQwenParams = resp.supports_reasoning ? recommendedValuesForPick( resolveQwenThinkingParams( resp.model, (resp.reasoning_always_on ?? false) || paneState.reasoningEnabled, ), paneState.activePresetSource, paneState.presetEditedKeys, ) : null; store.setParams( { ...mergeBackendRecommendedInference({ current: paneParams, response: resp, modelId: resp.model, presetSource: paneState.activePresetSource, presetEditedKeys: paneState.presetEditedKeys, loadedContextLength: loadedContextFields(resp).loadedContextLength, }), ...paneQwenParams, ...(targetIsGguf ? {} : { maxSeqLength: loadedContextForParams( loadedContextFields(resp).loadedContextLength, effectiveMaxSeqLength, paneParams.maxSeqLength, ), }), }, { fromModelDefaults: true, maxTokensCap: paneMaxTokensCap }, ); store.setModelRequiresTrustRemoteCode( resp.requires_trust_remote_code ?? false, ); // Own saved Context Length: the wire value is Auto-resolved, pinning it would freeze Auto. const keepCustomCtx = targetIsGguf ? resolveExplicitCtxPin(effectiveCustomContextLength) : retainedContextPin({ isMlx: isServedByMlx( targetIsGguf, platform.deviceType, platform.chatOnlyReason, platform.mlxInference, ), requestedContextLength: compareMaxSeqLength, }); // Diffusion ignores --parallel, so a count there would mint a phantom override. const committedSlots = ((resp.is_gguf ?? false) && !(resp.is_diffusion ?? false)) || (resp.is_mlx ?? false) ? (ownConfig.nParallel ?? null) : null; const committedNBatch = (targetIsGguf || targetIsMlx) && !(resp.is_diffusion ?? false) ? (ownConfig.nBatch ?? null) : null; const committedNUbatch = (targetIsGguf || targetIsMlx) && !(resp.is_diffusion ?? false) ? (ownConfig.nUbatch ?? null) : null; useChatRuntimeStore.setState({ supportsReasoning: resp.supports_reasoning ?? false, reasoningAlwaysOn: resp.reasoning_always_on ?? false, ...reasoningCapsFromLoad(resp), supportsPreserveThinking: resp.supports_preserve_thinking ?? false, preserveThinking: resolvePreserveThinkingOnLoad(resp), supportsTools: resp.supports_tools ?? false, deepResearchEnabled: resolveToolsEnabledOnLoad( resp.supports_tools ?? false, ).deepResearchEnabled, kvCacheDtype: resp.cache_type_kv ?? null, loadedKvCacheDtype: resp.cache_type_kv ?? null, ...mlxRuntimeStateFrom(resp), nParallel: committedSlots, loadedNParallel: committedSlots, reasoningBudget: (targetIsGguf || targetIsMlx) && !(resp.is_diffusion ?? false) ? (resp.reasoning_budget ?? ownConfig.reasoningBudget) : -1, loadedReasoningBudget: (targetIsGguf || targetIsMlx) && !(resp.is_diffusion ?? false) ? (resp.reasoning_budget ?? ownConfig.reasoningBudget) : -1, reasoningBudgetMessage: (targetIsGguf || targetIsMlx) && !(resp.is_diffusion ?? false) ? (resp.reasoning_budget_message ?? ownConfig.reasoningBudgetMessage) : "", loadedReasoningBudgetMessage: (targetIsGguf || targetIsMlx) && !(resp.is_diffusion ?? false) ? (resp.reasoning_budget_message ?? ownConfig.reasoningBudgetMessage) : "", loadedReasoningBudgetRequested: (targetIsGguf || targetIsMlx) && !resp.is_diffusion ? (resp.requested_reasoning_budget ?? ownConfig.reasoningBudget) : -1, loadedReasoningBudgetMessageRequested: (targetIsGguf || targetIsMlx) && !resp.is_diffusion ? (resp.requested_reasoning_budget_message ?? ownConfig.reasoningBudgetMessage) : "", nBatch: committedNBatch, loadedNBatch: committedNBatch, nUbatch: committedNUbatch, loadedNUbatch: committedNUbatch, ...(targetIsGguf && !(resp.is_diffusion ?? false) ? committedServerTuningState(ownConfig) : targetIsMlx ? committedMlxServerTuningState(ownConfig) : clearedServerTuningState()), // The status applier is held off during the load, so record this pane's args now. loadedLlamaExtraArgs: resp.requested_llama_extra_args !== undefined ? (resp.requested_llama_extra_args ?? []) : (ownConfig.llamaExtraArgs ?? null), tensorParallel: resp.tensor_parallel ?? false, loadedTensorParallel: resp.tensor_parallel ?? false, loadedEngine: resp.engine ?? "auto", loadedEnginePrecision: resp.engine_precision ?? "auto", loadedEngineParallelism: resp.engine_parallelism ?? "tensor", loadedEngineLaunch: engineLaunchFieldsFrom(resp), loadedDisableVision: resp.disable_vision ?? false, disableVision: resp.disable_vision ?? false, defaultChatTemplate: resp.chat_template ?? null, chatTemplateOverride: effectiveChatTemplateOverride, loadedChatTemplateOverride: effectiveChatTemplateOverride, loadedCustomContextLength: keepCustomCtx, ...loadedGpuMemoryFields(resp), loadedIsDiffusion: resp.is_diffusion ?? false, loadedIsMultimodal: isMultimodalResponse(resp), loadedVisionDisabledByUser: resp.vision_disabled_by_user ?? false, mmprojFallbackReason: resp.mmproj_fallback_reason ?? null, activeModelIsLocal: resp.is_local_model ?? false, customContextLength: keepCustomCtx, ...loadedContextFields(resp), // Compare loads carry no native lease; clear any stale token/expiry. activeNativePathToken: null, activeNativePathExpiresAtMs: null, ...resolveLoadedSpeculativeSettings(resp), }); loadedFromConfig = config != null; // /api/models/list can lag the model's actual state. const currentModels = useChatRuntimeStore.getState().models; const idx = currentModels.findIndex((m) => m.id === sel.id); const synced = { isVision: Boolean(resp.is_vision), isGguf: Boolean(resp.is_gguf), isMlx: Boolean(resp.is_mlx), isAudio: Boolean(resp.is_audio), audioType: resp.audio_type ?? null, hasAudioInput: Boolean(resp.has_audio_input), hasVideoInput: Boolean(resp.has_video_input), speaks: Boolean(resp.speaks), }; if (idx === -1) { store.setModels([ ...currentModels, { id: sel.id, name: resp.display_name ?? sel.id, isLora: sel.isLora, ...synced, }, ]); } else { const next = [...currentModels]; next[idx] = { ...next[idx], ...synced }; store.setModels(next); } return resp.status; } const handle1 = handlesRef.current["model1"]; const handle2 = handlesRef.current["model2"]; await Promise.all([ handle1?.appendMessage(content, model1), handle2?.appendMessage(content, model2), ]); const name1 = model1?.id ? compareModelDisplayName(model1.id) : ""; const name2 = model2?.id ? compareModelDisplayName(model2.id) : ""; const toastId = toast("Comparing models…", { duration: Infinity }); setComparing(true); onComparingChange?.(true); try { if (handle1 && model1?.id) { toast("Loading Model 1…", { id: toastId, description: name1, duration: Infinity, }); const status1 = await ensureModelLoaded(model1); throwIfCompareCancelled(compareSignal); releaseCompareModelLifecycle(); toast("Generating with Model 1…", { id: toastId, description: `${name1} (${status1})`, duration: Infinity, }); const done = handle1.waitForRunEnd(); handle1.startRun(); await done; throwIfCompareCancelled(compareSignal); } if (handle2 && model2?.id) { acquireCompareModelLifecycle(); const needsLoad = compareSelectionNeedsLoad(model2); if (needsLoad) { const currentStopDecision = await confirmStopRunningChatsIfNeeded( "Loading the second model for comparison", "reload", ); if (!currentStopDecision.proceed) { throw new Error("Second comparison model load cancelled."); } throwIfCompareCancelled(compareSignal); compareStopDecision = currentStopDecision; toast("Loading Model 2…", { id: toastId, description: name2, duration: Infinity, }); } const status2 = await ensureModelLoaded(model2); throwIfCompareCancelled(compareSignal); releaseCompareModelLifecycle(); toast("Generating with Model 2…", { id: toastId, description: `${name2} (${status2})`, duration: Infinity, }); const done = handle2.waitForRunEnd(); handle2.startRun(); await done; throwIfCompareCancelled(compareSignal); } compareStepSucceededRef.current = true; toast.success("Compare complete", { id: toastId, duration: 2000 }); } 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"), ); // A load whose cancel failed keeps running; resyncing now would pin the outgoing model. if (cleanupError) { await waitForBackendLoadToSettle(); } await resyncInferenceStatusAfterServerModelChange(); } if (upgradeUnloadedActive) { useChatRuntimeStore.getState().clearCheckpoint(); } 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", action: failure instanceof LoadModelError ? managedEngineFailureLogsAction(failure.detail) : undefined, duration: cancelled ? 5000 : 4000, }, ); } finally { compareRunsRef.current.release(run); releaseCompareModelLifecycle(); setComparing(false); onComparingChange?.(false); } } else { 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); } } audioUpload.cancel(); clearSubmittedDraft(); for (const handle of handles) { handle.append(content); } } } sendRef.current = send; function stop() { if (isDictating) stopDictation(); const run = compareRunsRef.current.cancelCurrent(); // Aborting the fetch frees only the browser; /unload 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 load. unloadModel({ model_path: run.loadingModel.modelPath, cancel_load_request_id: run.loadingModel.requestId, }), ); } for (const handle of Object.values(handlesRef.current)) { handle.cancel(); } } const busy = running || comparing; function onKeyDown(e: KeyboardEvent) { const msSinceCompositionEnd = e.timeStamp - compositionEndedAtRef.current; compositionEndedAtRef.current = -Infinity; // IME: Enter commits the candidate (#5318); re-pin composingRef and re-arm the watchdog (#5546). const imeKey = e.nativeEvent.isComposing || e.keyCode === 229; if (imeKey) { if ( imeKeydownBlocksComposerSubmit( e, imeSessionOpenRef.current, msSinceCompositionEnd, ) ) { composingRef.current = true; refreshStuckImeTimer(); return; } setCompositionState(false); } // Non-IME key while composingRef is stuck; mirrors the fix in thread.tsx. if (composingRef.current) { // Candidate-confirming Enter can arrive as non-composing; keep it gated. if (e.key === "Enter") { if (!e.shiftKey) { e.preventDefault(); } refreshStuckImeTimer(); return; } setCompositionState(false); } if ( composerSubmitIntent( imeKey ? composerKeyEventForImeSubmit(e) : e, sendShortcut, text, ) ) { e.preventDefault(); if (!busy && !isDictating) { send(); } } } const canSend = (text.trim().length > 0 || pendingImages.length > 0 || pendingAudio.length > 0) && !busy && !isComposing && !isDictating && convertingImages === 0 && addingFiles === 0 && !sendUnavailableReason; useShortcut( "startDictation", () => { // Stop dictation first and ungated, so a recording stays stoppable behind a dialog. if (isDictating) { stopDictation(); return; } if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return; startDictation(); }, { enabled: chatActive }, ); // Through sendRef: `send` is render-scoped and cannot outlive the render. useShortcut( "sendMessage", () => { if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return; sendRef.current?.(); }, { enabled: chatActive && canSend, skipInTextFields: true, textFieldException: COMPOSER_INPUT_SELECTOR, }, ); const sendFollowUp = () => { if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return; sendRef.current?.(); }; const followUpOptions = { enabled: chatActive && canSend, skipInTextFields: true, textFieldException: COMPOSER_INPUT_SELECTOR, }; useShortcut("queueMessage", sendFollowUp, followUpOptions); useShortcut("steerMessage", sendFollowUp, followUpOptions); useShortcut( "attachFiles", () => { if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return; fileInputRef.current?.click(); }, { enabled: chatActive }, ); const [plusOpen, setPlusOpen] = useState(false); const setPlusMenuOpen = (open: boolean) => { setPlusOpen(open); if (open) void refreshRecentPrompts(); }; useShortcut( "openComposerMenu", () => { // The open menu inerts the composer, so closing skips the gate. if (plusOpen) return setPlusMenuOpen(false); if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return; setPlusMenuOpen(true); }, { enabled: chatActive }, ); useShortcut("stopGeneration", stop, { enabled: chatActive && busy, claims: () => isSurfaceInForeground(COMPOSER_INPUT_SELECTOR), }); const runPromptList = useCallback( (items: string[]) => { const filtered = items.filter((p) => p.trim()); if (!filtered.length) return; // `running` lags the 200ms poll, so ask the handles directly. const liveRunning = busy || Object.values(handlesRef.current).some((h) => h.isRunning()); if (liveRunning || isQueueRunningRef.current) { toast.error("Wait for the current response to finish"); return; } // A compare send holds the loading lease before `comparing` is set. if (useChatRuntimeStore.getState().modelLoading) { toast.info("A model is loading", { description: "Wait for it to finish or cancel it first.", }); return; } if (isDictating) { toast.error("Finish dictating before running a list"); return; } // send() cancels an in-flight transcription, which would discard it. if (audioUpload.busy) { toast.error("Wait for the transcription to finish before running a list"); return; } if ( pendingImagesRef.current.length > 0 || pendingAudioRef.current.length > 0 || attachingRef.current > 0 ) { toast.error("Remove the staged attachment before running a list", { description: "Only the first prompt in the list would carry it.", }); return; } const hasCompareHandles = Boolean( handlesRef.current["model1"] || handlesRef.current["model2"], ); const isGeneralizedCompare = hasCompareHandles && Boolean(model1?.id && model2?.id); if (hasCompareHandles && !isGeneralizedCompare) { toast.error("Pick a model in each pane to compare", { description: "Use the model dropdown above each pane, then send your prompt.", }); return; } setPromptStorageOpen(false); queueRef.current = filtered; queueIndexRef.current = 0; isQueueRunningRef.current = true; setIsQueueRunning(true); setQueueProgress({ current: 1, total: filtered.length }); toast(`Prompt 1 / ${filtered.length}`, { description: filtered[0].length > 80 ? `${filtered[0].slice(0, 80)}…` : filtered[0], }); setCurrentText(filtered[0]); setTimeout(() => { sendRef.current?.(); }, 100); }, [busy, isDictating, audioUpload.busy, handlesRef, model1?.id, model2?.id, setCurrentText], ); const plusMenuNodes: Record = { // Compare runs no research, so the item has nothing to offer here. deepResearch: null, browserUse: , computerUse: , chatWithFiles: ( { // As in the main composer: a hidden files panel comes back rather than RAG turning off. const { ragPanelHidden, setRagPanelHidden } = useChatRuntimeStore.getState(); if (ragEnabled && ragPanelHidden) { setRagPanelHidden(false); return; } setRagEnabled(!ragEnabled); }} > Chat with files {ragEnabled && !ragDisabled ? ( ) : null} ), mcp: ( setMcpEnabledForChat(!mcpEnabledForChat)} > MCP {mcpEnabledForChat ? ( ) : null} ), skills: ( setSkillsOn(!skillsOn)} > Skills {skillsOn ? ( ) : null} ), // Two chats at once, so this is the account-wide switch only. memory: , savedPrompts: ( Saved prompts {recentPrompts.map((p) => ( { insertSavedPrompt(textareaRef.current, p.text, setCurrentText); requestAnimationFrame(() => textareaRef.current?.focus()); }} > {p.name} ))} {recentLists.map((l) => ( runPromptList(l.items)}> {l.name} ))} {recentPrompts.length > 0 || recentLists.length > 0 ? ( ) : null} setPromptStorageOpen(true)}> All saved prompts… ), compareChat: ( Compare chat ), exportChat: ( Export chat ({ key: label, label }))} subContentClassName="unsloth-plus-menu w-[calc(176px*var(--ui-space-scale,1))]" onSelect={(label) => { const fn = composerExportFormats().find((f) => f.label === label)?.fn; if (!fn) return; if (!exportThreadIds.length) { toast.error("No conversation to export yet."); return; } (async () => { for (const id of exportThreadIds) { await fn(id); } })().catch((error) => { if (!isDownloadCancelled(error)) toast.error("Export failed."); }); }} /> ), projects: ( Projects setNewProjectOpen(true)}> New project Recents {recentProjects.length > 0 ? ( recentProjects.map((project) => ( openProject(project.id)} > {project.name} )) ) : ( No recent projects )} ), }; const { pinned: pinnedPlusItems, overflow: overflowPlusItems } = splitPlusMenuItems(plusOrder, plusPins); return (
{ insertSavedPrompt(textareaRef.current, t, setCurrentText); requestAnimationFrame(() => textareaRef.current?.focus()); }} onRunList={runPromptList} />
{ if (isTauri || isPortaledDrop(e)) return; e.preventDefault(); setDragging(true); }} onDragLeave={() => setDragging(false)} onDrop={(e) => { // Phase 1 native model drops own Tauri local-path drops. Restore browser attachment drops in // Tauri once Phase 1d adds token bridging. if (isTauri || isPortaledDrop(e)) return; e.preventDefault(); setDragging(false); void addFiles(e.dataTransfer.files); }} > {/* Gemini-style drop affordance, mirrored from the single composer; blurred only while shown (see thread.tsx). */}
Drop files here
{/* Always mounted and hidden while empty, the way the assistant-ui composer's own attachment strip is, so "no attachments" and "this markup moved" are different observations rather than the same absent node. `empty:hidden` keeps the rendered result identical to the previous conditional. */}
{pendingImages.map(({ id, file }) => ( removePendingImage(id)} /> ))} {pendingAudio.map((clip) => (
{clip.name}
))}
{skillMentions.popover}
{ void addFiles(e.target.files); e.target.value = ""; }} /> { void addFiles(e.target.files); e.target.value = ""; }} /> {/* Same + menu as single-chat (ComposerToolsMenu), wired to the compare composer's own file/audio inputs and tools. */} event.preventDefault()} > fileInputRef.current?.click()}> Add photos & files {activeModel?.hasAudioInput && ( audioInputRef.current?.click()} > Upload audio )} { const next = !toolsEnabled; setToolsEnabled(next); // Mirror the Search pill: Kimi forbids search + thinking together. if (isKimiExternal) { setReasoningEnabled(!next, { persist: false }); applyQwenThinkingParams(!next); } }} > Web search {toolsEnabled && !searchDisabled ? ( ) : null} setCodeToolsEnabled(!codeToolsEnabled)} > {/* Scale, not width: an oversized box pushed the label out of line. */} Tools {codeToolsEnabled && !codeDisabled ? ( ) : null} {showImagePill && ( setImageToolsEnabled(!imageToolsEnabled)} > Images {imageToolsEnabled && !imageDisabled ? ( ) : null} )} {/* Browser use sits right under Chat with files, or leads this section without it. */} {pinnedPlusItems.map((id) => ( {plusMenuNodes[id]} ))} More {overflowPlusItems.map((id) => ( {plusMenuNodes[id]} ))} {overflowPlusItems.length > 0 && } useSettingsDialogStore.getState().openDialog("chat", { scrollTarget: "chat-composer", })} > {t("composerSettings.settings")} {/* Active in compare mode; sits first. Click to exit back to single chat. */} {/* Permission-level pill sits immediately after Compare and ahead of every other tool pill so the Full access danger state reads first. */} {icon}} /> {icon}} /> {showImagePill && ( )} {showRagPill && } {showWebFetchPill && ( )} {mcpEnabledForChat ? : null}