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: stop CLI commands running as another account when Studio has more than one (#12492)

Nilay6f0278dbac8c
diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.py
index 6399bd35e66..423d0f61420 100644
--- a/unsloth_cli/_inference.py
+++ b/unsloth_cli/_inference.py
@@ -853,7 +853,14 @@ def _studio_token() -> Optional[str]:
from studio.backend.auth import storage
from studio.backend.auth.authentication import create_access_token
- row = storage.get_connection().execute("SELECT username FROM auth_user LIMIT 1").fetchone()
+ row = (
+ storage.get_connection()
+ .execute(
+ "SELECT username FROM auth_user WHERE username = ?",
+ (storage.DEFAULT_ADMIN_USERNAME,),
+ )
+ .fetchone()
+ )
return create_access_token(row[0], desktop = True) if row else None
except Exception:
return None
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 06ced6cf878..0b66ec886bf 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -1775,12 +1775,6 @@ def _agent_api_key(
)
# Identity verified: replay a previously auto-minted key, else mint a new one.
- for key in _cached_keys(cache, base, "minted"):
- if _key_accepted(base, key):
- _remember_key(cache, base, key, "minted")
- return key
-
- # Self-issue a JWT (signed with the local secret) and mint a key.
token = _studio_token()
if token is None:
_fail(
@@ -1788,6 +1782,18 @@ def _agent_api_key(
"an API key in Unsloth → Settings → API and pass it with --api-key, "
"or set UNSLOTH_API_KEY."
)
+ # Older releases could mint for a managed account, which cannot see the owner's model.
+ owned = {
+ entry.get("key_prefix")
+ for entry in _http_json(
+ "GET", f"{base}/api/auth/api-keys", token, error = "Couldn't list API keys"
+ ).get("api_keys", [])
+ }
+ for key in _cached_keys(cache, base, "minted"):
+ if key[len("sk-unsloth-") :][:8] in owned and _key_accepted(base, key):
+ _remember_key(cache, base, key, "minted")
+ return key
+
key = _http_json(
"POST",
f"{base}/api/auth/api-keys",
@@ -1903,6 +1909,13 @@ def _inference_status(base: str, key: str) -> dict:
return {}
+_OTHER_ACCOUNT_RESIDENT = (
+ "The model loaded in Unsloth belongs to another account, so this API key cannot use it. "
+ "Pass --model <hf-id-or-path> to load one: the same model and quant shares it, anything "
+ "else unloads it for every session using it."
+)
+
+
def _resident_load_target(models: list, status: dict, allow_casefold: bool):
"""(identifier to post, id it is advertised as) for the running model. The loaded listing shows only the sanitized basename while _same_loaded_identifier compares resident paths exactly, so the load must carry the identifier status reports."""
if status.get("is_diffusion"):
@@ -1935,6 +1948,8 @@ def _resident_load_target(models: list, status: dict, allow_casefold: bool):
)
public_id = active_id or (entry or {}).get("id")
if not public_id:
+ if status.get("yours") is False:
+ _fail(_OTHER_ACCOUNT_RESIDENT)
if status:
# Status answered and named no chat model. Returning empty here would drop the knobs silently, which is the bug this path exists to fix.
_fail(
@@ -2199,6 +2214,14 @@ def _resolve_model(
)
typer.echo("This unloads the current model for every attached session.")
announced_switch = True
+ elif not active_id and _inference_status(base, key).get("yours") is False:
+ typer.echo(
+ "Switching the Unsloth server from another account's model to "
+ f"{_display_model_spec(requested, load.gguf_variant)}."
+ )
+ typer.echo(
+ "This unloads it for every attached session, unless it is the same model and quant."
+ )
# Mirror `unsloth run`'s load knobs; keep the default payload as just model_path so a bare `--model` load is unchanged. Membership decides, not truthiness: a reset like --context-length 0 equals the default yet must be sent.
payload = {"model_path": requested}
if "gguf_variant" in overrides and load.gguf_variant:
@@ -2300,6 +2323,8 @@ def _resolve_model(
)
resident = next((m for m in models if m.get("loaded") is not False), None)
if resident is None:
+ if _inference_status(base, key).get("yours") is False:
+ _fail(_OTHER_ACCOUNT_RESIDENT)
# An empty listing and one holding only unloaded entries are the same situation
# to the user, and which one a server sends depends only on its version.
_fail(
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index 5f975184b4a..5c27aa11b96 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -1519,6 +1519,8 @@ def fake_studio(tmp_path, monkeypatch):
if url.endswith("/api/inference/status"):
return {"is_gguf": True, "model_identifier": state["models"][0]["id"]}
if url.endswith("/api/auth/api-keys"):
+ if method == "GET":
+ return {"api_keys": [{"key_prefix": "feedface"}]}
return {"key": "sk-unsloth-feedfacefeedface"}
if url.endswith("/api/settings/embedding-model"):
return {"embedding_model": "unsloth/bge-small-en-v1.5"}
@@ -2834,12 +2836,20 @@ def test_connect_key_minted_once_then_cached(fake_studio, tmp_path):
CliRunner().invoke(start.start_app, ["claude", "--no-launch"])
CliRunner().invoke(start.start_app, ["claude", "--no-launch"])
# First run mints; second reuses the minted key cached for this server.
- mints = [c for c in fake_studio if c[1].endswith("/api/auth/api-keys")]
+ mints = [c for c in fake_studio if c[0] == "POST" and c[1].endswith("/api/auth/api-keys")]
assert len(mints) == 1
cached = json.loads((tmp_path / "agent_api_key.json").read_text())
assert cached["servers"][BASE]["minted"] == ["sk-unsloth-feedfacefeedface"]
+def test_connect_skips_a_minted_key_the_owner_does_not_hold(fake_studio, tmp_path):
+ cache = tmp_path / "agent_api_key.json"
+ cache.write_text(json.dumps({"servers": {BASE: {"minted": ["sk-unsloth-a11ce000a11ce000"]}}}))
+ result = CliRunner().invoke(start.start_app, ["claude", "--no-launch"])
+ assert result.exit_code == 0, result.output
+ _assert_env_set(result.output, "ANTHROPIC_AUTH_TOKEN", "sk-unsloth-feedfacefeedface")
+
+
def test_connect_explicit_key_remembered_for_keyless_runs(fake_studio, tmp_path):
CliRunner().invoke(
start.start_app,
@@ -4230,6 +4240,25 @@ def test_verify_studio_identity_end_to_end(tmp_path, monkeypatch):
stop_bad()
+def test_studio_token_is_issued_for_the_owner_not_a_managed_account(tmp_path, monkeypatch):
+ import secrets
+
+ import jwt
+
+ import unsloth_cli._inference as inference
+
+ inference.ensure_studio_backend_path()
+ from studio.backend.auth import storage
+
+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")
+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))
+ storage.issue_account_setup_code(username = "alice")
+
+ token = inference._studio_token()
+ assert token
+ assert jwt.decode(token, options = {"verify_signature": False})["sub"] == "unsloth"
+
+
def _serve_redirect(target):
"""Start a localhost server that 302-redirects every GET to target+path."""
import threading
@@ -4847,6 +4876,78 @@ def test_resolve_model_refused_load_reports_survivor(monkeypatch, capsys):
assert "Nothing was unloaded; owner/model-GGUF is still serving." in captured.err
+def _other_account_studio(
+ monkeypatch,
+ capsys,
+ load_status = "loaded",
+):
+ state = {"models": [], "loads": []}
+
+ def http_json(
+ method,
+ url,
+ key,
+ payload = None,
+ timeout = 30,
+ error = None,
+ ):
+ if url.endswith("/api/inference/loaded-models"):
+ return {"object": "list", "data": state["models"]}
+ assert url.endswith("/api/inference/status"), url
+ if state["models"]:
+ return {"is_gguf": True, "active_model": "owner/model-GGUF", "gguf_variant": "Q4_K_M"}
+ return {"loaded": [], "loading": [], "yours": False}
+
+ def load_model(base, key, model, load, payload):
+ state["loads"].append((payload, capsys.readouterr().out))
+ state["models"] = [{"id": model, "loaded": True}]
+ return {"status": load_status, "model": model}
+
+ monkeypatch.setattr(start, "_http_json", http_json)
+ monkeypatch.setattr(start, "_load_model_with_progress", load_model)
+ return state
+
+
+ "load",
+ [start.LoadOptions(), start.LoadOptions(max_seq_length = 4096)],
+ ids = ["no-settings", "settings-only"],
+)
+def test_resolve_model_says_another_account_holds_the_resident(monkeypatch, capsys, load):
+ state = _other_account_studio(monkeypatch, capsys)
+
+ with pytest.raises(typer.Exit):
+ start._resolve_model(BASE, "key", None, load)
+
+ err = capsys.readouterr().err
+ assert "belongs to another account" in err
+ assert "No model is loaded" not in err and "No chat model" not in err
+ assert state["loads"] == []
+
+
+def test_resolve_model_warns_before_replacing_another_accounts_resident(monkeypatch, capsys):
+ state = _other_account_studio(monkeypatch, capsys)
+
+ start._resolve_model(BASE, "key", "owner/model-GGUF")
+
+ [(payload, before_load)] = state["loads"]
+ assert payload == {"model_path": "owner/model-GGUF"}
+ assert "from another account's model to owner/model-GGUF." in before_load
+ assert "unloads it for every attached session" in before_load
+
+
+def test_resolve_model_exact_match_shares_another_accounts_resident(monkeypatch, capsys):
+ state = _other_account_studio(monkeypatch, capsys, load_status = "already_loaded")
+
+ entry = start._resolve_model(
+ BASE, "key", "owner/model-GGUF", start.LoadOptions(gguf_variant = "Q4_K_M")
+ )
+
+ assert entry["id"] == "owner/model-GGUF"
+ assert state["loads"][0][0]["gguf_variant"] == "Q4_K_M"
+ assert "Reusing loaded model: owner/model-GGUF:Q4_K_M" in capsys.readouterr().out
+
+
def test_resolve_model_interrupt_skips_survivor_probe(monkeypatch, capsys):
models = [{"id": "owner/model-GGUF", "loaded": True}]
probes = []