Recommended files with a quant; floating selection bar

Picking model weights in Add model or Download more also selects the
files that usually go with them (chat template, MTP head, mmproj, ...),
shown in a strip where each can be unchecked. Variants are matched by
quant, otherwise the best single one; kinds already selected aren't
added twice. Which kinds is set in Settings -> Downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 23:10:53 +02:00
1 parent 145818f149
commit 0247f257fb
16 files changed
+514 -27

No files matched your search

+8 -1
View File
@@ -44,6 +44,12 @@ step 1 (Hugging Face downloader) is released as a minor version.
job runs `hf download` into the existing folder: hf 2.1.1 hashes files it didn't download itself,
keeps those that match and downloads only missing or different ones. Other files in the folder
are left alone. Jobs show the purpose "import".
- **Recommended files:** picking a quant (chip or checkbox) in Add model or Download more also
selects the files that usually go with it, shown in a "Recommended with your quant" strip where
each can be unchecked. They drop out again when you deselect the quant. Variants are matched:
the MTP head or mmproj with the same quant if there is one, otherwise the best single one (mmproj:
F16, BF16, Q8_0, F32); nothing is added if the model already has one of that kind. Which kinds
(default: chat template, MTP, vision) is set in the new **Settings → Downloads**.
- Create tags in Settings (name and color), before any model uses them.
- Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your
existing tags with their colors, and "Manage tags…".
@@ -59,7 +65,8 @@ step 1 (Hugging Face downloader) is released as a minor version.
- Quant labels (library column, Quant filter, "Local copy") only count model weights, not MTP,
mmproj or imatrix files.
- Tags are no longer deleted automatically when no model uses them anymore; delete them in Settings.
- Settings has separate pages for **File labels** and **Tags**.
- Settings has separate pages for **File labels**, **Tags** and **Downloads**.
- The selection bar at the bottom of Add model is a floating card like the rest of the page.
- Header: app icon, navigation with icons and the current page highlighted.
### Fixed
+2 -1
View File
@@ -64,7 +64,8 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
</p>
- **Add model:** enter a repo ID like `unsloth/Qwen3-8B-GGUF` (or paste the URL), click a quant, and
**Add & download**. You can add tags right there.
**Add & download**. Files that belong with the quant (chat template, MTP head, vision projector)
are selected along with it; choose which kinds in Settings → Downloads. You can add tags right there.
- **Search:** type anything: `unsloth qwen`, `q4_k_m`, `gemma`, `roleplay`. Every word has to match
somewhere (repo, author, base model family, architecture, quant, tags).
- **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so
+30 -6
View File
@@ -5,9 +5,11 @@ import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
@@ -26,6 +28,7 @@ export function FilesHeader({
localCount,
localBytes,
candidates,
selectedPaths,
freeBytes,
busy,
hubMissing,
@@ -37,6 +40,8 @@ export function FilesHeader({
localCount: number;
localBytes: number;
candidates: Candidate[];
/** Files the model already has selected (no second mmproj/MTP is recommended). */
selectedPaths: string[];
freeBytes: number | null;
/** A download is queued/running; adding files has to wait. */
busy: boolean;
@@ -61,13 +66,18 @@ export function FilesHeader({
return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }));
}, [candidates]);
// Companions (template, MTP, mmproj, …) of newly picked model files come along.
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(candidates, picked, { have: selectedPaths });
const chosen = useMemo(() => new Set([...picked, ...recActive]), [picked, recActive]);
// Split files are one entry; its checkbox selects all parts.
const entries = useMemo(() => groupSplitFiles(candidates), [candidates]);
const pickedEntries = entries.filter((e) => e.parts.every((p) => picked.has(p.path))).length;
const pickedBytes = candidates.filter((c) => picked.has(c.path)).reduce((s, c) => s + c.size, 0);
const pickedEntries = entries.filter((e) => e.parts.every((p) => chosen.has(p.path))).length;
const pickedBytes = candidates.filter((c) => chosen.has(c.path)).reduce((s, c) => s + c.size, 0);
const tooBig = freeBytes != null && pickedBytes > freeBytes;
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setPicked((prev) => {
const next = new Set(prev);
for (const p of paths) {
@@ -84,7 +94,7 @@ export function FilesHeader({
const res = await fetch(`/api/models/${modelId}/files`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ add: [...picked] }),
body: JSON.stringify({ add: [...chosen] }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
@@ -94,6 +104,7 @@ export function FilesHeader({
toast.success(`${body.added} file${body.added === 1 ? "" : "s"} added, download queued`);
setOpen(false);
setPicked(new Set());
resetRecommended();
router.refresh();
} finally {
setSubmitting(false);
@@ -165,10 +176,13 @@ export function FilesHeader({
</div>
)}
<RecommendedStrip files={candidates} paths={recAll} active={recActive} onToggle={toggle} className="mx-5 mt-3" />
<ul className="mt-3 max-h-96 divide-y overflow-y-auto border-y bg-card">
{entries.map((e) => {
const paths = e.parts.map((p) => p.path);
const on = paths.every((p) => picked.has(p));
const on = paths.every((p) => chosen.has(p));
const isRecommended = paths.every((p) => recAll.includes(p));
return (
<li key={e.path}>
<label className="grid cursor-pointer grid-cols-[1rem_auto_minmax(0,1fr)_auto] items-center gap-x-3 px-5 py-2 hover:bg-muted/50">
@@ -181,6 +195,11 @@ export function FilesHeader({
{e.totalParts} parts
</span>
)}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
</span>
<span className="text-right text-sm text-muted-foreground tabular-nums">{formatBytes(e.size)}</span>
</label>
@@ -202,10 +221,15 @@ export function FilesHeader({
)}
</span>
<div className="ml-auto flex gap-2">
<Button variant="ghost" size="sm" onClick={() => setPicked(new Set())} disabled={picked.size === 0}>
<Button variant="ghost" size="sm" onClick={() => {
setPicked(new Set());
resetRecommended();
}}
disabled={chosen.size === 0}
>
Clear
</Button>
<Button size="sm" onClick={submit} disabled={picked.size === 0 || submitting || busy}>
<Button size="sm" onClick={submit} disabled={chosen.size === 0 || submitting || busy}>
{submitting ? "Adding…" : pickedEntries === 0 ? "Download" : `Download ${pickedEntries} file${pickedEntries === 1 ? "" : "s"}`}
</Button>
</div>
+1
View File
@@ -155,6 +155,7 @@ export function FilesTab({
localCount={localEntries.length}
localBytes={localBytes}
candidates={others.map((f) => ({ path: f.path, size: f.size }))}
selectedPaths={selected.map((f) => f.path)}
freeBytes={freeBytes}
busy={busy}
hubMissing={hubMissing}
+41 -11
View File
@@ -2,9 +2,10 @@
import { XIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { RecommendedStrip } from "@/components/recommended-strip";
import { TagBadge } from "@/components/tag-badge";
import { TagPicker } from "@/components/tag-picker";
import { Badge } from "@/components/ui/badge";
@@ -14,6 +15,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, shortSha } from "@/lib/format";
import type { LookupResult } from "@/lib/hub/lookup";
@@ -57,6 +59,22 @@ export function AddModelForm({
const [submitting, setSubmitting] = useState(false);
const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]);
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const repoFiles = useMemo(() => result?.files ?? [], [result]);
const isExcluded = useCallback((path: string) => matchesAny(path, excludePatterns), [excludePatterns]);
// Picked by checkbox or include pattern; recommended companions come on top.
const picked = useMemo(
() => repoFiles.filter((f) => (checked.has(f.path) || matchesAny(f.path, includePatterns)) && !isExcluded(f.path)).map((f) => f.path),
[repoFiles, checked, includePatterns, isExcluded],
);
const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(
repoFiles,
picked,
{ isExcluded },
);
// Local files of the imported folder by path.
const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]);
@@ -70,6 +88,7 @@ export function AddModelForm({
setRevision(r.revision);
// Import: preselect every repo file that's already in the folder.
setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path)));
resetRecommended();
setIncludeText("");
setExcludeText("");
setTags([]);
@@ -90,23 +109,22 @@ export function AddModelForm({
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported
}, [importFolder]);
const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]);
const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]);
const files = useMemo(() => {
if (!result) return [];
return result.files.map((f) => {
const pickedSet = new Set(picked);
return repoFiles.map((f) => {
const byPattern = matchesAny(f.path, includePatterns);
const excluded = matchesAny(f.path, excludePatterns);
const excluded = isExcluded(f.path);
return {
...f,
group: quantGroup(f.path),
byPattern,
excluded,
selected: (checked.has(f.path) || byPattern) && !excluded,
recommended: recAll.includes(f.path),
selected: pickedSet.has(f.path) || recActive.has(f.path),
};
});
}, [result, checked, includePatterns, excludePatterns]);
}, [repoFiles, picked, includePatterns, isExcluded, recAll, recActive]);
const groups = useMemo(() => {
const m = new Map<string, { paths: string[]; size: number }>();
@@ -134,6 +152,7 @@ export function AddModelForm({
const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0;
function toggle(paths: string[], on: boolean) {
setRecommendedOn(paths, on);
setChecked((prev) => {
const next = new Set(prev);
for (const path of paths) {
@@ -164,7 +183,7 @@ export function AddModelForm({
repoId: result.repoId,
revision: result.revision,
sha: result.sha,
include: [...includePatterns, ...[...checked].sort().map(escapeGlob)],
include: [...includePatterns, ...[...new Set([...checked, ...recActive])].sort().map(escapeGlob)],
exclude: excludePatterns,
tags: tags.map((t) => t.name),
localPath: importFolder?.path,
@@ -300,6 +319,8 @@ export function AddModelForm({
</div>
)}
<RecommendedStrip files={repoFiles} paths={recAll} active={recActive} onToggle={toggle} />
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="include">Include patterns</Label>
@@ -378,6 +399,7 @@ export function AddModelForm({
const some = !all && parts.some((f) => f.selected);
const byPattern = parts.every((f) => f.byPattern);
const excluded = parts.every((f) => f.excluded);
const isRecommended = parts.every((f) => f.recommended);
return (
<TableRow key={e.path} data-state={all ? "selected" : undefined}>
<TableCell>
@@ -400,6 +422,11 @@ export function AddModelForm({
</span>
)}
{excluded && <span className="text-xs text-muted-foreground">(excluded)</span>}
{isRecommended && (
<span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1 text-[10px] leading-4 text-amber-700 dark:text-amber-300">
recommended
</span>
)}
{importFolder && <DiskState parts={parts} onDisk={onDisk} />}
</span>
</TableCell>
@@ -414,7 +441,7 @@ export function AddModelForm({
</Table>
</Card>
<div className="sticky bottom-0 -mx-4 border-t bg-background/95 px-4 py-3 backdrop-blur">
<div className="sticky bottom-3 z-10 rounded-xl bg-card/95 px-4 py-3 text-card-foreground shadow-lg ring-1 ring-foreground/10 backdrop-blur">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div className="text-sm">
<span className="font-medium">
@@ -429,7 +456,10 @@ export function AddModelForm({
)}
</div>
<div className="ml-auto flex gap-2">
<Button type="button" variant="ghost" onClick={() => setChecked(new Set())}>
<Button type="button" variant="ghost" onClick={() => {
setChecked(new Set());
resetRecommended();
}}>
Clear
</Button>
<Button
+7 -3
View File
@@ -5,14 +5,18 @@ import { AppNav } from "@/components/app-nav";
import { LabelSettingsProvider } from "@/components/labels";
import { UserMenu } from "@/components/user-menu";
import { WorkerIndicator } from "@/components/worker-indicator";
import { getFileRoleStyles } from "@/lib/settings";
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export default async function AppLayout({ children }: LayoutProps<"/">) {
const session = await auth();
if (!session?.user) redirect("/login");
const [worker, fileRoles] = await Promise.all([getWorkerStatus(), getFileRoleStyles()]);
const [worker, fileRoles, recommendedRoles] = await Promise.all([
getWorkerStatus(),
getFileRoleStyles(),
getRecommendedRoles(),
]);
return (
<div className="flex min-h-screen flex-col overflow-x-clip">
@@ -38,7 +42,7 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
</div>
</header>
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
<LabelSettingsProvider fileRoles={fileRoles}>{children}</LabelSettingsProvider>
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
</main>
</div>
);
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { getRecommendedRoles } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Downloads · Settings" };
export default async function DownloadSettingsPage() {
return <RecommendedSettings initial={await getRecommendedRoles()} />;
}
@@ -0,0 +1,96 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { FileRoleBadge } from "@/components/labels";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { FILE_ROLES, type FileRole } from "@/lib/file-roles";
import { RECOMMENDABLE_ROLES } from "@/lib/recommend";
/** Example file name per kind, so the badge shows the configured label and color. */
const EXAMPLE: Partial<Record<FileRole, string>> = {
template: "chat_template.jinja",
mtp: "mtp-model.gguf",
vision: "mmproj-F16.gguf",
draft: "model-draft.gguf",
config: "config.json",
tokenizer: "tokenizer.json",
imatrix: "imatrix.dat",
adapter: "adapter_model.safetensors",
docs: "README.md",
};
const HINT: Partial<Record<FileRole, string>> = {
mtp: "The variant with the same quant as your model file, otherwise the closest one.",
vision: "One mmproj file: same quant if there is one, otherwise F16, BF16, Q8_0, F32.",
draft: "One draft model, picked like MTP.",
imatrix: "Only needed to make your own quants.",
config: "GGUF files already contain it; useful for safetensors repos.",
tokenizer: "GGUF files already contain it; useful for safetensors repos.",
};
/** Which file kinds are selected automatically when you pick model weights. Saves on change. */
export function RecommendedSettings({ initial }: { initial: FileRole[] }) {
const router = useRouter();
const [roles, setRoles] = useState(new Set(initial));
const [saving, setSaving] = useState(false);
async function toggle(role: FileRole, on: boolean) {
const before = roles;
const next = new Set(roles);
if (on) next.add(role);
else next.delete(role);
setRoles(next);
setSaving(true);
try {
const res = await fetch("/api/settings/downloads", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ recommendedRoles: [...next] }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Could not save (${res.status})`);
setRoles(before);
return;
}
router.refresh();
} finally {
setSaving(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Recommended files</CardTitle>
<CardDescription>
When you pick model weights (a quant) in Add model or Download more, files of these kinds are selected along
with them. You can still uncheck them before downloading.
</CardDescription>
</CardHeader>
<CardContent>
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{RECOMMENDABLE_ROLES.map((role) => (
<label key={role} className="flex cursor-pointer items-start gap-3 px-4 py-3 hover:bg-muted/40">
<Checkbox
checked={roles.has(role)}
disabled={saving}
onCheckedChange={(v) => void toggle(role, v === true)}
className="mt-0.5"
aria-label={FILE_ROLES[role].label}
/>
<FileRoleBadge path={EXAMPLE[role] ?? role} />
<span className="flex min-w-0 flex-col">
<span className="text-sm">{FILE_ROLES[role].description}</span>
{HINT[role] && <span className="text-xs text-muted-foreground">{HINT[role]}</span>}
</span>
</label>
))}
</div>
</CardContent>
</Card>
);
}
+2 -1
View File
@@ -1,9 +1,10 @@
import { TagIcon, TagsIcon } from "lucide-react";
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getRecommendedRoles, saveRecommendedRoles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Download settings: which file kinds are picked along with model weights. */
export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() }));
const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) });
export const PUT = withAuth(async (req) => {
try {
const { recommendedRoles } = Body.parse(await req.json());
return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) });
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+23 -4
View File
@@ -2,7 +2,8 @@
import { createContext, useContext } from "react";
import { BADGE_CLASS } from "@/lib/colors";
import { FILE_ROLES, fileRole, type FileRoleStyles } from "@/lib/file-roles";
import { FILE_ROLES, fileRole, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { DEFAULT_RECOMMENDED_ROLES } from "@/lib/recommend";
import { cn } from "@/lib/utils";
const defaults = Object.fromEntries(
@@ -10,16 +11,34 @@ const defaults = Object.fromEntries(
) as FileRoleStyles;
const LabelContext = createContext<FileRoleStyles>(defaults);
const RecommendedContext = createContext<FileRole[]>(DEFAULT_RECOMMENDED_ROLES);
/** Provides the label settings (from the Settings page) to client components. */
export function LabelSettingsProvider({ fileRoles, children }: { fileRoles: FileRoleStyles; children: React.ReactNode }) {
return <LabelContext.Provider value={fileRoles}>{children}</LabelContext.Provider>;
/** Provides file label and download settings (from the Settings page) to client components. */
export function LabelSettingsProvider({
fileRoles,
recommendedRoles,
children,
}: {
fileRoles: FileRoleStyles;
recommendedRoles: FileRole[];
children: React.ReactNode;
}) {
return (
<LabelContext.Provider value={fileRoles}>
<RecommendedContext.Provider value={recommendedRoles}>{children}</RecommendedContext.Provider>
</LabelContext.Provider>
);
}
export function useFileRoleStyles(): FileRoleStyles {
return useContext(LabelContext);
}
/** File kinds picked automatically along with model weights. */
export function useRecommendedRoles(): FileRole[] {
return useContext(RecommendedContext);
}
/** Label in front of a file name telling what the file is (Model, MTP, Vision, …). */
export function FileRoleBadge({ path, className }: { path: string; className?: string }) {
const styles = useFileRoleStyles();
+63
View File
@@ -0,0 +1,63 @@
"use client";
import { SparklesIcon } from "lucide-react";
import Link from "next/link";
import { FileRoleBadge } from "@/components/labels";
import { Checkbox } from "@/components/ui/checkbox";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes } from "@/lib/format";
import { cn } from "@/lib/utils";
/** Companion files picked along with the chosen quant; each can be unchecked. */
export function RecommendedStrip({
files,
paths,
active,
onToggle,
className,
}: {
files: { path: string; size: number }[];
/** All recommended paths (checked or not). */
paths: string[];
active: Set<string>;
onToggle: (paths: string[], on: boolean) => void;
className?: string;
}) {
if (paths.length === 0) return null;
const wanted = new Set(paths);
const entries = groupSplitFiles(files.filter((f) => wanted.has(f.path)));
return (
<div className={cn("flex flex-col gap-2 rounded-lg bg-muted/50 px-3 py-2.5 ring-1 ring-foreground/5", className)}>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="flex items-center gap-1.5 font-medium text-foreground">
<SparklesIcon className="size-3.5 text-amber-500" />
Recommended with your quant
</span>
<Link href="/settings/downloads" className="hover:text-foreground hover:underline">
Change in Settings
</Link>
</div>
<div className="flex flex-wrap gap-2">
{entries.map((e) => {
const parts = e.parts.map((p) => p.path);
const on = parts.every((p) => active.has(p));
return (
<label
key={e.path}
className={cn(
"flex cursor-pointer items-center gap-2 rounded-md border bg-background px-2 py-1 text-xs transition-opacity",
!on && "opacity-60",
)}
>
<Checkbox checked={on} onCheckedChange={(v) => onToggle(parts, v === true)} aria-label={`Download ${e.path}`} />
<FileRoleBadge path={e.path} />
<span className="font-mono break-all">{e.path}</span>
<span className="text-muted-foreground tabular-nums">{formatBytes(e.size)}</span>
</label>
);
})}
</div>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
"use client";
import { useMemo, useState } from "react";
import { useRecommendedRoles } from "@/components/labels";
import { modelFilePaths, recommendFiles } from "@/lib/recommend";
/**
* Companion files (template, MTP, mmproj, …) for the model weights in `picked`, per the
* "Recommended files" setting. They count as selected unless the user unchecked them (`dismissed`),
* and drop out by themselves when the model file they belong to is deselected.
*/
export function useRecommended(
files: { path: string; size: number }[],
picked: Iterable<string>,
options: { isExcluded?: (path: string) => boolean; have?: string[] } = {},
) {
const { isExcluded, have } = options;
const roles = useRecommendedRoles();
const [dismissed, setDismissed] = useState<Set<string>>(new Set());
const pickedList = useMemo(() => [...picked], [picked]);
const all = useMemo(() => {
const already = new Set(pickedList);
return recommendFiles(files, modelFilePaths(pickedList), roles, [...pickedList, ...(have ?? [])]).filter(
(p) => !already.has(p) && !isExcluded?.(p),
);
}, [files, pickedList, roles, isExcluded, have]);
const active = useMemo(() => new Set(all.filter((p) => !dismissed.has(p))), [all, dismissed]);
/** Check or uncheck recommended paths (unchecking remembers the choice). */
function setOn(paths: string[], on: boolean) {
setDismissed((prev) => {
const next = new Set(prev);
for (const p of paths) {
if (on) next.delete(p);
else next.add(p);
}
return next;
});
}
return { all, active, setOn, reset: () => setDismissed(new Set()) };
}
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { DEFAULT_RECOMMENDED_ROLES, quantTag, recommendFiles } from "./recommend";
const f = (path: string, size = 1) => ({ path, size });
// Trimmed from unsloth/Qwen3.8-27B-GGUF and unsloth/Qwen3-8B-GGUF.
const qwen38 = [
f(".gitattributes"),
f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf", 1_369_590_656),
f("Qwen3.8-27B-Q4_0.gguf"),
f("Qwen3.8-27B-UD-Q4_K_XL.gguf"),
f("README.md"),
f("config.json"),
f("imatrix_unsloth.gguf"),
f("mmproj-BF16.gguf", 931_146_432),
f("mmproj-F16.gguf", 927_607_488),
];
const qwen3 = [f("Qwen3-8B-Q4_K_M.gguf"), f("Qwen3-8B-Q8_0.gguf"), f("params"), f("template"), f("config.json"), f("imatrix_unsloth.dat")];
describe("quantTag", () => {
it("reads quant and precision tags", () => {
assert.equal(quantTag("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"), "q4_0");
assert.equal(quantTag("mmproj-F16.gguf"), "f16");
assert.equal(quantTag("Qwen3.8-27B-UD-Q4_K_XL.gguf"), "ud-q4_k_xl");
});
});
describe("recommendFiles", () => {
it("adds the only MTP head and prefers the F16 mmproj", () => {
const rec = recommendFiles(qwen38, ["Qwen3.8-27B-UD-Q4_K_XL.gguf"], DEFAULT_RECOMMENDED_ROLES);
assert.deepEqual(rec.sort(), ["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "mmproj-F16.gguf"]);
});
it("matches the variant with the same quant", () => {
const files = [...qwen38, f("MTP/mtp-Qwen3.8-27B-Q8_0.gguf"), f("Qwen3.8-27B-Q8_0.gguf")];
assert.deepEqual(recommendFiles(files, ["Qwen3.8-27B-Q8_0.gguf"], ["mtp"]), ["MTP/mtp-Qwen3.8-27B-Q8_0.gguf"]);
assert.deepEqual(recommendFiles(files, ["Qwen3.8-27B-Q4_0.gguf"], ["mtp"]), ["MTP/mtp-Qwen3.8-27B-Q4_0.gguf"]);
});
it("adds the chat template, and config only when enabled", () => {
assert.deepEqual(recommendFiles(qwen3, ["Qwen3-8B-Q4_K_M.gguf"], DEFAULT_RECOMMENDED_ROLES), ["template"]);
assert.deepEqual(recommendFiles(qwen3, ["Qwen3-8B-Q4_K_M.gguf"], ["config"]).sort(), ["config.json", "params"]);
});
it("doesn't add a second variant when one is already selected", () => {
assert.deepEqual(recommendFiles(qwen38, ["Qwen3.8-27B-Q4_0.gguf"], ["vision"], ["mmproj-BF16.gguf"]), []);
assert.deepEqual(recommendFiles(qwen38, ["Qwen3.8-27B-Q4_0.gguf", "mmproj-BF16.gguf"], ["vision", "mtp"]), [
"MTP/mtp-Qwen3.8-27B-Q4_0.gguf",
]);
});
it("recommends nothing without picked model files", () => {
assert.deepEqual(recommendFiles(qwen38, [], DEFAULT_RECOMMENDED_ROLES), []);
});
});
+93
View File
@@ -0,0 +1,93 @@
// Files that usually go with the model weights you pick: chat template, MTP head, vision
// projector (mmproj), … Which kinds is a setting. Shared by UI and server (pure functions).
import { groupSplitFiles } from "./file-groups";
import { fileRole, type FileRole } from "./file-roles";
import { quantGroup } from "./selection";
/** File kinds that can be recommended, in display order. */
export const RECOMMENDABLE_ROLES: FileRole[] = ["template", "mtp", "vision", "draft", "config", "tokenizer", "imatrix", "adapter", "docs"];
export const DEFAULT_RECOMMENDED_ROLES: FileRole[] = ["template", "mtp", "vision"];
/** Kinds where a repo has alternatives (one per quant or precision) and one is enough. */
const VARIANT_ROLES = new Set<FileRole>(["mtp", "vision", "draft", "adapter", "imatrix"]);
/** Preferred precision when no variant matches the picked quant. */
const PRECISION_ORDER = ["f16", "bf16", "q8_0", "f32"];
const basename = (p: string) => p.slice(p.lastIndexOf("/") + 1);
const dirname = (p: string) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
/** Quant/precision tag from a file name: "mtp-X-Q4_0.gguf" → "q4_0", "mmproj-F16.gguf" → "f16". */
export function quantTag(path: string): string | null {
const g = quantGroup(basename(path));
return g ? g.replace(/^mmproj-/i, "").toLowerCase() : null;
}
const withoutUd = (q: string) => q.replace(/^ud-/, "");
const bits = (q: string) => q.match(/^(?:ud-)?(?:i?q|tq|bf|f)(\d+)/)?.[1] ?? null;
/**
* Paths to download along with `modelPaths` (model weights), for the given kinds. Variant kinds
* (MTP, mmproj, …) get the variant matching a picked quant, else the best single one; other kinds
* (template, config, …) get every such file at the repo root or next to a picked model file.
* `have`: everything already selected; a variant kind that's already there isn't added again.
*/
export function recommendFiles(
files: { path: string; size: number }[],
modelPaths: string[],
roles: FileRole[],
have: string[] = [],
): string[] {
if (modelPaths.length === 0 || roles.length === 0) return [];
const picked = new Set([...modelPaths, ...have]);
const haveRoles = new Set([...picked].map(fileRole));
const quants = modelPaths.map(quantTag).filter((q): q is string => !!q);
const dirs = new Set(["", ...modelPaths.map(dirname)]);
const out: string[] = [];
for (const role of roles) {
const entries = groupSplitFiles(files.filter((f) => !picked.has(f.path) && fileRole(f.path) === role));
if (entries.length === 0) continue;
if (!VARIANT_ROLES.has(role)) {
for (const e of entries) if (dirs.has(dirname(e.path))) out.push(...e.parts.map((p) => p.path));
continue;
}
if (haveRoles.has(role)) continue; // e.g. an mmproj is already selected
if (entries.length === 1) {
out.push(...entries[0].parts.map((p) => p.path));
continue;
}
const tag = (e: (typeof entries)[number]) => quantTag(e.path) ?? "";
// Same quant as a picked model file (ignoring unsloth's "UD-" prefix): take those.
const same = entries.filter((e) => quants.some((q) => withoutUd(q) === withoutUd(tag(e))));
if (same.length > 0) {
for (const e of same) out.push(...e.parts.map((p) => p.path));
continue;
}
// Otherwise one variant: next to the model, then preferred precision, then same bit width, then smallest.
const pickedBits = new Set(quants.map(bits).filter(Boolean));
const score = (e: (typeof entries)[number]) => {
const t = tag(e);
const precision = PRECISION_ORDER.indexOf(t);
return [
dirs.has(dirname(e.path)) && dirname(e.path) !== "" ? 0 : 1,
precision === -1 ? PRECISION_ORDER.length : precision,
pickedBits.has(bits(t)) ? 0 : 1,
e.size,
];
};
const best = [...entries].sort((a, b) => {
const sa = score(a);
const sb = score(b);
for (let i = 0; i < sa.length; i++) if (sa[i] !== sb[i]) return sa[i] - sb[i];
return 0;
})[0];
out.push(...best.parts.map((p) => p.path));
}
return [...new Set(out)];
}
/** Model-weight paths among `paths`. */
export function modelFilePaths(paths: Iterable<string>): string[] {
return [...paths].filter((p) => fileRole(p) === "model");
}
+17
View File
@@ -4,6 +4,7 @@ import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { isLabelColor } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
const FILE_ROLES_KEY = "labels.fileRoles";
export const FILE_ROLE_LABEL_MAX = 24;
@@ -67,3 +68,19 @@ export async function saveFileRoleStyles(input: Record<string, { label?: unknown
await write(FILE_ROLES_KEY, stored);
return getFileRoleStyles();
}
const RECOMMENDED_KEY = "downloads.recommendedRoles";
/** File kinds picked automatically along with model weights (Settings → Downloads). */
export async function getRecommendedRoles(): Promise<FileRole[]> {
const stored = await read<unknown>(RECOMMENDED_KEY);
if (!Array.isArray(stored)) return DEFAULT_RECOMMENDED_ROLES;
return RECOMMENDABLE_ROLES.filter((r) => stored.includes(r));
}
export async function saveRecommendedRoles(roles: string[]): Promise<FileRole[]> {
const unknown = roles.find((r) => !RECOMMENDABLE_ROLES.includes(r as FileRole));
if (unknown) throw new SettingsError(`"${unknown}" can't be recommended.`);
await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r)));
return getRecommendedRoles();
}