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: remember last used model in the backend, not per-browser (#8587)

Nilay8696c5fb3cd9
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index d19374fdb59..abab19c189f 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -2,8 +2,10 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import functools
+import hashlib
import re
import threading
+import time
from typing import Any, Literal, Optional, get_args
from urllib.parse import unquote, urlsplit
@@ -666,6 +668,9 @@ _MAX_VARIANT_SUFFIX_LEN = 64
# A limit under PATH_MAX would 422 the server sync while the local save succeeded.
MAX_MODEL_OVERRIDE_KEY_LEN = 4096 + 1 + _MAX_VARIANT_SUFFIX_LEN
+# GgufVariantDetail.quant may be a path-qualified variant key, not just a quant suffix.
+MAX_GGUF_VARIANT_KEY_LEN = 4096
+
# A list longer than MAX_GPU_ID cannot name a device the normalizer would store, so bound it
# here and reject an oversized array at the boundary instead of walking it.
MAX_GPU_IDS = MAX_GPU_ID + 1
@@ -991,6 +996,109 @@ def update_model_memory(
return _model_memory_response()
+LAST_LOCAL_MODEL_SETTING_KEY = "last_local_model_load"
+_LAST_LOCAL_MODEL_LOCK = threading.Lock()
+
+
+def _last_local_model_key(subject: str) -> str:
+ """Per-subject key: one shared row would hand user B user A's last model."""
+ subject = (subject or "").strip()
+ if not subject:
+ return LAST_LOCAL_MODEL_SETTING_KEY
+ # Hashed so an arbitrary subject cannot collide with another key.
+ digest = hashlib.sha256(subject.encode("utf-8")).hexdigest()[:32]
+ return f"{LAST_LOCAL_MODEL_SETTING_KEY}:{digest}"
+
+
+def _read_last_local_model(subject: str) -> "dict | None":
+ """The subject's record, falling back to the pre-scoping shared row so an
+ upgrade keeps the model the install already remembered."""
+ from storage.studio_db import get_app_setting
+
+ stored = get_app_setting(_last_local_model_key(subject), None)
+ if not isinstance(stored, dict):
+ stored = get_app_setting(LAST_LOCAL_MODEL_SETTING_KEY, None)
+ return stored if isinstance(stored, dict) else None
+
+
+# Clients stamp loads, so cap how far ahead of server time a client clock may claim.
+_LAST_LOCAL_MODEL_CLOCK_SLACK_MS = 5 * 60 * 1000
+
+
+class LastLocalModelPayload(BaseModel):
+ id: str = Field(..., min_length = 1, max_length = MAX_MODEL_OVERRIDE_KEY_LEN)
+ kind: Literal["gguf", "model"]
+ gguf_variant: Optional[str] = Field(default = None, max_length = MAX_GGUF_VARIANT_KEY_LEN)
+ # Epoch ms of the load; orders writes from surfaces that keep their own local shadow.
+ loaded_at: Optional[int] = Field(default = None, ge = 0)
+ # The client clock when the request was sent: the skew (server_now - client_now)
+ # translates loaded_at into the server frame. Never persisted.
+ client_now: Optional[int] = Field(default = None, ge = 0)
+
+
+class LastLocalModelResponse(BaseModel):
+ id: Optional[str] = None
+ kind: Optional[Literal["gguf", "model"]] = None
+ gguf_variant: Optional[str] = None
+ loaded_at: Optional[int] = None
+ # Lets the client translate loaded_at back into its own clock frame.
+ server_now: Optional[int] = None
+
+
[email protected]("/last-local-model", response_model = LastLocalModelResponse)
+def get_last_local_model(
+ current_subject: str = Depends(get_current_subject),
+) -> LastLocalModelResponse:
+ stored = _read_last_local_model(current_subject)
+ _now = int(time.time() * 1000)
+ if stored is None:
+ return LastLocalModelResponse(server_now = _now)
+ try:
+ payload = LastLocalModelPayload(**stored)
+ except Exception:
+ return LastLocalModelResponse(server_now = _now)
+ return LastLocalModelResponse(**payload.model_dump(exclude = {"client_now"}), server_now = _now)
+
+
[email protected]("/last-local-model", response_model = LastLocalModelResponse)
+def update_last_local_model(
+ payload: LastLocalModelPayload, current_subject: str = Depends(get_current_subject)
+) -> LastLocalModelResponse:
+ from storage.studio_db import upsert_app_settings
+
+ # loaded_at orders stamped writes so a delayed older PUT cannot overwrite a newer
+ # load; the stored record is returned. Unstamped writes stay last-write-wins.
+ _server_now = int(time.time() * 1000)
+ _key = _last_local_model_key(current_subject)
+ with _LAST_LOCAL_MODEL_LOCK:
+ if payload.loaded_at is not None:
+ if payload.client_now is not None:
+ # Into the server frame: fresh loads land near now, re-issued shadows stay old.
+ _shifted = payload.loaded_at + (_server_now - payload.client_now)
+ payload = payload.model_copy(update = {"loaded_at": max(0, _shifted)})
+ _cap = _server_now + _LAST_LOCAL_MODEL_CLOCK_SLACK_MS
+ if payload.loaded_at > _cap:
+ payload = payload.model_copy(update = {"loaded_at": _cap})
+ stored = _read_last_local_model(current_subject)
+ if stored is not None:
+ try:
+ current = LastLocalModelPayload(**stored)
+ except Exception:
+ current = None
+ if (
+ current is not None
+ and current.loaded_at is not None
+ and payload.loaded_at < current.loaded_at
+ ):
+ return LastLocalModelResponse(
+ **current.model_dump(exclude = {"client_now"}), server_now = _server_now
+ )
+ upsert_app_settings({_key: payload.model_dump(exclude = {"client_now"})})
+ return LastLocalModelResponse(
+ **payload.model_dump(exclude = {"client_now"}), server_now = _server_now
+ )
+
+
@router.get("/vram-budget", response_model = VramBudgetResponse)
def get_vram_budget(current_subject: str = Depends(get_current_subject)) -> VramBudgetResponse:
return _vram_budget_response()
diff --git a/studio/backend/tests/test_last_local_model_setting.py b/studio/backend/tests/test_last_local_model_setting.py
new file mode 100644
index 00000000000..a1cb2a58cbe
--- /dev/null
+++ b/studio/backend/tests/test_last_local_model_setting.py
@@ -0,0 +1,295 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Route-level tests for the last-local-model setting endpoints."""
+
+from pathlib import Path
+import time
+import sys
+import types as _types
+
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
+sys.modules.setdefault("loggers", _loggers_stub)
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import routes.settings as settings
+import storage.studio_db as studio_db
+
+
+def client(monkeypatch):
+ store: dict = {}
+
+ monkeypatch.setattr(
+ studio_db, "get_app_setting", lambda key, fallback = None: store.get(key, fallback)
+ )
+ monkeypatch.setattr(
+ studio_db, "upsert_app_settings", lambda values: store.update(values) or store
+ )
+
+ app = FastAPI()
+ app.include_router(settings.router)
+ app.dependency_overrides[settings.get_current_subject] = lambda: "admin"
+ return TestClient(app, raise_server_exceptions = False), store
+
+
+def test_get_with_nothing_stored(client):
+ c, _ = client
+ r = c.get("/last-local-model")
+ assert r.status_code == 200
+ body = r.json()
+ assert isinstance(body.pop("server_now"), int)
+ assert body == {"id": None, "kind": None, "gguf_variant": None, "loaded_at": None}
+
+
+def test_put_then_get_round_trips(client):
+ c, store = client
+ payload = {"id": "unsloth/gemma-4-E2B-it-GGUF", "kind": "gguf", "gguf_variant": "UD-Q4_K_XL"}
+ r = c.put("/last-local-model", json = payload)
+ assert r.status_code == 200
+ body = r.json()
+ body.pop("server_now")
+ assert body == {**payload, "loaded_at": None}
+ assert store[settings._last_local_model_key("admin")] == {**payload, "loaded_at": None}
+
+ r = c.get("/last-local-model")
+ assert r.status_code == 200
+ body = r.json()
+ body.pop("server_now")
+ assert body == {**payload, "loaded_at": None}
+
+
+def test_put_accepts_path_qualified_variant(client):
+ c, _ = client
+ variant = "quants/" + "a" * 80 + "/model-UD-Q4_K_XL-00001-of-00002.gguf"
+ payload = {"id": "unsloth/gemma-4-E2B-it-GGUF", "kind": "gguf", "gguf_variant": variant}
+ r = c.put("/last-local-model", json = payload)
+ assert r.status_code == 200
+ assert r.json()["gguf_variant"] == variant
+
+
+def test_put_round_trips_loaded_at(client):
+ c, _ = client
+ payload = {"id": "unsloth/Qwen3-4B", "kind": "model", "loaded_at": 1765432100000}
+ r = c.put("/last-local-model", json = payload)
+ assert r.status_code == 200
+ assert r.json()["loaded_at"] == 1765432100000
+ assert c.get("/last-local-model").json()["loaded_at"] == 1765432100000
+
+
+def test_put_without_variant(client):
+ c, _ = client
+ r = c.put("/last-local-model", json = {"id": "unsloth/Qwen3-4B", "kind": "model"})
+ assert r.status_code == 200
+ body = r.json()
+ body.pop("server_now")
+ assert body == {
+ "id": "unsloth/Qwen3-4B",
+ "kind": "model",
+ "gguf_variant": None,
+ "loaded_at": None,
+ }
+
+
+def test_put_ignores_stale_timestamped_write(client):
+ c, _ = client
+ newer = {"id": "unsloth/Qwen3-4B", "kind": "model", "loaded_at": 2000}
+ stale = {
+ "id": "unsloth/gemma-4-E2B-it-GGUF",
+ "kind": "gguf",
+ "gguf_variant": "UD-Q4_K_XL",
+ "loaded_at": 1000,
+ }
+ assert c.put("/last-local-model", json = newer).status_code == 200
+ r = c.put("/last-local-model", json = stale)
+ assert r.status_code == 200
+ assert r.json()["id"] == "unsloth/Qwen3-4B"
+ assert c.get("/last-local-model").json()["loaded_at"] == 2000
+
+
+def test_put_unstamped_write_keeps_last_write_wins(client):
+ c, _ = client
+ stamped = {"id": "unsloth/Qwen3-4B", "kind": "model", "loaded_at": 2000}
+ assert c.put("/last-local-model", json = stamped).status_code == 200
+ assert (
+ c.put("/last-local-model", json = {"id": "unsloth/OLMo-4-13B", "kind": "model"}).status_code
+ == 200
+ )
+ assert c.get("/last-local-model").json()["id"] == "unsloth/OLMo-4-13B"
+
+
+def test_put_clamps_future_dated_stamps(client):
+ c, _ = client
+ import time as _time
+
+ r = c.put(
+ "/last-local-model",
+ json = {"id": "unsloth/Qwen3-4B", "kind": "model", "loaded_at": 9_999_999_999_999},
+ )
+ assert r.status_code == 200
+ cap = int(_time.time() * 1000) + settings._LAST_LOCAL_MODEL_CLOCK_SLACK_MS
+ assert r.json()["loaded_at"] <= cap
+
+
+def test_put_normalizes_slow_client_clocks(client):
+ c, store = client
+ import time as _time
+
+ now = int(_time.time() * 1000)
+ assert (
+ c.put(
+ "/last-local-model",
+ json = {"id": "unsloth/Qwen3-4B", "kind": "model", "loaded_at": now, "client_now": now},
+ ).status_code
+ == 200
+ )
+ # a clock hours behind: a genuinely later load still lands after the stored one
+ slow_now = now - 7_200_000
+ r = c.put(
+ "/last-local-model",
+ json = {
+ "id": "unsloth/OLMo-4-13B",
+ "kind": "model",
+ "loaded_at": slow_now + 60_000,
+ "client_now": slow_now,
+ },
+ )
+ assert r.status_code == 200
+ assert c.get("/last-local-model").json()["id"] == "unsloth/OLMo-4-13B"
+ assert "client_now" not in store[settings._last_local_model_key("admin")]
+
+
+def test_put_rejects_bad_payloads(client):
+ c, _ = client
+ assert c.put("/last-local-model", json = {"id": "x", "kind": "lora"}).status_code == 422
+ assert c.put("/last-local-model", json = {"id": "", "kind": "gguf"}).status_code == 422
+ assert c.put("/last-local-model", json = {"kind": "gguf"}).status_code == 422
+
+
+def test_get_tolerates_corrupt_stored_value(client):
+ c, store = client
+ store[settings.LAST_LOCAL_MODEL_SETTING_KEY] = {"id": "x", "kind": "lora"}
+ r = c.get("/last-local-model")
+ assert r.status_code == 200
+ body = r.json()
+ body.pop("server_now")
+ assert body == {"id": None, "kind": None, "gguf_variant": None, "loaded_at": None}
+
+ store[settings.LAST_LOCAL_MODEL_SETTING_KEY] = "not-a-dict"
+ r = c.get("/last-local-model")
+ assert r.status_code == 200
+ body = r.json()
+ body.pop("server_now")
+ assert body == {"id": None, "kind": None, "gguf_variant": None, "loaded_at": None}
+
+
+# ── per-subject scoping ─────────────────────────────────────────────
+
+
+def multi_subject_client(monkeypatch):
+ """One backend and one store, with a swappable authenticated subject."""
+ store: dict = {}
+ subject = {"value": "alice"}
+
+ monkeypatch.setattr(
+ studio_db, "get_app_setting", lambda key, fallback = None: store.get(key, fallback)
+ )
+ monkeypatch.setattr(
+ studio_db, "upsert_app_settings", lambda values: store.update(values) or store
+ )
+ app = FastAPI()
+ app.include_router(settings.router)
+ app.dependency_overrides[settings.get_current_subject] = lambda: subject["value"]
+ return TestClient(app, raise_server_exceptions = False), store, subject
+
+
+def test_one_subject_does_not_inherit_anothers_model(multi_subject_client):
+ c, _, subject = multi_subject_client
+ subject["value"] = "alice"
+ c.put("/last-local-model", json = {"id": "alice/model", "kind": "model"})
+
+ subject["value"] = "bob"
+ assert c.get("/last-local-model").json()["id"] is None
+
+ c.put("/last-local-model", json = {"id": "bob/model", "kind": "model"})
+ assert c.get("/last-local-model").json()["id"] == "bob/model"
+
+ subject["value"] = "alice"
+ assert c.get("/last-local-model").json()["id"] == "alice/model"
+
+
+def test_an_upgraded_install_still_sees_the_shared_row(multi_subject_client):
+ """Pre-scoping installs stored one shared record; a subject with no row of
+ its own inherits it rather than booting with nothing remembered."""
+ c, store, subject = multi_subject_client
+ store[settings.LAST_LOCAL_MODEL_SETTING_KEY] = {
+ "id": "unsloth/gemma-4-E2B-it-GGUF",
+ "kind": "gguf",
+ "gguf_variant": "UD-Q4_K_XL",
+ "loaded_at": 1000,
+ }
+ subject["value"] = "alice"
+ assert c.get("/last-local-model").json()["id"] == "unsloth/gemma-4-E2B-it-GGUF"
+
+ # Once the subject writes it owns its row and stops following the shared one.
+ c.put("/last-local-model", json = {"id": "alice/model", "kind": "model", "loaded_at": 2000})
+ assert c.get("/last-local-model").json()["id"] == "alice/model"
+ assert store[settings.LAST_LOCAL_MODEL_SETTING_KEY]["id"] == "unsloth/gemma-4-E2B-it-GGUF"
+
+
+def test_subject_keys_do_not_collide(multi_subject_client):
+ _, _, _ = multi_subject_client
+ keys = {settings._last_local_model_key(s) for s in ("a", "b", "a:b", "", " ")}
+ # "" and " " degrade to the shared key; the rest are distinct.
+ assert len(keys) == 4
+ assert settings._last_local_model_key("") == settings.LAST_LOCAL_MODEL_SETTING_KEY
+
+
+def test_a_delayed_put_is_dated_from_arrival_not_from_the_load(client):
+ """Known limitation, pinned so any change is deliberate. client_now is
+ stamped at send, so flight time is indistinguishable from clock skew: a
+ retry-delayed PUT lands near arrival and can outrank a newer load."""
+ c, store = client
+ now = int(time.time() * 1000)
+
+ # The newer load reaches the server first.
+ c.put(
+ "/last-local-model",
+ json = {"id": "newer", "kind": "model", "loaded_at": now, "client_now": now},
+ )
+ assert c.get("/last-local-model").json()["id"] == "newer"
+
+ # An older load whose PUT sat in a retry for 30s: the shift re-dates it to now.
+ old = now - 30_000
+ c.put(
+ "/last-local-model",
+ json = {"id": "older", "kind": "model", "loaded_at": old, "client_now": old},
+ )
+ assert c.get("/last-local-model").json()["id"] == "older"
+
+
+def test_a_re_issued_old_shadow_stays_old(client):
+ """The other half of the same shift: a shadow re-sent long after its load
+ keeps its age, so it cannot displace a newer record."""
+ c, _ = client
+ now = int(time.time() * 1000)
+ c.put(
+ "/last-local-model",
+ json = {"id": "newer", "kind": "model", "loaded_at": now, "client_now": now},
+ )
+ # Loaded 30s ago, re-issued now: age is preserved, so it loses.
+ c.put(
+ "/last-local-model",
+ json = {"id": "stale", "kind": "model", "loaded_at": now - 30_000, "client_now": now},
+ )
+ assert c.get("/last-local-model").json()["id"] == "newer"
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 460fac0da77..a6c4ab8598e 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -2576,7 +2576,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const hfToken = store.hfToken || null;
const trustRemoteCode = store.params.trustRemoteCode ?? false;
const specSettings = resolveSpeculativeSettingsForLoad();
- const lastLoaded = readLastLocalModelLoad();
+ const lastLoaded = await readLastLocalModelLoad(options?.abortSignal);
let autoLoadToastDismissed = false;
const toastId = toast.message("Loading a model…", {
description: lastLoaded
diff --git a/studio/frontend/src/features/chat/utils/last-local-model-load.ts b/studio/frontend/src/features/chat/utils/last-local-model-load.ts
index 2b1e4a8ea7b..29d90378d39 100644
--- a/studio/frontend/src/features/chat/utils/last-local-model-load.ts
+++ b/studio/frontend/src/features/chat/utils/last-local-model-load.ts
@@ -1,6 +1,8 @@
// 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 { authFetch } from "@/features/auth";
+
export type LastLocalModelKind = "gguf" | "model";
const PATH_LIKE_ID_RE = /^(?:[/~]|[A-Za-z]:[\\/]|\\\\)/;
@@ -14,82 +16,241 @@ export type LastLocalModelLoad = {
id: string;
kind: LastLocalModelKind;
ggufVariant: string | null;
- loadedAt: number;
};
-const STORAGE_KEY = "unsloth.last-local-model-load.v1";
+const API_PATH = "/api/settings/last-local-model";
+// Pre-backend installs kept the record here; still read so an upgrade does not
+// forget the model.
+const LEGACY_STORAGE_KEY = "unsloth.last-local-model-load.v1";
-function storage(): Storage | null {
- try {
- return typeof localStorage === "undefined" ? null : localStorage;
- } catch {
+function isLastLocalModelKind(value: unknown): value is LastLocalModelKind {
+ return value === "gguf" || value === "model";
+}
+
+function toRecord(input: {
+ id?: unknown;
+ kind?: unknown;
+ ggufVariant?: unknown;
+}): LastLocalModelLoad | null {
+ if (typeof input.id !== "string" || !isLastLocalModelKind(input.kind)) {
+ return null;
+ }
+ const id = input.id.trim();
+ const ggufVariant =
+ typeof input.ggufVariant === "string"
+ ? input.ggufVariant.trim() || null
+ : null;
+ if (!id) {
return null;
}
+ // A quant-less cached repo names no file; a local .gguf path is the file.
+ if (input.kind === "gguf" && !ggufVariant && !isPathLikeId(id)) {
+ return null;
+ }
+ return { id, kind: input.kind, ggufVariant };
}
-function isLastLocalModelKind(value: unknown): value is LastLocalModelKind {
- return value === "gguf" || value === "model";
+function sameRecord(a: LastLocalModelLoad, b: LastLocalModelLoad): boolean {
+ return a.id === b.id && a.kind === b.kind && a.ggufVariant === b.ggufVariant;
}
-export function readLastLocalModelLoad(): LastLocalModelLoad | null {
+function writeLegacyRecord(
+ record: LastLocalModelLoad,
+ pendingSync: boolean,
+ loadedAt: number,
+): void {
try {
- const raw = storage()?.getItem(STORAGE_KEY);
+ localStorage.setItem(
+ LEGACY_STORAGE_KEY,
+ JSON.stringify({
+ id: record.id,
+ kind: record.kind,
+ ggufVariant: record.ggufVariant,
+ // Old bundles reject entries without a numeric loadedAt.
+ loadedAt,
+ // True until this record's PUT confirms; a pending shadow may be newer.
+ pendingSync,
+ }),
+ );
+ } catch {
+ // Storage unavailable (private mode, quota): best effort only.
+ }
+}
+
+type LegacyEntry = {
+ record: LastLocalModelLoad;
+ pendingSync: boolean;
+ loadedAt: number | null;
+};
+
+function readLegacyEntry(): LegacyEntry | null {
+ try {
+ const raw = localStorage.getItem(LEGACY_STORAGE_KEY);
if (!raw) {
return null;
}
- const parsed = JSON.parse(raw) as Partial<LastLocalModelLoad>;
- if (
- typeof parsed.id !== "string" ||
- !parsed.id.trim() ||
- !isLastLocalModelKind(parsed.kind) ||
- typeof parsed.loadedAt !== "number"
- ) {
- return null;
- }
- // A quant-less cached repo names no file; a local .gguf path is the file.
- if (
- parsed.kind === "gguf" &&
- !isPathLikeId(parsed.id) &&
- (typeof parsed.ggufVariant !== "string" || !parsed.ggufVariant.trim())
- ) {
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ const record = toRecord(parsed);
+ if (!record) {
return null;
}
return {
- id: parsed.id,
- kind: parsed.kind,
- ggufVariant:
- typeof parsed.ggufVariant === "string" ? parsed.ggufVariant : null,
- loadedAt: parsed.loadedAt,
+ record,
+ pendingSync: parsed.pendingSync === true,
+ loadedAt: typeof parsed.loadedAt === "number" ? parsed.loadedAt : null,
};
} catch {
return null;
}
}
+export async function readLastLocalModelLoad(
+ signal?: AbortSignal,
+): Promise<LastLocalModelLoad | null> {
+ try {
+ const res = await authFetch(API_PATH, { signal });
+ if (res.ok) {
+ const data = (await res.json()) as {
+ id?: unknown;
+ kind?: unknown;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ gguf_variant?: unknown;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ loaded_at?: unknown;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ server_now?: unknown;
+ };
+ const record = toRecord({
+ id: data.id,
+ kind: data.kind,
+ ggufVariant: data.gguf_variant,
+ });
+ if (record) {
+ const legacy = readLegacyEntry();
+ let backendLoadedAt =
+ typeof data.loaded_at === "number" ? data.loaded_at : null;
+ if (backendLoadedAt !== null && typeof data.server_now === "number") {
+ // Shadow stamps live in this clock's frame: compare like with like.
+ backendLoadedAt -= data.server_now - Date.now();
+ }
+ if (
+ legacy &&
+ legacy.loadedAt !== null &&
+ (backendLoadedAt === null
+ ? legacy.pendingSync
+ : legacy.loadedAt > backendLoadedAt)
+ ) {
+ // A local record the backend has not seen: a PUT dropped at teardown
+ // (pendingSync) or a pre-upgrade bundle's write. Re-sync it with its
+ // original stamp, even on an identity match, so the backend stamp
+ // advances past older dropped writes elsewhere. An unstamped backend
+ // record gives no order, so only a pending shadow may outrank it.
+ recordLastLocalModelLoad({
+ ...legacy.record,
+ loadedAt: legacy.loadedAt,
+ });
+ return legacy.record;
+ }
+ if (legacy?.pendingSync) {
+ // The backend record is at least as new: adopt it, clear the marker.
+ writeLegacyRecord(record, false, backendLoadedAt ?? Date.now());
+ }
+ return record;
+ }
+ }
+ } catch (err) {
+ // Name, not instanceof: the retry wrapper surfaces aborts as a plain Error.
+ if ((err as { name?: string } | null)?.name === "AbortError") {
+ throw err;
+ }
+ // Unreachable settings API: fall back to the legacy record.
+ }
+ return readLegacyEntry()?.record ?? null;
+}
+
export function recordLastLocalModelLoad(input: {
id: string;
kind: LastLocalModelKind;
ggufVariant?: string | null;
+ // Reconcile re-issues keep the original load time; fresh loads stamp now.
+ loadedAt?: number;
}): void {
- const id = input.id.trim();
- if (!id) {
- return;
- }
- const ggufVariant = input.ggufVariant?.trim() || null;
- if (input.kind === "gguf" && !ggufVariant && !isPathLikeId(id)) {
+ const record = toRecord(input);
+ if (!record) {
return;
}
- try {
- storage()?.setItem(
- STORAGE_KEY,
- JSON.stringify({
- id,
- kind: input.kind,
- ggufVariant: input.kind === "gguf" ? ggufVariant : null,
- loadedAt: Date.now(),
- } satisfies LastLocalModelLoad),
- );
- } catch {
- // Ignore disabled storage / quota errors; auto-load falls back to size order.
- }
+ const loadedAt =
+ typeof input.loadedAt === "number" ? input.loadedAt : Date.now();
+ // Shadow write first, synchronously: a fetch pending at teardown is dropped
+ // without running either callback. Also covers a pre-route backend's 404.
+ writeLegacyRecord(record, true, loadedAt);
+ authFetch(API_PATH, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ id: record.id,
+ kind: record.kind,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ gguf_variant: record.ggufVariant,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ loaded_at: loadedAt,
+ // The server shifts loaded_at by (server_now - client_now).
+ // biome-ignore lint/style/useNamingConvention: API schema
+ client_now: Date.now(),
+ }),
+ })
+ .then(async (res) => {
+ if (!res.ok) {
+ return;
+ }
+ // Adopt the server's answer: it may have clamped or rejected this
+ // write, and the shadow must mirror what is stored.
+ let serverRecord: LastLocalModelLoad | null = null;
+ let serverLoadedAt: number | null = null;
+ try {
+ const body = (await res.json()) as {
+ id?: unknown;
+ kind?: unknown;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ gguf_variant?: unknown;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ loaded_at?: unknown;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ server_now?: unknown;
+ };
+ serverRecord = toRecord({
+ id: body.id,
+ kind: body.kind,
+ ggufVariant: body.gguf_variant,
+ });
+ serverLoadedAt =
+ typeof body.loaded_at === "number" ? body.loaded_at : null;
+ if (serverLoadedAt !== null && typeof body.server_now === "number") {
+ // Shadow stamps live in this clock's frame: translate back first.
+ serverLoadedAt -= body.server_now - Date.now();
+ }
+ } catch {
+ // Pre-loaded_at backend or opaque response: fall back to our stamp.
+ }
+ // Clear only this write's marker: a newer load may have replaced the
+ // shadow mid-flight, even a reload of the same model, so the stamp must
+ // match too.
+ const legacy = readLegacyEntry();
+ if (
+ !legacy?.pendingSync ||
+ !sameRecord(legacy.record, record) ||
+ legacy.loadedAt !== loadedAt
+ ) {
+ return;
+ }
+ if (serverRecord && !sameRecord(serverRecord, record)) {
+ // The server kept a newer record from another surface: ours lost.
+ writeLegacyRecord(serverRecord, false, serverLoadedAt ?? Date.now());
+ } else {
+ writeLegacyRecord(record, false, serverLoadedAt ?? loadedAt);
+ }
+ })
+ .catch(() => {
+ // Best effort; the read path reconciles the pending shadow next launch.
+ });
}
diff --git a/studio/frontend/tests/last-local-model-load.test.ts b/studio/frontend/tests/last-local-model-load.test.ts
new file mode 100644
index 00000000000..df734e9fa9e
--- /dev/null
+++ b/studio/frontend/tests/last-local-model-load.test.ts
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The backend owns the remembered model; localStorage is a shadow so old
+// bundles, old backends and dropped writes all still behave.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+const { store } = installLocalStorageFake();
+
+const LEGACY_KEY = "unsloth.last-local-model-load.v1";
+
+const { readLastLocalModelLoad, recordLastLocalModelLoad } = await import(
+ "../src/features/chat/utils/last-local-model-load.ts"
+);
+
+type Backend = { record: Record<string, unknown> | null; status?: number };
+
+let backend: Backend = { record: null };
+let puts: Record<string, unknown>[] = [];
+let serverSkewMs = 0;
+
+globalThis.fetch = (async (_input: string, init?: RequestInit) => {
+ if (init?.signal?.aborted) {
+ throw Object.assign(new Error("aborted"), { name: "AbortError" });
+ }
+ const status = backend.status ?? 200;
+ const serverNow = Date.now() + serverSkewMs;
+ if (status !== 200) {
+ return { ok: false, status, json: async () => ({}) } as Response;
+ }
+ if (init?.method === "PUT") {
+ const body = JSON.parse(String(init.body)) as Record<string, unknown>;
+ puts.push(body);
+ // Mirror the server: shift into its frame, then keep the newer stamp.
+ const shifted =
+ typeof body.loaded_at === "number" && typeof body.client_now === "number"
+ ? body.loaded_at + (serverNow - body.client_now)
+ : body.loaded_at;
+ const current = backend.record;
+ const beaten =
+ current &&
+ typeof current.loaded_at === "number" &&
+ typeof shifted === "number" &&
+ shifted < current.loaded_at;
+ if (!beaten) {
+ backend.record = { ...body, loaded_at: shifted };
+ delete (backend.record as { client_now?: unknown }).client_now;
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ ...(backend.record ?? {}), server_now: serverNow }),
+ } as Response;
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ ...(backend.record ?? {}), server_now: serverNow }),
+ } as Response;
+}) as typeof fetch;
+
+function reset(): void {
+ store.clear();
+ backend = { record: null };
+ puts = [];
+ serverSkewMs = 0;
+}
+
+function legacy(): Record<string, unknown> | null {
+ const raw = store.get(LEGACY_KEY);
+ return raw ? (JSON.parse(raw) as Record<string, unknown>) : null;
+}
+
+test("a new frontend against an old backend falls back to the shadow", async () => {
+ reset();
+ backend.status = 404;
+ recordLastLocalModelLoad({ id: "u/m", kind: "gguf", ggufVariant: "Q4" });
+ const got = await readLastLocalModelLoad();
+ assert.deepEqual(got, { id: "u/m", kind: "gguf", ggufVariant: "Q4" });
+ // The write could not land, so the shadow stays flagged for a later sync.
+ assert.equal(legacy()?.pendingSync, true);
+});
+
+test("the shadow is written synchronously so a teardown cannot lose it", () => {
+ reset();
+ // No await: the record must already be stored when this returns.
+ recordLastLocalModelLoad({ id: "u/m", kind: "model", ggufVariant: null });
+ assert.equal(legacy()?.id, "u/m");
+ assert.equal(typeof legacy()?.loadedAt, "number");
+});
+
+test("the shadow keeps loadedAt so a still-open old tab can still read it", () => {
+ reset();
+ recordLastLocalModelLoad({ id: "u/m", kind: "model", ggufVariant: null });
+ // Pre-backend readers reject a record without a numeric loadedAt.
+ assert.equal(typeof legacy()?.loadedAt, "number");
+});
+
+test("a newer backend record wins over an older shadow", async () => {
+ reset();
+ const now = Date.now();
+ store.set(
+ LEGACY_KEY,
+ JSON.stringify({ id: "old", kind: "model", ggufVariant: null, loadedAt: now - 60_000 }),
+ );
+ backend.record = { id: "new", kind: "model", gguf_variant: null, loaded_at: now };
+ const got = await readLastLocalModelLoad();
+ assert.equal(got?.id, "new");
+});
+
+test("a newer shadow wins over an older backend record and is re-synced", async () => {
+ reset();
+ const now = Date.now();
+ store.set(
+ LEGACY_KEY,
+ JSON.stringify({ id: "fresh", kind: "model", ggufVariant: null, loadedAt: now }),
+ );
+ backend.record = { id: "stale", kind: "model", gguf_variant: null, loaded_at: now - 60_000 };
+ const got = await readLastLocalModelLoad();
+ assert.equal(got?.id, "fresh");
+ // Re-issued so the server stops handing the stale one to other surfaces.
+ assert.equal(puts.at(-1)?.id, "fresh");
+});
+
+test("a stale shadow loses to an unstamped backend record", async () => {
+ reset();
+ store.set(
+ LEGACY_KEY,
+ JSON.stringify({
+ id: "shadow",
+ kind: "model",
+ ggufVariant: null,
+ loadedAt: Date.now() - 60_000,
+ }),
+ );
+ // Written by a pre-loaded_at client, so there is no stamp to compare.
+ backend.record = { id: "backend", kind: "model", gguf_variant: null, loaded_at: null };
+ const got = await readLastLocalModelLoad();
+ assert.equal(got?.id, "backend");
+});
+
+test("a pending shadow beats an unstamped backend record", async () => {
+ reset();
+ store.set(
+ LEGACY_KEY,
+ JSON.stringify({
+ id: "pending",
+ kind: "model",
+ ggufVariant: null,
+ loadedAt: Date.now(),
+ pendingSync: true,
+ }),
+ );
+ backend.record = { id: "backend", kind: "model", gguf_variant: null, loaded_at: null };
+ assert.equal((await readLastLocalModelLoad())?.id, "pending");
+});
+
+for (const skew of [-86_400_000, 86_400_000]) {
+ test(`a server clock ${skew < 0 ? "behind" : "ahead"} by a day still orders correctly`, async () => {
+ reset();
+ serverSkewMs = skew;
+ const now = Date.now();
+ store.set(
+ LEGACY_KEY,
+ JSON.stringify({ id: "fresh", kind: "model", ggufVariant: null, loadedAt: now }),
+ );
+ // The same instant, expressed in the server's frame.
+ backend.record = {
+ id: "stale",
+ kind: "model",
+ gguf_variant: null,
+ loaded_at: now + skew - 60_000,
+ };
+ assert.equal((await readLastLocalModelLoad())?.id, "fresh");
+ });
+}
+
+test("a corrupt shadow is ignored rather than thrown", async () => {
+ reset();
+ store.set(LEGACY_KEY, "{not json");
+ assert.equal(await readLastLocalModelLoad(), null);
+});
+
+test("a gguf record with no variant and a repo id is rejected", async () => {
+ reset();
+ backend.record = { id: "u/m", kind: "gguf", gguf_variant: null, loaded_at: Date.now() };
+ // Names no file to load, so it cannot be acted on.
+ assert.equal(await readLastLocalModelLoad(), null);
+});
+
+test("a gguf record with no variant but a filesystem path is kept", async () => {
+ reset();
+ backend.record = {
+ id: "/models/m.gguf",
+ kind: "gguf",
+ gguf_variant: null,
+ loaded_at: Date.now(),
+ };
+ assert.equal((await readLastLocalModelLoad())?.id, "/models/m.gguf");
+});
+
+test("an aborted read rejects rather than falling back", async () => {
+ reset();
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(() => readLastLocalModelLoad(controller.signal));
+});