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(local-models): add memory cleanup guidance, live recheck, and model activation
Dongdong Chenf1376d289290
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.mdindex 1b4bc750..1ff0d2f4 100644--- a/apps/teamhub/AGENTS.md+++ b/apps/teamhub/AGENTS.md@@ -222,11 +222,16 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.`runtime_model` equals the model's `pi_model` exactly (loaded or not), limited to theAgents the reader sees in the Agent directory. Only the owner acts(`LOCAL_MODEL_ACTION_FORBIDDEN`), and only while the Computer is online by- the Computers page's 60-second rule (`LOCAL_COMPUTER_OFFLINE`). A connected- Computer that has not decided within the action's 10 seconds answers 504+ the Computers page's 60-second rule (`LOCAL_COMPUTER_OFFLINE`). `POST .../local-models`+ (`refreshLocalComputerModels`) forwards an empty-model `refresh` command through+ the same owner/online gate, while `POST .../local-models/{modelId}/actions` acts on+ one model (`refresh` stays invalid there). A connected Computer that has not+ decided within the action's 10 seconds answers 504`LOCAL_MODEL_ACTION_UNCONFIRMED`: it may still act, and the snapshots showthe outcome. The Computer's refusal codes map to `LocalModelsErrorCode` in- `internal/app/handlers_local_models.go`.+ `internal/app/handlers_local_models.go` (and `LOAD_NO_ROOM` / `MEMORY_INSUFFICIENT`+ on model-source switches map to `LOCAL_MODEL_NO_ROOM` in+ `internal/app/handlers_model_source.go`).- A Computer's model source lives on the Computer(`internal/app/handlers_model_source.go`); TeamHub never stores a BYOK key.A switch checks for running work, runs `apply` on the Computer, then movesdiff --git a/apps/teamhub/internal/app/handlers_local_models.go b/apps/teamhub/internal/app/handlers_local_models.goindex 301ce472..7ed76098 100644--- a/apps/teamhub/internal/app/handlers_local_models.go+++ b/apps/teamhub/internal/app/handlers_local_models.go@@ -168,6 +168,28 @@ func (a *App) actOnLocalComputerModel(c *gin.Context) {a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Local model action is invalid")return}+ var unloadFirst []string+ if request.UnloadFirst != nil {+ unloadFirst = *request.UnloadFirst+ }+ a.forwardLocalModelAction(c, string(request.Action), modelID, unloadFirst, func(computerID string) {+ c.JSON(http.StatusAccepted, httpapi.LocalModelActionAccepted{+ ComputerId: computerID, ModelId: modelID, Action: httpapi.LocalModelActionAcceptedAction(request.Action),+ })+ })+}++// refreshLocalComputerModels asks an owned connected Computer to recheck+// free memory and models and report a fresh library snapshot.+func (a *App) refreshLocalComputerModels(c *gin.Context) {+ a.forwardLocalModelAction(c, "refresh", "", nil, func(computerID string) {+ c.JSON(http.StatusAccepted, httpapi.LocalModelsRefreshAccepted{+ ComputerId: computerID, Action: httpapi.LocalModelsRefreshAcceptedRefresh,+ })+ })+}++func (a *App) forwardLocalModelAction(c *gin.Context, action string, modelID string, unloadFirst []string, onAccepted func(computerID string)) {tenantID, computerID := c.Param("tenantId"), c.Param("computerId")viewerID, ok := a.spaceHuman(c, tenantID)if !ok {@@ -197,18 +219,13 @@ func (a *App) actOnLocalComputerModel(c *gin.Context) {}command := roomagent.LocalModelActionCommand{TenantID: tenantID, OwnerActorID: viewerID, ComputerID: computerID,- RequestID: ids.New("local_model_action"), Action: string(request.Action), ModelID: modelID,- ExpiresAt: time.Now().UTC().Add(localModelActionLifetime),- }- if request.UnloadFirst != nil {- command.UnloadFirst = *request.UnloadFirst+ RequestID: ids.New("local_model_action"), Action: action, ModelID: modelID,+ UnloadFirst: unloadFirst, ExpiresAt: time.Now().UTC().Add(localModelActionLifetime),}refusal, err := a.localComputers.ActOnLocalModels(c.Request.Context(), command)switch {case err == nil && refusal == nil:- c.JSON(http.StatusAccepted, httpapi.LocalModelActionAccepted{- ComputerId: computerID, ModelId: modelID, Action: httpapi.LocalModelActionAcceptedAction(request.Action),- })+ onAccepted(computerID)case err == nil:code, known := localModelRefusalCodes[refusal.Code]if !known {diff --git a/apps/teamhub/internal/app/handlers_model_source.go b/apps/teamhub/internal/app/handlers_model_source.goindex 0b0b3b94..1904b1ca 100644--- a/apps/teamhub/internal/app/handlers_model_source.go+++ b/apps/teamhub/internal/app/handlers_model_source.go@@ -28,6 +28,8 @@ var modelSourceRefusalCodes = map[string]httpapi.ModelSourceErrorCode{"MODEL_SOURCE_UNAVAILABLE": httpapi.ModelSourceErrorCodeModelSourceUnavailable,"MODEL_SOURCE_UNSUPPORTED": httpapi.ModelSourceErrorCodeModelSourceUnavailable,"RUNTIME_NOT_ENABLED": httpapi.ModelSourceErrorCodeRuntimeNotEnabled,+ "LOAD_NO_ROOM": httpapi.ModelSourceErrorCodeLocalModelNoRoom,+ "MEMORY_INSUFFICIENT": httpapi.ModelSourceErrorCodeLocalModelNoRoom,"MODEL_UNKNOWN": httpapi.ModelSourceErrorCodeLocalModelUnknown,"BYOK_INVALID_CONFIG": httpapi.ModelSourceErrorCodeByokInvalidConfig,"BYOK_AUTH_FAILED": httpapi.ModelSourceErrorCodeByokAuthFailed,@@ -44,6 +46,7 @@ var modelSourceErrorMessages = map[httpapi.ModelSourceErrorCode]string{httpapi.ModelSourceErrorCodeModelSourceUnavailable: "This Computer cannot switch model sources",httpapi.ModelSourceErrorCodeAgentHasActiveRuns: "Agents on this Computer are working on tasks",httpapi.ModelSourceErrorCodeRuntimeNotEnabled: "The selected AI runtime is not enabled on this Computer",+ httpapi.ModelSourceErrorCodeLocalModelNoRoom: "There is not enough free memory on the Computer to load this model",httpapi.ModelSourceErrorCodeLocalModelUnknown: "The Computer does not know this model",httpapi.ModelSourceErrorCodeByokInvalidConfig: "The Computer rejected this endpoint configuration",httpapi.ModelSourceErrorCodeByokAuthFailed: "The endpoint rejected the API key",diff --git a/apps/teamhub/internal/app/handlers_model_source_test.go b/apps/teamhub/internal/app/handlers_model_source_test.goindex 6a3df4e2..068b928e 100644--- a/apps/teamhub/internal/app/handlers_model_source_test.go+++ b/apps/teamhub/internal/app/handlers_model_source_test.go@@ -37,3 +37,15 @@ func TestValidModelSourceSwitchMatchesRuntimeAndInputsToMode(t *testing.T) {}}}++func TestModelSourceRefusalCodesMapRoomErrors(t *testing.T) {+ for _, computerCode := range []string{"LOAD_NO_ROOM", "MEMORY_INSUFFICIENT"} {+ got, ok := modelSourceRefusalCodes[computerCode]+ if !ok || got != httpapi.ModelSourceErrorCodeLocalModelNoRoom {+ t.Fatalf("%s mapped to %q (ok=%v), want %q", computerCode, got, ok, httpapi.ModelSourceErrorCodeLocalModelNoRoom)+ }+ }+ if modelSourceErrorMessages[httpapi.ModelSourceErrorCodeLocalModelNoRoom] == "" {+ t.Fatal("LOCAL_MODEL_NO_ROOM has no message")+ }+}diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.goindex bb6e4c61..5635c625 100644--- a/apps/teamhub/internal/app/routes_public.go+++ b/apps/teamhub/internal/app/routes_public.go@@ -175,6 +175,7 @@ func (a *App) publicRoutes() []contractRoute {route(http.MethodGet, "/v0/tenants/:tenantId/local-computers/:computerId/browser-connection", nil, session, a.getLocalComputerBrowserConnection),route(http.MethodPut, "/v0/tenants/:tenantId/local-computers/:computerId/browser-connection", nil, session, a.putLocalComputerBrowserConnection),route(http.MethodGet, "/v0/tenants/:tenantId/local-computers/:computerId/local-models", nil, session, a.getLocalComputerModels),+ route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/local-models", nil, session, a.refreshLocalComputerModels),route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/local-models/:modelId/actions", nil, session, a.actOnLocalComputerModel),route(http.MethodGet, "/v0/tenants/:tenantId/local-computers/:computerId/model-source", nil, session, a.getLocalComputerModelSource),route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/model-source", nil, session, a.switchLocalComputerModelSource),diff --git a/apps/teamhub/tests/integration/local_models_test.go b/apps/teamhub/tests/integration/local_models_test.goindex 17902e8b..da5e21f2 100644--- a/apps/teamhub/tests/integration/local_models_test.go+++ b/apps/teamhub/tests/integration/local_models_test.go@@ -196,13 +196,27 @@ INSERT INTO agent_registrations(actor_id,tenant_id,agent_management_id,status,int.Fatalf("unconfirmed action status=%d body=%s", status, body)}computers.err = nil+ if status, _, body := env.request(bob, http.MethodPost, base, nil, ""); status != http.StatusForbidden || !containsJSONText(body, "LOCAL_MODEL_ACTION_FORBIDDEN") {+ t.Fatalf("member refresh status=%d body=%s", status, body)+ }+ if status, _, body := env.request(alice, http.MethodPost, base, nil, ""); status != http.StatusAccepted ||+ !containsJSONText(body, `"action":"refresh"`) {+ t.Fatalf("owner refresh status=%d body=%s", status, body)+ }+ if len(computers.commands) != 5 || computers.commands[4].Action != "refresh" || computers.commands[4].ModelID != "" ||+ computers.commands[4].OwnerActorID != "actor_acme_alice" || computers.commands[4].RequestID == "" {+ t.Fatalf("forwarded refresh commands=%+v", computers.commands)+ }if _, err := pool.Exec(t.Context(), `UPDATE local_computers SET last_seen_at=now()-interval '2 minutes' WHERE computer_id=$1`, computerID); err != nil {t.Fatal(err)}if status, body := act(alice, map[string]any{"action": "unload"}); status != http.StatusServiceUnavailable || !containsJSONText(body, "LOCAL_COMPUTER_OFFLINE") {t.Fatalf("offline action status=%d body=%s", status, body)}- if len(computers.commands) != 4 {+ if status, _, body := env.request(alice, http.MethodPost, base, nil, ""); status != http.StatusServiceUnavailable || !containsJSONText(body, "LOCAL_COMPUTER_OFFLINE") {+ t.Fatalf("offline refresh status=%d body=%s", status, body)+ }+ if len(computers.commands) != 5 {t.Fatalf("an offline Computer was sent an action: %d commands", len(computers.commands))}diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex c59ca0d6..2a43eafc 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -31,7 +31,12 @@ build:assets` to check the initial JS budget.owner confirms. The Local model tab is one Computer's model library asTeamHub last stored it. The Computer decidesfit, availability, placement, the recommendation and memory; the page only- orders and labels them, picks the Make room default, renders tinted family+ 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 familyicon tiles, Agent usage counts, structured capability/parameter badges (nevermatched against `name` or `description`), state-distinct cards (`loaded`,`recommended`, `failed`, `unavailable`), download speed/ETA, and topdiff --git a/apps/web/src/features/local-models/local-model-details.tsx b/apps/web/src/features/local-models/local-model-details.tsxindex 94ec5160..4a9f5aeb 100644--- a/apps/web/src/features/local-models/local-model-details.tsx+++ b/apps/web/src/features/local-models/local-model-details.tsx@@ -6,6 +6,7 @@ import {} from "@hugeicons/core-free-icons";import { Button } from "@/components/ui/button";+import { FormFeedback } from "@/components/ui/form-feedback";import { Icon } from "@/components/ui/icon";import { ModalDialog } from "@/components/ui/modal-dialog";import { cn } from "@/lib/cn";@@ -30,6 +31,7 @@ import {poolFreeBytes,poolLabel,poolOf,+ poolOtherBytes,safeModelSourceUrl,speedLabel,type ModelEntry,@@ -108,6 +110,26 @@ export function ModelFacts({const parameters = parametersLabel(model);const speed = speedLabel(model);const sourceUrl = safeModelSourceUrl(model.source_url);+ const externalBytes = view.pools.reduce(+ (sum, item) => sum + poolOtherBytes(item),+ 0,+ );+ const maxHardware = Math.max(+ view.computer.host?.ram_total_bytes ?? 0,+ ...(view.computer.host?.gpus.map((gpu) => gpu.total_bytes) ?? [0]),+ ...view.pools.map((item) => item.total_bytes),+ 0,+ );+ const reclaimable =+ externalBytes > 0 &&+ model.availability.reason?.code === "MEMORY_INSUFFICIENT" &&+ model.availability.reason.need_bytes !== undefined &&+ model.availability.reason.need_bytes <= maxHardware;+ const availableNeedsRoom =+ status === "available" &&+ pool !== undefined &&+ poolOtherBytes(pool) > 0 &&+ poolFreeBytes(pool) < model.memory_bytes;return (<div>{model.error || status === "unavailable" ? (@@ -125,7 +147,7 @@ export function ModelFacts({{status === "unavailable" ? (<Fact bordered={Boolean(model.error)} label="Why not"><span className="text-app-danger">- {unavailableCopy(model.availability.reason)}+ {unavailableCopy(model.availability.reason, reclaimable)}</span></Fact>) : null}@@ -140,6 +162,16 @@ export function ModelFacts({</Fact></div>) : null}+ {availableNeedsRoom ? (+ <div className="my-1.5">+ <FormFeedback tone="warning">+ This model can download now, but only{" "}+ {formatGigabytes(poolFreeBytes(pool))} is free on{" "}+ {poolLabel(view, pool)}. Close memory-heavy apps and recheck memory+ before loading it.+ </FormFeedback>+ </div>+ ) : null}<div className="mt-1 grid grid-cols-1 gap-x-6 @xl:grid-cols-2">{capabilities.length ? (<Fact className="@xl:col-span-2" label="Capabilities">@@ -224,11 +256,7 @@ function PoolBar({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 otherBytes = poolOtherBytes(pool);const width = (bytes: number) =>`${pool.total_bytes ? Math.min(100, (bytes / pool.total_bytes) * 100) : 0}%`;return (diff --git a/apps/web/src/features/local-models/local-model-dialogs.tsx b/apps/web/src/features/local-models/local-model-dialogs.tsxindex e81bae3f..1f61f160 100644--- a/apps/web/src/features/local-models/local-model-dialogs.tsx+++ b/apps/web/src/features/local-models/local-model-dialogs.tsx@@ -14,6 +14,7 @@ import {makesRoom,poolLabel,poolOf,+ poolOtherBytes,type LoadCheck,type ModelEntry,} from "./local-models-rules";@@ -37,13 +38,15 @@ function AffectedAgents({);}-/** Loading would overfill the pool: offer to unload loaded models first. */+/** Loading would overfill the pool: offer to unload loaded models or recheck memory. */export function MakeRoomDialog({check,disabled,entry,onClose,onConfirm,+ onRecheck,+ rechecking = false,view,}: {check: LoadCheck;@@ -52,11 +55,18 @@ export function MakeRoomDialog({entry: ModelEntry;onClose: () => void;onConfirm: (unloadIds: string[]) => void;+ onRecheck?: () => void;+ rechecking?: boolean;view: LocalModelsView;}) {const [selected, setSelected] = useState(() => makeRoomSelection(check));const chosen = new Set(selected);- const enough = makesRoom(check, chosen);+ const roomFreeNow = check.freeBytes >= check.needBytes;+ const enough = roomFreeNow || makesRoom(check, chosen);+ const otherBytes = poolOtherBytes(check.pool);+ const unifiedFitsHardware =+ check.pool.kind === "unified" &&+ (view.computer.host?.ram_total_bytes ?? 0) >= check.needBytes;const affected = check.loaded.flatMap((item) =>chosen.has(item.model.id) ? item.used_by.map((user) => user.name) : [],);@@ -66,6 +76,15 @@ export function MakeRoomDialog({description={`${entry.model.name} needs ${formatGigabytes(check.needBytes)} on ${poolLabel(view, check.pool)}; ${formatGigabytes(check.freeBytes)} is free.`}footer={<>+ {onRecheck ? (+ <Button+ disabled={disabled}+ loading={rechecking}+ onClick={onRecheck}+ >+ Recheck memory+ </Button>+ ) : null}<Button onClick={onClose}>Cancel</Button><Buttondisabled={disabled || !enough}@@ -81,7 +100,12 @@ export function MakeRoomDialog({title="Make room to load"><div className="grid gap-3 px-5 py-4">- {check.loaded.length ? (+ {roomFreeNow ? (+ <FormFeedback tone="success">+ Enough memory is free now ({formatGigabytes(check.freeBytes)}{" "}+ available). Click Load to start.+ </FormFeedback>+ ) : check.loaded.length ? (<fieldset className="grid gap-0.5"><legend className="mb-1.5 text-sm text-muted-foreground">Unload these to free memory:@@ -124,10 +148,19 @@ export function MakeRoomDialog({</fieldset>) : (<FormFeedback tone="danger">- Nothing else is loaded there. This model doesn't fit even when- the memory is empty.+ Nothing else is loaded there.+ {otherBytes > 0 || unifiedFitsHardware+ ? `${otherBytes > 0 ? ` Other apps are using ${formatGigabytes(otherBytes)}.` : ""} Close video players, games, or other memory-heavy apps, then click Recheck memory so loading won't overload your computer.`+ : " This model doesn't fit even when the memory is empty."}</FormFeedback>)}+ {check.loaded.length > 0 && !enough && otherBytes > 0 ? (+ <FormFeedback tone="warning">+ Other apps are using {formatGigabytes(otherBytes)} on{" "}+ {poolLabel(view, check.pool)}. Close unnecessary apps and click+ Recheck memory to free the remaining room.+ </FormFeedback>+ ) : null}{affected.length ? (<FormFeedback tone="warning">{affected.join(", ")} can't answer until their model is loadeddiff --git a/apps/web/src/features/local-models/local-model-row.tsx b/apps/web/src/features/local-models/local-model-row.tsxindex c4467cb5..f3b7405e 100644--- a/apps/web/src/features/local-models/local-model-row.tsx+++ b/apps/web/src/features/local-models/local-model-row.tsx@@ -148,6 +148,7 @@ interface Handlers {onRemove: () => void;onToggle: () => void;onUnload: () => void;+ onUseForAgents?: () => void;}function stopRowClick(event: MouseEvent) {@@ -303,6 +304,7 @@ export function ModelRow({entry,expanded,requested,+ switchingForAgents = false,view,...handlers}: Handlers & {@@ -312,6 +314,7 @@ export function ModelRow({expanded: boolean;/** An action asked for and not yet in a snapshot. */requested?: LocalModelAction;+ switchingForAgents?: boolean;view: LocalModelsView;}) {const panelId = useId();@@ -439,6 +442,22 @@ export function ModelRow({hasMeta && "@2xl:col-start-3",)}>+ {status === "loaded" && handlers.onUseForAgents ? (+ <Button+ aria-label={`Use ${model.name} for Agents`}+ className="px-2.5"+ disabled={disabled}+ loading={switchingForAgents}+ onClick={(event) => {+ stopRowClick(event);+ handlers.onUseForAgents?.();+ }}+ size="compact"+ tone="primary"+ >+ Use for Agents+ </Button>+ ) : null}{action ? (<Buttonaria-label={`${action[0]} ${model.name}`}diff --git a/apps/web/src/features/local-models/local-models-copy.ts b/apps/web/src/features/local-models/local-models-copy.tsindex bfa5f18e..eb0baa98 100644--- a/apps/web/src/features/local-models/local-models-copy.ts+++ b/apps/web/src/features/local-models/local-models-copy.ts@@ -1,6 +1,6 @@import type { components } from "@linger/wire-contracts/teamhub-public/types";-import { formatGigabytes } from "./local-models-rules";+import { formatGigabytes, type MemoryGuidance } from "./local-models-rules";type Schemas = components["schemas"];@@ -28,7 +28,7 @@ const actionRefusals: Record<Schemas["LocalModelsErrorCode"], string> = {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.",+ "There isn't enough free memory to load it. Close memory-heavy apps or unload another model, then recheck memory.",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:@@ -105,7 +105,10 @@ export function unavailableShortCopy(reason: AvailabilityReason | undefined) {}/** The full reason a model can't be downloaded, shown in its details. */-export function unavailableCopy(reason: AvailabilityReason | undefined) {+export function unavailableCopy(+ reason: AvailabilityReason | undefined,+ reclaimable = false,+) {const need =reason?.need_bytes === undefined? undefined@@ -115,10 +118,15 @@ export function unavailableCopy(reason: AvailabilityReason | undefined) {? undefined: formatGigabytes(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 "MEMORY_INSUFFICIENT": {+ const base =+ need && have+ ? `Needs ${need} of memory; this computer has ${have} for models.`+ : "This computer doesn't have enough memory for it.";+ return reclaimable+ ? `${base} Close memory-heavy apps and recheck memory.`+ : base;+ }case "DISK_INSUFFICIENT":return need && have? `Needs ${need} of disk; ${have} is free.`@@ -190,6 +198,8 @@ const modelSourceRefusals: Record<Schemas["ModelSourceErrorCode"], string> = {BYOK_UPSTREAM_REJECTED: "The endpoint rejected the test request.",LOCAL_COMPUTER_OFFLINE:"The computer is offline. Reconnect it in Computers, then try again.",+ LOCAL_MODEL_NO_ROOM:+ "There isn't enough free memory on the computer to load that model. Close memory-heavy apps or unload another model, recheck memory, and try again.",LOCAL_MODEL_UNKNOWN: "The computer doesn't have this model anymore.",MODEL_SOURCE_FAILED: "The computer couldn't switch. Try again.",MODEL_SOURCE_FORBIDDEN:@@ -223,3 +233,28 @@ export const byokProtocolLabels: Record<Schemas["ByokProtocol"], string> = {"openai-chat": "OpenAI Chat Completions","openai-responses": "OpenAI Responses",};++/** Guidance telling the owner how freeing external memory unlocks larger models. */+export function memoryGuidanceCopy(guidance: MemoryGuidance) {+ const memoryKind = guidance.gpu ? "GPU memory" : "memory";+ const other = formatGigabytes(guidance.otherBytes);+ const free = formatGigabytes(guidance.freeBytes);+ const total = formatGigabytes(guidance.totalBytes);+ switch (guidance.kind) {+ case "blocked_load":+ return {+ body: `Other apps are holding ${other} of ${memoryKind} (${free} of ${total} free). Forcing a model into tight memory can freeze the computer. Close video players, games, browsers, or other memory-heavy apps, then click Recheck memory to load it.`,+ title: `Free ${memoryKind} before loading`,+ };+ case "blocked_download":+ return {+ body: `Other apps are holding ${other} of ${memoryKind} (${free} of ${total} free), so larger models look unavailable right now. Close unnecessary apps (such as video players, games, or browsers) and click Recheck memory to detect all free memory before installing.`,+ title: `Free ${memoryKind} to install a larger model`,+ };+ case "constrained_pool":+ return {+ body: `Other apps are using ${other} of ${memoryKind} (${free} of ${total} free). To avoid loading failures or system freezes, close unnecessary apps and click Recheck memory so you can load a better model.`,+ title: `Other apps are using ${memoryKind}`,+ };+ }+}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 48c00ed4..22e0c587 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@@ -45,6 +45,7 @@ type InventoryComputer = TeamHubLocalComputerPage["items"][number];interface Fixture {actions: { body: unknown; computerId: string; modelId: string }[];+ refreshes: string[];runtime: TestTeamHubRuntime;views: Record<string, LocalModelsView>;}@@ -65,6 +66,7 @@ function setup(}));const fixture: Fixture = {actions: [],+ refreshes: [],runtime,views: Object.fromEntries(views.map((view) => [view.computer.computer_id, view]),@@ -83,6 +85,13 @@ function setup(const view = fixture.views[params.computerId!];return view ?? teamHubErrorResponse(404, "LOCAL_COMPUTER_NOT_FOUND");})+ .on("POST", viewPath, ({ params }) => {+ fixture.refreshes.push(params.computerId!);+ return Response.json(+ { action: "refresh", computer_id: params.computerId },+ { status: 202 },+ );+ }).on("POST", actionPath, ({ body, params }) => {fixture.actions.push({body,@@ -929,7 +938,7 @@ describe("LocalModelsPage", () => {answer();expect(await screen.findByRole("alert")).toHaveTextContent(- "Gemma 3 27B: There isn't enough free memory to load it. Unload another model first.",+ "Gemma 3 27B: There isn't enough free memory to load it. Close memory-heavy apps or unload another model, then recheck memory.",);expect(statusOf("Gemma 3 27B")).toMatch(/^Downloaded/);expect(@@ -947,7 +956,7 @@ describe("LocalModelsPage", () => {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.",+ "Gemma 3 27B: There isn't enough free memory to load it. Close memory-heavy apps or unload another model, then recheck memory.",);expect(screen.queryByText(/raw refusal detail/)).not.toBeInTheDocument();});@@ -1663,4 +1672,314 @@ describe("Model source", () => {(switches[0] as { local_model_id?: string }).local_model_id,).toBeTruthy();});++ it("guides users to free external memory, rechecks, and clears guidance when room returns", async () => {+ const blockedPool = {+ ...gpuPool(0, 24),+ used_bytes: gb(16),+ };+ const busyView = labView({+ models: [+ modelView(+ localModel({+ availability: {+ downloadable: false,+ reason: {+ code: "MEMORY_INSUFFICIENT",+ have_bytes: gb(8),+ need_bytes: gb(16),+ },+ },+ fit: "none",+ id: "qwen3.8-27b:IQ3_S",+ memory_bytes: gb(16),+ name: "Qwen3.8 27B",+ pool: undefined,+ }),+ ),+ modelView(+ localModel({+ id: "spark-4b:Q4_K_M",+ memory_bytes: gb(4),+ name: "Spark 4B",+ pool: "gpu:0",+ }),+ ),+ ],+ pools: [blockedPool],+ });+ const fixture = setup([busyView]);+ withSource(fixture, {+ ...byokStatus,+ mode: "subscription",+ runtime: "claude",+ runtime_model: "claude-sonnet",+ });+ await renderPage(fixture);++ const tip = await screen.findByRole("complementary", {+ name: "Local model tip",+ });+ expect(tip).toHaveTextContent("16 GB");+ fireEvent.click(+ within(tip).getByRole("button", { name: "Open Local model" }),+ );++ const guidance = await screen.findByRole("complementary", {+ name: "Memory guidance",+ });+ expect(guidance).toHaveTextContent(+ "Free GPU memory to install a larger model",+ );+ fireEvent.click(+ within(guidance).getByRole("button", { name: "Recheck memory" }),+ );+ await waitFor(() => expect(fixture.refreshes).toEqual(["computer-lab"]));++ // After closing external GPU apps, the snapshot clears the warning and unlocks the 27B model.+ publishSnapshot(+ fixture,+ labView({+ models: [+ modelView(+ localModel({+ id: "qwen3.8-27b:IQ3_S",+ memory_bytes: gb(16),+ name: "Qwen3.8 27B",+ pool: "gpu:0",+ recommended: true,+ }),+ ),+ ],+ observed_at: "2026-11-13T10:05:00.000Z",+ pools: [gpuPool(0, 24)],+ }),+ );++ await waitFor(() =>+ expect(+ screen.queryByRole("complementary", { name: "Memory guidance" }),+ ).not.toBeInTheDocument(),+ );+ expect(+ screen.getByRole("button", { name: "Download Qwen3.8 27B" }),+ ).toBeEnabled();+ });++ it("rechecks memory from Make room to load on unified Macs and surfaces refresh failures", async () => {+ const busyMac = macView({+ models: [+ modelView(+ localModel({+ download_bytes: gb(42.5),+ error: { code: "LOAD_NO_ROOM", detail: "need 46 GiB" },+ fit: "unified",+ id: "llama3.3-70b:Q4_K_M",+ memory_bytes: gb(46),+ name: "Llama 3.3 70B",+ pool: "unified",+ state: "failed",+ }),+ ),+ ],+ pools: [+ {+ holders: [],+ id: "unified",+ kind: "unified",+ total_bytes: gb(51.2),+ used_bytes: gb(20),+ },+ ],+ });+ const fixture = setup([busyMac]);+ await renderPage(fixture);+ await findModels();++ fireEvent.click(+ screen.getByRole("button", { name: "Retry Llama 3.3 70B" }),+ );+ const dialog = screen.getByRole("dialog", { name: "Make room to load" });+ expect(dialog).toHaveTextContent("Other apps are using 20 GB.");++ fireEvent.click(+ within(dialog).getByRole("button", { name: "Recheck memory" }),+ );+ await waitFor(() => expect(fixture.refreshes).toEqual(["computer-mac"]));++ publishSnapshot(fixture, {+ ...busyMac,+ observed_at: "2026-11-13T10:06:00.000Z",+ pools: [+ {+ holders: [],+ id: "unified",+ kind: "unified",+ total_bytes: gb(51.2),+ used_bytes: 0,+ },+ ],+ });++ await waitFor(() =>+ expect(dialog).toHaveTextContent(+ "Enough memory is free now (51.2 GB available).",+ ),+ );+ fireEvent.click(within(dialog).getByRole("button", { name: "Load" }));+ await waitFor(() =>+ expect(fixture.actions).toEqual([+ {+ body: { action: "load" },+ computerId: "computer-mac",+ modelId: "llama3.3-70b:Q4_K_M",+ },+ ]),+ );++ // Failed rechecks show a retryable action error without crashing the library.+ fixture.runtime.server.on("POST", viewPath, () =>+ teamHubErrorResponse(503, "LOCAL_COMPUTER_OFFLINE"),+ );+ fireEvent.click(screen.getByRole("button", { name: "Recheck memory" }));+ expect(+ await screen.findByText(+ "The computer is offline. Reconnect it in Computers, then try again.",+ ),+ ).toBeInTheDocument();+ });++ it("lets the owner choose a loaded larger model in SwitchToLocalNotice and Use for Agents", async () => {+ const small = localModel({+ id: "spark-4b:Q4_K_M",+ memory_bytes: gb(4),+ name: "Spark 4B",+ pi_model: "localmodels-library/spark-4b",+ pool: "gpu:0",+ state: "loaded",+ });+ const large = 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 view = labView({+ models: [modelView(small), modelView(large)],+ });+ const fixture = setup([view]);+ const { switches } = withSource(fixture, {+ ...byokStatus,+ mode: "byok",+ runtime: "pi",+ runtime_model: "localmodels-byok",+ });+ 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/spark-4b",+ },+ viewer_is_owner: true,+ });+ });+ await renderPage(fixture);++ fireEvent.click(await screen.findByRole("tab", { name: "Local model" }));+ const modelSelect = await screen.findByRole("combobox", {+ name: "Local model",+ });+ fireEvent.click(modelSelect);+ fireEvent.click(await screen.findByRole("option", { name: /Spark 4B/u }));+ fireEvent.click(+ screen.getByRole("button", { name: "Switch to Local model" }),+ );+ await waitFor(() => expect(switches).toHaveLength(1));+ expect(switches[0]).toEqual({+ local_model_id: "spark-4b:Q4_K_M",+ mode: "local",+ });++ // Once on Local model mode running Spark 4B, loaded Qwen3.8 27B offers Use for Agents.+ const useLarge = await screen.findByRole("button", {+ name: "Use Qwen3.8 27B for Agents",+ });+ expect(+ screen.queryByRole("button", { name: "Use Spark 4B for Agents" }),+ ).toBeNull();+ fireEvent.click(useLarge);+ await waitFor(() => expect(switches).toHaveLength(2));+ expect(switches[1]).toEqual({+ local_model_id: "qwen3.8-27b:IQ3_S",+ mode: "local",+ });+ });++ it("hides Recheck memory and Use for Agents when read-only or offline while keeping one status notice", async () => {+ const busyView = labView({+ models: [+ modelView(+ localModel({+ availability: {+ downloadable: false,+ reason: {+ code: "MEMORY_INSUFFICIENT",+ have_bytes: gb(8),+ need_bytes: gb(16),+ },+ },+ fit: "none",+ id: "qwen3.8-27b:IQ3_S",+ memory_bytes: gb(16),+ name: "Qwen3.8 27B",+ pool: undefined,+ }),+ ),+ modelView(+ localModel({+ id: "loaded:Q4",+ memory_bytes: gb(4),+ name: "Loaded Model",+ pi_model: "localmodels-library/loaded",+ pool: "gpu:0",+ state: "loaded",+ }),+ ),+ ],+ pools: [{ ...gpuPool(0, 24), used_bytes: gb(16) }],+ viewer_is_owner: false,+ });+ const readOnlyFixture = setup([busyView]);+ await renderPage(readOnlyFixture);+ await findModels();++ expect(screen.getAllByRole("status")).toHaveLength(1);+ expect(+ screen.queryByRole("button", { name: "Recheck memory" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Use .* for Agents/u }),+ ).not.toBeInTheDocument();++ cleanup();+ const offlineView = labView({+ ...busyView,+ computer: { ...busyView.computer, status: "offline" },+ viewer_is_owner: true,+ });+ await renderPage(setup([offlineView]));+ await findModels();++ expect(screen.getAllByRole("status")).toHaveLength(1);+ expect(+ screen.queryByRole("button", { name: "Recheck memory" }),+ ).not.toBeInTheDocument();+ });});diff --git a/apps/web/src/features/local-models/local-models-page.tsx b/apps/web/src/features/local-models/local-models-page.tsxindex d117d542..a1350fd8 100644--- a/apps/web/src/features/local-models/local-models-page.tsx+++ b/apps/web/src/features/local-models/local-models-page.tsx@@ -28,12 +28,18 @@ import {RemoveModelDialog,UnloadModelDialog,} from "./local-model-dialogs";-import { actionErrorCopy, libraryUnavailableCopy } from "./local-models-copy";+import {+ actionErrorCopy,+ libraryUnavailableCopy,+ memoryGuidanceCopy,+} from "./local-models-copy";import {actOnLocalComputerModel,localModelActionMutationKey,localModelsQueryKey,localModelsQueryOptions,+ localModelsRefreshMutationKey,+ refreshLocalComputerModels,type LocalModelAction,type LocalModelActionInput,type LocalModelsView,@@ -42,9 +48,13 @@ import {downloadStopped,formatGigabytes,loadCheck,- localSwitchTarget,+ localSwitchTargets,+ memoryGuidance,memorySummary,modelEntries,+ poolFreeBytes,+ poolOf,+ poolRoomCheck,type ModelEntry,type ModelStatus,} from "./local-models-rules";@@ -59,6 +69,7 @@ import {import {type ModelSourceMode,modelSourceQueryOptions,+ type ModelSourceStatus,} from "./model-source-queries";type Dialog =@@ -223,6 +234,7 @@ function ComputerModels({tenantId: string;}) {const { client } = useTeamHubRuntime();+ const queryClient = useQueryClient();const query = useQuery(localModelsQueryOptions(client, tenantId, computerId));const view = query.data;const [dialog, setDialog] = useState<Dialog | null>(null);@@ -243,7 +255,28 @@ function ComputerModels({tenantId,});const switching = switcher.pending !== undefined;- const target = view?.available ? localSwitchTarget(view) : undefined;+ const switchTargets = view?.available ? localSwitchTargets(view) : [];+ const [refreshError, setRefreshError] = useState<string | null>(null);+ const refresh = useMutation({+ mutationFn: () => refreshLocalComputerModels(client, tenantId, computerId),+ mutationKey: localModelsRefreshMutationKey(tenantId, computerId),+ onError: (error) =>+ setRefreshError(+ error instanceof TeamHubError ? error.code : "REFRESH_FAILED",+ ),+ onMutate: () => setRefreshError(null),+ onSettled: () =>+ queryClient.invalidateQueries({+ queryKey: localModelsQueryKey(tenantId, computerId),+ }),+ });+ const canRecheck = Boolean(+ view && view.viewer_is_owner && view.computer.status === "online",+ );+ const guidance = view?.available ? memoryGuidance(view) : null;+ const subscriptionGuidanceCopy = guidance+ ? memoryGuidanceCopy(guidance)+ : undefined;return (<>@@ -256,15 +289,32 @@ function ComputerModels({</p>) : null}{summary?.totalBytes ? (- <p className="mt-1.5 text-sm text-muted-foreground">- {formatGigabytes(summary.usedBytes)} of{" "}- {formatGigabytes(summary.totalBytes)}{" "}- {summary.gpu ? "GPU memory" : "memory"} in use- </p>+ <>+ <p className="mt-1.5 text-sm text-muted-foreground">+ {formatGigabytes(summary.usedBytes)} of{" "}+ {formatGigabytes(summary.totalBytes)}{" "}+ {summary.gpu ? "GPU memory" : "memory"} in use+ </p>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {formatGigabytes(summary.freeBytes)} free+ {view?.observed_at+ ? ` · Checked ${relativeTime(view.observed_at)}`+ : ""}+ </p>+ </>) : null}</div><div className="flex shrink-0 items-center gap-2">{computerPicker}+ {canRecheck ? (+ <Button+ loading={refresh.isPending}+ onClick={() => refresh.mutate()}+ size="compact"+ >+ Recheck memory+ </Button>+ ) : null}{view?.available ? (<ButtononClick={() => setDialog({ kind: "advanced" })}@@ -288,6 +338,13 @@ function ComputerModels({<FormFeedback tone="danger">{switcher.failure}</FormFeedback></div>) : null}+ {refreshError ? (+ <div className="mt-4">+ <FormFeedback tone="danger">+ {actionErrorCopy(refreshError)}+ </FormFeedback>+ </div>+ ) : null}{switching ? (<p className="mt-4 text-sm text-muted-foreground" role="status">Switching {computerName}. This can take a few minutes the first time.@@ -295,12 +352,32 @@ function ComputerModels({) : null}{feedback}{status && shownTab === "subscription" ? (- <SubscriptionPanel- disabled={switching}- runtimes={runtimes}- status={status}- switcher={switcher}- />+ <>+ <SubscriptionPanel+ disabled={switching}+ runtimes={runtimes}+ status={status}+ switcher={switcher}+ />+ {subscriptionGuidanceCopy ? (+ <aside+ aria-label="Local model tip"+ className="mt-6 flex flex-wrap items-start justify-between gap-3 rounded-xl bg-muted px-4 py-3"+ >+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-foreground">+ {subscriptionGuidanceCopy.title}+ </p>+ <p className="mt-1 text-sm text-muted-foreground">+ {subscriptionGuidanceCopy.body}+ </p>+ </div>+ <Button onClick={() => setTab("local")} size="compact">+ Open Local model+ </Button>+ </aside>+ ) : null}+ </>) : status && shownTab === "byok" ? (<ByokPanelcomputerId={computerId}@@ -315,14 +392,26 @@ function ComputerModels({{status && status.mode !== "local" ? (<SwitchToLocalNoticedisabled={switching || view.computer.status === "offline"}- modelId={target?.id}- modelName={target?.name}+ models={switchTargets}switcher={switcher}/>) : null}<Librarydialog={dialog}+ guidance={guidance}+ onRefresh={() => refresh.mutate()}+ onUseForAgents={(modelId) =>+ switcher.request({ local_model_id: modelId, mode: "local" })+ }+ rechecking={refresh.isPending}setDialog={setDialog}+ status={status}+ switchingModelId={+ switcher.pending?.mode === "local"+ ? switcher.pending.local_model_id+ : undefined+ }+ switching={switching}tenantId={tenantId}view={view}/>@@ -355,12 +444,26 @@ function ComputerModels({function Library({dialog,+ guidance,+ onRefresh,+ onUseForAgents,+ rechecking,setDialog,+ status,+ switching,+ switchingModelId,tenantId,view,}: {dialog: Dialog | null;+ guidance: ReturnType<typeof memoryGuidance>;+ onRefresh: () => void;+ onUseForAgents: (modelId: string) => void;+ rechecking: boolean;setDialog: (dialog: Dialog | null) => void;+ status: ModelSourceStatus | undefined;+ switching: boolean;+ switchingModelId: string | undefined;tenantId: string;view: LocalModelsView;}) {@@ -449,11 +552,31 @@ function Library({actionStatuses[action].includes(entry.status);const dialogEntry =dialog && dialog.kind !== "advanced" ? find(dialog.modelId) : undefined;+ const dialogPool = dialogEntry+ ? poolOf(view, dialogEntry.model.pool)+ : undefined;const makeRoom =dialog?.kind === "makeRoom" && dialogEntry- ? loadCheck(view, dialogEntry.model)+ ? (poolRoomCheck(+ view,+ dialogPool,+ dialogEntry.model.memory_bytes,+ dialogEntry.model.id,+ ) ??+ (dialogPool+ ? {+ freeBytes: poolFreeBytes(dialogPool),+ loaded: [],+ needBytes: dialogEntry.model.memory_bytes,+ pool: dialogPool,+ }+ : null)): null;const failedEntry = failure ? find(failure.modelId) : undefined;+ const guidanceCopy =+ !offline && view.available && guidance+ ? memoryGuidanceCopy(guidance)+ : undefined;function act(input: LocalModelActionInput) {setDialog(null);@@ -522,12 +645,41 @@ function Library({</FormFeedback></div>) : null}+ {guidanceCopy ? (+ <aside+ aria-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"+ >+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-app-warning">+ {guidanceCopy.title}+ </p>+ <p className="mt-1 text-sm text-muted-foreground">+ {guidanceCopy.body}+ </p>+ </div>+ {readOnly ? null : (+ <Button 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- disabled={offline || readOnly || requests.has(modelId)}+ disabled={+ offline || readOnly || switching || requests.has(modelId)+ }entry={entry}expanded={expandedId === modelId}key={modelId}@@ -541,7 +693,11 @@ function Library({)}onUnload={() => unload(entry)}+ onUseForAgents={+ canUseForAgents ? () => onUseForAgents(modelId) : undefined+ }requested={requests.get(modelId)}+ switchingForAgents={switchingModelId === modelId}view={view}/>);@@ -566,6 +722,8 @@ function Library({unloadFirst,})}+ onRecheck={!offline && !readOnly ? onRefresh : undefined}+ rechecking={rechecking}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.tsindex 72a2e970..6aee92af 100644--- a/apps/web/src/features/local-models/local-models-queries.ts+++ b/apps/web/src/features/local-models/local-models-queries.ts@@ -12,6 +12,7 @@ export type LocalModelPool = Schemas["LocalModelPool"];export type LocalModelHost = Schemas["LocalModelHost"];export type LocalModelActionRequest = Schemas["LocalModelActionRequest"];export type LocalModelAction = LocalModelActionRequest["action"];+export type LocalModelsRefreshAccepted = Schemas["LocalModelsRefreshAccepted"];const localModelsPath ="/v0/tenants/{tenantId}/local-computers/{computerId}/local-models";@@ -49,6 +50,27 @@ export function localModelsQueryOptions(});}+/** Identifies pending memory/model refreshes for one Computer. */+export function localModelsRefreshMutationKey(+ tenantId: string,+ computerId: string,+) {+ return ["teamhub", tenantId, "local-models-refresh", computerId] as const;+}++/** Asks the Computer to recheck free memory and report a fresh snapshot. */+export function refreshLocalComputerModels(+ client: TeamHubClient,+ tenantId: string,+ computerId: string,+) {+ return teamHubData(+ client.api.POST(localModelsPath, {+ params: { path: { computerId, tenantId } },+ }),+ );+}+/** Identifies pending actions of one Computer, so each row can show its own. */export function localModelActionMutationKey(tenantId: string,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 8e3f6ca7..ccf0eaab 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@@ -8,8 +8,10 @@ import {formatGigabytes,isModelOnComputer,loadCheck,+ localSwitchTargets,makeRoomSelection,makesRoom,+ memoryGuidance,memorySummary,modelCapabilities,modelEntries,@@ -17,6 +19,8 @@ import {parametersLabel,placeName,poolLabel,+ poolOtherBytes,+ poolRoomCheck,safeModelSourceUrl,speedLabel,usedByBadge,@@ -82,17 +86,114 @@ describe("local models rules", () => {it("adds up GPU memory, or the memory of a Computer without GPUs", () => {expect(memorySummary(labView())).toEqual({+ freeBytes: gb(2.6) + gb(22.9),gpu: true,totalBytes: gb(24) * 2,usedBytes: gb(21.4) + gb(1.1),});expect(memorySummary(macView())).toEqual({+ freeBytes: gb(51.2) - gb(14.3),gpu: false,totalBytes: gb(51.2),usedBytes: gb(14.3),});});+ it("detects external app memory and surfaces cleanup guidance when it blocks models", () => {+ expect(memoryGuidance(labView())).toBeNull();+ expect(memoryGuidance(macView())).toBeNull();++ const busyGpu = {+ ...gpuPool(0, 24, [{ gb: 4, id: "small", name: "Small" }]),+ used_bytes: gb(18),+ };+ expect(poolOtherBytes(busyGpu)).toBe(gb(14));+ expect(poolRoomCheck(labView(), busyGpu, gb(8))?.freeBytes).toBe(gb(6));++ // A game holds 14 GB on a 24 GB card, so a 14 GB model is marked MEMORY_INSUFFICIENT.+ const blockedDownload = labView({+ models: [+ modelView(+ localModel({+ availability: {+ downloadable: false,+ reason: {+ code: "MEMORY_INSUFFICIENT",+ have_bytes: gb(6),+ need_bytes: gb(14),+ },+ },+ fit: "none",+ id: "qwen3.8-27b:IQ3_S",+ name: "Qwen3.8 27B",+ pool: undefined,+ }),+ ),+ ],+ pools: [busyGpu],+ });+ expect(memoryGuidance(blockedDownload)).toMatchObject({+ gpu: true,+ kind: "blocked_download",+ otherBytes: gb(14),+ });++ const blockedLoad = labView({+ models: [+ modelView(+ localModel({+ id: "gemma3-12b:Q4_K_M",+ memory_bytes: gb(10),+ name: "Gemma 3 12B",+ note: { code: "NO_ROOM_TO_LOAD" },+ pool: "gpu:0",+ state: "idle",+ }),+ ),+ ],+ pools: [busyGpu],+ });+ expect(memoryGuidance(blockedLoad)).toMatchObject({+ gpu: true,+ kind: "blocked_load",+ otherBytes: gb(14),+ });+ });++ it("orders local switch targets with loaded models first, then recommended, then largest", () => {+ const idleLarge = localModel({+ id: "large:Q4",+ memory_bytes: gb(20),+ name: "Large",+ state: "idle",+ });+ const idleSmallRec = localModel({+ id: "small:Q4",+ memory_bytes: gb(4),+ name: "Small",+ recommended: true,+ state: "idle",+ });+ const loadedOther = localModel({+ id: "loaded:Q4",+ memory_bytes: gb(8),+ name: "Loaded",+ state: "loaded",+ });+ const view = macView({+ models: [+ modelView(idleLarge),+ modelView(idleSmallRec),+ modelView(loadedOther),+ ],+ });+ expect(localSwitchTargets(view).map((model) => model.id)).toEqual([+ "loaded:Q4",+ "small:Q4",+ "large:Q4",+ ]);+ });+it("loads at once when the reported pool has room", () => {const view = labView();const gemma = view.models.find(diff --git a/apps/web/src/features/local-models/local-models-rules.ts b/apps/web/src/features/local-models/local-models-rules.tsindex d3b6e320..96988d8b 100644--- a/apps/web/src/features/local-models/local-models-rules.ts+++ b/apps/web/src/features/local-models/local-models-rules.ts@@ -133,17 +133,145 @@ export function poolFreeBytes(pool: LocalModelPool) {return Math.max(0, pool.total_bytes - pool.used_bytes);}+/** Memory held by known models and foundation components in one pool. */+export function poolHolderBytes(pool: LocalModelPool) {+ return pool.holders.reduce((sum, holder) => sum + holder.bytes, 0);+}++/** Memory in the pool used by other apps (games, browsers, video players). */+export function poolOtherBytes(pool: LocalModelPool) {+ return Math.max(0, pool.used_bytes - poolHolderBytes(pool));+}++/** Free memory plus memory currently held by external apps in one pool. */+export function poolReclaimableBytes(pool: LocalModelPool) {+ return poolFreeBytes(pool) + poolOtherBytes(pool);+}+/** 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;+ const totalBytes = pools.reduce((sum, pool) => sum + pool.total_bytes, 0);+ const usedBytes = pools.reduce((sum, pool) => sum + pool.used_bytes, 0);return {+ freeBytes: Math.max(0, totalBytes - usedBytes),gpu: gpus.length > 0,- totalBytes: pools.reduce((sum, pool) => sum + pool.total_bytes, 0),- usedBytes: pools.reduce((sum, pool) => sum + pool.used_bytes, 0),+ totalBytes,+ usedBytes,};}+export interface MemoryGuidance {+ kind: "blocked_download" | "blocked_load" | "constrained_pool";+ gpu: boolean;+ otherBytes: number;+ freeBytes: number;+ totalBytes: number;+}++function maxHardwareCapacity(view: LocalModelsView) {+ const gpus = view.pools.filter((pool) => pool.kind === "gpu");+ if (gpus.length) {+ return Math.max(+ ...gpus.map((pool) => pool.total_bytes),+ ...(view.computer.host?.gpus.map((gpu) => gpu.total_bytes) ?? [0]),+ );+ }+ const unifiedOrSystem = view.pools.map((pool) => pool.total_bytes);+ return Math.max(+ view.computer.host?.ram_total_bytes ?? 0,+ ...unifiedOrSystem,+ 0,+ );+}++/**+ * Whether external apps hold enough GPU or system memory that closing them+ * and rechecking could let a larger model download or load.+ */+export function memoryGuidance(view: LocalModelsView): MemoryGuidance | null {+ if (!view.available || !view.pools.length) return null;+ const summary = memorySummary(view);+ const externalPools = view.pools+ .map((pool) => ({ external: poolOtherBytes(pool), pool }))+ .filter((item) => item.external > 0)+ .sort((left, right) => right.external - left.external);+ if (!externalPools.length) return null;++ const top = externalPools[0]!;+ const otherBytes = externalPools.reduce(+ (sum, item) => sum + item.external,+ 0,+ );+ const blockedLoad = modelEntries(view).some((entry) => {+ const { model, status } = entry;+ if (status !== "idle" && status !== "failed") return false;+ const pool = poolOf(view, model.pool);+ const poolHasExternal = pool ? poolOtherBytes(pool) > 0 : false;+ if (!poolHasExternal) return false;+ return (+ model.note?.code === "NO_ROOM_TO_LOAD" ||+ model.error?.code === "LOAD_NO_ROOM" ||+ model.error?.code === "OUT_OF_MEMORY" ||+ loadCheck(view, model) !== null+ );+ });+ if (blockedLoad) {+ return {+ freeBytes: summary.freeBytes,+ gpu: top.pool.kind === "gpu" || summary.gpu,+ kind: "blocked_load",+ otherBytes,+ totalBytes: summary.totalBytes,+ };+ }++ const hardwareMax = maxHardwareCapacity(view);+ const blockedDownload = modelEntries(view).some((entry) => {+ const reason = entry.model.availability.reason;+ return (+ entry.status === "unavailable" &&+ reason?.code === "MEMORY_INSUFFICIENT" &&+ reason.need_bytes !== undefined &&+ reason.need_bytes <= hardwareMax+ );+ });+ if (blockedDownload) {+ return {+ freeBytes: summary.freeBytes,+ gpu: top.pool.kind === "gpu" || summary.gpu,+ kind: "blocked_download",+ otherBytes,+ totalBytes: summary.totalBytes,+ };+ }++ const constrainedAvailable = modelEntries(view).some((entry) => {+ if (entry.status !== "available") return false;+ const pool = poolOf(view, entry.model.pool);+ return (+ pool !== undefined &&+ poolOtherBytes(pool) > 0 &&+ entry.model.memory_bytes > poolFreeBytes(pool)+ );+ });+ const twoGigabytes = 2 * 1024 ** 3;+ if (+ otherBytes >= twoGigabytes &&+ (constrainedAvailable || externalPools.length > 0)+ ) {+ return {+ freeBytes: summary.freeBytes,+ gpu: top.pool.kind === "gpu" || summary.gpu,+ kind: "constrained_pool",+ otherBytes,+ totalBytes: summary.totalBytes,+ };+ }+ return null;+}+export interface LoadCheck {pool: LocalModelPool;needBytes: number;@@ -152,26 +280,43 @@ export interface LoadCheck {loaded: ModelEntry[];}-/** Why a model cannot load now, or `null` when its pool reports room for it. */-export function loadCheck(+/**+ * Why a model cannot load into `pool` now, or `null` when that pool reports+ * room for `needBytes`.+ */+export function poolRoomCheck(view: LocalModelsView,- model: LocalModel,+ pool: LocalModelPool | undefined,+ needBytes: number,+ excludeModelId?: string,): LoadCheck | null {- const pool = poolOf(view, model.pool);- if (!pool || poolFreeBytes(pool) >= model.memory_bytes) return null;+ if (!pool || poolFreeBytes(pool) >= needBytes) return null;return {freeBytes: poolFreeBytes(pool),loaded: modelEntries(view).filter((entry) =>entry.status === "loaded" &&entry.model.pool === pool.id &&- entry.model.id !== model.id,+ entry.model.id !== excludeModelId,),- needBytes: model.memory_bytes,+ needBytes,pool,};}+/** Why a model cannot load now, or `null` when its pool reports room for it. */+export function loadCheck(+ view: LocalModelsView,+ model: LocalModel,+): LoadCheck | null {+ return poolRoomCheck(+ view,+ poolOf(view, model.pool),+ model.memory_bytes,+ model.id,+ );+}+function freedBytes(entries: ModelEntry[]) {return entries.reduce((sum, entry) => sum + entry.model.memory_bytes, 0);}@@ -374,10 +519,22 @@ export function modelSourceLabel(url: string) {* The model a switch to Local model runs: a loaded one, else one on disk. None* when the Computer has no model downloaded yet.*/+/** Candidate local models on disk ordered loaded-first, recommended, then largest. */+export function localSwitchTargets(view: LocalModelsView): LocalModel[] {+ return view.models+ .map((item) => item.model)+ .filter((model) => model.state === "loaded" || model.state === "idle")+ .sort((left, right) => {+ if (left.state !== right.state) {+ return left.state === "loaded" ? -1 : 1;+ }+ if (left.recommended !== right.recommended) {+ return left.recommended ? -1 : 1;+ }+ return right.memory_bytes - left.memory_bytes;+ });+}+export function localSwitchTarget(view: LocalModelsView) {- const models = view.models.map((item) => item.model);- return (- models.find((model) => model.state === "loaded") ??- models.find((model) => model.state === "idle")- );+ return localSwitchTargets(view)[0];}diff --git a/apps/web/src/features/local-models/model-source-panel.tsx b/apps/web/src/features/local-models/model-source-panel.tsxindex c50c284d..6bcc08df 100644--- a/apps/web/src/features/local-models/model-source-panel.tsx+++ b/apps/web/src/features/local-models/model-source-panel.tsx@@ -26,8 +26,11 @@ import {modelSourceModeLabels,modelSourceRuntimeLabels,} from "./local-models-copy";-import { tenantLocalModelsQueryKey } from "./local-models-queries";-import { contextLabel } from "./local-models-rules";+import {+ type LocalModel,+ tenantLocalModelsQueryKey,+} from "./local-models-queries";+import { contextLabel, formatGigabytes } from "./local-models-rules";import {type ByokInput,type ByokModel,@@ -268,38 +271,63 @@ function Panel({ children, title }: { children: ReactNode; title: string }) {/** Offered above the library while the Agents use another source. */export function SwitchToLocalNotice({disabled,- modelId,- modelName,+ models,switcher,}: {disabled: boolean;- modelId: string | undefined;- modelName: string | undefined;+ 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 single = models.length === 1 ? models[0] : undefined;+return (- <div className="mt-6 flex items-center justify-between gap-4 rounded-xl bg-muted px-4 py-3">- <p className="text-sm text-muted-foreground">- {modelName ? (+ <div className="mt-6 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-muted px-4 py-3">+ <p className="min-w-0 flex-1 text-sm text-muted-foreground">+ {single ? (<>- <span className="text-foreground">{modelName}</span> is on this+ <span className="text-foreground">{single.name}</span> is on thiscomputer and can run your Agents locally.</>+ ) : models.length > 1 ? (+ "Choose a model on this computer to run your Agents locally.") : ("Download a model below to run your Agents locally.")}</p>- <Button- disabled={disabled || !modelId}- loading={switcher.pending?.mode === "local"}- onClick={() =>- switcher.request({ local_model_id: modelId, mode: "local" })- }- size="compact"- tone="primary"- >- Switch to Local model- </Button>+ <div className="flex shrink-0 flex-wrap items-center gap-2">+ {models.length > 1 && chosen ? (+ <Select+ aria-label="Local model"+ onValueChange={setSelectedId}+ value={chosen.id}+ variant="pill"+ >+ {models.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ {model.name} ·{" "}+ {model.state === "loaded" ? "Loaded" : "Downloaded"} ·{" "}+ {formatGigabytes(model.memory_bytes)}+ </SelectItem>+ ))}+ </Select>+ ) : null}+ <Button+ disabled={disabled || !chosen}+ loading={switcher.pending?.mode === "local"}+ onClick={() =>+ chosen &&+ switcher.request({ local_model_id: chosen.id, mode: "local" })+ }+ size="compact"+ tone="primary"+ >+ Switch to Local model+ </Button>+ </div></div>);}diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.goindex 89eca03a..61c5dca7 100644--- a/contracts/generated/go/teamhubpublic/openapi.gen.go+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go@@ -2444,6 +2444,21 @@ func (e LocalModelsErrorCode) Valid() bool {}}+// Defines values for LocalModelsRefreshAcceptedAction.+const (+ LocalModelsRefreshAcceptedRefresh LocalModelsRefreshAcceptedAction = "refresh"+)++// Valid indicates whether the value is a known member of the LocalModelsRefreshAcceptedAction enum.+func (e LocalModelsRefreshAcceptedAction) Valid() bool {+ switch e {+ case LocalModelsRefreshAcceptedRefresh:+ return true+ default:+ return false+ }+}+// Defines values for LocalModelsViewUnavailableReasonCode.const (LocalModelsViewNotReported LocalModelsViewUnavailableReasonCode = "NOT_REPORTED"@@ -2801,6 +2816,7 @@ const (ModelSourceErrorCodeByokUnreachable ModelSourceErrorCode = "BYOK_UNREACHABLE"ModelSourceErrorCodeByokUpstreamRejected ModelSourceErrorCode = "BYOK_UPSTREAM_REJECTED"ModelSourceErrorCodeLocalComputerOffline ModelSourceErrorCode = "LOCAL_COMPUTER_OFFLINE"+ ModelSourceErrorCodeLocalModelNoRoom ModelSourceErrorCode = "LOCAL_MODEL_NO_ROOM"ModelSourceErrorCodeLocalModelUnknown ModelSourceErrorCode = "LOCAL_MODEL_UNKNOWN"ModelSourceErrorCodeModelSourceFailed ModelSourceErrorCode = "MODEL_SOURCE_FAILED"ModelSourceErrorCodeModelSourceForbidden ModelSourceErrorCode = "MODEL_SOURCE_FORBIDDEN"@@ -2827,6 +2843,8 @@ func (e ModelSourceErrorCode) Valid() bool {return truecase ModelSourceErrorCodeLocalComputerOffline:return true+ case ModelSourceErrorCodeLocalModelNoRoom:+ return truecase ModelSourceErrorCodeLocalModelUnknown:return truecase ModelSourceErrorCodeModelSourceFailed:@@ -6708,6 +6726,17 @@ type LocalModelsErrorResponse struct {Error LocalModelsError `json:"error"`}+// LocalModelsRefreshAccepted defines model for LocalModelsRefreshAccepted.+type LocalModelsRefreshAccepted struct {+ Action LocalModelsRefreshAcceptedAction `json:"action"`++ // ComputerId Opaque, case-sensitive identifier. Clients must not infer type or time from it.+ ComputerId Id `json:"computer_id"`+}++// LocalModelsRefreshAcceptedAction defines model for LocalModelsRefreshAccepted.Action.+type LocalModelsRefreshAcceptedAction string+// LocalModelsView One Computer's model library as last reported. Only the Computer owner can act (viewer_is_owner); other Tenant members who can see the Computer read it.type LocalModelsView struct {Available bool `json:"available"`@@ -7212,7 +7241,7 @@ type MessageThreadSummaryUpdatedPayload struct {// ModelSourceError The common error body with error.code narrowed to ModelSourceErrorCode.type ModelSourceError struct {- // Code error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).+ // Code error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_NO_ROOM, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).Code ModelSourceErrorCode `json:"code"`Details *[]ErrorDetail `json:"details,omitempty"`@@ -7221,7 +7250,7 @@ type ModelSourceError struct {RequestId string `json:"request_id"`}-// ModelSourceErrorCode error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).+// ModelSourceErrorCode error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_NO_ROOM, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).type ModelSourceErrorCode string// ModelSourceErrorResponse defines model for ModelSourceErrorResponse.diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.tsindex d7e714c2..ced85053 100644--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts@@ -463,7 +463,11 @@ export interface paths {*/get: operations["getLocalComputerModels"];put?: never;- post?: never;+ /**+ * Ask an owned Local Computer to recheck memory and refresh its model library.+ * @description Only the Computer owner may ask it to refresh. TeamHub forwards a refresh command to the Computer, which answers at once; 202 means the Computer will re-probe free memory and models and send a fresh snapshot.+ */+ post: operations["refreshLocalComputerModels"];delete?: never;options?: never;head?: never;@@ -4791,18 +4795,10 @@ export interface components {pools: components["schemas"]["LocalModelPool"][];models: components["schemas"]["LocalModelView"][];};- /** @description A Human's action on one model. The click is the approval; there is no separate confirm step on the Computer. unload_first only with load. */- LocalModelActionRequest: {- /** @enum {string} */- action: "download" | "cancel" | "load" | "unload" | "remove";- /** @description Loaded models in the same pool to unload before the load starts. */- unload_first?: components["schemas"]["LocalModelId"][];- };- LocalModelActionAccepted: {+ LocalModelsRefreshAccepted: {computer_id: components["schemas"]["Id"];- model_id: components["schemas"]["LocalModelId"];/** @enum {string} */- action: "download" | "cancel" | "load" | "unload" | "remove";+ action: "refresh";};/*** @description error.code of a refused local-models action (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. LOCAL_MODEL_ACTION_FORBIDDEN: the viewer is not the Computer owner. LOCAL_MODELS_UNAVAILABLE: the Computer has no usable localmodels tool. LOCAL_MODEL_ACTION_FAILED: the Computer refused with a library error that has no code of its own here (502). LOCAL_MODELS_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). LOCAL_MODEL_ACTION_UNCONFIRMED: the connected Computer had not decided by the action's deadline; it may still run the action, and the library snapshots show the outcome (504). The other LOCAL_MODEL_ codes are the Computer's refusal codes of the same name (409).@@ -4835,6 +4831,19 @@ export interface components {LocalModelsErrorResponse: {error: components["schemas"]["LocalModelsError"];};+ /** @description A Human's action on one model. The click is the approval; there is no separate confirm step on the Computer. unload_first only with load. */+ LocalModelActionRequest: {+ /** @enum {string} */+ action: "download" | "cancel" | "load" | "unload" | "remove";+ /** @description Loaded models in the same pool to unload before the load starts. */+ unload_first?: components["schemas"]["LocalModelId"][];+ };+ LocalModelActionAccepted: {+ computer_id: components["schemas"]["Id"];+ model_id: components["schemas"]["LocalModelId"];+ /** @enum {string} */+ action: "download" | "cancel" | "load" | "unload" | "remove";+ };/*** @description Active model source mode on a Local Computer.* @enum {string}@@ -4879,7 +4888,7 @@ export interface components {terminated_run_count?: number;};/**- * @description error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).+ * @description error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_NO_ROOM, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).* @enum {string}*/ModelSourceErrorCode:@@ -4888,6 +4897,7 @@ export interface components {| "MODEL_SOURCE_UNAVAILABLE"| "AGENT_HAS_ACTIVE_RUNS"| "RUNTIME_NOT_ENABLED"+ | "LOCAL_MODEL_NO_ROOM"| "LOCAL_MODEL_UNKNOWN"| "BYOK_INVALID_CONFIG"| "BYOK_AUTH_FAILED"@@ -9110,6 +9120,36 @@ export interface operations {404: components["responses"]["NotFound"];};};+ refreshLocalComputerModels: {+ parameters: {+ query?: never;+ header?: never;+ path: {+ tenantId: components["parameters"]["TenantId"];+ computerId: components["parameters"]["ComputerId"];+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description The Computer started refreshing its model library. */+ 202: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["LocalModelsRefreshAccepted"];+ };+ };+ 401: components["responses"]["Unauthenticated"];+ 403: components["responses"]["LocalModelsRefused"];+ 404: components["responses"]["NotFound"];+ 409: components["responses"]["LocalModelsRefused"];+ 502: components["responses"]["LocalModelsRefused"];+ 503: components["responses"]["LocalModelsRefused"];+ 504: components["responses"]["LocalModelsRefused"];+ };+ };actOnLocalComputerModel: {parameters: {query?: never;diff --git a/contracts/openapi/components/local-models.yaml b/contracts/openapi/components/local-models.yamlindex 68dd90f4..ea5bf042 100644--- a/contracts/openapi/components/local-models.yaml+++ b/contracts/openapi/components/local-models.yaml@@ -680,6 +680,17 @@ components:LocalModelActionAcceptedUnload,LocalModelActionAcceptedRemove,]+ LocalModelsRefreshAccepted:+ type: object+ additionalProperties: false+ required: [computer_id, action]+ properties:+ computer_id:+ $ref: "./common.yaml#/components/schemas/Id"+ action:+ type: string+ enum: [refresh]+ x-enum-varnames: [LocalModelsRefreshAcceptedRefresh]LocalModelsErrorCode:description: >-error.code of a refused local-models action (403, 409, 502, 503, 504);diff --git a/contracts/openapi/components/model-source.yaml b/contracts/openapi/components/model-source.yamlindex 7d0799be..cba5d362 100644--- a/contracts/openapi/components/model-source.yaml+++ b/contracts/openapi/components/model-source.yaml@@ -266,11 +266,12 @@ components:Agents on the Computer have running work and force_terminate wasfalse; details carries one entry per such Agent, with field "agent"and the Agent's display name as reason. RUNTIME_NOT_ENABLED,- LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals- (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has- no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent- Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the- Computer had not answered by the deadline; it may still switch (504).+ LOCAL_MODEL_NO_ROOM, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the+ Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed+ with an error that has no code of its own here (502).+ MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached+ (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the+ deadline; it may still switch (504).type: stringenum:- LOCAL_COMPUTER_OFFLINE@@ -278,6 +279,7 @@ components:- MODEL_SOURCE_UNAVAILABLE- AGENT_HAS_ACTIVE_RUNS- RUNTIME_NOT_ENABLED+ - LOCAL_MODEL_NO_ROOM- LOCAL_MODEL_UNKNOWN- BYOK_INVALID_CONFIG- BYOK_AUTH_FAILED@@ -293,6 +295,7 @@ components:- ModelSourceErrorCodeModelSourceUnavailable- ModelSourceErrorCodeAgentHasActiveRuns- ModelSourceErrorCodeRuntimeNotEnabled+ - ModelSourceErrorCodeLocalModelNoRoom- ModelSourceErrorCodeLocalModelUnknown- ModelSourceErrorCodeByokInvalidConfig- ModelSourceErrorCodeByokAuthFaileddiff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yamlindex a12c6ffe..52ee9899 100644--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml@@ -768,6 +768,35 @@ paths:$ref: '../components/common.yaml#/components/responses/Unauthenticated''404':$ref: '../components/common.yaml#/components/responses/NotFound'+ post:+ tags: [Local Computers]+ operationId: refreshLocalComputerModels+ summary: Ask an owned Local Computer to recheck memory and refresh its model library.+ description: >-+ Only the Computer owner may ask it to refresh. TeamHub forwards a refresh command to the+ Computer, which answers at once; 202 means the Computer will re-probe free memory and+ models and send a fresh snapshot.+ responses:+ '202':+ description: The Computer started refreshing its model library.+ content:+ application/json:+ schema:+ $ref: '../components/local-models.yaml#/components/schemas/LocalModelsRefreshAccepted'+ '401':+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'+ '403':+ $ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'+ '404':+ $ref: '../components/common.yaml#/components/responses/NotFound'+ '409':+ $ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'+ '502':+ $ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'+ '503':+ $ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'+ '504':+ $ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'/v0/tenants/{tenantId}/local-computers/{computerId}/local-models/{modelId}/actions:parameters:- $ref: '#/components/parameters/TenantId'