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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: search chats, projects, files and models from tabs in chat search (#12564)
Michael Hanf388286cf747
diff --git a/studio/frontend/src/features/chat/components/chat-search-dialog.tsx b/studio/frontend/src/features/chat/components/chat-search-dialog.tsxindex f7c9f5665e6..851c7bc4d05 100644--- a/studio/frontend/src/features/chat/components/chat-search-dialog.tsx+++ b/studio/frontend/src/features/chat/components/chat-search-dialog.tsx@@ -8,34 +8,84 @@ import {CommandGroup,CommandList,} from "@/components/ui/command";-import { useShortcut } from "@/features/settings/hooks/use-shortcut";-import { MessageCircleIcon } from "@/lib/hugeicons-derived";+import {+ type ShortcutId,+ isImeComposing,+ triggerShortcut,+ useShortcut,+ useShortcutAvailable,+ useShortcutLabel,+} from "@/features/settings";+import { type TranslationKey, useT } from "@/i18n";+import { MessageCircleIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";import { cn } from "@/lib/utils";-import { Cancel01Icon, Search01Icon } from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";+import {+ Cancel01Icon,+ DashboardCircleIcon,+ FlimSlateIcon,+ Folder01Icon,+ Image03Icon,+ PencilEdit02Icon,+ Search01Icon,+ BubbleChatTemporaryIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";import { useNavigate } from "@tanstack/react-router";import { Command as CommandPrimitive } from "cmdk";-import { useDeferredValue, useEffect, useMemo, useState } from "react";+import { Columns2Icon, GitBranchIcon, type LucideIcon } from "lucide-react";+import {+ type KeyboardEvent,+ type ReactNode,+ useCallback,+ useDeferredValue,+ useEffect,+ useMemo,+ useState,+} from "react";import {+ type CachedInventoryRow,+ type LocalInventoryRow,+ type ModelInventoryFormat,+ isHiddenModelId,+ useHubInventory,+} from "@/features/hub";+import { modelLabelKey } from "@/features/library";+import { useChatProjects } from "../hooks/use-chat-projects";+import { useChatSidebarItems } from "../hooks/use-chat-sidebar-items";+import {+ type ChatSearchItem,chatSearchIndexHasRows,useChatSearchIndex,} from "../hooks/use-chat-search-index";+import {+ type LibrarySearchEntry,+ libraryTime,+ useChatSearchSources,+} from "../hooks/use-chat-search-sources";import { useChatSearchStore } from "../stores/chat-search-store";import { isCompactChatSearchList } from "../utils/chat-search-list-height";+import {+ ALL_TAB_GROUP_LIMIT,+ CHAT_SEARCH_TABS,+ type ChatSearchKind,+ type ChatSearchRow,+ type ChatSearchTab,+ filterRows,+ haystackMatches,+ queryTokens,+ recentRows,+ stepTab,+ tabStepForKey,+} from "../utils/chat-search-tabs";// Rows mounted while the dialog animates open; the rest follow once it settles, so a long// history never lays out hundreds of rows mid-transition.const INITIAL_ROW_COUNT = 24;const FULL_ROW_REVEAL_MS = 220;-// Lowercased whitespace tokens of the query (haystacks are lowercased in the index).-function queryTokens(search: string): string[] {- return search.trim().toLowerCase().split(/\s+/).filter(Boolean);-}--function haystackMatches(haystack: string, tokens: string[]): boolean {- return tokens.every((token) => haystack.includes(token));-}+const KINDS = CHAT_SEARCH_TABS.filter(+ (tab): tab is ChatSearchKind => tab !== "all",+);// We filter rows here (cmdk runs with shouldFilter=false) to control the two-tier behavior and// avoid cmdk's fuzzy scorer keeping non-matches visible (#5572): every whitespace token must@@ -53,23 +103,94 @@ export function selectVisibleChats<return items.filter((it) => haystackMatches(it.searchText, tokens));}-function formatRelative(createdAt: number): string {- const diff = Date.now() - createdAt;+type WhenKey = "today" | "pastWeek" | "pastMonth" | "older";++function whenKey(time: number): WhenKey {+ const diff = Date.now() - time;const day = 86_400_000;- if (diff < day) return "Today";- if (diff < 7 * day) return "Past week";- if (diff < 30 * day) return "Past month";- return "Older";+ if (diff < day) return "today";+ if (diff < 7 * day) return "pastWeek";+ if (diff < 30 * day) return "pastMonth";+ return "older";}+/** Hugeicons path data, or a lucide icon (compare and fork, as in the Library). */+type RowIcon = IconSvgElement | LucideIcon;++interface Row extends ChatSearchRow {+ icon: RowIcon;+ /** Replaces the age at the row's end. */+ meta?: string;+ /** Not a runnable model (embedder, STT, probe); listed only when queried. */+ hidden?: boolean;+ open: () => void;+}++type ActionId = Extract<+ ShortcutId,+ "newChat" | "newTemporaryChat" | "switchToTrain" | "switchToImages" | "switchToVideo"+>;++interface Action {+ id: ActionId;+ icon: IconSvgElement;+ labelKey: TranslationKey;+}++// Run through the shortcut registry, like the command palette.+const ACTIONS: Action[] = [+ { id: "newChat", icon: PencilEdit02Icon, labelKey: "shell.search.newChat" },+ {+ id: "newTemporaryChat",+ icon: BubbleChatTemporaryIcon,+ labelKey: "shell.search.newTemporaryChat",+ },+ {+ id: "switchToTrain",+ icon: TestTubeOutlineIcon,+ labelKey: "shell.search.fineTune",+ },+ {+ id: "switchToImages",+ icon: Image03Icon,+ labelKey: "shell.search.generateImage",+ },+ {+ id: "switchToVideo",+ icon: FlimSlateIcon,+ labelKey: "shell.search.generateVideo",+ },+];++const NAVIGATION_KEYS = new Set(["ArrowUp", "ArrowDown", "Home", "End", "PageUp", "PageDown"]);++const ROW_CLASS =+ "relative flex cursor-pointer select-none items-center gap-3 rounded-full px-3 py-2.5 text-sm outline-hidden data-selected:bg-muted data-selected:text-foreground";+export function ChatSearchDialog() {+ const t = useT();const isOpen = useChatSearchStore((s) => s.isOpen);const setOpen = useChatSearchStore((s) => s.setOpen);const close = useChatSearchStore((s) => s.close);const opener = useChatSearchStore((s) => s.opener);const navigate = useNavigate();const { items, loading } = useChatSearchIndex(isOpen);+ // Every thread, empty ones too: the index skips those, the sidebar's project ages do not.+ const { items: threads } = useChatSidebarItems({+ enabled: isOpen,+ requireMessages: false,+ });+ const { projects, hasLoaded: projectsLoaded } = useChatProjects();+ const sources = useChatSearchSources(isOpen);+ const { cachedRows, localRows, downloadedReady } = useHubInventory({+ kind: "models",+ enabled: isOpen,+ });const [query, setQuery] = useState("");+ const [tab, setTab] = useState<ChatSearchTab>("all");+ // Pin the highlight to the first row until the user moves it: later-loading kinds can sort above it.+ const [selected, setSelected] = useState("");+ const [moved, setMoved] = useState(false);// Filtering scans every conversation's text, so keep it off the keystroke path.const deferredQuery = useDeferredValue(query);// An empty query needs no scan, and the deferred value must not hold a previous filter over a reopened dialog.@@ -80,6 +201,24 @@ export function ChatSearchDialog() {isCompactChatSearchList(true, chatSearchIndexHasRows()),);+ // One call per action (hooks cannot run in a loop). Availability can change while open, so it+ // gates the selection keys too, not just the rendered rows.+ const available: Record<ActionId, boolean> = {+ newChat: useShortcutAvailable("newChat", false),+ newTemporaryChat: useShortcutAvailable("newTemporaryChat", false),+ switchToTrain: useShortcutAvailable("switchToTrain", false),+ switchToImages: useShortcutAvailable("switchToImages", false),+ switchToVideo: useShortcutAvailable("switchToVideo", false),+ };+ // Compact only while no kind has rows: projects, Library, downloads and actions fill the list too.+ const otherRows =+ projects.length > 0 ||+ sources.files.length > 0 ||+ sources.fineTunes.length > 0 ||+ cachedRows.length > 0 ||+ localRows.length > 0 ||+ Object.values(available).some(Boolean);+// Reset in the opening render, not an effect: Radix mounts the portal as this render commits, so// an effect would trim rows only after the previous set was in the DOM. Resetting on close// instead would tear rows down inside the exit animation.@@ -88,21 +227,22 @@ export function ChatSearchDialog() {setWasOpen(isOpen);if (isOpen) {setQuery("");+ setTab("all");+ setMoved(false);+ setSelected("");setRowLimit(INITIAL_ROW_COUNT);- setCompactList(isCompactChatSearchList(true, chatSearchIndexHasRows()));+ setCompactList(+ isCompactChatSearchList(true, otherRows || chatSearchIndexHasRows()),+ );}} else if (- compactList !== isCompactChatSearchList(compactList, items.length > 0)+ compactList !==+ isCompactChatSearchList(compactList, otherRows || items.length > 0)) {// Backstop for an open with no hint at all: the fixed height is taken when the first build lands.setCompactList(false);}- const visibleItems = useMemo(- () => selectVisibleChats(items, activeQuery),- [items, activeQuery],- );-useEffect(() => {if (!isOpen) return;const timer = setTimeout(@@ -118,6 +258,168 @@ export function ChatSearchDialog() {skipInTextFields: true,});+ const go = (to: () => void) => () => {+ to();+ close();+ };++ // The labels a row shows but its text lacks, so typing them finds it.+ const chats = useMemo(() => {+ const untitled = t("shell.search.untitledChat").toLowerCase();+ const compare = t("shell.search.compare").toLowerCase();+ return items.map((item) => {+ const extra = [+ item.title ? "" : untitled,+ item.type === "compare" ? compare : "",+ ].join(" ").trim();+ return extra+ ? {+ ...item,+ userSearchText: `${item.userSearchText} ${extra}`,+ searchText: `${item.searchText} ${extra}`,+ }+ : item;+ });+ }, [items, t]);++ // Unfiltered rows per kind. Chats are matched separately (two tiers).+ const rowsByKind = useMemo<Record<Exclude<ChatSearchKind, "chats">, Row[]>>(() => {+ // As the sidebar: a project's own edits or its newest chat, whichever is later.+ const newestChat = new Map<string, number>();+ for (const thread of threads) {+ if (!thread.projectId) continue;+ newestChat.set(+ thread.projectId,+ Math.max(newestChat.get(thread.projectId) ?? 0, thread.updatedAt),+ );+ }+ const activityAt = (project: (typeof projects)[number]) =>+ Math.max(project.updatedAt ?? project.createdAt, newestChat.get(project.id) ?? 0);+ return {+ projects: projects+ .filter((project) => !project.archived)+ .map((project) => ({+ key: `project:${project.id}`,+ kind: "projects" as const,+ title: project.name,+ time: activityAt(project),+ haystack: project.name.toLowerCase(),+ icon: Folder01Icon,+ open: () =>+ navigate({ to: "/chat", search: { project: project.id } }),+ }))+ .sort((a, b) => b.time - a.time),+ files: sources.files.map((entry) => libraryRow(entry, "files", navigate)),+ // Hub downloads plus Library fine-tunes.+ models: [+ ...downloadedModelRows(cachedRows, localRows, navigate),+ ...sources.fineTunes.map((entry) => {+ const row = libraryRow(entry, "models", navigate);+ // How it was made, as the Library labels it (LoRA, GGUF export, ...).+ const label = t(modelLabelKey(entry.item) ?? "library.modelKind.model");+ return { ...row, meta: label, haystack: `${row.haystack} ${label.toLowerCase()}` };+ }),+ ].sort((a, b) => b.time - a.time),+ };+ }, [projects, threads, sources, cachedRows, localRows, navigate, t]);++ const matchAll = useCallback(+ (search: string): Record<ChatSearchKind, Row[]> => ({+ chats: selectVisibleChats(chats, search)+ .map((item) => chatRow(item, t, navigate))+ .sort((a, b) => b.time - a.time),+ projects: filterRows(rowsByKind.projects, search),+ files: filterRows(rowsByKind.files, search),+ // Infrastructure models stay out until a query names them, as in the Hub.+ models: filterRows(+ queryTokens(search).length > 0+ ? rowsByKind.models+ : rowsByKind.models.filter((row) => !row.hidden),+ search,+ ),+ }),+ [chats, rowsByKind, t, navigate],+ );+ const matched = useMemo(() => matchAll(activeQuery), [matchAll, activeQuery]);++ const hasQuery = queryTokens(activeQuery).length > 0;+ // Live query, not the deferred one: Enter must never run an action the input no longer matches.+ const visibleActions = ACTIONS.filter(+ (action) =>+ available[action.id] &&+ haystackMatches(t(action.labelKey).toLowerCase(), queryTokens(query)),+ );++ // All: one headed group per kind. A kind's tab: one list.+ const groupsFor = (+ rows: Record<ChatSearchKind, Row[]>,+ queried: boolean,+ ): { heading?: string; rows: Row[] }[] =>+ tab !== "all"+ ? [{ rows: rows[tab].slice(0, rowLimit) }]+ : queried+ ? KINDS.map((kind) => ({+ heading: t(`shell.search.tabs.${kind}`),+ rows: rows[kind].slice(0, ALL_TAB_GROUP_LIMIT),+ }))+ : [{ heading: t("shell.search.recents"), rows: recentRows(rows) }];+ const groups = groupsFor(matched, hasQuery);+ const showActions = tab === "all" && visibleActions.length > 0;+ const rowCount = groups.reduce((sum, group) => sum + group.rows.length, 0);+ const firstKey =+ groups.find((group) => group.rows.length > 0)?.rows[0].key ??+ (showActions ? `action:${visibleActions[0].id}` : "");+ const shownKeys = new Set([+ ...groups.flatMap((group) => group.rows.map((row) => row.key)),+ ...(showActions ? visibleActions.map((action) => `action:${action.id}`) : []),+ ]);++ const activate = (row: Row) => {+ // The list can trail the input by a render; only open rows the live query still matches.+ if (query === activeQuery) return go(row.open)();+ const live = matchAll(query);+ if (live[row.kind].some((match) => match.key === row.key)) return go(row.open)();+ // A stale auto-highlight: run what the caught-up list will show first.+ if (moved) return;+ const first = groupsFor(live, queryTokens(query).length > 0).find(+ (group) => group.rows.length > 0,+ )?.rows[0];+ if (first) go(first.open)();+ else if (showActions) go(() => void triggerShortcut(visibleActions[0].id))();+ };++ const switchTab = (next: ChatSearchTab) => {+ setTab(next);+ setMoved(false);+ setSelected("");+ };++ const onInputKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {+ // An arrow mid-composition moves the IME caret, not the tab.+ if (isImeComposing(event.nativeEvent)) return;+ if (event.altKey || event.metaKey || event.ctrlKey || event.shiftKey) return;+ const step = tabStepForKey(event.key, event.currentTarget);+ if (step === null) return;+ const next = stepTab(tab, step);+ if (next === tab) return;+ event.preventDefault();+ switchTab(next);+ };++ const loadingByTab: Record<ChatSearchTab, boolean> = {+ chats: loading,+ projects: !projectsLoaded,+ files: !sources.ready,+ models: !downloadedReady || !sources.ready,+ all: loading || !projectsLoaded || !sources.ready || !downloadedReady,+ };+ const sourceLoading = loadingByTab[tab];+ const emptyText = sourceLoading+ ? t("shell.search.loading")+ : hasQuery+ ? t("shell.search.noMatches")+ : t(`shell.search.empty.${tab}`);+return (<CommandDialogopen={isOpen}@@ -131,7 +433,15 @@ export function ChatSearchDialog() {className="chat-search-surface rounded-3xl! max-sm:rounded-none! top-[calc(50%+var(--studio-window-chrome-top,0px)/2)] -translate-y-1/2 w-[calc(635px*var(--ui-space-scale,1))] max-w-[calc(100%-2rem)] gap-0 p-0 ring-0 duration-[180ms] ease-[cubic-bezier(0.16,1,0.3,1)] sm:max-w-[calc(635px*var(--ui-space-scale,1))]"overlayClassName="bg-transparent supports-backdrop-filter:backdrop-blur-none">- <Command className="rounded-3xl p-0" shouldFilter={false}>+ <Command+ className="rounded-3xl p-0"+ shouldFilter={false}+ value={moved && shownKeys.has(selected) ? selected : firstKey}+ onValueChange={setSelected}+ onKeyDown={(e) => {+ if (NAVIGATION_KEYS.has(e.key)) setMoved(true);+ }}+ ><div className="flex items-center gap-3 border-b border-border/40 px-4 py-3"><HugeiconsIconicon={Search01Icon}@@ -139,18 +449,26 @@ export function ChatSearchDialog() {className="size-4 shrink-0 text-muted-foreground"/><CommandPrimitive.Input- placeholder="Search chats..."+ placeholder={t("shell.search.placeholder")}// Controlled: reopening inside the exit animation reuses the mounted tree, so cmdk would keep// the previous text while the filter state is clear.value={query}- onValueChange={setQuery}+ onValueChange={(value) => {+ setQuery(value);+ setMoved(false);+ setSelected("");+ }}+ onKeyDown={onInputKeyDown}className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"/><buttontype="button"onClick={close}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.stopPropagation();+ }}className="flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"- aria-label="Close"+ aria-label={t("common.close")}><HugeiconsIconicon={Cancel01Icon}@@ -159,72 +477,292 @@ export function ChatSearchDialog() {/></button></div>+ <div+ role="tablist"+ aria-label={t("shell.search.placeholder")}+ className="no-scrollbar flex items-center gap-1 overflow-x-auto border-b border-border/40 px-3 py-2"+ >+ {CHAT_SEARCH_TABS.map((entry) => (+ <button+ key={entry}+ type="button"+ role="tab"+ aria-selected={entry === tab}+ // Keep focus in the input.+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => switchTab(entry)}+ // cmdk's root runs the highlighted row on Enter; a focused tab must only switch.+ onKeyDown={(e) => {+ if (e.key === "Enter") e.stopPropagation();+ }}+ className={cn(+ "shrink-0 rounded-full px-3 py-1 text-ui-13 font-medium transition-colors",+ entry === tab+ ? "bg-muted text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`shell.search.tabs.${entry}`)}+ </button>+ ))}+ </div><CommandList+ onPointerMove={() => setMoved(true)}className={cn("cmd-native-scrollbar hover-scrollbar p-1",compactList ? "max-h-[calc(420px*var(--ui-space-scale,1))]" : "h-[calc(420px*var(--ui-space-scale,1))] max-h-[60dvh]",)}><CommandEmpty className="py-6 text-center text-xs text-muted-foreground">- {loading- ? "Loading…"- : items.length === 0- ? "No chats yet."- : "No chats match."}+ {emptyText}</CommandEmpty>- <CommandGroup className="p-0">- {visibleItems.slice(0, rowLimit).map((item) => (- <CommandPrimitive.Item- key={item.id}- value={item.id}- onSelect={() => {- // The list can trail the input by a render, so a row is activatable only if the live query still- // matches it. Scanned on activation, not per key.- if (- query !== activeQuery &&- !selectVisibleChats(items, query).some(- (live) => live.id === item.id,- )- ) {- return;- }- navigate({- to: "/chat",- search:- item.type === "single"- ? {- thread: item.id,- ...(item.projectId- ? { project: item.projectId }- : {}),- }- : {- compare: item.id,- ...(item.projectId- ? { project: item.projectId }- : {}),- },- });- close();- }}- className="relative flex cursor-pointer select-none items-center gap-3 rounded-full px-3 py-2.5 text-sm outline-hidden data-selected:bg-muted data-selected:text-foreground"- >- <HugeiconsIcon- icon={MessageCircleIcon}- strokeWidth={2}- className="size-4 shrink-0 text-muted-foreground"+ {groups.map(+ (group) =>+ group.rows.length > 0 && (+ <CommandGroup+ key={group.heading ?? tab}+ heading={group.heading}+ className="p-0"+ >+ {group.rows.map((row) => (+ <CommandPrimitive.Item+ key={row.key}+ value={row.key}+ onSelect={() => activate(row)}+ className={ROW_CLASS}+ >+ <RowGlyph icon={row.icon} />+ <span className="min-w-0 flex-1 truncate text-ui-13 font-medium">+ {row.title}+ </span>+ <span className="shrink-0 text-ui-11 text-muted-foreground">+ {row.meta ?? t(`shell.search.when.${whenKey(row.time)}`)}+ </span>+ </CommandPrimitive.Item>+ ))}+ </CommandGroup>+ ),+ )}+ {showActions && (+ <CommandGroup+ heading={t("shell.search.actions")}+ className={cn("p-0", rowCount > 0 && "mt-2")}+ >+ {visibleActions.map((action) => (+ <ActionItem+ key={action.id}+ action={action}+ onSelect={go(() => void triggerShortcut(action.id))}/>- <span className="min-w-0 flex-1 truncate text-ui-13 font-medium">- {item.title || "Untitled chat"}- </span>- <span className="shrink-0 text-ui-11 text-muted-foreground">- {formatRelative(item.createdAt)}- </span>- </CommandPrimitive.Item>- ))}- </CommandGroup>+ ))}+ </CommandGroup>+ )}</CommandList>+ <div className="flex items-center gap-5 border-t border-border/40 px-5 py-2.5 text-ui-11 text-muted-foreground max-sm:hidden">+ <FooterHint label={t("shell.search.footer.close")}>+ <Key>Esc</Key>+ </FooterHint>+ <FooterHint label={t("shell.search.footer.changeType")}>+ <Key>←</Key>+ <Key>→</Key>+ </FooterHint>+ <FooterHint label={t("shell.search.footer.open")}>+ <Key>↵</Key>+ </FooterHint>+ </div></Command></CommandDialog>);}++const FORMAT_LABELS: Partial<Record<ModelInventoryFormat, string>> = {+ gguf: "GGUF",+ safetensors: "Safetensors",+ checkpoint: "Safetensors",+ adapter: "Adapter",+};++/** Complete downloads only. */+function downloadedModelRows(+ cachedRows: readonly CachedInventoryRow[],+ localRows: readonly LocalInventoryRow[],+ navigate: ReturnType<typeof useNavigate>,+): Row[] {+ const open = (id: string) => () =>+ navigate({ to: "/hub", search: { tab: "downloaded", model: id } });+ // The server already hides infrastructure cache rows, but not optimistic ones.+ const cached = cachedRows+ .filter(+ (row) =>+ !row.partial &&+ !(row.optimistic && isHiddenModelId(row.id, row.repoId, row.cachePath)),+ )+ .map(+ (row): Row => ({+ key: `hub-cache:${row.id}`,+ kind: "models",+ title: row.repoId,+ time: row.lastModified ?? 0,+ haystack: [+ row.repoId,+ row.formatVariant ?? "",+ row.modelFormat,+ FORMAT_LABELS[row.modelFormat] ?? "",+ ]+ .join(" ")+ .toLowerCase(),+ icon: DashboardCircleIcon,+ meta: FORMAT_LABELS[row.modelFormat],+ open: open(row.id),+ }),+ );+ const local = localRows+ .filter((row) => !row.partial)+ .map((row): Row => {+ const title = row.displayName || row.title;+ return {+ key: `hub-local:${row.id}`,+ kind: "models",+ title,+ time: row.updatedAt ?? 0,+ haystack: [+ title,+ row.repoId ?? "",+ row.sourceLabel,+ row.path,+ row.modelFormat,+ FORMAT_LABELS[row.modelFormat] ?? "",+ ]+ .join(" ")+ .toLowerCase(),+ icon: DashboardCircleIcon,+ meta: row.sourceLabel,+ hidden: isHiddenModelId(row.id, row.repoId, row.path, row.title),+ open: open(row.id),+ };+ });+ return [...cached, ...local];+}++function chatRow(+ item: ChatSearchItem,+ t: ReturnType<typeof useT>,+ navigate: ReturnType<typeof useNavigate>,+): Row {+ return {+ key: `chat:${item.id}`,+ kind: "chats",+ title: item.title || t("shell.search.untitledChat"),+ time: item.updatedAt ?? item.createdAt,+ haystack: item.searchText,+ icon:+ item.type === "compare"+ ? Columns2Icon+ : item.isFork+ ? GitBranchIcon+ : MessageCircleIcon,+ meta: item.type === "compare" ? t("shell.search.compare") : undefined,+ open: () =>+ navigate({+ to: "/chat",+ search:+ item.type === "single"+ ? {+ thread: item.id,+ ...(item.projectId ? { project: item.projectId } : {}),+ }+ : {+ compare: item.id,+ ...(item.projectId ? { project: item.projectId } : {}),+ },+ }),+ };+}++function libraryRow(+ { item, icon }: LibrarySearchEntry,+ kind: "files" | "models",+ navigate: ReturnType<typeof useNavigate>,+): Row {+ return {+ key: `library:${item.id}`,+ kind,+ title: item.name,+ time: libraryTime(item),+ haystack: [+ item.name,+ item.fileName ?? "",+ item.threadTitle ?? "",+ item.model?.baseModel ?? "",+ ]+ .join(" ")+ .toLowerCase(),+ icon,+ open: () =>+ navigate({+ to: "/library",+ search: { show: kind === "models" ? "models" : "all", item: item.id },+ }),+ };+}++function ActionItem({+ action,+ onSelect,+}: {+ action: Action;+ onSelect: () => void;+}) {+ const t = useT();+ const label = useShortcutLabel(action.id);+ return (+ <CommandPrimitive.Item+ value={`action:${action.id}`}+ onSelect={onSelect}+ className={ROW_CLASS}+ >+ <RowGlyph icon={action.icon} />+ <span className="min-w-0 flex-1 truncate text-ui-13 font-medium">+ {t(action.labelKey)}+ </span>+ {label && (+ <span className="shrink-0 text-ui-11 text-muted-foreground">+ {label}+ </span>+ )}+ </CommandPrimitive.Item>+ );+}++const GLYPH_CLASS = "size-4 shrink-0 text-muted-foreground";++// Same stroke as the sidebar and Library.+function RowGlyph({ icon }: { icon: RowIcon }) {+ if (isHugeicon(icon)) {+ return <HugeiconsIcon icon={icon} strokeWidth={1.75} className={GLYPH_CLASS} />;+ }+ const Icon = icon;+ return <Icon strokeWidth={1.75} className={GLYPH_CLASS} />;+}++// Hugeicons glyphs are arrays; lucide glyphs are components.+function isHugeicon(icon: RowIcon): icon is IconSvgElement {+ return Array.isArray(icon);+}++function FooterHint({ label, children }: { label: string; children: ReactNode }) {+ return (+ <span className="flex items-center gap-1.5">+ {label}+ <span className="flex items-center gap-1">{children}</span>+ </span>+ );+}++function Key({ children }: { children: ReactNode }) {+ return (+ <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded-md border border-border/60 px-1 font-sans text-ui-11 text-muted-foreground">+ {children}+ </kbd>+ );+}diff --git a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts b/studio/frontend/src/features/chat/hooks/use-chat-search-index.tsindex ccba29adec0..76e2c99edae 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-search-index.ts@@ -43,7 +43,11 @@ export interface ChatSearchItem {// Prebuilt so filtering never re-lowercases per keystroke.searchText: string;createdAt: number;+ /** Last activity (`updatedAt ?? createdAt`; the latest of a compare pair), as the sidebar ranks chats. */+ updatedAt?: number;projectId?: string | null;+ /** Forked from another chat (branch icon, as in the Library). */+ isFork?: boolean;}// Messages are indexed for this many most recently updated threads; older chats match by title.@@ -160,7 +164,13 @@ export async function buildChatSearchIndex(): Promise<ChatSearchIndexBuild> {if (t.pairId) {if (seenPairs.has(t.pairId)) {const existing = itemThreadIds.get(t.pairId);- if (existing) existing.threadIds.push(t.id);+ if (existing) {+ existing.threadIds.push(t.id);+ existing.item.updatedAt = Math.max(+ existing.item.updatedAt ?? 0,+ t.updatedAt ?? t.createdAt,+ );+ }continue;}seenPairs.add(t.pairId);@@ -170,6 +180,7 @@ export async function buildChatSearchIndex(): Promise<ChatSearchIndexBuild> {id: t.pairId,title: t.title,createdAt: t.createdAt,+ updatedAt: t.updatedAt ?? t.createdAt,projectId: t.projectId ?? null,},threadIds: [t.id],@@ -181,7 +192,9 @@ export async function buildChatSearchIndex(): Promise<ChatSearchIndexBuild> {id: t.id,title: t.title,createdAt: t.createdAt,+ updatedAt: t.updatedAt ?? t.createdAt,projectId: t.projectId ?? null,+ isFork: Boolean(t.forkedFromThreadId),},threadIds: [t.id],});diff --git a/studio/frontend/src/features/chat/hooks/use-chat-search-sources.ts b/studio/frontend/src/features/chat/hooks/use-chat-search-sources.tsnew file mode 100644index 00000000000..ff27b26ff83--- /dev/null+++ b/studio/frontend/src/features/chat/hooks/use-chat-search-sources.ts@@ -0,0 +1,89 @@+// 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 { AUTH_SESSION_CLEARED_EVENT } from "@/features/auth";+import {+ KIND_ICONS,+ type LibraryItem,+ fileKind,+ isModelItem,+} from "@/features/library";+import type { IconSvgElement } from "@hugeicons/react";+import { useEffect, useState } from "react";++export interface LibrarySearchEntry {+ item: LibraryItem;+ icon: IconSvgElement;+}++export interface ChatSearchSources {+ /** The Library has loaded once, so empty lists are really empty. */+ ready: boolean;+ files: LibrarySearchEntry[];+ /** Fine-tuned models live in the Library, not the Hub. */+ fineTunes: LibrarySearchEntry[];+}++const EMPTY: ChatSearchSources = { ready: false, files: [], fineTunes: [] };++/** Library items for search. The store loads on first open, not with the app. */+export function useChatSearchSources(open: boolean): ChatSearchSources {+ const [sources, setSources] = useState<ChatSearchSources>(EMPTY);++ useEffect(() => {+ const clear = () => setSources(EMPTY);+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, clear);+ return () => window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, clear);+ }, []);++ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ let unsubscribe: (() => void) | undefined;++ import("@/features/library/store")+ .then(({ useLibraryStore }) => {+ if (cancelled) return;+ const publish = (items: LibraryItem[]) => {+ const files: LibrarySearchEntry[] = [];+ const fineTunes: LibrarySearchEntry[] = [];+ for (const item of items) {+ if (item.archived) continue;+ const entry = { item, icon: KIND_ICONS[fileKind(item)] };+ (isModelItem(item) ? fineTunes : files).push(entry);+ }+ const newest = (a: LibrarySearchEntry, b: LibrarySearchEntry) =>+ libraryTime(b.item) - libraryTime(a.item);+ setSources((prev) => ({+ ready: prev.ready || isSettled(useLibraryStore.getState().status),+ files: files.sort(newest),+ fineTunes: fineTunes.sort(newest),+ }));+ };+ publish(useLibraryStore.getState().items);+ unsubscribe = useLibraryStore.subscribe((state, prev) => {+ if (state.items !== prev.items || state.status !== prev.status) {+ publish(state.items);+ }+ });+ void useLibraryStore.getState().refresh().catch(() => {});+ })+ .catch(() => {+ if (!cancelled) setSources((prev) => ({ ...prev, ready: true }));+ });++ return () => {+ cancelled = true;+ unsubscribe?.();+ };+ }, [open]);++ return sources;+}++const isSettled = (status: string) => status === "ready" || status === "error";++/** Last opened or changed. */+export function libraryTime(item: LibraryItem): number {+ return Math.max(item.openedAt ?? 0, item.updatedAt);+}diff --git a/studio/frontend/src/features/chat/utils/chat-search-tabs.ts b/studio/frontend/src/features/chat/utils/chat-search-tabs.tsnew file mode 100644index 00000000000..e8887a78259--- /dev/null+++ b/studio/frontend/src/features/chat/utils/chat-search-tabs.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Search tabs, in order. "all" mixes every kind. */+export const CHAT_SEARCH_TABS = [+ "all",+ "chats",+ "projects",+ "files",+ "models",+] as const;+export type ChatSearchTab = (typeof CHAT_SEARCH_TABS)[number];+export type ChatSearchKind = Exclude<ChatSearchTab, "all">;++/** A search result of any kind. */+export interface ChatSearchRow {+ /** Unique across kinds; the cmdk value. */+ key: string;+ kind: ChatSearchKind;+ title: string;+ /** Sort key, newest first. */+ time: number;+ /** Lowercased text to match against. */+ haystack: string;+}++/** Rows per kind on the All tab while typing. */+export const ALL_TAB_GROUP_LIMIT = 5;+/** Rows under Recents on an empty All tab. */+export const RECENT_ROW_LIMIT = 5;++// Lowercased whitespace tokens of the query.+export function queryTokens(search: string): string[] {+ return search.trim().toLowerCase().split(/\s+/).filter(Boolean);+}++export function haystackMatches(haystack: string, tokens: string[]): boolean {+ return tokens.every((token) => haystack.includes(token));+}++/** Every token must be a substring. */+export function filterRows<T extends ChatSearchRow>(rows: T[], search: string): T[] {+ const tokens = queryTokens(search);+ if (tokens.length === 0) return rows;+ return rows.filter((row) => haystackMatches(row.haystack, tokens));+}++/** The next or previous tab, without wrapping. */+export function stepTab(tab: ChatSearchTab, step: -1 | 1): ChatSearchTab {+ const index = CHAT_SEARCH_TABS.indexOf(tab) + step;+ return CHAT_SEARCH_TABS[Math.min(Math.max(index, 0), CHAT_SEARCH_TABS.length - 1)];+}++/** Newest rows across kinds, for the empty All tab. */+export function recentRows<T extends ChatSearchRow>(+ byKind: Record<ChatSearchKind, T[]>,+ limit = RECENT_ROW_LIMIT,+): T[] {+ // Kinds need not arrive sorted by `time` (chats are listed by creation, ranked by activity).+ return Object.values(byKind)+ .flat()+ .sort((a, b) => b.time - a.time)+ .slice(0, limit);+}++/** Arrows switch tabs only at the ends of the query, so they still move the caret. */+export function tabStepForKey(+ key: string,+ input: { value: string; selectionStart: number | null; selectionEnd: number | null },+): -1 | 1 | null {+ const { value, selectionStart, selectionEnd } = input;+ if (selectionStart !== selectionEnd) return null;+ if (key === "ArrowLeft" && selectionStart === 0) return -1;+ if (key === "ArrowRight" && selectionEnd === value.length) return 1;+ return null;+}diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.tsindex 466e23b176c..55353bcf5f3 100644--- a/studio/frontend/src/features/library/index.ts+++ b/studio/frontend/src/features/library/index.ts@@ -19,9 +19,11 @@ export {} from "./settings-store";export { STORAGE_LABELS, refreshLibraryStorage, useLibraryStorage } from "./storage";export { formatSize } from "./format";+export { KIND_ICONS, fileKind, isModelItem, modelLabelKey } from "./file-kind";export { parentFolder } from "./paths";export { LibraryStorageBar } from "./components/storage-bar";export {+ type LibraryItem,type LibraryLocation,errorMessage,getLibraryLocations,diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex ea2c2bb6098..d963228bc1b 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -220,6 +220,45 @@ export const ar = {chat: "الدردشة",searchChats: "ابحث في الدردشات...",},+ search: {+ placeholder: "بحث",+ tabs: {+ all: "الكل",+ chats: "المحادثات",+ projects: "المشاريع",+ files: "الملفات",+ models: "النماذج",+ },+ recents: "العناصر الأخيرة",+ actions: "الإجراءات",+ newChat: "محادثة جديدة",+ newTemporaryChat: "محادثة مؤقتة جديدة",+ fineTune: "ضبط نموذج",+ generateImage: "إنشاء صورة",+ generateVideo: "إنشاء فيديو",+ untitledChat: "محادثة بلا عنوان",+ compare: "مقارنة",+ loading: "جارٍ التحميل...",+ empty: {+ all: "لا يوجد شيء للبحث فيه بعد.",+ chats: "لا توجد محادثات بعد.",+ projects: "لا توجد مشاريع بعد.",+ files: "لا توجد ملفات في مكتبتك بعد.",+ models: "لا توجد نماذج منزّلة بعد.",+ },+ noMatches: "لا توجد نتائج.",+ when: {+ today: "اليوم",+ pastWeek: "الأسبوع الماضي",+ pastMonth: "الشهر الماضي",+ older: "أقدم",+ },+ footer: {+ close: "إغلاق",+ changeType: "تغيير النوع",+ open: "فتح",+ },+ },notFound: {title: "الصفحة غير موجودة",description: "{path} غير موجود.",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 088f3364ce1..317896ca2f4 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -223,6 +223,45 @@ export const de = {chat: "Chat",searchChats: "Chats durchsuchen...",},+ search: {+ placeholder: "Suchen",+ tabs: {+ all: "Alle",+ chats: "Chats",+ projects: "Projekte",+ files: "Dateien",+ models: "Modelle",+ },+ recents: "Zuletzt verwendet",+ actions: "Aktionen",+ newChat: "Neuer Chat",+ newTemporaryChat: "Neuer temporärer Chat",+ fineTune: "Modell feinabstimmen",+ generateImage: "Bild generieren",+ generateVideo: "Video generieren",+ untitledChat: "Unbenannter Chat",+ compare: "Vergleich",+ loading: "Wird geladen…",+ empty: {+ all: "Noch nichts zu durchsuchen.",+ chats: "Noch keine Chats.",+ projects: "Noch keine Projekte.",+ files: "Noch keine Dateien in deiner Bibliothek.",+ models: "Noch keine heruntergeladenen Modelle.",+ },+ noMatches: "Keine Ergebnisse.",+ when: {+ today: "Heute",+ pastWeek: "Letzte Woche",+ pastMonth: "Letzter Monat",+ older: "Älter",+ },+ footer: {+ close: "Schließen",+ changeType: "Typ wechseln",+ open: "Öffnen",+ },+ },notFound: {title: "Seite nicht gefunden",description: "{path} existiert nicht.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex c77ae21c1fa..2c70d051e58 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -264,6 +264,45 @@ export const en = {chat: "Chat",searchChats: "Search chats...",},+ search: {+ placeholder: "Search",+ tabs: {+ all: "All",+ chats: "Chats",+ projects: "Projects",+ files: "Files",+ models: "Models",+ },+ recents: "Recents",+ actions: "Actions",+ newChat: "New chat",+ newTemporaryChat: "New temporary chat",+ fineTune: "Fine-tune a model",+ generateImage: "Generate an image",+ generateVideo: "Generate a video",+ untitledChat: "Untitled chat",+ compare: "Compare",+ loading: "Loading…",+ empty: {+ all: "Nothing to search yet.",+ chats: "No chats yet.",+ projects: "No projects yet.",+ files: "No files in your Library yet.",+ models: "No downloaded models yet.",+ },+ noMatches: "No results.",+ when: {+ today: "Today",+ pastWeek: "Past week",+ pastMonth: "Past month",+ older: "Older",+ },+ footer: {+ close: "Close",+ changeType: "Change type",+ open: "Open",+ },+ },notFound: {title: "Page not found",description: "{path} does not exist.",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 4cd1a3c9bb4..4df84a2bfa8 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -222,6 +222,45 @@ export const es = {chat: "Chat",searchChats: "Buscar chats...",},+ search: {+ placeholder: "Buscar",+ tabs: {+ all: "Todo",+ chats: "Chats",+ projects: "Proyectos",+ files: "Archivos",+ models: "Modelos",+ },+ recents: "Recientes",+ actions: "Acciones",+ newChat: "Nuevo chat",+ newTemporaryChat: "Nuevo chat temporal",+ fineTune: "Ajustar un modelo",+ generateImage: "Generar una imagen",+ generateVideo: "Generar un vídeo",+ untitledChat: "Chat sin título",+ compare: "Comparar",+ loading: "Cargando...",+ empty: {+ all: "Aún no hay nada que buscar.",+ chats: "Aún no hay chats.",+ projects: "Aún no hay proyectos.",+ files: "Aún no hay archivos en tu Biblioteca.",+ models: "Aún no hay modelos descargados.",+ },+ noMatches: "Sin resultados.",+ when: {+ today: "Hoy",+ pastWeek: "Última semana",+ pastMonth: "Último mes",+ older: "Más antiguo",+ },+ footer: {+ close: "Cerrar",+ changeType: "Cambiar tipo",+ open: "Abrir",+ },+ },notFound: {title: "Página no encontrada",description: "{path} no existe.",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex b44c953b7c3..2318c64fcfe 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -223,6 +223,45 @@ export const fr = {chat: "Chat",searchChats: "Rechercher des chats...",},+ search: {+ placeholder: "Rechercher",+ tabs: {+ all: "Tout",+ chats: "Discussions",+ projects: "Projets",+ files: "Fichiers",+ models: "Modèles",+ },+ recents: "Récents",+ actions: "Actions",+ newChat: "Nouvelle discussion",+ newTemporaryChat: "Nouvelle discussion temporaire",+ fineTune: "Affiner un modèle",+ generateImage: "Générer une image",+ generateVideo: "Générer une vidéo",+ untitledChat: "Discussion sans titre",+ compare: "Comparaison",+ loading: "Chargement...",+ empty: {+ all: "Rien à rechercher pour l’instant.",+ chats: "Aucune discussion pour l’instant.",+ projects: "Aucun projet pour l’instant.",+ files: "Aucun fichier dans votre Bibliothèque pour l’instant.",+ models: "Aucun modèle téléchargé pour l’instant.",+ },+ noMatches: "Aucun résultat.",+ when: {+ today: "Aujourd’hui",+ pastWeek: "Semaine dernière",+ pastMonth: "Mois dernier",+ older: "Plus ancien",+ },+ footer: {+ close: "Fermer",+ changeType: "Changer de type",+ open: "Ouvrir",+ },+ },notFound: {title: "Page introuvable",description: "{path} n'existe pas.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 06612127925..942dfe2c064 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -223,6 +223,45 @@ export const hi = {chat: "चैट",searchChats: "चैट खोजें...",},+ search: {+ placeholder: "खोजें",+ tabs: {+ all: "सभी",+ chats: "चैट",+ projects: "प्रोजेक्ट",+ files: "फ़ाइलें",+ models: "मॉडल",+ },+ recents: "हाल के",+ actions: "क्रियाएँ",+ newChat: "नई चैट",+ newTemporaryChat: "नई अस्थायी चैट",+ fineTune: "मॉडल फ़ाइन-ट्यून करें",+ generateImage: "इमेज बनाएँ",+ generateVideo: "वीडियो बनाएँ",+ untitledChat: "बिना शीर्षक वाली चैट",+ compare: "तुलना",+ loading: "लोड हो रहा है...",+ empty: {+ all: "अभी खोजने के लिए कुछ नहीं है।",+ chats: "अभी कोई चैट नहीं है।",+ projects: "अभी कोई प्रोजेक्ट नहीं है।",+ files: "आपकी लाइब्रेरी में अभी कोई फ़ाइल नहीं है।",+ models: "अभी कोई डाउनलोड किया गया मॉडल नहीं है।",+ },+ noMatches: "कोई परिणाम नहीं।",+ when: {+ today: "आज",+ pastWeek: "पिछला सप्ताह",+ pastMonth: "पिछला महीना",+ older: "पुराने",+ },+ footer: {+ close: "बंद करें",+ changeType: "प्रकार बदलें",+ open: "खोलें",+ },+ },notFound: {title: "पेज नहीं मिला",description: "{path} मौजूद नहीं है।",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 12551d677ef..eb2cdc2ac04 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -184,6 +184,45 @@ export const it = {chat: "Chat",searchChats: "Cerca nelle chat...",},+ search: {+ placeholder: "Cerca",+ tabs: {+ all: "Tutti",+ chats: "Chat",+ projects: "Progetti",+ files: "File",+ models: "Modelli",+ },+ recents: "Recenti",+ actions: "Azioni",+ newChat: "Nuova chat",+ newTemporaryChat: "Nuova chat temporanea",+ fineTune: "Fai il fine-tune di un modello",+ generateImage: "Genera un'immagine",+ generateVideo: "Genera un video",+ untitledChat: "Chat senza titolo",+ compare: "Confronto",+ loading: "Caricamento...",+ empty: {+ all: "Ancora niente da cercare.",+ chats: "Ancora nessuna chat.",+ projects: "Ancora nessun progetto.",+ files: "Ancora nessun file nella tua Libreria.",+ models: "Ancora nessun modello scaricato.",+ },+ noMatches: "Nessun risultato.",+ when: {+ today: "Oggi",+ pastWeek: "Ultima settimana",+ pastMonth: "Ultimo mese",+ older: "Meno recenti",+ },+ footer: {+ close: "Chiudi",+ changeType: "Cambia tipo",+ open: "Apri",+ },+ },notFound: {title: "Pagina non trovata",description: "{path} non esiste.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex dede4234adb..b77f9bb3a8b 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -222,6 +222,45 @@ export const ja = {chat: "チャット",searchChats: "チャットを検索...",},+ search: {+ placeholder: "検索",+ tabs: {+ all: "すべて",+ chats: "チャット",+ projects: "プロジェクト",+ files: "ファイル",+ models: "モデル",+ },+ recents: "最近",+ actions: "アクション",+ newChat: "新規チャット",+ newTemporaryChat: "新しい一時チャット",+ fineTune: "モデルをファインチューン",+ generateImage: "画像を生成",+ generateVideo: "動画を生成",+ untitledChat: "無題のチャット",+ compare: "比較",+ loading: "読み込み中...",+ empty: {+ all: "まだ検索できるものはありません。",+ chats: "チャットはまだありません。",+ projects: "プロジェクトはまだありません。",+ files: "ライブラリにファイルはまだありません。",+ models: "ダウンロード済みのモデルはまだありません。",+ },+ noMatches: "結果がありません。",+ when: {+ today: "今日",+ pastWeek: "過去 1 週間",+ pastMonth: "過去 1 か月",+ older: "それ以前",+ },+ footer: {+ close: "閉じる",+ changeType: "種類を切り替え",+ open: "開く",+ },+ },notFound: {title: "ページが見つかりません",description: "{path} は存在しません。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 6b0b05ee146..bcaee828917 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -220,6 +220,45 @@ export const ko = {chat: "채팅",searchChats: "채팅 검색...",},+ search: {+ placeholder: "검색",+ tabs: {+ all: "전체",+ chats: "채팅",+ projects: "프로젝트",+ files: "파일",+ models: "모델",+ },+ recents: "최근 항목",+ actions: "작업",+ newChat: "새 채팅",+ newTemporaryChat: "새 임시 채팅",+ fineTune: "모델 파인튜닝",+ generateImage: "이미지 생성",+ generateVideo: "동영상 생성",+ untitledChat: "제목 없는 채팅",+ compare: "비교",+ loading: "로딩 중...",+ empty: {+ all: "아직 검색할 항목이 없습니다.",+ chats: "아직 채팅이 없습니다.",+ projects: "아직 프로젝트가 없습니다.",+ files: "아직 라이브러리에 파일이 없습니다.",+ models: "아직 다운로드한 모델이 없습니다.",+ },+ noMatches: "결과가 없습니다.",+ when: {+ today: "오늘",+ pastWeek: "지난주",+ pastMonth: "지난달",+ older: "이전",+ },+ footer: {+ close: "닫기",+ changeType: "유형 변경",+ open: "열기",+ },+ },notFound: {title: "페이지를 찾을 수 없습니다",description: "{path} 경로가 존재하지 않습니다.",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex e2b96f7a17d..7cfef1ce41c 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -222,6 +222,45 @@ export const ptBR = {chat: "Chat",searchChats: "Buscar chats...",},+ search: {+ placeholder: "Buscar",+ tabs: {+ all: "Tudo",+ chats: "Chats",+ projects: "Projetos",+ files: "Arquivos",+ models: "Modelos",+ },+ recents: "Recentes",+ actions: "Ações",+ newChat: "Novo chat",+ newTemporaryChat: "Novo chat temporário",+ fineTune: "Fazer fine-tune de um modelo",+ generateImage: "Gerar uma imagem",+ generateVideo: "Gerar um vídeo",+ untitledChat: "Chat sem título",+ compare: "Comparar",+ loading: "Carregando...",+ empty: {+ all: "Nada para buscar ainda.",+ chats: "Nenhum chat ainda.",+ projects: "Nenhum projeto ainda.",+ files: "Nenhum arquivo na sua Biblioteca ainda.",+ models: "Nenhum modelo baixado ainda.",+ },+ noMatches: "Nenhum resultado.",+ when: {+ today: "Hoje",+ pastWeek: "Última semana",+ pastMonth: "Último mês",+ older: "Mais antigos",+ },+ footer: {+ close: "Fechar",+ changeType: "Mudar tipo",+ open: "Abrir",+ },+ },notFound: {title: "Página não encontrada",description: "{path} não existe.",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 119d3e625f5..d7319311a07 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -222,6 +222,45 @@ export const ru = {chat: "Чат",searchChats: "Поиск по чатам...",},+ search: {+ placeholder: "Поиск",+ tabs: {+ all: "Все",+ chats: "Чаты",+ projects: "Проекты",+ files: "Файлы",+ models: "Модели",+ },+ recents: "Недавние",+ actions: "Действия",+ newChat: "Новый чат",+ newTemporaryChat: "Новый временный чат",+ fineTune: "Дообучить модель",+ generateImage: "Создать изображение",+ generateVideo: "Создать видео",+ untitledChat: "Чат без названия",+ compare: "Сравнение",+ loading: "Загрузка…",+ empty: {+ all: "Пока нечего искать.",+ chats: "Пока нет чатов.",+ projects: "Пока нет проектов.",+ files: "В вашей библиотеке пока нет файлов.",+ models: "Пока нет скачанных моделей.",+ },+ noMatches: "Ничего не найдено.",+ when: {+ today: "Сегодня",+ pastWeek: "За неделю",+ pastMonth: "За месяц",+ older: "Ранее",+ },+ footer: {+ close: "Закрыть",+ changeType: "Сменить тип",+ open: "Открыть",+ },+ },notFound: {title: "Страница не найдена",description: "{path} не существует.",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 1b9b918d3a2..6d2d075ae54 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -218,6 +218,45 @@ export const zhCN = {chat: "聊天",searchChats: "搜索聊天...",},+ search: {+ placeholder: "搜索",+ tabs: {+ all: "全部",+ chats: "聊天",+ projects: "项目",+ files: "文件",+ models: "模型",+ },+ recents: "最近",+ actions: "操作",+ newChat: "新聊天",+ newTemporaryChat: "新建临时聊天",+ fineTune: "微调模型",+ generateImage: "生成图像",+ generateVideo: "生成视频",+ untitledChat: "未命名聊天",+ compare: "对比",+ loading: "加载中...",+ empty: {+ all: "暂无可搜索的内容。",+ chats: "暂无聊天。",+ projects: "暂无项目。",+ files: "你的资料库中暂无文件。",+ models: "暂无已下载的模型。",+ },+ noMatches: "无结果。",+ when: {+ today: "今天",+ pastWeek: "过去一周",+ pastMonth: "过去一个月",+ older: "更早",+ },+ footer: {+ close: "关闭",+ changeType: "切换类型",+ open: "打开",+ },+ },notFound: {title: "页面未找到",description: "{path} 不存在。",diff --git a/studio/frontend/tests/chat-search-tabs.test.ts b/studio/frontend/tests/chat-search-tabs.test.tsnew file mode 100644index 00000000000..4a18a4fb7a4--- /dev/null+++ b/studio/frontend/tests/chat-search-tabs.test.ts@@ -0,0 +1,169 @@+// 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 { readFile } from "node:fs/promises";+import test from "node:test";++import {+ CHAT_SEARCH_TABS,+ type ChatSearchKind,+ type ChatSearchRow,+ filterRows,+ recentRows,+ stepTab,+ tabStepForKey,+} from "../src/features/chat/utils/chat-search-tabs.ts";++const DIALOG = await readFile(+ new URL("../src/features/chat/components/chat-search-dialog.tsx", import.meta.url),+ "utf8",+);+const SOURCES = await readFile(+ new URL("../src/features/chat/hooks/use-chat-search-sources.ts", import.meta.url),+ "utf8",+);++function row(kind: ChatSearchKind, title: string, time: number): ChatSearchRow {+ return { key: `${kind}:${title}`, kind, title, time, haystack: title.toLowerCase() };+}++test("the tabs run All, then each kind a user looks for", () => {+ assert.deepEqual([...CHAT_SEARCH_TABS], ["all", "chats", "projects", "files", "models"]);+});++test("left and right step through the tabs and stop at either end", () => {+ assert.equal(stepTab("all", 1), "chats");+ assert.equal(stepTab("chats", -1), "all");+ assert.equal(stepTab("all", -1), "all");+ assert.equal(stepTab("models", 1), "models");+});++test("the arrows change tab only from the ends of the query, so the caret still moves inside it", () => {+ const at = (value: string, start: number, end = start) => ({ value, selectionStart: start, selectionEnd: end });+ assert.equal(tabStepForKey("ArrowRight", at("", 0)), 1);+ assert.equal(tabStepForKey("ArrowLeft", at("", 0)), -1);+ assert.equal(tabStepForKey("ArrowRight", at("llama", 5)), 1);+ assert.equal(tabStepForKey("ArrowRight", at("llama", 2)), null);+ assert.equal(tabStepForKey("ArrowLeft", at("llama", 2)), null);+ assert.equal(tabStepForKey("ArrowLeft", at("llama", 0, 3)), null);+ assert.equal(tabStepForKey("ArrowDown", at("", 0)), null);+});++test("every query word must appear in a row", () => {+ const rows = [row("projects", "Qwen fine-tune", 1), row("projects", "Llama eval", 2)];+ assert.deepEqual(filterRows(rows, " "), rows);+ assert.deepEqual(filterRows(rows, "QWEN tune").map((r) => r.title), ["Qwen fine-tune"]);+ assert.deepEqual(filterRows(rows, "qwen eval"), []);+});++test("Recents are the newest rows of every kind together", () => {+ const recents = recentRows(+ {+ chats: [row("chats", "c2", 50), row("chats", "c1", 10)],+ projects: [row("projects", "p", 40)],+ files: [row("files", "f", 60)],+ models: [row("models", "m", 30)],+ },+ 3,+ );+ assert.deepEqual(recents.map((r) => r.title), ["f", "c2", "p"]);+});++test("Recents ranks a kind that is not listed newest first", () => {+ // Oldest first, as if listed by creation, with the oldest one used most recently.+ const chats = [40, 50, 60, 70, 80].map((t) => row("chats", `c${t}`, t));+ chats.push(row("chats", "created first, used today", 90));+ const recents = recentRows({ chats, projects: [], files: [], models: [] }, 1);+ assert.deepEqual(recents.map((r) => r.title), ["created first, used today"]);+});++test("the dialog keeps chat search's surface, header, rows and shortcut", () => {+ assert.match(DIALOG, /<CommandDialog[\s\S]*className="chat-search-surface /);+ assert.ok(DIALOG.includes('className="flex items-center gap-3 border-b border-border/40 px-4 py-3"'));+ assert.match(DIALOG, /rounded-full px-3 py-2\.5 text-sm outline-hidden data-selected:bg-muted/);+ assert.match(DIALOG, /useShortcut\("searchChats"/);+ assert.match(DIALOG, /role="tablist"/);+});++test("the Library store loads with the dialog, not with the app, and recipes are not searched", () => {+ assert.match(SOURCES, /import\("@\/features\/library\/store"\)/);+ assert.doesNotMatch(SOURCES, /from "@\/features\/library\/store"/);+ assert.doesNotMatch(SOURCES + DIALOG, /data-recipes|recipe/i);+});++test("Models lists every complete download the Hub knows of, plus the Library's fine-tunes", () => {+ assert.match(DIALOG, /useHubInventory\(\{\s*kind: "models",\s*enabled: isOpen,\s*\}\)/);+ assert.match(DIALOG, /cachedRows\s*\.filter\(\s*\(row\) =>\s*!row\.partial &&/);+ assert.match(DIALOG, /localRows\s*\.filter\(\(row\) => !row\.partial\)/);+ assert.match(DIALOG, /search: \{ tab: "downloaded", model: id \}/);+ assert.match(DIALOG, /sources\.fineTunes\.map/);+});++test("Enter never runs a stale action or row, and a focused tab only switches", () => {+ // Actions follow the live query, not the deferred one.+ assert.ok(DIALOG.includes("haystackMatches(t(action.labelKey).toLowerCase(), queryTokens(query)),"));+ // cmdk's root runs the highlighted row on Enter, so the tabs stop it, as the close button does.+ assert.match(DIALOG, /onClick=\{\(\) => switchTab\(entry\)\}[\s\S]{0,200}?if \(e\.key === "Enter"\) e\.stopPropagation\(\);/);+ // A kept selection must still be on screen, and is cleared with the pin.+ assert.match(DIALOG, /value=\{moved && shownKeys\.has\(selected\) \? selected : firstKey\}/);+ assert.equal(DIALOG.match(/setMoved\(false\);\n\s*setSelected\(""\);/g)?.length, 3);+});++test("empty states wait for their source, and chats rank by last activity", () => {+ assert.match(SOURCES, /ready: prev\.ready \|\| isSettled\(useLibraryStore\.getState\(\)\.status\)/);+ assert.match(DIALOG, /files: !sources\.ready,/);+ assert.match(DIALOG, /projects: !projectsLoaded,/);+ assert.match(DIALOG, /time: item\.updatedAt \?\? item\.createdAt,/);+});++test("an action that becomes unavailable leaves the selection keys too", () => {+ // Rows and keys share one list, so a key never points at an unmounted row.+ assert.match(DIALOG, /available\[action\.id\] &&\s*haystackMatches\(/);+ assert.doesNotMatch(DIALOG.slice(DIALOG.indexOf("function ActionItem(")), /useShortcutAvailable|return null/);+});++test("Enter on a stale auto-highlight runs what the caught-up list shows first", () => {+ assert.match(DIALOG, /if \(moved\) return;\n\s*const first = groupsFor\(live, queryTokens\(query\)\.length > 0\)/);+ assert.match(DIALOG, /else if \(showActions\) go\(\(\) => void triggerShortcut\(visibleActions\[0\]\.id\)\)\(\);/);+});++test("the compact height counts every kind, not only chats", () => {+ assert.match(DIALOG, /isCompactChatSearchList\(true, otherRows \|\| chatSearchIndexHasRows\(\)\)/);+ assert.match(DIALOG, /isCompactChatSearchList\(compactList, otherRows \|\| items\.length > 0\)/);+});++test("model rows are searchable by the labels they show", () => {+ assert.equal(DIALOG.match(/FORMAT_LABELS\[row\.modelFormat\] \?\? "",/g)?.length, 2);+ assert.match(DIALOG, /t\(modelLabelKey\(entry\.item\) \?\? "library\.modelKind\.model"\)/);+ assert.doesNotMatch(DIALOG, /shell\.search\.fineTuned/);+});++test("projects rank by their newest chat, as the sidebar does", () => {+ assert.match(DIALOG, /Math\.max\(project\.updatedAt \?\? project\.createdAt, newestChat\.get\(project\.id\) \?\? 0\)/);+ assert.match(DIALOG, /time: activityAt\(project\),/);+});++test("untitled and compare chats are searchable by their shown labels", () => {+ assert.match(DIALOG, /item\.title \? "" : untitled,/);+ assert.match(DIALOG, /item\.type === "compare" \? compare : "",/);+ assert.match(DIALOG, /selectVisibleChats\(chats, search\)/);+});++test("project ages count empty threads, which the search index skips", () => {+ assert.match(DIALOG, /useChatSidebarItems\(\{\s*enabled: isOpen,\s*requireMessages: false,\s*\}\)/);+ assert.match(DIALOG, /for \(const thread of threads\) \{/);+});++test("infrastructure models stay out of the list until queried", () => {+ assert.match(DIALOG, /hidden: isHiddenModelId\(row\.id, row\.repoId, row\.path, row\.title\),/);+ assert.match(DIALOG, /row\.optimistic && isHiddenModelId\(row\.id, row\.repoId, row\.cachePath\)/);+ assert.match(DIALOG, /: rowsByKind\.models\.filter\(\(row\) => !row\.hidden\),/);+});++test("tab arrows leave IME composition alone", () => {+ assert.match(+ DIALOG,+ /if \(isImeComposing\(event\.nativeEvent\)\) return;\n[^\n]*\n\s*const step = tabStepForKey/,+ );+});