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.

133 KB
Raw Blame
// 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 { mlxRuntimeStateFrom } from "./lib/mlx-runtime-state";
import { offloadCountsFrom, offloadWarning } from "./lib/partial-offload";
import { llamaServerLoadFields } from "./lib/load-request";
import {
  clearedServerTuningState,
  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 { 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 { 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 { 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,
  loadModel,
  unloadModel,
  validateModel,
} from "./api/chat-api";
import {
  CompareRunOwnership,
  isCompareCancellation,
  throwIfCompareCancelled,
} from "./compare-run-ownership";
import {
  loadedContextForParams,
  mergeBackendRecommendedInference,
  resolveExplicitCtxPin,
  resolveFitMaxSeqLength,
  retainedContextPin,
  unpinnedLoadContext,
  replayMaxTokensCap,
} from "./presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
  parseExternalModelId,
  providerModelSupportsVision,

  providerModelSupportsStudioTools,
} 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 { 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[]) => Promise<void>;
  startRun: () => void;
  cancel: () => void;
  isRunning: () => boolean;
  threadIds: () => string[];
  waitForRunEnd: () => Promise<void>;
}

// 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<string> {
  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<StudioDictationSession | null>(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<Record<string, CompareHandle>>;

const CompareHandlesContext = createContext<CompareHandles | null>(null);

export function CompareHandlesProvider({
  handlesRef,
  children,
}: {
  handlesRef: CompareHandles;
  children: ReactNode;
}): ReactElement {
  return (
    <CompareHandlesContext.Provider value={handlesRef}>
      {children}
    </CompareHandlesContext.Provider>
  );
}

export function RegisterCompareHandle({
  name,
}: {
  name: string;
}): ReactElement | null {
  const handlesRef = useContext(CompareHandlesContext);
  const aui = useAui();

  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) => {
        const count = aui.thread().getState().messages.length;
        aui.thread().append({
          role: "user",
          content,
          createdAt: new Date(),
          startRun: false,
        } as never);
        return new Promise<void>((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<void>((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]);

  return null;
}

type PendingImage = { id: string; file: File };

function PendingImageThumb({
  file,
  onRemove,
}: {
  file: File;
  onRemove: () => void;
}): ReactElement {
  const [src, setSrc] = useState<string | null>(null);
  useEffect(() => {
    const url = URL.createObjectURL(file);
    setSrc(url);
    return () => URL.revokeObjectURL(url);
  }, [file]);
  if (!src)
    return <div className="size-14 animate-pulse rounded-lg bg-muted" />;
  return (
    <div
      data-reload-snapshot-sensitive
      data-composer-attachment="image"
      className="relative size-14 shrink-0 overflow-hidden rounded-lg border border-[color-mix(in_oklab,var(--foreground)_calc(20%*var(--contrast-edge-gain,1)),transparent)] bg-muted"
    >
      <img src={src} alt={file.name} className="h-full w-full object-cover" />
      <button
        type="button"
        onClick={onRemove}
        className="absolute top-1 right-1 flex size-5 items-center justify-center rounded-full bg-white text-muted-foreground shadow-sm hover:bg-destructive hover:text-destructive-foreground"
        aria-label="Remove attachment"
      >
        <HugeiconsIcon icon={Cancel01Icon} className="size-3" />
      </button>
    </div>
  );
}

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 (
    <span className="composer-pill-glyph">
      {children}
      <HugeiconsIcon icon={Cancel01Icon} className="composer-pill-x" />
    </span>
  );
}

/** 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<void> {
  const deadline = Date.now() + LOAD_SETTLE_TIMEOUT_MS;
  while (Date.now() < deadline) {
    try {
      const status = await getInferenceStatus();
      if (status.loading.length === 0) return;
    } catch {
      // 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<string | null>(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<PendingImage[]>([]);
  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<string, number>());
  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<PromptEntry[]>([]);
  const [recentLists, setRecentLists] = useState<PromptListEntry[]>([]);
  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<string[]>([]);
  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<HTMLTextAreaElement>(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<ReturnType<typeof setTimeout> | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const audioInputRef = useRef<HTMLInputElement>(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 activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
  const exportThreadIds = [model1ThreadId, model2ThreadId, activeThreadId].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 = selectedExternalProvider?.providerType === "gemini";
  // 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 (12 rows, animated height), measured by hand: no autosize here.
  const inputId = useId();
  const oneRowHeight = Math.round(40 * useUiSpaceScale());
  const [editorHeight, setEditorHeight] = useState(40);
  const [editorRows, setEditorRows] = useState(1);
  const [isWritingExpanded, setIsWritingExpanded] = useState(false);
  const editorRef = useRef<HTMLDivElement>(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 * 12 + 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]);
  // 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<void>) => {
    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<HTMLTextAreaElement>) => {
      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<typeof confirmStopRunningChatsIfNeeded>
    > | 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) => {
        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<string> {
        throwIfCompareCancelled(compareSignal);
        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<string>(),
                {
                  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),
            DEFAULT_MAX_SEQ_LENGTH,
          );
        const effectiveChatTemplateOverride = cleanCompareChatTemplate(
          ownConfig.chatTemplateOverride,
        );
        const targetIsMlx = isServedByMlx(
          targetIsGguf,
          platform.deviceType,
          platform.chatOnlyReason,
        );
        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_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,
          }),
          // 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 &&
          paneState.activePresetSource === "builtin-default"
            ? resolveQwenThinkingParams(
                resp.model,
                (resp.reasoning_always_on ?? false) || paneState.reasoningEnabled,
              )
            : null;
        store.setParams(
          {
            ...mergeBackendRecommendedInference({
              current: paneParams,
              response: resp,
              modelId: resp.model,
              presetSource: paneState.activePresetSource,
              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,
              ),
              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 && !(resp.is_diffusion ?? false)
            ? (ownConfig.nBatch ?? null)
            : null;
        const committedNUbatch =
          targetIsGguf && !(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 && !(resp.is_diffusion ?? false)
              ? (resp.reasoning_budget ?? ownConfig.reasoningBudget)
              : -1,
          loadedReasoningBudget:
            targetIsGguf && !(resp.is_diffusion ?? false)
              ? (resp.reasoning_budget ?? ownConfig.reasoningBudget)
              : -1,
          reasoningBudgetMessage:
            targetIsGguf && !(resp.is_diffusion ?? false)
              ? (resp.reasoning_budget_message ??
                ownConfig.reasoningBudgetMessage)
              : "",
          loadedReasoningBudgetMessage:
            targetIsGguf && !(resp.is_diffusion ?? false)
              ? (resp.reasoning_budget_message ??
                ownConfig.reasoningBudgetMessage)
              : "",
          loadedReasoningBudgetRequested: targetIsGguf && !resp.is_diffusion
            ? (resp.requested_reasoning_budget ?? ownConfig.reasoningBudget)
            : -1,
          loadedReasoningBudgetMessageRequested: targetIsGguf && !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)
            : 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),
        handle2?.appendMessage(content),
      ]);

      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",
            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<PlusMenuItemId, ReactNode> = {
    // Compare runs no research, so the item has nothing to offer here.
    deepResearch: null,
    browserUse: <BrowserAgentMenuItem />,
    chatWithFiles: (
      <DropdownMenuItem
        disabled={ragDisabled}
        className={
          ragEnabled && !ragDisabled ? "text-primary font-medium" : undefined
        }
        onSelect={() => {
          // 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);
        }}
      >
        <HugeiconsIcon icon={FileSearchIcon} strokeWidth={2} />
        Chat with files
        {ragEnabled && !ragDisabled ? (
          <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
        ) : null}
      </DropdownMenuItem>
    ),
    mcp: (
      <DropdownMenuItem
        disabled={!supportsTools}
        className={mcpEnabledForChat ? "text-primary font-medium" : undefined}
        onSelect={() => setMcpEnabledForChat(!mcpEnabledForChat)}
      >
        <HugeiconsIcon icon={McpServerIcon} strokeWidth={2} />
        MCP
        {mcpEnabledForChat ? (
          <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
        ) : null}
      </DropdownMenuItem>
    ),
    skills: (
      <DropdownMenuItem
        className={skillsOn ? "text-primary font-medium" : undefined}
        onSelect={() => setSkillsOn(!skillsOn)}
      >
        <HugeiconsIcon icon={Scroll01Icon} strokeWidth={2} />
        Skills
        {skillsOn ? (
          <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
        ) : null}
      </DropdownMenuItem>
    ),
    savedPrompts: (
      <DropdownMenuSub>
        <DropdownMenuSubTrigger>
          <HugeiconsIcon icon={BookmarkIcon} strokeWidth={2} />
          Saved prompts
        </DropdownMenuSubTrigger>
        <DropdownMenuSubContent
          collisionPadding={16}
          className="unsloth-plus-menu w-[calc(208px*var(--ui-space-scale,1))]"
        >
          {recentPrompts.map((p) => (
            <DropdownMenuItem
              key={`prompt:${p.id}`}
              onSelect={() => {
                insertSavedPrompt(textareaRef.current, p.text, setCurrentText);
                requestAnimationFrame(() => textareaRef.current?.focus());
              }}
            >
              <span className="truncate">{p.name}</span>
            </DropdownMenuItem>
          ))}
          {recentLists.map((l) => (
            <DropdownMenuItem key={`list:${l.id}`} onSelect={() => runPromptList(l.items)}>
              <span className="truncate">{l.name}</span>
              <PromptCountBadge count={l.items.length} />
            </DropdownMenuItem>
          ))}
          {recentPrompts.length > 0 || recentLists.length > 0 ? (
            <DropdownMenuSeparator />
          ) : null}
          <DropdownMenuItem onSelect={() => setPromptStorageOpen(true)}>
            All saved prompts…
          </DropdownMenuItem>
        </DropdownMenuSubContent>
      </DropdownMenuSub>
    ),
    compareChat: (
      <DropdownMenuItem
        className="text-primary font-medium"
        onSelect={handleExitCompare}
      >
        <HugeiconsIcon icon={LayoutTwoColumnIcon} strokeWidth={2} />
        Compare chat
        <HugeiconsIcon icon={MenuTickIcon} strokeWidth={2} className="ml-auto" />
      </DropdownMenuItem>
    ),
    exportChat: (
      <DropdownMenuSub>
        <DropdownMenuSubTrigger disabled={exportThreadIds.length === 0}>
          <HugeiconsIcon icon={Download01Icon} strokeWidth={2} />
          Export chat
        </DropdownMenuSubTrigger>
        <DropdownMenuSubContent
          collisionPadding={16}
          className="unsloth-plus-menu w-[calc(208px*var(--ui-space-scale,1))]"
        >
          <ExportFormatItems
            options={composerExportFormats().map(({ label }) => ({ 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.");
              });
            }}
          />
        </DropdownMenuSubContent>
      </DropdownMenuSub>
    ),
    projects: (
      <DropdownMenuSub>
        <DropdownMenuSubTrigger>
          <HugeiconsIcon icon={ProjectIcon} strokeWidth={2} />
          Projects
        </DropdownMenuSubTrigger>
        <DropdownMenuSubContent className="unsloth-plus-menu w-[calc(232px*var(--ui-space-scale,1))]">
          <DropdownMenuItem onSelect={() => setNewProjectOpen(true)}>
            <HugeiconsIcon icon={FolderAddIcon} strokeWidth={2} />
            New project
          </DropdownMenuItem>
          <DropdownMenuLabel>Recents</DropdownMenuLabel>
          {recentProjects.length > 0 ? (
            recentProjects.map((project) => (
              <DropdownMenuItem
                key={project.id}
                onSelect={() => openProject(project.id)}
              >
                <HugeiconsIcon icon={ProjectIcon} strokeWidth={2} />
                <span className="truncate">{project.name}</span>
              </DropdownMenuItem>
            ))
          ) : (
            <DropdownMenuItem disabled={true}>
              No recent projects
            </DropdownMenuItem>
          )}
        </DropdownMenuSubContent>
      </DropdownMenuSub>
    ),
  };
  const { pinned: pinnedPlusItems, overflow: overflowPlusItems } =
    splitPlusMenuItems(plusOrder, plusPins);

  return (
    <div
      className="relative flex w-full flex-col"
      // Compare mode's composer, same as the thread's: find searches the conversation, not the
      // chrome around it. This one is rendered from `chat-page.tsx`, outside the marked one.
      {...{ [FIND_SKIP_ATTRIBUTE]: "" }}
      data-writing-expanded={isWritingExpanded ? "true" : undefined}
    >
      <ChatAudioUploadMount audioUpload={audioUpload} />

      <PromptStorageDialog
        open={promptStorageOpen}
        onOpenChange={setPromptStorageOpen}
        onUse={(t) => {
          insertSavedPrompt(textareaRef.current, t, setCurrentText);
          requestAnimationFrame(() => textareaRef.current?.focus());
        }}
        onRunList={runPromptList}
      />
      <div
        className="aui-composer-attachment-dropzone unsloth-composer-surface relative z-10"
        onDragOver={(e) => {
          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). */}
        <div
          className={`pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-1 overflow-hidden rounded-[inherit] bg-background/90 transition-opacity duration-150 dark:bg-card/90 ${dragging ? "opacity-100 backdrop-blur-sm" : "opacity-0"}`}
        >
          <HugeiconsIcon
            icon={Attachment01Icon}
            strokeWidth={2}
            className="size-6 text-primary"
          />
          <span className="text-sm font-medium text-primary">Drop files here</span>
        </div>
        {/* 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. */}
        <div
          data-composer-attachments=""
          className="mb-2 flex w-full flex-row flex-wrap items-center gap-2 px-1.5 pt-0.5 pb-1 empty:hidden"
        >
          {pendingImages.map(({ id, file }) => (
            <PendingImageThumb
              key={id}
              file={file}
              onRemove={() => removePendingImage(id)}
            />
          ))}
          {pendingAudio.map((clip) => (
            <div
              key={clip.id}
              data-composer-attachment="audio"
              className="flex items-center gap-2 rounded-full border border-[color-mix(in_oklab,var(--foreground)_calc(20%*var(--contrast-edge-gain,1)),transparent)] bg-muted px-3 py-1.5 text-xs"
            >
              <HugeiconsIcon icon={AiSpeechIcon} className="size-3.5 text-muted-foreground" />
              <span data-reload-snapshot-sensitive className="max-w-48 truncate">
                {clip.name}
              </span>
              <button
                type="button"
                onClick={() => {
                  setPendingAudio((prev) =>
                    prev.filter((other) => other.id !== clip.id),
                  );
                }}
                className="flex size-4 items-center justify-center rounded-full hover:bg-destructive hover:text-destructive-foreground"
                aria-label="Remove audio"
              >
                <HugeiconsIcon icon={Cancel01Icon} className="size-3" />
              </button>
            </div>
          ))}
        </div>
        {skillMentions.popover}
        <ComposerDraftPreview text={text} />

        <div
          className="unsloth-composer-line"
          // Always two rows: dictation types into the textarea, it never swaps in a bar.
          data-expanded="true"
        >
          <div
            ref={pillRowRef}
            className="unsloth-composer-left"
            data-pill-compact={pillCompact}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept={CHAT_IMAGE_ACCEPT}
              multiple
              className="hidden"
              onChange={(e) => {
                void addFiles(e.target.files);
                e.target.value = "";
              }}
            />
            <input
              ref={audioInputRef}
              type="file"
              accept={AUDIO_PICKER_ACCEPT}
              multiple
              className="hidden"
              onChange={(e) => {
                void addFiles(e.target.files);
                e.target.value = "";
              }}
            />
            <NewProjectDialog
              open={newProjectOpen}
              onOpenChange={setNewProjectOpen}
            />
            {/* Same + menu as single-chat (ComposerToolsMenu), wired to the compare composer's own file/audio
                inputs and tools. */}
            <DropdownMenu open={plusOpen} onOpenChange={setPlusMenuOpen}>
              <DropdownMenuTrigger asChild={true}>
                <button
                  type="button"
                  aria-label="Tools and attachments"
                  data-pill-label="Add files and more"
                  className="unsloth-composer-plus"
                >
                  <HugeiconsIcon icon={PlusSignIcon} className="size-[calc(22px*var(--ui-space-scale,1))] stroke-[1.75px]" />
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent
                side="top"
                align="start"
                sideOffset={0}
                avoidCollisions={true}
                className="unsloth-plus-menu w-[calc(244px*var(--ui-space-scale,1))]"
                onCloseAutoFocus={(event) => event.preventDefault()}
              >
                <DropdownMenuItem onSelect={() => fileInputRef.current?.click()}>
                  <HugeiconsIcon icon={Attachment01Icon} strokeWidth={2} />
                  Add photos &amp; files
                </DropdownMenuItem>
                {activeModel?.hasAudioInput && (
                  <DropdownMenuItem
                    onSelect={() => audioInputRef.current?.click()}
                  >
                    <HugeiconsIcon icon={AiSpeechIcon} strokeWidth={2} />
                    Upload audio
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem
                  disabled={searchDisabled}
                  className={
                    toolsEnabled && !searchDisabled
                      ? "text-primary font-medium"
                      : undefined
                  }
                  onSelect={() => {
                    const next = !toolsEnabled;
                    setToolsEnabled(next);
                    // Mirror the Search pill: Kimi forbids search + thinking together.
                    if (isKimiExternal) {
                      setReasoningEnabled(!next, { persist: false });
                      applyQwenThinkingParams(!next);
                    }
                  }}
                >
                  <InternetGlyph />
                  Web search
                  {toolsEnabled && !searchDisabled ? (
                    <HugeiconsIcon
                      icon={MenuTickIcon}
                      strokeWidth={2}
                      className="ml-auto"
                    />
                  ) : null}
                </DropdownMenuItem>
                <DropdownMenuItem
                  disabled={codeDisabled}
                  className={
                    codeToolsEnabled && !codeDisabled
                      ? "text-primary font-medium"
                      : undefined
                  }
                  onSelect={() => setCodeToolsEnabled(!codeToolsEnabled)}
                >
                  {/* Scale, not width: an oversized box pushed the label out of line. */}
                  <HugeiconsIcon
                    icon={CodeIcon}
                    strokeWidth={2}
                    className="scale-[1.12]"
                  />
                  Tools
                  {codeToolsEnabled && !codeDisabled ? (
                    <HugeiconsIcon
                      icon={MenuTickIcon}
                      strokeWidth={2}
                      className="ml-auto"
                    />
                  ) : null}
                </DropdownMenuItem>
                {showImagePill && (
                  <DropdownMenuItem
                    disabled={imageDisabled}
                    className={
                      imageToolsEnabled && !imageDisabled
                        ? "text-primary font-medium"
                        : undefined
                    }
                    onSelect={() => setImageToolsEnabled(!imageToolsEnabled)}
                  >
                    <HugeiconsIcon icon={ImageIcon} strokeWidth={2} />
                    Images
                    {imageToolsEnabled && !imageDisabled ? (
                      <HugeiconsIcon
                        icon={MenuTickIcon}
                        strokeWidth={2}
                        className="ml-auto"
                      />
                    ) : null}
                  </DropdownMenuItem>
                )}
                <DropdownMenuSeparator />
                {/* Browser use sits right under Chat with files, or leads this section without it. */}
                {pinnedPlusItems.map((id) => (
                  <Fragment key={id}>{plusMenuNodes[id]}</Fragment>
                ))}
                <DropdownMenuSub>
                  <DropdownMenuSubTrigger>
                    <HugeiconsIcon icon={MoreHorizontalIcon} className="size-4" />
                    More
                  </DropdownMenuSubTrigger>
                  <DropdownMenuSubContent className="unsloth-plus-menu w-[calc(248px*var(--ui-space-scale,1))]">
                    {overflowPlusItems.map((id) => (
                      <Fragment key={id}>{plusMenuNodes[id]}</Fragment>
                    ))}
                    {overflowPlusItems.length > 0 && <DropdownMenuSeparator />}
                    <DropdownMenuItem
                      onSelect={() => useSettingsDialogStore.getState().openDialog("chat", {
                        scrollTarget: "chat-composer",
                      })}
                    >
                      <HugeiconsIcon icon={SlidersHorizontalIcon} className="size-4" />
                      {t("composerSettings.settings")}
                    </DropdownMenuItem>
                  </DropdownMenuSubContent>
                </DropdownMenuSub>
              </DropdownMenuContent>
            </DropdownMenu>
            {/* Active in compare mode; sits first. Click to exit back to single chat. */}
            <button
              type="button"
              onClick={handleExitCompare}
              className="composer-pill-btn"
              data-active="true"
              data-keep-label="true"
              aria-label="Exit compare chat"
            >
              <PillGlyph>
                <HugeiconsIcon icon={LayoutTwoColumnIcon} strokeWidth={2} className="size-[calc(14px*var(--ui-space-scale,1))]" />
              </PillGlyph>
              <span>Compare</span>
            </button>
            {/* Permission-level pill sits immediately after Compare and ahead of every other tool pill so the
                Full access danger state reads first. */}
            <PermissionModeComposerPill side="top" />
            <button
              type="button"
              disabled={searchDisabled}
              onClick={() => {
                const next = !toolsEnabled;
                setToolsEnabled(next);
                // Kimi's $web_search builtin requires thinking=disabled, so toggle the Think pill off when Search is
                // on, mirroring the backend. Per https://platform.kimi.ai/docs/guide/use-web-search.
                if (isKimiExternal) {
                  setReasoningEnabled(!next, { persist: false });
                  applyQwenThinkingParams(!next);
                }
              }}
              className="composer-pill-btn"
              data-pill-label="Search"
              data-active={toolsEnabled && !searchDisabled ? "true" : "false"}
              aria-label={
                toolsEnabled ? "Disable web search" : "Enable web search"
              }
            >
              <PillGlyph>
                <InternetGlyph className="size-[calc(15px*var(--ui-space-scale,1))]" />
              </PillGlyph>
              <span>Search</span>
            </button>
            <button
              type="button"
              disabled={codeDisabled}
              onClick={() => setCodeToolsEnabled(!codeToolsEnabled)}
              className="composer-pill-btn"
              data-pill-label="Tools"
              data-active={codeToolsEnabled && !codeDisabled ? "true" : "false"}
              aria-label={
                codeToolsEnabled
                  ? "Disable tools"
                  : "Enable tools"
              }
            >
              <PillGlyph>
                <HugeiconsIcon
                  icon={CodeIcon}
                  className="size-[calc(18.5px*var(--ui-space-scale,1))]"
                  strokeWidth={2}
                />
              </PillGlyph>
              <span>Tools</span>
            </button>
            <BrowserAgentPill glyph={(icon) => <PillGlyph>{icon}</PillGlyph>} />
            {showImagePill && (
              <button
                type="button"
                disabled={imageDisabled}
                onClick={() => setImageToolsEnabled(!imageToolsEnabled)}
                className="composer-pill-btn"
                data-pill-label="Images"
                data-active={
                  imageToolsEnabled && !imageDisabled ? "true" : "false"
                }
                aria-label={
                  imageToolsEnabled
                    ? "Disable image generation"
                    : "Enable image generation"
                }
              >
                <PillGlyph>
                  <HugeiconsIcon
                    icon={ImageIcon}
                    className="size-3.5"
                    strokeWidth={2}
                  />
                </PillGlyph>
                <span>Images</span>
              </button>
            )}
            {showRagPill && <KnowledgeBaseComposerButton side="top" hasFilesPanel={false} />}
            {showWebFetchPill && (
              <button
                type="button"
                disabled={webFetchDisabled}
                onClick={() => setWebFetchToolsEnabled(!webFetchToolsEnabled)}
                className="composer-pill-btn"
                data-pill-label="Fetch"
                data-active={
                  webFetchToolsEnabled && !webFetchDisabled ? "true" : "false"
                }
                aria-label={
                  webFetchToolsEnabled ? "Disable URL fetch" : "Enable URL fetch"
                }
              >
                <PillGlyph>
                  <HugeiconsIcon icon={Download01Icon} className="size-3.5" />
                </PillGlyph>
                <span>Fetch</span>
              </button>
            )}
            {mcpEnabledForChat ? <McpComposerButton side="top" /> : null}
            <SkillsComposerButton side="top" />
          </div>
          <div
            ref={editorRef}
            className="unsloth-composer-editor"
            style={
              {
                "--composer-editor-height": `${text.length === 0 ? oneRowHeight : Math.max(oneRowHeight, editorHeight)}px`,
              } as CSSProperties
            }
          >
              <textarea
                {...skillMentions.inputProps}
                id={inputId}
                ref={composerSurfaceRef}
                data-type-to-activate="composer"
                value={text}
                onChange={(e) => {
                  // ALWAYS mirror the DOM value into React state, even during IME composition: the controlled `value`
                  // must match the DOM at all times, else an unrelated parent re-render reconciles the textarea back
                  // to the stored value mid-composition, wiping the preedit (#5318).
                  setCompositionState(isNativeComposing(e.nativeEvent));
                  setCurrentText(e.target.value);
                  skillMentions.update(
                    e.target.value,
                    e.target.selectionStart ?? e.target.value.length,
                  );
                }}

                onSelect={(event) => {
                  skillMentions.update(
                    event.currentTarget.value,
                    event.currentTarget.selectionStart ??
                      event.currentTarget.value.length,
                  );
                }}
                onScroll={(event) =>
                  markComposerScrollEdges(event.currentTarget)
                }
                onInputCapture={(event) =>
                  markComposerScrollEdges(event.currentTarget)
                }
                onCompositionStart={() => {
                  imeSessionOpenRef.current = true;
                  setCompositionState(true);
                }}
                onCompositionUpdate={() => {
                  refreshStuckImeTimer();
                }}
                onCompositionEnd={(e: CompositionEvent<HTMLTextAreaElement>) => {
                  imeSessionOpenRef.current = false;
                  compositionEndedAtRef.current = e.timeStamp;
                  setCompositionState(false);
                  setCurrentText(e.currentTarget.value);
                }}
                onKeyDown={(event) => {
                  if (!skillMentions.onKeyDown(event)) onKeyDown(event);
                }}
                onKeyDownCapture={(event) => {
                  plainPasteAtRef.current = isPlainPasteChord(event) ? performance.now() : 0;
                }}
                onKeyUpCapture={() => {
                  plainPasteAtRef.current = 0;
                }}
                onPaste={handleFilePaste}
                onBlur={() => {
                  plainPasteAtRef.current = 0;
                  // Mac: switching input methods can fire compositionstart without a matching compositionend,
                  // leaving composingRef pinned. The OS always commits or cancels before focus is lost.
                  imeSessionOpenRef.current = false;
                  setCompositionState(false);

                  skillMentions.close();
                }}
                placeholder="Send to both models..."
                // dir="auto" detects RTL from the first strong character; no effect on LTR scripts. Kept next to
                // the placeholder: the IME smoke reads this pair out of the source.
                dir="auto"
                // aui-composer-input carries no styling anywhere; it is the name both composers answer to, so one
                // selector can mean "the composer" whichever is on screen. Escape's decline exception and the
                // dictation foreground check rely on it.
                className="aui-composer-input unsloth-composer-input"
                rows={1}
              />
            {(showWritingToggle || isWritingExpanded) && (
              <TooltipIconButton
                type="button"
                tooltip={
                  isWritingExpanded ? "Collapse composer" : "Expand composer"
                }
                aria-expanded={isWritingExpanded}
                aria-controls={inputId}
                className="unsloth-composer-expand absolute -right-1 top-0 size-8 rounded-full bg-transparent text-muted-foreground hover:bg-transparent hover:text-muted-foreground dark:hover:bg-transparent aria-expanded:bg-transparent aria-expanded:text-muted-foreground"
                onMouseDown={(event) => event.preventDefault()}
                onClick={toggleWritingExpanded}
              >
                <svg
                  viewBox="0 0 20 20"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth={2.25}
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="size-4"
                  aria-hidden={true}
                >
                  <path
                    d={
                      isWritingExpanded
                        ? "M13 2v5h5M2 13h5v5"
                        : "M11 4h5v5M4 11v5h5"
                    }
                  />
                </svg>
              </TooltipIconButton>
            )}
          </div>
          <div className="aui-composer-action-wrapper flex shrink-0 items-center gap-1.5">
            {showReasoningControl ? (
              isEffort || supportsPreserveThinking ? (
                <NonModalDropdownMenu
                  side="top"
                  align="end"
                  className={cn(
                    "unsloth-plus-menu",
                    narrowEffortMenu ? "min-w-40" : "min-w-44",
                  )}
                  trigger={(triggerRef) => (
                    <button
                      ref={triggerRef}
                      type="button"
                      disabled={reasoningDisabled}
                      className="unsloth-thinking-pill"
                      data-pill-label="Thinking settings"
                      data-active={thinkingActiveLook ? "true" : "false"}
                      aria-label={thinkEffortAriaLabel({
                        modelLoaded,
                        reasoningDisabled,
                        reasoningEffort: displayedEffort,
                      })}
                    >
                      <BulbIcon className="size-[calc(15.5px*var(--ui-space-scale,1))]" />
                      {thinkingActiveLook ? (
                        <span className="unsloth-thinking-label">
                          {isEffort
                            ? `Thinking · ${formatReasoningEffortLabel(
                                displayedEffort,
                                externalSelection?.modelId,
                              )}`
                            : "Thinking"}
                        </span>
                      ) : null}
                      <HugeiconsIcon icon={ChevronDownStandardIcon} strokeWidth={1.5} className="unsloth-thinking-caret size-[calc(15px*var(--ui-space-scale,1))]" />
                    </button>
                  )}
                >
                  {isEffort ? (
                    <>
                      {effectiveSupportsReasoningOff && (
                        <DropdownMenuItem
                          onSelect={() => {
                            setReasoningEnabled(false);
                            applyQwenThinkingParams(false);
                            // Preserve thinking needs thinking on, so turn it off too.
                            setPreserveThinking(false);
                          }}
                        >
                          {formatReasoningDisabledLabel(
                            effectiveSupportsReasoningOff,
                            isExternalOpenAIReasoning,
                            checkpoint,
                          )}
                          <HugeiconsIcon
                    icon={Tick02Icon}
                    strokeWidth={2}
                            className={cn(
                              "unsloth-tick ms-auto size-4",
                              effectiveReasoningVisualEnabled && "opacity-0",
                            )}
                          />
                        </DropdownMenuItem>
                      )}
                      {effectiveReasoningEffortLevels
                        .filter((level) => level !== "none")
                        .map((level) => (
                          <DropdownMenuItem
                            key={level}
                            onSelect={() => {
                              setReasoningEffort(level);
                              setReasoningEnabled(true);
                              applyQwenThinkingParams(true);
                              // Mutual exclusion: turning thinking on for a Kimi model forces its
                              // web_search builtin off.
                              if (isKimiExternal && toolsEnabled) {
                                setToolsEnabled(false, { persist: false });
                              }
                            }}
                          >
                            {formatReasoningEffortLabel(
                              level,
                              externalSelection?.modelId,
                            )}
                            <HugeiconsIcon
                    icon={Tick02Icon}
                    strokeWidth={2}
                              className={cn(
                                "unsloth-tick ms-auto size-4",
                                !(
                                  effectiveReasoningVisualEnabled &&
                                  displayedEffort === level
                                ) && "opacity-0",
                              )}
                            />
                          </DropdownMenuItem>
                        ))}
                    </>
                  ) : (
                    effectiveSupportsReasoning &&
                    effectiveSupportsReasoningOff &&
                    !reasoningLockedOn && (
                      <DropdownMenuItem
                        onSelect={() => {
                          const next = !reasoningEnabled;
                          setReasoningEnabled(next);
                          applyQwenThinkingParams(next);
                          // Preserve thinking cannot run without thinking.
                          if (!next) setPreserveThinking(false);
                          if (isKimiExternal && next && toolsEnabled) {
                            setToolsEnabled(false, { persist: false });
                          }
                        }}
                      >
                        Thinking
                        <HugeiconsIcon
                    icon={Tick02Icon}
                    strokeWidth={2}
                          className={cn(
                            "unsloth-tick ms-auto size-4",
                            !effectiveReasoningEnabled && "opacity-0",
                          )}
                        />
                      </DropdownMenuItem>
                    )
                  )}
                  {supportsPreserveThinking && (
                    <DropdownMenuItem
                      disabled={!modelLoaded}
                      onSelect={(e) => {
                        e.preventDefault();
                        const next = !preserveThinking;
                        setPreserveThinking(next);
                        // Only local models couple this setting to generation controls.
                        if (next && !isExternalModel) {
                          setReasoningEnabled(true);
                          applyQwenThinkingParams(true);
                        }
                      }}
                    >
                      Preserve thinking
                      <HugeiconsIcon
                    icon={Tick02Icon}
                    strokeWidth={2}
                        className={cn(
                          "unsloth-tick ms-auto size-4",
                          !preserveThinking && "opacity-0",
                        )}
                      />
                    </DropdownMenuItem>
                  )}
                </NonModalDropdownMenu>
              ) : (
                <button
                  type="button"
                  disabled={reasoningDisabled || reasoningLockedOn}
                  aria-disabled={reasoningDisabled || reasoningLockedOn}
                  title={
                    reasoningLockedOn
                      ? "This model requires reasoning to stay on."
                      : undefined
                  }
                  onClick={() => {
                    if (reasoningLockedOn) return;
                    const next = !reasoningEnabled;
                    setReasoningEnabled(next);
                    applyQwenThinkingParams(next);
                    // Mutual exclusion: Kimi's $web_search builtin requires thinking off, so turning thinking on
                    // flips Search off.
                    if (isKimiExternal && next && toolsEnabled) {
                      setToolsEnabled(false, { persist: false });
                    }
                  }}
                  className="unsloth-thinking-pill"
                  data-pill-label="Thinking"
                  data-active={thinkingActiveLook ? "true" : "false"}
                  aria-label={thinkToggleAriaLabel({
                    reasoningLockedOn,
                    modelLoaded,
                    reasoningDisabled,
                    effectiveReasoningEnabled,
                  })}
                >
                  <PillGlyph>
                    <BulbIcon className="size-[calc(15.5px*var(--ui-space-scale,1))]" />
                  </PillGlyph>
                  {thinkingActiveLook ? (
                    <span className="unsloth-thinking-label">Thinking</span>
                  ) : null}
                </button>
              )
            ) : null}
            {
              <>
                {!isDictating ? (
                  audioUpload.busy ? (
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="h-9 gap-1.5 rounded-full px-2.5 text-muted-foreground"
                      aria-label={t("settings.voice.dictation.audioUploadCancel")}
                      title={t("settings.voice.dictation.audioUploadCancel")}
                      onClick={audioUpload.cancel}
                    >
                      <Spinner className="size-4" />
                      <span>{t("settings.voice.dictation.audioUploadTranscribing")}</span>
                      <HugeiconsIcon icon={Cancel01Icon} className="size-3.5" aria-hidden="true" />
                    </Button>
                  ) : (
                    <TooltipIconButton
                      tooltip="Dictate"
                      type="button"
                      variant="ghost"
                      className="size-9 rounded-full text-foreground"
                      disabled={!chatActive}
                      onClick={startDictation}
                      aria-label="Dictate"
                    >
                      <MicIcon className="unsloth-dictate-icon size-6" />
                    </TooltipIconButton>
                  )
                ) : (
                  <TooltipIconButton
                    tooltip={
                      isDictationFinalizing
                        ? "Cancel transcription"
                        : "Stop dictation"
                    }
                    type="button"
                    variant="ghost"
                    className="size-9 rounded-full text-destructive"
                    onClick={stopDictation}
                    aria-label={
                      isDictationFinalizing
                        ? "Cancel transcription"
                        : "Stop dictation"
                    }
                  >
                    <HugeiconsIcon icon={StopIcon} className="composer-glyph-snap size-3.5 animate-pulse fill-current" />
                  </TooltipIconButton>
                )}
              </>
            }
            {isQueueRunning ? (
              // Wrapped: the narrow layout squares every direct button of this group, and this one has a label.
              <div className="ml-1.5 flex">
                <button
                  type="button"
                  onClick={() => {
                    resetPromptQueue();
                    stop();
                  }}
                  aria-label="Stop prompt queue"
                  className="btn-fill flex items-center gap-1.5 rounded-full border border-transparent px-2.5 py-1 text-xs font-semibold text-muted-foreground transition-colors hover:text-foreground "
                >
                  <HugeiconsIcon icon={StopIcon} className="size-2.5 shrink-0 fill-current" />
                  <span className="tabular-nums">
                    Stop queue {queueProgress.current}/{queueProgress.total}
                  </span>
                </button>
              </div>
            ) : busy ? (
              <Button
                type="button"
                variant="primary"
                size="icon"
                className="aui-composer-cancel ml-1.5 size-9 rounded-full"
                aria-label="Stop generating"
                onClick={stop}
              >
                <HugeiconsIcon icon={StopIcon} className="composer-glyph-snap size-3.5 fill-current" />
              </Button>
            ) : (
              <TooltipIconButton
                tooltip={
                  sendUnavailableReason ??
                  t("promptQueue.sendTooltip", { shortcut: shortcutLabels.send })
                }
                side="bottom"
                variant="primary"
                size="icon"
                className="aui-composer-send ml-1.5 size-9 rounded-full"
                onClick={send}
                disabled={!canSend}
                aria-label={t("promptQueue.sendLabel")}
              >
                <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[calc(21px*var(--ui-space-scale,1))] stroke-2" />
              </TooltipIconButton>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}