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.
fix(web): harden local models settings UX, sync, and responsive layout
Dongdong Chena5a3d1421684
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex a3e45dd7..bd54b4ce 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -27,40 +27,44 @@ build:assets` to check the initial JS budget.Its tabs read and switch the Computer's model source (Local model, BYOK)through TeamHub's `model-source` API, which asks the Computer live; the pageoffers no switch to Subscription, and a Computer already on one opens on- Local model; the page never holds a saved API key, and a switch refused- with `AGENT_HAS_ACTIVE_RUNS` retries with `force_terminate` only after the- owner confirms. The Local model tab is 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 (including external-app- cleanup & `Recheck memory` prompts when other apps occupy pool memory or- unified memory is constrained), shows an explicit `Memory guidance` banner and- `Recheck memory` button (`POST .../local-models`), lets owners pick among- installed local models in `SwitchToLocalNotice` or click `Use for Agents` on a- loaded row, renders tinted family- icon tiles, Agent usage counts, structured capability/parameter badges (never- matched against `name` or `description`), state-distinct cards (`loaded`,- `recommended`, `failed`, `unavailable`), download speed/ETA, live Bifrost- (`Pi`) `Gateway` readiness, and top- diagnostic callouts with a two-column model-card facts grid from structured- `LocalModel` fields in `local-models-rules.ts`, resolves Sponsor-owned Agent- eligibility and `Pi` runtime switch payloads in `local-model-agents.ts`- (`Use with <Another Me>`, `Open chat`, `Switch Agent…` in `Used by`, and- `Make room` automatic Agent handoff once the replacement model loads when `Pi`- is ready), and maps every code and enum- label 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. From the click- until a snapshot with another status or observation time, or a refusal, the- row shows a requested load or download as started, labels a cancel, unload- or remove under way (Cancelling, Unloading, Removing), and spins that- action's button, with the row's actions off; a download the Computer- accepted can be cancelled before its first progress. Make room lists what- else holds the pool (components, and other apps from `used_bytes` no holder+ Local model; the page never holds a saved API key (reusing a saved key only+ for the saved endpoint's origin, clearing entered keys after saving, offering+ manual model ID entry even when endpoints list models, and disabling BYOK+ edits while offline), and a switch refused with `AGENT_HAS_ACTIVE_RUNS`+ retries with `force_terminate` only after the owner confirms. The Local model+ tab is 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 (including+ external-app cleanup & `Recheck memory` prompts when other apps occupy pool+ memory or unified memory is constrained), shows an explicit `Memory guidance`+ banner and `Recheck memory` button (`POST .../local-models`), lets owners+ pick among installed local models in `SwitchToLocalNotice` or click+ `Use for Agents` on a loaded row, renders tinted family icon tiles, Agent+ usage counts, structured capability/parameter badges (never matched against+ `name` or `description`), state-distinct cards (`loaded`, `recommended`,+ `failed` with short failure reasons and direct `Remove` for damaged/missing+ files, `unavailable`), download speed/ETA, live Bifrost (`Pi`) `Gateway`+ readiness, and top diagnostic callouts with a two-column model-card facts+ grid from structured `LocalModel` fields in `local-models-rules.ts`, resolves+ Sponsor-owned Agent eligibility and `Pi` runtime switch payloads in+ `local-model-agents.ts` (`Use with <Another Me>`, `Open chat`,+ `Switch Agent…` in `Used by`, and `Make room` automatic Agent handoff once+ the replacement model loads when `Pi` is ready), and maps every code and enum+ label to English in `local-models-copy.ts`. Without `?computer=` the desktop+ app opens its own Computer and a browser prefers an online Computer. Only the+ Computer's owner can act; actions return at once and progress arrives as+ `local-models` invalidation hints (while `directory` hints and model-source+ switches keep `Used by` and Agent registrations synchronized). From the click+ until a snapshot with another status, error code, or observation time, or a+ refusal (or while offline), the row shows a requested load or download as+ started, labels a cancel, unload or remove under way (Cancelling, Unloading,+ Removing), and spins that action's button, with the row's actions off; a+ download the Computer accepted can be cancelled before its first progress.+ Make room filters stale unloaded IDs out of `unload_first`, lists what else+ holds the pool (components, and other apps from `used_bytes` no holderaccounts for) when unloading models cannot free enough, and says a model- cannot fit only when it needs more than the pool's total. A Computer's- detail on the Computers page links here and reads no model state itself.+ cannot fit only when it needs more than the pool's total. 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/features/local-computer/computer-hint.tsx b/apps/web/src/features/local-computer/computer-hint.tsxindex 3794c248..51a3c6e8 100644--- a/apps/web/src/features/local-computer/computer-hint.tsx+++ b/apps/web/src/features/local-computer/computer-hint.tsx@@ -32,7 +32,7 @@ export function Hint({{children}<spanclassName={cn(- "pointer-events-none invisible absolute left-1/2 z-30 w-max max-w-64 -translate-x-1/2 rounded-md bg-primary px-2 py-1 text-left text-xs font-normal text-primary-foreground opacity-0 transition-opacity delay-200 duration-150 group-focus-within/hint:visible group-focus-within/hint:opacity-100 group-hover/hint:visible group-hover/hint:opacity-100 motion-reduce:transition-none",+ "pointer-events-none invisible absolute left-1/2 z-30 w-max max-w-64 -translate-x-1/2 rounded-md bg-primary px-2 py-1 text-left text-xs font-normal text-primary-foreground opacity-0 transition-opacity delay-200 duration-150 group-focus-visible/hint:visible group-focus-visible/hint:opacity-100 group-has-[:focus-visible]/hint:visible group-has-[:focus-visible]/hint:opacity-100 group-hover/hint:visible group-hover/hint:opacity-100 motion-reduce:transition-none",placement === "top" ? "bottom-full mb-1.5" : "top-full mt-1.5",)}id={tooltipId}diff --git a/apps/web/src/features/local-models/local-model-details.tsx b/apps/web/src/features/local-models/local-model-details.tsxindex d89b4b33..97c466f0 100644--- a/apps/web/src/features/local-models/local-model-details.tsx+++ b/apps/web/src/features/local-models/local-model-details.tsx@@ -1,4 +1,4 @@-import { useState, type ReactNode } from "react";+import { useEffect, useRef, useState, type ReactNode } from "react";import {Copy01Icon,LinkSquare02Icon,@@ -79,17 +79,46 @@ function Fact({function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) {const [copied, setCopied] = useState(false);+ const timerRef = useRef<number | undefined>(undefined);+ const codeRef = useRef<HTMLElement>(null);++ useEffect(+ () => () => {+ window.clearTimeout(timerRef.current);+ },+ [],+ );++ function markCopied() {+ window.clearTimeout(timerRef.current);+ setCopied(true);+ timerRef.current = window.setTimeout(() => setCopied(false), 1_500);+ }++ function copy() {+ const clipboard = navigator.clipboard;+ if (clipboard?.writeText) {+ void clipboard.writeText(endpoint).then(+ () => markCopied(),+ () => selectCodeText(codeRef.current),+ );+ return;+ }+ selectCodeText(codeRef.current);+ }+return (<span className="flex items-center gap-1">- <code className="min-w-0 truncate font-mono text-xs">{endpoint}</code>+ <code className="min-w-0 truncate font-mono text-xs" ref={codeRef}>+ {endpoint}+ </code><Button- aria-label={`Copy ${name} endpoint`}- onClick={() => {- void navigator.clipboard- ?.writeText(endpoint)- .then(() => setCopied(true));- }}+ aria-label={+ copied ? `Copied ${name} endpoint` : `Copy ${name} endpoint`+ }+ onClick={copy}size="compactIcon"+ title={copied ? "Copied" : "Copy endpoint"}tone="ghost"><Icon icon={copied ? Tick02Icon : Copy01Icon} size={14} />@@ -98,6 +127,16 @@ function CopyEndpoint({ endpoint, name }: { endpoint: string; name: string }) {);}+function selectCodeText(element: HTMLElement | null) {+ if (!element) return;+ const selection = window.getSelection();+ if (!selection) return;+ const range = document.createRange();+ range.selectNodeContents(element);+ selection.removeAllRanges();+ selection.addRange(range);+}+function gatewayFactValue(entry: ModelEntry,view: LocalModelsView,@@ -139,6 +178,7 @@ export function ModelFacts({computer,disabled = false,entry,+ hasPrimaryAssignAction = false,onAssignAgent,view,}: {@@ -147,6 +187,7 @@ export function ModelFacts({computer?: TeamHubLocalComputerPage["items"][number];disabled?: boolean;entry: ModelEntry;+ hasPrimaryAssignAction?: boolean;onAssignAgent?: (agent: AssignableLocalModelAgent) => void;view: LocalModelsView;}) {@@ -170,6 +211,8 @@ export function ModelFacts({poolFreeBytes(pool) < model.memory_bytes;const computerId = view.computer.computer_id;const usedNames = usedByAgentNames(entry, assignableAgents, computerId);+ const idleUsedWarning =+ status === "idle" && !model.note && usedNames.length > 0;const unassigned = assignableAgents.filter((agent) => !isAgentUsingModel(entry, agent, computerId),);@@ -178,7 +221,10 @@ export function ModelFacts({status === "loaded" &&Boolean(model.pi_model) &&Boolean(onAssignAgent) &&- (unassigned.some((agent) => !agent.isAnotherMe) || unassigned.length > 1);+ unassigned.length > 0 &&+ (!hasPrimaryAssignAction ||+ unassigned.some((agent) => !agent.isAnotherMe) ||+ unassigned.length > 1);const primaryBusy =status === "loaded" &&Boolean(model.pi_model) &&@@ -218,6 +264,15 @@ export function ModelFacts({</Fact></div>) : null}+ {idleUsedWarning ? (+ <div className="my-1.5">+ <FormFeedback tone="warning">+ {usedNames.join(", ")} {usedNames.length === 1 ? "uses" : "use"}{" "}+ this model. Load it so {usedNames.length === 1 ? "it" : "they"} can+ answer.+ </FormFeedback>+ </div>+ ) : null}{availableNeedsRoom ? (<div className="my-1.5"><FormFeedback tone="warning">@@ -289,7 +344,9 @@ export function ModelFacts({);if (target) onAssignAgent(target);}}- placeholder="Switch Agent…"+ placeholder={+ assigningAgentId ? "Switching…" : "Switch Agent…"+ }value=""variant="pill">@@ -367,17 +424,19 @@ function PoolBar({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} · ${formatGigabytes(holder.bytes)}`}- />- ))}+ {pool.holders+ .filter((holder) => holder.bytes > 0)+ .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} · ${formatGigabytes(holder.bytes)}`}+ />+ ))}{otherBytes ? (<spanclassName="h-full bg-muted-foreground/30"@@ -402,9 +461,20 @@ export function AdvancedDialog({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");+ type PoolHolder = LocalModelPool["holders"][number];+ const seenHolderIds = new Set<string>();+ const models: PoolHolder[] = [];+ const components: PoolHolder[] = [];+ let hasOtherApps = false;+ for (const pool of view.pools) {+ if (poolOtherBytes(pool) > 0) hasOtherApps = true;+ for (const holder of pool.holders) {+ if (seenHolderIds.has(holder.id)) continue;+ seenHolderIds.add(holder.id);+ if (holder.kind === "model") models.push(holder);+ else components.push(holder);+ }+ }const colorOf = (holderId: string) => {const index = models.findIndex((holder) => holder.id === holderId);return index < 0@@ -425,30 +495,56 @@ export function AdvancedDialog({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))}+ {view.pools.length ? (+ <>+ <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}/>- {holder.name}- </span>- ))}- </p>+ ))}+ </div>+ {seenHolderIds.size > 0 || hasOtherApps ? (+ <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>+ ))}+ {hasOtherApps ? (+ <span className="flex items-center gap-1.5">+ <span+ aria-hidden+ className="size-1.5 rounded-full bg-muted-foreground/30"+ />+ Other apps+ </span>+ ) : null}+ </p>+ ) : null}+ </>) : null}{host ? (<>- <h3 className="mt-5 mb-1 text-sm font-medium text-muted-foreground">+ <h3+ className={cn(+ "mb-1 text-sm font-medium text-muted-foreground",+ view.pools.length > 0 && "mt-5",+ )}+ >Hardware</h3><div>diff --git a/apps/web/src/features/local-models/local-model-dialogs.tsx b/apps/web/src/features/local-models/local-model-dialogs.tsxindex 166c9f18..b6a58e24 100644--- a/apps/web/src/features/local-models/local-model-dialogs.tsx+++ b/apps/web/src/features/local-models/local-model-dialogs.tsx@@ -9,10 +9,10 @@ import { cn } from "@/lib/cn";import {type AssignableLocalModelAgent,isAgentUsingModel,+ usedByAgentNames,} from "./local-model-agents";import type { LocalModelsView } from "./local-models-queries";import {- agentNames,formatGigabytes,makeRoomSelection,makesRoom,@@ -26,16 +26,16 @@ import {/** The amber notice naming the Agents that stop answering. */function AffectedAgents({- entry,+ names,until,}: {- entry: ModelEntry;+ names: readonly string[];until: string;}) {- const count = entry.used_by.length;+ const count = names.length;return count ? (<FormFeedback tone="warning">- {agentNames(entry)} {count === 1 ? "uses" : "use"} this model and+ {names.join(", ")} {count === 1 ? "uses" : "use"} this model andcan't answer until {until}.</FormFeedback>) : (@@ -69,7 +69,10 @@ export function MakeRoomDialog({const [selected, setSelected] = useState(() => makeRoomSelection(check));const [switchAgents, setSwitchAgents] = useState(true);const roomFreeNow = check.freeBytes >= check.needBytes;- const effectiveSelected = roomFreeNow ? [] : selected;+ const loadedIds = new Set(check.loaded.map((item) => item.model.id));+ const effectiveSelected = roomFreeNow+ ? []+ : selected.filter((id) => loadedIds.has(id));const chosen = new Set(effectiveSelected);const enough = roomFreeNow || makesRoom(check, chosen);const pool = poolLabel(view, check.pool);@@ -88,16 +91,27 @@ export function MakeRoomDialog({...(otherBytes ? [{ bytes: otherBytes, id: "", name: "Other apps" }] : []),...check.kept,];+ const computerId = view.computer.computer_id;const chosenLoaded = check.loaded.filter((item) => chosen.has(item.model.id));- const affected = chosenLoaded.flatMap((item) =>- item.used_by.map((user) => user.name),+ const selectedFreedBytes = chosenLoaded.reduce(+ (sum, item) => sum + item.model.memory_bytes,+ 0,);+ const remainingShortfallBytes = Math.max(+ 0,+ check.needBytes - (check.freeBytes + selectedFreedBytes),+ );+ const affected = [+ ...new Set(+ chosenLoaded.flatMap((item) =>+ usedByAgentNames(item, assignableAgents, computerId),+ ),+ ),+ ];const affectedAssignable = assignableAgents.filter((agent) =>!agent.busy &&- chosenLoaded.some((item) =>- isAgentUsingModel(item, agent, view.computer.computer_id),- ),+ chosenLoaded.some((item) => isAgentUsingModel(item, agent, computerId)),);const canSwitchOnLoad =Boolean(entry.model.pi_model) && affectedAssignable.length > 0;@@ -174,9 +188,16 @@ export function MakeRoomDialog({{item.model.name}</span><span className="text-xs text-muted-foreground">- {item.used_by.length- ? `Used by ${agentNames(item)}`- : "Not used"}+ {(() => {+ const names = usedByAgentNames(+ item,+ assignableAgents,+ computerId,+ );+ return names.length+ ? `Used by ${names.join(", ")}`+ : "Not used";+ })()}</span><span className="w-16 text-right text-xs tabular-nums text-muted-foreground">{formatGigabytes(item.model.memory_bytes)}@@ -223,6 +244,11 @@ export function MakeRoomDialog({unnecessary apps and click Recheck memory to free the remainingroom.</FormFeedback>+ ) : reachable && !enough && remainingShortfallBytes > 0 ? (+ <FormFeedback tone="info">+ Select at least {formatGigabytes(remainingShortfallBytes)} more to+ unload before loading {entry.model.name}.+ </FormFeedback>) : null}{affected.length ? (<FormFeedback tone="warning">@@ -251,12 +277,14 @@ export function MakeRoomDialog({/** Unloading a model an Agent uses stops that Agent, so it asks first. */export function UnloadModelDialog({+ assignableAgents = [],disabled,entry,onClose,onConfirm,view,}: {+ assignableAgents?: readonly AssignableLocalModelAgent[];/** The action no longer applies, or its Computer takes no actions. */disabled: boolean;entry: ModelEntry;@@ -265,6 +293,11 @@ export function UnloadModelDialog({view: LocalModelsView;}) {const pool = poolOf(view, entry.model.pool);+ const names = usedByAgentNames(+ entry,+ assignableAgents,+ view.computer.computer_id,+ );return (<ModalDialogdescription={`Frees ${formatGigabytes(entry.model.memory_bytes)} of ${@@ -283,19 +316,21 @@ export function UnloadModelDialog({title={`Unload ${entry.model.name}?`}><div className="px-5 py-4">- <AffectedAgents entry={entry} until="it is loaded again" />+ <AffectedAgents names={names} until="it is loaded again" /></div></ModalDialog>);}export function RemoveModelDialog({+ assignableAgents = [],disabled,entry,onClose,onConfirm,view,}: {+ assignableAgents?: readonly AssignableLocalModelAgent[];/** The action no longer applies, or its Computer takes no actions. */disabled: boolean;entry: ModelEntry;@@ -303,6 +338,11 @@ export function RemoveModelDialog({onConfirm: () => void;view: LocalModelsView;}) {+ const names = usedByAgentNames(+ entry,+ assignableAgents,+ view.computer.computer_id,+ );return (<ModalDialogdescription={`${@@ -324,8 +364,8 @@ export function RemoveModelDialog({><div className="px-5 py-4"><AffectedAgents- entry={entry}- until={`you choose another model for ${entry.used_by.length === 1 ? "it" : "them"}`}+ names={names}+ until={`you choose another model for ${names.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.tsxindex b6f06473..df3f48bb 100644--- a/apps/web/src/features/local-models/local-model-row.tsx+++ b/apps/web/src/features/local-models/local-model-row.tsx@@ -27,7 +27,7 @@ import {usedByAgentNames,} from "./local-model-agents";import { ModelFacts } from "./local-model-details";-import { unavailableShortCopy } from "./local-models-copy";+import { modelErrorShortCopy, unavailableShortCopy } from "./local-models-copy";import type {LocalModel,LocalModelAction,@@ -312,13 +312,17 @@ function DownloadProgress({model: LocalModel;progress: number;}) {+ const shownProgress =+ model.download?.step === "verify" && !model.download.total_bytes+ ? 100+ : progress;return (<div className="px-4 pb-3"><spanaria-label={`${model.name} download progress`}aria-valuemax={100}aria-valuemin={0}- aria-valuenow={progress}+ aria-valuenow={shownProgress}className="block h-1.5 overflow-hidden rounded-full bg-muted"role="progressbar">@@ -328,7 +332,7 @@ function DownloadProgress({model.download?.step === "verify" &&"animate-pulse motion-reduce:animate-none",)}- style={{ transform: `scaleX(${progress / 100})` }}+ style={{ transform: `scaleX(${shownProgress / 100})` }}/></span></div>@@ -415,11 +419,19 @@ export function ModelRow({Boolean(onAssignAgent);const { badges, overflowTitle } = collapsedRowBadges(model);const hasMeta = Boolean(usedBy) || badges.length > 0;+ const damagedFiles =+ status === "failed" &&+ (model.error?.code === "CHECKSUM_MISMATCH" ||+ model.error?.code === "MODEL_FILES_MISSING");const detail = {available: download,downloading: started ? null : downloadStatusDetail(model),- failed: null,- idle: model.note ? "no room to load yet" : null,+ failed: modelErrorShortCopy(model.error) ?? null,+ idle: model.note+ ? "no room to load yet"+ : usedNames.length+ ? "load to answer"+ : null,loaded: [where ? `${where[0]!.toUpperCase()}${where.slice(1)}` : undefined,formatGigabytes(model.memory_bytes),@@ -436,13 +448,21 @@ export function ModelRow({downloading: ["Cancel", handlers.onCancel, "cancel"],failed: stopped? (["Resume download", handlers.onDownload, "download"] as const)- : (["Retry", handlers.onLoad, "load"] as const),+ : damagedFiles+ ? (["Remove", handlers.onRemove, "remove"] as const)+ : (["Retry", handlers.onLoad, "load"] as const),idle: ["Load", handlers.onLoad, "load"],loaded: ["Unload", handlers.onUnload, "unload"],loading: null,unavailable: null,} as const)[status];+ const showsPrimaryAssignButton =+ !(status === "loaded" && handlers.onUseForAgents) &&+ canUsePrimary &&+ Boolean(primaryAgent) &&+ !primaryUsing &&+ Boolean(onAssignAgent);// A stopped download has no record to remove; discarding it deletes the// kept partial instead.const removable =@@ -470,7 +490,7 @@ export function ModelRow({aria-expanded={expanded}aria-label={model.name}className={cn(- "col-start-1 row-start-1 flex min-w-0 items-center gap-3 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ "col-span-2 col-start-1 row-start-1 flex min-w-0 items-center gap-3 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring @md:col-span-1",status === "unavailable" && "opacity-60",)}onClick={handlers.onToggle}@@ -511,8 +531,8 @@ export function ModelRow({) : null}<divclassName={cn(- "col-start-2 row-start-1 flex shrink-0 items-center gap-1.5",- hasMeta && "@2xl:col-start-3",+ "col-span-2 flex flex-wrap items-center justify-end gap-1.5 pl-13 @md:col-span-1 @md:col-start-2 @md:row-start-1 @md:flex-nowrap @md:pl-0",+ hasMeta ? "row-start-3 @2xl:col-start-3" : "row-start-2",)}>{status === "loaded" && handlers.onUseForAgents ? (@@ -530,10 +550,7 @@ export function ModelRow({>Use for Agents</Button>- ) : canUsePrimary &&- primaryAgent &&- !primaryUsing &&- onAssignAgent ? (+ ) : showsPrimaryAssignButton && primaryAgent && onAssignAgent ? (<Buttonaria-label={`Use ${model.name} with ${primaryAgent.name}`}className="px-2.5"@@ -576,9 +593,11 @@ export function ModelRow({tone={status === "downloading"? "ghost"- : recommended- ? "primary"- : "secondary"+ : damagedFiles+ ? "danger"+ : recommended+ ? "primary"+ : "secondary"}>{action[0]}@@ -624,6 +643,7 @@ export function ModelRow({computer={computer}disabled={disabled}entry={entry}+ hasPrimaryAssignAction={showsPrimaryAssignButton}onAssignAgent={onAssignAgent}view={view}/>diff --git a/apps/web/src/features/local-models/local-models-copy.ts b/apps/web/src/features/local-models/local-models-copy.tsindex 8b19e115..0df39e44 100644--- a/apps/web/src/features/local-models/local-models-copy.ts+++ b/apps/web/src/features/local-models/local-models-copy.ts@@ -39,6 +39,9 @@ const actionRefusals: Record<Schemas["LocalModelsErrorCode"], string> = {/** Why an action or a read failed: a TeamHub error code, or anything else. */export function actionErrorCopy(code: string | undefined) {+ if (code === "LOCAL_COMPUTER_NOT_FOUND") {+ return "This computer wasn't found. It may have been removed.";+ }return code && Object.hasOwn(actionRefusals, code)? actionRefusals[code as keyof typeof actionRefusals]: "Something went wrong. Try again.";@@ -76,6 +79,35 @@ const modelErrorCauses: Record<: "It loaded, but Agents couldn't be given access to it: a Linger folder on the computer belongs to another account.",};+const modelErrorsShort: Record<+ Schemas["LocalModelErrorCode"],+ string | undefined+> = {+ CANCELLED: "loading stopped",+ CHECKSUM_MISMATCH: "files damaged",+ DISK_INSUFFICIENT: "not enough disk",+ DOWNLOAD_FAILED: undefined,+ ENGINE_START_FAILED: "engine didn't start",+ GATEWAY_REGISTRATION_FAILED: "Agents couldn't reach it",+ HEALTH_CHECK_FAILED: "model didn't answer",+ INVALID_STATE: "busy with another step",+ JOB_RUNNING: "busy with another step",+ LOAD_NO_ROOM: "not enough free memory",+ MEMORY_INSUFFICIENT: "not enough memory",+ MODEL_FILES_MISSING: "files missing",+ MODEL_UNKNOWN: "no longer on computer",+ NETWORK_UNAVAILABLE: "network unavailable",+ OUT_OF_MEMORY: "ran out of memory",+ PLATFORM_UNSUPPORTED: "not for this computer",+};++/** Short failure summary for a collapsed model row; undefined when the status label suffices. */+export function modelErrorShortCopy(+ error: Schemas["LocalModelError"] | undefined,+) {+ return error ? modelErrorsShort[error.code] : undefined;+}+/*** Why the last load or download of a model failed. A cause names the fix;* its path reaches only the Computer's owner.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.tsxindex c3024fb8..edf0eeb2 100644--- a/apps/web/src/features/local-models/local-models-page.test.tsx+++ b/apps/web/src/features/local-models/local-models-page.test.tsx@@ -475,7 +475,11 @@ describe("LocalModelsPage", () => {await renderPage(fixture);await findModels();- expect(statusOf("Llama 3.3 70B")).toBe("Download stopped");+ expect(statusOf("Llama 3.3 70B")).toBe(+ code === "NETWORK_UNAVAILABLE"+ ? "Download stopped · network unavailable"+ : "Download stopped",+ );expect(screen.queryByRole("button", { name: "Retry Llama 3.3 70B" }),).toBeNull();@@ -654,7 +658,9 @@ describe("LocalModelsPage", () => {await renderPage(fixture);await findModels();- expect(statusOf("Llama 3.3 70B")).toBe("Couldn't load");+ expect(statusOf("Llama 3.3 70B")).toBe(+ "Couldn't load · engine didn't start",+ );fireEvent.click(screen.getByRole("button", { name: "Llama 3.3 70B" }));const details = screen.getByRole("region", {name: "Llama 3.3 70B details",@@ -704,7 +710,9 @@ describe("LocalModelsPage", () => {await renderPage(fixture, "?computer=computer-mac");await findModels();- expect(statuses()).toContain("Llama 3.3 70B: Couldn't load");+ expect(statuses()).toContain(+ "Llama 3.3 70B: Couldn't load · not enough free memory",+ );fireEvent.click(screen.getByRole("button", { name: "Llama 3.3 70B" }));const details = screen.getByRole("region", {name: "Llama 3.3 70B details",@@ -2727,5 +2735,496 @@ describe("Model source", () => {expect(alert).toHaveTextContent("Couldn't read how Agents on this computer get their model. Try again.",);+ const retry = within(alert).getByRole("button", { name: "Retry" });+ fixture.runtime.server.on("GET", modelSourcePath, ({ params }) =>+ Response.json({+ computer_id: params.computerId,+ online: true,+ status: {+ ...byokStatus,+ mode: "local",+ runtime: "pi",+ runtime_model: "localmodels-library/qwen3-coder-30b",+ },+ viewer_is_owner: true,+ }),+ );+ fireEvent.click(retry);+ expect(+ await screen.findByText("Agents on lab-118 use Local model"),+ ).toBeInTheDocument();+ });++ it("refetches model source when a Computer comes back online and disables BYOK when offline", async () => {+ const offlineLab = labView({+ computer: { ...labView().computer, status: "offline" },+ });+ const fixture = setup([offlineLab]);+ let online = false;+ fixture.runtime.server.on("GET", switchPath, ({ params }) =>+ Response.json({+ computer_id: params.computerId,+ online,+ ...(online ? { status: byokStatus } : {}),+ viewer_is_owner: true,+ }),+ );+ fixture.runtime.server.on("POST", modelsPath, () =>+ Response.json({ base_url: "https://api.example.com", models: [] }),+ );+ await renderPage(fixture);+ await findModels();++ expect(+ screen.queryByRole("tablist", { name: "Model source" }),+ ).not.toBeInTheDocument();++ online = true;+ publishSnapshot(fixture, labView());++ expect(+ await screen.findByRole("tab", { name: /BYOK/u, selected: true }),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Base URL")).toBeEnabled();++ // Going offline while viewing BYOK shows the offline notice and disables edits.+ publishSnapshot(fixture, offlineLab);+ expect(await screen.findByText(/Reconnect it in/u)).toBeInTheDocument();+ expect(screen.getByLabelText("Base URL")).toBeDisabled();+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();+ });++ it("resets stale BYOK test feedback, protects saved keys across origins, clears models on empty URL, and allows manual model IDs", async () => {+ const fixture = setup([labView()]);+ const { listings, switches, tests } = withSource(fixture, byokStatus);+ fixture.runtime.server.on("POST", switchPath, ({ body }) => {+ switches.push(body);+ return Response.json({+ computer_id: "computer-lab",+ online: true,+ status: byokStatus,+ viewer_is_owner: true,+ });+ });+ await renderPage(fixture);++ expect(await screen.findByText("2 models listed.")).toBeInTheDocument();+ const tabs = screen.getByRole("tablist", { name: "Model source" });+ expect(tabs).toHaveClass("self-start");++ // Manual model ID toggle lets owners type custom IDs even when models were listed.+ fireEvent.click(+ screen.getByRole("button", { name: "Enter model ID manually" }),+ );+ const manualInput = screen.getByLabelText("Model");+ expect(manualInput).toHaveValue("vendor/model");+ fireEvent.change(manualInput, { target: { value: "custom/alias" } });++ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));+ expect(+ await screen.findByText(/Connected to https:\/\/api\.example\.com/u),+ ).toBeInTheDocument();++ // Changing Base URL to a different origin resets test feedback and stops reusing the saved key.+ const baseUrl = screen.getByLabelText("Base URL");+ fireEvent.change(baseUrl, {+ target: { value: "https://other.example.net/v1" },+ });+ expect(+ screen.queryByText(/Connected to https:\/\/api\.example\.com/u),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/A key is saved on this computer/u),+ ).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));+ await waitFor(() => expect(tests).toHaveLength(2));+ expect(tests[1]).toEqual({+ byok: {+ base_url: "https://other.example.net/v1",+ model_id: "custom/alias",+ },+ runtime: "codex",+ });++ // Clearing Base URL clears stale listed models instead of keeping previous endpoint choices.+ fireEvent.change(baseUrl, { target: { value: "" } });+ fireEvent.blur(baseUrl);+ expect(screen.queryByText("2 models listed.")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Choose from list" }),+ ).not.toBeInTheDocument();++ // Saving while already on BYOK clears the typed API key input cleanly.+ fireEvent.change(baseUrl, {+ target: { value: "https://api.example.com/v1" },+ });+ fireEvent.change(screen.getByLabelText("API key"), {+ target: { value: "sk-rotate" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(switches).toHaveLength(1));+ await waitFor(() =>+ expect(screen.getByLabelText("API key")).toHaveValue(""),+ );+ expect(listings.length).toBeGreaterThanOrEqual(1);+ });++ it("refreshes Tenant Agents after Use for Agents and lets SwitchToLocalNotice prefer a newly loaded model", async () => {+ const idleSmall = localModel({+ id: "spark-4b:Q4_K_M",+ memory_bytes: gb(4),+ name: "Spark 4B",+ pi_model: "localmodels-library/spark-4b",+ pool: "gpu:0",+ state: "idle",+ });+ const loadedLarge = localModel({+ id: "qwen3.8-27b:IQ3_S",+ memory_bytes: gb(16),+ name: "Qwen3.8 27B",+ pi_model: "localmodels-library/qwen3.8-27b",+ pool: "gpu:0",+ state: "loaded",+ });+ const fixture = setup([labView({ models: [modelView(idleSmall)] })]);+ enableReadyPi(fixture);+ const { switches } = withSource(fixture, {+ ...byokStatus,+ mode: "byok",+ runtime: "pi",+ runtime_model: "localmodels-byok",+ });+ let agentReads = 0;+ fixture.runtime.server.on("GET", "/v0/tenants/{tenantId}/agents", () => {+ agentReads += 1;+ return {+ items: fixture.runtime.seed.tenantAgents,+ page: { has_more: false },+ };+ });+ fixture.runtime.server.on("POST", switchPath, ({ body }) => {+ switches.push(body);+ return Response.json({+ computer_id: "computer-lab",+ online: true,+ status: {+ ...byokStatus,+ mode: "local",+ runtime: "pi",+ runtime_model: "localmodels-library/qwen3.8-27b",+ },+ viewer_is_owner: true,+ });+ });+ await renderPage(fixture);++ fireEvent.click(await screen.findByRole("tab", { name: "Local model" }));+ await findModels();++ // A newly loaded model becomes the default target without sticking on the earlier idle one.+ publishSnapshot(+ fixture,+ labView({+ models: [modelView(idleSmall), modelView(loadedLarge)],+ observed_at: "2026-11-13T10:08:00.000Z",+ }),+ );+ const readsBeforeSwitch = agentReads;+ await screen.findByRole("combobox", { name: "Local model" });+ fireEvent.click(+ screen.getByRole("button", { name: "Switch to Local model" }),+ );+ await waitFor(() => expect(switches).toHaveLength(1));+ expect(switches[0]).toEqual({+ local_model_id: "qwen3.8-27b:IQ3_S",+ mode: "local",+ });+ await waitFor(() => expect(agentReads).toBeGreaterThan(readsBeforeSwitch));+ });++ it("offers Remove for damaged files, warns for unloaded models with Agents, and recovers from missing Computers or TOOL_FAILED", async () => {+ const damaged = localModel({+ error: { code: "CHECKSUM_MISMATCH" },+ id: "broken:Q4",+ memory_bytes: gb(6),+ name: "Broken 6B",+ pool: "gpu:0",+ state: "failed",+ });+ const idleUsed = localModel({+ id: "idle-used:Q4",+ memory_bytes: gb(8),+ name: "Idle Used 8B",+ pi_model: "localmodels-library/idle-used",+ pool: "gpu:1",+ state: "idle",+ });+ const offlineFirst = labView({+ computer: {+ ...labView().computer,+ computer_id: "computer-offline",+ display_name: "Old Laptop",+ status: "offline",+ },+ });+ const onlineSecond = labView({+ computer: {+ ...labView().computer,+ computer_id: "computer-online",+ display_name: "Workstation",+ status: "online",+ },+ models: [modelView(damaged), modelView(idleUsed, ["Research agent"])],+ pools: [gpuPool(0, 24), { ...gpuPool(1, 24), used_bytes: gb(5) }],+ });+ const fixture = setup(+ [offlineFirst, onlineSecond],+ [inventoryComputer(offlineFirst), inventoryComputer(onlineSecond)],+ );+ await renderPage(fixture);+ await findModels();++ // Prefers the online Computer over an earlier offline one when no ?computer= is given.+ expect(+ screen.getByRole("combobox", { name: "Computer" }),+ ).toHaveTextContent("Workstation");++ expect(statusOf("Broken 6B")).toBe("Couldn't load · files damaged");+ expect(+ screen.getByRole("button", { name: "Remove Broken 6B" }),+ ).toBeEnabled();+ expect(+ screen.queryByRole("button", { name: "Retry Broken 6B" }),+ ).toBeNull();++ expect(statusOf("Idle Used 8B")).toBe("Downloaded · load to answer");+ fireEvent.click(screen.getByRole("button", { name: "Idle Used 8B" }));+ expect(+ screen.getByRole("region", { name: "Idle Used 8B details" }),+ ).toHaveTextContent(+ "Research agent uses this model. Load it so it can answer.",+ );++ // Details modal includes Other apps in the legend when external apps hold memory.+ fireEvent.click(screen.getByRole("button", { name: "Details" }));+ const detailsDialog = screen.getByRole("dialog", {+ name: "Workstation details",+ });+ expect(detailsDialog).toHaveTextContent("Other apps");+ fireEvent.click(+ within(detailsDialog).getByRole("button", { name: "Close" }),+ );++ // A missing ?computer= shows clear copy and a button back to the owner's online Computer.+ cleanup();+ await renderPage(fixture, "?computer=computer-removed");+ expect(+ await screen.findByText(+ "This computer wasn't found. It may have been removed.",+ ),+ ).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Open Workstation" }));+ await findModels();+ expect(card("Broken 6B")).toBeVisible();++ // TOOL_FAILED offers Try again refresh when the Computer is online.+ publishSnapshot(fixture, {+ ...onlineSecond,+ available: false,+ models: [],+ observed_at: "2026-11-13T10:12:00.000Z",+ pools: [],+ reason: { code: "TOOL_FAILED" },+ });+ const retryTool = await screen.findByRole("button", { name: "Try again" });+ fireEvent.click(retryTool);+ await waitFor(() => expect(fixture.refreshes).toEqual(["computer-online"]));+ });++ it("clears optimistic action state when a snapshot lands before 202 and drops externally unloaded models from Make room", async () => {+ const baseMac = macView();+ const fixture = setup([baseMac]);+ let releaseAction!: () => void;+ fixture.runtime.server.on(+ "POST",+ actionPath,+ ({ body, params }) =>+ new Promise((resolve) => {+ fixture.actions.push({+ body,+ computerId: params.computerId!,+ modelId: params.modelId!,+ });+ releaseAction = () =>+ resolve(accepted((body as { action: string }).action));+ }),+ );+ await renderPage(fixture);+ await findModels();++ // Open Make room for Llama 3.3 70B (needs 46 GB, GPT-OSS 20B preselected).+ fireEvent.click(+ screen.getByRole("button", { name: "Retry Llama 3.3 70B" }),+ );+ const dialog = screen.getByRole("dialog", { name: "Make room to load" });+ const checkbox = within(dialog).getByRole("checkbox", {+ name: /GPT-OSS 20B/u,+ });+ // Unchecking shows the shortfall hint cleanly.+ fireEvent.click(checkbox);+ expect(dialog).toHaveTextContent(+ "Select at least 9.1 GB more to unload before loading Llama 3.3 70B.",+ );+ fireEvent.click(checkbox);++ // Another model is unloaded externally, leaving another loaded model on the pool.+ const extraLoaded = localModel({+ fit: "unified",+ id: "extra:Q4",+ memory_bytes: gb(12),+ name: "Extra 12B",+ pool: "unified",+ state: "loaded",+ });+ publishSnapshot(fixture, {+ ...baseMac,+ models: [modelView(extraLoaded), baseMac.models[1]!],+ observed_at: "2026-11-13T10:09:00.000Z",+ pools: [+ {+ holders: [+ { bytes: gb(12), id: "extra:Q4", kind: "model", name: "Extra 12B" },+ ],+ id: "unified",+ kind: "unified",+ total_bytes: gb(51.2),+ used_bytes: gb(12),+ },+ ],+ });+ const extraCheck = await within(dialog).findByRole("checkbox", {+ name: /Extra 12B/u,+ });+ fireEvent.click(extraCheck);+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Unload and load" }),+ );+ await waitFor(() => expect(fixture.actions).toHaveLength(1));+ // GPT-OSS 20B (no longer loaded) was filtered out of unload_first.+ expect(fixture.actions[0]).toEqual({+ body: { action: "load", unload_first: ["extra:Q4"] },+ computerId: "computer-mac",+ modelId: "llama3.3-70b:Q4_K_M",+ });++ // A newer snapshot arrives with the same failed status BEFORE the 202 resolves.+ publishSnapshot(fixture, {+ ...baseMac,+ models: [modelView(extraLoaded), baseMac.models[1]!],+ observed_at: "2026-11-13T10:10:00.000Z",+ });+ releaseAction();++ // Row does not stay stuck on "Loading" because observedAt was captured at click time.+ await waitFor(() =>+ expect(statusOf("Llama 3.3 70B")).toBe(+ "Couldn't load · not enough free memory",+ ),+ );+ expect(+ screen.getByRole("button", { name: "Retry Llama 3.3 70B" }),+ ).toBeEnabled();+ });++ it("preserves busy Agent warnings during mixed Make room handoff and shows queued handoff status", async () => {+ const mac = withModel(macView(), "llama3.3-70b:Q4_K_M", {+ pi_model: "localmodels-library/llama3.3-70b",+ });+ const fixture = setup([mac]);+ enableReadyPi(fixture);+ acceptTenantAgentUpdates(fixture.runtime);+ fixture.runtime.seed.tenantAgents = fixture.runtime.seed.tenantAgents.map(+ (agent) =>+ agent.actor.id === "actor-delegate" || agent.actor.id === "actor-codex"+ ? {+ ...agent,+ runtime: {+ model: "localmodels-library/gpt-oss-20b",+ placement: {+ computer_id: "computer-mac",+ runtime_type: "pi",+ type: "local",+ workspace_grant_id: "grant-linger-workspace",+ },+ },+ }+ : agent,+ );+ await renderPage(fixture, "?computer=computer-mac");+ await findModels();++ fireEvent.click(+ screen.getByRole("button", { name: "Retry Llama 3.3 70B" }),+ );+ const dialog = screen.getByRole("dialog", { name: "Make room to load" });+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Unload and load" }),+ );+ expect(+ await screen.findByText(+ "Will switch Jenny's Delegate, Codex to Llama 3.3 70B once it finishes loading.",+ ),+ ).toBeVisible();++ // Codex starts working while Jenny's Delegate stays idle.+ fixture.runtime.seed.tenantAgents = fixture.runtime.seed.tenantAgents.map(+ (agent) =>+ agent.actor.id === "actor-codex"+ ? {+ ...agent,+ availability: {+ active_task_count: 1,+ label: "Working",+ status: "online",+ },+ }+ : agent,+ );+ fixture.runtime.events.emitSignal({+ hint: { id: "actor-codex", resource: "agents", tenant_id: tenantId },+ type: "resource.invalidated",+ });+ await waitFor(() =>+ expect(+ fixture.runtime.server.requestsTo(+ "GET",+ "/v0/tenants/{tenantId}/agent-availability",+ ).length,+ ).toBeGreaterThanOrEqual(2),+ );++ publishSnapshot(+ fixture,+ withModel(mac, "llama3.3-70b:Q4_K_M", {+ endpoint: { base_url: "http://127.0.0.1:18100/v1" },+ state: "loaded",+ }),+ );++ // Idle Agent switches AND busy Agent warning survives instead of being wiped.+ await waitFor(() =>+ expect(+ fixture.runtime.server.requestsTo(+ "PATCH",+ "/v0/tenants/{tenantId}/agents/{agentId}",+ ),+ ).toHaveLength(1),+ );+ expect(+ await screen.findByText(+ "Couldn't switch Codex to Llama 3.3 70B while working. Switch once the current turn finishes.",+ ),+ ).toBeVisible();});});diff --git a/apps/web/src/features/local-models/local-models-page.tsx b/apps/web/src/features/local-models/local-models-page.tsxindex a4b00ac9..966bcee7 100644--- a/apps/web/src/features/local-models/local-models-page.tsx+++ b/apps/web/src/features/local-models/local-models-page.tsx@@ -38,6 +38,7 @@ import {assignableLocalModelAgents,buildLocalModelRuntimeUpdate,isAgentUsingModel,+ usedByAgentNames,} from "./local-model-agents";import { AdvancedDialog } from "./local-model-details";import { ModelRow } from "./local-model-row";@@ -85,6 +86,7 @@ import {} from "./model-source-panel";import {type ModelSourceMode,+ modelSourceQueryKey,modelSourceQueryOptions,type ModelSourceStatus,} from "./model-source-queries";@@ -128,10 +130,12 @@ export function ModelsPage() {const linkedId = searchParams.get("computer");const requestedId = linkedId ?? desktop?.status?.computerId;const owned = computers.find((item) => item.computer_id === requestedId);+ const defaultComputer =+ computers.find((item) => item.status === "online") ?? computers[0];// 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]);+ const computer = sharedId ? undefined : (owned ?? defaultComputer);function select(computerId: string) {setSearchParams(@@ -149,8 +153,15 @@ export function ModelsPage() {{sharedId ? (<ComputerModelscomputerId={sharedId}- computerPicker={null}+ defaultComputerName={defaultComputer?.display_name}key={sharedId}+ onOpenDefaultComputer={+ defaultComputer+ ? () => select(defaultComputer.computer_id)+ : undefined+ }+ onSelectComputer={select}+ ownedComputers={computers}tenantId={tenantId}/>) : computer ? (@@ -158,25 +169,9 @@ export function ModelsPage() {computer={computer}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}+ onSelectComputer={select}+ ownedComputers={computers}tenantId={tenantId}/>) : (@@ -238,15 +233,21 @@ function Notice({ children }: { children: ReactNode }) {function ComputerModels({computer,computerId,- computerPicker,+ defaultComputerName,displayName,+ onOpenDefaultComputer,+ onSelectComputer,+ ownedComputers,tenantId,}: {computer?: InventoryComputer;computerId: string;- computerPicker: ReactNode;+ defaultComputerName?: string;/** Absent for a Computer outside the viewer's own inventory. */displayName?: string;+ onOpenDefaultComputer?: () => void;+ onSelectComputer: (computerId: string) => void;+ ownedComputers: readonly InventoryComputer[];tenantId: string;}) {const { client } = useTeamHubRuntime();@@ -261,12 +262,42 @@ function ComputerModels({...modelSourceQueryOptions(client, tenantId, computerId),enabled: displayName !== undefined,});+ const offline = view?.computer.status === "offline";+ const onlineRefetchTriggeredRef = useRef(false);+ useEffect(() => {+ if (+ displayName !== undefined &&+ view?.computer.status === "online" &&+ source.data !== undefined &&+ !source.data.online &&+ !source.isFetching &&+ !onlineRefetchTriggeredRef.current+ ) {+ onlineRefetchTriggeredRef.current = true;+ void queryClient.invalidateQueries({+ queryKey: modelSourceQueryKey(tenantId, computerId),+ });+ return;+ }+ if (source.data?.online || view?.computer.status === "offline") {+ onlineRefetchTriggeredRef.current = false;+ }+ }, [+ computerId,+ displayName,+ queryClient,+ source.data,+ source.isFetching,+ tenantId,+ view?.computer.status,+ ]);const status = source.data?.status;const [tab, setTab] = useState<ModelSourceMode | null>(null);// A Computer on a subscription opens on Local model, which offers the way// off it; the Subscription tab is not offered.const shownTab = tab ?? (status?.mode === "byok" ? "byok" : "local");- const computerName = displayName ?? "this computer";+ const computerName =+ displayName ?? view?.computer.display_name ?? "this computer";const { feedback, switcher } = useModelSourceSwitch({computerId,computerName,@@ -294,11 +325,46 @@ function ComputerModels({view.computer.status === "online",);const guidance = view?.available ? memoryGuidance(view) : null;+ const queryErrorCode =+ query.error instanceof TeamHubError ? query.error.code : undefined;+ const showComputerPicker =+ displayName !== undefined+ ? ownedComputers.length > 1+ : Boolean(view && ownedComputers.length > 0);+ const computerPicker = showComputerPicker ? (+ <Select+ aria-label="Computer"+ onValueChange={onSelectComputer}+ value={computerId}+ variant="pill"+ >+ {displayName === undefined && view ? (+ <SelectItem value={computerId}>+ {view.computer.status === "online"+ ? view.computer.display_name+ : `${view.computer.display_name} · Offline`}+ </SelectItem>+ ) : null}+ {ownedComputers.map((item) => (+ <SelectItem key={item.computer_id} value={item.computer_id}>+ {item.status === "online"+ ? item.display_name+ : `${item.display_name} · Offline`}+ </SelectItem>+ ))}+ </Select>+ ) : null;++ function changeTab(next: ModelSourceMode) {+ setTab(next);+ setRefreshError(null);+ switcher.clearFeedback();+ }return (<>- <header className="flex items-start justify-between gap-4">- <div className="min-w-0">+ <header className="flex flex-wrap items-start justify-between gap-3 sm:gap-4">+ <div className="min-w-48 flex-1"><h1 className="text-2xl text-foreground">Models</h1>{status ? (<p className="mt-1.5 text-sm text-muted-foreground">@@ -321,7 +387,7 @@ function ComputerModels({</>) : null}</div>- <div className="flex shrink-0 items-center gap-2">+ <div className="flex flex-wrap items-center gap-2">{computerPicker}{canRecheck ? (<Button@@ -346,20 +412,30 @@ function ComputerModels({{status ? (<ModelSourceTabsactive={status.mode}- onChange={setTab}+ onChange={changeTab}value={shownTab}/>) : null}- {source.isError &&- !switcher.failure &&- view?.computer.status !== "offline" ? (+ {source.isError && !switcher.failure && !offline ? (<div className="mt-4"><FormFeedback tone="danger">- {modelSourceReadErrorCopy(- source.error instanceof TeamHubError- ? source.error.code- : undefined,- )}+ <span className="flex flex-wrap items-center gap-2">+ <span>+ {modelSourceReadErrorCopy(+ source.error instanceof TeamHubError+ ? source.error.code+ : undefined,+ )}+ </span>+ <button+ className="font-medium underline underline-offset-2 disabled:opacity-50"+ disabled={source.isFetching}+ onClick={() => void source.refetch()}+ type="button"+ >+ {source.isFetching ? "Retrying…" : "Retry"}+ </button>+ </span></FormFeedback></div>) : null}@@ -382,19 +458,40 @@ function ComputerModels({) : null}{feedback}{status && shownTab === "byok" ? (- <ByokPanel- computerId={computerId}- disabled={switching}- key={status.mode}- status={status}- switcher={switcher}- tenantId={tenantId}- />+ <>+ {offline && view ? (+ <Notice>+ <span className="text-foreground">+ {view.computer.display_name} is offline+ {view.computer.last_seen_at+ ? ` (last seen ${relativeTime(view.computer.last_seen_at)})`+ : ""}+ .+ </span>{" "}+ Reconnect it in{" "}+ <Link+ className="text-foreground underline underline-offset-2"+ to={computersPath(tenantId)}+ >+ Computers+ </Link>{" "}+ to test or change its model source.+ </Notice>+ ) : null}+ <ByokPanel+ computerId={computerId}+ disabled={switching || offline}+ key={`${status.mode}:${switcher.saveRevision}`}+ status={status}+ switcher={switcher}+ tenantId={tenantId}+ />+ </>) : view ? (<>{status && status.mode !== "local" ? (<SwitchToLocalNotice- disabled={switching || view.computer.status === "offline"}+ disabled={switching || offline}models={switchTargets}switcher={switcher}/>@@ -423,19 +520,24 @@ function ComputerModels({) : query.isError ? (<EmptyStateaction={- <Button- className="mt-6"- onClick={() => void query.refetch()}- size="compact"- >- Try again- </Button>+ <div className="mt-6 flex flex-wrap items-center justify-center gap-2">+ {onOpenDefaultComputer ? (+ <Button+ onClick={onOpenDefaultComputer}+ size="compact"+ tone="primary"+ >+ Open {defaultComputerName ?? "my computers"}+ </Button>+ ) : null}+ <Button onClick={() => void query.refetch()} size="compact">+ Try again+ </Button>+ </div>}title={`Couldn't load the models of ${displayName ?? "this computer"}`}>- {actionErrorCopy(- query.error instanceof TeamHubError ? query.error.code : undefined,- )}+ {actionErrorCopy(queryErrorCode)}</EmptyState>) : (<p className="mt-6 text-sm text-muted-foreground" role="status">@@ -502,11 +604,16 @@ function Library({} | null>(null);const completedSwitchKeyRef = useRef<string | null>(null);// An action the Computer accepted, shown on its row until a snapshot moves- // the model on: a different status or a newer snapshot.+ // the model on: a different status, error, or a newer snapshot.const [accepted, setAccepted] = useState<Record<string,- { action: LocalModelAction; from?: ModelStatus; observedAt?: string }+ {+ action: LocalModelAction;+ errorCode?: string;+ from?: ModelStatus;+ observedAt?: string;+ }>>({});const identityQuery = useQuery({@@ -575,17 +682,21 @@ function Library({},onMutate: (input) => {setFailure(null);- return { from: find(input.modelId)?.status };+ const current = find(input.modelId);+ return {+ errorCode: current?.model.error?.code,+ from: current?.status,+ observedAt: view.observed_at,+ };},onSuccess: (_result, input, started) =>setAccepted((current) => ({...current,[input.modelId]: {action: input.action,+ errorCode: started?.errorCode,from: started?.from,- observedAt: queryClient.getQueryData<LocalModelsView>(- localModelsQueryKey(tenantId, computerId),- )?.observed_at,+ observedAt: started?.observedAt,},})),// The Computer answers at once; a fresh read shows what it started even@@ -602,6 +713,7 @@ function Library({}: {agent: AssignableLocalModelAgent;piModel: string;+ preserveError?: boolean;}) =>teamHubData(client.api.PATCH("/v0/tenants/{tenantId}/agents/{agentId}", {@@ -617,15 +729,27 @@ function Library({params: { path: { agentId: agent.actorId, tenantId } },}),),- onError: (error) => {- setAssignError(- error instanceof Error- ? error.message- : "Couldn't switch the Agent to this model. Try again.",- );+ onError: (error, variables) => {+ if (!variables.preserveError) {+ setAssignError(+ error instanceof Error+ ? error.message+ : "Couldn't switch the Agent to this model. Try again.",+ );+ }+ void Promise.all([+ queryClient.invalidateQueries({+ queryKey: tenantAgentsQueryKey(tenantId),+ }),+ queryClient.invalidateQueries({+ queryKey: tenantAgentAvailabilityQueryKey(tenantId),+ }),+ ]);},- onMutate: () => {- setAssignError(null);+ onMutate: (variables) => {+ if (!variables.preserveError) {+ setAssignError(null);+ }},onSuccess: (updated) => {queryClient.setQueryData(@@ -642,6 +766,43 @@ function Library({}: current,);+ queryClient.setQueryData(+ localModelsQueryKey(tenantId, computerId),+ (current: LocalModelsView | undefined) => {+ if (!current?.available) return current;+ const placement =+ updated.runtime.placement?.type === "local"+ ? updated.runtime.placement+ : undefined;+ const onThisComputerPi =+ placement?.computer_id === computerId &&+ placement.runtime_type === "pi";+ return {+ ...current,+ models: current.models.map((item) => {+ const without = item.used_by.filter(+ (user) => user.agent_id !== updated.agent_management_id,+ );+ const matches =+ onThisComputerPi &&+ Boolean(item.model.pi_model) &&+ item.model.pi_model === updated.runtime.model;+ return {+ ...item,+ used_by: matches+ ? [+ ...without,+ {+ agent_id: updated.agent_management_id,+ name: updated.actor.display_name,+ },+ ]+ : without,+ };+ }),+ };+ },+ );void Promise.all([queryClient.invalidateQueries({queryKey: tenantAgentsQueryKey(tenantId),@@ -665,14 +826,18 @@ function Library({mutation.state.variables as LocalModelActionInput | undefined,});// The action each row shows as under way: one being sent, or one accepted- // that no snapshot reflects yet.+ // that no snapshot reflects yet. Offline snapshots stay as last reported.const requests = new Map<string, LocalModelAction>();- for (const [modelId, request] of Object.entries(accepted)) {- if (- request.observedAt === view.observed_at &&- request.from === find(modelId)?.status- )- requests.set(modelId, request.action);+ if (!offline) {+ for (const [modelId, request] of Object.entries(accepted)) {+ const current = find(modelId);+ if (+ request.observedAt === view.observed_at &&+ request.from === current?.status &&+ request.errorCode === current?.model.error?.code+ )+ requests.set(modelId, request.action);+ }}for (const input of sending) {if (input) requests.set(input.modelId, input.action);@@ -714,16 +879,27 @@ function Library({const busySkipped = matching.filter((agent) => agent.busy);const targets = matching.filter((agent) => !agent.busy);setPendingSwitch(null);- if (busySkipped.length) {- const names = busySkipped.map((agent) => agent.name).join(", ");- setAssignError(- `Couldn't switch ${names} to ${target.model.name} while working. Switch once the current turn finishes.`,- );+ const busyMessage = busySkipped.length+ ? `Couldn't switch ${busySkipped.map((agent) => agent.name).join(", ")} to ${target.model.name} while working. Switch once the current turn finishes.`+ : null;+ if (busyMessage) {+ setAssignError(busyMessage);}if (!targets.length) return;- void Promise.all(- targets.map((agent) => applyAgentAssignment({ agent, piModel })),- ).catch(() => undefined);+ void Promise.allSettled(+ targets.map((agent) =>+ applyAgentAssignment({ agent, piModel, preserveError: true }),+ ),+ ).then((results) => {+ const failedNames = targets+ .filter((_, index) => results[index]?.status === "rejected")+ .map((agent) => agent.name);+ const failureMessage = failedNames.length+ ? `Couldn't switch ${failedNames.join(", ")} to ${target.model.name}. Try again.`+ : null;+ const combined = [busyMessage, failureMessage].filter(Boolean).join(" ");+ if (combined) setAssignError(combined);+ });}, [applyAgentAssignment,assignableAgents,@@ -788,7 +964,7 @@ function Library({}function unload(entry: ModelEntry) {- if (entry.used_by.length)+ if (usedByAgentNames(entry, assignableAgents, computerId).length)setDialog({ kind: "unload", modelId: entry.model.id });else act({ action: "unload", modelId: entry.model.id });}@@ -796,6 +972,18 @@ function Library({const unavailable = view.available? undefined: libraryUnavailableCopy(view.reason?.code, name);+ const canRetryUnavailable =+ !offline && !readOnly && view.reason?.code === "TOOL_FAILED";+ const pendingSwitchTarget = pendingSwitch+ ? find(pendingSwitch.modelId)+ : undefined;+ const pendingSwitchNames: string[] = [];+ if (pendingSwitch) {+ const pendingIds = new Set(pendingSwitch.agentIds);+ for (const agent of assignableAgents) {+ if (pendingIds.has(agent.actorId)) pendingSwitchNames.push(agent.name);+ }+ }return (<>@@ -832,7 +1020,23 @@ function Library({) : null}{unavailable ? (- <EmptyState title={unavailable.title}>{unavailable.body}</EmptyState>+ <EmptyState+ action={+ canRetryUnavailable ? (+ <Button+ className="mt-6"+ loading={rechecking}+ onClick={onRefresh}+ size="compact"+ >+ Try again+ </Button>+ ) : undefined+ }+ title={unavailable.title}+ >+ {unavailable.body}+ </EmptyState>) : (<>{failure ? (@@ -848,10 +1052,18 @@ function Library({<FormFeedback tone="danger">{assignError}</FormFeedback></div>) : null}+ {pendingSwitchTarget && pendingSwitchNames.length ? (+ <div className="mt-6">+ <FormFeedback tone="info">+ Will switch {pendingSwitchNames.join(", ")} to{" "}+ {pendingSwitchTarget.model.name} once it finishes loading.+ </FormFeedback>+ </div>+ ) : null}{guidanceCopy ? (<asidearia-label="Memory guidance"- className="mt-6 flex flex-wrap items-start justify-between gap-3 rounded-xl border border-[var(--app-status-warning-border)] bg-[var(--app-status-warning-surface)] px-4 py-3"+ className="mt-6 flex flex-col items-start justify-between gap-3 rounded-xl border border-[var(--app-status-warning-border)] bg-[var(--app-status-warning-surface)] px-4 py-3 sm:flex-row"><div className="min-w-0 flex-1"><p className="text-sm font-medium text-app-warning">@@ -862,61 +1074,74 @@ function Library({</p></div>{readOnly ? null : (- <Button loading={rechecking} onClick={onRefresh} size="compact">+ <Button+ className="shrink-0"+ loading={rechecking}+ onClick={onRefresh}+ size="compact"+ >Recheck memory</Button>)}</aside>) : null}- <section aria-label="Models" className="mt-6 grid gap-2">- {entries.map((entry) => {- const modelId = entry.model.id;- const canUseForAgents =- !offline &&- !readOnly &&- status?.mode === "local" &&- entry.status === "loaded" &&- entry.model.pi_model !== status.runtime_model &&- entry.model.id !== status.runtime_model;- return (- <ModelRow- anotherMeChatHref={anotherMeChatHref}- assignableAgents={assignableAgents}- assigningAgentId={assigningAgentId}- computer={computer}- disabled={offline || readOnly || switching || busy(modelId)}- entry={entry}- expanded={expandedId === modelId}- key={modelId}- onAssignAgent={- entry.model.pi_model && canSwitchAgents- ? (agent) =>- assignMutation.mutate({- agent,- piModel: entry.model.pi_model!,- })- : undefined- }- 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)}- onUseForAgents={- canUseForAgents ? () => onUseForAgents(modelId) : undefined- }- requested={requests.get(modelId)}- switchingForAgents={switchingModelId === modelId}- view={view}- />- );- })}- </section>+ {entries.length === 0 ? (+ <EmptyState title="No local models available">+ {name} didn't list any models for this hardware yet.+ </EmptyState>+ ) : (+ <section aria-label="Models" className="mt-6 grid gap-2">+ {entries.map((entry) => {+ const modelId = entry.model.id;+ const canUseForAgents =+ !offline &&+ !readOnly &&+ status?.mode === "local" &&+ entry.status === "loaded" &&+ entry.model.pi_model !== status.runtime_model &&+ entry.model.id !== status.runtime_model;+ return (+ <ModelRow+ anotherMeChatHref={anotherMeChatHref}+ assignableAgents={assignableAgents}+ assigningAgentId={assigningAgentId}+ computer={computer}+ disabled={offline || readOnly || switching || busy(modelId)}+ entry={entry}+ expanded={expandedId === modelId}+ key={modelId}+ onAssignAgent={+ entry.model.pi_model && canSwitchAgents+ ? (agent) =>+ assignMutation.mutate({+ agent,+ piModel: entry.model.pi_model!,+ })+ : undefined+ }+ 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)}+ onUseForAgents={+ canUseForAgents+ ? () => onUseForAgents(modelId)+ : undefined+ }+ requested={requests.get(modelId)}+ switchingForAgents={switchingModelId === modelId}+ view={view}+ />+ );+ })}+ </section>+ )}</>)}@@ -950,6 +1175,7 @@ function Library({) : null}{dialogEntry && dialog?.kind === "unload" ? (<UnloadModelDialog+ assignableAgents={assignableAgents}disabled={!confirmable(dialogEntry, "unload")}entry={dialogEntry}onClose={() => setDialog(null)}@@ -961,6 +1187,7 @@ function Library({) : null}{dialogEntry && dialog?.kind === "remove" ? (<RemoveModelDialog+ assignableAgents={assignableAgents}disabled={!confirmable(dialogEntry, "remove")}entry={dialogEntry}onClose={() => setDialog(null)}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.tsindex ed6ca2e2..3749ea85 100644--- a/apps/web/src/features/local-models/local-models-rules.test.ts+++ b/apps/web/src/features/local-models/local-models-rules.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {collapsedRowBadges,+ contextLabel,downloadPercent,downloadStatusDetail,downloadStopped,@@ -16,7 +17,6 @@ import {memorySummary,modelCapabilities,modelEntries,- modelSourceLabel,parametersLabel,placeName,poolLabel,@@ -562,7 +562,41 @@ describe("local models rules", () => {expect(safeModelSourceUrl("http://example.com/model")).toBeUndefined();const safe = safeModelSourceUrl("https://huggingface.co/Qwen/Qwen3-4B/");expect(safe).toBe("https://huggingface.co/Qwen/Qwen3-4B/");- expect(modelSourceLabel(safe!)).toBe("huggingface.co/Qwen/Qwen3-4B");+ expect(+ downloadStatusDetail(+ localModel({+ download: {+ bytes_per_second: mb,+ done_bytes: 0,+ step: "download",+ total_bytes: 3590 * mb,+ },+ id: "m",+ name: "m",+ state: "downloading",+ }),+ ),+ ).toBe("0% · 1 MB/s · 1h left");+ expect(contextLabel(512)).toBe("512 tokens");+ expect(contextLabel(131_072)).toBe("128K tokens");++ // A stopped download does not trigger blocked_load memory guidance.+ const stoppedDownloadView = labView({+ models: [+ modelView(+ localModel({+ error: { code: "NETWORK_UNAVAILABLE" },+ id: "stopped:Q4",+ memory_bytes: gb(20),+ name: "Stopped",+ pool: "gpu:0",+ state: "failed",+ }),+ ),+ ],+ pools: [{ ...gpuPool(0, 24), used_bytes: gb(12) }],+ });+ expect(memoryGuidance(stoppedDownloadView)).toBeNull();});});diff --git a/apps/web/src/features/local-models/local-models-rules.ts b/apps/web/src/features/local-models/local-models-rules.tsindex 19bfc01c..af88c8a5 100644--- a/apps/web/src/features/local-models/local-models-rules.ts+++ b/apps/web/src/features/local-models/local-models-rules.ts@@ -240,7 +240,8 @@ export function memoryGuidance(view: LocalModelsView): MemoryGuidance | null {if (stats.otherBytes <= 0) continue;const poolIds = new Set(group.pools.map((pool) => pool.id));const blockedLoad = entries.some(({ model, status }) => {- if (status !== "idle" && status !== "failed") return false;+ if (status !== "idle" && (status !== "failed" || downloadStopped(model)))+ return false;if (model.pool === undefined || !poolIds.has(model.pool)) return false;const pool = poolOf(view, model.pool);if (!pool || poolOtherBytes(pool) <= 0) return false;@@ -400,6 +401,7 @@ export function downloadPercent(model: LocalModel) {/** Context length in thousands of tokens, as model cards write it: 128K. */export function contextLabel(tokens: number) {+ if (tokens < 1024) return `${tokens} tokens`;return `${Math.round(tokens / 1024)}K tokens`;}@@ -491,10 +493,10 @@ export function collapsedRowBadges(model: LocalModel): CollapsedRowBadges {function formatRemainingTime(seconds: number) {if (seconds < 60) return `${seconds}s left`;- if (seconds < 3600) return `${Math.ceil(seconds / 60)}m left`;- const hours = Math.floor(seconds / 3600);- const minutes = Math.ceil((seconds % 3600) / 60);- if (minutes >= 60) return `${hours + 1}h left`;+ const totalMinutes = Math.ceil(seconds / 60);+ if (totalMinutes < 60) return `${totalMinutes}m left`;+ const hours = Math.floor(totalMinutes / 60);+ const minutes = totalMinutes % 60;return minutes > 0 ? `${hours}h ${minutes}m left` : `${hours}h left`;}diff --git a/apps/web/src/features/local-models/model-source-panel.tsx b/apps/web/src/features/local-models/model-source-panel.tsxindex c3263ebe..fff18fa3 100644--- a/apps/web/src/features/local-models/model-source-panel.tsx+++ b/apps/web/src/features/local-models/model-source-panel.tsx@@ -15,6 +15,10 @@ import { ModalDialog } from "@/components/ui/modal-dialog";import { Select, SelectItem } from "@/components/ui/select";import { Hint } from "@/features/local-computer/computer-hint";import { localComputersQueryKey } from "@/features/local-computer/local-computer-queries";+import {+ tenantAgentAvailabilityQueryKey,+ tenantAgentsQueryKey,+} from "@/features/rooms/room-queries";import { TeamHubError } from "@/features/teamhub/teamhub-error";import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";import { cn } from "@/lib/cn";@@ -64,9 +68,11 @@ export function activeSourceLabel(status: ModelSourceStatus) {}interface ModelSourceSwitcher {+ clearFeedback: () => void;failure: string | undefined;pending: ModelSourceSwitchRequest | undefined;request: (body: ModelSourceSwitchRequest) => void;+ saveRevision: number;}/**@@ -91,6 +97,7 @@ export function useModelSourceSwitch({body: ModelSourceSwitchRequest;} | null>(null);const [notice, setNotice] = useState<string | null>(null);+ const [saveRevision, setSaveRevision] = useState(0);const mutation = useMutation({mutationFn: (body: ModelSourceSwitchRequest) =>switchModelSource(client, tenantId, computerId, body),@@ -113,23 +120,37 @@ export function useModelSourceSwitch({onSuccess: (view) => {queryClient.setQueryData(modelSourceQueryKey(tenantId, computerId), view);setNotice(switchedNotice(view));- void queryClient.invalidateQueries({- queryKey: tenantLocalModelsQueryKey(tenantId),- });- void queryClient.invalidateQueries({- queryKey: localComputersQueryKey(tenantId),- });+ setSaveRevision((current) => current + 1);+ void Promise.all([+ queryClient.invalidateQueries({+ queryKey: tenantLocalModelsQueryKey(tenantId),+ }),+ queryClient.invalidateQueries({+ queryKey: localComputersQueryKey(tenantId),+ }),+ queryClient.invalidateQueries({+ queryKey: tenantAgentsQueryKey(tenantId),+ }),+ queryClient.invalidateQueries({+ queryKey: tenantAgentAvailabilityQueryKey(tenantId),+ }),+ ]);},});const failureCode =mutation.error instanceof TeamHubError ? mutation.error.code : undefined;const switcher: ModelSourceSwitcher = {+ clearFeedback: () => {+ setNotice(null);+ if (mutation.isError) mutation.reset();+ },failure:mutation.isError && failureCode !== "AGENT_HAS_ACTIVE_RUNS"? modelSourceErrorCopy(failureCode): undefined,pending: mutation.isPending ? mutation.variables : undefined,request: (body) => mutation.mutate(body),+ saveRevision,};const feedback = (<>@@ -215,7 +236,7 @@ export function ModelSourceTabs({return (<divaria-label="Model source"- className="mt-6 inline-flex rounded-lg bg-muted p-0.5"+ className="mt-6 inline-flex self-start rounded-lg bg-muted p-0.5"role="tablist">{modes.map((mode) => {@@ -244,7 +265,7 @@ export function ModelSourceTabs({</button>);return mode === "byok" ? (- <Hint key={mode} placement="bottom" text={byokExplanation}>+ <Hint key={mode} placement="top" text={byokExplanation}>{tab}</Hint>) : (@@ -265,10 +286,11 @@ export function SwitchToLocalNotice({models: readonly LocalModel[];switcher: ModelSourceSwitcher;}) {- const [selectedId, setSelectedId] = useState<string | undefined>(- () => models[0]?.id,- );- const chosen = models.find((model) => model.id === selectedId) ?? models[0];+ const [selectedId, setSelectedId] = useState<string | undefined>(undefined);+ const chosen =+ (selectedId+ ? models.find((model) => model.id === selectedId)+ : undefined) ?? models[0];const single = models.length === 1 ? models[0] : undefined;return (@@ -337,6 +359,18 @@ function ByokModelOption({ model }: { model: ByokModel }) {);}+function sameEndpointOrigin(savedUrl: string | undefined, nextUrl: string) {+ const trimmedSaved = savedUrl?.trim();+ const trimmedNext = nextUrl.trim();+ if (!trimmedSaved || !trimmedNext) return false;+ if (trimmedSaved === trimmedNext) return true;+ try {+ return new URL(trimmedSaved).origin === new URL(trimmedNext).origin;+ } catch {+ return false;+ }+}+/*** The person's own endpoint. The API key goes to the Computer, which keeps* it private; Linger never shows it again.@@ -363,6 +397,7 @@ export function ByokPanel({const [apiKey, setApiKey] = useState("");// Starts empty until a model is saved, then shows the saved one.const [modelId, setModelId] = useState(saved.model_id ?? "");+ const [manualModelEntry, setManualModelEntry] = useState(false);// Models are listed for the address and key as they stand when a field is// left, not on every keystroke.const [listed, setListed] = useState({@@ -370,13 +405,26 @@ export function ByokPanel({keyRevision: 0,});const [keyEdited, setKeyEdited] = useState(false);+ const trimmedBaseUrl = baseUrl.trim();+ // Never reuse a saved key when the owner points BYOK at a different host.+ const canReuseSavedKey =+ saved.key_saved &&+ (!saved.base_url || sameEndpointOrigin(saved.base_url, trimmedBaseUrl));const credentials = apiKey? { api_key: apiKey }- : saved.key_saved+ : canReuseSavedKey+ ? { reuse_saved_key: true }+ : {};+ const listedCanReuseSavedKey =+ saved.key_saved &&+ (!saved.base_url || sameEndpointOrigin(saved.base_url, listed.baseUrl));+ const listedCredentials = apiKey+ ? { api_key: apiKey }+ : listedCanReuseSavedKey? { reuse_saved_key: true }: {};const input: ByokInput = {- base_url: baseUrl.trim(),+ base_url: trimmedBaseUrl,model_id: modelId.trim(),...credentials,};@@ -385,13 +433,14 @@ export function ByokPanel({client,tenantId,computerId,- { base_url: listed.baseUrl, ...credentials },+ { base_url: listed.baseUrl, ...listedCredentials },listed.keyRevision,),- // A refresh keeps the current choices on screen until the new list lands.- placeholderData: keepPreviousData,+ // A refresh keeps the current choices on screen until the new list lands,+ // but clearing the address clears stale options.+ placeholderData: listed.baseUrl ? keepPreviousData : undefined,});- const listedModels = models.data?.models ?? [];+ const listedModels = listed.baseUrl ? (models.data?.models ?? []) : [];// A saved or typed ID the endpoint does not list stays choosable.const modelOptions =input.model_id === "" ||@@ -407,6 +456,7 @@ export function ByokPanel({: listedModels.length? `${listedModels.length} ${listedModels.length === 1 ? "model" : "models"} listed.`: undefined;+ const showModelSelect = listedModels.length > 0 && !manualModelEntry;// The Computer decides whether the endpoint needs a key: one on this// computer or the local network may have none.const complete = input.base_url !== "" && input.model_id !== "";@@ -474,7 +524,10 @@ export function ByokPanel({: { ...current, baseUrl: input.base_url },)}- onChange={(event) => setBaseUrl(event.target.value)}+ onChange={(event) => {+ setBaseUrl(event.target.value);+ test.reset();+ }}placeholder="https://api.example.com/v1"spellCheck={false}value={baseUrl}@@ -483,7 +536,7 @@ export function ByokPanel({autoComplete="new-password"disabled={disabled}hint={- saved.key_saved+ canReuseSavedKey? "A key is saved on this computer. Leave blank to keep it.": "Optional for an endpoint on this computer or your local network."}@@ -499,6 +552,7 @@ export function ByokPanel({onChange={(event) => {setApiKey(event.target.value);setKeyEdited(true);+ test.reset();}}type="password"value={apiKey}@@ -510,9 +564,9 @@ export function ByokPanel({>Model</label>- <div className="flex gap-2">- <div className="min-w-0 flex-1">- {listedModels.length ? (+ <div className="flex flex-wrap gap-2">+ <div className="min-w-48 flex-1">+ {showModelSelect ? (<Selectaria-describedby={modelHint ? modelHintId : undefined}aria-label="Model"@@ -539,7 +593,10 @@ export function ByokPanel({className={fieldControlClassName}disabled={disabled}id={modelControlId}- onChange={(event) => setModelId(event.target.value)}+ onChange={(event) => {+ setModelId(event.target.value);+ test.reset();+ }}placeholder="provider/model-name"spellCheck={false}value={modelId}@@ -550,19 +607,29 @@ export function ByokPanel({disabled={disabled || input.base_url === ""}loading={models.isFetching}onClick={listModels}+ onMouseDown={(event) => event.preventDefault()}size="large">{models.isFetching ? null : <Icon icon={RefreshIcon} size={16} />}List models</Button></div>- {modelHint ? (- <p- className="mt-1.5 text-xs text-muted-foreground"- id={modelHintId}- >- {modelHint}- </p>+ {modelHint || listedModels.length > 0 ? (+ <div className="mt-1.5 flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">+ <p id={modelHintId}>{modelHint}</p>+ {listedModels.length > 0 ? (+ <button+ className="text-foreground underline underline-offset-2 disabled:opacity-50"+ disabled={disabled}+ onClick={() => setManualModelEntry((current) => !current)}+ type="button"+ >+ {manualModelEntry+ ? "Choose from list"+ : "Enter model ID manually"}+ </button>+ ) : null}+ </div>) : null}</div>{test.isSuccess ? (diff --git a/apps/web/src/features/rooms/chat/direct-agent-model-switch.tsx b/apps/web/src/features/rooms/chat/direct-agent-model-switch.tsxindex adf6c658..4b46b73d 100644--- a/apps/web/src/features/rooms/chat/direct-agent-model-switch.tsx+++ b/apps/web/src/features/rooms/chat/direct-agent-model-switch.tsx@@ -1,5 +1,6 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { lazy, Suspense, useState } from "react";+import { tenantLocalModelsQueryKey } from "@/features/local-models/local-models-queries";import { teamHubData } from "@/features/teamhub/teamhub-api";import { type TeamHubClient } from "@/features/teamhub/teamhub-client";import type {@@ -76,9 +77,14 @@ function RuntimeSettingsEntry({ client, registration, tenantId, busy }: Props) {}: current,);- void queryClient.invalidateQueries({- queryKey: tenantAgentsQueryKey(tenantId),- });+ void Promise.all([+ queryClient.invalidateQueries({+ queryKey: tenantAgentsQueryKey(tenantId),+ }),+ queryClient.invalidateQueries({+ queryKey: tenantLocalModelsQueryKey(tenantId),+ }),+ ]);setOpen(false);},});diff --git a/apps/web/src/features/rooms/event-sync.test.tsx b/apps/web/src/features/rooms/event-sync.test.tsxindex eca0d269..23f52458 100644--- a/apps/web/src/features/rooms/event-sync.test.tsx+++ b/apps/web/src/features/rooms/event-sync.test.tsx@@ -167,7 +167,7 @@ describe("TeamHub event signals", () => {mac.stop();});- it("refreshes the directory, the Room members and the Room list it shows", async () => {+ it("refreshes the directory, the Room members, the Room list, and local models it shows", async () => {const queryClient = new QueryClient();const members = observe(queryClient,@@ -178,8 +178,10 @@ describe("TeamHub event signals", () => {queryClient,tenantAgentAvailabilityQueryKey("tenant-a"),);+ const models = observe(queryClient, localModelsQueryKey("tenant-a", "lab"));await vi.waitFor(() => expect(members.fetch).toHaveBeenCalledOnce());await vi.waitFor(() => expect(rooms.fetch).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(models.fetch).toHaveBeenCalledOnce());await applyTeamHubEventSignal(queryClient, {hint: { id: "tenant-a", resource: "directory", tenant_id: "tenant-a" },@@ -189,9 +191,11 @@ describe("TeamHub event signals", () => {await vi.waitFor(() => expect(members.fetch).toHaveBeenCalledTimes(2));await vi.waitFor(() => expect(availability.fetch).toHaveBeenCalledTimes(2));await vi.waitFor(() => expect(rooms.fetch).toHaveBeenCalledTimes(2));+ await vi.waitFor(() => expect(models.fetch).toHaveBeenCalledTimes(2));members.stop();availability.stop();rooms.stop();+ models.stop();});it("drops retained preview bytes only when Document access may change", async () => {diff --git a/apps/web/src/features/rooms/event-sync.tsx b/apps/web/src/features/rooms/event-sync.tsxindex 30850ee1..8e945deb 100644--- a/apps/web/src/features/rooms/event-sync.tsx+++ b/apps/web/src/features/rooms/event-sync.tsx@@ -146,6 +146,8 @@ async function applyInvalidation(// Room rows carry their Direct peer's name, so a renamed Actor// renames its Chat row too.tenantRoomsQueryKey(tenantId),+ // Local models views list which Agents use each model.+ tenantLocalModelsQueryKey(tenantId),...findQueryKeys(queryClient,(queryKey) =>diff --git a/apps/web/src/features/rooms/members/actor-profile.tsx b/apps/web/src/features/rooms/members/actor-profile.tsxindex 55da0427..e4c526a2 100644--- a/apps/web/src/features/rooms/members/actor-profile.tsx+++ b/apps/web/src/features/rooms/members/actor-profile.tsx@@ -64,6 +64,7 @@ import type {AgentRuntimeField,AgentRuntimeUpdateInput,} from "./edit-agent-runtime-dialog";+import { tenantLocalModelsQueryKey } from "@/features/local-models/local-models-queries";import { useResolvedAgentModelLabel } from "./use-agent-model-selection";const EditAgentRuntimeDialog = lazy(async () => ({default: (await import("./edit-agent-runtime-dialog")).EditAgentRuntimeDialog,@@ -291,6 +292,9 @@ export function AgentProfileContent({queryClient.invalidateQueries({queryKey: tenantAgentsQueryKey(tenantId),}),+ queryClient.invalidateQueries({+ queryKey: tenantLocalModelsQueryKey(tenantId),+ }),queryClient.invalidateQueries({queryKey: tenantRoomsQueryKey(tenantId),}),diff --git a/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.test.tsx b/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.test.tsxindex 2dc5607d..bb49c3a9 100644--- a/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.test.tsx+++ b/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.test.tsx@@ -607,9 +607,66 @@ describe("EditAgentRuntimeDialog", () => {expect(onClose).toHaveBeenCalledTimes(1);},);++ it("resolves an unloaded local model name in the unavailable Model option", async () => {+ const computer = localComputer("computer-old", "Old Mac", "online");+ computer.runtimes = [+ ...computer.runtimes,+ { models: [], status: "ready", type: "pi" },+ ];+ const registration = localCodexAgent();+ registration.runtime = {+ model: "localmodels-library/qwen3-coder-30b",+ placement: {+ computer_id: "computer-old",+ runtime_type: "pi",+ type: "local",+ workspace_grant_id: "grant-workspace",+ },+ };+ const api = {+ GET: vi.fn().mockResolvedValue({+ data: {+ available: true,+ computer: {+ computer_id: "computer-old",+ display_name: "Old Mac",+ status: "online",+ },+ models: [+ {+ model: {+ id: "qwen3-coder-30b:Q4_K_M",+ name: "Qwen3 Coder 30B",+ pi_model: "localmodels-library/qwen3-coder-30b",+ state: "idle",+ },+ used_by: [],+ },+ ],+ pools: [],+ viewer_is_owner: true,+ },+ response: new Response(null, { status: 200 }),+ }),+ };+ renderDialog({+ api,+ computersOverride: { items: [computer] },+ onSave: vi.fn(),+ registration,+ });++ await waitFor(() =>+ expect(+ screen.getByRole("combobox", { name: "Agent model" }),+ ).toHaveTextContent("Qwen3 Coder 30B · Unavailable"),+ );+ });});function renderDialog({+ api,field = "runtime",onClose = vi.fn(),onSave,@@ -619,6 +676,7 @@ function renderDialog({defaultOptions: { queries: { retry: false } },}),}: {+ api?: { GET: ReturnType<typeof vi.fn> };queryClient?: QueryClient;field?: AgentRuntimeField;onClose?: () => void;@@ -633,6 +691,7 @@ function renderDialog({],};const client = {+ ...(api ? { api: api as never } : {}),listTenantLocalComputers: vi.fn().mockResolvedValue(computers),};diff --git a/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.tsx b/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.tsxindex ec57ef2a..7c78304c 100644--- a/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.tsx+++ b/apps/web/src/features/rooms/members/edit-agent-runtime-dialog.tsx@@ -9,6 +9,7 @@ import { runtimeStatusLabels } from "@/features/local-computer/computer-readinesimport { localComputersQueryKey } from "@/features/local-computer/local-computer-queries";import { LocalRuntimeAuthenticationGuidance } from "@/features/local-computer/local-runtime-authentication-guidance";import { LocalRuntimeInstallGuidance } from "@/features/local-computer/local-runtime-install-guidance";+import { localModelsQueryOptions } from "@/features/local-models/local-models-queries";import type { TeamHubClient } from "@/features/teamhub/teamhub-client";import type {TeamHubAgentReasoningEffort,@@ -53,7 +54,8 @@ export function EditAgentRuntimeDialog({tenantId,}: {busy?: boolean;- client: Pick<TeamHubClient, "listTenantLocalComputers">;+ client: Pick<TeamHubClient, "listTenantLocalComputers"> &+ Partial<Pick<TeamHubClient, "api">>;field?: AgentRuntimeField;error?: string;isPending: boolean;@@ -73,6 +75,26 @@ export function EditAgentRuntimeDialog({const { computer, grant, localReady, model, moving, runtime, target } =selection;const modelIsAvailable = Boolean(selection.selectedModel);+ const localModels = useQuery({+ ...localModelsQueryOptions(+ client as TeamHubClient,+ tenantId,+ selection.computerId,+ ),+ enabled: Boolean(+ client.api &&+ selection.runtimeType === "pi" &&+ selection.computerId &&+ model &&+ !modelIsAvailable &&+ model.startsWith("localmodels-library/"),+ ),+ });+ const unavailableModelLabel =+ (localModels.data?.available+ ? localModels.data.models.find((item) => item.model.pi_model === model)+ ?.model.name+ : undefined) ?? model;const loading = computers.isPending;const placementLocked = field === "model" || field === "reasoning";const noWritableGrant = moving && Boolean(computer) && !grant;@@ -169,7 +191,7 @@ export function EditAgentRuntimeDialog({>{model && !modelIsAvailable ? (<SelectItem value={model} disabled>- {model} · Unavailable+ {unavailableModelLabel} · Unavailable</SelectItem>) : null}{selection.modelOptions.map((item) => (diff --git a/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsx b/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsxindex 153e6ef6..fe30d1cd 100644--- a/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsx+++ b/apps/web/src/features/rooms/quick-create-general-agent-page.test.tsx@@ -859,6 +859,45 @@ describe("quick Local Agent creation", () => {expect(screen.getByRole("combobox", { name: "Runtime" })).toHaveTextContent("Pi",);+ const manageLink = screen.getByRole("link", { name: "Settings › Models" });+ expect(manageLink).toHaveAttribute(+ "href",+ `/t/tenant-northstar/settings/models?computer=${encodeURIComponent(computer.computer_id)}`,+ );+ });++ it("links to Settings › Models when Pi has no loaded local models", async () => {+ const runtime = await testRuntime();+ const inventory =+ await runtime.client.listTenantLocalComputers("tenant-northstar");+ const computer = inventory.items[0]!;+ vi.spyOn(runtime.client, "listTenantLocalComputers").mockResolvedValue({+ items: [+ {+ ...computer,+ runtimes: [+ ...computer.runtimes,+ { models: [], status: "ready", type: "pi" },+ ],+ },+ ],+ });+ renderCreation(runtime, "local");+ fireEvent.click(+ await screen.findByRole("combobox", { name: "Local Computer" }),+ );+ fireEvent.click(await screen.findByRole("option", { name: "Jenny's Mac" }));+ fireEvent.click(screen.getByRole("combobox", { name: "Runtime" }));+ fireEvent.click(await screen.findByRole("option", { name: "Pi" }));++ const link = await screen.findByRole("link", { name: "Settings › Models" });+ expect(link).toHaveAttribute(+ "href",+ `/t/tenant-northstar/settings/models?computer=${encodeURIComponent(computer.computer_id)}`,+ );+ expect(link.closest("p")).toHaveTextContent(+ "Download and load a local model in Settings › Models to run Agents with Pi on this computer.",+ );});describe("in the desktop app", () => {diff --git a/apps/web/src/features/rooms/quick-create-local-agent-dialog.tsx b/apps/web/src/features/rooms/quick-create-local-agent-dialog.tsxindex af61d684..6de092ee 100644--- a/apps/web/src/features/rooms/quick-create-local-agent-dialog.tsx+++ b/apps/web/src/features/rooms/quick-create-local-agent-dialog.tsx@@ -1,6 +1,7 @@import { Add01Icon, ArrowLeft01Icon } from "@hugeicons/core-free-icons";import { useQuery } from "@tanstack/react-query";import { useEffect, useState } from "react";+import { Link } from "react-router";import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icon";@@ -361,28 +362,43 @@ export function QuickCreateLocalAgentDialog({))}</Select></label>- <label className="block">- <span className="mb-1.5 block text-sm font-medium">- Model- </span>- <Select- aria-label="Model"- className="min-w-0 w-full"- disabled={!modelOptions.length}- placeholder="No models available"- value={selectedModel?.id ?? ""}- onValueChange={(value) => {- setModelId(value);- setEffort(undefined);- }}- >- {modelOptions.map((model) => (- <SelectItem key={model.id} value={model.id}>- {model.label}- </SelectItem>- ))}- </Select>- </label>+ <div className="space-y-1.5">+ <label className="block">+ <span className="mb-1.5 block text-sm font-medium">+ Model+ </span>+ <Select+ aria-label="Model"+ className="min-w-0 w-full"+ disabled={!modelOptions.length}+ placeholder="No models available"+ value={selectedModel?.id ?? ""}+ onValueChange={(value) => {+ setModelId(value);+ setEffort(undefined);+ }}+ >+ {modelOptions.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ {model.label}+ </SelectItem>+ ))}+ </Select>+ </label>+ {selectedRuntime?.type === "pi" && modelOptions.length > 0 ? (+ <p className="text-xs text-muted-foreground">+ Manage downloaded models in{" "}+ <Link+ className="font-medium text-foreground underline underline-offset-2"+ onClick={onClose}+ to={`/t/${encodeURIComponent(tenantId)}/settings/models?computer=${encodeURIComponent(selectedComputer.computer_id)}`}+ >+ Settings › Models+ </Link>+ .+ </p>+ ) : null}+ </div><label className="block"><span className="mb-1.5 block text-sm font-medium">Thinking effort@@ -405,8 +421,20 @@ export function QuickCreateLocalAgentDialog({</Select></label>{!selectedModel && !loginRuntime ? (- selectedComputer &&- selectedRuntime?.status === "not_installed" ? (+ selectedRuntime?.type === "pi" ? (+ <p className="text-xs text-muted-foreground" role="status">+ Download and load a local model in{" "}+ <Link+ className="font-medium text-foreground underline underline-offset-2"+ onClick={onClose}+ to={`/t/${encodeURIComponent(tenantId)}/settings/models?computer=${encodeURIComponent(selectedComputer.computer_id)}`}+ >+ Settings › Models+ </Link>{" "}+ to run Agents with Pi on this computer.+ </p>+ ) : selectedComputer &&+ selectedRuntime?.status === "not_installed" ? (<div role="status"><LocalRuntimeInstallGuidancecomputerName={selectedComputer.display_name}