Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(local-models): Hugging Face — browse GGUF repositories and pull a quantization
rubenluetke10-beep150ec0c6d9c7
diff --git a/jarvis/ui/web/frontend/src/views/local-models/HuggingFacePanel.test.tsx b/jarvis/ui/web/frontend/src/views/local-models/HuggingFacePanel.test.tsxnew file mode 100644index 0000000000..8b2c3766e3--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/HuggingFacePanel.test.tsx@@ -0,0 +1,368 @@+/**+ * HuggingFacePanel — off by default, browse when on, pull one quantization.+ *+ * No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().+ */+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { mockState } = vi.hoisted(() => ({+ mockState: { setActiveSection: vi.fn() },+}));++vi.mock("@/store/events", () => ({+ useEventStore: (selector: (s: typeof mockState) => unknown) =>+ selector(mockState),+}));++vi.mock("@/i18n", () => ({+ // Identity translator: assertions match the keys themselves.+ useT: () => (key: string) => key,+ useUiLanguage: () => "en",+}));++const openExternalUrl = vi.fn();+vi.mock("@/lib/openExternal", () => ({+ openExternalUrl: (url: string) => openExternalUrl(url),+}));++import {+ HuggingFacePanel,+ formatContext,+ formatParams,+} from "./HuggingFacePanel";++const BASE = "/api/providers/ollama/local-models";++const REPO = {+ id: "unsloth/Qwen3.8-27B-GGUF",+ author: "unsloth",+ downloads: 123456,+ likes: 42,+ last_modified: "2026-08-20T10:00:00Z",+ architecture: "qwen3",+ total_params: 27_000_000_000,+ context_length: 262144,+};++const FILES = [+ {+ filename: "Qwen3.8-27B-Q4_K_M.gguf",+ quant: "Q4_K_M",+ size_gb: 16.5,+ fit: "comfortable",+ fit_note: "",+ },+ {+ filename: "Qwen3.8-27B-Q8_0.gguf",+ quant: "Q8_0",+ size_gb: 28.9,+ fit: "tight",+ fit_note: "Needs more memory than this machine has free.",+ },+];++type Answer = { ok?: boolean; status?: number; body: unknown };++function installFetch(+ routes: (url: string, method: string, body: unknown) => Answer | undefined,+) {+ let enabled = false;+ const fetchMock = vi.fn(+ async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ const body = init?.body ? JSON.parse(String(init.body)) : undefined;+ if (url === `${BASE}/hf/enabled` && method === "GET") {+ return { ok: true, status: 200, json: async () => ({ enabled }) };+ }+ if (url === `${BASE}/hf/enabled` && method === "PUT") {+ enabled = Boolean((body as { enabled: boolean }).enabled);+ return { ok: true, status: 200, json: async () => ({ enabled }) };+ }+ const hit = routes(url, method, body);+ if (!hit) throw new Error(`unexpected fetch ${method} ${url}`);+ return {+ ok: hit.ok ?? true,+ status: hit.status ?? 200,+ json: async () => hit.body,+ };+ },+ );+ vi.stubGlobal("fetch", fetchMock);+ return { fetchMock, setEnabled: (v: boolean) => (enabled = v) };+}++function renderPanel() {+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return render(+ <QueryClientProvider client={qc}>+ <HuggingFacePanel providerId="ollama" />+ </QueryClientProvider>,+ );+}++async function typeAndSettle(text: string) {+ fireEvent.change(screen.getByRole("textbox"), { target: { value: text } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(400);+ });+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ mockState.setActiveSection = vi.fn();+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe("HuggingFacePanel", () => {+ it("starts off, shows only the toggle sentence and makes no browse request", async () => {+ const { fetchMock } = installFetch(() => undefined);+ renderPanel();++ await waitFor(() =>+ expect(screen.getByTestId("hf-enabled-switch")).toBeTruthy(),+ );+ expect(+ screen.getByText("local_models.huggingface.toggle_sentence"),+ ).toBeTruthy();+ expect(screen.queryByRole("textbox")).toBeNull();+ const urls = fetchMock.mock.calls.map((c) => String(c[0]));+ expect(urls.every((u) => u === `${BASE}/hf/enabled`)).toBe(true);+ });++ it("switching on writes hf/enabled and reveals search, sort chips and the notes", async () => {+ const { fetchMock } = installFetch(() => undefined);+ renderPanel();++ const toggle = await screen.findByTestId("hf-enabled-switch");+ fireEvent.click(toggle);++ await waitFor(() => expect(screen.getByRole("textbox")).toBeTruthy());+ const put = fetchMock.mock.calls.find(+ (c) => (c[1] as RequestInit | undefined)?.method === "PUT",+ );+ expect(put).toBeTruthy();+ expect(JSON.parse(String((put![1] as RequestInit).body))).toEqual({+ enabled: true,+ });++ expect(+ screen.getByRole("tab", {+ name: "local_models.huggingface.sort_downloads",+ }),+ ).toBeTruthy();+ expect(+ screen.getByRole("tab", { name: "local_models.huggingface.sort_newest" }),+ ).toBeTruthy();+ expect(+ screen.getByRole("tab", {+ name: "local_models.huggingface.sort_trending",+ }),+ ).toBeTruthy();+ expect(+ screen.getByText("local_models.huggingface.empty_query"),+ ).toBeTruthy();+ expect(+ screen.getByText("local_models.huggingface.token_note"),+ ).toBeTruthy();+ expect(+ screen.getByText("local_models.huggingface.private_hint"),+ ).toBeTruthy();++ fireEvent.click(screen.getByText("local_models.huggingface.token_link"));+ expect(mockState.setActiveSection).toHaveBeenCalledWith("apikeys");+ fireEvent.click(screen.getByText("hf.co/settings/keys"));+ expect(openExternalUrl).toHaveBeenCalledWith(+ "https://huggingface.co/settings/keys",+ );+ });++ it("searches with the chosen sort, expands a repository and pulls a quantization with inline progress", async () => {+ let polls = 0;+ const { fetchMock, setEnabled } = installFetch((url, method) => {+ if (url.startsWith(`${BASE}/hf/search?`))+ return { body: { repos: [REPO], error: null } };+ if (url === `${BASE}/hf/unsloth/Qwen3.8-27B-GGUF/files`)+ return { body: { files: FILES, error: null } };+ if (url === `${BASE}/hf/pull` && method === "POST")+ return {+ body: {+ state: "running",+ model: "hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M",+ message: "",+ percent: 0,+ },+ };+ if (url.startsWith("/api/providers/ollama/pull/status?")) {+ polls += 1;+ return {+ body:+ polls < 2+ ? {+ state: "running",+ model: "hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M",+ message: "pulling",+ percent: 42,+ }+ : {+ state: "done",+ model: "hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M",+ message: "Installed.",+ percent: 100,+ },+ };+ }+ return undefined;+ });+ setEnabled(true);+ renderPanel();++ await screen.findByRole("textbox");+ fireEvent.click(+ screen.getByRole("tab", { name: "local_models.huggingface.sort_newest" }),+ );+ await typeAndSettle("qwen3.8");++ await waitFor(() =>+ expect(screen.getByTestId(`hf-repo-${REPO.id}`)).toBeTruthy(),+ );+ const searchUrl = fetchMock.mock.calls+ .map((c) => String(c[0]))+ .find((u) => u.includes("/hf/search?"));+ expect(searchUrl).toContain("q=qwen3.8");+ expect(searchUrl).toContain("sort=lastModified");+ // Row facts: author, architecture, params, context.+ expect(screen.getByText("unsloth")).toBeTruthy();+ expect(screen.getByText("qwen3")).toBeTruthy();+ expect(+ screen.getByText("local_models.huggingface.col_params 27B"),+ ).toBeTruthy();+ expect(+ screen.getByText("local_models.huggingface.col_context 256K"),+ ).toBeTruthy();++ fireEvent.click(+ screen.getByRole("button", { name: /unsloth\/Qwen3\.8-27B-GGUF/ }),+ );+ await waitFor(() =>+ expect(+ screen.getByTestId("hf-file-Qwen3.8-27B-Q4_K_M.gguf"),+ ).toBeTruthy(),+ );+ expect(screen.getByText("Q8_0")).toBeTruthy();+ expect(screen.getByText("16.50 GB")).toBeTruthy();+ expect(screen.getByText("local_models.huggingface.fit_tight")).toBeTruthy();+ expect(+ screen.getByText("Needs more memory than this machine has free."),+ ).toBeTruthy();++ fireEvent.click(+ screen.getByRole("button", {+ name: "local_models.huggingface.pull Q4_K_M",+ }),+ );+ await waitFor(() => {+ const post = fetchMock.mock.calls.find(+ (c) => String(c[0]) === `${BASE}/hf/pull`,+ );+ expect(post).toBeTruthy();+ expect(JSON.parse(String((post![1] as RequestInit).body))).toEqual({+ user: "unsloth",+ repo: "Qwen3.8-27B-GGUF",+ quant: "Q4_K_M",+ });+ });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(2600);+ });+ await waitFor(() => expect(screen.getByText(/42%/)).toBeTruthy());+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2600);+ });+ await waitFor(() => expect(screen.getByText("Installed.")).toBeTruthy());+ expect(+ screen.getByText("local_models.huggingface.pull_again"),+ ).toBeTruthy();+ const statusUrl = fetchMock.mock.calls+ .map((c) => String(c[0]))+ .find((u) => u.includes("/pull/status?"));+ expect(statusUrl).toContain(+ encodeURIComponent("hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M"),+ );+ });++ it("shows the backend's rate-limit sentence instead of an empty list", async () => {+ const { setEnabled } = installFetch((url) => {+ if (url.startsWith(`${BASE}/hf/search?`))+ return {+ body: {+ repos: [],+ error: "Hugging Face is rate-limiting this address for 5 minutes.",+ },+ };+ return undefined;+ });+ setEnabled(true);+ renderPanel();+ await screen.findByRole("textbox");+ await typeAndSettle("llama");+ await waitFor(() =>+ expect(+ screen.getByText(+ "Hugging Face is rate-limiting this address for 5 minutes.",+ ),+ ).toBeTruthy(),+ );+ });++ it("shows the 404 sentence when the backend says browsing is off", async () => {+ const { setEnabled } = installFetch((url) => {+ if (url.startsWith(`${BASE}/hf/search?`))+ return {+ ok: false,+ status: 404,+ body: { detail: "Hugging Face browsing is switched off." },+ };+ return undefined;+ });+ setEnabled(true);+ renderPanel();+ await screen.findByRole("textbox");+ await typeAndSettle("llama");+ await waitFor(() =>+ expect(+ screen.getByText("Hugging Face browsing is switched off."),+ ).toBeTruthy(),+ );+ });+});++describe("formatters", () => {+ it("abbreviate parameters and context the way the hub does", () => {+ expect(formatParams(null)).toBe("—");+ expect(formatParams(8_030_000_000)).toBe("8B");+ expect(formatParams(1_500_000_000)).toBe("1.5B");+ expect(formatParams(540_000_000)).toBe("540M");+ expect(formatContext(null)).toBe("—");+ expect(formatContext(131072)).toBe("128K");+ expect(formatContext(512)).toBe("512");+ });+});diff --git a/jarvis/ui/web/frontend/src/views/local-models/HuggingFacePanel.tsx b/jarvis/ui/web/frontend/src/views/local-models/HuggingFacePanel.tsxnew file mode 100644index 0000000000..2e4140bc3f--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/local-models/HuggingFacePanel.tsx@@ -0,0 +1,589 @@+/**+ * Hugging Face — browse public GGUF repositories and pull one quantization.+ *+ * Off by default: the first thing on the panel is the switch that writes+ * `[brain.providers.ollama].hf_enabled`. While it is off the backend answers+ * every browse route with a 404 sentence, and the panel makes no outbound+ * request at all — an install that wants no Hugging Face traffic gets none.+ *+ * When on: a search field with three sort chips, a hairline ledger of+ * repositories (id, author, architecture, parameters, context, downloads,+ * updated) and, per expanded row, the `.gguf` files with quantization, size,+ * fit verdict and a Pull button. A pull posts `hf/pull`, then polls the+ * existing pull-status route until it finishes; progress shows inline on the+ * file row. The optional token is NOT collected here — the note points to the+ * API Keys screen — and private repositories get the SSH-key hint sentence.+ *+ * Props: `providerId` — the id of the pull-capable provider card (the panel is+ * gated on the capability by its caller, never on a provider name).+ */+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { ChevronDown, ExternalLink, KeyRound } from "lucide-react";++import {+ EmptyRow,+ InlineSearch,+ SegmentedFilter,+ SoftButton,+ StatusDot,+ formatShortDate,+} from "@/components/extensions/primitives";+import { Switch } from "@/components/ui/switch";+import {+ hfPullName,+ modelPullStatus,+ useHfEnabled,+ useHfFiles,+ useHfSearch,+ useInvalidateLocalModels,+ useSetHfEnabled,+ useStartHfPull,+ type HfFile,+ type HfRepo,+ type HfSort,+ type ModelPullProgress,+} from "@/hooks/useLocalModels";+import { useT, useUiLanguage } from "@/i18n";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";++const HF_KEYS_URL = "https://huggingface.co/settings/keys";+const HF_REPO_URL = "https://huggingface.co/";+const SEARCH_DEBOUNCE_MS = 350;+const PULL_POLL_MS = 2500;++const EYEBROW = "text-[11px] uppercase tracking-[0.18em] text-muted-foreground";++/** "8.03B" / "27B" / "540M" — the way Hugging Face itself abbreviates. */+export function formatParams(total: number | null): string {+ if (total === null || !Number.isFinite(total) || total <= 0) return "—";+ if (total >= 1e12) return `${(total / 1e12).toFixed(1).replace(/\.0$/, "")}T`;+ if (total >= 1e9) return `${(total / 1e9).toFixed(1).replace(/\.0$/, "")}B`;+ if (total >= 1e6) return `${Math.round(total / 1e6)}M`;+ return String(total);+}++/** "128K" / "32K" / "4096" for the context window. */+export function formatContext(ctx: number | null): string {+ if (ctx === null || !Number.isFinite(ctx) || ctx <= 0) return "—";+ return ctx >= 1024 ? `${Math.round(ctx / 1024)}K` : String(ctx);+}++function formatCount(n: number, locale: string): string {+ try {+ return new Intl.NumberFormat(locale, {+ notation: "compact",+ maximumFractionDigits: 1,+ }).format(n);+ } catch {+ return String(n);+ }+}++function formatSize(gb: number | null, t: (k: string) => string): string {+ if (gb === null || !Number.isFinite(gb))+ return t("local_models.huggingface.size_unknown");+ return `${gb.toFixed(2)} GB`;+}++/** Split "user/repo" once; anything else is not a repository id. */+function splitRepoId(id: string): { user: string; repo: string } | null {+ const idx = id.indexOf("/");+ if (idx <= 0 || idx === id.length - 1) return null;+ return { user: id.slice(0, idx), repo: id.slice(idx + 1) };+}++type PullState = { progress: ModelPullProgress | null; error: string | null };++export function HuggingFacePanel({ providerId }: { providerId: string }) {+ const t = useT();+ const locale = useUiLanguage();+ const setActiveSection = useEventStore((s) => s.setActiveSection);++ const enabledQuery = useHfEnabled(providerId);+ const setEnabled = useSetHfEnabled(providerId);+ const enabled = enabledQuery.data?.enabled === true;++ const [query, setQuery] = useState("");+ const [debounced, setDebounced] = useState("");+ const [sort, setSort] = useState<HfSort>("downloads");+ const [openRepo, setOpenRepo] = useState<string | null>(null);++ useEffect(() => {+ const timer = window.setTimeout(+ () => setDebounced(query.trim()),+ SEARCH_DEBOUNCE_MS,+ );+ return () => window.clearTimeout(timer);+ }, [query]);++ const search = useHfSearch(providerId, debounced, sort, enabled);++ // One pull at a time per panel, keyed by the exact pull name so the progress+ // lands on the file row that started it.+ const [pulls, setPulls] = useState<Record<string, PullState>>({});+ const startPull = useStartHfPull(providerId);+ const invalidate = useInvalidateLocalModels(providerId);+ const pollTimers = useRef<Record<string, number>>({});++ useEffect(() => {+ const timers = pollTimers.current;+ return () => {+ Object.values(timers).forEach((id) => window.clearInterval(id));+ };+ }, []);++ const poll = useCallback(+ (name: string) => {+ if (pollTimers.current[name]) return;+ const timer = window.setInterval(async () => {+ try {+ const next = await modelPullStatus(providerId, name);+ setPulls((prev) => ({+ ...prev,+ [name]: { progress: next, error: null },+ }));+ if (next.state === "done" || next.state === "error") {+ window.clearInterval(timer);+ delete pollTimers.current[name];+ if (next.state === "done") invalidate();+ }+ } catch (err) {+ window.clearInterval(timer);+ delete pollTimers.current[name];+ setPulls((prev) => ({+ ...prev,+ [name]: {+ progress: null,+ error: err instanceof Error ? err.message : String(err),+ },+ }));+ }+ }, PULL_POLL_MS);+ pollTimers.current[name] = timer;+ },+ [providerId, invalidate],+ );++ const pull = useCallback(+ async (user: string, repo: string, quant: string | null) => {+ const name = hfPullName(user, repo, quant);+ setPulls((prev) => ({+ ...prev,+ [name]: { progress: null, error: null },+ }));+ try {+ const started = await startPull.mutateAsync({ user, repo, quant });+ setPulls((prev) => ({+ ...prev,+ [name]: { progress: started, error: null },+ }));+ if (started.state === "done") invalidate();+ else if (started.state === "running") poll(name);+ } catch (err) {+ setPulls((prev) => ({+ ...prev,+ [name]: {+ progress: null,+ error: err instanceof Error ? err.message : String(err),+ },+ }));+ }+ },+ [startPull, poll, invalidate],+ );++ const sortOptions = useMemo(+ () => [+ {+ id: "downloads" as const,+ label: t("local_models.huggingface.sort_downloads"),+ },+ {+ id: "lastModified" as const,+ label: t("local_models.huggingface.sort_newest"),+ },+ {+ id: "trendingScore" as const,+ label: t("local_models.huggingface.sort_trending"),+ },+ ],+ [t],+ );++ const toggleError =+ setEnabled.error instanceof Error ? setEnabled.error.message : null;+ const readError =+ enabledQuery.error instanceof Error ? enabledQuery.error.message : null;++ // The backend's own sentence (429, offline, 404 while off) beats a generic one.+ const searchError =+ search.data?.error ??+ (search.error instanceof Error ? search.error.message : null);+ const repos = search.data?.repos ?? [];++ return (+ <div className="space-y-4" data-testid="huggingface-panel">+ {/* Enable row */}+ <div className="flex items-start justify-between gap-4 rounded-xl border border-border bg-card/60 px-4 py-3">+ <div className="min-w-0">+ <div className={EYEBROW}>+ {t("local_models.huggingface.toggle_label")}+ </div>+ <p className="mt-1 text-sm text-foreground">+ {t("local_models.huggingface.toggle_sentence")}+ </p>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {t("local_models.huggingface.toggle_hint")}+ </p>+ {(toggleError || readError) && (+ <p className="mt-1 text-xs text-destructive" role="alert">+ {toggleError ?? readError}+ </p>+ )}+ </div>+ <Switch+ checked={enabled}+ disabled={enabledQuery.isLoading || setEnabled.isPending}+ aria-label={t("local_models.huggingface.toggle_label")}+ data-testid="hf-enabled-switch"+ onCheckedChange={(next) => setEnabled.mutate(next)}+ />+ </div>++ {enabled && (+ <>+ {/* Search + sort */}+ <div className="flex flex-wrap items-center gap-3">+ <div className="min-w-[220px] flex-1">+ <InlineSearch+ value={query}+ onChange={setQuery}+ placeholder={t("local_models.huggingface.search_placeholder")}+ />+ </div>+ <SegmentedFilter<HfSort>+ label={t("local_models.huggingface.sort_label")}+ value={sort}+ onChange={setSort}+ options={sortOptions}+ />+ </div>++ {/* Results */}+ {debounced.length === 0 ? (+ <EmptyRow>{t("local_models.huggingface.empty_query")}</EmptyRow>+ ) : searchError ? (+ <EmptyRow>+ <span role="alert">{searchError}</span>+ </EmptyRow>+ ) : search.isLoading ? (+ <EmptyRow>{t("local_models.huggingface.searching")}</EmptyRow>+ ) : repos.length === 0 ? (+ <EmptyRow>{t("local_models.huggingface.no_results")}</EmptyRow>+ ) : (+ <div+ className="divide-y divide-border/70 overflow-hidden rounded-xl border border-border bg-card/60"+ data-testid="hf-repo-list"+ >+ {repos.map((repo) => (+ <RepoRow+ key={repo.id}+ repo={repo}+ open={openRepo === repo.id}+ onToggle={() =>+ setOpenRepo((cur) => (cur === repo.id ? null : repo.id))+ }+ providerId={providerId}+ pulls={pulls}+ onPull={pull}+ locale={locale}+ t={t}+ />+ ))}+ </div>+ )}++ {/* Token note + private-repo hint */}+ <div className="space-y-2 rounded-xl border border-border bg-card/60 px-4 py-3">+ <div className={EYEBROW}>+ {t("local_models.huggingface.notes_label")}+ </div>+ <p className="text-xs text-muted-foreground">+ {t("local_models.huggingface.token_note")}{" "}+ <button+ type="button"+ onClick={() => setActiveSection("apikeys")}+ className="inline-flex items-center gap-1 text-foreground/90 underline-offset-2 hover:underline"+ >+ <KeyRound className="h-3 w-3" />+ {t("local_models.huggingface.token_link")}+ </button>+ </p>+ <p className="text-xs text-muted-foreground">+ {t("local_models.huggingface.private_hint")}{" "}+ <button+ type="button"+ onClick={() => void openExternalUrl(HF_KEYS_URL)}+ className="inline-flex items-center gap-1 text-foreground/90 underline-offset-2 hover:underline"+ >+ <ExternalLink className="h-3 w-3" />+ hf.co/settings/keys+ </button>+ </p>+ </div>+ </>+ )}+ </div>+ );+}++function RepoRow({+ repo,+ open,+ onToggle,+ providerId,+ pulls,+ onPull,+ locale,+ t,+}: {+ repo: HfRepo;+ open: boolean;+ onToggle: () => void;+ providerId: string;+ pulls: Record<string, PullState>;+ onPull: (user: string, repo: string, quant: string | null) => void;+ locale: string;+ t: (k: string) => string;+}) {+ const parts = splitRepoId(repo.id);+ return (+ <div data-testid={`hf-repo-${repo.id}`}>+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={open}+ className="flex w-full items-center gap-3 px-3.5 py-3 text-left transition-colors hover:bg-sheen/[0.05]"+ >+ <ChevronDown+ className={cn(+ "h-4 w-4 shrink-0 text-muted-foreground transition-transform",+ open && "rotate-180",+ )}+ />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium text-foreground">+ {repo.id}+ </div>+ <div className="mt-0.5 flex flex-wrap gap-x-4 gap-y-0.5 text-xs text-muted-foreground tabular-nums">+ <span>{repo.author || "—"}</span>+ <span>+ {repo.architecture || t("local_models.huggingface.arch_unknown")}+ </span>+ <span>+ {t("local_models.huggingface.col_params")}{" "}+ {formatParams(repo.total_params)}+ </span>+ <span>+ {t("local_models.huggingface.col_context")}{" "}+ {formatContext(repo.context_length)}+ </span>+ </div>+ </div>+ <div className="hidden shrink-0 text-right text-xs text-muted-foreground tabular-nums sm:block">+ <div>+ {formatCount(repo.downloads, locale)}{" "}+ {t("local_models.huggingface.col_downloads")}+ </div>+ <div>+ {t("local_models.huggingface.col_updated")}{" "}+ {formatShortDate(repo.last_modified || null, locale)}+ </div>+ </div>+ </button>+ {open && parts && (+ <FileList+ providerId={providerId}+ user={parts.user}+ repo={parts.repo}+ pulls={pulls}+ onPull={onPull}+ t={t}+ />+ )}+ </div>+ );+}++function FileList({+ providerId,+ user,+ repo,+ pulls,+ onPull,+ t,+}: {+ providerId: string;+ user: string;+ repo: string;+ pulls: Record<string, PullState>;+ onPull: (user: string, repo: string, quant: string | null) => void;+ t: (k: string) => string;+}) {+ const files = useHfFiles(providerId, user, repo);+ const error =+ files.data?.error ??+ (files.error instanceof Error ? files.error.message : null);+ const rows = files.data?.files ?? [];++ return (+ <div+ className="border-t border-border/70 bg-background/40 px-3.5 py-2"+ data-testid="hf-file-list"+ >+ {files.isLoading ? (+ <p className="py-2 text-xs text-muted-foreground">+ {t("local_models.huggingface.loading_files")}+ </p>+ ) : error ? (+ <p className="py-2 text-xs text-destructive" role="alert">+ {error}+ </p>+ ) : rows.length === 0 ? (+ <p className="py-2 text-xs text-muted-foreground">+ {t("local_models.huggingface.no_files")}+ </p>+ ) : (+ <div className="divide-y divide-border/50">+ {rows.map((file) => (+ <FileRow+ key={file.filename}+ file={file}+ state={pulls[hfPullName(user, repo, file.quant)]}+ onPull={() => onPull(user, repo, file.quant)}+ t={t}+ />+ ))}+ </div>+ )}+ <p className="pt-2 text-[11px] text-muted-foreground">+ <button+ type="button"+ onClick={() => void openExternalUrl(`${HF_REPO_URL}${user}/${repo}`)}+ className="inline-flex items-center gap-1 underline-offset-2 hover:underline"+ >+ <ExternalLink className="h-3 w-3" />+ {t("local_models.huggingface.open_repo")}+ </button>+ </p>+ </div>+ );+}++function FileRow({+ file,+ state,+ onPull,+ t,+}: {+ file: HfFile;+ state: PullState | undefined;+ onPull: () => void;+ t: (k: string) => string;+}) {+ const progress = state?.progress ?? null;+ const running =+ progress?.state === "running" ||+ (state !== undefined && progress === null && !state.error);+ const done = progress?.state === "done";+ const failed = progress?.state === "error" || Boolean(state?.error);+ const percent =+ typeof progress?.percent === "number"+ ? Math.max(0, Math.min(100, Math.round(progress.percent)))+ : null;++ return (+ <div+ className="flex items-center gap-3 py-2"+ data-testid={`hf-file-${file.filename}`}+ >+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-x-3 text-sm">+ <span className="font-medium tabular-nums text-foreground">+ {file.quant ?? t("local_models.huggingface.quant_default")}+ </span>+ <span className="text-xs text-muted-foreground tabular-nums">+ {formatSize(file.size_gb, t)}+ </span>+ <span+ className={cn(+ "text-xs",+ file.fit === "tight"+ ? "text-amber-600 dark:text-amber-400"+ : file.fit === "comfortable"+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-muted-foreground",+ )}+ >+ {t(`local_models.huggingface.fit_${file.fit}`)}+ </span>+ </div>+ <div className="truncate text-[11px] text-muted-foreground">+ {file.filename}+ </div>+ {file.fit === "tight" && file.fit_note && (+ <div className="text-[11px] text-amber-600 dark:text-amber-400">+ {file.fit_note}+ </div>+ )}+ {running && (+ <div className="mt-1 flex items-center gap-2">+ <div className="h-1 w-40 overflow-hidden rounded-full bg-muted-foreground/20">+ <div+ className="h-full bg-primary transition-[width]"+ style={{ width: `${percent ?? 5}%` }}+ />+ </div>+ <span className="text-[11px] text-muted-foreground tabular-nums">+ {percent !== null+ ? `${percent}%`+ : t("local_models.huggingface.pull_starting")}+ {progress?.message ? ` · ${progress.message}` : ""}+ </span>+ </div>+ )}+ {done && (+ <div className="mt-1">+ <StatusDot+ tone="ok"+ label={+ progress?.message || t("local_models.huggingface.pull_done")+ }+ />+ </div>+ )}+ {failed && (+ <div className="mt-1 text-[11px] text-destructive" role="alert">+ {state?.error ??+ progress?.message ??+ t("local_models.huggingface.pull_failed")}+ </div>+ )}+ </div>+ <SoftButton+ onClick={onPull}+ disabled={running}+ primary={!done}+ ariaLabel={`${t("local_models.huggingface.pull")} ${file.quant ?? file.filename}`}+ >+ {done+ ? t("local_models.huggingface.pull_again")+ : running+ ? t("local_models.huggingface.pulling")+ : t("local_models.huggingface.pull")}+ </SoftButton>+ </div>+ );+}