Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: embedding model picker, pins and eject in the RAG menu (#12875)

Michael Han8f20a9f3dbe4
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index ac7c62bb0e7..5763712b54d 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1992,6 +1992,8 @@ class DiffusionAcceleratorFallbackResponse(BaseModel):
PINNED_MODELS_SETTING_KEY = "model_picker_pinned"
PINNED_CONNECTED_MODELS_SETTING_KEY = "model_picker_pinned_connected"
+# Embedding models pinned to the RAG menu.
+PINNED_EMBEDDING_MODELS_SETTING_KEY = "rag_embedding_pinned"
MAX_PINNED_MODELS = 512
# Room for a "::quant" suffix or an "external::<connection>::" prefix on top of a model id.
_MAX_PIN_KEY_LEN = MAX_MODEL_OVERRIDE_KEY_LEN + 512
@@ -2005,18 +2007,26 @@ class PinnedModelsPayload(BaseModel):
pinned: Optional[list[_PinKey]] = Field(default = None, max_length = MAX_PINNED_MODELS)
connected: Optional[list[_PinKey]] = Field(default = None, max_length = MAX_PINNED_MODELS)
+ embedding: Optional[list[_PinKey]] = Field(default = None, max_length = MAX_PINNED_MODELS)
class PinnedModelsResponse(BaseModel):
# None = never stored, so the browser seeds it.
pinned: Optional[list[str]] = None
connected: Optional[list[str]] = None
+ embedding: Optional[list[str]] = None
def _pinned_models_response() -> PinnedModelsResponse:
from storage.studio_db import get_app_settings
- stored = get_app_settings([PINNED_MODELS_SETTING_KEY, PINNED_CONNECTED_MODELS_SETTING_KEY])
+ stored = get_app_settings(
+ [
+ PINNED_MODELS_SETTING_KEY,
+ PINNED_CONNECTED_MODELS_SETTING_KEY,
+ PINNED_EMBEDDING_MODELS_SETTING_KEY,
+ ]
+ )
def _ids(value: Any) -> Optional[list[str]]:
return [v for v in value if isinstance(v, str)] if isinstance(value, list) else None
@@ -2024,6 +2034,7 @@ def _pinned_models_response() -> PinnedModelsResponse:
return PinnedModelsResponse(
pinned = _ids(stored.get(PINNED_MODELS_SETTING_KEY)),
connected = _ids(stored.get(PINNED_CONNECTED_MODELS_SETTING_KEY)),
+ embedding = _ids(stored.get(PINNED_EMBEDDING_MODELS_SETTING_KEY)),
)
@@ -2044,6 +2055,8 @@ def update_pinned_models(
updates[PINNED_MODELS_SETTING_KEY] = list(dict.fromkeys(payload.pinned))
if payload.connected is not None:
updates[PINNED_CONNECTED_MODELS_SETTING_KEY] = list(dict.fromkeys(payload.connected))
+ if payload.embedding is not None:
+ updates[PINNED_EMBEDDING_MODELS_SETTING_KEY] = list(dict.fromkeys(payload.embedding))
if updates:
upsert_app_settings(updates, read_back = False)
return _pinned_models_response()
diff --git a/studio/backend/tests/test_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.py
index b385f3bedd9..e1a0de88fa2 100644
--- a/studio/backend/tests/test_account_chat_settings.py
+++ b/studio/backend/tests/test_account_chat_settings.py
@@ -494,18 +494,34 @@ def test_managed_load_uses_its_own_override_then_the_owners(fresh_override_cache
def test_pinned_models_are_per_account(client):
empty = client.get("/settings/pinned-models")
- assert empty.status_code == 200 and empty.json() == {"pinned": None, "connected": None}
+ assert empty.status_code == 200 and empty.json() == {
+ "pinned": None,
+ "connected": None,
+ "embedding": None,
+ }
saved = client.put(
"/settings/pinned-models", json = {"pinned": ["org/a::Q4_K_M", "org/b", "org/b"]}
)
assert saved.status_code == 200, saved.text
- assert saved.json() == {"pinned": ["org/a::Q4_K_M", "org/b"], "connected": None}
+ assert saved.json() == {
+ "pinned": ["org/a::Q4_K_M", "org/b"],
+ "connected": None,
+ "embedding": None,
+ }
both = client.put("/settings/pinned-models", json = {"connected": ["external::c1::gpt"]}).json()
- assert both == {"pinned": ["org/a::Q4_K_M", "org/b"], "connected": ["external::c1::gpt"]}
+ assert both == {
+ "pinned": ["org/a::Q4_K_M", "org/b"],
+ "connected": ["external::c1::gpt"],
+ "embedding": None,
+ }
+ embed = client.put(
+ "/settings/pinned-models", json = {"embedding": ["unsloth/bge-m3", "unsloth/bge-m3"]}
+ ).json()
+ assert embed["embedding"] == ["unsloth/bge-m3"] and embed["connected"] == ["external::c1::gpt"]
cleared = client.put("/settings/pinned-models", json = {"pinned": []}).json()
assert cleared["pinned"] == [] and cleared["connected"] == ["external::c1::gpt"]
bob = client.get("/settings/pinned-models", headers = {"x-test-account": "bob"}).json()
- assert bob == {"pinned": None, "connected": None}
+ assert bob == {"pinned": None, "connected": None, "embedding": None}
assert (
run_as(OWNER, studio_db.get_app_setting, settings.PINNED_MODELS_SETTING_KEY, None) is None
)
@@ -518,6 +534,7 @@ def test_pinned_models_are_per_account(client):
{"pinned": [""]},
{"pinned": ["x"] * (settings.MAX_PINNED_MODELS + 1)},
{"connected": [1]},
+ {"embedding": [""]},
],
)
def test_pinned_models_rejects_bad_payloads(client, body):
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 9bdae8be8d8..91a28eeb341 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -36,7 +36,7 @@ import { InterfaceZoom, zoomInterfaceFromMenu } from "@/features/interface-zoom"
import { bootstrapPersistedCredentials } from "@/features/credentials/bootstrap";
import { SharedRunConfigLinkHandler } from "@/features/model-picker";
import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";
-import { hydratePins } from "@/features/model-picker/components/model-selector/pins-mirror";
+import { hydratePins } from "@/lib/pins-mirror";
import { usePersonalizationSync } from "@/features/profile";
import { RemoteCodeConsentDialog } from "@/features/security";
import {
diff --git a/studio/frontend/src/features/chat/permission-mode-select.tsx b/studio/frontend/src/features/chat/permission-mode-select.tsx
index e7afe9fa2ea..ca8a3716235 100644
--- a/studio/frontend/src/features/chat/permission-mode-select.tsx
+++ b/studio/frontend/src/features/chat/permission-mode-select.tsx
@@ -221,7 +221,7 @@ function SandboxLevelMenuPicker({ onOsSandboxMissing }: { onOsSandboxMissing?: (
setOpen(false);
}}
// Negative margins cancel the hover pill's padding so nothing shifts.
- className="sandbox-level-chip -my-1 -mr-1.5 flex shrink-0 cursor-pointer items-center gap-1 rounded-full border-0 py-1 pr-1.5 pl-2.5 text-ui-12 font-medium outline-none transition-colors"
+ className="menu-heading-chip -my-1 -mr-1.5 flex shrink-0 cursor-pointer items-center gap-1 rounded-full border-0 py-1 pr-1.5 pl-2.5 text-ui-12 font-medium outline-none transition-colors"
>
<span className="text-foreground">{t("settings.sandbox.levelLabel")}</span>
<span className={active === "off" ? "text-muted-foreground" : "text-primary"}>
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts b/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts
index 00175d4c0a4..691b55978bd 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts
@@ -7,7 +7,7 @@
import { create } from "zustand";
-import { mirrorPins, onPinsRestored } from "./pins-mirror.ts";
+import { mirrorPins, onPinsRestored } from "../../../../lib/pins-mirror.ts";
const KEY = "unsloth_pinned_connected_models";
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pinned-models.ts b/studio/frontend/src/features/model-picker/components/model-selector/pinned-models.ts
index ae8a8c82c5e..46c6dd3f0dc 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pinned-models.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pinned-models.ts
@@ -7,7 +7,7 @@
import { create } from "zustand";
-import { mirrorPins, onPinsRestored } from "./pins-mirror.ts";
+import { mirrorPins, onPinsRestored } from "../../../../lib/pins-mirror.ts";
const KEY = "unsloth_pinned_models";
diff --git a/studio/frontend/src/features/rag/components/embedding-model-menu-picker.tsx b/studio/frontend/src/features/rag/components/embedding-model-menu-picker.tsx
new file mode 100644
index 00000000000..dc6888e11bc
--- /dev/null
+++ b/studio/frontend/src/features/rag/components/embedding-model-menu-picker.tsx
@@ -0,0 +1,342 @@
+// 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 { PinIcon, PinOffIcon, RemoveCircleIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
+import { useEffect, useRef, useState } from "react";
+
+import {
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "@/components/ui/dropdown-menu";
+import { Spinner } from "@/components/ui/spinner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useChatRuntimeStore } from "@/features/chat";
+import {
+ ejectEmbeddingModel,
+ embeddingModelName,
+ embeddingModelOwner,
+ switchEmbeddingModel,
+ useEmbeddingModelStore,
+ useEmbeddingPinsStore,
+ useSettingsDialogStore,
+} from "@/features/settings";
+import { useWheelScrollRef } from "@/hooks";
+import { useT } from "@/i18n";
+import { ChevronLeftStandardIcon, ChevronRightStandardIcon } from "@/lib/chevron-icons";
+import { MenuTickIcon } from "@/lib/tick-icon";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import { embeddingMenuModels } from "../lib/embedding-menu-models";
+
+const HEADING_LINK_CLASS =
+ "my-0! shrink-0 cursor-pointer rounded-sm font-normal text-muted-foreground underline decoration-muted-foreground/50 underline-offset-[3px] outline-hidden transition-colors hover:text-foreground hover:decoration-foreground/60 data-[highlighted]:text-foreground data-[highlighted]:decoration-foreground/60";
+
+// Fixed width, so the pin sits in the same place on every row, ticked or not.
+const TRAILING_SLOT_CLASS =
+ "flex w-[calc(var(--ui-icon-size)+2px)] shrink-0 items-center justify-center";
+
+/** The model item of the row after (else before) the one holding `el`. */
+function neighbourRowItem(el: HTMLElement): HTMLElement | null {
+ const row = el.closest(".menu-row-with-action");
+ for (const step of ["nextElementSibling", "previousElementSibling"] as const) {
+ for (let next = row?.[step]; next; next = next[step]) {
+ if (next.classList.contains("menu-row-with-action"))
+ return next.querySelector<HTMLElement>('[role^="menuitem"]');
+ }
+ }
+ return null;
+}
+
+/** "Model <name> ›" chip in the RAG menu heading. Swaps the menu to the model list. */
+export function EmbeddingModelMenuChip({ onOpen }: { onOpen: () => void }) {
+ const t = useT();
+ const settings = useEmbeddingModelStore((s) => s.settings);
+
+ useEffect(() => {
+ void useEmbeddingModelStore.getState().load();
+ }, []);
+
+ if (!settings) return null;
+ const current = settings.embeddingModel;
+ return (
+ <DropdownMenuPrimitive.Item
+ onSelect={(event) => {
+ // Keep the menu open; it shows the list instead.
+ event.preventDefault();
+ onOpen();
+ }}
+ // Pill edge stays put; slim right padding sets the text close to it.
+ className="menu-heading-chip -my-1 -mr-2 flex min-w-0 shrink cursor-pointer items-center gap-1 rounded-full border-0 py-1 pr-1 pl-2.5 text-ui-12 font-medium outline-none transition-colors"
+ >
+ <span className="shrink-0 text-foreground">{t("settings.general.rag.menuChip")}</span>
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <span className="min-w-0 truncate text-primary">{embeddingModelName(current)}</span>
+ </TooltipTrigger>
+ <TooltipContent side="top">{current}</TooltipContent>
+ </Tooltip>
+ <HugeiconsIcon
+ icon={ChevronRightStandardIcon}
+ strokeWidth={1.75}
+ className="-ml-0.5 size-[calc(13px*var(--ui-space-scale,1))] shrink-0 text-foreground"
+ />
+ </DropdownMenuPrimitive.Item>
+ );
+}
+
+/** Model list shown in place of the RAG menu: current, default and pinned models. */
+export function EmbeddingModelMenuList({ onBack }: { onBack: () => void }) {
+ const t = useT();
+ const hfToken = useChatRuntimeStore((s) => s.hfToken);
+ const settings = useEmbeddingModelStore((s) => s.settings);
+ const pinned = useEmbeddingPinsStore((s) => s.pinned);
+ const togglePin = useEmbeddingPinsStore((s) => s.togglePin);
+ const openSettings = useSettingsDialogStore((s) => s.openDialog);
+ const [switching, setSwitching] = useState<string | null>(null);
+ const [ejecting, setEjecting] = useState(false);
+ // A slow switch can land after the menu closed and reopened; only the live list may navigate.
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+ const listRef = useWheelScrollRef<HTMLDivElement>();
+
+ // Fresh residency, so Eject reflects a model indexing just loaded.
+ useEffect(() => {
+ void useEmbeddingModelStore.getState().load();
+ }, []);
+
+ if (!settings) return null;
+ const current = settings.embeddingModel;
+ const models = embeddingMenuModels(current, settings.defaultEmbeddingModel, pinned);
+
+ const pick = async (model: string) => {
+ if (model === current) {
+ onBack();
+ return;
+ }
+ if (switching) return;
+ setSwitching(model);
+ const name = embeddingModelName(model);
+ try {
+ const result = await switchEmbeddingModel(model, hfToken || undefined);
+ if (result.status === "failed") {
+ toast.error(t("settings.general.rag.switchFailed"), {
+ description: result.message || undefined,
+ });
+ return;
+ }
+ if (result.status === "saved" && result.needsDownload) {
+ toast.info(t("settings.general.rag.switchedNeedsDownload", { model: name }), {
+ description: t("settings.general.rag.switchedNeedsDownloadDescription"),
+ action: {
+ label: t("settings.general.rag.openSettings"),
+ onClick: () => openSettings("general", { scrollTarget: "general-rag-embedding" }),
+ },
+ });
+ } else if (result.status === "saved" && result.needsDownload === null) {
+ // Saved, but the resolve failed, so whether the files are on disk is unknown.
+ toast.info(t("settings.general.rag.switched", { model: name }), {
+ description: t("settings.general.rag.switchedUncheckedDescription"),
+ action: {
+ label: t("settings.general.rag.openSettings"),
+ onClick: () => openSettings("general", { scrollTarget: "general-rag-embedding" }),
+ },
+ });
+ } else if (result.status === "saved") {
+ toast.success(t("settings.general.rag.switched", { model: name }), {
+ description: t("settings.general.rag.reindexWarning"),
+ });
+ }
+ if (mountedRef.current) onBack();
+ } finally {
+ if (mountedRef.current) setSwitching(null);
+ }
+ };
+
+ const eject = async (menu: Element | null) => {
+ if (ejecting) return;
+ setEjecting(true);
+ try {
+ await ejectEmbeddingModel();
+ toast.success(t("settings.general.rag.ejected"));
+ // The Eject row goes with the model and took focus with it; land on the first model row.
+ requestAnimationFrame(() =>
+ menu?.querySelector<HTMLElement>('.menu-row-with-action [role^="menuitem"]')?.focus(),
+ );
+ } catch (error) {
+ toast.error(t("settings.general.rag.unloadFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ } finally {
+ setEjecting(false);
+ }
+ };
+
+ return (
+ // Capped to the menu's room, so the rows scroll inside it instead of the whole menu.
+ <div className="flex max-h-[calc(var(--radix-dropdown-menu-content-available-height)-1rem*var(--ui-space-scale,1))] flex-col">
+ {/* Header and Eject stay put; only the model rows scroll. */}
+ {/* A page header, not a label: the back button returns to the source list, and the title
+ names this page, so the arrow never reads as "go back to <title>". */}
+ <div className="flex shrink-0 items-start gap-2 px-2 pt-2 pb-2">
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <DropdownMenuPrimitive.Item
+ aria-label={t("settings.general.rag.back")}
+ onSelect={(event) => {
+ event.preventDefault();
+ onBack();
+ }}
+ className="-ml-1 flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground outline-hidden transition-colors hover:bg-[rgb(0_0_0_/_calc(0.1*var(--contrast-wash-gain,1)))] hover:text-foreground data-[highlighted]:bg-[rgb(0_0_0_/_calc(0.1*var(--contrast-wash-gain,1)))] data-[highlighted]:text-foreground dark:hover:bg-[rgb(255_255_255_/_calc(0.14*var(--contrast-wash-gain,1)))] dark:data-[highlighted]:bg-[rgb(255_255_255_/_calc(0.14*var(--contrast-wash-gain,1)))]"
+ >
+ <HugeiconsIcon
+ icon={ChevronLeftStandardIcon}
+ strokeWidth={2}
+ className="size-[calc(14px*var(--ui-space-scale,1))]"
+ />
+ </DropdownMenuPrimitive.Item>
+ </TooltipTrigger>
+ <TooltipContent side="top">{t("settings.general.rag.back")}</TooltipContent>
+ </Tooltip>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-ui-12 font-medium leading-tight text-foreground">
+ {t("settings.general.rag.embeddingModel")}
+ </span>
+ <span className="truncate text-xs leading-snug text-muted-foreground">
+ {t("settings.general.rag.menuSubtitle")}
+ </span>
+ </div>
+ <DropdownMenuPrimitive.Item
+ className={cn(HEADING_LINK_CLASS, "mt-px text-ui-12")}
+ // Deferred past the menu's focus restore.
+ onSelect={() =>
+ setTimeout(() => openSettings("general", { scrollTarget: "general-rag-embedding" }), 0)
+ }
+ >
+ {t("settings.general.rag.moreModels")}
+ </DropdownMenuPrimitive.Item>
+ </div>
+ <div
+ ref={listRef}
+ className="min-h-0 flex-1 overflow-y-auto max-h-[calc(236px*var(--ui-space-scale,1))]"
+ >
+ {models.map((model) => {
+ const isPinned = pinned.includes(model);
+ const owner = embeddingModelOwner(model);
+ const details = [
+ owner || t("settings.general.rag.localModel"),
+ ...(model === settings.defaultEmbeddingModel ? [t("settings.general.rag.defaultTag")] : []),
+ ...(model === current
+ ? [t(settings.loaded ? "settings.general.rag.loaded" : "settings.general.rag.notLoaded")]
+ : []),
+ ].join(" · ");
+ const pinLabel = t(isPinned ? "settings.general.rag.unpin" : "settings.general.rag.pin");
+ return (
+ // The pin is its own menu item, so arrow keys reach it; it is laid over the row's spacer.
+ <div key={model} className="menu-row-with-action group/row relative">
+ <DropdownMenuItem
+ disabled={switching !== null && switching !== model}
+ onSelect={(event) => {
+ // Stay open while it switches; the list goes back once it lands.
+ event.preventDefault();
+ void pick(model);
+ }}
+ className={cn("items-start gap-2 py-2", model === current && "font-medium")}
+ >
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-ui-13 leading-tight">{embeddingModelName(model)}</span>
+ <span className="truncate text-xs font-normal leading-snug text-muted-foreground">
+ {details}
+ </span>
+ </span>
+ <span className="flex shrink-0 items-center gap-2 self-center">
+ <span className="size-6" />
+ <span className={TRAILING_SLOT_CLASS}>
+ {switching === model ? (
+ <Spinner className="size-4" />
+ ) : model === current ? (
+ <HugeiconsIcon
+ icon={MenuTickIcon}
+ strokeWidth={2}
+ className="permission-mode-tick"
+ />
+ ) : null}
+ </span>
+ </span>
+ </DropdownMenuItem>
+ <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center gap-2">
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <DropdownMenuPrimitive.CheckboxItem
+ checked={isPinned}
+ aria-label={pinLabel}
+ data-row-action={true}
+ onSelect={(event) => {
+ event.preventDefault();
+ // Unpinning an extra row removes the focused item; hand focus to a neighbour.
+ const leaving =
+ isPinned && model !== current && model !== settings.defaultEmbeddingModel;
+ const neighbour = leaving
+ ? neighbourRowItem(event.currentTarget as HTMLElement)
+ : null;
+ togglePin(model);
+ if (neighbour) requestAnimationFrame(() => neighbour.focus());
+ }}
+ // As on Recents: grey, unpin glyph once pinned. Shown on row hover or focus, always on touch.
+ className="pointer-events-auto flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground opacity-0 outline-hidden transition-colors group-hover/row:opacity-100 group-has-[[data-highlighted]]/row:opacity-100 [@media(hover:none)]:opacity-100 hover:bg-[rgb(0_0_0_/_calc(0.06*var(--contrast-wash-gain,1)))] data-[highlighted]:bg-[rgb(0_0_0_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] dark:data-[highlighted]:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]"
+ >
+ <HugeiconsIcon
+ icon={isPinned ? PinOffIcon : PinIcon}
+ strokeWidth={1.75}
+ className="size-3.5!"
+ />
+ </DropdownMenuPrimitive.CheckboxItem>
+ </TooltipTrigger>
+ <TooltipContent side="top">{pinLabel}</TooltipContent>
+ </Tooltip>
+ <span className={TRAILING_SLOT_CLASS} />
+ </span>
+ </div>
+ );
+ })}
+ {pinned.length === 0 ? (
+ <DropdownMenuPrimitive.Item
+ className={cn(HEADING_LINK_CLASS, "mx-3 mt-1 mb-2 inline-flex w-fit text-xs")}
+ // Deferred past the menu's focus restore, as More models is.
+ onSelect={() =>
+ setTimeout(() => openSettings("general", { scrollTarget: "general-rag-embedding" }), 0)
+ }
+ >
+ {t("settings.general.rag.pinMoreModels")}
+ </DropdownMenuPrimitive.Item>
+ ) : null}
+ </div>
+ {settings.backendLoaded ? (
+ <div className="shrink-0">
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={switching !== null}
+ onSelect={(event) => {
+ // Stay open; the row goes away once the model is out.
+ event.preventDefault();
+ void eject((event.currentTarget as HTMLElement).closest('[role="menu"]'));
+ }}
+ >
+ {ejecting ? (
+ <Spinner className="size-4 shrink-0" />
+ ) : (
+ <HugeiconsIcon icon={RemoveCircleIcon} strokeWidth={1.75} />
+ )}
+ {t("settings.general.rag.ejectModel")}
+ </DropdownMenuItem>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx b/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx
index bc0e89cef27..82c503f64bd 100644
--- a/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx
+++ b/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx
@@ -8,7 +8,7 @@ import {
import { Tick02Icon } from "@/lib/tick-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import { FileDatabaseIcon } from "@hugeicons/core-free-icons";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import {
DropdownMenu,
@@ -18,6 +18,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { useIsAccountOwner } from "@/features/auth";
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
@@ -26,6 +27,7 @@ import {
subscribeKnowledgeBasesChanged,
} from "../api/rag-api";
import type { KnowledgeBase } from "../types/rag";
+import { EmbeddingModelMenuChip, EmbeddingModelMenuList } from "./embedding-model-menu-picker";
import { KnowledgeBaseDialog } from "./knowledge-base-dialog";
// Matches the Thinking/MCP pill chevron. Picks the retrieval source. Shown whenever retrieval is
@@ -40,10 +42,25 @@ export function KnowledgeBaseComposerButton({
const ragDisabled = useRagToolDisabled();
const ragSource = useChatRuntimeStore((s) => s.ragSource);
const setRagSource = useChatRuntimeStore((s) => s.setRagSource);
+ // The embedding model is a server setting only the owner can change.
+ const isOwner = useIsAccountOwner();
const [kbs, setKbs] = useState<KnowledgeBase[]>([]);
const [kbsLoaded, setKbsLoaded] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
+ // The embedding list replaces the source list in the same menu.
+ const [view, setView] = useState<"source" | "embedding">("source");
+ const contentRef = useRef<HTMLDivElement>(null);
+ const shownViewRef = useRef(view);
+ // A swap unmounts the focused item while the menu stays open, which strands focus outside it and
+ // kills arrow keys. Focus the new view's first item, as Radix does on open.
+ useLayoutEffect(() => {
+ if (shownViewRef.current === view) return;
+ shownViewRef.current = view;
+ contentRef.current
+ ?.querySelector<HTMLElement>('[role^="menuitem"]:not([data-disabled])')
+ ?.focus();
+ }, [view]);
const [dialogOpen, setDialogOpen] = useState(false);
// Refreshes overlap; an older answer landing last would restore a deleted KB.
@@ -88,6 +105,7 @@ export function KnowledgeBaseComposerButton({
onOpenChange={(open) => {
setMenuOpen(open);
if (open) void refresh();
+ else setView("source");
}}
>
<DropdownMenuTrigger asChild={true}>
@@ -129,62 +147,76 @@ export function KnowledgeBaseComposerButton({
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
+ ref={contentRef}
side={side}
align="start"
sideOffset={2}
avoidCollisions={true}
- className="unsloth-plus-menu mcp-menu w-[calc(232px*var(--ui-space-scale,1))]"
+ className={
+ isOwner
+ ? "unsloth-plus-menu mcp-menu w-[calc(320px*var(--ui-space-scale,1))]"
+ : "unsloth-plus-menu mcp-menu w-[calc(232px*var(--ui-space-scale,1))]"
+ }
>
- <DropdownMenuLabel>Retrieve from</DropdownMenuLabel>
- <DropdownMenuItem
- onSelect={() => setRagSource({ type: "thread" })}
- className={
- ragSource.type === "thread"
- ? "relative text-primary font-medium"
- : "relative"
- }
- >
- <span className="truncate">This thread's documents</span>
- {ragSource.type === "thread" ? (
- <HugeiconsIcon
- icon={Tick02Icon}
- strokeWidth={2}
- className="ml-auto"
- />
- ) : null}
- </DropdownMenuItem>
- {kbs.length > 0 ? <DropdownMenuSeparator /> : null}
- {kbs.map((kb) => {
- const selected =
- ragSource.type === "kb" && ragSource.kbId === kb.id;
- return (
- <DropdownMenuItem
- key={kb.id}
- onSelect={() => setRagSource({ type: "kb", kbId: kb.id })}
- className={
- selected ? "relative text-primary font-medium" : "relative"
- }
- >
- <span className="truncate">{kb.name}</span>
- {selected ? (
- <HugeiconsIcon
- icon={Tick02Icon}
- strokeWidth={2}
- className="ml-auto"
- />
- ) : null}
- </DropdownMenuItem>
- );
- })}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={() => {
- setMenuOpen(false);
- setDialogOpen(true);
- }}
- >
- Manage knowledge bases…
- </DropdownMenuItem>
+ {isOwner && view === "embedding" ? (
+ <EmbeddingModelMenuList onBack={() => setView("source")} />
+ ) : (
+ <>
+ <DropdownMenuLabel className="flex items-center justify-between gap-3">
+ <span className="shrink-0">Retrieve from</span>
+ {isOwner ? <EmbeddingModelMenuChip onOpen={() => setView("embedding")} /> : null}
+ </DropdownMenuLabel>
+ <DropdownMenuItem
+ onSelect={() => setRagSource({ type: "thread" })}
+ className={
+ ragSource.type === "thread"
+ ? "relative text-primary font-medium"
+ : "relative"
+ }
+ >
+ <span className="truncate">This thread's documents</span>
+ {ragSource.type === "thread" ? (
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ strokeWidth={2}
+ className="ml-auto"
+ />
+ ) : null}
+ </DropdownMenuItem>
+ {kbs.length > 0 ? <DropdownMenuSeparator /> : null}
+ {kbs.map((kb) => {
+ const selected =
+ ragSource.type === "kb" && ragSource.kbId === kb.id;
+ return (
+ <DropdownMenuItem
+ key={kb.id}
+ onSelect={() => setRagSource({ type: "kb", kbId: kb.id })}
+ className={
+ selected ? "relative text-primary font-medium" : "relative"
+ }
+ >
+ <span className="truncate">{kb.name}</span>
+ {selected ? (
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ strokeWidth={2}
+ className="ml-auto"
+ />
+ ) : null}
+ </DropdownMenuItem>
+ );
+ })}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ setMenuOpen(false);
+ setDialogOpen(true);
+ }}
+ >
+ Manage knowledge bases…
+ </DropdownMenuItem>
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
<KnowledgeBaseDialog
diff --git a/studio/frontend/src/features/rag/lib/embedding-menu-models.ts b/studio/frontend/src/features/rag/lib/embedding-menu-models.ts
new file mode 100644
index 00000000000..56c3680a3d2
--- /dev/null
+++ b/studio/frontend/src/features/rag/lib/embedding-menu-models.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Current, default, then pinned models, each once. */
+export function embeddingMenuModels(
+ current: string,
+ defaultModel: string,
+ pinned: readonly string[],
+): string[] {
+ const models: string[] = [];
+ for (const model of [current, defaultModel, ...pinned]) {
+ const id = model.trim();
+ if (id && !models.includes(id)) models.push(id);
+ }
+ return models;
+}
diff --git a/studio/frontend/src/features/settings/components/documents-rag-section.tsx b/studio/frontend/src/features/settings/components/documents-rag-section.tsx
index 6e4fab12dd2..f58eef78aaf 100644
--- a/studio/frontend/src/features/settings/components/documents-rag-section.tsx
+++ b/studio/frontend/src/features/settings/components/documents-rag-section.tsx
@@ -5,7 +5,10 @@ import { Button } from "@/components/ui/button";
import { useChatRuntimeStore } from "@/features/chat";
import { formatBytes, listCachedGguf, listCachedModels } from "@/features/hub";
import { Spinner } from "@/components/ui/spinner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
+import { InformationCircleIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
import {
DOWNLOAD_KIND,
downloadManager,
@@ -15,7 +18,7 @@ import {
} from "@/features/hub/download-manager";
import { useT } from "@/i18n";
import { toast } from "@/lib/toast";
-import { type ReactElement, useCallback, useEffect, useState } from "react";
+import { type ReactElement, useCallback, useEffect, useRef, useState } from "react";
import {
EmbeddingModelBlockedError,
type EmbeddingModelResolution,
@@ -25,6 +28,8 @@ import {
updateEmbeddingModelSettings,
} from "../api/embedding-model";
import { useEmbeddingModelStore } from "../stores/embedding-model-store";
+import { useEmbeddingPinsStore } from "../stores/embedding-pins-store";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import { EmbeddingModelPicker } from "./embedding-model-picker";
import { SettingsRow } from "./settings-row";
import { SettingsSection } from "./settings-section";
@@ -65,6 +70,21 @@ export function DocumentsRagSection(): ReactElement {
const [cachedRepos, setCachedRepos] = useState<ReadonlySet<string>>(
() => new Set(),
);
+ const pinnedModels = useEmbeddingPinsStore((s) => s.pinned);
+ const togglePin = useEmbeddingPinsStore((s) => s.togglePin);
+ const sectionRef = useRef<HTMLElement | null>(null);
+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+ const consumeScrollTarget = useSettingsDialogStore((s) => s.consumeScrollTarget);
+
+ // "Change model" in the RAG menu lands here.
+ useEffect(() => {
+ if (scrollTarget !== "general-rag-embedding") return;
+ const frame = window.requestAnimationFrame(() => {
+ sectionRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
+ consumeScrollTarget("general-rag-embedding");
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [consumeScrollTarget, scrollTarget]);
useEffect(() => {
void useEmbeddingModelStore.getState().load();
@@ -331,10 +351,22 @@ export function DocumentsRagSection(): ReactElement {
: t("settings.general.rag.onDevice")
: "";
+ // On disk but not in memory: said under the picker, since Eject only shows once it loads.
+ const notLoaded = onDevice && !embeddingModel?.loaded && !downloading;
+ const statusHint =
+ onDevice && !downloading && !canDownload
+ ? t(
+ embeddingModel?.loaded
+ ? "settings.general.rag.loadedHint"
+ : "settings.general.rag.onDeviceHint",
+ )
+ : "";
+
const unload = async () => {
setIsSavingEmbeddingModel(true);
try {
await applyResidency(unloadEmbeddingModel);
+ toast.success(t("settings.general.rag.ejected"));
} catch (error) {
toast.error(t("settings.general.rag.unloadFailed"), {
description: error instanceof Error ? error.message : undefined,
@@ -345,92 +377,122 @@ export function DocumentsRagSection(): ReactElement {
};
return (
- <SettingsSection title={t("settings.general.rag.sectionTitle")}>
+ <SettingsSection ref={sectionRef} title={t("settings.general.rag.sectionTitle")}>
<SettingsRow
label={t("settings.general.rag.embeddingModel")}
- description={t("settings.general.rag.embeddingModelDescription", {
+ // Long explanation behind the info icon; the row shows the model's status.
+ hint={`${t("settings.general.rag.embeddingModelDescription", {
defaultModel: embeddingModel?.defaultEmbeddingModel ?? "",
- })}
- className="max-[360px]:flex-col max-[360px]:items-stretch max-[360px]:gap-3"
- below={
- <div className="flex flex-col items-end gap-1 max-[360px]:w-full">
- {embeddingModelError ? (
- <span className="max-w-[calc(300px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
- {embeddingModelError}
+ })} ${t("settings.general.rag.reindexWarning")}`}
+ description={
+ <span className="flex flex-col gap-1">
+ <span>{t("settings.general.rag.embeddingModelShort")}</span>
+ {statusText ? (
+ <span className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="flex min-w-0 items-center gap-1.5">
+ {statusTone ? (
+ <span
+ className={cn(
+ "size-[calc(6px*var(--ui-space-scale,1))] shrink-0 rounded-full",
+ statusTone === "pending"
+ ? "animate-pulse bg-muted-foreground"
+ : statusTone === "ready"
+ ? "bg-status-success"
+ : "bg-destructive",
+ )}
+ />
+ ) : null}
+ <span className="truncate">{statusText}</span>
+ {statusHint ? <StatusHint text={statusHint} /> : null}
+ </span>
</span>
) : null}
- <div className="flex min-h-7 w-full items-center justify-between gap-3">
- <span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
- {statusTone ? (
- <span
- className={cn(
- "size-1.5 shrink-0 rounded-full",
- statusTone === "pending"
- ? "animate-pulse bg-current"
- : statusTone === "ready"
- ? "bg-emerald-500"
- : "bg-destructive",
- )}
- />
- ) : null}
- <span className="truncate">{statusText}</span>
- </span>
- {forceCandidate ? (
- <Button
- variant="outline"
- size="sm"
- className="h-7 shrink-0 px-2.5 text-xs"
- disabled={isSavingEmbeddingModel}
- onClick={() => void applyEmbeddingModel(forceCandidate, true)}
- >
- {t("settings.general.rag.saveAnyway")}
- </Button>
- ) : canDownload ? (
- <Button
- variant="outline"
- size="sm"
- className="h-7 shrink-0 px-2.5 text-xs"
- disabled={downloading || isSavingEmbeddingModel}
- onClick={() => resolution && void startDownload(resolution)}
- >
- {downloading ? <Spinner className="mr-1.5" /> : null}
- {t("settings.general.rag.download")}
- </Button>
- ) : null}
- {/* Outside the chain above: saving a new model does not release the old one, so while Download shows the previous model can still be resident. */}
- {embeddingModel?.backendLoaded ? (
- <Button
- variant="outline"
- size="sm"
- className="h-7 shrink-0 px-2.5 text-xs"
- disabled={isSavingEmbeddingModel}
- onClick={() => void unload()}
- >
- {t("settings.general.rag.unload")}
- </Button>
- ) : null}
- </div>
- <span className="max-w-[calc(300px*var(--ui-space-scale,1))] text-right text-xs text-muted-foreground">
- {t("settings.general.rag.reindexWarning")}
+ </span>
+ }
+ // Bottom-aligned while Not loaded shows, so it sits level with the On device line.
+ className={cn(
+ "max-[360px]:flex-col max-[360px]:items-stretch max-[360px]:gap-3",
+ notLoaded && "items-end",
+ )}
+ below={
+ embeddingModelError ? (
+ <span className="max-w-[calc(300px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
+ {embeddingModelError}
</span>
- </div>
+ ) : undefined
}
>
- {/* Sets the trigger's width, since its own w-full outranks the 260px
- class: 300px, as wide as the notes below it. */}
- <div className="w-[calc(300px*var(--ui-space-scale,1))] max-[360px]:w-full">
- <EmbeddingModelPicker
- value={embeddingModel?.embeddingModel ?? ""}
- onSelect={(model) => void applyEmbeddingModel(model, false)}
- defaultModel={embeddingModel?.defaultEmbeddingModel}
- cachedModels={cachedRepos}
- accessToken={hfToken || undefined}
- disabled={!embeddingModel}
- busy={isSavingEmbeddingModel}
- className="w-[calc(260px*var(--ui-space-scale,1))] max-[360px]:w-full"
- />
+ {/* Wraps the Download button above the picker when the panel is too narrow for both. */}
+ <div className="flex max-w-full flex-wrap items-start justify-end gap-2 max-[360px]:w-full">
+ {forceCandidate ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ disabled={isSavingEmbeddingModel}
+ onClick={() => void applyEmbeddingModel(forceCandidate, true)}
+ >
+ {t("settings.general.rag.saveAnyway")}
+ </Button>
+ ) : canDownload ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ disabled={downloading || isSavingEmbeddingModel}
+ onClick={() => resolution && void startDownload(resolution)}
+ >
+ {downloading ? <Spinner /> : null}
+ {t("settings.general.rag.download")}
+ </Button>
+ ) : null}
+ {/* Status sits in the picker's column, so it lines up under the model name. */}
+ <div className="flex max-w-full flex-col gap-1 max-[360px]:w-full">
+ <EmbeddingModelPicker
+ value={embeddingModel?.embeddingModel ?? ""}
+ onSelect={(model) => void applyEmbeddingModel(model, false)}
+ defaultModel={embeddingModel?.defaultEmbeddingModel}
+ cachedModels={cachedRepos}
+ pinnedModels={pinnedModels}
+ onTogglePin={togglePin}
+ accessToken={hfToken || undefined}
+ disabled={!embeddingModel}
+ busy={isSavingEmbeddingModel}
+ loaded={embeddingModel?.loaded}
+ // Any resident embedder, not just this one: switching does not release the old one.
+ onEject={embeddingModel?.backendLoaded ? () => void unload() : undefined}
+ className="w-[calc(260px*var(--ui-space-scale,1))] max-w-full max-[360px]:w-full"
+ />
+ {notLoaded ? (
+ <span className="flex items-center gap-1.5 px-3.5 text-xs leading-snug text-muted-foreground">
+ <span className="size-[calc(6px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-muted-foreground" />
+ {t("settings.general.rag.notLoaded")}
+ <StatusHint text={t("settings.general.rag.notLoadedHint")} />
+ </span>
+ ) : null}
+ </div>
</div>
</SettingsRow>
</SettingsSection>
);
}
+
+/** Small info icon after a status, explaining what it means. */
+function StatusHint({ text }: { text: string }): ReactElement {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={text}
+ className="flex shrink-0 items-center rounded text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon icon={InformationCircleIcon} className="size-[calc(10px*var(--ui-space-scale,1))]" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[calc(260px*var(--ui-space-scale,1))] text-ui-11 leading-snug">
+ {text}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/embedding-model-picker.tsx b/studio/frontend/src/features/settings/components/embedding-model-picker.tsx
index 32dacc954c6..b3287a70ee6 100644
--- a/studio/frontend/src/features/settings/components/embedding-model-picker.tsx
+++ b/studio/frontend/src/features/settings/components/embedding-model-picker.tsx
@@ -8,11 +8,18 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { Spinner } from "@/components/ui/spinner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { formatBytes, useHubModelSearch } from "@/features/hub";
import { useDebouncedValue, useWheelScrollRef } from "@/hooks";
import { useT } from "@/i18n";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
-import { Search01Icon } from "@hugeicons/core-free-icons";
+import {
+ CheckmarkCircle02Icon,
+ PinIcon,
+ PinOffIcon,
+ RemoveCircleIcon,
+ Search01Icon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import type { PipelineType } from "@huggingface/hub";
import { type ReactElement, useMemo, useState } from "react";
@@ -34,10 +41,17 @@ type EmbeddingModelPickerProps = {
defaultModel?: string;
/** Repos already on disk, for the on-device dot. */
cachedModels?: ReadonlySet<string>;
+ /** Models pinned to the RAG menu; each row toggles its own pin. */
+ pinnedModels?: readonly string[];
+ onTogglePin?: (model: string) => void;
accessToken?: string;
disabled?: boolean;
/** Held open with a spinner while the pick is resolved and saved. */
busy?: boolean;
+ /** The selected model is in memory: green tick on the trigger. */
+ loaded?: boolean;
+ /** Something is resident; set to offer eject on trigger hover, as the chat model picker does. */
+ onEject?: () => void;
className?: string;
};
@@ -86,9 +100,13 @@ export function EmbeddingModelPicker({
onSelect,
defaultModel,
cachedModels,
+ pinnedModels,
+ onTogglePin,
accessToken,
disabled,
busy,
+ loaded,
+ onEject,
className,
}: EmbeddingModelPickerProps): ReactElement {
const t = useT();
@@ -123,8 +141,12 @@ export function EmbeddingModelPicker({
if (fallback && !rows.some((row) => row.id === fallback)) {
rows.push({ id: fallback, sizeBytes: null });
}
+ // Pinned models stay listed, so they can be unpinned here.
+ for (const pin of pinnedModels ?? []) {
+ if (!rows.some((row) => row.id === pin)) rows.push({ id: pin, sizeBytes: null });
+ }
return rows;
- }, [results, value, defaultModel]);
+ }, [results, value, defaultModel, pinnedModels]);
const pick = (model: string) => {
setOpen(false);
@@ -149,9 +171,39 @@ export function EmbeddingModelPicker({
data-testid="embedding-model-trigger"
aria-label={t("settings.general.rag.embeddingModel")}
disabled={disabled || busy}
- className={`border-border bg-background hover:bg-accent/50 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] focus-visible:border-ring flex h-8 w-full cursor-pointer items-center justify-between gap-1.5 rounded-full border px-3.5 font-mono text-ui-11 outline-none transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${className ?? ""}`}
+ className={`group/trigger border-border bg-background hover:bg-accent/50 dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] focus-visible:border-ring flex h-8 w-full cursor-pointer items-center justify-between gap-1.5 rounded-full border pr-3.5 font-mono text-ui-11 outline-none transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${onEject ? "pl-2.5" : "pl-3.5"} ${className ?? ""}`}
>
- <span className="truncate">{value}</span>
+ {onEject ? (
+ // As on the chat model picker: tick at rest, eject on hover. Keyboard and screen reader
+ // users get the Eject button at the foot of the list; a button can't nest in the trigger.
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <span
+ aria-hidden={true}
+ data-eject-hit={true}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onEject();
+ }}
+ className="-my-1 flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-[rgb(0_0_0_/_calc(0.1*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] [@media(hover:none)]:pointer-events-none"
+ >
+ <HugeiconsIcon
+ icon={loaded ? CheckmarkCircle02Icon : RemoveCircleIcon}
+ strokeWidth={1.75}
+ className={`size-3.5 group-hover/trigger:hidden ${loaded ? "text-emerald-500" : "text-muted-foreground"}`}
+ />
+ <HugeiconsIcon
+ icon={RemoveCircleIcon}
+ strokeWidth={1.75}
+ className="hidden size-3.5 text-red-500 group-hover/trigger:block"
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top">{t("settings.general.rag.ejectModel")}</TooltipContent>
+ </Tooltip>
+ ) : null}
+ <span className="min-w-0 flex-1 truncate text-left">{value}</span>
{busy ? (
<Spinner className="size-3.5 shrink-0" />
) : (
@@ -206,46 +258,97 @@ export function EmbeddingModelPicker({
{t("settings.general.rag.noResults")}
</div>
) : (
- items.map((item) => (
- <button
- key={item.id}
- type="button"
- onClick={() => pick(item.id)}
- aria-selected={item.id === value}
- className={`flex w-full items-center justify-between gap-3 rounded-full px-2.5 py-1.5 text-left transition-colors hover:bg-muted ${
- item.id === value ? "bg-accent font-medium" : ""
- }`}
- >
- <span className="flex min-w-0 flex-1 items-center gap-1.5">
- {/* Same green dot the Hub marks an on-device row with. */}
- {isOnDevice(cachedModels, item.id) ? (
- <span
- // A bare span is generic, and ARIA-in-HTML forbids naming
- // one, so Safari and Firefox drop the label and the dot goes
- // unannounced. Same role the Hub's own on-device dot carries.
- role="img"
- aria-label={t("settings.general.rag.onDevice")}
- className="size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-status-success"
- />
- ) : null}
- <span className="truncate font-mono text-ui-11">
- {item.id}
- </span>
- {item.id === defaultModel ? (
- <span className="shrink-0 rounded-full bg-emerald-500/12 px-1.5 py-px text-ui-9 font-medium text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400">
- {t("settings.general.rag.recommended")}
+ items.map((item) => {
+ const pinned = pinnedModels?.includes(item.id) ?? false;
+ return (
+ <div
+ key={item.id}
+ className={`group/row flex items-center rounded-full transition-colors hover:bg-muted ${
+ item.id === value ? "bg-accent font-medium" : ""
+ }`}
+ >
+ <button
+ type="button"
+ onClick={() => pick(item.id)}
+ aria-selected={item.id === value}
+ className="flex min-w-0 flex-1 items-center justify-between gap-3 rounded-full py-1.5 pl-2.5 text-left"
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-1.5">
+ {/* Same green dot the Hub marks an on-device row with. */}
+ {isOnDevice(cachedModels, item.id) ? (
+ <span
+ // A bare span is generic, and ARIA-in-HTML forbids naming
+ // one, so Safari and Firefox drop the label and the dot goes
+ // unannounced. Same role the Hub's own on-device dot carries.
+ role="img"
+ aria-label={t("settings.general.rag.onDevice")}
+ className="size-[calc(5px*var(--ui-space-scale,1))] shrink-0 rounded-full bg-status-success"
+ />
+ ) : null}
+ <span className="truncate font-mono text-ui-11">
+ {item.id}
+ </span>
+ {item.id === defaultModel ? (
+ <span className="shrink-0 rounded-full bg-emerald-500/12 px-1.5 py-px text-ui-9 font-medium text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400">
+ {t("settings.general.rag.recommended")}
+ </span>
+ ) : null}
</span>
- ) : null}
- </span>
- {item.sizeBytes ? (
- <span className="shrink-0 text-ui-10 tabular-nums text-muted-foreground">
- {formatBytes(item.sizeBytes)}
- </span>
- ) : null}
- </button>
- ))
+ {item.sizeBytes ? (
+ <span className="shrink-0 text-ui-10 tabular-nums text-muted-foreground">
+ {formatBytes(item.sizeBytes)}
+ </span>
+ ) : null}
+ </button>
+ {onTogglePin ? (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ onClick={() => onTogglePin(item.id)}
+ aria-pressed={pinned}
+ aria-label={t(
+ pinned ? "settings.general.rag.unpin" : "settings.general.rag.pin",
+ )}
+ // As on Recents: grey, unpin glyph once pinned. Hover only until then; always shown on touch.
+ className={`mr-1 ml-1 flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring ${
+ pinned ? "" : "opacity-0 group-hover/row:opacity-100 [@media(hover:none)]:opacity-100"
+ }`}
+ >
+ <HugeiconsIcon
+ icon={pinned ? PinOffIcon : PinIcon}
+ strokeWidth={1.75}
+ className="size-3.5"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top">
+ {t(pinned ? "settings.general.rag.unpin" : "settings.general.rag.pin")}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="w-2.5 shrink-0" />
+ )}
+ </div>
+ );
+ })
)}
</div>
+ {onEject ? (
+ <div className="border-t border-border/60 p-1">
+ <button
+ type="button"
+ onClick={() => {
+ setOpen(false);
+ onEject();
+ }}
+ className="flex w-full cursor-pointer items-center gap-2 rounded-full px-2.5 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:text-foreground focus-visible:outline-none"
+ >
+ <HugeiconsIcon icon={RemoveCircleIcon} strokeWidth={1.75} className="size-3.5" />
+ {t("settings.general.rag.ejectModel")}
+ </button>
+ </div>
+ ) : null}
</PopoverContent>
</Popover>
);
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 6df1b9c0078..d3d1efe17c2 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -69,6 +69,15 @@ export type {
SidebarNavItemPref,
} from "./stores/appearance-custom-store";
export { useMonitorOverlayStore } from "./stores/monitor-overlay-store";
+export { useEmbeddingModelStore } from "./stores/embedding-model-store";
+export { useEmbeddingPinsStore } from "./stores/embedding-pins-store";
+export {
+ type EmbeddingSwitchResult,
+ ejectEmbeddingModel,
+ embeddingModelName,
+ embeddingModelOwner,
+ switchEmbeddingModel,
+} from "./lib/switch-embedding-model";
export {
applyInterfaceScale,
stepInterfaceScale,
diff --git a/studio/frontend/src/features/settings/lib/switch-embedding-model.ts b/studio/frontend/src/features/settings/lib/switch-embedding-model.ts
new file mode 100644
index 00000000000..f26d8b0862b
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/switch-embedding-model.ts
@@ -0,0 +1,75 @@
+// 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 {
+ type EmbeddingModelResolution,
+ resolveEmbeddingModel,
+ unloadEmbeddingModel,
+ updateEmbeddingModelSettings,
+} from "../api/embedding-model";
+import { useEmbeddingModelStore } from "../stores/embedding-model-store";
+
+export type EmbeddingSwitchResult =
+ /** `needsDownload`: saved, but indexing needs the files on disk first. Null when the resolve
+ * failed, so nobody knows. */
+ | { status: "saved"; needsDownload: boolean | null }
+ /** A newer pick from another surface won; say nothing. */
+ | { status: "superseded" }
+ | { status: "failed"; message: string };
+
+/** Switch the embedding model from outside Settings (the RAG menu). Same order as the
+ * Settings picker: claim save order, resolve, then save what the resolve found. */
+export async function switchEmbeddingModel(
+ model: string,
+ hfToken: string | undefined,
+): Promise<EmbeddingSwitchResult> {
+ const store = useEmbeddingModelStore.getState();
+ const reservation = store.beginSave();
+ let plan: EmbeddingModelResolution | null = null;
+ try {
+ plan = await resolveEmbeddingModel(model, { hfToken });
+ } catch {
+ // Resolve is advisory; the save still verifies.
+ }
+ if (!store.isSaveCurrent(reservation)) return { status: "superseded" };
+ if (plan?.error) return { status: "failed", message: plan.error };
+ try {
+ const stood = await store.save(
+ () =>
+ updateEmbeddingModelSettings(model, {
+ hfToken,
+ ggufRepo: plan?.backend === "llama" ? (plan.downloadRepo ?? null) : null,
+ backend: plan?.backend ?? null,
+ }),
+ reservation,
+ );
+ if (!stood) return { status: "superseded" };
+ return {
+ status: "saved",
+ needsDownload: plan ? Boolean(!plan.cached && plan.downloadRepo) : null,
+ };
+ } catch (error) {
+ return { status: "failed", message: error instanceof Error ? error.message : "" };
+ }
+}
+
+/** Free the resident embedding model. It reloads on the next index or search. */
+export async function ejectEmbeddingModel(): Promise<void> {
+ await useEmbeddingModelStore.getState().applyResidency(unloadEmbeddingModel);
+}
+
+/** "unsloth/bge-small-en-v1.5" -> "bge-small-en-v1.5"; local paths keep their last segment. */
+export function embeddingModelName(model: string): string {
+ const id = model.trim().replace(/[\\/]+$/, "");
+ return id.slice(Math.max(id.lastIndexOf("/"), id.lastIndexOf("\\")) + 1) || id;
+}
+
+/** Owner of a repo id, or "" for a local path. A slashless name is a `sentence-transformers/`
+ * alias, as the backend resolves it. */
+export function embeddingModelOwner(model: string): string {
+ const id = model.trim();
+ // The path forms the backend's is_local_path reads as local without touching disk.
+ if (!id || /^[/.~]/.test(id) || id.includes("\\") || id.includes(":")) return "";
+ const slash = id.indexOf("/");
+ return slash === -1 ? "sentence-transformers" : id.slice(0, slash);
+}
diff --git a/studio/frontend/src/features/settings/stores/embedding-pins-store.ts b/studio/frontend/src/features/settings/stores/embedding-pins-store.ts
new file mode 100644
index 00000000000..33fb4392082
--- /dev/null
+++ b/studio/frontend/src/features/settings/stores/embedding-pins-store.ts
@@ -0,0 +1,57 @@
+// 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 { create } from "zustand";
+
+import { mirrorPins, onPinsRestored } from "../../../lib/pins-mirror.ts";
+
+export const EMBEDDING_PINS_STORAGE_KEY = "unsloth_embedding_pins";
+
+/** Embedding models pinned to the RAG menu for quick switching. A plain id list in localStorage,
+ * mirrored to the account so an account switch's purge does not lose it. */
+interface EmbeddingPinsState {
+ pinned: string[];
+ togglePin: (model: string) => void;
+}
+
+function readPins(): string[] {
+ try {
+ const raw: unknown = JSON.parse(localStorage.getItem(EMBEDDING_PINS_STORAGE_KEY) ?? "[]");
+ return Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+function writePins(pinned: string[]): void {
+ mirrorPins("embedding", pinned);
+ try {
+ localStorage.setItem(EMBEDDING_PINS_STORAGE_KEY, JSON.stringify(pinned));
+ } catch {
+ // Storage unavailable; the account copy still has them.
+ }
+}
+
+export const useEmbeddingPinsStore = create<EmbeddingPinsState>()((set, get) => ({
+ pinned: readPins(),
+ togglePin: (model) => {
+ const id = model.trim();
+ if (!id) return;
+ const current = get().pinned;
+ const pinned = current.includes(id)
+ ? current.filter((pin) => pin !== id)
+ : [...current, id];
+ writePins(pinned);
+ set({ pinned });
+ },
+}));
+
+onPinsRestored("embedding", () => useEmbeddingPinsStore.setState({ pinned: readPins() }));
+
+if (typeof window !== "undefined") {
+ window.addEventListener("storage", (event) => {
+ if (event.key === EMBEDDING_PINS_STORAGE_KEY || event.key === null) {
+ useEmbeddingPinsStore.setState({ pinned: readPins() });
+ }
+ });
+}
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 4752547240e..c5712b69747 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -37,6 +37,7 @@ export type SettingsScrollTarget =
| "chat-composer"
| "browser-html-network"
| "general-hub"
+ | "general-rag-embedding"
/** Old name of sandbox-permissions, from when Permissions lived in General. */
| "general-permissions"
| "library-storage"
@@ -142,6 +143,7 @@ const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
"appearance-sidebar-nav": "appearance",
"browser-html-network": "browser",
"general-hub": "general",
+ "general-rag-embedding": "general",
"general-permissions": "sandbox",
"library-storage": "library",
"resources-caches": "resources",
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 3e06ef6877d..e0031734815 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1644,6 +1644,7 @@ export const ar = {
rag: {
sectionTitle: "المستندات وRAG",
embeddingModel: "نموذج التضمين (Embedding)",
+ embeddingModelShort: "يحوّل مستنداتك إلى متجهات ليتمكن الدردشة من البحث فيها.",
embeddingModelDescription:
"نموذج Hugging Face أو مسار محلي يُستخدم لفهرسة مستنداتك والبحث فيها. القيمة الافتراضية هي {defaultModel}.",
searchPlaceholder: "ابحث عن أي نموذج على HF",
@@ -1660,8 +1661,14 @@ export const ar = {
checking: "جارٍ التحقق…",
noResults: "لم يتم العثور على نماذج تضمين",
download: "تنزيل",
- unload: "إلغاء التحميل",
- unloadFailed: "تعذّر إلغاء تحميل نموذج التضمين",
+ unload: "إخراج",
+ unloadFailed: "تعذّر إخراج نموذج التضمين",
+ ejected: "تم إخراج نموذج التضمين",
+ ejectModel: "إخراج النموذج",
+ onDeviceHint: "تم تنزيله على هذا الكمبيوتر. لا يُحمَّل في الذاكرة إلا أثناء فهرسة المستندات أو البحث فيها، فلا يستهلك RAM أو VRAM حتى ذلك الحين.",
+ loadedHint: "في الذاكرة الآن ويستخدم RAM أو VRAM. مرّر المؤشر فوق منتقي النموذج وانقر الأيقونة الحمراء لإخراجه.",
+ notLoaded: "غير محمّل",
+ notLoadedHint: "ليس في الذاكرة الآن. يُحمَّل تلقائيًا عند فهرسة المستندات أو البحث فيها، وبعدها يمكنك إخراجه من المنتقي.",
downloadingStatus: "جارٍ التنزيل…",
notDownloaded: "غير مُنزّل",
notDownloadedSized: "غير مُنزّل · {size}",
@@ -1672,6 +1679,21 @@ export const ar = {
downloadFailed: "تعذّر بدء التنزيل",
downloadConflict: "استأنف هذا التنزيل من Hub",
downloadBusy: "التنزيل قيد التقدم بالفعل",
+ pin: "تثبيت في قائمة RAG",
+ unpin: "إلغاء التثبيت من قائمة RAG",
+ menuChip: "النموذج",
+ moreModels: "المزيد من النماذج",
+ pinMoreModels: "ثبّت نماذج أخرى",
+ defaultTag: "افتراضي",
+ localModel: "نموذج محلي",
+ switched: "تم تعيين نموذج التضمين إلى {model}",
+ switchedNeedsDownload: "لم يتم تنزيل {model} بعد",
+ switchedNeedsDownloadDescription: "نزّله من الإعدادات قبل فهرسة ملفات جديدة.",
+ switchedUncheckedDescription: "تعذّر التحقق مما إذا كان قد نُزّل. تحقّق في الإعدادات قبل فهرسة ملفات جديدة.",
+ openSettings: "فتح الإعدادات",
+ switchFailed: "تعذّر تبديل نموذج التضمين",
+ back: "العودة إلى المصادر",
+ menuSubtitle: "يشغّل البحث في الملفات",
},
storage: {
sectionTitle: "التخزين",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 17fc34b41ba..934e8bea9f4 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1667,6 +1667,7 @@ export const de = {
rag: {
sectionTitle: "Dokumente & RAG",
embeddingModel: "Embedding-Modell",
+ embeddingModelShort: "Wandelt deine Dokumente in Vektoren um, damit der Chat sie durchsuchen kann.",
embeddingModelDescription:
"Hugging-Face-Modell oder lokaler Pfad zum Indexieren und Durchsuchen Ihrer Dokumente. Standard ist {defaultModel}.",
searchPlaceholder: "Beliebiges Modell auf HF suchen",
@@ -1685,8 +1686,14 @@ export const de = {
checking: "Wird geprüft…",
noResults: "Keine Embedding-Modelle gefunden",
download: "Herunterladen",
- unload: "Entladen",
- unloadFailed: "Embedding-Modell konnte nicht entladen werden",
+ unload: "Auswerfen",
+ unloadFailed: "Embedding-Modell konnte nicht ausgeworfen werden",
+ ejected: "Embedding-Modell ausgeworfen",
+ ejectModel: "Modell auswerfen",
+ onDeviceHint: "Auf diesen Computer heruntergeladen. Es wird nur beim Indexieren oder Durchsuchen von Dokumenten in den Speicher geladen und belegt bis dahin weder RAM noch VRAM.",
+ loadedHint: "Jetzt im Speicher und belegt RAM oder VRAM. Fahre über die Modellauswahl und klicke auf das rote Symbol, um es auszuwerfen.",
+ notLoaded: "Nicht geladen",
+ notLoadedHint: "Gerade nicht im Speicher. Es lädt automatisch beim nächsten Indexieren oder Durchsuchen von Dokumenten, danach kannst du es in der Auswahl auswerfen.",
downloadingStatus: "Wird heruntergeladen…",
notDownloaded: "Nicht heruntergeladen",
notDownloadedSized: "Nicht heruntergeladen · {size}",
@@ -1697,6 +1704,21 @@ export const de = {
downloadFailed: "Download konnte nicht gestartet werden",
downloadConflict: "Diesen Download im Hub fortsetzen",
downloadBusy: "Download läuft bereits",
+ pin: "An das RAG-Menü anheften",
+ unpin: "Vom RAG-Menü lösen",
+ menuChip: "Modell",
+ moreModels: "Weitere Modelle",
+ pinMoreModels: "Weitere Modelle anheften",
+ defaultTag: "Standard",
+ localModel: "Lokales Modell",
+ switched: "Embedding-Modell auf {model} gesetzt",
+ switchedNeedsDownload: "{model} ist noch nicht heruntergeladen",
+ switchedNeedsDownloadDescription: "Lade es in den Einstellungen herunter, bevor neue Dateien indexiert werden.",
+ switchedUncheckedDescription: "Konnte nicht prüfen, ob es heruntergeladen ist. Prüfe es in den Einstellungen, bevor du neue Dateien indexierst.",
+ openSettings: "Einstellungen öffnen",
+ switchFailed: "Embedding-Modell konnte nicht gewechselt werden",
+ back: "Zurück zu den Quellen",
+ menuSubtitle: "Für die Dateisuche",
},
storage: {
sectionTitle: "Speicher",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e00753f17a0..6b5b279b651 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1703,6 +1703,7 @@ export const en = {
rag: {
sectionTitle: "Documents & RAG",
embeddingModel: "Embedding model",
+ embeddingModelShort: "Turns your documents into vectors so chat can search them.",
embeddingModelDescription:
"Hugging Face model or local path used to index and search your documents. Default is {defaultModel}.",
searchPlaceholder: "Search any model on HF",
@@ -1719,8 +1720,14 @@ export const en = {
checking: "Checking…",
noResults: "No embedding models found",
download: "Download",
- unload: "Unload",
- unloadFailed: "Couldn't unload the embedding model",
+ unload: "Eject",
+ unloadFailed: "Couldn't eject the embedding model",
+ ejected: "Embedding model ejected",
+ ejectModel: "Eject model",
+ onDeviceHint: "Downloaded to this computer. It loads into memory only while documents are indexed or searched, so it uses no RAM or VRAM until then.",
+ loadedHint: "In memory now, using RAM or VRAM. Hover the model picker and click the red icon to eject it.",
+ notLoaded: "Not loaded",
+ notLoadedHint: "Not in memory right now. It loads on its own the next time documents are indexed or searched, then you can eject it from the picker.",
downloadingStatus: "Downloading…",
notDownloaded: "Not downloaded",
notDownloadedSized: "Not downloaded · {size}",
@@ -1731,6 +1738,21 @@ export const en = {
downloadFailed: "Couldn't start the download",
downloadConflict: "Resume this download from the Hub",
downloadBusy: "Download already in progress",
+ pin: "Pin to the RAG menu",
+ unpin: "Unpin from the RAG menu",
+ menuChip: "Model",
+ moreModels: "More models",
+ pinMoreModels: "Pin more models",
+ defaultTag: "Default",
+ localModel: "Local model",
+ switched: "Embedding model set to {model}",
+ switchedNeedsDownload: "{model} is not downloaded yet",
+ switchedNeedsDownloadDescription: "Download it in Settings before indexing new files.",
+ switchedUncheckedDescription: "Couldn't check whether it's downloaded. Check in Settings before indexing new files.",
+ openSettings: "Open settings",
+ switchFailed: "Couldn't switch the embedding model",
+ back: "Back to sources",
+ menuSubtitle: "Powers file search",
},
storage: {
sectionTitle: "Storage",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 956accd21a4..52a58e1eb6f 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1662,6 +1662,7 @@ export const es = {
rag: {
sectionTitle: "Documentos y RAG",
embeddingModel: "Modelo de embeddings",
+ embeddingModelShort: "Convierte tus documentos en vectores para que el chat pueda buscar en ellos.",
embeddingModelDescription:
"Modelo de Hugging Face o ruta local usada para indexar y buscar tus documentos. El valor predeterminado es {defaultModel}.",
searchPlaceholder: "Buscar cualquier modelo en HF",
@@ -1680,8 +1681,14 @@ export const es = {
checking: "Comprobando…",
noResults: "No se encontraron modelos de embedding",
download: "Descargar",
- unload: "Descargar de memoria",
- unloadFailed: "No se pudo descargar el modelo de embedding",
+ unload: "Expulsar",
+ unloadFailed: "No se pudo expulsar el modelo de embedding",
+ ejected: "Modelo de embedding expulsado",
+ ejectModel: "Expulsar modelo",
+ onDeviceHint: "Descargado en este equipo. Solo se carga en memoria al indexar o buscar documentos, así que no usa RAM ni VRAM hasta entonces.",
+ loadedHint: "En memoria ahora, usando RAM o VRAM. Pasa el cursor por el selector de modelo y haz clic en el icono rojo para expulsarlo.",
+ notLoaded: "No cargado",
+ notLoadedHint: "No está en memoria ahora. Se carga solo la próxima vez que se indexen o busquen documentos, y luego puedes expulsarlo desde el selector.",
downloadingStatus: "Descargando…",
notDownloaded: "No descargado",
notDownloadedSized: "No descargado · {size}",
@@ -1692,6 +1699,21 @@ export const es = {
downloadFailed: "No se pudo iniciar la descarga",
downloadConflict: "Reanuda esta descarga desde el Hub",
downloadBusy: "La descarga ya está en curso",
+ pin: "Fijar en el menú RAG",
+ unpin: "Quitar del menú RAG",
+ menuChip: "Modelo",
+ moreModels: "Más modelos",
+ pinMoreModels: "Fijar más modelos",
+ defaultTag: "Predeterminado",
+ localModel: "Modelo local",
+ switched: "Modelo de embedding cambiado a {model}",
+ switchedNeedsDownload: "{model} aún no está descargado",
+ switchedNeedsDownloadDescription: "Descárgalo en Ajustes antes de indexar archivos nuevos.",
+ switchedUncheckedDescription: "No se pudo comprobar si está descargado. Revísalo en Ajustes antes de indexar archivos nuevos.",
+ openSettings: "Abrir ajustes",
+ switchFailed: "No se pudo cambiar el modelo de embedding",
+ back: "Volver a las fuentes",
+ menuSubtitle: "Para buscar en archivos",
},
storage: {
sectionTitle: "Almacenamiento",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 4fcd556c2c1..441433852a9 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1666,6 +1666,7 @@ export const fr = {
rag: {
sectionTitle: "Documents et RAG",
embeddingModel: "Modèle d'embedding",
+ embeddingModelShort: "Convertit vos documents en vecteurs pour que le chat puisse y chercher.",
embeddingModelDescription:
"Modèle Hugging Face ou chemin local utilisé pour indexer et rechercher vos documents. La valeur par défaut est {defaultModel}.",
searchPlaceholder: "Rechercher n'importe quel modèle sur HF",
@@ -1683,8 +1684,14 @@ export const fr = {
checking: "Vérification…",
noResults: "Aucun modèle d'embedding trouvé",
download: "Télécharger",
- unload: "Décharger",
- unloadFailed: "Impossible de décharger le modèle d'embedding",
+ unload: "Éjecter",
+ unloadFailed: "Impossible d'éjecter le modèle d'embedding",
+ ejected: "Modèle d'embedding éjecté",
+ ejectModel: "Éjecter le modèle",
+ onDeviceHint: "Téléchargé sur cet ordinateur. Il ne se charge en mémoire que pendant l'indexation ou la recherche de documents, et n'utilise ni RAM ni VRAM d'ici là.",
+ loadedHint: "En mémoire, il utilise de la RAM ou de la VRAM. Survolez le sélecteur de modèle et cliquez sur l'icône rouge pour l'éjecter.",
+ notLoaded: "Non chargé",
+ notLoadedHint: "Pas en mémoire pour l'instant. Il se charge tout seul à la prochaine indexation ou recherche de documents, puis vous pouvez l'éjecter depuis le sélecteur.",
downloadingStatus: "Téléchargement…",
notDownloaded: "Non téléchargé",
notDownloadedSized: "Non téléchargé · {size}",
@@ -1695,6 +1702,21 @@ export const fr = {
downloadFailed: "Impossible de démarrer le téléchargement",
downloadConflict: "Reprenez ce téléchargement depuis le Hub",
downloadBusy: "Téléchargement déjà en cours",
+ pin: "Épingler au menu RAG",
+ unpin: "Désépingler du menu RAG",
+ menuChip: "Modèle",
+ moreModels: "Plus de modèles",
+ pinMoreModels: "Épingler d'autres modèles",
+ defaultTag: "Par défaut",
+ localModel: "Modèle local",
+ switched: "Modèle d'embedding défini sur {model}",
+ switchedNeedsDownload: "{model} n'est pas encore téléchargé",
+ switchedNeedsDownloadDescription: "Téléchargez-le dans les Paramètres avant d'indexer de nouveaux fichiers.",
+ switchedUncheckedDescription: "Impossible de vérifier s'il est téléchargé. Vérifiez dans les paramètres avant d'indexer de nouveaux fichiers.",
+ openSettings: "Ouvrir les paramètres",
+ switchFailed: "Impossible de changer le modèle d'embedding",
+ back: "Retour aux sources",
+ menuSubtitle: "Pour la recherche de fichiers",
},
storage: {
sectionTitle: "Stockage",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 96c979d6f58..2c9529f6e76 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -1747,6 +1747,7 @@ export const he = {
rag: {
sectionTitle: "מסמכים ו-RAG",
embeddingModel: "מודל שיבוץ (Embedding)",
+ embeddingModelShort: "ממיר את המסמכים שלך לווקטורים כדי שהצ'אט יוכל לחפש בהם.",
embeddingModelDescription:
"מודל Hugging Face או נתיב מקומי המשמש לאינדוקס וחיפוש במסמכים שלך. ברירת המחדל היא {defaultModel}.",
searchPlaceholder: "חפש כל מודל ב-HF",
@@ -1763,8 +1764,14 @@ export const he = {
checking: "בודק…",
noResults: "לא נמצאו מודלי שיבוץ",
download: "הורד",
- unload: "פרוק מהזיכרון",
- unloadFailed: "לא ניתן לפרוק את מודל השיבוץ מהזיכרון",
+ unload: "הוצאה",
+ unloadFailed: "לא ניתן להוציא את מודל השיבוץ",
+ ejected: "מודל השיבוץ הוצא",
+ ejectModel: "הוצאת המודל",
+ onDeviceHint: "הורד למחשב הזה. הוא נטען לזיכרון רק בזמן אינדוקס או חיפוש מסמכים, כך שעד אז אינו משתמש ב-RAM או ב-VRAM.",
+ loadedHint: "בזיכרון כעת ומשתמש ב-RAM או ב-VRAM. רחף מעל בורר המודל ולחץ על הסמל האדום כדי להוציא אותו.",
+ notLoaded: "לא טעון",
+ notLoadedHint: "לא בזיכרון כרגע. הוא ייטען לבד בפעם הבאה שמסמכים יעברו אינדוקס או חיפוש, ואז אפשר להוציא אותו מהבורר.",
downloadingStatus: "מוריד…",
notDownloaded: "לא הורד",
notDownloadedSized: "לא הורד · {size}",
@@ -1775,6 +1782,21 @@ export const he = {
downloadFailed: "לא ניתן להתחיל בהורדה",
downloadConflict: "המשך הורדה זו מתוך ה-Hub",
downloadBusy: "הורדה כבר מתבצעת כעת",
+ pin: "הצמדה לתפריט RAG",
+ unpin: "ביטול הצמדה מתפריט RAG",
+ menuChip: "מודל",
+ moreModels: "מודלים נוספים",
+ pinMoreModels: "הצמדת מודלים נוספים",
+ defaultTag: "ברירת מחדל",
+ localModel: "מודל מקומי",
+ switched: "מודל ההטמעה הוגדר ל-{model}",
+ switchedNeedsDownload: "{model} עדיין לא הורד",
+ switchedNeedsDownloadDescription: "הורידו אותו בהגדרות לפני אינדוקס קבצים חדשים.",
+ switchedUncheckedDescription: "לא ניתן לבדוק אם הוא הורד. בדוק בהגדרות לפני אינדוקס קבצים חדשים.",
+ openSettings: "פתיחת ההגדרות",
+ switchFailed: "לא ניתן להחליף את מודל ההטמעה",
+ back: "חזרה למקורות",
+ menuSubtitle: "מפעיל את חיפוש הקבצים",
},
storage: {
sectionTitle: "אחסון",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 9382a0be379..5fb924cc472 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1647,6 +1647,7 @@ export const hi = {
rag: {
sectionTitle: "दस्तावेज़ और RAG",
embeddingModel: "एम्बेडिंग मॉडल",
+ embeddingModelShort: "आपके दस्तावेज़ों को वेक्टर में बदलता है ताकि चैट उनमें खोज सके।",
embeddingModelDescription:
"आपके दस्तावेज़ों को इंडेक्स और खोजने के लिए उपयोग किया जाने वाला Hugging Face मॉडल या स्थानीय पथ। डिफ़ॉल्ट {defaultModel} है।",
searchPlaceholder: "HF पर कोई भी मॉडल खोजें",
@@ -1663,8 +1664,14 @@ export const hi = {
checking: "जाँच रहे हैं…",
noResults: "कोई एम्बेडिंग मॉडल नहीं मिला",
download: "डाउनलोड करें",
- unload: "अनलोड करें",
- unloadFailed: "एम्बेडिंग मॉडल अनलोड नहीं हो सका",
+ unload: "इजेक्ट करें",
+ unloadFailed: "एम्बेडिंग मॉडल इजेक्ट नहीं हो सका",
+ ejected: "एम्बेडिंग मॉडल इजेक्ट हो गया",
+ ejectModel: "मॉडल इजेक्ट करें",
+ onDeviceHint: "इस कंप्यूटर पर डाउनलोड है। यह केवल दस्तावेज़ इंडेक्स या खोजते समय मेमोरी में लोड होता है, तब तक कोई RAM या VRAM नहीं लेता।",
+ loadedHint: "अभी मेमोरी में है और RAM या VRAM ले रहा है। इजेक्ट करने के लिए मॉडल पिकर पर होवर करें और लाल आइकन पर क्लिक करें।",
+ notLoaded: "लोड नहीं है",
+ notLoadedHint: "अभी मेमोरी में नहीं है। अगली बार दस्तावेज़ इंडेक्स या खोजे जाने पर यह अपने आप लोड होगा, फिर आप इसे पिकर से इजेक्ट कर सकते हैं।",
downloadingStatus: "डाउनलोड हो रहा है…",
notDownloaded: "डाउनलोड नहीं हुआ",
notDownloadedSized: "डाउनलोड नहीं हुआ · {size}",
@@ -1675,6 +1682,21 @@ export const hi = {
downloadFailed: "डाउनलोड शुरू नहीं हो सका",
downloadConflict: "इस डाउनलोड को Hub से फिर से शुरू करें",
downloadBusy: "डाउनलोड पहले से चल रहा है",
+ pin: "RAG मेन्यू में पिन करें",
+ unpin: "RAG मेन्यू से अनपिन करें",
+ menuChip: "मॉडल",
+ moreModels: "और मॉडल",
+ pinMoreModels: "और मॉडल पिन करें",
+ defaultTag: "डिफ़ॉल्ट",
+ localModel: "लोकल मॉडल",
+ switched: "एम्बेडिंग मॉडल {model} पर सेट किया गया",
+ switchedNeedsDownload: "{model} अभी डाउनलोड नहीं हुआ है",
+ switchedNeedsDownloadDescription: "नई फ़ाइलें इंडेक्स करने से पहले इसे सेटिंग्स में डाउनलोड करें।",
+ switchedUncheckedDescription: "यह जाँच नहीं हो सकी कि यह डाउनलोड है या नहीं। नई फ़ाइलें इंडेक्स करने से पहले सेटिंग्स में देखें।",
+ openSettings: "सेटिंग्स खोलें",
+ switchFailed: "एम्बेडिंग मॉडल नहीं बदला जा सका",
+ back: "स्रोतों पर वापस जाएँ",
+ menuSubtitle: "फ़ाइल खोज के लिए",
},
storage: {
sectionTitle: "स्टोरेज",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index f5ab5d88979..0d2a275726c 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1644,6 +1644,7 @@ export const it = {
rag: {
sectionTitle: "Documenti e RAG",
embeddingModel: "Modello di embedding",
+ embeddingModelShort: "Trasforma i tuoi documenti in vettori così la chat può cercarli.",
embeddingModelDescription:
"Modello Hugging Face o percorso locale usato per indicizzare e cercare nei tuoi documenti. Il valore predefinito è {defaultModel}.",
searchPlaceholder: "Cerca qualsiasi modello su HF",
@@ -1662,8 +1663,14 @@ export const it = {
checking: "Verifica…",
noResults: "Nessun modello di embedding trovato",
download: "Scarica",
- unload: "Scarica dalla memoria",
- unloadFailed: "Impossibile scaricare il modello di embedding",
+ unload: "Espelli",
+ unloadFailed: "Impossibile espellere il modello di embedding",
+ ejected: "Modello di embedding espulso",
+ ejectModel: "Espelli modello",
+ onDeviceHint: "Scaricato su questo computer. Si carica in memoria solo durante l'indicizzazione o la ricerca dei documenti, quindi fino ad allora non usa RAM né VRAM.",
+ loadedHint: "Ora in memoria, usa RAM o VRAM. Passa sul selettore del modello e fai clic sull'icona rossa per espellerlo.",
+ notLoaded: "Non caricato",
+ notLoadedHint: "Ora non è in memoria. Si carica da solo alla prossima indicizzazione o ricerca dei documenti, poi puoi espellerlo dal selettore.",
downloadingStatus: "Download in corso…",
notDownloaded: "Non scaricato",
notDownloadedSized: "Non scaricato · {size}",
@@ -1674,6 +1681,21 @@ export const it = {
downloadFailed: "Impossibile avviare il download",
downloadConflict: "Riprendi questo download dall'Hub",
downloadBusy: "Download già in corso",
+ pin: "Fissa nel menu RAG",
+ unpin: "Rimuovi dal menu RAG",
+ menuChip: "Modello",
+ moreModels: "Altri modelli",
+ pinMoreModels: "Fissa altri modelli",
+ defaultTag: "Predefinito",
+ localModel: "Modello locale",
+ switched: "Modello di embedding impostato su {model}",
+ switchedNeedsDownload: "{model} non è ancora scaricato",
+ switchedNeedsDownloadDescription: "Scaricalo nelle Impostazioni prima di indicizzare nuovi file.",
+ switchedUncheckedDescription: "Impossibile verificare se è scaricato. Controlla nelle impostazioni prima di indicizzare nuovi file.",
+ openSettings: "Apri impostazioni",
+ switchFailed: "Impossibile cambiare il modello di embedding",
+ back: "Torna alle fonti",
+ menuSubtitle: "Per la ricerca nei file",
},
storage: {
sectionTitle: "Archiviazione",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index afad5ee5ddc..aa062698a06 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1632,6 +1632,7 @@ export const ja = {
rag: {
sectionTitle: "ドキュメントと RAG",
embeddingModel: "埋め込みモデル",
+ embeddingModelShort: "ドキュメントをベクトルに変換し、チャットで検索できるようにします。",
embeddingModelDescription: "ドキュメントのインデックス作成と検索に使用する Hugging Face モデルまたはローカルパス。デフォルトは {defaultModel} です。",
searchPlaceholder: "HF 上の任意のモデルを検索",
reindexWarning: "新しくインデックスされるドキュメントにのみ影響します。モデルを変更した後は、既存のドキュメントを再アップロードしてください。",
@@ -1646,8 +1647,14 @@ export const ja = {
checking: "確認中…",
noResults: "埋め込みモデルが見つかりません",
download: "ダウンロード",
- unload: "アンロード",
- unloadFailed: "埋め込みモデルをアンロードできませんでした",
+ unload: "取り出す",
+ unloadFailed: "埋め込みモデルを取り出せませんでした",
+ ejected: "埋め込みモデルを取り出しました",
+ ejectModel: "モデルを取り出す",
+ onDeviceHint: "このコンピューターにダウンロード済みです。ドキュメントのインデックス作成や検索中にのみメモリに読み込まれるため、それまでは RAM や VRAM を使いません。",
+ loadedHint: "現在メモリ上にあり、RAM または VRAM を使用しています。モデルピッカーにカーソルを合わせ、赤いアイコンをクリックすると取り出せます。",
+ notLoaded: "未読み込み",
+ notLoadedHint: "現在メモリにはありません。次にドキュメントのインデックス作成や検索を行うと自動で読み込まれ、その後ピッカーから取り出せます。",
downloadingStatus: "ダウンロード中…",
notDownloaded: "未ダウンロード",
notDownloadedSized: "未ダウンロード · {size}",
@@ -1657,6 +1664,21 @@ export const ja = {
downloadFailed: "ダウンロードを開始できませんでした",
downloadConflict: "このダウンロードは Hub から再開してください",
downloadBusy: "ダウンロードはすでに進行中です",
+ pin: "RAG メニューにピン留め",
+ unpin: "RAG メニューからピン留めを外す",
+ menuChip: "モデル",
+ moreModels: "その他のモデル",
+ pinMoreModels: "他のモデルをピン留め",
+ defaultTag: "デフォルト",
+ localModel: "ローカルモデル",
+ switched: "埋め込みモデルを {model} に設定しました",
+ switchedNeedsDownload: "{model} はまだダウンロードされていません",
+ switchedNeedsDownloadDescription: "新しいファイルをインデックスする前に、設定でダウンロードしてください。",
+ switchedUncheckedDescription: "ダウンロード済みか確認できませんでした。新しいファイルをインデックスする前に設定で確認してください。",
+ openSettings: "設定を開く",
+ switchFailed: "埋め込みモデルを切り替えられませんでした",
+ back: "ソースに戻る",
+ menuSubtitle: "ファイル検索に使用",
},
storage: {
sectionTitle: "ストレージ",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 38debcbfbab..07d718ce841 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1641,6 +1641,7 @@ export const ko = {
rag: {
sectionTitle: "문서 & RAG",
embeddingModel: "임베딩 모델",
+ embeddingModelShort: "문서를 벡터로 변환해 채팅에서 검색할 수 있게 합니다.",
embeddingModelDescription:
"문서 인덱싱 및 검색에 사용할 Hugging Face 모델이나 로컬 경로를 지정합니다. 기본값은 {defaultModel}입니다.",
searchPlaceholder: "HF의 모든 모델 검색",
@@ -1657,8 +1658,14 @@ export const ko = {
checking: "확인 중…",
noResults: "임베딩 모델을 찾을 수 없습니다",
download: "다운로드",
- unload: "언로드",
- unloadFailed: "임베딩 모델을 언로드할 수 없습니다",
+ unload: "꺼내기",
+ unloadFailed: "임베딩 모델을 꺼낼 수 없습니다",
+ ejected: "임베딩 모델을 꺼냈습니다",
+ ejectModel: "모델 꺼내기",
+ onDeviceHint: "이 컴퓨터에 다운로드되어 있습니다. 문서를 인덱싱하거나 검색할 때만 메모리에 로드되므로 그전까지는 RAM이나 VRAM을 쓰지 않습니다.",
+ loadedHint: "지금 메모리에 있으며 RAM 또는 VRAM을 사용 중입니다. 모델 선택기에 마우스를 올리고 빨간 아이콘을 클릭하면 꺼낼 수 있습니다.",
+ notLoaded: "로드되지 않음",
+ notLoadedHint: "지금은 메모리에 없습니다. 다음에 문서를 인덱싱하거나 검색할 때 자동으로 로드되며, 그 후 선택기에서 꺼낼 수 있습니다.",
downloadingStatus: "다운로드 중…",
notDownloaded: "다운로드되지 않음",
notDownloadedSized: "다운로드되지 않음 · {size}",
@@ -1668,6 +1675,21 @@ export const ko = {
downloadFailed: "다운로드를 시작할 수 없습니다",
downloadConflict: "Hub에서 이 다운로드를 재개하세요",
downloadBusy: "이미 다운로드가 진행 중입니다",
+ pin: "RAG 메뉴에 고정",
+ unpin: "RAG 메뉴에서 고정 해제",
+ menuChip: "모델",
+ moreModels: "더 많은 모델",
+ pinMoreModels: "모델 더 고정하기",
+ defaultTag: "기본값",
+ localModel: "로컬 모델",
+ switched: "임베딩 모델을 {model}(으)로 설정했습니다",
+ switchedNeedsDownload: "{model}이(가) 아직 다운로드되지 않았습니다",
+ switchedNeedsDownloadDescription: "새 파일을 인덱싱하기 전에 설정에서 다운로드하세요.",
+ switchedUncheckedDescription: "다운로드 여부를 확인하지 못했습니다. 새 파일을 인덱싱하기 전에 설정에서 확인하세요.",
+ openSettings: "설정 열기",
+ switchFailed: "임베딩 모델을 전환하지 못했습니다",
+ back: "소스로 돌아가기",
+ menuSubtitle: "파일 검색에 사용",
},
storage: {
sectionTitle: "저장소",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4e0196b05fc..0e289781c66 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1656,6 +1656,7 @@ export const ptBR = {
rag: {
sectionTitle: "Documentos e RAG",
embeddingModel: "Modelo de embedding",
+ embeddingModelShort: "Transforma seus documentos em vetores para que o chat possa pesquisá-los.",
embeddingModelDescription:
"Modelo do Hugging Face ou caminho local usado para indexar e buscar seus documentos. O padrão é {defaultModel}.",
searchPlaceholder: "Buscar qualquer modelo no HF",
@@ -1672,8 +1673,14 @@ export const ptBR = {
checking: "Verificando…",
noResults: "Nenhum modelo de embedding encontrado",
download: "Baixar",
- unload: "Descarregar",
- unloadFailed: "Não foi possível descarregar o modelo de embedding",
+ unload: "Ejetar",
+ unloadFailed: "Não foi possível ejetar o modelo de embedding",
+ ejected: "Modelo de embedding ejetado",
+ ejectModel: "Ejetar modelo",
+ onDeviceHint: "Baixado neste computador. Só é carregado na memória ao indexar ou pesquisar documentos, então não usa RAM nem VRAM até lá.",
+ loadedHint: "Na memória agora, usando RAM ou VRAM. Passe o mouse no seletor de modelo e clique no ícone vermelho para ejetar.",
+ notLoaded: "Não carregado",
+ notLoadedHint: "Não está na memória agora. Carrega sozinho na próxima vez que documentos forem indexados ou pesquisados, e então você pode ejetá-lo no seletor.",
downloadingStatus: "Baixando…",
notDownloaded: "Não baixado",
notDownloadedSized: "Não baixado · {size}",
@@ -1684,6 +1691,21 @@ export const ptBR = {
downloadFailed: "Não foi possível iniciar o download",
downloadConflict: "Retome este download pelo Hub",
downloadBusy: "Download já em andamento",
+ pin: "Fixar no menu RAG",
+ unpin: "Desafixar do menu RAG",
+ menuChip: "Modelo",
+ moreModels: "Mais modelos",
+ pinMoreModels: "Fixar mais modelos",
+ defaultTag: "Padrão",
+ localModel: "Modelo local",
+ switched: "Modelo de embedding definido como {model}",
+ switchedNeedsDownload: "{model} ainda não foi baixado",
+ switchedNeedsDownloadDescription: "Baixe-o nas Configurações antes de indexar novos arquivos.",
+ switchedUncheckedDescription: "Não foi possível verificar se está baixado. Confira nas configurações antes de indexar novos arquivos.",
+ openSettings: "Abrir configurações",
+ switchFailed: "Não foi possível trocar o modelo de embedding",
+ back: "Voltar às fontes",
+ menuSubtitle: "Para busca em arquivos",
},
storage: {
sectionTitle: "Armazenamento",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index a5c1fce8c58..a99141efd09 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1649,6 +1649,7 @@ export const ru = {
rag: {
sectionTitle: "Документы и RAG",
embeddingModel: "Модель эмбеддингов",
+ embeddingModelShort: "Превращает документы в векторы, чтобы чат мог по ним искать.",
embeddingModelDescription:
"Модель Hugging Face или локальный путь для индексации и поиска по вашим документам. По умолчанию {defaultModel}.",
searchPlaceholder: "Поиск любой модели на HF",
@@ -1665,8 +1666,14 @@ export const ru = {
checking: "Проверка…",
noResults: "Модели эмбеддингов не найдены",
download: "Скачать",
- unload: "Выгрузить",
- unloadFailed: "Не удалось выгрузить модель эмбеддингов",
+ unload: "Извлечь",
+ unloadFailed: "Не удалось извлечь модель эмбеддингов",
+ ejected: "Модель эмбеддингов извлечена",
+ ejectModel: "Извлечь модель",
+ onDeviceHint: "Скачана на этот компьютер. Загружается в память только при индексации или поиске документов, поэтому до тех пор не занимает RAM или VRAM.",
+ loadedHint: "Сейчас в памяти и занимает RAM или VRAM. Наведите на выбор модели и нажмите красный значок, чтобы извлечь её.",
+ notLoaded: "Не загружена",
+ notLoadedHint: "Сейчас не в памяти. Загрузится сама при следующей индексации или поиске документов, после чего её можно извлечь в выборе модели.",
downloadingStatus: "Загрузка…",
notDownloaded: "Не загружено",
notDownloadedSized: "Не загружено · {size}",
@@ -1677,6 +1684,21 @@ export const ru = {
downloadFailed: "Не удалось начать загрузку",
downloadConflict: "Возобновите эту загрузку в Hub",
downloadBusy: "Загрузка уже выполняется",
+ pin: "Закрепить в меню RAG",
+ unpin: "Открепить из меню RAG",
+ menuChip: "Модель",
+ moreModels: "Другие модели",
+ pinMoreModels: "Закрепить другие модели",
+ defaultTag: "По умолчанию",
+ localModel: "Локальная модель",
+ switched: "Модель эмбеддингов: {model}",
+ switchedNeedsDownload: "{model} ещё не загружена",
+ switchedNeedsDownloadDescription: "Загрузите её в настройках, прежде чем индексировать новые файлы.",
+ switchedUncheckedDescription: "Не удалось проверить, скачана ли модель. Проверьте в настройках перед индексацией новых файлов.",
+ openSettings: "Открыть настройки",
+ switchFailed: "Не удалось сменить модель эмбеддингов",
+ back: "Назад к источникам",
+ menuSubtitle: "Для поиска по файлам",
},
storage: {
sectionTitle: "Хранилище",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 66ba105da1a..62343e2ad86 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -1815,6 +1815,7 @@ export const sv = {
rag: {
sectionTitle: "Dokument och RAG",
embeddingModel: "Inbäddningsmodell",
+ embeddingModelShort: "Gör om dina dokument till vektorer så att chatten kan söka i dem.",
embeddingModelDescription:
"Hugging Face-modell eller lokal sökväg som används för att indexera och söka i dina dokument. Standard är {defaultModel}.",
searchPlaceholder: "Sök efter valfri modell på HF",
@@ -1832,8 +1833,14 @@ export const sv = {
checking: "Kontrollerar …",
noResults: "Inga inbäddningsmodeller hittades",
download: "Hämta",
- unload: "Avlasta",
- unloadFailed: "Det gick inte att avlasta inbäddningsmodellen",
+ unload: "Mata ut",
+ unloadFailed: "Det gick inte att mata ut inbäddningsmodellen",
+ ejected: "Inbäddningsmodellen har matats ut",
+ ejectModel: "Mata ut modell",
+ onDeviceHint: "Nedladdad till den här datorn. Den laddas bara in i minnet när dokument indexeras eller söks, så den använder inget RAM eller VRAM förrän dess.",
+ loadedHint: "I minnet nu och använder RAM eller VRAM. Hovra över modellväljaren och klicka på den röda ikonen för att mata ut den.",
+ notLoaded: "Inte laddad",
+ notLoadedHint: "Inte i minnet just nu. Den laddas av sig själv nästa gång dokument indexeras eller söks, sedan kan du mata ut den i väljaren.",
downloadingStatus: "Hämtar …",
notDownloaded: "Inte hämtad",
notDownloadedSized: "Inte hämtad · {size}",
@@ -1844,6 +1851,21 @@ export const sv = {
downloadFailed: "Det gick inte att starta hämtningen",
downloadConflict: "Återuppta denna hämtning från Hubben",
downloadBusy: "En hämtning pågår redan",
+ pin: "Fäst i RAG-menyn",
+ unpin: "Lossa från RAG-menyn",
+ menuChip: "Modell",
+ moreModels: "Fler modeller",
+ pinMoreModels: "Fäst fler modeller",
+ defaultTag: "Standard",
+ localModel: "Lokal modell",
+ switched: "Inbäddningsmodellen är nu {model}",
+ switchedNeedsDownload: "{model} är inte nedladdad än",
+ switchedNeedsDownloadDescription: "Ladda ned den i Inställningar innan nya filer indexeras.",
+ switchedUncheckedDescription: "Kunde inte kontrollera om den är nedladdad. Kontrollera i inställningarna innan du indexerar nya filer.",
+ openSettings: "Öppna inställningar",
+ switchFailed: "Kunde inte byta inbäddningsmodell",
+ back: "Tillbaka till källor",
+ menuSubtitle: "Används för filsökning",
},
storage: {
sectionTitle: "Lagring",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 933c9057b50..3d474e824cc 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1623,6 +1623,7 @@ export const zhCN = {
rag: {
sectionTitle: "文档与 RAG",
embeddingModel: "Embedding 模型",
+ embeddingModelShort: "将文档转换为向量,以便聊天时检索。",
embeddingModelDescription:
"用于为文档建立索引和搜索的 Hugging Face 模型或本地路径。默认值为 {defaultModel}。",
searchPlaceholder: "搜索 HF 上的任意模型",
@@ -1639,8 +1640,14 @@ export const zhCN = {
checking: "检查中…",
noResults: "未找到 embedding 模型",
download: "下载",
- unload: "卸载",
- unloadFailed: "无法卸载 embedding 模型",
+ unload: "弹出",
+ unloadFailed: "无法弹出 embedding 模型",
+ ejected: "已弹出 embedding 模型",
+ ejectModel: "弹出模型",
+ onDeviceHint: "已下载到这台电脑。只有在索引或搜索文档时才会加载到内存,在此之前不占用 RAM 或 VRAM。",
+ loadedHint: "当前在内存中,占用 RAM 或 VRAM。将鼠标悬停在模型选择器上并点击红色图标即可弹出。",
+ notLoaded: "未加载",
+ notLoadedHint: "当前不在内存中。下次索引或搜索文档时会自动加载,之后可在选择器中弹出。",
downloadingStatus: "正在下载…",
notDownloaded: "未下载",
notDownloadedSized: "未下载 · {size}",
@@ -1650,6 +1657,21 @@ export const zhCN = {
downloadFailed: "无法开始下载",
downloadConflict: "请在 Hub 中继续此下载",
downloadBusy: "下载已在进行中",
+ pin: "固定到 RAG 菜单",
+ unpin: "从 RAG 菜单取消固定",
+ menuChip: "模型",
+ moreModels: "更多模型",
+ pinMoreModels: "固定更多模型",
+ defaultTag: "默认",
+ localModel: "本地模型",
+ switched: "嵌入模型已设为 {model}",
+ switchedNeedsDownload: "{model} 尚未下载",
+ switchedNeedsDownloadDescription: "请先在设置中下载,再为新文件建立索引。",
+ switchedUncheckedDescription: "无法确认是否已下载。索引新文件前请在设置中查看。",
+ openSettings: "打开设置",
+ switchFailed: "无法切换嵌入模型",
+ back: "返回来源",
+ menuSubtitle: "用于文件搜索",
},
storage: {
sectionTitle: "存储",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index c3290dd42cf..8ec90c6758a 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -4056,11 +4056,19 @@ html[data-chat-font] .aui-root {
height: var(--ui-icon-size) !important;
}
- /* "Sandbox High ›" chip: pill on hover or while open, same wash as menu rows. */
- .sandbox-level-chip:is(:hover, :focus-visible, [data-highlighted], [data-state="open"]) {
+ /* Menu heading chips ("Sandbox High ›", "Embedding … ›"): pill on hover or while open. */
+ .menu-heading-chip:is(:hover, :focus-visible, [data-highlighted], [data-state="open"]) {
background-color: rgb(0 0 0 / calc(0.06 * var(--contrast-wash-gain, 1)));
}
- .dark .sandbox-level-chip:is(:hover, :focus-visible, [data-highlighted], [data-state="open"]) {
+ .dark .menu-heading-chip:is(:hover, :focus-visible, [data-highlighted], [data-state="open"]) {
+ background-color: rgb(255 255 255 / calc(0.1 * var(--contrast-wash-gain, 1)));
+ }
+
+ /* A row whose action is its own menu item (RAG pins): keep the row lit while the action is. */
+ .unsloth-plus-menu .menu-row-with-action:has([data-row-action]:is(:hover, [data-highlighted])) > :is([data-slot="dropdown-menu-item"], [data-slot="context-menu-item"]) {
+ background-color: rgb(0 0 0 / calc(0.06 * var(--contrast-wash-gain, 1)));
+ }
+ .dark .unsloth-plus-menu .menu-row-with-action:has([data-row-action]:is(:hover, [data-highlighted])) > :is([data-slot="dropdown-menu-item"], [data-slot="context-menu-item"]) {
background-color: rgb(255 255 255 / calc(0.1 * var(--contrast-wash-gain, 1)));
}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pins-mirror.ts b/studio/frontend/src/lib/pins-mirror.ts
similarity index 92%
rename from studio/frontend/src/features/model-picker/components/model-selector/pins-mirror.ts
rename to studio/frontend/src/lib/pins-mirror.ts
index bdcd3e46d71..8e032e2a17e 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pins-mirror.ts
+++ b/studio/frontend/src/lib/pins-mirror.ts
@@ -1,14 +1,16 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-// Mirrors picker pins to the account's studio.db: an account switch clears "unsloth*" localStorage keys.
+// Mirrors model pins (chat picker and RAG embedding) to the account's studio.db: an account switch
+// clears "unsloth*" localStorage keys.
-export type PinList = "pinned" | "connected";
+export type PinList = "pinned" | "connected" | "embedding";
const URL = "/api/settings/pinned-models";
const STORAGE_KEYS: Record<PinList, string> = {
pinned: "unsloth_pinned_models",
connected: "unsloth_pinned_connected_models",
+ embedding: "unsloth_embedding_pins",
};
const restorers: Partial<Record<PinList, () => void>> = {};
diff --git a/studio/frontend/tests/embedding-model-picker.test.ts b/studio/frontend/tests/embedding-model-picker.test.ts
index a0db3debe2d..e10369267a7 100644
--- a/studio/frontend/tests/embedding-model-picker.test.ts
+++ b/studio/frontend/tests/embedding-model-picker.test.ts
@@ -133,8 +133,8 @@ test("the action slot offers Download or Unload, not Reset to default", () => {
!SECTION.includes("resetEmbeddingModelSettings"),
"reset is reachable by picking the default in the list",
);
- assert.match(SECTION, /settings\.general\.rag\.unload/);
- assert.match(SECTION, /embeddingModel\?\.backendLoaded \? \(/);
+ assert.match(SECTION, /settings\.general\.rag\.unloadFailed/);
+ assert.match(SECTION, /onEject=\{embeddingModel\?\.backendLoaded \? \(\) => void unload\(\) : undefined\}/);
assert.ok(
!SECTION.includes("): embeddingModel?.loaded ? ("),
"Unload is not an alternative to Download",
@@ -298,7 +298,7 @@ test("the configured default stays reachable when the listing drops it", () => {
// The empty query is scoped to `unsloth`, so a private, other-owner or local default has no row.
assert.match(PICKER, /rows\.push\(\{ id: fallback, sizeBytes: null \}\)/);
assert.match(PICKER, /const fallback = defaultModel\?\.trim\(\)/);
- assert.match(PICKER, /\}, \[results, value, defaultModel\]\)/);
+ assert.match(PICKER, /\}, \[results, value, defaultModel, pinnedModels\]\)/);
assert.match(SECTION, /defaultModel=\{embeddingModel\?\.defaultEmbeddingModel\}/);
});
diff --git a/studio/frontend/tests/knowledge-base-composer-refresh.test.ts b/studio/frontend/tests/knowledge-base-composer-refresh.test.ts
index f04dd14a970..aeace3c5194 100644
--- a/studio/frontend/tests/knowledge-base-composer-refresh.test.ts
+++ b/studio/frontend/tests/knowledge-base-composer-refresh.test.ts
@@ -64,6 +64,10 @@ function harness() {
slots[index] = deps;
effects.push(effect);
},
+ // Focus-only; nothing to run here.
+ useLayoutEffect() {
+ cursor++;
+ },
},
"react/jsx-runtime": stubJsxRuntime(),
"lucide-react": {},
@@ -87,6 +91,11 @@ function harness() {
},
},
"./knowledge-base-dialog": { KnowledgeBaseDialog: "KnowledgeBaseDialog" },
+ "./embedding-model-menu-picker": {
+ EmbeddingModelMenuChip: "EmbeddingModelMenuChip",
+ EmbeddingModelMenuList: "EmbeddingModelMenuList",
+ },
+ "@/features/auth": { useIsAccountOwner: () => true },
},
);
function render() {
diff --git a/studio/frontend/tests/permission-mode-learn-more.test.ts b/studio/frontend/tests/permission-mode-learn-more.test.ts
index d2284d1df96..6cb2a5fceae 100644
--- a/studio/frontend/tests/permission-mode-learn-more.test.ts
+++ b/studio/frontend/tests/permission-mode-learn-more.test.ts
@@ -63,7 +63,7 @@ test("the menu heading carries a Sandbox chip that opens the level picker, Learn
assert.match(label, /settings\.general\.permissions\.sectionTitle/);
// "Sandbox High ›": a submenu trigger, not a switch.
assert.match(label, /<DropdownMenuPrimitive\.SubTrigger/);
- assert.match(label, /className="sandbox-level-chip\b/);
+ assert.match(label, /className="menu-heading-chip\b/);
// Click to open: hover must not open the picker.
assert.match(label, /onPointerMove=\{\(event\) => event\.preventDefault\(\)\}/);
// Controlled: stays open until a click outside the picker, the chip, or ArrowLeft.
diff --git a/studio/frontend/tests/pinned-models-server-mirror.test.ts b/studio/frontend/tests/pinned-models-server-mirror.test.ts
index 1c01d4ac83e..e0e75c12316 100644
--- a/studio/frontend/tests/pinned-models-server-mirror.test.ts
+++ b/studio/frontend/tests/pinned-models-server-mirror.test.ts
@@ -14,7 +14,7 @@ const { store } = installLocalStorageFake();
const { hydratePins, pinsMirrorSettledForTests, resetPinsMirrorForTests } =
await import(
- "../src/features/model-picker/components/model-selector/pins-mirror.ts"
+ "../src/lib/pins-mirror.ts"
);
const { usePinnedModelsStore } = await import(
"../src/features/model-picker/components/model-selector/pinned-models.ts"
@@ -22,12 +22,21 @@ const { usePinnedModelsStore } = await import(
const { usePinnedConnectedModelsStore } = await import(
"../src/features/model-picker/components/model-selector/pinned-connected-models.ts"
);
+const { useEmbeddingPinsStore } = await import(
+ "../src/features/settings/stores/embedding-pins-store.ts"
+);
const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");
const PINNED = "unsloth_pinned_models";
const CONNECTED = "unsloth_pinned_connected_models";
-type Server = { pinned: string[] | null; connected: string[] | null };
+const EMBEDDING = "unsloth_embedding_pins";
+
+type Server = {
+ pinned: string[] | null;
+ connected: string[] | null;
+ embedding?: string[] | null;
+};
function serve(server: Server): { puts: Record<string, unknown>[] } {
const puts: Record<string, unknown>[] = [];
@@ -47,6 +56,7 @@ function reset(): void {
resetPinsMirrorForTests();
usePinnedModelsStore.setState({ pinned: [] });
usePinnedConnectedModelsStore.setState({ pinned: [] });
+ useEmbeddingPinsStore.setState({ pinned: [] });
}
// Sends await a dynamic import, so a fixed number of ticks does not drain them on every platform.
@@ -125,3 +135,14 @@ test("a failed read leaves the browser alone and sends nothing", async () => {
assert.equal(store.get(PINNED), JSON.stringify(["org/b", "org/local"]));
setAuthFetchHandler(null);
});
+
+test("RAG embedding pins come back after an account switch and mirror every edit", async () => {
+ reset();
+ const { puts } = serve({ pinned: null, connected: null, embedding: ["unsloth/bge-m3"] });
+ await hydratePins();
+ assert.deepEqual(useEmbeddingPinsStore.getState().pinned, ["unsloth/bge-m3"]);
+ assert.equal(store.get(EMBEDDING), JSON.stringify(["unsloth/bge-m3"]));
+ useEmbeddingPinsStore.getState().togglePin("unsloth/embeddinggemma-2");
+ await settle();
+ assert.deepEqual(puts, [{ embedding: ["unsloth/bge-m3", "unsloth/embeddinggemma-2"] }]);
+});
diff --git a/studio/frontend/tests/rag-embedding-picker.test.ts b/studio/frontend/tests/rag-embedding-picker.test.ts
new file mode 100644
index 00000000000..8d64d8cafe8
--- /dev/null
+++ b/studio/frontend/tests/rag-embedding-picker.test.ts
@@ -0,0 +1,314 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { embeddingMenuModels } from "../src/features/rag/lib/embedding-menu-models.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+function read(path: string): string {
+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf-8");
+}
+
+const MENU_PICKER = read("../src/features/rag/components/embedding-model-menu-picker.tsx");
+const KB_BUTTON = read("../src/features/rag/components/knowledge-base-composer-button.tsx");
+const SECTION = read("../src/features/settings/components/documents-rag-section.tsx");
+const PICKER = read("../src/features/settings/components/embedding-model-picker.tsx");
+
+type Plan = {
+ embeddingModel: string;
+ backend: "llama" | "sentence-transformers";
+ downloadRepo: string | null;
+ cached: boolean;
+ error: string | null;
+};
+
+function switcher(options: { plan?: Plan | Error; current?: boolean; saveError?: Error }) {
+ const saves: Array<{ model: string; ggufRepo: unknown; backend: unknown }> = [];
+ const store = {
+ beginSave: () => 1,
+ isSaveCurrent: () => options.current ?? true,
+ save: async (request: () => Promise<unknown>) => {
+ await request();
+ return true;
+ },
+ };
+ const mod = loadWithStubs<{
+ switchEmbeddingModel: (model: string, token?: string) => Promise<unknown>;
+ embeddingModelName: (model: string) => string;
+ embeddingModelOwner: (model: string) => string;
+ }>(new URL("../src/features/settings/lib/switch-embedding-model.ts", import.meta.url), {
+ "../api/embedding-model": {
+ resolveEmbeddingModel: async () => {
+ if (options.plan instanceof Error) throw options.plan;
+ return options.plan;
+ },
+ updateEmbeddingModelSettings: async (
+ model: string,
+ opts: { ggufRepo: unknown; backend: unknown },
+ ) => {
+ if (options.saveError) throw options.saveError;
+ saves.push({ model, ggufRepo: opts.ggufRepo, backend: opts.backend });
+ return {};
+ },
+ },
+ "../stores/embedding-model-store": {
+ useEmbeddingModelStore: { getState: () => store },
+ },
+ });
+ return { ...mod, saves };
+}
+
+const PLAN: Plan = {
+ embeddingModel: "unsloth/embeddinggemma-2",
+ backend: "llama",
+ downloadRepo: "unsloth/embeddinggemma-2-GGUF",
+ cached: true,
+ error: null,
+};
+
+test("switching saves the GGUF repo the resolve picked", async () => {
+ const app = switcher({ plan: PLAN });
+ assert.deepEqual(await app.switchEmbeddingModel(PLAN.embeddingModel), {
+ status: "saved",
+ needsDownload: false,
+ });
+ assert.deepEqual(app.saves, [
+ { model: PLAN.embeddingModel, ggufRepo: "unsloth/embeddinggemma-2-GGUF", backend: "llama" },
+ ]);
+});
+
+test("a model not on disk saves and says it needs a download", async () => {
+ const app = switcher({ plan: { ...PLAN, cached: false } });
+ assert.deepEqual(await app.switchEmbeddingModel(PLAN.embeddingModel), {
+ status: "saved",
+ needsDownload: true,
+ });
+});
+
+test("a resolve error is reported and nothing is saved", async () => {
+ const app = switcher({ plan: { ...PLAN, error: "Not an embedding model" } });
+ assert.deepEqual(await app.switchEmbeddingModel(PLAN.embeddingModel), {
+ status: "failed",
+ message: "Not an embedding model",
+ });
+ assert.equal(app.saves.length, 0);
+});
+
+test("a newer pick from another surface wins", async () => {
+ const app = switcher({ plan: PLAN, current: false });
+ assert.deepEqual(await app.switchEmbeddingModel(PLAN.embeddingModel), { status: "superseded" });
+ assert.equal(app.saves.length, 0);
+});
+
+test("a failed resolve still saves, and a failed save is reported", async () => {
+ const resolveDown = switcher({ plan: new Error("offline") });
+ // Unknown, not ready: the menu points to Settings instead of claiming success.
+ assert.deepEqual(await resolveDown.switchEmbeddingModel("acme/embed"), {
+ status: "saved",
+ needsDownload: null,
+ });
+ assert.deepEqual(resolveDown.saves, [{ model: "acme/embed", ggufRepo: null, backend: null }]);
+ const saveDown = switcher({ plan: PLAN, saveError: new Error("Could not verify") });
+ assert.deepEqual(await saveDown.switchEmbeddingModel(PLAN.embeddingModel), {
+ status: "failed",
+ message: "Could not verify",
+ });
+});
+
+test("model names and owners read from repo ids and local paths", () => {
+ const { embeddingModelName, embeddingModelOwner } = switcher({});
+ assert.equal(embeddingModelName("unsloth/bge-small-en-v1.5"), "bge-small-en-v1.5");
+ assert.equal(embeddingModelName("/models/my-embedder/"), "my-embedder");
+ assert.equal(embeddingModelName("bge-small"), "bge-small");
+ assert.equal(embeddingModelOwner("unsloth/bge-small-en-v1.5"), "unsloth");
+ assert.equal(embeddingModelOwner("/models/my-embedder"), "");
+ assert.equal(embeddingModelOwner("./my-embedder"), "");
+ assert.equal(embeddingModelOwner("~/models/e"), "");
+ assert.equal(embeddingModelOwner("C:\\models\\e"), "");
+ // Slashless names load from sentence-transformers/, not from disk.
+ assert.equal(embeddingModelOwner("all-MiniLM-L6-v2"), "sentence-transformers");
+});
+
+test("the menu lists current, default, then pinned models, each once", () => {
+ assert.deepEqual(
+ embeddingMenuModels("acme/a", "unsloth/b", ["acme/a", "acme/c", "unsloth/b", " "]),
+ ["acme/a", "unsloth/b", "acme/c"],
+ );
+});
+
+test("the chip shows for the owner only and swaps the menu to the model list", () => {
+ assert.match(KB_BUTTON, /\{isOwner \? <EmbeddingModelMenuChip onOpen=\{\(\) => setView\("embedding"\)\} \/> : null\}/);
+ assert.match(KB_BUTTON, /isOwner && view === "embedding" \? \(\s*<EmbeddingModelMenuList onBack=\{\(\) => setView\("source"\)\} \/>/);
+ // Closing resets it, so the menu reopens on the source list.
+ assert.match(KB_BUTTON, /else setView\("source"\);/);
+ // No side submenu any more.
+ assert.doesNotMatch(MENU_PICKER, /DropdownMenuPrimitive\.Sub\b|SubContent/);
+});
+
+test("More models and the download toasts open the embedding row in Settings", () => {
+ const opens = MENU_PICKER.match(
+ /openSettings\("general", \{ scrollTarget: "general-rag-embedding" \}\)/g,
+ );
+ assert.equal(opens?.length, 4);
+ assert.match(SECTION, /if \(scrollTarget !== "general-rag-embedding"\) return;/);
+ assert.match(SECTION, /<SettingsSection ref=\{sectionRef\}/);
+});
+
+test("Settings rows pin and unpin, and pinned models stay listed", () => {
+ assert.match(PICKER, /onClick=\{\(\) => onTogglePin\(item\.id\)\}/);
+ assert.match(PICKER, /for \(const pin of pinnedModels \?\? \[\]\)/);
+ assert.match(SECTION, /pinnedModels=\{pinnedModels\}\s*onTogglePin=\{togglePin\}/);
+});
+
+test("pins are grey with the Recents unpin glyph, and tooltips are the app's own", () => {
+ for (const source of [MENU_PICKER, PICKER]) {
+ assert.match(source, /icon=\{(isPinned|pinned) \? PinOffIcon : PinIcon\}/);
+ assert.doesNotMatch(source, /text-primary hover:text-primary|\? "text-primary"/);
+ assert.doesNotMatch(source, /title=\{/);
+ assert.match(source, /<TooltipContent side="top">/);
+ }
+});
+
+test("in the composer list the pin shows on row hover only, pinned or not", () => {
+ assert.match(MENU_PICKER, /text-muted-foreground opacity-0 outline-hidden transition-colors group-hover\/row:opacity-100/);
+ assert.doesNotMatch(MENU_PICKER, /!isPinned &&/);
+});
+
+test("Settings keeps the long text in the info hint and the status on the row", () => {
+ assert.match(SECTION, /hint=\{`\$\{t\("settings\.general\.rag\.embeddingModelDescription"/);
+ assert.match(SECTION, /settings\.general\.rag\.embeddingModelShort[\s\S]*?\{statusText \? \(/);
+ // The row's `below` slot carries errors only.
+ assert.match(SECTION, /below=\{\s*embeddingModelError \?/);
+});
+
+test("Eject sits on the picker and in the RAG menu, only while a model is resident", () => {
+ assert.match(SECTION, /onEject=\{embeddingModel\?\.backendLoaded \?/);
+ assert.match(PICKER, /\{onEject \? \([\s\S]*?onEject\(\);[\s\S]*?group-hover\/trigger:block/);
+ assert.match(MENU_PICKER, /\{settings\.backendLoaded \? \([\s\S]*?void eject\(/);
+ assert.match(MENU_PICKER, /settings\.general\.rag\.ejectModel/);
+});
+
+test("On device explains itself and says when the model is not loaded", () => {
+ assert.match(SECTION, /settings\.general\.rag\.onDeviceHint/);
+ assert.match(SECTION, /const notLoaded = onDevice && !embeddingModel\?\.loaded && !downloading;/);
+ // In the picker's column, a filled dot, with its own hint.
+ assert.match(SECTION, /<EmbeddingModelPicker[\s\S]*?\{notLoaded \? \([\s\S]*?rounded-full bg-muted-foreground[\s\S]*?settings\.general\.rag\.notLoadedHint/);
+});
+
+test("ejecting frees the model through the shared residency path", async () => {
+ const calls: unknown[] = [];
+ const unload = async () => ({ loaded: false });
+ const mod = loadWithStubs<{ ejectEmbeddingModel: () => Promise<void> }>(
+ new URL("../src/features/settings/lib/switch-embedding-model.ts", import.meta.url),
+ {
+ "../api/embedding-model": {
+ resolveEmbeddingModel: async () => null,
+ unloadEmbeddingModel: unload,
+ updateEmbeddingModelSettings: async () => null,
+ },
+ "../stores/embedding-model-store": {
+ useEmbeddingModelStore: {
+ getState: () => ({ applyResidency: async (request: unknown) => calls.push(request) }),
+ },
+ },
+ },
+ );
+ await mod.ejectEmbeddingModel();
+ assert.deepEqual(calls, [unload]);
+});
+
+test("an unchecked switch points to Settings rather than reading as ready", () => {
+ assert.match(
+ MENU_PICKER,
+ /result\.needsDownload === null\)[\s\S]*?switchedUncheckedDescription[\s\S]*?scrollTarget: "general-rag-embedding"/,
+ );
+});
+
+test("Settings keeps a focusable Eject in the picker list", () => {
+ assert.match(PICKER, /\{onEject \? \(\s*<div className="border-t[\s\S]*?<button\s+type="button"[\s\S]*?onEject\(\);[\s\S]*?settings\.general\.rag\.ejectModel/);
+});
+
+test("embedding pins are account data, like chat model pins, so Reset all leaves them", () => {
+ const general = read("../src/features/settings/tabs/general-tab.tsx");
+ const keys = general.slice(general.indexOf("const PREFS_KEYS"), general.indexOf("];", general.indexOf("const PREFS_KEYS")));
+ assert.doesNotMatch(keys, /EMBEDDING_PINS_STORAGE_KEY|unsloth_embedding_pins|unsloth_pinned_models/);
+});
+
+test("composer pins are their own menu items, so the keyboard reaches them", () => {
+ assert.match(
+ MENU_PICKER,
+ /<DropdownMenuPrimitive\.CheckboxItem\s+checked=\{isPinned\}[\s\S]*?data-row-action=\{true\}[\s\S]*?togglePin\(model\);/,
+ );
+ assert.doesNotMatch(MENU_PICKER, /tabIndex=\{-1\}/);
+ assert.match(read("../src/index.css"), /\.menu-row-with-action:has\(\[data-row-action\]:is\(:hover, \[data-highlighted\]\)\)/);
+});
+
+test("pins show without hover on touch screens", () => {
+ assert.match(PICKER, /"opacity-0 group-hover\/row:opacity-100 \[@media\(hover:none\)\]:opacity-100"/);
+ assert.match(MENU_PICKER, /group-has-\[\[data-highlighted\]\]\/row:opacity-100 \[@media\(hover:none\)\]:opacity-100/);
+});
+
+test("the embedding controls wrap and fit narrow settings panels", () => {
+ assert.match(SECTION, /flex max-w-full flex-wrap items-start justify-end gap-2/);
+ assert.match(SECTION, /w-\[calc\(260px\*var\(--ui-space-scale,1\)\)\] max-w-full/);
+});
+
+test("swapping menu views moves focus into the new view", () => {
+ assert.match(
+ KB_BUTTON,
+ /useLayoutEffect\(\(\) => \{\s*if \(shownViewRef\.current === view\) return;[\s\S]*?querySelector<HTMLElement>\('\[role\^="menuitem"\]:not\(\[data-disabled\]\)'\)\s*\?\.focus\(\);\s*\}, \[view\]\);/,
+ );
+ assert.match(KB_BUTTON, /<DropdownMenuContent\s+ref=\{contentRef\}/);
+});
+
+test("unpinning a row that leaves the list hands focus to a neighbour row", () => {
+ assert.match(MENU_PICKER, /const leaving =\s*isPinned && model !== current && model !== settings\.defaultEmbeddingModel;/);
+ assert.match(MENU_PICKER, /togglePin\(model\);\s*if \(neighbour\) requestAnimationFrame\(\(\) => neighbour\.focus\(\)\);/);
+ assert.match(MENU_PICKER, /function neighbourRowItem\(el: HTMLElement\)/);
+});
+
+test("a switch that lands after the list unmounted does not change the menu view", () => {
+ assert.match(MENU_PICKER, /if \(mountedRef\.current\) onBack\(\);/);
+ assert.match(MENU_PICKER, /return \(\) => \{\s*mountedRef\.current = false;\s*\};/);
+});
+
+test("only the model rows scroll; the header and Eject stay put", () => {
+ assert.match(MENU_PICKER, /<div className="flex shrink-0 items-start[\s\S]*?ref=\{listRef\}\s*className="min-h-0 flex-1 overflow-y-auto/);
+ assert.match(MENU_PICKER, /<\/div>\s*\{settings\.backendLoaded \? \(\s*<div className="shrink-0">/);
+});
+
+test("the list header is a page header: its own back button, then a titled page", () => {
+ // Back is a separate round button labelled with where it goes, not an arrow on the title.
+ // Wash on hover or focus only, no resting circle.
+ assert.match(MENU_PICKER, /aria-label=\{t\("settings\.general\.rag\.back"\)\}[\s\S]*?rounded-full text-muted-foreground[^"]*hover:bg-\[/);
+ // Title matches the More models link size.
+ assert.match(MENU_PICKER, /truncate text-ui-12 font-medium leading-tight text-foreground/);
+ assert.match(
+ MENU_PICKER,
+ /t\("settings\.general\.rag\.embeddingModel"\)[\s\S]*?t\("settings\.general\.rag\.menuSubtitle"\)/,
+ );
+ assert.doesNotMatch(MENU_PICKER, /menuTitle|DropdownMenuLabel/);
+});
+
+test("ejecting from the menu moves focus to a model row", () => {
+ assert.match(MENU_PICKER, /void eject\(\(event\.currentTarget as HTMLElement\)\.closest\('\[role="menu"\]'\)\)/);
+ assert.match(MENU_PICKER, /menu\?\.querySelector<HTMLElement>\('\.menu-row-with-action \[role\^="menuitem"\]'\)\?\.focus\(\)/);
+});
+
+test("embedding pins mirror to the account like the chat model pins", () => {
+ const store = read("../src/features/settings/stores/embedding-pins-store.ts");
+ assert.match(store, /mirrorPins\("embedding", pinned\)/);
+ assert.match(store, /onPinsRestored\("embedding"/);
+ assert.match(read("../src/lib/pins-mirror.ts"), /embedding: "unsloth_embedding_pins"/);
+});
+
+test("with nothing pinned, a Pin more models link opens the Settings embedding row", () => {
+ assert.match(
+ MENU_PICKER,
+ /\{pinned\.length === 0 \? \(\s*<DropdownMenuPrimitive\.Item[\s\S]*?scrollTarget: "general-rag-embedding"[\s\S]*?settings\.general\.rag\.pinMoreModels/,
+ );
+});