Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: optimize model picker scans with shared inventory caching (#8381)

oobaboogad707c4eb9b85
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 6020bc653c1..3c06ba56880 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -59,6 +59,11 @@ import {
downloadManager,
useRepoDownload,
} from "@/features/hub/download-manager";
+import {
+ INVENTORY_FRESHNESS_WINDOW_MS,
+ useDeviceInventorySources,
+} from "@/features/hub/inventory";
+import { chatLocalModelOptions } from "./local-model-options";
import {
type NativeIntent,
NativeAttachmentTargetContext,
@@ -112,7 +117,7 @@ import {
useState,
} from "react";
import type { PanelImperativeHandle } from "react-resizable-panels";
-import { listLocalModels, notifyChatHistoryUpdated } from "./api/chat-api";
+import { notifyChatHistoryUpdated } from "./api/chat-api";
import { ArtifactSurface } from "./artifacts/artifact-surface";
import {
clearAutoOpenedArtifacts,
@@ -3055,38 +3060,17 @@ export function ChatPage({
[externalProvidersForChat, lastOpenRouterChosenModel],
);
- const [localModels, setLocalModels] = useState<LoraModelOption[]>([]);
+ const localModelInventory = useDeviceInventorySources(["localModels"], {
+ enabled: active,
+ });
+ const localModels = useMemo<LoraModelOption[]>(
+ () => chatLocalModelOptions(localModelInventory.localModels.rows),
+ [localModelInventory.localModels.rows],
+ );
const refreshLocalModels = useCallback(() => {
- void listLocalModels()
- .then((res) => {
- setLocalModels(
- res.models
- .filter(
- (m) =>
- m.source === "lmstudio" ||
- m.source === "models_dir" ||
- m.source === "custom",
- )
- .map((m) => ({
- id: m.id,
- name:
- m.source === "lmstudio" && m.model_id
- ? m.model_id
- : m.display_name,
- baseModel:
- m.source === "lmstudio"
- ? "LM Studio"
- : m.source === "custom"
- ? "Custom Folders"
- : "Local models",
- updatedAt: m.updated_at ?? undefined,
- source: "local" as const,
- })),
- );
- })
- .catch(() => {});
- }, [navigate]);
+ void localModelInventory.refresh();
+ }, [localModelInventory.refresh]);
const refreshModelLists = useCallback(
(deletedModel?: DeletedModelRef) => {
@@ -3123,8 +3107,8 @@ export function ChatPage({
const refreshDeferredModelInventories = useCallback(() => {
inventoryRefreshStartedRef.current = true;
void refresh({ includeLoras: true });
- refreshLocalModels();
- }, [refresh, refreshLocalModels]);
+ void localModelInventory.refreshIfOlderThan(INVENTORY_FRESHNESS_WINDOW_MS);
+ }, [refresh, localModelInventory.refreshIfOlderThan]);
useEffect(() => {
if (getTrainingCompareHandoff()) return;
diff --git a/studio/frontend/src/features/chat/local-model-options.ts b/studio/frontend/src/features/chat/local-model-options.ts
new file mode 100644
index 00000000000..904af1df791
--- /dev/null
+++ b/studio/frontend/src/features/chat/local-model-options.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { LocalModelInfo } from "@/features/hub/inventory/api";
+import type { LoraModelOption } from "@/features/model-picker/components/model-selector/types";
+
+/** The device-inventory sources Chat lists as local models.
+ *
+ * Deliberately the same set as the picker's `PICKER_LOCAL_SOURCES`, and `ollama` is
+ * deliberately absent from both. The compat endpoint Chat used to call materialized a
+ * `.gguf` link eagerly and handed back a loadable path, while `/api/hub/local` scans
+ * read-only and returns an opaque `ollama-manifest:` reference that only
+ * `materialize_ollama_model_ref` can resolve. Nothing calls that yet, so offering these
+ * rows would produce entries that fail on selection rather than load.
+ */
+const CHAT_LOCAL_SOURCES: ReadonlySet<LocalModelInfo["source"]> = new Set([
+ "lmstudio",
+ "models_dir",
+ "custom",
+]);
+
+function baseModelLabel(source: LocalModelInfo["source"]): string {
+ switch (source) {
+ case "lmstudio":
+ return "LM Studio";
+ case "custom":
+ return "Custom Folders";
+ default:
+ return "Local models";
+ }
+}
+
+/** Chat's local model options, one per load id.
+ *
+ * The shared inventory keys a row on (format, path), so a directory holding both GGUF and
+ * safetensors weights arrives as two rows with distinct `inventory_id` but the SAME `id`.
+ * The selector keys on `id` (`key={adapter.id}`, `selected={value === adapter.id}`), so
+ * both rows would collide on a React key and render as selected together. The compat
+ * endpoint returned one row per directory, so collapsing on `id` keeps that behaviour.
+ */
+export function chatLocalModelOptions(
+ rows: readonly LocalModelInfo[],
+): LoraModelOption[] {
+ const options: LoraModelOption[] = [];
+ const seen = new Set<string>();
+ for (const model of rows) {
+ if (!CHAT_LOCAL_SOURCES.has(model.source) || seen.has(model.id)) {
+ continue;
+ }
+ seen.add(model.id);
+ options.push({
+ id: model.id,
+ name:
+ model.source === "lmstudio" && model.model_id
+ ? model.model_id
+ : model.display_name,
+ baseModel: baseModelLabel(model.source),
+ updatedAt: model.updated_at ?? undefined,
+ source: "local" as const,
+ });
+ }
+ return options;
+}
diff --git a/studio/frontend/src/features/hub/inventory/index.ts b/studio/frontend/src/features/hub/inventory/index.ts
index d9b2802d1b5..efee78c74a6 100644
--- a/studio/frontend/src/features/hub/inventory/index.ts
+++ b/studio/frontend/src/features/hub/inventory/index.ts
@@ -71,6 +71,7 @@ export {
type DeviceInventorySource,
type DeviceInventorySourceState,
} from "./use-device-inventory";
+export { INVENTORY_FRESHNESS_WINDOW_MS } from "./inventory-freshness";
export {
useHubInventory,
type HubInventoryKind,
diff --git a/studio/frontend/src/features/hub/inventory/inventory-freshness.ts b/studio/frontend/src/features/hub/inventory/inventory-freshness.ts
new file mode 100644
index 00000000000..db613e680e3
--- /dev/null
+++ b/studio/frontend/src/features/hub/inventory/inventory-freshness.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type InventoryRefreshDecision = "reuse" | "join" | "refresh";
+export const INVENTORY_FRESHNESS_WINDOW_MS = 30_000;
+
+/** Whether a `Date.now()` stamp is still inside `maxAgeMs`.
+ *
+ * A NEGATIVE age counts as stale, not fresh. These stamps come from `Date.now()`, which
+ * tracks the system clock and can step backwards (an NTP correction of more than ~125ms
+ * jumps rather than slews, and a VM resume or a user editing the clock does the same); only
+ * `performance.now()` is monotonic. Without the guard a stamp from the future reads as
+ * "younger than the window", so every caller reuses and the inventory stays frozen for the
+ * length of the skew -- including `refreshIfOlderThan(0)`, which callers use to mean
+ * "refresh unconditionally".
+ */
+export function isInventoryStampFresh(
+ stamp: number | null,
+ now: number,
+ maxAgeMs: number,
+): boolean {
+ if (stamp === null) {
+ return false;
+ }
+ const age = now - stamp;
+ return age >= 0 && age < Math.max(0, maxAgeMs);
+}
+
+/** The `revalidatedAt` a completed scan should leave behind.
+ *
+ * The stamp means one thing only: "an empty inventory has been seen TWICE, so the emptiness
+ * is confirmed". `useHubInventory` skips its second look while the stamp is fresh, so it has
+ * to track both ends of that claim.
+ *
+ * - rows came back, so the inventory is not empty: clear it. Keeping it would let a later
+ * FIRST empty scan land inside the window and read as already confirmed.
+ * - a forced scan over an inventory already observed empty: this is the second look, stamp
+ * it. Stamping every force instead lets a manual refresh that happens to return empty
+ * record itself as its own confirmation.
+ * - anything else: carry the stamp for the same key, and drop it when the key changes.
+ */
+export function nextRevalidationStamp({
+ force,
+ requestKey,
+ previous,
+ rowCount,
+ now,
+}: {
+ force: boolean;
+ requestKey: string;
+ previous: {
+ key: string | null;
+ ready: boolean;
+ error: string | null;
+ rowCount: number;
+ revalidatedAt: number | null;
+ };
+ rowCount: number;
+ now: number;
+}): number | null {
+ if (rowCount > 0) {
+ return null;
+ }
+ const sameKey = previous.key === requestKey;
+ if (force && sameKey && previous.ready && previous.error === null && previous.rowCount === 0) {
+ return now;
+ }
+ return sameKey ? previous.revalidatedAt : null;
+}
+
+export function inventoryRefreshDecision(
+ source: {
+ ready: boolean;
+ loading: boolean;
+ error: string | null;
+ key: string | null;
+ refreshedAt: number | null;
+ },
+ requestKey: string,
+ now: number,
+ maxAgeMs: number,
+): InventoryRefreshDecision {
+ if (!source.ready || source.key !== requestKey || source.loading) {
+ return "join";
+ }
+ if (source.error !== null) {
+ return "refresh";
+ }
+ return isInventoryStampFresh(source.refreshedAt, now, maxAgeMs)
+ ? "reuse"
+ : "refresh";
+}
diff --git a/studio/frontend/src/features/hub/inventory/inventory-settlement.ts b/studio/frontend/src/features/hub/inventory/inventory-settlement.ts
index 0daf2517980..23ea030a81c 100644
--- a/studio/frontend/src/features/hub/inventory/inventory-settlement.ts
+++ b/studio/frontend/src/features/hub/inventory/inventory-settlement.ts
@@ -3,20 +3,18 @@
export function resolveInventorySettlement({
downloadedReady,
- emptyRevalidationSignature,
+ emptyRevalidationFresh,
hasActiveEmptyRefresh,
hasInventoryRows,
hasUnreadyInventoryFailure,
inventoryFailed,
- lastEmptyRevalidationSignature,
}: {
downloadedReady: boolean;
- emptyRevalidationSignature: string;
+ emptyRevalidationFresh: boolean;
hasActiveEmptyRefresh: boolean;
hasInventoryRows: boolean;
hasUnreadyInventoryFailure: boolean;
inventoryFailed: boolean;
- lastEmptyRevalidationSignature: string | null;
}): {
emptyRevalidationRequired: boolean;
inventorySettled: boolean;
@@ -26,7 +24,7 @@ export function resolveInventorySettlement({
!inventoryFailed &&
!hasInventoryRows &&
!hasActiveEmptyRefresh &&
- lastEmptyRevalidationSignature !== emptyRevalidationSignature;
+ !emptyRevalidationFresh;
return {
emptyRevalidationRequired,
inventorySettled:
diff --git a/studio/frontend/src/features/hub/inventory/use-device-inventory.ts b/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
index 4ce0f3622e5..3866248e949 100644
--- a/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
+++ b/studio/frontend/src/features/hub/inventory/use-device-inventory.ts
@@ -20,6 +20,10 @@ import { useInventoryVersion } from "../stores/inventory-events";
import { useCallback, useEffect, useMemo } from "react";
import { create } from "zustand";
import { useShallow } from "zustand/react/shallow";
+import {
+ inventoryRefreshDecision,
+ nextRevalidationStamp,
+} from "./inventory-freshness";
export type DeviceInventorySource =
| "cachedGguf"
@@ -42,6 +46,8 @@ export type DeviceInventorySourceState<Rows extends readonly unknown[]> = {
ready: boolean;
error: string | null;
key: string | null;
+ refreshedAt: number | null;
+ revalidatedAt: number | null;
};
type DeviceInventoryState = {
@@ -66,6 +72,7 @@ type UseDeviceInventoryResult<
Sources extends readonly DeviceInventorySource[],
> = Pick<DeviceInventoryState, Sources[number]> & {
refresh: () => Promise<void>;
+ refreshIfOlderThan: (maxAgeMs: number) => Promise<void>;
};
const TOKEN_SCOPED_SOURCES = new Set<DeviceInventorySource>([
@@ -86,6 +93,8 @@ function emptySource<
ready: false,
error: null,
key: null,
+ refreshedAt: null,
+ revalidatedAt: null,
};
}
@@ -214,7 +223,12 @@ export function fetchInventorySource<K extends DeviceInventorySource>(
forceQueue.set(key, refetch);
return refetch;
}
- if (!options.force && current.ready && current.key === key) {
+ if (
+ !options.force &&
+ current.ready &&
+ current.error === null &&
+ current.key === key
+ ) {
return Promise.resolve(current.rows);
}
@@ -225,17 +239,34 @@ export function fetchInventorySource<K extends DeviceInventorySource>(
ready: current.ready,
error: null,
key,
+ refreshedAt: current.key === key ? current.refreshedAt : null,
+ revalidatedAt: current.key === key ? current.revalidatedAt : null,
});
const request = runSourceFetch(source, options.hfToken)
.then((rows) => {
if (useDeviceInventoryStore.getState()[source].key === key) {
+ const refreshedAt = Date.now();
updateSourceState(source, {
rows,
loading: false,
ready: true,
error: null,
key,
+ refreshedAt,
+ revalidatedAt: nextRevalidationStamp({
+ force: Boolean(options.force),
+ requestKey: key,
+ previous: {
+ key: current.key,
+ ready: current.ready,
+ error: current.error,
+ rowCount: current.rows.length,
+ revalidatedAt: current.revalidatedAt,
+ },
+ rowCount: rows.length,
+ now: refreshedAt,
+ }),
});
}
return rows;
@@ -263,23 +294,6 @@ export function fetchInventorySource<K extends DeviceInventorySource>(
return request;
}
-export function inventoryEmptyRevalidationSignature(
- sources: readonly Pick<
- DeviceInventorySourceState<readonly unknown[]>,
- "error" | "key" | "ready"
- >[],
-): string {
- return sources
- .map((source) =>
- [
- source.key ?? "pending",
- source.ready ? "ready" : "pending",
- source.error ?? "",
- ].join("\u0001"),
- )
- .join("\u0002");
-}
-
export function useTokenScopedInventoryRequestOptions(
inventoryVersion: number,
hfToken?: string | null,
@@ -368,6 +382,43 @@ export function useDeviceInventorySources<
}
}, [sourceList, hfToken, tokenFingerprint, inventoryVersion]);
+ const refreshIfOlderThan = useCallback(
+ async (maxAgeMs: number) => {
+ const now = Date.now();
+ const requests = sourceList.flatMap((source) => {
+ const key = sourceRequestKey(
+ source,
+ inventoryVersion,
+ tokenFingerprint,
+ );
+ const current = useDeviceInventoryStore.getState()[source];
+ const decision = inventoryRefreshDecision(current, key, now, maxAgeMs);
+ if (decision === "reuse") return [];
+ return [
+ {
+ source,
+ request: fetchInventorySource(source, {
+ hfToken,
+ tokenFingerprint,
+ inventoryVersion,
+ force: decision === "refresh",
+ }),
+ },
+ ];
+ });
+ const results = await Promise.allSettled(
+ requests.map(({ request }) => request),
+ );
+ for (const [index, result] of results.entries()) {
+ if (result.status === "rejected") {
+ const source = requests[index]?.source;
+ if (source) logInventorySourceFailure(source, result.reason);
+ }
+ }
+ },
+ [sourceList, hfToken, tokenFingerprint, inventoryVersion],
+ );
+
useEffect(() => {
if (!enabled) {
return;
@@ -384,5 +435,6 @@ export function useDeviceInventorySources<
return {
...state,
refresh,
+ refreshIfOlderThan,
} as UseDeviceInventoryResult<Sources>;
}
diff --git a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
index 6f02657ca86..ca09b0f34cb 100644
--- a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
+++ b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts
@@ -7,7 +7,7 @@ import {
useDownloadManagerStore,
} from "@/features/hub/download-manager";
import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import type { LocalDatasetInfo } from "./api";
import {
dedupeSameSourceHubCacheRows,
@@ -29,7 +29,6 @@ import { resolveInventorySettlement } from "./inventory-settlement";
import type { CachedInventoryRow, LocalInventoryRow } from "./types";
import {
type DeviceInventorySource,
- inventoryEmptyRevalidationSignature,
useDeviceInventorySources,
} from "./use-device-inventory";
import {
@@ -38,6 +37,10 @@ import {
defaultCapabilities,
normalizeTimestamp,
} from "./view-models";
+import {
+ INVENTORY_FRESHNESS_WINDOW_MS,
+ isInventoryStampFresh,
+} from "./inventory-freshness";
export interface HubInventory {
cachedRows: CachedInventoryRow[];
@@ -49,6 +52,7 @@ export interface HubInventory {
inventoryError: boolean;
inventoryWarning: boolean;
refreshInventory: () => Promise<void>;
+ refreshInventoryIfOlderThan: (maxAgeMs: number) => Promise<void>;
}
export type HubInventoryKind = "models" | "datasets";
@@ -263,6 +267,13 @@ export function useHubInventory(
const refreshDatasetInventory = datasetInventory.refresh;
const refreshLocalModelInventory = localModelInventory.refresh;
const refreshLocalDatasetInventory = localDatasetInventory.refresh;
+ const refreshModelInventoryIfOlderThan = modelInventory.refreshIfOlderThan;
+ const refreshDatasetInventoryIfOlderThan =
+ datasetInventory.refreshIfOlderThan;
+ const refreshLocalModelInventoryIfOlderThan =
+ localModelInventory.refreshIfOlderThan;
+ const refreshLocalDatasetInventoryIfOlderThan =
+ localDatasetInventory.refreshIfOlderThan;
const pendingHints = useInventoryHintStore((state) => state.pending);
const observedInventoryKeys = useInventoryHintStore(
(state) => state.observedKeys,
@@ -281,8 +292,6 @@ export function useHubInventory(
[isDatasetMode],
);
const liveInventoryJobs = useDownloadManagerStore(selectLiveInventoryJobs);
- const [lastEmptyRevalidationSignature, setLastEmptyRevalidationSignature] =
- useState<string | null>(null);
const pendingForRenderRef = useRef<PendingInventoryHints | null>(null);
const pendingForRenderNext = useMemo(
@@ -557,6 +566,33 @@ export function useHubInventory(
const refreshInventory = useCallback(async () => {
await refreshDeviceInventory();
}, [refreshDeviceInventory]);
+ const refreshInventoryIfOlderThan = useCallback(
+ async (maxAgeMs: number) => {
+ if (isDatasetMode) {
+ await Promise.all([
+ refreshDatasetInventoryIfOlderThan(maxAgeMs),
+ ...(includeLocal
+ ? [refreshLocalDatasetInventoryIfOlderThan(maxAgeMs)]
+ : []),
+ ]);
+ return;
+ }
+ await Promise.all([
+ refreshModelInventoryIfOlderThan(maxAgeMs),
+ ...(includeLocal
+ ? [refreshLocalModelInventoryIfOlderThan(maxAgeMs)]
+ : []),
+ ]);
+ },
+ [
+ includeLocal,
+ isDatasetMode,
+ refreshDatasetInventoryIfOlderThan,
+ refreshLocalDatasetInventoryIfOlderThan,
+ refreshLocalModelInventoryIfOlderThan,
+ refreshModelInventoryIfOlderThan,
+ ],
+ );
const downloadedReady = isDatasetMode ? datasetReady : modelReady;
const hasInventoryRows =
cachedRows.length > 0 || effectiveLocalRows.length > 0;
@@ -566,37 +602,31 @@ export function useHubInventory(
: cachedGgufSource.loading ||
cachedModelsSource.loading ||
(includeLocal && localModelsSource.loading);
- const emptyRevalidationSignature = useMemo(
- () =>
- isDatasetMode
- ? inventoryEmptyRevalidationSignature([
- cachedDatasetsSource,
- ...(includeLocal ? [localDatasetsSource] : []),
- ])
- : inventoryEmptyRevalidationSignature([
- cachedGgufSource,
- cachedModelsSource,
- ...(includeLocal ? [localModelsSource] : []),
- ]),
- [
- cachedDatasetsSource,
- cachedGgufSource,
- cachedModelsSource,
- includeLocal,
- isDatasetMode,
- localDatasetsSource,
- localModelsSource,
- ],
+ const relevantInventorySources = isDatasetMode
+ ? [cachedDatasetsSource, ...(includeLocal ? [localDatasetsSource] : [])]
+ : [
+ cachedGgufSource,
+ cachedModelsSource,
+ ...(includeLocal ? [localModelsSource] : []),
+ ];
+ const now = Date.now();
+ const emptyRevalidationFresh = relevantInventorySources.every(
+ (source) =>
+ source.error === null &&
+ isInventoryStampFresh(
+ source.revalidatedAt,
+ now,
+ INVENTORY_FRESHNESS_WINDOW_MS,
+ ),
);
const { emptyRevalidationRequired, inventorySettled } =
resolveInventorySettlement({
downloadedReady,
- emptyRevalidationSignature,
+ emptyRevalidationFresh,
hasActiveEmptyRefresh,
hasInventoryRows,
hasUnreadyInventoryFailure,
inventoryFailed,
- lastEmptyRevalidationSignature,
});
useEffect(() => {
@@ -604,13 +634,11 @@ export function useHubInventory(
return;
}
const timer = window.setTimeout(() => {
- setLastEmptyRevalidationSignature(emptyRevalidationSignature);
void refreshDeviceInventory();
}, 500);
return () => window.clearTimeout(timer);
}, [
emptyRevalidationRequired,
- emptyRevalidationSignature,
enabled,
refreshDeviceInventory,
]);
@@ -625,5 +653,6 @@ export function useHubInventory(
inventoryError: inventoryFailed,
inventoryWarning,
refreshInventory,
+ refreshInventoryIfOlderThan,
};
}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index bead2773443..4aee383cfc9 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -12,6 +12,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { usePlatformStore } from "@/config/env";
+import { INVENTORY_FRESHNESS_WINDOW_MS } from "@/features/hub/inventory";
import { ApiProviderLogo } from "@/features/chat";
import {
type ScanFolderInfo,
@@ -2326,8 +2327,13 @@ export function HubModelPicker({
}, []);
const pickerInventory = useChatPickerInventory({ enabled: true });
- const { cachedGguf, cachedModels, cachedReady, refreshInventory } =
- pickerInventory;
+ const {
+ cachedGguf,
+ cachedModels,
+ cachedReady,
+ refreshInventory,
+ refreshInventoryIfOlderThan,
+ } = pickerInventory;
const cachedReadyAtMount = useRef(cachedReady);
const lmStudioModels = useMemo(
() =>
@@ -2519,8 +2525,8 @@ export function HubModelPicker({
if (!shouldRefreshPickerInventoryOnMount(cachedReadyAtMount.current)) {
return;
}
- void refreshInventory();
- }, [refreshInventory]);
+ void refreshInventoryIfOlderThan(INVENTORY_FRESHNESS_WINDOW_MS);
+ }, [refreshInventoryIfOlderThan]);
// Hide downloaded models from the recommended list. Case-insensitive
// since the HF cache lowercases repo IDs.
diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
index 4d37f3d8e8d..96c9556d243 100644
--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
@@ -73,6 +73,7 @@ export interface ChatPickerInventory {
cachedReady: boolean;
localModels: LocalModelInfo[];
refreshInventory: () => Promise<void>;
+ refreshInventoryIfOlderThan: (maxAgeMs: number) => Promise<void>;
}
export function useChatPickerInventory(
@@ -134,5 +135,6 @@ export function useChatPickerInventory(
cachedReady: inventory.downloadedReady,
localModels,
refreshInventory: inventory.refreshInventory,
+ refreshInventoryIfOlderThan: inventory.refreshInventoryIfOlderThan,
};
}
diff --git a/studio/frontend/tests/chat-local-model-options.test.ts b/studio/frontend/tests/chat-local-model-options.test.ts
new file mode 100644
index 00000000000..f0c8b96c964
--- /dev/null
+++ b/studio/frontend/tests/chat-local-model-options.test.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Chat reads local models from the shared device inventory rather than the compat
+// /api/models/local endpoint. The two disagree in ways that silently drop models, so the
+// mapping is pinned here against what each endpoint actually returns.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { chatLocalModelOptions } = await import(
+ "../src/features/chat/local-model-options.ts"
+);
+
+function row(over: Record<string, unknown> = {}) {
+ return {
+ id: "/models/demo",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ display_name: "demo",
+ path: "/models/demo",
+ source: "models_dir",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ updated_at: 1,
+ ...over,
+ } as never;
+}
+
+test("Ollama rows are withheld until their refs are loadable", () => {
+ // /api/hub/local scans read-only and returns an opaque `ollama-manifest:` id that only
+ // materialize_ollama_model_ref can turn into a .gguf path, and nothing calls that yet.
+ // The picker withholds these rows for the same reason (PICKER_LOCAL_SOURCES), so Chat
+ // matches it: an entry that fails on click is worse than one that is not offered.
+ assert.deepEqual(
+ chatLocalModelOptions([
+ row({
+ id: "ollama-manifest:%2Fhome%2Fu%2F.ollama%2Fmanifests%2Fllama3",
+ display_name: "llama3",
+ source: "ollama",
+ }),
+ ]),
+ [],
+ );
+});
+
+test("a directory with two weight formats yields one option per load id", () => {
+ // The shared inventory keys a row on (format, path), so this arrives as two rows with the
+ // same `id`. The selector keys on `id`, so both would share a React key and read as
+ // selected together.
+ const options = chatLocalModelOptions([
+ row({ model_format: "gguf", inventory_id: "models_dir:gguf:/models/demo" }),
+ row({
+ model_format: "safetensors",
+ inventory_id: "models_dir:safetensors:/models/demo",
+ }),
+ ]);
+ assert.equal(options.length, 1);
+ assert.equal(options[0]?.id, "/models/demo");
+});
+
+test("hf_cache rows stay out of the local list", () => {
+ assert.deepEqual(chatLocalModelOptions([row({ source: "hf_cache" })]), []);
+});
+
+test("LM Studio rows prefer the model id and keep their label", () => {
+ const options = chatLocalModelOptions([
+ row({
+ id: "/lm/x",
+ source: "lmstudio",
+ model_id: "publisher/model",
+ display_name: "x",
+ }),
+ ]);
+ assert.equal(options[0]?.name, "publisher/model");
+ assert.equal(options[0]?.baseModel, "LM Studio");
+});
+
+test("custom and models_dir rows keep the labels the picker groups on", () => {
+ const options = chatLocalModelOptions([
+ row({ id: "/a", source: "custom" }),
+ row({ id: "/b", source: "models_dir" }),
+ ]);
+ assert.deepEqual(
+ options.map((o) => o.baseModel),
+ ["Custom Folders", "Local models"],
+ );
+});
diff --git a/studio/frontend/tests/inventory-freshness.test.ts b/studio/frontend/tests/inventory-freshness.test.ts
new file mode 100644
index 00000000000..c999a0f6bfb
--- /dev/null
+++ b/studio/frontend/tests/inventory-freshness.test.ts
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ inventoryRefreshDecision,
+ nextRevalidationStamp,
+ isInventoryStampFresh,
+} from "../src/features/hub/inventory/inventory-freshness.ts";
+
+const NOW = 100_000;
+const KEY = "localModels:7:local";
+
+test("fresh inventory is reused across rapid picker opens", () => {
+ assert.equal(
+ inventoryRefreshDecision(
+ {
+ ready: true,
+ loading: false,
+ error: null,
+ key: KEY,
+ refreshedAt: NOW - 1_000,
+ },
+ KEY,
+ NOW,
+ 30_000,
+ ),
+ "reuse",
+ );
+});
+
+test("an in-flight inventory request is joined without queuing another scan", () => {
+ assert.equal(
+ inventoryRefreshDecision(
+ {
+ ready: false,
+ loading: true,
+ error: null,
+ key: KEY,
+ refreshedAt: null,
+ },
+ KEY,
+ NOW,
+ 30_000,
+ ),
+ "join",
+ );
+});
+
+test("expired inventory is refreshed", () => {
+ assert.equal(
+ inventoryRefreshDecision(
+ {
+ ready: true,
+ loading: false,
+ error: null,
+ key: KEY,
+ refreshedAt: NOW - 30_000,
+ },
+ KEY,
+ NOW,
+ 30_000,
+ ),
+ "refresh",
+ );
+});
+
+test("an invalidated inventory key is fetched without a forced follow-up", () => {
+ assert.equal(
+ inventoryRefreshDecision(
+ {
+ ready: true,
+ loading: false,
+ error: null,
+ key: "localModels:6:local",
+ refreshedAt: NOW,
+ },
+ KEY,
+ NOW,
+ 30_000,
+ ),
+ "join",
+ );
+});
+
+test("a failed current key is refreshed even while its prior rows are fresh", () => {
+ assert.equal(
+ inventoryRefreshDecision(
+ {
+ ready: true,
+ loading: false,
+ error: "scan failed",
+ key: KEY,
+ refreshedAt: NOW - 1_000,
+ },
+ KEY,
+ NOW,
+ 30_000,
+ ),
+ "refresh",
+ );
+});
+
+test("a stamp from the future is refreshed, not reused", () => {
+ // `Date.now()` follows the system clock, so a stamp can end up in the future after an
+ // NTP correction, a VM resume or a user editing the clock. A negative age must not read
+ // as "younger than the window", or the picker stops scanning for the length of the skew.
+ assert.equal(
+ inventoryRefreshDecision(
+ {
+ ready: true,
+ loading: false,
+ error: null,
+ key: KEY,
+ refreshedAt: NOW + 3_600_000,
+ },
+ KEY,
+ NOW,
+ 30_000,
+ ),
+ "refresh",
+ );
+});
+
+test("a zero max age always refreshes, even after the clock steps backwards", () => {
+ // refreshIfOlderThan(0) means "refresh unconditionally"; a future stamp must not turn it
+ // into a no-op.
+ for (const refreshedAt of [NOW - 1, NOW, NOW + 60_000]) {
+ assert.equal(
+ inventoryRefreshDecision(
+ { ready: true, loading: false, error: null, key: KEY, refreshedAt },
+ KEY,
+ NOW,
+ 0,
+ ),
+ "refresh",
+ );
+ }
+});
+
+test("isInventoryStampFresh rejects a null, an expired and a future stamp", () => {
+ assert.equal(isInventoryStampFresh(null, NOW, 30_000), false);
+ assert.equal(isInventoryStampFresh(NOW - 30_000, NOW, 30_000), false);
+ assert.equal(isInventoryStampFresh(NOW + 1, NOW, 30_000), false);
+ assert.equal(isInventoryStampFresh(NOW - 29_999, NOW, 30_000), true);
+ assert.equal(isInventoryStampFresh(NOW, NOW, 30_000), true);
+});
+
+test("the revalidation stamp tracks both ends of a confirmed empty inventory", () => {
+ const emptyPrev = {
+ key: KEY,
+ ready: true,
+ error: null,
+ rowCount: 0,
+ revalidatedAt: null as number | null,
+ };
+ const call = (over: Record<string, unknown>) =>
+ nextRevalidationStamp({
+ force: true,
+ requestKey: KEY,
+ previous: emptyPrev,
+ rowCount: 0,
+ now: NOW,
+ ...over,
+ });
+
+ // A forced second look at an inventory already seen empty is the confirmation.
+ assert.equal(call({}), NOW);
+
+ // Rows came back, so the inventory is not empty: the stamp must be cleared, or a later
+ // FIRST empty scan inside the window reads as already confirmed and the picker settles
+ // on "no models" after one look.
+ assert.equal(call({ rowCount: 3 }), null);
+ assert.equal(
+ call({ rowCount: 3, previous: { ...emptyPrev, revalidatedAt: NOW - 1_000 } }),
+ null,
+ );
+
+ // First empty scan after a populated one is an observation, not a confirmation.
+ assert.equal(
+ call({ previous: { ...emptyPrev, rowCount: 4, revalidatedAt: null } }),
+ null,
+ );
+ // Not forced, unready or previously failed: carry, never stamp.
+ assert.equal(call({ force: false }), null);
+ assert.equal(call({ previous: { ...emptyPrev, ready: false } }), null);
+ assert.equal(call({ previous: { ...emptyPrev, error: "scan failed" } }), null);
+ // A key change drops the previous confirmation.
+ assert.equal(
+ call({ previous: { ...emptyPrev, key: "other", revalidatedAt: NOW - 10 } }),
+ null,
+ );
+ // Same key, nothing decisive: carry what was there.
+ assert.equal(
+ call({ force: false, previous: { ...emptyPrev, revalidatedAt: NOW - 500 } }),
+ NOW - 500,
+ );
+});
diff --git a/studio/frontend/tests/inventory-settlement.test.ts b/studio/frontend/tests/inventory-settlement.test.ts
index 863000759a7..b03c34e346d 100644
--- a/studio/frontend/tests/inventory-settlement.test.ts
+++ b/studio/frontend/tests/inventory-settlement.test.ts
@@ -7,7 +7,7 @@ import { resolveInventorySettlement } from "../src/features/hub/inventory/invent
const emptyReadyInventory = {
downloadedReady: true,
- emptyRevalidationSignature: "empty-ready",
+ emptyRevalidationFresh: false,
hasActiveEmptyRefresh: false,
hasInventoryRows: false,
hasUnreadyInventoryFailure: false,
@@ -18,7 +18,6 @@ test("keeps an empty ready inventory unsettled until revalidation", () => {
assert.deepEqual(
resolveInventorySettlement({
...emptyReadyInventory,
- lastEmptyRevalidationSignature: null,
}),
{
emptyRevalidationRequired: true,
@@ -28,7 +27,7 @@ test("keeps an empty ready inventory unsettled until revalidation", () => {
assert.deepEqual(
resolveInventorySettlement({
...emptyReadyInventory,
- lastEmptyRevalidationSignature: "empty-ready",
+ emptyRevalidationFresh: true,
}),
{
emptyRevalidationRequired: false,
@@ -46,7 +45,6 @@ test("settles usable rows and failures with prior ready state", () => {
resolveInventorySettlement({
...emptyReadyInventory,
...state,
- lastEmptyRevalidationSignature: null,
}),
{
emptyRevalidationRequired: false,
@@ -62,7 +60,6 @@ test("keeps an unready failure unsettled for the next enable retry", () => {
...emptyReadyInventory,
hasUnreadyInventoryFailure: true,
inventoryFailed: true,
- lastEmptyRevalidationSignature: null,
}),
{
emptyRevalidationRequired: false,
@@ -78,7 +75,6 @@ test("settles a partial failure when another source returned rows", () => {
hasInventoryRows: true,
hasUnreadyInventoryFailure: true,
inventoryFailed: true,
- lastEmptyRevalidationSignature: null,
}),
{
emptyRevalidationRequired: false,