Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(web): add the Local models settings page
Dongdong Chen00f9b2db5781
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 251ca02b..5af5f5d8 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -19,6 +19,14 @@ build:assets` to check the initial JS budget.- `src/app`: routes, providers, route error boundaries, and global CSS.- `src/features/teamhub`: Human API, Session, error, and realtime adapters.- `src/features/rooms`: Room routes, Chat, Timeline, the right sidebar (Agent Info, Activity, Thread, Document) and membership UI.+- `src/features/local-models`: Settings › Local models (`settings/local-models?computer=<id>`),+ one Computer's model library as TeamHub last stored it. The Computer decides+ fit, availability, placement, the recommendation and memory; the page only+ orders and labels them, picks the Make room default, and maps every code to+ English in `local-models-copy.ts`. Without `?computer=` the desktop app opens+ its own Computer. Only the Computer's owner can act; actions return at once+ and progress arrives as `local-models` invalidation hints. A Computer's+ detail on the Computers page links here and reads no model state itself.- `src/test`: unit-test support, including the in-process TeamHub test server.- `e2e`: Playwright product workflows; every spec runs on the real TeamHub andDocument Runtime stack (`make check-e2e-room-document`).diff --git a/apps/web/src/app/router.tsx b/apps/web/src/app/router.tsxindex 432cf8e6..8f2daff5 100644--- a/apps/web/src/app/router.tsx+++ b/apps/web/src/app/router.tsx@@ -710,6 +710,13 @@ function createSettingsRoute(): RouteObject {}),path: "computers",},+ {+ lazy: async () => ({+ Component: (await import("@/features/local-models/local-models-page"))+ .LocalModelsPage,+ }),+ path: "local-models",+ },{ loader: openProfile, path: "administration" },],ErrorBoundary: PanelRouteErrorSurface,diff --git a/apps/web/src/components/ui/form-feedback.tsx b/apps/web/src/components/ui/form-feedback.tsxindex e358ea2b..8f3f8102 100644--- a/apps/web/src/components/ui/form-feedback.tsx+++ b/apps/web/src/components/ui/form-feedback.tsx@@ -1,4 +1,5 @@import {+ Alert02Icon,AlertCircleIcon,CheckmarkCircle02Icon,InformationCircleIcon,@@ -7,7 +8,7 @@ import type { ReactNode } from "react";import { Icon, type IconSvgElement } from "@/components/ui/icon";-type FormFeedbackTone = "danger" | "info" | "success";+type FormFeedbackTone = "danger" | "info" | "success" | "warning";const feedbackStyle: Record<FormFeedbackTone,@@ -31,6 +32,12 @@ const feedbackStyle: Record<icon: CheckmarkCircle02Icon,role: "status",},+ warning: {+ className:+ "border-[var(--app-status-warning-border)] bg-[var(--app-status-warning-surface)] text-[var(--app-status-warning-text)]",+ icon: Alert02Icon,+ role: "status",+ },};export function FormFeedback({diff --git a/apps/web/src/features/local-computer/computer-detail.tsx b/apps/web/src/features/local-computer/computer-detail.tsxindex 40e34e13..72d40e22 100644--- a/apps/web/src/features/local-computer/computer-detail.tsx+++ b/apps/web/src/features/local-computer/computer-detail.tsx@@ -1,6 +1,7 @@import {Activity01Icon,Add01Icon,+ AiChipIcon,ArrowDown01Icon,ArrowRight01Icon,Delete02Icon,@@ -17,6 +18,7 @@ import {Tick02Icon,} from "@hugeicons/core-free-icons";import { type ReactNode, useState } from "react";+import { Link } from "react-router";import { Button } from "@/components/ui/button";import { Icon, type IconSvgElement } from "@/components/ui/icon";@@ -68,6 +70,7 @@ export function ComputerDetail({agents,browserConnection,computer: latestComputer,+ localModelsHref,onConnect,onOpenAgent,onRemove,@@ -77,6 +80,8 @@ export function ComputerDetail({/** The browser status as a progress chip or an Access row; the page owns its TeamHub reads. */browserConnection?: (variant: "chip" | "row") => ReactNode;computer: LocalComputer;+ /** Where this Computer's Local models page is; the page owns the route. */+ localModelsHref?: string;onConnect?: () => void;onOpenAgent: (actorId: string) => void;onRemove?: () => void;@@ -153,6 +158,31 @@ export function ComputerDetail({/>))}</Group>+ {localModelsHref ? (+ <Group title="Local models">+ <Link+ className="flex min-h-14 w-full items-center gap-3 rounded-lg py-2 pr-2.5 pl-2 transition-colors duration-150 hover:bg-sidebar-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring motion-reduce:transition-none"+ to={localModelsHref}+ >+ <RowMark>+ <Icon icon={AiChipIcon} size={20} />+ </RowMark>+ <span className="min-w-0 flex-1 text-left">+ <span className="block truncate text-sm text-foreground">+ Manage local models+ </span>+ <span className="block truncate text-sm text-muted-foreground">+ Download and load models that run on this computer+ </span>+ </span>+ <Icon+ className="text-muted-foreground/60"+ icon={ArrowRight01Icon}+ size={16}+ />+ </Link>+ </Group>+ ) : null}{displayStatus === "offline" ? null : (<Group defaultOpen={false} title="Access">{browserConnection?.("row")}diff --git a/apps/web/src/features/local-computer/computers-page.test.tsx b/apps/web/src/features/local-computer/computers-page.test.tsxindex 48968424..fdb5416c 100644--- a/apps/web/src/features/local-computer/computers-page.test.tsx+++ b/apps/web/src/features/local-computer/computers-page.test.tsx@@ -28,24 +28,15 @@ import type {TeamHubTenantAgentAvailabilitySnapshot,} from "@/features/teamhub/teamhub-types";+import { tenantLocalModelsQueryKey } from "@/features/local-models/local-models-queries";+import { ComputersPage } from "./computers-page";import { localComputersQueryKey } from "./local-computer-queries";import { publishLocalComputerEnrollment } from "./local-computer-enrollment-events";describe("ComputersPage", () => {- it("manages Computers without fetching or showing background model progress", async () => {- const fixture = await authenticatedFixture();- const getModelProgress = vi.fn().mockResolvedValue({- available: true,- components: [{ component: "embedding", state: "downloading" }],- });- const runtime = {- ...fixture,- client: {- ...fixture.client,- getTenantLocalModelServices: getModelProgress,- },- };+ it("links a Computer to its Local models page without reading its models", async () => {+ const runtime = await authenticatedFixture();const queryClient = renderPage(runtime,"/t/tenant-northstar/computers?computer=computer-offline-lab",@@ -55,20 +46,31 @@ describe("ComputersPage", () => {name: "Offline Lab Mac details",});expect(within(detail).getByRole("status")).toHaveTextContent("Offline");+ expect(+ within(detail).getByRole("link", { name: /Manage local models/ }),+ ).toHaveAttribute(+ "href",+ "/t/tenant-northstar/settings/local-models?computer=computer-offline-lab",+ );fireEvent.click(within(detail).getByRole("button", { name: "Advanced" }));fireEvent.click(within(detail).getByRole("button", { name: "Remove" }));expect(await screen.findByRole("dialog", { name: "Remove Local Computer" }),).toBeVisible();- expect(getModelProgress).not.toHaveBeenCalled();+ // Model downloads and loads live on the Local models page only: the+ // Computers page neither reads nor shows them.+ expect(+ runtime.server.requestsTo(+ "GET",+ "/v0/tenants/{tenantId}/local-computers/{computerId}/local-models",+ ),+ ).toHaveLength(0);expect(- queryClient.getQueryState([- "teamhub",- "tenant-northstar",- "local-model-services",- ]),- ).toBeUndefined();+ queryClient+ .getQueryCache()+ .findAll({ queryKey: tenantLocalModelsQueryKey("tenant-northstar") }),+ ).toHaveLength(0);expect(screen.queryByRole("region", { name: "Background model services" }),).not.toBeInTheDocument();diff --git a/apps/web/src/features/local-computer/computers-page.tsx b/apps/web/src/features/local-computer/computers-page.tsxindex 11418b8f..78574229 100644--- a/apps/web/src/features/local-computer/computers-page.tsx+++ b/apps/web/src/features/local-computer/computers-page.tsx@@ -235,6 +235,7 @@ export function ComputersPage() {)}computer={selectedComputer}key={selectedComputer.computer_id}+ localModelsHref={`/t/${tenantId}/settings/local-models?computer=${encodeURIComponent(selectedComputer.computer_id)}`}onConnect={openSetup}onOpenAgent={(actorId) => {if (!openAgent.isPending) openAgent.mutate(actorId);diff --git a/apps/web/src/features/local-models/local-model-details.tsx b/apps/web/src/features/local-models/local-model-details.tsxnew file mode 100644index 00000000..52b0d3ae--- /dev/null+++ b/apps/web/src/features/local-models/local-model-details.tsx@@ -0,0 +1,256 @@+import { useState, type ReactNode } from "react";+import { Copy01Icon, Tick02Icon } from "@hugeicons/core-free-icons";++import { Button } from "@/components/ui/button";+import { Icon } from "@/components/ui/icon";+import { ModalDialog } from "@/components/ui/modal-dialog";+import { cn } from "@/lib/cn";+import { formatBytes } from "@/lib/format-bytes";++import {+ modelErrorCopy,+ modelNoteCopy,+ unavailableCopy,+} from "./local-models-copy";+import type { LocalModelPool, LocalModelsView } from "./local-models-queries";+import {+ agentNames,+ contextLabel,+ placeName,+ poolFreeBytes,+ poolLabel,+ poolOf,+ type ModelEntry,+} from "./local-models-rules";++/** Category colors from the Nature palette, one per model holding memory. */+const segmentColors = ["bg-rain-500", "bg-lichen-500", "bg-sun-500"] as const;+/** Foundation components hold memory too, but are not models of the list. */+const componentColor = "bg-muted-foreground/40";++function Fact({ label, children }: { label: string; children: ReactNode }) {+ return (+ <div className="flex min-h-10 items-center gap-3 py-1.5 text-sm">+ <span className="w-28 shrink-0 text-muted-foreground">{label}</span>+ <span className="min-w-0 flex-1 text-foreground">{children}</span>+ </div>+ );+}++function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <span className="flex items-center gap-1">+ <code className="min-w-0 truncate font-mono text-xs">{endpoint}</code>+ <Button+ aria-label={`Copy ${name} endpoint`}+ onClick={() => {+ void navigator.clipboard+ ?.writeText(endpoint)+ .then(() => setCopied(true));+ }}+ size="compactIcon"+ tone="ghost"+ >+ <Icon icon={copied ? Tick02Icon : Copy01Icon} size={14} />+ </Button>+ </span>+ );+}++/** Everything about one model on one Computer, shown when its row expands. */+export function ModelFacts({+ entry,+ view,+}: {+ entry: ModelEntry;+ view: LocalModelsView;+}) {+ const { model, status } = entry;+ const onComputer = status !== "available" && status !== "unavailable";+ const pool = poolOf(view, model.pool);+ const plannedPlace =+ status === "available" ? placeName(view, model.pool) : undefined;+ return (+ <div className="divide-y divide-border">+ <Fact label="Version">{model.quant}</Fact>+ <Fact label="Memory">+ {formatBytes(model.memory_bytes)}+ {onComputer && pool+ ? ` on ${poolLabel(view, pool)}`+ : plannedPlace+ ? ` on ${plannedPlace}`+ : ""}+ </Fact>+ <Fact label={onComputer ? "On disk" : "Download"}>+ {formatBytes(model.download_bytes)}+ </Fact>+ <Fact label="Context">{contextLabel(model.context_tokens)}</Fact>+ {model.tokens_per_second ? (+ <Fact label="Speed">+ {Math.round(model.tokens_per_second)} tokens/s+ </Fact>+ ) : null}+ {onComputer ? (+ <Fact label="Used by">+ {entry.used_by.length ? agentNames(entry) : "No Agent yet"}+ </Fact>+ ) : null}+ {model.endpoint ? (+ <Fact label="Endpoint">+ <CopyEndpoint endpoint={model.endpoint.base_url} name={model.name} />+ </Fact>+ ) : null}+ {model.error ? (+ <Fact label="Last load">+ <span className="text-app-danger">+ {modelErrorCopy(model.error.code)}+ </span>+ </Fact>+ ) : null}+ {model.note ? (+ <Fact label="Note">+ <span className="text-app-warning">+ {modelNoteCopy(model.note.code, placeName(view, model.pool))}+ </span>+ </Fact>+ ) : null}+ {status === "unavailable" ? (+ <Fact label="Why not">+ <span className="text-app-danger">+ {unavailableCopy(model.availability.reason)}+ </span>+ </Fact>+ ) : null}+ </div>+ );+}++function PoolBar({+ colorOf,+ pool,+ view,+}: {+ colorOf: (holderId: string) => string;+ pool: LocalModelPool;+ view: LocalModelsView;+}) {+ const label = poolLabel(view, pool);+ // used_bytes is the device's real use; on a shared card other processes+ // hold memory that no holder accounts for.+ const otherBytes = Math.max(+ 0,+ pool.used_bytes -+ pool.holders.reduce((sum, holder) => sum + holder.bytes, 0),+ );+ const width = (bytes: number) =>+ `${pool.total_bytes ? Math.min(100, (bytes / pool.total_bytes) * 100) : 0}%`;+ return (+ <div className="flex min-h-10 items-center gap-3 py-1.5 text-sm">+ <span className="w-28 shrink-0 text-muted-foreground">+ {pool.kind === "gpu" ? `GPU ${pool.gpu_index}` : label}+ </span>+ <span+ aria-label={`${label}: ${formatBytes(pool.used_bytes)} of ${formatBytes(pool.total_bytes)} in use`}+ className="flex h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-muted"+ role="img"+ >+ {pool.holders.map((holder) => (+ <span+ className={cn(+ "h-full border-r-2 border-card last:border-r-0",+ colorOf(holder.id),+ )}+ key={holder.id}+ style={{ width: width(holder.bytes) }}+ title={`${holder.name} · ${formatBytes(holder.bytes)}`}+ />+ ))}+ {otherBytes ? (+ <span+ className="h-full bg-muted-foreground/30"+ style={{ width: width(otherBytes) }}+ title={`Other apps · ${formatBytes(otherBytes)}`}+ />+ ) : null}+ </span>+ <span className="w-24 shrink-0 text-right text-xs whitespace-nowrap tabular-nums text-muted-foreground">+ {formatBytes(poolFreeBytes(pool))} free+ </span>+ </div>+ );+}++/** Memory and hardware of one Computer, for people who want the numbers. */+export function AdvancedDialog({+ onClose,+ view,+}: {+ onClose: () => void;+ view: LocalModelsView;+}) {+ const host = view.computer.host;+ const holders = view.pools.flatMap((pool) => pool.holders);+ const models = holders.filter((holder) => holder.kind === "model");+ const components = holders.filter((holder) => holder.kind === "component");+ const colorOf = (holderId: string) => {+ const index = models.findIndex((holder) => holder.id === holderId);+ return index < 0+ ? componentColor+ : segmentColors[index % segmentColors.length]!;+ };++ return (+ <ModalDialog+ closeOnBackdrop+ description={+ host+ ? [host.os_label, host.engine_label].filter(Boolean).join(" · ")+ : undefined+ }+ onClose={onClose}+ size="md"+ title={`${view.computer.display_name} details`}+ >+ <div className="px-5 py-4">+ <h3 className="mb-1 text-sm font-medium text-muted-foreground">+ Memory+ </h3>+ <div className="divide-y divide-border">+ {view.pools.map((pool) => (+ <PoolBar colorOf={colorOf} key={pool.id} pool={pool} view={view} />+ ))}+ </div>+ {holders.length ? (+ <p className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">+ {[...models, ...components].map((holder) => (+ <span className="flex items-center gap-1.5" key={holder.id}>+ <span+ aria-hidden+ className={cn("size-1.5 rounded-full", colorOf(holder.id))}+ />+ {holder.name}+ </span>+ ))}+ </p>+ ) : null}+ {host ? (+ <>+ <h3 className="mt-5 mb-1 text-sm font-medium text-muted-foreground">+ Hardware+ </h3>+ <div className="divide-y divide-border">+ <Fact label="Memory">{formatBytes(host.ram_total_bytes)}</Fact>+ {host.gpus.map((gpu) => (+ <Fact key={gpu.index} label={`GPU ${gpu.index}`}>+ {gpu.name} · {formatBytes(gpu.total_bytes)}+ </Fact>+ ))}+ <Fact label="Free disk">{formatBytes(host.disk_free_bytes)}</Fact>+ </div>+ </>+ ) : null}+ </div>+ </ModalDialog>+ );+}diff --git a/apps/web/src/features/local-models/local-model-dialogs.tsx b/apps/web/src/features/local-models/local-model-dialogs.tsxnew file mode 100644index 00000000..a7d19a67--- /dev/null+++ b/apps/web/src/features/local-models/local-model-dialogs.tsx@@ -0,0 +1,223 @@+import { useState } from "react";++import { Button } from "@/components/ui/button";+import { FormFeedback } from "@/components/ui/form-feedback";+import { ModalDialog } from "@/components/ui/modal-dialog";+import { sourceCheckClassName } from "@/features/settings/provider-selection-picker";+import { cn } from "@/lib/cn";+import { formatBytes } from "@/lib/format-bytes";++import type { LocalModelsView } from "./local-models-queries";+import {+ agentNames,+ makeRoomSelection,+ makesRoom,+ poolLabel,+ poolOf,+ type LoadCheck,+ type ModelEntry,+} from "./local-models-rules";++/** The amber notice naming the Agents that stop answering. */+function AffectedAgents({+ entry,+ until,+}: {+ entry: ModelEntry;+ until: string;+}) {+ const count = entry.used_by.length;+ return count ? (+ <FormFeedback tone="warning">+ {agentNames(entry)} {count === 1 ? "uses" : "use"} this model and+ can't answer until {until}.+ </FormFeedback>+ ) : (+ <p className="text-sm text-muted-foreground">No Agent uses this model.</p>+ );+}++/** Loading would overfill the pool: offer to unload loaded models first. */+export function MakeRoomDialog({+ check,+ disabled,+ entry,+ onClose,+ onConfirm,+ view,+}: {+ check: LoadCheck;+ /** The model can no longer be loaded, or its Computer took no actions. */+ disabled: boolean;+ entry: ModelEntry;+ onClose: () => void;+ onConfirm: (unloadIds: string[]) => void;+ view: LocalModelsView;+}) {+ const [selected, setSelected] = useState(() => makeRoomSelection(check));+ const chosen = new Set(selected);+ const enough = makesRoom(check, chosen);+ const affected = check.loaded.flatMap((item) =>+ chosen.has(item.model.id) ? item.used_by.map((user) => user.name) : [],+ );++ return (+ <ModalDialog+ description={`${entry.model.name} needs ${formatBytes(check.needBytes)} on ${poolLabel(view, check.pool)}; ${formatBytes(check.freeBytes)} is free.`}+ footer={+ <>+ <Button onClick={onClose}>Cancel</Button>+ <Button+ disabled={disabled || !enough}+ onClick={() => onConfirm(selected)}+ tone="primary"+ >+ {selected.length ? "Unload and load" : "Load"}+ </Button>+ </>+ }+ onClose={onClose}+ size="md"+ title="Make room to load"+ >+ <div className="grid gap-3 px-5 py-4">+ {check.loaded.length ? (+ <fieldset className="grid gap-0.5">+ <legend className="mb-1.5 text-sm text-muted-foreground">+ Unload these to free memory:+ </legend>+ {check.loaded.map((item) => (+ <label+ className={cn(+ "flex min-h-10 cursor-pointer items-center gap-2 rounded-sm px-2 text-sm transition-colors duration-150 motion-reduce:transition-none",+ chosen.has(item.model.id)+ ? "bg-app-selected text-app-ink"+ : "text-app-body hover:bg-app-hover",+ )}+ key={item.model.id}+ >+ <input+ checked={chosen.has(item.model.id)}+ className={sourceCheckClassName}+ onChange={(event) =>+ setSelected((current) =>+ event.target.checked+ ? [...current, item.model.id]+ : current.filter((id) => id !== item.model.id),+ )+ }+ type="checkbox"+ />+ <span className="min-w-0 flex-1 truncate">+ {item.model.name}+ </span>+ <span className="text-xs text-muted-foreground">+ {item.used_by.length+ ? `Used by ${agentNames(item)}`+ : "Not used"}+ </span>+ <span className="w-16 text-right text-xs tabular-nums text-muted-foreground">+ {formatBytes(item.model.memory_bytes)}+ </span>+ </label>+ ))}+ </fieldset>+ ) : (+ <FormFeedback tone="danger">+ Nothing else is loaded there. This model doesn't fit even when+ the memory is empty.+ </FormFeedback>+ )}+ {affected.length ? (+ <FormFeedback tone="warning">+ {affected.join(", ")} can't answer until their model is loaded+ again.+ </FormFeedback>+ ) : null}+ </div>+ </ModalDialog>+ );+}++/** Unloading a model an Agent uses stops that Agent, so it asks first. */+export function UnloadModelDialog({+ disabled,+ entry,+ onClose,+ onConfirm,+ view,+}: {+ /** The action no longer applies, or its Computer takes no actions. */+ disabled: boolean;+ entry: ModelEntry;+ onClose: () => void;+ onConfirm: () => void;+ view: LocalModelsView;+}) {+ const pool = poolOf(view, entry.model.pool);+ return (+ <ModalDialog+ description={`Frees ${formatBytes(entry.model.memory_bytes)} of ${+ pool ? poolLabel(view, pool) : "memory"+ }. It stays on disk, so you can load it again later.`}+ footer={+ <>+ <Button onClick={onClose}>Cancel</Button>+ <Button disabled={disabled} onClick={onConfirm} tone="primary">+ Unload+ </Button>+ </>+ }+ onClose={onClose}+ size="sm"+ title={`Unload ${entry.model.name}?`}+ >+ <div className="px-5 py-4">+ <AffectedAgents entry={entry} until="it is loaded again" />+ </div>+ </ModalDialog>+ );+}++export function RemoveModelDialog({+ disabled,+ entry,+ onClose,+ onConfirm,+ view,+}: {+ /** The action no longer applies, or its Computer takes no actions. */+ disabled: boolean;+ entry: ModelEntry;+ onClose: () => void;+ onConfirm: () => void;+ view: LocalModelsView;+}) {+ return (+ <ModalDialog+ description={`${+ entry.status === "loaded"+ ? "Unloads it, deletes its files"+ : "Deletes its files"+ } and frees ${formatBytes(entry.model.download_bytes)} of disk on ${view.computer.display_name}. You can download it again later.`}+ footer={+ <>+ <Button onClick={onClose}>Cancel</Button>+ <Button disabled={disabled} onClick={onConfirm} tone="danger">+ Remove+ </Button>+ </>+ }+ onClose={onClose}+ size="sm"+ title={`Remove ${entry.model.name}?`}+ >+ <div className="px-5 py-4">+ <AffectedAgents+ entry={entry}+ until={`you choose another model for ${entry.used_by.length === 1 ? "it" : "them"}`}+ />+ </div>+ </ModalDialog>+ );+}diff --git a/apps/web/src/features/local-models/local-model-row.tsx b/apps/web/src/features/local-models/local-model-row.tsxnew file mode 100644index 00000000..ef546e05--- /dev/null+++ b/apps/web/src/features/local-models/local-model-row.tsx@@ -0,0 +1,233 @@+import { AiChipIcon, ArrowDown01Icon } from "@hugeicons/core-free-icons";+import { useId, type MouseEvent } from "react";++import { Button } from "@/components/ui/button";+import { Icon } from "@/components/ui/icon";+import { cn } from "@/lib/cn";++import { formatBytes } from "@/lib/format-bytes";++import { ModelFacts } from "./local-model-details";+import { unavailableShortCopy } from "./local-models-copy";+import type { LocalModelsView } from "./local-models-queries";+import {+ downloadPercent,+ placeName,+ type ModelEntry,+ type ModelStatus,+} from "./local-models-rules";++/**+ * The status word every row shows under its name, with the dot that colors+ * it. Models not on the Computer carry no dot, like an unconnected Connector.+ */+const statusTags: Record<+ ModelStatus,+ { dot?: string; label: string; working?: boolean }+> = {+ available: { label: "Not downloaded" },+ downloading: {+ dot: "bg-app-info",+ label: "Downloading",+ working: true,+ },+ failed: { dot: "bg-app-danger", label: "Couldn't load" },+ idle: { dot: "bg-muted-foreground/60", label: "Downloaded" },+ loaded: { dot: "bg-app-success", label: "Loaded" },+ loading: { dot: "bg-app-info", label: "Loading", working: true },+ unavailable: { label: "Can't download" },+};++interface Handlers {+ onCancel: () => void;+ onDownload: () => void;+ onLoad: () => void;+ onRemove: () => void;+ onToggle: () => void;+ onUnload: () => void;+}++function stopRowClick(event: MouseEvent) {+ event.stopPropagation();+}++/**+ * One catalog model on one Computer: a full-width Connectors-style card whose+ * header carries the status and one action, and which expands to the details.+ */+export function ModelRow({+ disabled,+ entry,+ expanded,+ view,+ ...handlers+}: Handlers & {+ /** Actions are off: the Computer is offline, the viewer only reads, or one is pending. */+ disabled: boolean;+ entry: ModelEntry;+ expanded: boolean;+ view: LocalModelsView;+}) {+ const panelId = useId();+ const { model, status } = entry;+ const where = placeName(view, model.pool);+ const tag = statusTags[status];+ const progress = downloadPercent(model);+ const download = formatBytes(model.download_bytes);+ const detail = {+ available: model.recommended+ ? `${download} · Recommended`+ : model.fit === "system"+ ? `${download} · runs slower`+ : download,+ downloading:+ model.download?.step === "verify" ? "checking file" : `${progress}%`,+ failed: null,+ idle: model.note ? "no room to load yet" : null,+ loaded: [+ where ? `${where[0]!.toUpperCase()}${where.slice(1)}` : undefined,+ formatBytes(model.memory_bytes),+ ]+ .filter(Boolean)+ .join(" · "),+ loading: where ?? null,+ unavailable: unavailableShortCopy(model.availability.reason),+ }[status];++ const action = (+ {+ available: ["Download", handlers.onDownload],+ downloading: ["Cancel", handlers.onCancel],+ failed: ["Retry", handlers.onLoad],+ idle: ["Load", handlers.onLoad],+ loaded: ["Unload", handlers.onUnload],+ loading: null,+ unavailable: null,+ } as const+ )[status];+ const removable =+ status === "loaded" || status === "idle" || status === "failed";++ return (+ <article+ className={cn(+ "rounded-xl border bg-card transition-colors duration-150 motion-reduce:transition-none",+ expanded ? "border-border-hover" : "border-border hover:bg-accent/40",+ )}+ >+ <div className="flex items-center gap-3 px-4 py-3">+ <button+ aria-controls={panelId}+ aria-expanded={expanded}+ aria-label={model.name}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-3 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ status === "unavailable" && "opacity-60",+ )}+ onClick={handlers.onToggle}+ type="button"+ >+ <span className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-card text-foreground shadow-outline">+ <Icon icon={AiChipIcon} size={20} />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">+ {model.name}+ </span>+ <span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">+ {tag.dot ? (+ <span+ aria-hidden+ className={cn("size-1.5 shrink-0 rounded-full", tag.dot)}+ />+ ) : null}+ <span+ className={cn("truncate", tag.working && "town-shimmer-text")}+ >+ <span className={tag.dot ? "text-foreground" : undefined}>+ {tag.label}+ </span>+ {detail ? ` · ${detail}` : null}+ </span>+ </span>+ </span>+ </button>+ {action ? (+ <Button+ aria-label={`${action[0]} ${model.name}`}+ className="px-2.5"+ disabled={disabled}+ onClick={(event) => {+ stopRowClick(event);+ action[1]();+ }}+ size="compact"+ tone={status === "downloading" ? "ghost" : "secondary"}+ >+ {action[0]}+ </Button>+ ) : null}+ <Button+ aria-hidden+ className="text-muted-foreground"+ onClick={handlers.onToggle}+ size="compactIcon"+ tabIndex={-1}+ tone="ghost"+ >+ <Icon+ className={cn(+ "transition-transform duration-200 motion-reduce:transition-none",+ !expanded && "-rotate-90",+ )}+ icon={ArrowDown01Icon}+ size={14}+ />+ </Button>+ </div>+ {status === "downloading" ? (+ <div className="px-4 pb-3">+ <span+ aria-label={`${model.name} download progress`}+ aria-valuemax={100}+ aria-valuemin={0}+ aria-valuenow={progress}+ className="block h-1 overflow-hidden rounded-full bg-muted"+ role="progressbar"+ >+ <span+ className="block h-full origin-left rounded-full bg-primary transition-transform duration-200 motion-reduce:transition-none"+ style={{ transform: `scaleX(${progress / 100})` }}+ />+ </span>+ </div>+ ) : null}+ {expanded ? (+ <div+ className="border-t border-border px-4 pt-1 pb-3"+ id={panelId}+ role="region"+ aria-label={`${model.name} details`}+ >+ {model.description ? (+ <p className="pt-2 pb-1 text-sm text-muted-foreground">+ {model.description}+ </p>+ ) : null}+ <ModelFacts entry={entry} view={view} />+ {removable ? (+ <Button+ className="mt-2"+ disabled={disabled}+ onClick={handlers.onRemove}+ size="compact"+ tone="danger"+ >+ Remove from computer+ </Button>+ ) : null}+ </div>+ ) : null}+ </article>+ );+}diff --git a/apps/web/src/features/local-models/local-models-copy.ts b/apps/web/src/features/local-models/local-models-copy.tsnew file mode 100644index 00000000..dd775757--- /dev/null+++ b/apps/web/src/features/local-models/local-models-copy.ts@@ -0,0 +1,156 @@+import type { components } from "@linger/wire-contracts/teamhub-public/types";++import { formatBytes } from "@/lib/format-bytes";++type Schemas = components["schemas"];++/**+ * Every code the Local models page shows, as English copy. The page branches+ * on codes only; diagnostic `detail` text from the Computer is never shown.+ * Typing each map by its generated code set makes a new code a type error+ * here until it has copy.+ */++const actionRefusals: Record<Schemas["LocalModelsErrorCode"], string> = {+ LOCAL_COMPUTER_OFFLINE:+ "The computer is offline. Reconnect it in Computers, then try again.",+ LOCAL_MODEL_ACTION_FAILED: "The computer couldn't start this. Try again.",+ LOCAL_MODEL_ACTION_UNCONFIRMED:+ "The computer didn't confirm in time. Its models below show what it's doing.",+ LOCAL_MODEL_ACTION_FORBIDDEN:+ "Only the person who connected this computer can manage its models.",+ LOCAL_MODEL_DISK_INSUFFICIENT:+ "There isn't enough free disk on the computer for this model.",+ LOCAL_MODEL_INVALID_STATE:+ "The model changed on the computer. Check its status and try again.",+ LOCAL_MODEL_JOB_RUNNING:+ "The computer is still working on this model. Wait for it to finish.",+ LOCAL_MODEL_MEMORY_INSUFFICIENT:+ "The computer doesn't have enough memory for this model.",+ LOCAL_MODEL_NO_ROOM:+ "There isn't enough free memory to load it. Unload another model first.",+ LOCAL_MODEL_PLATFORM_UNSUPPORTED: "This model doesn't run on this computer.",+ LOCAL_MODEL_UNKNOWN: "The computer doesn't have this model anymore.",+ LOCAL_MODELS_SERVICE_UNAVAILABLE:+ "Linger couldn't reach the computer right now. Try again.",+ LOCAL_MODELS_UNAVAILABLE:+ "The local model tools on this computer aren't working.",+};++/** Why an action or a read failed: a TeamHub error code, or anything else. */+export function actionErrorCopy(code: string | undefined) {+ return code && Object.hasOwn(actionRefusals, code)+ ? actionRefusals[code as keyof typeof actionRefusals]+ : "Something went wrong. Try again.";+}++const modelErrors: Record<Schemas["LocalModelErrorCode"], string> = {+ CANCELLED: "Loading was stopped.",+ CHECKSUM_MISMATCH:+ "The downloaded files were damaged. Remove the model and download it again.",+ DISK_INSUFFICIENT: "There wasn't enough free disk.",+ DOWNLOAD_FAILED: "The download didn't finish.",+ ENGINE_START_FAILED: "The model engine didn't start.",+ GATEWAY_REGISTRATION_FAILED:+ "It loaded, but Agents couldn't be given access to it.",+ HEALTH_CHECK_FAILED: "The model started but didn't answer.",+ INVALID_STATE: "The model was busy with another step.",+ JOB_RUNNING: "Another step was still running.",+ LOAD_NO_ROOM: "There wasn't enough free memory to load it.",+ MEMORY_INSUFFICIENT: "The computer doesn't have enough memory for it.",+ MODEL_FILES_MISSING:+ "Its files are missing. Remove the model and download it again.",+ MODEL_UNKNOWN: "The computer doesn't know this model anymore.",+ NETWORK_UNAVAILABLE: "The computer couldn't reach the network.",+ OUT_OF_MEMORY: "It ran out of memory while loading.",+ PLATFORM_UNSUPPORTED: "This model doesn't run on this computer.",+};++/** Why the last load of a model failed. */+export function modelErrorCopy(code: Schemas["LocalModelErrorCode"]) {+ return modelErrors[code];+}++const notes: Record<+ Schemas["LocalModelNote"]["code"],+ (place: string) => string+> = {+ NO_ROOM_TO_LOAD: (place) =>+ `It downloaded, but there wasn't enough free ${place} to load it. Load it when there is room.`,+};++/** Why a finished download did not load by itself; `place` names its memory. */+export function modelNoteCopy(+ code: Schemas["LocalModelNote"]["code"],+ place = "memory",+) {+ return notes[code](place);+}++type AvailabilityReason = Schemas["LocalModelAvailabilityReason"];++/** The short reason on a row that can't be downloaded. */+export function unavailableShortCopy(reason: AvailabilityReason | undefined) {+ if (reason?.code === "PLATFORM_UNSUPPORTED" || !reason)+ return "not for this computer";+ const need =+ reason.need_bytes === undefined ? "" : formatBytes(reason.need_bytes);+ if (!need)+ return reason.code === "DISK_INSUFFICIENT"+ ? "needs more disk"+ : "needs more memory";+ return reason.code === "DISK_INSUFFICIENT"+ ? `needs ${need} of disk`+ : `needs ${need}`;+}++/** The full reason a model can't be downloaded, shown in its details. */+export function unavailableCopy(reason: AvailabilityReason | undefined) {+ const need =+ reason?.need_bytes === undefined+ ? undefined+ : formatBytes(reason.need_bytes);+ const have =+ reason?.have_bytes === undefined+ ? undefined+ : formatBytes(reason.have_bytes);+ switch (reason?.code) {+ case "MEMORY_INSUFFICIENT":+ return need && have+ ? `Needs ${need} of memory; this computer has ${have} for models.`+ : "This computer doesn't have enough memory for it.";+ case "DISK_INSUFFICIENT":+ return need && have+ ? `Needs ${need} of disk; ${have} is free.`+ : "There isn't enough free disk for it.";+ default:+ return "This model doesn't run on this computer.";+ }+}++const libraryUnavailable: Record<+ Schemas["LocalModelsViewUnavailableReason"]["code"],+ { body: string; title: (computer: string) => string }+> = {+ NOT_REPORTED: {+ body: "It reports them once it connects with an up-to-date Linger app.",+ title: (computer) => `${computer} hasn't reported local models yet`,+ },+ TOOL_FAILED: {+ body: "The local model tools on this computer didn't answer. Check that they're installed and working, then open this page again.",+ title: (computer) => `Couldn't read the local models on ${computer}`,+ },+ TOOL_NOT_INSTALLED: {+ body: "Run Quick Install in the Linger desktop app on that computer to add them.",+ title: (computer) => `Local models aren't set up on ${computer}`,+ },+};++/** Why a Computer reports no model library. */+export function libraryUnavailableCopy(+ code: Schemas["LocalModelsViewUnavailableReason"]["code"] | undefined,+ computer: string,+) {+ const copy = libraryUnavailable[code ?? "NOT_REPORTED"];+ return { body: copy.body, title: copy.title(computer) };+}diff --git a/apps/web/src/features/local-models/local-models-page.test.tsx b/apps/web/src/features/local-models/local-models-page.test.tsxnew file mode 100644index 00000000..0ee8fab5--- /dev/null+++ b/apps/web/src/features/local-models/local-models-page.test.tsx@@ -0,0 +1,815 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { Suspense } from "react";+import { MemoryRouter, Route, Routes, useLocation } from "react-router";+import { afterEach, describe, expect, it } from "vitest";++import { TeamHubEventSync } from "@/features/rooms/event-sync";+import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import type { TeamHubLocalComputerPage } from "@/features/teamhub/teamhub-types";+import {+ createTestTeamHubRuntime,+ type TestTeamHubRuntime,+} from "@/test/teamhub-test-runtime";+import { teamHubErrorResponse } from "@/test/teamhub-test-server";++import { LocalModelsPage } from "./local-models-page";+import type { LocalModelsView } from "./local-models-queries";+import { gb, gpuPool, labView, macView } from "./local-models-test-support";++const tenantId = "tenant-northstar";+const viewPath =+ "/v0/tenants/{tenantId}/local-computers/{computerId}/local-models";+const actionPath =+ "/v0/tenants/{tenantId}/local-computers/{computerId}/local-models/{modelId}/actions";++type InventoryComputer = TeamHubLocalComputerPage["items"][number];++interface Fixture {+ actions: { body: unknown; computerId: string; modelId: string }[];+ runtime: TestTeamHubRuntime;+ views: Record<string, LocalModelsView>;+}++function setup(+ views: LocalModelsView[] = [labView(), macView()],+ inventory?: InventoryComputer[],+): Fixture {+ const runtime = createTestTeamHubRuntime();+ const template = runtime.seed.localComputers[0]!;+ runtime.seed.localComputers =+ inventory ??+ views.map((view) => ({+ ...template,+ computer_id: view.computer.computer_id,+ display_name: view.computer.display_name,+ status: view.computer.status,+ }));+ const fixture: Fixture = {+ actions: [],+ runtime,+ views: Object.fromEntries(+ views.map((view) => [view.computer.computer_id, view]),+ ),+ };+ runtime.server+ .on("GET", viewPath, ({ params }) => {+ const view = fixture.views[params.computerId!];+ return view ?? teamHubErrorResponse(404, "LOCAL_COMPUTER_NOT_FOUND");+ })+ .on("POST", actionPath, ({ body, params }) => {+ fixture.actions.push({+ body,+ computerId: params.computerId!,+ modelId: params.modelId!,+ });+ return Response.json(+ {+ action: (body as { action: string }).action,+ computer_id: params.computerId,+ model_id: params.modelId,+ },+ { status: 202 },+ );+ });+ return fixture;+}++function inventoryComputer(view: LocalModelsView): InventoryComputer {+ const template = createTestTeamHubRuntime().seed.localComputers[0]!;+ return {+ ...template,+ computer_id: view.computer.computer_id,+ display_name: view.computer.display_name,+ status: view.computer.status,+ };+}++function CurrentSearch() {+ return <p>Address search: {useLocation().search}</p>;+}++function renderPage(fixture: Fixture, search = "") {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ render(+ <QueryClientProvider client={queryClient}>+ <TeamHubRuntimeProvider runtime={fixture.runtime}>+ <TeamHubEventSync />+ <MemoryRouter+ initialEntries={[`/t/${tenantId}/settings/local-models${search}`]}+ >+ <Suspense fallback={<p>Loading page</p>}>+ <Routes>+ <Route+ element={+ <>+ <LocalModelsPage />+ <CurrentSearch />+ </>+ }+ path="/t/:tenantId/settings/local-models"+ />+ <Route+ element={<p>Computers page</p>}+ path="/t/:tenantId/settings/computers"+ />+ </Routes>+ </Suspense>+ </MemoryRouter>+ </TeamHubRuntimeProvider>+ </QueryClientProvider>,+ );+}++function cards() {+ return within(screen.getByRole("region", { name: "Models" })).getAllByRole(+ "article",+ );+}++function card(name: string) {+ return cards().find(+ (item) => within(item).queryByRole("button", { name }) !== null,+ )!;+}++/** Each card as "name: status line", in page order. */+function statuses() {+ return cards().map((item) => {+ const toggle = within(item).getAllByRole("button")[0]!;+ const name = toggle.getAttribute("aria-label")!;+ return `${name}: ${toggle.textContent.slice(name.length)}`;+ });+}++async function findModels() {+ return screen.findByRole("region", { name: "Models" });+}++function publishSnapshot(fixture: Fixture, view: LocalModelsView) {+ fixture.views[view.computer.computer_id] = view;+ fixture.runtime.events.emitSignal({+ hint: {+ id: view.computer.computer_id,+ resource: "local-models",+ tenant_id: tenantId,+ },+ type: "resource.invalidated",+ });+}++function withModel(+ view: LocalModelsView,+ modelId: string,+ fields: Partial<LocalModelsView["models"][number]["model"]>,+): LocalModelsView {+ return {+ ...view,+ models: view.models.map((item) =>+ item.model.id === modelId+ ? { ...item, model: { ...item.model, ...fields } }+ : item,+ ),+ };+}++afterEach(() => {+ delete (window as { lingerDesktop?: unknown }).lingerDesktop;+});++describe("LocalModelsPage", () => {+ it("lists every model once with its status, as the Computer reported it", async () => {+ renderPage(setup());+ await findModels();++ expect(statuses()).toEqual([+ "Qwen3 Coder 30B: Loaded · GPU 0 · 21.4 GB",+ "Gemma 3 27B: Downloaded",+ "GPT-OSS 20B: Not downloaded · 12.1 GB · Recommended",+ "Gemma 3 4B: Not downloaded · 3.3 GB",+ "Llama 3.3 70B: Not downloaded · 42.5 GB · runs slower",+ "Llama 3.1 405B: Can't download · needs 230 GB",+ ]);+ expect(+ screen.getByText("22.5 GB of 48 GB GPU memory in use"),+ ).toBeVisible();+ expect(screen.queryByText("Sample data")).not.toBeInTheDocument();+ // A model that can't be downloaded has no action, only its toggle.+ expect(within(card("Llama 3.1 405B")).getAllByRole("button")).toHaveLength(+ 1,+ );+ });++ it("expands one row at a time to show a model's details", async () => {+ renderPage(setup());+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Qwen3 Coder 30B" }));+ const details = screen.getByRole("region", {+ name: "Qwen3 Coder 30B details",+ });+ expect(details).toHaveTextContent("21.4 GB on GPU 0 · RTX 4090");+ expect(details).toHaveTextContent("Research agent, Code reviewer");+ expect(details).toHaveTextContent("http://127.0.0.1:18100/v1");+ expect(details).toHaveTextContent("46 tokens/s");+ expect(details).toHaveTextContent("128K tokens");++ fireEvent.click(screen.getByRole("button", { name: "Llama 3.1 405B" }));+ expect(+ screen.queryByRole("region", { name: "Qwen3 Coder 30B details" }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole("region", { name: "Llama 3.1 405B details" }),+ ).toHaveTextContent(+ "Needs 230 GB of memory; this computer has 102.4 GB for models.",+ );+ });++ it("shows the Computer's pools and hardware in Details", async () => {+ renderPage(setup());+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Details" }));+ const dialog = screen.getByRole("dialog", { name: "lab-118 details" });+ expect(+ within(dialog).getByRole("img", {+ name: "GPU 0 · RTX 4090: 21.4 GB of 24 GB in use",+ }),+ ).toBeVisible();+ // A foundation component holds memory but is not a model row.+ expect(dialog).toHaveTextContent("Qwen3 Embedding");+ expect(dialog).toHaveTextContent("Ubuntu 24.04 · llama.cpp b11370 · CUDA");+ expect(dialog).toHaveTextContent("412 GB");+ });++ it("shows memory other apps use in a pool's bar", async () => {+ const shared = gpuPool(0, 24, [{ gb: 4, id: "small", name: "Small" }]);+ // Another process holds 15 GB of the card next to the model.+ renderPage(+ setup([labView({ pools: [{ ...shared, used_bytes: gb(19) }] })]),+ );+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Details" }));+ const dialog = screen.getByRole("dialog", { name: "lab-118 details" });+ expect(within(dialog).getByTitle("Other apps · 15 GB")).toHaveStyle({+ width: "62.5%",+ });+ expect(within(dialog).getByTitle("Small · 4 GB")).toHaveStyle({+ width: `${(4 / 24) * 100}%`,+ });+ });++ it("downloads on click and follows the snapshots the Computer sends", async () => {+ const fixture = setup();+ renderPage(fixture);+ await findModels();++ fireEvent.click(+ screen.getByRole("button", { name: "Download GPT-OSS 20B" }),+ );+ await waitFor(() =>+ expect(fixture.actions).toEqual([+ {+ body: { action: "download" },+ computerId: "computer-lab",+ modelId: "gpt-oss-20b:Q4_K_M",+ },+ ]),+ );++ publishSnapshot(+ fixture,+ withModel(labView(), "gpt-oss-20b:Q4_K_M", {+ download: { done_bytes: 32, step: "download", total_bytes: 100 },+ state: "downloading",+ }),+ );+ await waitFor(() =>+ expect(statuses()).toContain("GPT-OSS 20B: Downloading · 32%"),+ );+ expect(+ screen.getByRole("progressbar", {+ name: "GPT-OSS 20B download progress",+ }),+ ).toHaveAttribute("aria-valuenow", "32");++ publishSnapshot(+ fixture,+ withModel(labView(), "gpt-oss-20b:Q4_K_M", {+ download: { done_bytes: 100, step: "verify", total_bytes: 100 },+ state: "downloading",+ }),+ );+ await waitFor(() =>+ expect(statuses()).toContain("GPT-OSS 20B: Downloading · checking file"),+ );++ fireEvent.click(screen.getByRole("button", { name: "Cancel GPT-OSS 20B" }));+ await waitFor(() =>+ expect(fixture.actions.at(-1)?.body).toEqual({ action: "cancel" }),+ );++ publishSnapshot(+ fixture,+ withModel(labView(), "gpt-oss-20b:Q4_K_M", {+ note: { code: "NO_ROOM_TO_LOAD" },+ state: "idle",+ }),+ );+ await waitFor(() =>+ expect(statuses()).toContain(+ "GPT-OSS 20B: Downloaded · no room to load yet",+ ),+ );+ });++ it("loads at once when the pool has room", async () => {+ const fixture = setup();+ renderPage(fixture);+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Load Gemma 3 27B" }));+ await waitFor(() =>+ expect(fixture.actions).toEqual([+ {+ body: { action: "load" },+ computerId: "computer-lab",+ modelId: "gemma3-27b:Q4_K_M",+ },+ ]),+ );+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("offers to unload the model holding the memory before loading another", async () => {+ const fixture = setup();+ renderPage(fixture, "?computer=computer-mac");+ await findModels();++ expect(statuses()).toContain("Llama 3.3 70B: Couldn't load");+ fireEvent.click(screen.getByRole("button", { name: "Llama 3.3 70B" }));+ const details = screen.getByRole("region", {+ name: "Llama 3.3 70B details",+ });+ expect(details).toHaveTextContent(+ "There wasn't enough free memory to load it.",+ );+ // Diagnostic text from the Computer is never shown.+ expect(details).not.toHaveTextContent("need 46 GiB");++ fireEvent.click(+ screen.getByRole("button", { name: "Retry Llama 3.3 70B" }),+ );+ const dialog = screen.getByRole("dialog", { name: "Make room to load" });+ expect(dialog).toHaveTextContent(+ "Llama 3.3 70B needs 46 GB on Unified memory; 36.9 GB is free.",+ );+ const gptOss = within(dialog).getByRole("checkbox", {+ name: /GPT-OSS 20B/,+ });+ expect(gptOss).toBeChecked();+ expect(dialog).toHaveTextContent(+ "Another Me can't answer until their model is loaded again.",+ );++ fireEvent.click(gptOss);+ expect(within(dialog).getByRole("button", { name: "Load" })).toBeDisabled();+ fireEvent.click(gptOss);+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Unload and load" }),+ );++ await waitFor(() =>+ expect(fixture.actions).toEqual([+ {+ body: { action: "load", unload_first: ["gpt-oss-20b:Q4_K_M"] },+ computerId: "computer-mac",+ modelId: "llama3.3-70b:Q4_K_M",+ },+ ]),+ );+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("says so when nothing else in the pool can be unloaded", async () => {+ const mac = macView();+ renderPage(+ setup([+ {+ ...mac,+ models: mac.models.slice(1),+ pools: [+ {+ ...mac.pools[0]!,+ holders: [],+ total_bytes: gb(40),+ used_bytes: 0,+ },+ ],+ },+ ]),+ );+ await findModels();++ fireEvent.click(+ screen.getByRole("button", { name: "Retry Llama 3.3 70B" }),+ );+ expect(+ screen.getByRole("dialog", { name: "Make room to load" }),+ ).toHaveTextContent("Nothing else is loaded there.");+ });++ it("asks before unloading a model an Agent uses, and not otherwise", async () => {+ const fixture = setup();+ renderPage(fixture);+ await findModels();++ fireEvent.click(+ screen.getByRole("button", { name: "Unload Qwen3 Coder 30B" }),+ );+ const dialog = screen.getByRole("dialog", {+ name: "Unload Qwen3 Coder 30B?",+ });+ expect(dialog).toHaveTextContent(+ "Research agent, Code reviewer use this model and can't answer until it is loaded again.",+ );+ expect(fixture.actions).toEqual([]);+ fireEvent.click(within(dialog).getByRole("button", { name: "Unload" }));+ await waitFor(() =>+ expect(fixture.actions).toEqual([+ {+ body: { action: "unload" },+ computerId: "computer-lab",+ modelId: "qwen3-coder-30b:Q4_K_M",+ },+ ]),+ );++ publishSnapshot(fixture, {+ ...labView(),+ models: labView().models.map((item) => ({ ...item, used_by: [] })),+ });+ fireEvent.click(screen.getByRole("button", { name: "Qwen3 Coder 30B" }));+ await waitFor(() =>+ expect(+ screen.getByRole("region", { name: "Qwen3 Coder 30B details" }),+ ).toHaveTextContent("No Agent yet"),+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Unload Qwen3 Coder 30B" }),+ );+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ await waitFor(() => expect(fixture.actions).toHaveLength(2));+ });++ it("warns which Agents lose their model before removing it", async () => {+ const fixture = setup();+ renderPage(fixture);+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Qwen3 Coder 30B" }));+ fireEvent.click(+ within(+ screen.getByRole("region", { name: "Qwen3 Coder 30B details" }),+ ).getByRole("button", { name: "Remove from computer" }),+ );+ const dialog = screen.getByRole("dialog", {+ name: "Remove Qwen3 Coder 30B?",+ });+ expect(dialog).toHaveTextContent(+ "Unloads it, deletes its files and frees 18.6 GB of disk on lab-118.",+ );+ expect(dialog).toHaveTextContent(+ "Research agent, Code reviewer use this model and can't answer until you choose another model for them.",+ );+ fireEvent.click(within(dialog).getByRole("button", { name: "Remove" }));+ await waitFor(() =>+ expect(fixture.actions).toEqual([+ {+ body: { action: "remove" },+ computerId: "computer-lab",+ modelId: "qwen3-coder-30b:Q4_K_M",+ },+ ]),+ );+ });++ it("lists the Agents of a downloaded model and warns before removing it", async () => {+ const view = labView();+ // TeamHub matches Agents by pi_model, which a model keeps while idle.+ view.models[1] = {+ ...view.models[1]!,+ used_by: [{ agent_id: "agent-writer", name: "Writer" }],+ };+ const fixture = setup([view]);+ renderPage(fixture);+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Gemma 3 27B" }));+ const details = screen.getByRole("region", { name: "Gemma 3 27B details" });+ expect(details).toHaveTextContent("Used byWriter");+ fireEvent.click(+ within(details).getByRole("button", { name: "Remove from computer" }),+ );+ const dialog = screen.getByRole("dialog", { name: "Remove Gemma 3 27B?" });+ expect(dialog).toHaveTextContent("Deletes its files");+ expect(dialog).toHaveTextContent(+ "Writer uses this model and can't answer until you choose another model for it.",+ );+ });++ it("opens a Computer the viewer may read but does not own", async () => {+ // The owned-Computer inventory is empty; the library API allows the read.+ const fixture = setup([labView({ viewer_is_owner: false })], []);+ renderPage(fixture, "?computer=computer-lab");+ await findModels();++ expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent(+ "Local models",+ );+ expect(+ screen.getByText(+ "Only the person who connected lab-118 can download, load or remove its models.",+ ),+ ).toBeVisible();+ expect(+ screen.getByRole("button", { name: "Unload Qwen3 Coder 30B" }),+ ).toBeDisabled();+ expect(screen.getByText(/Address search:/)).toHaveTextContent(+ "?computer=computer-lab",+ );+ });++ it("keeps a shared Computer selected next to the viewer's own", async () => {+ const fixture = setup(+ [labView({ viewer_is_owner: false }), macView()],+ [inventoryComputer(macView())],+ );+ renderPage(fixture, "?computer=computer-lab");+ await findModels();++ // Not the viewer's own Mac: lab-118, read-only.+ expect(card("Qwen3 Coder 30B")).toBeVisible();+ expect(+ screen.getByText(+ "Only the person who connected lab-118 can download, load or remove its models.",+ ),+ ).toBeVisible();+ });++ it.each([+ ["Unload Qwen3 Coder 30B", "Unload Qwen3 Coder 30B?", "Unload"],+ ["Remove from computer", "Remove Qwen3 Coder 30B?", "Remove"],+ ])(+ "disables an open %s confirmation once the Computer goes offline",+ async (opener, title, confirm) => {+ const fixture = setup([labView()]);+ renderPage(fixture);+ await findModels();+ if (opener === "Remove from computer")+ fireEvent.click(+ screen.getByRole("button", { name: "Qwen3 Coder 30B" }),+ );+ fireEvent.click(screen.getByRole("button", { name: opener }));+ const dialog = await screen.findByRole("dialog", { name: title });++ publishSnapshot(+ fixture,+ labView({ computer: { ...labView().computer, status: "offline" } }),+ );+ await waitFor(() =>+ expect(+ within(dialog).getByRole("button", { name: confirm }),+ ).toBeDisabled(),+ );+ fireEvent.click(within(dialog).getByRole("button", { name: confirm }));+ expect(fixture.actions).toEqual([]);+ },+ );++ it("disables an open Unload confirmation once the model is no longer loaded", async () => {+ const fixture = setup([labView()]);+ renderPage(fixture);+ await findModels();+ fireEvent.click(+ screen.getByRole("button", { name: "Unload Qwen3 Coder 30B" }),+ );+ const dialog = await screen.findByRole("dialog", {+ name: "Unload Qwen3 Coder 30B?",+ });++ publishSnapshot(+ fixture,+ withModel(labView(), "qwen3-coder-30b:Q4_K_M", {+ endpoint: undefined,+ state: "idle",+ }),+ );+ await waitFor(() =>+ expect(+ within(dialog).getByRole("button", { name: "Unload" }),+ ).toBeDisabled(),+ );+ });++ it("shows a refusal from the Computer as copy for its code", async () => {+ const fixture = setup();+ fixture.runtime.server.on("POST", actionPath, () =>+ teamHubErrorResponse(409, "LOCAL_MODEL_NO_ROOM", "raw refusal detail"),+ );+ renderPage(fixture);+ await findModels();++ fireEvent.click(screen.getByRole("button", { name: "Load Gemma 3 27B" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Gemma 3 27B: There isn't enough free memory to load it. Unload another model first.",+ );+ expect(screen.queryByText(/raw refusal detail/)).not.toBeInTheDocument();+ });++ it("shows what an offline Computer last reported with every action off", async () => {+ renderPage(+ setup([+ labView({+ computer: {+ ...labView().computer,+ last_seen_at: new Date(Date.now() - 3 * 3_600_000).toISOString(),+ status: "offline",+ },+ }),+ ]),+ );+ await findModels();++ expect(screen.getByRole("status")).toHaveTextContent(+ "lab-118 is offline (last seen 3 hours ago). This is what it last reported. Reconnect it in Computers to manage its models.",+ );+ expect(+ screen.getByRole("button", { name: "Load Gemma 3 27B" }),+ ).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Download GPT-OSS 20B" }),+ ).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: "Gemma 3 27B" }));+ expect(+ screen.getByRole("button", { name: "Remove from computer" }),+ ).toBeDisabled();+ fireEvent.click(screen.getByRole("link", { name: "Computers" }));+ expect(await screen.findByText("Computers page")).toBeVisible();+ });++ it("lets only the owner act and tells everyone else why", async () => {+ renderPage(setup([labView({ viewer_is_owner: false })]));+ await findModels();++ expect(screen.getByRole("status")).toHaveTextContent(+ "Only the person who connected lab-118 can download, load or remove its models.",+ );+ expect(+ screen.getByRole("button", { name: "Unload Qwen3 Coder 30B" }),+ ).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Download GPT-OSS 20B" }),+ ).toBeDisabled();+ });++ it.each([+ [+ "TOOL_NOT_INSTALLED",+ "Local models aren't set up on lab-118",+ "Run Quick Install",+ ],+ [+ "TOOL_FAILED",+ "Couldn't read the local models on lab-118",+ "didn't answer",+ ],+ [+ "NOT_REPORTED",+ "lab-118 hasn't reported local models yet",+ "up-to-date Linger app",+ ],+ ] as const)(+ "explains a Computer without a model library (%s)",+ async (code, title, body) => {+ renderPage(+ setup([+ labView({+ available: false,+ models: [],+ pools: [],+ reason: { code, detail: "raw tool output" },+ }),+ ]),+ );++ const empty = await screen.findByRole("region", { name: title });+ expect(empty).toHaveTextContent(body);+ expect(empty).not.toHaveTextContent("raw tool output");+ expect(+ screen.queryByRole("region", { name: "Models" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Details" }),+ ).not.toBeInTheDocument();+ },+ );++ it("sends a Tenant without Computers to Computers", async () => {+ renderPage(setup([], []));++ const empty = await screen.findByRole("region", {+ name: "No computers yet",+ });+ fireEvent.click(within(empty).getByRole("link", { name: "Computers" }));+ expect(await screen.findByText("Computers page")).toBeVisible();+ });++ it("renders a model that fits nowhere without a placement", async () => {+ renderPage(setup());+ await findModels();++ expect(statuses()).toContain(+ "Llama 3.1 405B: Can't download · needs 230 GB",+ );+ fireEvent.click(screen.getByRole("button", { name: "Llama 3.1 405B" }));+ const memory = within(+ screen.getByRole("region", { name: "Llama 3.1 405B details" }),+ )+ .getByText("Memory")+ .closest("div")!;+ expect(memory).toHaveTextContent(/^Memory230 GB$/);+ });++ it("shows a loaded model's endpoint without a gateway model id", async () => {+ const lab = labView();+ renderPage(+ setup([+ withModel(lab, "qwen3-coder-30b:Q4_K_M", {+ endpoint: { base_url: "http://127.0.0.1:18100/v1" },+ }),+ ]),+ );+ await findModels();++ expect(statuses()[0]).toBe("Qwen3 Coder 30B: Loaded · GPU 0 · 21.4 GB");+ fireEvent.click(screen.getByRole("button", { name: "Qwen3 Coder 30B" }));+ expect(+ screen.getByRole("region", { name: "Qwen3 Coder 30B details" }),+ ).toHaveTextContent("http://127.0.0.1:18100/v1");+ });++ it("keeps the chosen Computer in the address", async () => {+ renderPage(setup(), "?computer=computer-mac");+ await findModels();+ expect(statuses()[0]).toBe("GPT-OSS 20B: Loaded · Memory · 14.3 GB");+ expect(screen.getByText("14.3 GB of 51.2 GB memory in use")).toBeVisible();++ fireEvent.click(screen.getByRole("combobox", { name: "Computer" }));+ fireEvent.click(await screen.findByRole("option", { name: "lab-118" }));++ await waitFor(() =>+ expect(+ screen.getByText("Address search: ?computer=computer-lab"),+ ).toBeVisible(),+ );+ await waitFor(() =>+ expect(statuses()[0]).toBe("Qwen3 Coder 30B: Loaded · GPU 0 · 21.4 GB"),+ );+ });++ it("opens the desktop app's own Computer when the address names none", async () => {+ (window as { lingerDesktop?: unknown }).lingerDesktop = {+ computer: {+ enroll: () => Promise.reject(new Error("not used")),+ getStatus: () =>+ Promise.resolve({+ activeOperations: 0,+ bridge: "connected",+ computerId: "computer-mac",+ runtime: "ready",+ }),+ onStatus: () => () => undefined,+ },+ };+ renderPage(setup());++ await waitFor(() =>+ expect(+ screen.getByRole("combobox", { name: "Computer" }),+ ).toHaveTextContent("Mac Studio"),+ );+ await waitFor(() =>+ expect(statuses()[0]).toBe("GPT-OSS 20B: Loaded · Memory · 14.3 GB"),+ );+ });+});diff --git a/apps/web/src/features/local-models/local-models-page.tsx b/apps/web/src/features/local-models/local-models-page.tsxnew file mode 100644index 00000000..c9e46572--- /dev/null+++ b/apps/web/src/features/local-models/local-models-page.tsx@@ -0,0 +1,470 @@+import { AiChipIcon } from "@hugeicons/core-free-icons";+import {+ useMutation,+ useMutationState,+ useQuery,+ useQueryClient,+ useSuspenseQuery,+} from "@tanstack/react-query";+import { type ReactNode, useState } from "react";+import { Link, useParams, useSearchParams } from "react-router";++import { Button } from "@/components/ui/button";+import { FormFeedback } from "@/components/ui/form-feedback";+import { Icon } from "@/components/ui/icon";+import { Select, SelectItem } from "@/components/ui/select";+import { relativeTime } from "@/features/local-computer/computer-relative-time";+import { useDesktopComputer } from "@/features/local-computer/desktop-computer";+import { localComputersQueryOptions } from "@/features/local-computer/local-computer-queries";+import { requireRoomRouteParam } from "@/features/rooms/room-route-params";+import { TeamHubError } from "@/features/teamhub/teamhub-error";+import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";+import { formatBytes } from "@/lib/format-bytes";++import { AdvancedDialog } from "./local-model-details";+import { ModelRow } from "./local-model-row";+import {+ MakeRoomDialog,+ RemoveModelDialog,+ UnloadModelDialog,+} from "./local-model-dialogs";+import { actionErrorCopy, libraryUnavailableCopy } from "./local-models-copy";+import {+ actOnLocalComputerModel,+ localModelActionMutationKey,+ localModelsQueryKey,+ localModelsQueryOptions,+ type LocalModelActionInput,+ type LocalModelsView,+} from "./local-models-queries";+import {+ loadCheck,+ memorySummary,+ modelEntries,+ type ModelEntry,+ type ModelStatus,+} from "./local-models-rules";++type Dialog =+ | { kind: "advanced" }+ | { kind: "makeRoom"; modelId: string }+ | { kind: "remove"; modelId: string }+ | { kind: "unload"; modelId: string };++/** The model states each confirmed action applies to, as the row offers it. */+const actionStatuses: Record<"load" | "remove" | "unload", ModelStatus[]> = {+ load: ["idle", "failed"],+ remove: ["loaded", "idle", "failed"],+ unload: ["loaded"],+};++function computersPath(tenantId: string) {+ return `/t/${tenantId}/settings/computers`;+}++/**+ * The model library of one Computer, chosen by `?computer=`. Without it the+ * desktop app opens its own Computer and a browser the first one.+ */+export function LocalModelsPage() {+ const { client } = useTeamHubRuntime();+ const tenantId = requireRoomRouteParam(useParams().tenantId, "Tenant");+ const { data: inventory } = useSuspenseQuery(+ localComputersQueryOptions(client, tenantId),+ );+ const desktop = useDesktopComputer();+ const [searchParams, setSearchParams] = useSearchParams();+ const computers = inventory.items;+ const linkedId = searchParams.get("computer");+ const requestedId = linkedId ?? desktop?.status?.computerId;+ const owned = computers.find((item) => item.computer_id === requestedId);+ // A linked Computer the viewer does not own may be another member's: the+ // library API, not the owned inventory, decides whether they may read it.+ const sharedId = linkedId && !owned ? linkedId : undefined;+ const computer = sharedId ? undefined : (owned ?? computers[0]);++ function select(computerId: string) {+ setSearchParams(+ (current) => {+ const next = new URLSearchParams(current);+ next.set("computer", computerId);+ return next;+ },+ { replace: true },+ );+ }++ return (+ <main className="mx-auto flex min-h-0 w-full max-w-(--app-settings-width) flex-col pb-4">+ {sharedId ? (+ <ComputerModels+ computerId={sharedId}+ computerPicker={null}+ key={sharedId}+ tenantId={tenantId}+ />+ ) : computer ? (+ <ComputerModels+ computerId={computer.computer_id}+ displayName={computer.display_name}+ computerPicker={+ computers.length > 1 ? (+ <Select+ aria-label="Computer"+ onValueChange={select}+ value={computer.computer_id}+ variant="pill"+ >+ {computers.map((item) => (+ <SelectItem key={item.computer_id} value={item.computer_id}>+ {item.status === "online"+ ? item.display_name+ : `${item.display_name} · Offline`}+ </SelectItem>+ ))}+ </Select>+ ) : null+ }+ key={computer.computer_id}+ tenantId={tenantId}+ />+ ) : (+ <>+ <h1 className="text-2xl text-foreground">Local models</h1>+ <EmptyState title="No computers yet">+ Connect a computer in{" "}+ <Link+ className="text-foreground underline underline-offset-2"+ to={computersPath(tenantId)}+ >+ Computers+ </Link>{" "}+ to download and run models on it.+ </EmptyState>+ </>+ )}+ </main>+ );+}++function EmptyState({+ action,+ children,+ title,+}: {+ action?: ReactNode;+ children: ReactNode;+ title: string;+}) {+ return (+ <section+ aria-label={title}+ className="mt-6 flex flex-col items-center px-4 pt-12 text-center"+ >+ <span className="flex size-16 items-center justify-center rounded-[20%] bg-muted text-foreground">+ <Icon icon={AiChipIcon} size={28} />+ </span>+ <h2 className="mt-6 text-xl">{title}</h2>+ <p className="mt-1.5 max-w-md text-sm text-muted-foreground">+ {children}+ </p>+ {action}+ </section>+ );+}++function Notice({ children }: { children: ReactNode }) {+ return (+ <p+ className="mt-6 rounded-xl bg-muted px-3.5 py-3 text-sm text-muted-foreground"+ role="status"+ >+ {children}+ </p>+ );+}++function ComputerModels({+ computerId,+ computerPicker,+ displayName,+ tenantId,+}: {+ computerId: string;+ computerPicker: ReactNode;+ /** Absent for a Computer outside the viewer's own inventory. */+ displayName?: string;+ tenantId: string;+}) {+ const { client } = useTeamHubRuntime();+ const query = useQuery(localModelsQueryOptions(client, tenantId, computerId));+ const view = query.data;+ const [dialog, setDialog] = useState<Dialog | null>(null);+ const summary = view?.available ? memorySummary(view) : undefined;++ return (+ <>+ <header className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h1 className="text-2xl text-foreground">Local models</h1>+ {summary?.totalBytes ? (+ <p className="mt-1.5 text-sm text-muted-foreground">+ {formatBytes(summary.usedBytes)} of{" "}+ {formatBytes(summary.totalBytes)}{" "}+ {summary.gpu ? "GPU memory" : "memory"} in use+ </p>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {computerPicker}+ {view?.available ? (+ <Button+ onClick={() => setDialog({ kind: "advanced" })}+ size="compact"+ >+ Details+ </Button>+ ) : null}+ </div>+ </header>++ {view ? (+ <Library+ dialog={dialog}+ setDialog={setDialog}+ tenantId={tenantId}+ view={view}+ />+ ) : query.isError ? (+ <EmptyState+ action={+ <Button+ className="mt-6"+ onClick={() => void query.refetch()}+ size="compact"+ >+ Try again+ </Button>+ }+ title={`Couldn't load the models of ${displayName ?? "this computer"}`}+ >+ {actionErrorCopy(+ query.error instanceof TeamHubError ? query.error.code : undefined,+ )}+ </EmptyState>+ ) : (+ <p className="mt-6 text-sm text-muted-foreground" role="status">+ Loading models+ </p>+ )}+ </>+ );+}++function Library({+ dialog,+ setDialog,+ tenantId,+ view,+}: {+ dialog: Dialog | null;+ setDialog: (dialog: Dialog | null) => void;+ tenantId: string;+ view: LocalModelsView;+}) {+ const { client } = useTeamHubRuntime();+ const queryClient = useQueryClient();+ const computerId = view.computer.computer_id;+ const name = view.computer.display_name;+ const [expandedId, setExpandedId] = useState<string | null>(null);+ const [failure, setFailure] = useState<{+ code?: string;+ modelId: string;+ } | null>(null);+ const mutationKey = localModelActionMutationKey(tenantId, computerId);+ const action = useMutation({+ mutationFn: (input: LocalModelActionInput) =>+ actOnLocalComputerModel(client, tenantId, computerId, input),+ mutationKey,+ onError: (error, input) =>+ setFailure({+ code: error instanceof TeamHubError ? error.code : undefined,+ modelId: input.modelId,+ }),+ onMutate: () => setFailure(null),+ // The Computer answers at once; a fresh read shows what it started even+ // before its next snapshot hint.+ onSettled: () =>+ queryClient.invalidateQueries({+ queryKey: localModelsQueryKey(tenantId, computerId),+ }),+ });+ const pendingIds = new Set(+ useMutationState({+ filters: { mutationKey, status: "pending" },+ select: (mutation) =>+ (mutation.state.variables as LocalModelActionInput | undefined)+ ?.modelId,+ }),+ );+ const offline = view.computer.status === "offline";+ const readOnly = !view.viewer_is_owner;+ // A dialog stays open across snapshots, so its confirm checks the model+ // and Computer as they are now, the way the row's buttons do.+ const confirmable = (+ entry: ModelEntry,+ action: "load" | "remove" | "unload",+ ) =>+ !offline &&+ !readOnly &&+ !pendingIds.has(entry.model.id) &&+ actionStatuses[action].includes(entry.status);+ const entries = view.available ? modelEntries(view) : [];+ const find = (modelId: string) =>+ entries.find((entry) => entry.model.id === modelId);+ const dialogEntry =+ dialog && dialog.kind !== "advanced" ? find(dialog.modelId) : undefined;+ const makeRoom =+ dialog?.kind === "makeRoom" && dialogEntry+ ? loadCheck(view, dialogEntry.model)+ : null;+ const failedEntry = failure ? find(failure.modelId) : undefined;++ function act(input: LocalModelActionInput) {+ setDialog(null);+ action.mutate(input);+ }++ function load(entry: ModelEntry) {+ if (loadCheck(view, entry.model))+ setDialog({ kind: "makeRoom", modelId: entry.model.id });+ else act({ action: "load", modelId: entry.model.id });+ }++ function unload(entry: ModelEntry) {+ if (entry.used_by.length)+ setDialog({ kind: "unload", modelId: entry.model.id });+ else act({ action: "unload", modelId: entry.model.id });+ }++ const unavailable = view.available+ ? undefined+ : libraryUnavailableCopy(view.reason?.code, name);++ return (+ <>+ {offline ? (+ <Notice>+ <span className="text-foreground">+ {name} is offline+ {view.computer.last_seen_at+ ? ` (last seen ${relativeTime(view.computer.last_seen_at)})`+ : ""}+ .+ </span>{" "}+ This is what it last reported.+ {readOnly ? null : (+ <>+ {" "}+ Reconnect it in{" "}+ <Link+ className="text-foreground underline underline-offset-2"+ to={computersPath(tenantId)}+ >+ Computers+ </Link>{" "}+ to manage its models.+ </>+ )}+ </Notice>+ ) : null}+ {readOnly ? (+ <Notice>+ Only the person who connected {name} can download, load or remove its+ models.+ </Notice>+ ) : null}++ {unavailable ? (+ <EmptyState title={unavailable.title}>{unavailable.body}</EmptyState>+ ) : (+ <>+ {failure ? (+ <div className="mt-6">+ <FormFeedback tone="danger">+ {failedEntry ? `${failedEntry.model.name}: ` : null}+ {actionErrorCopy(failure.code)}+ </FormFeedback>+ </div>+ ) : null}+ <section aria-label="Models" className="mt-6 grid gap-2">+ {entries.map((entry) => {+ const modelId = entry.model.id;+ return (+ <ModelRow+ disabled={offline || readOnly || pendingIds.has(modelId)}+ entry={entry}+ expanded={expandedId === modelId}+ key={modelId}+ onCancel={() => act({ action: "cancel", modelId })}+ onDownload={() => act({ action: "download", modelId })}+ onLoad={() => load(entry)}+ onRemove={() => setDialog({ kind: "remove", modelId })}+ onToggle={() =>+ setExpandedId((current) =>+ current === modelId ? null : modelId,+ )+ }+ onUnload={() => unload(entry)}+ view={view}+ />+ );+ })}+ </section>+ </>+ )}++ {dialog?.kind === "advanced" ? (+ <AdvancedDialog onClose={() => setDialog(null)} view={view} />+ ) : null}+ {dialogEntry && makeRoom ? (+ <MakeRoomDialog+ check={makeRoom}+ disabled={!confirmable(dialogEntry, "load")}+ entry={dialogEntry}+ onClose={() => setDialog(null)}+ onConfirm={(unloadFirst) =>+ act({+ action: "load",+ modelId: dialogEntry.model.id,+ unloadFirst,+ })+ }+ view={view}+ />+ ) : null}+ {dialogEntry && dialog?.kind === "unload" ? (+ <UnloadModelDialog+ disabled={!confirmable(dialogEntry, "unload")}+ entry={dialogEntry}+ onClose={() => setDialog(null)}+ onConfirm={() =>+ act({ action: "unload", modelId: dialogEntry.model.id })+ }+ view={view}+ />+ ) : null}+ {dialogEntry && dialog?.kind === "remove" ? (+ <RemoveModelDialog+ disabled={!confirmable(dialogEntry, "remove")}+ entry={dialogEntry}+ onClose={() => setDialog(null)}+ onConfirm={() =>+ act({ action: "remove", modelId: dialogEntry.model.id })+ }+ view={view}+ />+ ) : null}+ </>+ );+}diff --git a/apps/web/src/features/local-models/local-models-queries.ts b/apps/web/src/features/local-models/local-models-queries.tsnew file mode 100644index 00000000..72a2e970--- /dev/null+++ b/apps/web/src/features/local-models/local-models-queries.ts@@ -0,0 +1,81 @@+import type { components } from "@linger/wire-contracts/teamhub-public/types";+import { queryOptions } from "@tanstack/react-query";++import { teamHubData } from "@/features/teamhub/teamhub-api";+import type { TeamHubClient } from "@/features/teamhub/teamhub-client";++type Schemas = components["schemas"];+export type LocalModelsView = Schemas["LocalModelsView"];+export type LocalModelView = Schemas["LocalModelView"];+export type LocalModel = Schemas["LocalModel"];+export type LocalModelPool = Schemas["LocalModelPool"];+export type LocalModelHost = Schemas["LocalModelHost"];+export type LocalModelActionRequest = Schemas["LocalModelActionRequest"];+export type LocalModelAction = LocalModelActionRequest["action"];++const localModelsPath =+ "/v0/tenants/{tenantId}/local-computers/{computerId}/local-models";+const localModelActionPath =+ "/v0/tenants/{tenantId}/local-computers/{computerId}/local-models/{modelId}/actions";++/** Every Computer's local-models view of a Tenant: the prefix a computers hint refreshes. */+export function tenantLocalModelsQueryKey(tenantId: string) {+ return ["teamhub", tenantId, "local-models"] as const;+}++export function localModelsQueryKey(tenantId: string, computerId: string) {+ return [...tenantLocalModelsQueryKey(tenantId), computerId] as const;+}++/**+ * One Computer's model library as it last reported it. A local-models hint+ * with the Computer ID refreshes it while a download or load runs.+ */+export function localModelsQueryOptions(+ client: TeamHubClient,+ tenantId: string,+ computerId: string,+) {+ return queryOptions({+ queryFn: ({ signal }) =>+ teamHubData(+ client.api.GET(localModelsPath, {+ params: { path: { computerId, tenantId } },+ signal,+ }),+ ),+ queryKey: localModelsQueryKey(tenantId, computerId),+ retry: false,+ });+}++/** Identifies pending actions of one Computer, so each row can show its own. */+export function localModelActionMutationKey(+ tenantId: string,+ computerId: string,+) {+ return ["teamhub", tenantId, "local-model-action", computerId] as const;+}++export interface LocalModelActionInput {+ action: LocalModelAction;+ modelId: string;+ unloadFirst?: string[];+}++/** Asks the Computer to start an action; the outcome arrives as a new snapshot. */+export function actOnLocalComputerModel(+ client: TeamHubClient,+ tenantId: string,+ computerId: string,+ { action, modelId, unloadFirst }: LocalModelActionInput,+) {+ return teamHubData(+ client.api.POST(localModelActionPath, {+ body: unloadFirst?.length+ ? { action, unload_first: unloadFirst }+ : { action },+ params: { path: { computerId, modelId, tenantId } },+ }),+ );+}diff --git a/apps/web/src/features/local-models/local-models-rules.test.ts b/apps/web/src/features/local-models/local-models-rules.test.tsnew file mode 100644index 00000000..54b25417--- /dev/null+++ b/apps/web/src/features/local-models/local-models-rules.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from "vitest";++import {+ downloadPercent,+ loadCheck,+ makeRoomSelection,+ makesRoom,+ memorySummary,+ modelEntries,+ placeName,+ poolLabel,+} from "./local-models-rules";+import {+ gb,+ gpuPool,+ labView,+ localModel,+ macView,+ modelView,+} from "./local-models-test-support";++function loaded(id: string, memoryGb: number, usedBy: string[] = []) {+ return modelView(+ localModel({+ id,+ memory_bytes: gb(memoryGb),+ name: id,+ pool: "gpu:0",+ state: "loaded",+ }),+ usedBy,+ );+}++describe("local models rules", () => {+ it("orders models by status, then the recommended one, then by fit", () => {+ expect(+ modelEntries(labView()).map(+ (entry) => `${entry.model.name}: ${entry.status}`,+ ),+ ).toEqual([+ "Qwen3 Coder 30B: loaded",+ "Gemma 3 27B: idle",+ "GPT-OSS 20B: available",+ "Gemma 3 4B: available",+ "Llama 3.3 70B: available",+ "Llama 3.1 405B: unavailable",+ ]);+ });++ it("names pools from what the Computer reported", () => {+ const view = labView();+ expect(view.pools.map((pool) => poolLabel(view, pool))).toEqual([+ "GPU 0 · RTX 4090",+ "GPU 1 · RTX 4090",+ "System memory",+ ]);+ expect(placeName(view, "gpu:1")).toBe("GPU 1");+ expect(placeName(view, "system")).toBe("system memory");+ expect(placeName(macView(), "unified")).toBe("memory");+ // A model that fits nowhere has no placement to show.+ expect(placeName(view, undefined)).toBeUndefined();+ });++ it("adds up GPU memory, or the memory of a Computer without GPUs", () => {+ expect(memorySummary(labView())).toEqual({+ gpu: true,+ totalBytes: gb(24) * 2,+ usedBytes: gb(21.4) + gb(1.1),+ });+ expect(memorySummary(macView())).toEqual({+ gpu: false,+ totalBytes: gb(51.2),+ usedBytes: gb(14.3),+ });+ });++ it("loads at once when the reported pool has room", () => {+ const view = labView();+ const gemma = view.models.find(+ (item) => item.model.name === "Gemma 3 27B",+ )!;+ expect(loadCheck(view, gemma.model)).toBeNull();+ });++ it("lists the other loaded models of a full pool", () => {+ const view = macView();+ const llama = view.models.find(+ (item) => item.model.name === "Llama 3.3 70B",+ )!;+ const check = loadCheck(view, llama.model)!;+ expect(check.needBytes).toBe(gb(46));+ expect(check.freeBytes).toBe(gb(51.2) - gb(14.3));+ expect(check.loaded.map((entry) => entry.model.name)).toEqual([+ "GPT-OSS 20B",+ ]);+ });++ it("preselects the fewest models, preferring ones no Agent uses", () => {+ const pool = gpuPool(0, 24, [{ gb: 22, id: "taken", name: "taken" }]);+ const big = loaded("big-used", 12, ["Research agent"]);+ const small = loaded("small-unused", 6);+ const medium = loaded("medium-unused", 9);+ const check = {+ freeBytes: gb(2),+ loaded: [big, small, medium].map((item) => ({+ ...item,+ status: "loaded" as const,+ })),+ needBytes: gb(12),+ pool,+ };++ // Fewest first: the one used model frees enough where no single unused+ // one does; with a larger need, two unused models beat a used one.+ expect(makeRoomSelection(check)).toEqual(["big-used"]);+ expect(makeRoomSelection({ ...check, needBytes: gb(17) })).toEqual([+ "medium-unused",+ "small-unused",+ ]);+ expect(makeRoomSelection({ ...check, needBytes: gb(40) })).toEqual([]);+ expect(makesRoom(check, new Set(["small-unused"]))).toBe(false);+ expect(makesRoom(check, new Set(["small-unused", "medium-unused"]))).toBe(+ true,+ );+ });++ it("reports download progress in whole percent", () => {+ expect(+ downloadPercent(+ localModel({+ download: { done_bytes: 333, step: "download", total_bytes: 1000 },+ id: "m",+ name: "m",+ state: "downloading",+ }),+ ),+ ).toBe(33);+ expect(downloadPercent(localModel({ id: "m", name: "m" }))).toBe(0);+ });+});diff --git a/apps/web/src/features/local-models/local-models-rules.ts b/apps/web/src/features/local-models/local-models-rules.tsnew file mode 100644index 00000000..89772d35--- /dev/null+++ b/apps/web/src/features/local-models/local-models-rules.ts@@ -0,0 +1,192 @@+import type {+ LocalModel,+ LocalModelPool,+ LocalModelsView,+ LocalModelView,+} from "./local-models-queries";++/**+ * Presentation rules of the Local models page. The Computer decides fit,+ * availability, placement, the recommendation and every memory figure; these+ * rules only order, label and add up what it reported.+ */++/**+ * Every status a model has on one Computer, in list order. The first five+ * are on the Computer (or downloading to it); the last two are not.+ */+export const modelStatuses = [+ "loaded",+ "loading",+ "failed",+ "idle",+ "downloading",+ "available",+ "unavailable",+] as const;++export type ModelStatus = (typeof modelStatuses)[number];++export interface ModelEntry extends LocalModelView {+ status: ModelStatus;+}++export function modelStatus(model: LocalModel): ModelStatus {+ if (model.state !== "absent") return model.state;+ return model.availability.downloadable ? "available" : "unavailable";+}++const fitOrder: Record<LocalModel["fit"], number> = {+ gpu: 0,+ none: 2,+ system: 1,+ unified: 0,+};++/** The library as one list: by status, then the recommended model, then by fit. */+export function modelEntries(view: LocalModelsView): ModelEntry[] {+ return view.models+ .map((item) => ({ ...item, status: modelStatus(item.model) }))+ .sort(+ (a, b) =>+ modelStatuses.indexOf(a.status) - modelStatuses.indexOf(b.status) ||+ Number(b.model.recommended) - Number(a.model.recommended) ||+ fitOrder[a.model.fit] - fitOrder[b.model.fit],+ );+}++/** The pool a model lives in; none when it fits nowhere or the pool is unreported. */+export function poolOf(view: LocalModelsView, poolId: string | undefined) {+ return poolId === undefined+ ? undefined+ : view.pools.find((pool) => pool.id === poolId);+}++function gpuName(view: LocalModelsView, pool: LocalModelPool) {+ return view.computer.host?.gpus.find((gpu) => gpu.index === pool.gpu_index)+ ?.name;+}++/** A pool's full name: "GPU 0 · RTX 4090", "System memory", "Unified memory". */+export function poolLabel(view: LocalModelsView, pool: LocalModelPool) {+ if (pool.kind === "system") return "System memory";+ if (pool.kind === "unified") return "Unified memory";+ const name = gpuName(view, pool);+ return name ? `GPU ${pool.gpu_index} · ${name}` : `GPU ${pool.gpu_index}`;+}++/**+ * A pool's short name for status lines: "GPU 0", "system memory", "memory".+ * Undefined without a pool, so no placement is shown.+ */+export function placeName(view: LocalModelsView, poolId: string | undefined) {+ const pool = poolOf(view, poolId);+ if (!pool) return undefined;+ if (pool.kind === "gpu") return `GPU ${pool.gpu_index}`;+ return pool.kind === "system" ? "system memory" : "memory";+}++export function poolFreeBytes(pool: LocalModelPool) {+ return Math.max(0, pool.total_bytes - pool.used_bytes);+}++/** What the header adds up: GPU memory when the Computer has GPUs, else its memory. */+export function memorySummary(view: LocalModelsView) {+ const gpus = view.pools.filter((pool) => pool.kind === "gpu");+ const pools = gpus.length ? gpus : view.pools;+ return {+ gpu: gpus.length > 0,+ totalBytes: pools.reduce((sum, pool) => sum + pool.total_bytes, 0),+ usedBytes: pools.reduce((sum, pool) => sum + pool.used_bytes, 0),+ };+}++export interface LoadCheck {+ pool: LocalModelPool;+ needBytes: number;+ freeBytes: number;+ /** Loaded models in the same pool, the ones the user could unload. */+ loaded: ModelEntry[];+}++/** Why a model cannot load now, or `null` when its pool reports room for it. */+export function loadCheck(+ view: LocalModelsView,+ model: LocalModel,+): LoadCheck | null {+ const pool = poolOf(view, model.pool);+ if (!pool || poolFreeBytes(pool) >= model.memory_bytes) return null;+ return {+ freeBytes: poolFreeBytes(pool),+ loaded: modelEntries(view).filter(+ (entry) =>+ entry.status === "loaded" &&+ entry.model.pool === pool.id &&+ entry.model.id !== model.id,+ ),+ needBytes: model.memory_bytes,+ pool,+ };+}++function freedBytes(entries: ModelEntry[]) {+ return entries.reduce((sum, entry) => sum + entry.model.memory_bytes, 0);+}++/**+ * The models Make room preselects: the fewest that free enough memory, and+ * among those the fewest an Agent uses. Empty when unloading all of them is+ * still not enough.+ */+export function makeRoomSelection(check: LoadCheck): string[] {+ const deficit = check.needBytes - check.freeBytes;+ const largestFirst = (a: ModelEntry, b: ModelEntry) =>+ b.model.memory_bytes - a.model.memory_bytes;+ const unused = check.loaded+ .filter((entry) => entry.used_by.length === 0)+ .sort(largestFirst);+ const used = check.loaded+ .filter((entry) => entry.used_by.length > 0)+ .sort(largestFirst);+ // For a count and a number of used models, the largest of each group free+ // the most, so checking those picks is exhaustive.+ for (let count = 1; count <= check.loaded.length; count += 1) {+ for (let usedCount = 0; usedCount <= count; usedCount += 1) {+ const pick = [+ ...unused.slice(0, count - usedCount),+ ...used.slice(0, usedCount),+ ];+ if (pick.length === count && freedBytes(pick) >= deficit)+ return pick.map((entry) => entry.model.id);+ }+ }+ return [];+}++/** Whether unloading the selected models makes room. */+export function makesRoom(check: LoadCheck, selectedIds: ReadonlySet<string>) {+ const freed = freedBytes(+ check.loaded.filter((entry) => selectedIds.has(entry.model.id)),+ );+ return check.freeBytes + freed >= check.needBytes;+}++/** Whole-percent download progress. */+export function downloadPercent(model: LocalModel) {+ const download = model.download;+ if (!download?.total_bytes) return 0;+ return Math.min(+ 100,+ Math.floor((download.done_bytes / download.total_bytes) * 100),+ );+}++/** Context length in thousands of tokens, as model cards write it: 128K. */+export function contextLabel(tokens: number) {+ return `${Math.round(tokens / 1024)}K tokens`;+}++/** Agent names joined for a sentence. */+export function agentNames(entry: Pick<LocalModelView, "used_by">) {+ return entry.used_by.map((user) => user.name).join(", ");+}diff --git a/apps/web/src/features/local-models/local-models-test-support.ts b/apps/web/src/features/local-models/local-models-test-support.tsnew file mode 100644index 00000000..a635add4--- /dev/null+++ b/apps/web/src/features/local-models/local-models-test-support.ts@@ -0,0 +1,270 @@+import type {+ LocalModel,+ LocalModelPool,+ LocalModelsView,+ LocalModelView,+} from "./local-models-queries";++/** Bytes of `value` gigabytes, as the page formats them back. */+export function gb(value: number) {+ return Math.round(value * 1024 ** 3);+}++export function localModel(+ fields: Partial<LocalModel> & Pick<LocalModel, "id" | "name">,+): LocalModel {+ return {+ availability: { downloadable: true },+ context_tokens: 131_072,+ description: `${fields.name} for tests.`,+ download_bytes: gb(10),+ fit: "gpu",+ memory_bytes: gb(12),+ pool: "gpu:0",+ quant: "Q4_K_M",+ recommended: false,+ state: "absent",+ vision: false,+ ...fields,+ };+}++export function modelView(+ model: LocalModel,+ usedBy: string[] = [],+): LocalModelView {+ return {+ model,+ used_by: usedBy.map((name, index) => ({+ agent_id: `agent-${model.id}-${index}`,+ name,+ })),+ };+}++export function gpuPool(+ index: number,+ totalGb: number,+ holders: { id: string; name: string; gb: number; component?: boolean }[] = [],+): LocalModelPool {+ return {+ gpu_index: index,+ holders: holders.map((holder) => ({+ bytes: gb(holder.gb),+ id: holder.id,+ kind: holder.component ? "component" : "model",+ name: holder.name,+ })),+ id: `gpu:${index}`,+ kind: "gpu",+ total_bytes: gb(totalGb),+ used_bytes: gb(holders.reduce((sum, holder) => sum + holder.gb, 0)),+ };+}++export function memoryPool(+ kind: "system" | "unified",+ totalGb: number,+ holders: { id: string; name: string; gb: number }[] = [],+): LocalModelPool {+ return {+ holders: holders.map((holder) => ({+ bytes: gb(holder.gb),+ id: holder.id,+ kind: "model",+ name: holder.name,+ })),+ id: kind,+ kind,+ total_bytes: gb(totalGb),+ used_bytes: gb(holders.reduce((sum, holder) => sum + holder.gb, 0)),+ };+}++const coder = localModel({+ download_bytes: gb(18.6),+ endpoint: {+ base_url: "http://127.0.0.1:18100/v1",+ },+ id: "qwen3-coder-30b:Q4_K_M",+ memory_bytes: gb(21.4),+ name: "Qwen3 Coder 30B",+ pi_model: "localmodels-library/qwen3-coder-30b",+ pool: "gpu:0",+ state: "loaded",+ tokens_per_second: 46.2,+});++/**+ * A Linux Computer with two 24 GB cards: one model loaded on GPU 0, an+ * embedding component on GPU 1, and every other status the list shows.+ */+export function labView(+ fields: Partial<LocalModelsView> = {},+): LocalModelsView {+ return {+ available: true,+ computer: {+ computer_id: "computer-lab",+ display_name: "lab-118",+ host: {+ arch: "x86_64",+ disk_free_bytes: gb(412),+ engine_label: "llama.cpp b11370 · CUDA",+ gpus: [+ {+ free_bytes: gb(2.6),+ index: 0,+ name: "RTX 4090",+ total_bytes: gb(24),+ },+ {+ free_bytes: gb(22.9),+ index: 1,+ name: "RTX 4090",+ total_bytes: gb(24),+ },+ ],+ os_label: "Ubuntu 24.04",+ platform: "linux",+ ram_total_bytes: gb(128),+ },+ status: "online",+ },+ models: [+ modelView(coder, ["Research agent", "Code reviewer"]),+ modelView(+ localModel({+ download_bytes: gb(16.5),+ id: "gemma3-27b:Q4_K_M",+ memory_bytes: gb(19.2),+ name: "Gemma 3 27B",+ pi_model: "localmodels-library/gemma3-27b",+ pool: "gpu:1",+ state: "idle",+ }),+ ),+ modelView(+ localModel({+ download_bytes: gb(3.3),+ id: "gemma3-4b:Q4_K_M",+ memory_bytes: gb(4.1),+ name: "Gemma 3 4B",+ pool: "gpu:1",+ }),+ ),+ modelView(+ localModel({+ download_bytes: gb(42.5),+ fit: "system",+ id: "llama3.3-70b:Q4_K_M",+ memory_bytes: gb(46),+ name: "Llama 3.3 70B",+ pool: "system",+ }),+ ),+ modelView(+ localModel({+ download_bytes: gb(12.1),+ id: "gpt-oss-20b:Q4_K_M",+ memory_bytes: gb(14.3),+ name: "GPT-OSS 20B",+ pool: "gpu:1",+ recommended: true,+ }),+ ),+ modelView(+ localModel({+ availability: {+ downloadable: false,+ reason: {+ code: "MEMORY_INSUFFICIENT",+ have_bytes: gb(102.4),+ need_bytes: gb(230),+ },+ },+ download_bytes: gb(220),+ fit: "none",+ id: "llama3.1-405b:Q4_K_M",+ memory_bytes: gb(230),+ name: "Llama 3.1 405B",+ // A model that fits nowhere has no pool.+ pool: undefined,+ }),+ ),+ ],+ observed_at: "2026-11-13T10:00:00.000Z",+ pools: [+ gpuPool(0, 24, [{ gb: 21.4, id: coder.id, name: coder.name }]),+ gpuPool(1, 24, [+ { component: true, gb: 1.1, id: "embedding", name: "Qwen3 Embedding" },+ ]),+ memoryPool("system", 102.4),+ ],+ tool_version: "0.9.0",+ viewer_is_owner: true,+ ...fields,+ };+}++/**+ * A Mac with one unified pool: one model loaded for Another Me and one that+ * failed to load because the pool is full.+ */+export function macView(+ fields: Partial<LocalModelsView> = {},+): LocalModelsView {+ const gptOss = localModel({+ download_bytes: gb(12.1),+ endpoint: {+ base_url: "http://127.0.0.1:18100/v1",+ },+ fit: "unified",+ id: "gpt-oss-20b:Q4_K_M",+ memory_bytes: gb(14.3),+ name: "GPT-OSS 20B",+ pi_model: "localmodels-library/gpt-oss-20b",+ pool: "unified",+ state: "loaded",+ });+ return {+ available: true,+ computer: {+ computer_id: "computer-mac",+ display_name: "Mac Studio",+ host: {+ arch: "arm64",+ disk_free_bytes: gb(188),+ engine_label: "llama.cpp b11370 · Metal",+ gpus: [],+ os_label: "macOS 26",+ platform: "darwin",+ ram_total_bytes: gb(64),+ },+ status: "online",+ },+ models: [+ modelView(gptOss, ["Another Me"]),+ modelView(+ localModel({+ download_bytes: gb(42.5),+ error: { code: "LOAD_NO_ROOM", detail: "need 46 GiB, free 36.9 GiB" },+ fit: "unified",+ id: "llama3.3-70b:Q4_K_M",+ memory_bytes: gb(46),+ name: "Llama 3.3 70B",+ pool: "unified",+ state: "failed",+ }),+ ),+ ],+ observed_at: "2026-11-13T10:00:00.000Z",+ pools: [+ memoryPool("unified", 51.2, [+ { gb: 14.3, id: gptOss.id, name: gptOss.name },+ ]),+ ],+ viewer_is_owner: true,+ ...fields,+ };+}diff --git a/apps/web/src/features/rooms/event-sync.test.tsx b/apps/web/src/features/rooms/event-sync.test.tsxindex b3303610..eca0d269 100644--- a/apps/web/src/features/rooms/event-sync.test.tsx+++ b/apps/web/src/features/rooms/event-sync.test.tsx@@ -7,6 +7,7 @@ import { render } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";+import { localModelsQueryKey } from "@/features/local-models/local-models-queries";import { teamHubDocumentsQueryKey } from "@/features/teamhub/document-queries";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";import type { TeamHubRoomEvent } from "@/features/teamhub/teamhub-types";@@ -139,6 +140,33 @@ describe("TeamHub event signals", () => {observer.stop();});+ it("refreshes only the named Computer's models for a local-models hint", async () => {+ const queryClient = new QueryClient();+ const lab = observe(queryClient, localModelsQueryKey("tenant-a", "lab"));+ const mac = observe(queryClient, localModelsQueryKey("tenant-a", "mac"));+ await vi.waitFor(() => expect(lab.fetch).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(mac.fetch).toHaveBeenCalledOnce());++ await applyTeamHubEventSignal(queryClient, {+ hint: { id: "lab", resource: "local-models", tenant_id: "tenant-a" },+ type: "resource.invalidated",+ });++ await vi.waitFor(() => expect(lab.fetch).toHaveBeenCalledTimes(2));+ expect(mac.fetch).toHaveBeenCalledOnce();++ // A Computer's connection and its Agents are part of every models view.+ await applyTeamHubEventSignal(queryClient, {+ hint: { id: "tenant-a", resource: "computers", tenant_id: "tenant-a" },+ type: "resource.invalidated",+ });++ await vi.waitFor(() => expect(lab.fetch).toHaveBeenCalledTimes(3));+ await vi.waitFor(() => expect(mac.fetch).toHaveBeenCalledTimes(2));+ lab.stop();+ mac.stop();+ });+it("refreshes the directory, the Room members and the Room list it shows", async () => {const queryClient = new QueryClient();const members = observe(diff --git a/apps/web/src/features/rooms/event-sync.tsx b/apps/web/src/features/rooms/event-sync.tsxindex e0f96496..30850ee1 100644--- a/apps/web/src/features/rooms/event-sync.tsx+++ b/apps/web/src/features/rooms/event-sync.tsx@@ -12,6 +12,10 @@ import {tenantExternalConnectionsQueryKey,} from "@/features/apps/connected-apps-queries";import { localComputersQueryKey } from "@/features/local-computer/local-computer-queries";+import {+ localModelsQueryKey,+ tenantLocalModelsQueryKey,+} from "@/features/local-models/local-models-queries";import { teamHubDocumentsQueryKey } from "@/features/teamhub/document-queries";import type { TeamHubEventSignal } from "@/features/teamhub/event-transport";import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";@@ -158,7 +162,17 @@ async function applyInvalidation(case "computers":await Promise.all([refreshAgentStatus(queryClient, tenantId),- refreshActiveQueries(queryClient, [localComputersQueryKey(tenantId)]),+ // A Local models view carries its Computer's connection and the+ // Agents that use each model.+ refreshActiveQueries(queryClient, [+ localComputersQueryKey(tenantId),+ tenantLocalModelsQueryKey(tenantId),+ ]),+ ]);+ return;+ case "local-models":+ await refreshActiveQueries(queryClient, [+ localModelsQueryKey(tenantId, hint.id),]);return;case "another-me":diff --git a/apps/web/src/features/settings/settings-page.tsx b/apps/web/src/features/settings/settings-page.tsxindex 01dafba1..d060d046 100644--- a/apps/web/src/features/settings/settings-page.tsx+++ b/apps/web/src/features/settings/settings-page.tsx@@ -1,4 +1,9 @@-import { Key01Icon, LaptopIcon, UserIcon } from "@hugeicons/core-free-icons";+import {+ AiChipIcon,+ Key01Icon,+ LaptopIcon,+ UserIcon,+} from "@hugeicons/core-free-icons";import { Icon } from "@/components/ui/icon";import { Suspense, type ReactNode } from "react";import { NavLink, Outlet, useLocation } from "react-router";@@ -36,6 +41,11 @@ export function SettingsLayout() {label="Computers"to="computers"/>+ <SettingsLink+ icon={<Icon icon={AiChipIcon} size={14} />}+ label="Local models"+ to="local-models"+ /></nav></aside><div className="workspace-content-viewport workspace-scrollbar flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto px-6 py-6 md:px-8">diff --git a/apps/web/src/features/settings/settings-pages.test.tsx b/apps/web/src/features/settings/settings-pages.test.tsxindex 91bdb036..92e5a7fb 100644--- a/apps/web/src/features/settings/settings-pages.test.tsx+++ b/apps/web/src/features/settings/settings-pages.test.tsx@@ -168,7 +168,7 @@ describe("Settings surfaces", () => {within(settingsNav).getAllByRole("link").map((link) => link.textContent?.replace(/\s+/g, " ").trim()),- ).toEqual(["Profile", "Security", "Computers"]);+ ).toEqual(["Profile", "Security", "Computers", "Local models"]);expect(screen.queryByRole("button", { name: "Log out" }),).not.toBeInTheDocument();diff --git a/apps/web/src/features/teamhub/event-transport.ts b/apps/web/src/features/teamhub/event-transport.tsindex 93074631..960bb870 100644--- a/apps/web/src/features/teamhub/event-transport.ts+++ b/apps/web/src/features/teamhub/event-transport.ts@@ -60,6 +60,7 @@ const invalidationResources = {directory: true,document: true,"document-access": true,+ "local-models": true,room: true,"work-items": true,} satisfies Record<TeamHubInvalidationResource, true>;diff --git a/apps/web/src/features/teamhub/teamhub-types.ts b/apps/web/src/features/teamhub/teamhub-types.tsindex f57fe0c6..652d8c1c 100644--- a/apps/web/src/features/teamhub/teamhub-types.ts+++ b/apps/web/src/features/teamhub/teamhub-types.ts@@ -364,7 +364,8 @@ export type TeamHubInvalidationResource =| "connections"| "work-items"| "document"- | "document-access";+ | "document-access"+ | "local-models";export interface TeamHubResourceInvalidation {id: string;resource: TeamHubInvalidationResource;