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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: per-account isolation for shared installs and the desktop app (#10588)
Daniel Han7434717466d0
diff --git a/.github/actions/frontend-dist-restore/action.yml b/.github/actions/frontend-dist-restore/action.ymlindex 7fa5a1a6d46..995397c3f91 100644--- a/.github/actions/frontend-dist-restore/action.yml+++ b/.github/actions/frontend-dist-restore/action.yml@@ -75,7 +75,7 @@ runs:- name: Refuse a frontend cache key that hashes nothingshell: bashenv:- FE_KEY: ${{ hashFiles(format('{0}studio/frontend/*', inputs.path-prefix), format('{0}studio/frontend/src/**', inputs.path-prefix), format('{0}studio/frontend/public/**', inputs.path-prefix), format('!{0}studio/frontend/tests/**', inputs.path-prefix), format('!{0}studio/frontend/scripts/**', inputs.path-prefix)) }}+ FE_KEY: ${{ hashFiles(format('{0}studio/frontend/*', inputs.path-prefix), format('{0}studio/frontend/src/**', inputs.path-prefix), format('{0}studio/frontend/public/**', inputs.path-prefix), format('!{0}studio/frontend/tests/**', inputs.path-prefix), format('!{0}studio/frontend/scripts/**', inputs.path-prefix), format('!{0}studio/frontend/e2e/**', inputs.path-prefix)) }}FE_PREFIX: ${{ inputs.path-prefix }}run: |# hashFiles returns "" when a glob matches no file, which would collapse@@ -99,7 +99,7 @@ runs:# of the wheels, which is most of the win. A near-miss dist is a bundle# built from DIFFERENT source: wrong, not partial. Only an exact match may# be served.- key: fe-dist-${{ runner.os }}-${{ hashFiles(format('{0}studio/frontend/*', inputs.path-prefix), format('{0}studio/frontend/src/**', inputs.path-prefix), format('{0}studio/frontend/public/**', inputs.path-prefix), format('!{0}studio/frontend/tests/**', inputs.path-prefix), format('!{0}studio/frontend/scripts/**', inputs.path-prefix)) }}+ key: fe-dist-${{ runner.os }}-${{ hashFiles(format('{0}studio/frontend/*', inputs.path-prefix), format('{0}studio/frontend/src/**', inputs.path-prefix), format('{0}studio/frontend/public/**', inputs.path-prefix), format('!{0}studio/frontend/tests/**', inputs.path-prefix), format('!{0}studio/frontend/scripts/**', inputs.path-prefix), format('!{0}studio/frontend/e2e/**', inputs.path-prefix)) }}# THE STEP THE WHOLE CACHE RESTS ON, and the one that is silent when wrong.#diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.ymlindex b52b8ffeeef..b9c8e03df99 100644--- a/.github/workflows/studio-ui-smoke.yml+++ b/.github/workflows/studio-ui-smoke.yml@@ -593,6 +593,16 @@ jobs:mkdir -p logs/playwright_fontscalepython tests/studio/playwright_ui_font_scale.py+ # The owner creates an account, its setup code is private, and switching accounts in one+ # browser clears account data; the account is deleted at the end, so the owner is back alone.+ - name: Multi-account switch flow (Playwright)+ if: matrix.shard == 'extra'+ env:+ STUDIO_E2E_URL: http://127.0.0.1:18894+ STUDIO_E2E_OWNER_PASSWORD: ${{ env.STUDIO_EXTRA_NEW_PW }}+ run: |+ python tests/studio/playwright_multi_account.py+- name: Update banner layout regression (Playwright)if: matrix.shard == 'chat'env:diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex 65d1b275ebf..cc7f63f9ca9 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -11,7 +11,11 @@ from fastapi.security.utils import get_authorization_scheme_paramimport jwtfrom starlette.concurrency import run_in_threadpool+from utils.account_context import OWNER, AccountContext, bind_account+from .storage import (+ get_account,+ get_user_record,API_KEY_PREFIX,DEFAULT_ADMIN_USERNAME,credential_generation,@@ -19,6 +23,7 @@ from .storage import (get_user_and_secret,load_jwt_secret,save_refresh_token,+ validate_api_key_account,validate_api_key_with_credential,verify_refresh_token,)@@ -185,6 +190,10 @@ class _BearerOrKeyless(HTTPBearer):security = _BearerOrKeyless(scheme_name = "HTTPBearer")+def _bind_owner() -> None:+ bind_account(OWNER)++def _get_secret_for_subject(subject: str) -> str:secret = get_jwt_secret(subject)if secret is None:@@ -251,7 +260,10 @@ def is_desktop_access_token(token: str) -> bool:except jwt.InvalidTokenError:return False- return payload.get("sub") == subject and payload.get("desktop") is True+ if payload.get("sub") != subject or payload.get("desktop") is not True:+ return False+ account = get_account(subject)+ return account is not None and account.is_ownerdef create_refresh_token(@@ -338,7 +350,6 @@ async def credentials_for_token(that covers them. None means no usable credential and no setting to stand in for one."""from utils.keyless_api_access import APPROVED_DUMMY_BEARERS, keyless_request_allowed- # /api/health slices the bearer out itself, so a blank one arrives as "", not as None.if token is not None and not token.strip():token = None# Settings/listener reads hit SQLite and DNS, so keep them off the event loop.@@ -438,28 +449,33 @@ async def _get_current_credential(credentials must bind their write to it, or a reset landing mid-request would bless what it justrevoked. Credential reads run in the threadpool so stalled SQLite cannot block the event loop."""if credentials.scheme == KEYLESS_SCHEME:+ _bind_owner()return await run_in_threadpool(_admin_credential)if credentials.scheme == KEYLESS_FALLBACK_SCHEME:from utils.keyless_api_access import APPROVED_DUMMY_BEARERS+if credentials.credentials not in APPROVED_DUMMY_BEARERS:raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED,detail = "Invalid authentication credentials",)+ _bind_owner()return await run_in_threadpool(_admin_credential)token = credentials.credentialsif token.startswith(API_KEY_PREFIX):- verified = await run_in_threadpool(validate_api_key_with_credential, token)+ verified = await run_in_threadpool(validate_api_key_account, token)if verified is None:raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED,detail = _invalid_api_key_detail(token),)- username, secret = verified- return username, credential_generation(secret)+ record, secret = verified+ # A second lookup by username would bind whoever owns that name after a delete and re-create.+ bind_account(AccountContext(record["account_id"], record["username"], record["role"]))+ return record["username"], credential_generation(secret)subject = _decode_subject_without_verification(token)if subject is None:@@ -468,30 +484,33 @@ async def _get_current_credential(detail = "Invalid token payload",)- record = await run_in_threadpool(get_user_and_secret, subject)- if record is None:+ record = await run_in_threadpool(get_user_record, subject)+ if record is None or not record.get("is_active", 1):raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED,detail = "Invalid or expired token",)- _salt, _pwd_hash, jwt_secret, must_change_password = record+ jwt_secret = record["jwt_secret"]+ must_change_password = bool(record["must_change_password"])try:payload = jwt.decode(token, jwt_secret, algorithms = [ALGORITHM])- if payload.get("sub") != subject:- raise HTTPException(- status_code = status.HTTP_401_UNAUTHORIZED,- detail = "Invalid token payload",- )- is_desktop = payload.get("desktop") is True- if must_change_password and not allow_password_change and not is_desktop:- raise HTTPException(- status_code = status.HTTP_403_FORBIDDEN,- detail = "Password change required",- )- return subject, credential_generation(jwt_secret)except jwt.InvalidTokenError:raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED,detail = "Invalid or expired token",)+ if payload.get("sub") != subject:+ raise HTTPException(+ status_code = status.HTTP_401_UNAUTHORIZED,+ detail = "Invalid token payload",+ )+ bind_account(AccountContext(record["account_id"], record["username"], record["role"]))+ # A managed token carrying the desktop marker gets no owner password-change bypass.+ is_desktop = payload.get("desktop") is True and record.get("role") == "owner"+ if must_change_password and not allow_password_change and not is_desktop:+ raise HTTPException(+ status_code = status.HTTP_403_FORBIDDEN,+ detail = "Password change required",+ )+ return subject, credential_generation(jwt_secret)diff --git a/studio/backend/auth/hashing.py b/studio/backend/auth/hashing.pyindex 4d97b835fe6..8c4f41d9337 100644--- a/studio/backend/auth/hashing.py+++ b/studio/backend/auth/hashing.py@@ -31,3 +31,13 @@ def verify_password(password: str, salt: str, hashed: str) -> bool:100_000,)return hmac.compare_digest(dk.hex(), hashed)+++# Fixed inputs, so a miss spends the same PBKDF2 round a real account would.+_EQUALIZE_SALT = "0" * 32+_EQUALIZE_HASH = "0" * 64+++def equalize_login_work(password: str) -> None:+ """Spend the verification cost with no stored hash, so a miss is not faster to reject."""+ verify_password(password, _EQUALIZE_SALT, _EQUALIZE_HASH)diff --git a/studio/backend/auth/policy.py b/studio/backend/auth/policy.pynew file mode 100644index 00000000000..fe0cc62d48b--- /dev/null+++ b/studio/backend/auth/policy.py@@ -0,0 +1,123 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Installation-wide account policy, cached against a generation bumped on account writes."""++from __future__ import annotations++import contextlib+import threading+from typing import Optional++from fastapi import Depends, HTTPException, status++LOGIN_MODE_SINGLE = "single"+LOGIN_MODE_MULTI = "multi"++_lock = threading.Lock()+_generation = 0+_cached: Optional[tuple[int, int, int]] = None+# Depth of in-flight account mutations; the cache is bypassed while any is open.+_mutating = 0+++def invalidate_account_cache() -> None:+ """Call after any account is created, deleted, activated or deactivated."""+ global _generation, _cached+ with _lock:+ _generation += 1+ _cached = None+++def account_mutation():+ """Wrap an account write, invalidation included. Post-commit invalidation alone leaves a window+ where the row is durable but the cache still answers the pre-write verdict, so the cache is+ bypassed for the whole write. Counted, so nesting works."""+ global _mutating, _generation, _cached+ with _lock:+ _mutating += 1+ try:+ yield+ finally:+ # One critical section: unsuppressing before invalidating would reopen the window.+ with _lock:+ _mutating -= 1+ _generation += 1+ _cached = None+++def account_generation() -> int:+ return _generation+++def _account_counts() -> tuple[int, int]:+ global _cached+ with _lock:+ if not _mutating and _cached is not None and _cached[0] == _generation:+ return _cached[1], _cached[2]+ generation = _generation+ from auth import storage++ try:+ active, managed = storage.account_counts()+ except Exception: # noqa: BLE001 - an unreadable auth.db is a one-user install+ # Never cached: a transient error would hold full access off until restart.+ from utils.account_context import is_owner_context++ # A bound managed account proves a multi-user install, so isolation stays on.+ return (1 if is_owner_context() else 2), 1+ with _lock:+ if not _mutating and generation == _generation:+ _cached = (generation, active, managed)+ return active, managed+++def active_account_count() -> int:+ return _account_counts()[0]+++def managed_account_count() -> int:+ """Managed accounts of any state; a deactivated one still counts."""+ return _account_counts()[1]+++def installation_is_multi_user() -> bool:+ return active_account_count() > 1+++def login_mode() -> str:+ return LOGIN_MODE_MULTI if installation_is_multi_user() else LOGIN_MODE_SINGLE+++def installation_has_managed_accounts() -> bool:+ """Any managed account exists. Gated on this, not login mode: deactivated files stay on disk."""+ return installation_is_multi_user() or managed_account_count() > 0+++def full_access_permitted() -> bool:+ """Unsandboxed tool modes: refused install-wide, owner included, if a managed account exists."""+ return not installation_has_managed_accounts()+++def _forbid(detail: str) -> HTTPException:+ return HTTPException(status_code = status.HTTP_403_FORBIDDEN, detail = detail)+++async def require_owner() -> None:+ from utils.account_context import current_account+ if not current_account().is_owner:+ raise _forbid("Only the installation owner can do this")+++def require_account_scope(resource_account_id: Optional[str]) -> None:+ """Refuse a resource owned by another account; ``None`` predates accounts and is owner-owned."""+ from utils.account_context import OWNER_ACCOUNT_ID, current_account_id++ owner_of = resource_account_id or OWNER_ACCOUNT_ID+ if owner_of != current_account_id():+ # 404 rather than 403: existence is itself information.+ raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = "Not found")+++OwnerOnly = Depends(require_owner)diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.pyindex 5958c826b5f..a3d6509ebf6 100644--- a/studio/backend/auth/storage.py+++ b/studio/backend/auth/storage.py@@ -3,17 +3,20 @@"""SQLite storage for auth data (user credentials + JWT secret)."""+import contextlibfrom contextlib import contextmanagerimport hashlibimport hmacimport ipaddressimport os+import reimport secretsimport sqlite3import tempfileimport threading-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezone+import uuidfrom typing import Iterator, Optional, Tuplefrom utils.paths import auth_db_path, ensure_dir@@ -199,9 +202,35 @@ def credential_generation(jwt_secret: str) -> str:return hashlib.sha256(jwt_secret.encode("utf-8")).hexdigest()+# Downgrade fence: managed creds live in ``account_*`` with prefixed hashes, so a build without+# account support 401s a managed login.+_FENCE_PREFIX = "account:"+_FENCED_HASH_SQL = "IN (?, ?)"+_LEGACY_PASSWORD_HASH_SENTINEL = "managed-account"+_SECRET_SQL = "COALESCE(account_jwt_secret, jwt_secret)"+_PASSWORD_HASH_SQL = "COALESCE(account_password_hash, password_hash)"+_PASSWORD_SALT_SQL = "COALESCE(account_password_salt, password_salt)"+++def _is_owner_name(username: str) -> bool:+ return username == DEFAULT_ADMIN_USERNAME+++def _fenced_hash(digest: str, username: str) -> str:+ return digest if _is_owner_name(username) else _FENCE_PREFIX + digest+++def _hash_candidates(digest: str) -> tuple[str, str]:+ return digest, _FENCE_PREFIX + digest+++def _legacy_dummies() -> tuple[str, str, str]:+ return secrets.token_hex(16), _LEGACY_PASSWORD_HASH_SENTINEL, secrets.token_urlsafe(64)++def _current_secret(conn: sqlite3.Connection, username: str) -> Optional[str]:row = conn.execute(- "SELECT jwt_secret FROM auth_user WHERE username = ?", (username,)+ f"SELECT {_SECRET_SQL} AS jwt_secret FROM auth_user WHERE username = ?", (username,)).fetchone()return row["jwt_secret"] if row else None@@ -231,6 +260,9 @@ def credential_generation_guard(username: str, expect_gen: Optional[str]) -> Iteconn.close()+_auth_schema_ready: set[tuple[str, int, int, int]] = set()++def get_connection() -> sqlite3.Connection:ensure_dir(DB_PATH.parent)conn = sqlite3.connect(DB_PATH)@@ -248,6 +280,15 @@ def get_connection() -> sqlite3.Connection:conn.execute("PRAGMA journal_mode=WAL")except sqlite3.Error:pass+ file_stat = DB_PATH.stat()+ schema_key = (+ str(DB_PATH),+ file_stat.st_dev,+ file_stat.st_ino,+ conn.execute("PRAGMA schema_version").fetchone()[0],+ )+ if schema_key in _auth_schema_ready:+ return connconn.execute("""CREATE TABLE IF NOT EXISTS auth_user (@@ -304,12 +345,20 @@ def get_connection() -> sqlite3.Connection:conn.execute("ALTER TABLE auth_user ADD COLUMN must_change_password INTEGER NOT NULL DEFAULT 0")+ _ensure_account_columns(conn, columns)+ _ensure_account_api_keys(conn, api_key_columns)refresh_columns = {row["name"] for row in conn.execute("PRAGMA table_info(refresh_tokens)")}if "is_desktop" not in refresh_columns:conn.execute("ALTER TABLE refresh_tokens ADD COLUMN is_desktop INTEGER NOT NULL DEFAULT 0")if "secret_gen" not in refresh_columns:conn.execute("ALTER TABLE refresh_tokens ADD COLUMN secret_gen TEXT")conn.commit()+ _auth_schema_ready.add(+ (+ *schema_key[:3],+ conn.execute("PRAGMA schema_version").fetchone()[0],+ )+ )return conn@@ -318,6 +367,490 @@ def get_connection() -> sqlite3.Connection:_api_key_pbkdf2_salt_cache: Optional[bytes] = None+_ACCOUNT_COLUMNS = (+ ("account_id", "TEXT"),+ ("role", "TEXT NOT NULL DEFAULT 'user'"),+ ("is_active", "INTEGER NOT NULL DEFAULT 1"),+ ("created_at", "TEXT"),+ ("setup_code_hash", "TEXT"),+ ("setup_code_expires_at", "TEXT"),+ ("account_password_salt", "TEXT"),+ ("account_password_hash", "TEXT"),+ ("account_jwt_secret", "TEXT"),+)+++_owner_id_repaired: set[str] = set()+++def _repair_owner_account_id(conn: sqlite3.Connection) -> None:+ db_key = str(DB_PATH)+ if db_key in _owner_id_repaired:+ return+ from utils.account_context import OWNER_ACCOUNT_ID, ROLE_OWNER++ repaired = conn.execute(+ "UPDATE auth_user SET account_id = ?, role = ?, created_at = COALESCE(created_at, ?) "+ "WHERE username = ? AND account_id IS NULL",+ (+ OWNER_ACCOUNT_ID,+ ROLE_OWNER,+ datetime.now(timezone.utc).isoformat(),+ DEFAULT_ADMIN_USERNAME,+ ),+ ).rowcount+ if repaired:+ conn.execute(+ "CREATE UNIQUE INDEX IF NOT EXISTS auth_user_account_id ON auth_user(account_id)"+ )+ conn.commit()+ _owner_id_repaired.add(db_key)+++def _ensure_account_columns(conn: sqlite3.Connection, existing: set) -> None:+ if all(name in existing for name, _decl in _ACCOUNT_COLUMNS):+ _repair_owner_account_id(conn)+ return+ # Both connections can see the columns missing: re-read under the write lock, where a losing+ # ALTER is the other side's, not an error.+ conn.execute("BEGIN IMMEDIATE")+ try:+ existing = {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}+ added = False+ fence_added = False+ for name, decl in _ACCOUNT_COLUMNS:+ if name in existing:+ continue+ try:+ conn.execute(f"ALTER TABLE auth_user ADD COLUMN {name} {decl}")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ continue+ added = True+ fence_added = fence_added or name == "account_jwt_secret"+ if added:+ _backfill_account_columns(conn, fence_added)+ conn.commit()+ except BaseException:+ conn.rollback()+ raise+++_ACCOUNT_API_KEY_COLUMNS = "username, key_prefix, key_hash, name, created_at, expires_at, is_active, is_internal, account_id"+++_account_keys_synced: set[str] = set()+++def _ensure_account_api_keys(conn: sqlite3.Connection, existing: set) -> None:+ """Pin managed API keys to the immutable ``account_id`` (a namesake inherits none) and mirror+ them into ``account_api_keys``. Idempotent."""+ db_key = str(DB_PATH)+ if db_key in _account_keys_synced and "account_id" in existing:+ return+ if "account_id" not in existing:+ try:+ conn.execute("ALTER TABLE api_keys ADD COLUMN account_id TEXT")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ conn.execute(+ """UPDATE api_keys SET account_id = (+ SELECT account_id FROM auth_user+ WHERE auth_user.username = api_keys.username AND auth_user.role != 'owner'+ ) WHERE account_id IS NULL"""+ )+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS account_api_keys (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ username TEXT NOT NULL,+ key_prefix TEXT NOT NULL,+ key_hash TEXT NOT NULL UNIQUE,+ name TEXT NOT NULL DEFAULT '',+ created_at TEXT NOT NULL,+ expires_at TEXT,+ is_active INTEGER NOT NULL DEFAULT 1,+ is_internal INTEGER NOT NULL DEFAULT 0,+ account_id TEXT NOT NULL+ );+ """+ )+ conn.execute(+ f"""INSERT INTO account_api_keys ({_ACCOUNT_API_KEY_COLUMNS})+ SELECT {_ACCOUNT_API_KEY_COLUMNS} FROM api_keys k+ WHERE k.account_id IS NOT NULL+ AND NOT EXISTS (SELECT 1 FROM account_api_keys b WHERE b.key_hash = k.key_hash)"""+ )+ conn.execute(+ f"""INSERT INTO api_keys ({_ACCOUNT_API_KEY_COLUMNS})+ SELECT {_ACCOUNT_API_KEY_COLUMNS} FROM account_api_keys b+ WHERE NOT EXISTS (SELECT 1 FROM api_keys k WHERE k.key_hash = b.key_hash)+ AND EXISTS (SELECT 1 FROM auth_user u WHERE u.account_id = b.account_id)"""+ )+ conn.commit()+ _account_keys_synced.add(db_key)+++def _backfill_account_columns(conn: sqlite3.Connection, fence_added: bool) -> None:+ from utils.account_context import OWNER_ACCOUNT_ID, ROLE_OWNER, ROLE_USER+ import uuid++ now = datetime.now(timezone.utc).isoformat()+ for row_id, username, account_id in conn.execute(+ "SELECT id, username, account_id FROM auth_user"+ ).fetchall():+ if account_id:+ continue+ if username == DEFAULT_ADMIN_USERNAME:+ account_id, role = OWNER_ACCOUNT_ID, ROLE_OWNER+ else:+ account_id, role = uuid.uuid4().hex, ROLE_USER+ conn.execute(+ "UPDATE auth_user SET account_id = ?, role = ?, created_at = COALESCE(created_at, ?) WHERE id = ?",+ (account_id, role, now, row_id),+ )+ conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS auth_user_account_id ON auth_user(account_id)")+ if fence_added:+ _fence_managed_credentials(conn)+++def _fence_managed_credentials(conn: sqlite3.Connection) -> None:+ # Positional reads: the caller's connection may lack a row factory.+ rows = conn.execute(+ "SELECT id, password_salt, password_hash, jwt_secret FROM auth_user "+ "WHERE role = 'user' AND account_jwt_secret IS NULL"+ ).fetchall()+ for row_id, real_salt, real_hash, real_secret in rows:+ salt, pwd_hash, secret = _legacy_dummies()+ conn.execute(+ """UPDATE auth_user+ SET account_password_salt = ?, account_password_hash = ?, account_jwt_secret = ?,+ password_salt = ?, password_hash = ?, jwt_secret = ?+ WHERE id = ?""",+ (real_salt, real_hash, real_secret, salt, pwd_hash, secret, row_id),+ )+ managed = "SELECT username FROM auth_user WHERE role = 'user'"+ conn.execute(+ f"UPDATE api_keys SET key_hash = ? || key_hash WHERE username IN ({managed}) AND key_hash NOT LIKE ?",+ (_FENCE_PREFIX, _FENCE_PREFIX + "%"),+ )+ conn.execute(+ f"UPDATE refresh_tokens SET token_hash = ? || token_hash WHERE username IN ({managed}) AND token_hash NOT LIKE ?",+ (_FENCE_PREFIX, _FENCE_PREFIX + "%"),+ )+++def get_user_record(username: str) -> Optional[dict]:+ conn = get_connection()+ try:+ row = conn.execute(+ f"""+ SELECT username, {_PASSWORD_SALT_SQL} AS password_salt,+ {_PASSWORD_HASH_SQL} AS password_hash, {_SECRET_SQL} AS jwt_secret,+ must_change_password, account_id, role, is_active+ FROM auth_user WHERE username = ?+ """,+ (username,),+ ).fetchone()+ return dict(row) if row else None+ finally:+ conn.close()+++def get_account(username: str):+ from utils.account_context import AccountContext++ record = get_user_record(username)+ if record is None:+ return None+ return AccountContext(record["account_id"], record["username"], record["role"])+++def get_account_by_id(account_id: str):+ from utils.account_context import AccountContext++ conn = get_connection()+ try:+ row = conn.execute(+ "SELECT account_id, username, role, is_active FROM auth_user WHERE account_id = ?",+ (account_id,),+ ).fetchone()+ finally:+ conn.close()+ if row is None or not row["is_active"]:+ return None+ return AccountContext(row["account_id"], row["username"], row["role"])+++def count_active_accounts() -> int:+ return account_counts()[0]+++def account_counts() -> tuple[int, int]:+ """``(active, managed-of-any-state)``; the second counts deactivated accounts too."""+ conn = get_connection()+ try:+ row = conn.execute(+ """+ SELECT COALESCE(SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END), 0) AS active,+ COALESCE(SUM(CASE WHEN role IS NOT NULL AND role != 'owner' THEN 1 ELSE 0 END), 0) AS managed+ FROM auth_user+ """+ ).fetchone()+ return int(row["active"]), int(row["managed"])+ finally:+ conn.close()+++def validate_account_username(username: str) -> str:+ username = username.casefold()+ if re.fullmatch(r"[a-z0-9_-]{3,32}", username) is None:+ raise ValueError("Username must contain 3 to 32 letters, digits, underscores or hyphens")+ if username in {"unsloth", "owner", "admin", "root", "system"}:+ raise ValueError("This username is reserved")+ return username+++def _public_account(row) -> dict:+ return {+ "account_id": row["account_id"],+ "username": row["username"],+ "role": row["role"],+ "is_active": bool(row["is_active"]),+ "created_at": row["created_at"],+ "setup_code_pending": bool(row["setup_code_hash"]),+ }+++def list_accounts() -> list[dict]:+ conn = get_connection()+ try:+ return [+ _public_account(row)+ for row in conn.execute("SELECT * FROM auth_user ORDER BY created_at, account_id")+ ]+ finally:+ conn.close()+++def _managed_account(conn: sqlite3.Connection, account_id: str):+ row = conn.execute("SELECT * FROM auth_user WHERE account_id = ?", (account_id,)).fetchone()+ if row is None:+ raise LookupError("Account not found")+ if row["role"] == "owner" or account_id == "owner":+ raise ValueError("The installation owner cannot be modified here")+ return row+++def _revoke_account_credentials(conn: sqlite3.Connection, row) -> None:+ # These frozen legacy tables key on username; resolve it from the account id under the same+ # write lock as the mutation.+ conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (row["username"],))+ conn.execute("DELETE FROM api_keys WHERE username = ?", (row["username"],))+ conn.execute("DELETE FROM account_api_keys WHERE account_id = ?", (row["account_id"],))+ conn.execute(+ "UPDATE auth_user SET account_jwt_secret = ? WHERE account_id = ?",+ (secrets.token_urlsafe(64), row["account_id"]),+ )+++def issue_account_setup_code(+ *, username: Optional[str] = None, account_id: Optional[str] = None+) -> dict:+ from auth.hashing import hash_password+ from auth.policy import account_mutation++ if (username is None) == (account_id is None):+ raise ValueError("Specify either a username or an account id")+ if username is not None:+ username = validate_account_username(username)+ code = secrets.token_urlsafe(32)+ salt, pwd_hash = hash_password(code)+ # Before the transaction: a first-run salt creation opens its own connection.+ code_hash = _hash_setup_code(code)+ now = datetime.now(timezone.utc)+ expires_at = (now + timedelta(minutes = 60)).isoformat()+ with account_mutation():+ conn = get_connection()+ try:+ with conn:+ conn.execute("BEGIN IMMEDIATE")+ if username is not None:+ account_id = uuid.uuid4().hex+ legacy_salt, legacy_hash, legacy_secret = _legacy_dummies()+ conn.execute(+ """INSERT INTO auth_user+ (username, account_id, role, is_active, created_at, password_salt,+ password_hash, jwt_secret, account_password_salt, account_password_hash,+ account_jwt_secret, must_change_password, setup_code_hash, setup_code_expires_at)+ VALUES (?, ?, 'user', 1, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)""",+ (+ username,+ account_id,+ now.isoformat(),+ legacy_salt,+ legacy_hash,+ legacy_secret,+ salt,+ pwd_hash,+ secrets.token_urlsafe(64),+ code_hash,+ expires_at,+ ),+ )+ else:+ row = _managed_account(conn, account_id)+ _revoke_account_credentials(conn, row)+ conn.execute(+ """UPDATE auth_user SET account_password_salt = ?, account_password_hash = ?,+ must_change_password = 1, setup_code_hash = ?, setup_code_expires_at = ?+ WHERE account_id = ?""",+ (salt, pwd_hash, code_hash, expires_at, account_id),+ )+ account = _public_account(_managed_account(conn, account_id))+ finally:+ conn.close()+ return {"account": account, "setup_code": code, "setup_code_expires_at": expires_at}+++def authenticate_account_login(+ username: str, password: str+) -> Optional[Tuple[str, str, str, bool]]:+ """Managed login. A setup code is consumed once; must_change_password with no pending code+ admits only the issued session's password change."""+ from auth.hashing import equalize_login_work, verify_password++ def miss():+ # A miss without a hash to check costs what a wrong password costs.+ equalize_login_work(password)+ return None++ conn = get_connection()+ try:+ row = conn.execute(+ f"""SELECT account_id, is_active, must_change_password, setup_code_hash,+ {_PASSWORD_SALT_SQL} AS password_salt, {_PASSWORD_HASH_SQL} AS password_hash,+ {_SECRET_SQL} AS jwt_secret+ FROM auth_user WHERE username = ?""",+ (username,),+ ).fetchone()+ if row is None or not row["is_active"]:+ return miss()+ if row["must_change_password"]:+ # The setup-code hash is the PBKDF2 round a miss would otherwise spend.+ if not row["setup_code_hash"] or not hmac.compare_digest(+ row["setup_code_hash"], _hash_setup_code(password)+ ):+ return None+ # Compare-and-swap on expiry, activity and generation: no code is spent twice.+ with conn:+ cursor = conn.execute(+ f"""UPDATE auth_user SET setup_code_hash = NULL, setup_code_expires_at = NULL+ WHERE account_id = ? AND setup_code_hash = ? AND {_SECRET_SQL} = ?+ AND is_active = 1 AND setup_code_expires_at > ?""",+ (+ row["account_id"],+ row["setup_code_hash"],+ row["jwt_secret"],+ datetime.now(timezone.utc).isoformat(),+ ),+ )+ if cursor.rowcount != 1:+ return None+ elif not verify_password(password, row["password_salt"], row["password_hash"]):+ return None+ return (+ row["password_salt"],+ row["password_hash"],+ row["jwt_secret"],+ bool(row["must_change_password"]),+ )+ finally:+ conn.close()+++def update_account_password(+ username: str, new_password: str, *, expect_password_hash: str, expect_secret: str+) -> Optional[str]:+ from auth.hashing import hash_password++ salt, pwd_hash = hash_password(new_password)+ secret = secrets.token_urlsafe(64)+ conn = get_connection()+ try:+ with conn:+ cursor = conn.execute(+ f"""UPDATE auth_user SET account_password_salt = ?, account_password_hash = ?,+ account_jwt_secret = ?, must_change_password = 0,+ setup_code_hash = NULL, setup_code_expires_at = NULL+ WHERE username = ? AND role = 'user' AND is_active = 1+ AND {_PASSWORD_HASH_SQL} = ? AND {_SECRET_SQL} = ?""",+ (salt, pwd_hash, secret, username, expect_password_hash, expect_secret),+ )+ if cursor.rowcount != 1:+ return None+ conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))+ return secret+ finally:+ conn.close()+++def set_account_active(account_id: str, is_active: bool) -> dict:+ from auth.policy import account_mutation+ with account_mutation():+ conn = get_connection()+ try:+ with conn:+ conn.execute("BEGIN IMMEDIATE")+ row = _managed_account(conn, account_id)+ if not is_active:+ _revoke_account_credentials(conn, row)+ conn.execute(+ "UPDATE auth_user SET is_active = ? WHERE account_id = ?",+ (int(is_active), account_id),+ )+ result = _public_account(_managed_account(conn, account_id))+ finally:+ conn.close()+ return result+++def delete_account(account_id: str, retire) -> None:+ """Revoke, retire files, then drop the identity under a write lock. ``retire()`` must not write+ auth.db under that lock; a failed retire leaves the account disabled for a retry."""+ from auth.policy import account_mutation+ from utils.account_context import AccountContext++ set_account_active(account_id, False)+ with account_mutation():+ conn = get_connection()+ restore_roots = None+ try:+ with conn:+ conn.execute("BEGIN IMMEDIATE")+ row = _managed_account(conn, account_id)+ _revoke_account_credentials(conn, row)+ restore_roots = retire(+ AccountContext(row["account_id"], row["username"], row["role"])+ )+ conn.execute("DELETE FROM auth_user WHERE account_id = ?", (account_id,))+ except Exception:+ # The identity survives the rollback, so the roots must come back too; a failed+ # restore is the error to report, the account staying disabled either way.+ try:+ if restore_roots is not None:+ restore_roots()+ finally:+ # An owner may reactivate between revocation and this lock; stay disabled anyway.+ with contextlib.suppress(sqlite3.Error):+ set_account_active(account_id, False)+ raise+ finally:+ conn.close()++def _get_or_create_api_key_pbkdf2_salt() -> bytes:"""Return the persistent API-key PBKDF2 salt, generating it once if missing. Hex-encoded 32-byterandom value in ``app_secrets``, regenerated only when the row is missing."""@@ -517,6 +1050,11 @@ def _pbkdf2_desktop_secret(raw_secret: str) -> str:return _pbkdf2_api_key(raw_secret)+def _hash_setup_code(code: str) -> str:+ """A setup code is typed where a password goes, so it is stored like an API key."""+ return _pbkdf2_api_key(code)++# Keyed by a salted HMAC, not the key; revocation/expiry are still enforced by the SQLite read, and# only known keys are cached._api_key_hash_cache: dict[str, str] = {}@@ -557,8 +1095,18 @@ def create_initial_user("""Create the initial admin user in the database. Raises sqlite3.IntegrityError if username alreadyexists."""from .hashing import hash_password+ from utils.account_context import OWNER_ACCOUNT_ID, ROLE_OWNER, ROLE_USER+ import uuidsalt, pwd_hash = hash_password(password)+ if username == DEFAULT_ADMIN_USERNAME:+ account_id, role = OWNER_ACCOUNT_ID, ROLE_OWNER+ legacy = (salt, pwd_hash, jwt_secret)+ fenced = (None, None, None)+ else:+ account_id, role = uuid.uuid4().hex, ROLE_USER+ legacy = _legacy_dummies()+ fenced = (salt, pwd_hash, jwt_secret)conn = get_connection()try:conn.execute(@@ -568,15 +1116,32 @@ def create_initial_user(password_salt,password_hash,jwt_secret,- must_change_password+ account_password_salt,+ account_password_hash,+ account_jwt_secret,+ must_change_password,+ account_id,+ role,+ created_at)- VALUES (?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",- (username, salt, pwd_hash, jwt_secret, int(must_change_password)),+ (+ username,+ *legacy,+ *fenced,+ int(must_change_password),+ account_id,+ role,+ datetime.now(timezone.utc).isoformat(),+ ),)conn.commit()finally:conn.close()+ from auth.policy import invalidate_account_cache++ invalidate_account_cache()def delete_user(username: str) -> None:@@ -588,6 +1153,9 @@ def delete_user(username: str) -> None:conn.commit()finally:conn.close()+ from auth.policy import invalidate_account_cache++ invalidate_account_cache()def get_user_and_secret(username: str) -> Optional[Tuple[str, str, str, bool]]:@@ -596,8 +1164,9 @@ def get_user_and_secret(username: str) -> Optional[Tuple[str, str, str, bool]]:conn = get_connection()try:cur = conn.execute(- """- SELECT password_salt, password_hash, jwt_secret, must_change_password+ f"""+ SELECT {_PASSWORD_SALT_SQL} AS password_salt, {_PASSWORD_HASH_SQL} AS password_hash,+ {_SECRET_SQL} AS jwt_secret, must_change_passwordFROM auth_userWHERE username = ?""",@@ -620,7 +1189,7 @@ def get_jwt_secret(username: str) -> Optional[str]:conn = get_connection()try:cur = conn.execute(- "SELECT jwt_secret FROM auth_user WHERE username = ?",+ f"SELECT {_SECRET_SQL} AS jwt_secret FROM auth_user WHERE username = ?",(username,),)row = cur.fetchone()@@ -698,23 +1267,28 @@ def update_password(salt, pwd_hash = hash_password(new_password)jwt_secret = secrets.token_urlsafe(64)+ columns = (+ "password_salt = ?, password_hash = ?, jwt_secret = ?"+ if _is_owner_name(username)+ else "account_password_salt = ?, account_password_hash = ?, account_jwt_secret = ?"+ )conn = get_connection()try:if expect_password_hash is None:cursor = conn.execute(- """+ f"""UPDATE auth_user- SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0+ SET {columns}, must_change_password = 0WHERE username = ?""",(salt, pwd_hash, jwt_secret, username),)else:cursor = conn.execute(- """+ f"""UPDATE auth_user- SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0- WHERE username = ? AND password_hash = ?+ SET {columns}, must_change_password = 0+ WHERE username = ? AND {_PASSWORD_HASH_SQL} = ?""",(salt, pwd_hash, jwt_secret, username, expect_password_hash),)@@ -739,10 +1313,14 @@ def save_refresh_token(is_desktop: bool = False,secret_gen: Optional[str] = None,) -> None:- """Store a hashed refresh token with its associated username and expiry. ``secret_gen`` binds the- token to a credential version; it defaults to the current one, and callers that already verified- a credential must pass the version they verified."""- token_hash = _hash_token(token)+ """+ Store a hashed refresh token with its associated username and expiry.++ ``secret_gen`` binds the token to a credential version; it defaults to the+ current one, and callers that already verified a credential must pass the+ version they verified rather than let this re-read a rotated one.+ """+ token_hash = _fenced_hash(_hash_token(token), username)conn = get_connection()try:if secret_gen is None:@@ -777,12 +1355,12 @@ def consume_refresh_token(token: str) -> Optional[Tuple[str, bool, str]]:(now,),)cur = conn.execute(- """+ f"""DELETE FROM refresh_tokens- WHERE token_hash = ? AND expires_at >= ?+ WHERE token_hash {_FENCED_HASH_SQL} AND expires_at >= ?RETURNING username, is_desktop, secret_gen""",- (token_hash, now),+ (*_hash_candidates(token_hash), now),)row = cur.fetchone()if row is None:@@ -812,11 +1390,11 @@ def verify_refresh_token(token: str) -> Optional[Tuple[str, bool]]:conn.commit()cur = conn.execute(- """+ f"""SELECT id, username, expires_at, is_desktop, secret_gen FROM refresh_tokens- WHERE token_hash = ?+ WHERE token_hash {_FENCED_HASH_SQL}""",- (token_hash,),+ _hash_candidates(token_hash),)row = cur.fetchone()if row is None:@@ -840,11 +1418,20 @@ def verify_refresh_token(token: str) -> Optional[Tuple[str, bool]]:conn.close()-def revoke_user_refresh_tokens(username: str) -> None:+def revoke_user_refresh_tokens(username: str, *, account_id: Optional[str] = None) -> None:+ """Revoke a user's refresh tokens. ``account_id`` pins the username-keyed table to the+ immutable identity, so a recreated namesake keeps its sessions."""conn = get_connection()try:- conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))- conn.commit()+ with conn:+ conn.execute("BEGIN IMMEDIATE")+ if account_id is not None:+ row = conn.execute(+ "SELECT username FROM auth_user WHERE account_id = ?", (account_id,)+ ).fetchone()+ if row is None or row["username"] != username:+ return+ conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))finally:conn.close()@@ -928,6 +1515,7 @@ def create_api_key(expires_at: Optional[str] = None,internal: bool = False,expect_gen: Optional[str] = None,+ account_id: Optional[str] = None,) -> Tuple[str, dict]:"""Create a new API key for *username*. Returns ``(raw_key, row_dict)`` where *raw_key* is shown tothe user exactly once; the database only stores the PBKDF2 hash. Pass ``internal=True`` for keys@@ -936,7 +1524,7 @@ def create_api_key(concurrent password reset cannot mint a key that outlives it. Raises ``CredentialRotated`` if itmoved."""raw_key = API_KEY_PREFIX + secrets.token_hex(16)- key_hash = _pbkdf2_api_key(raw_key)+ key_hash = _fenced_hash(_pbkdf2_api_key(raw_key), username)key_prefix = raw_key[len(API_KEY_PREFIX) : len(API_KEY_PREFIX) + 8]now = datetime.now(timezone.utc).isoformat()@@ -948,10 +1536,12 @@ def create_api_key(raise CredentialRotated("The credential this request authenticated with was revoked.")+ if account_id is None:+ account_id = _managed_account_id(conn, username)conn.execute("""- INSERT INTO api_keys (username, key_prefix, key_hash, name, created_at, expires_at, is_internal)- VALUES (?, ?, ?, ?, ?, ?, ?)+ INSERT INTO api_keys (username, key_prefix, key_hash, name, created_at, expires_at, is_internal, account_id)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",(username,@@ -961,8 +1551,15 @@ def create_api_key(now,expires_at,1 if internal else 0,+ account_id,),)+ if account_id is not None:+ conn.execute(+ f"""INSERT INTO account_api_keys ({_ACCOUNT_API_KEY_COLUMNS})+ SELECT {_ACCOUNT_API_KEY_COLUMNS} FROM api_keys WHERE key_hash = ?""",+ (key_hash,),+ )conn.commit()cur = conn.execute("SELECT * FROM api_keys WHERE key_hash = ?", (key_hash,))row = cur.fetchone()@@ -971,46 +1568,68 @@ def create_api_key(conn.close()-def list_api_keys(username: str, include_internal: bool = False) -> list:- """Return API keys for *username*. Internal workflow keys are hidden- by default so they do not clutter user-facing UIs."""+def list_api_keys(+ username: str,+ include_internal: bool = False,+ account_id: Optional[str] = None,+) -> list:conn = get_connection()try:- if include_internal:- cur = conn.execute(- """- SELECT id, username, key_prefix, name, created_at, last_used_at,- expires_at, is_active, is_internal- FROM api_keys- WHERE username = ?- ORDER BY created_at DESC- """,- (username,),- )- else:- cur = conn.execute(- """- SELECT id, username, key_prefix, name, created_at, last_used_at,- expires_at, is_active, is_internal- FROM api_keys- WHERE username = ? AND is_internal = 0- ORDER BY created_at DESC- """,- (username,),- )+ scope, params = _key_scope(username, account_id)+ internal = "" if include_internal else " AND is_internal = 0"+ cur = conn.execute(+ f"""+ SELECT id, username, key_prefix, name, created_at, last_used_at,+ expires_at, is_active, is_internal+ FROM api_keys+ WHERE {scope}{internal}+ ORDER BY created_at DESC+ """,+ params,+ )return [dict(row) for row in cur.fetchall()]finally:conn.close()-def revoke_api_key(username: str, key_id: int) -> bool:+def _managed_account_id(conn: sqlite3.Connection, username: str) -> Optional[str]:+ row = conn.execute(+ "SELECT account_id, role FROM auth_user WHERE username = ?", (username,)+ ).fetchone()+ if row is None or row["role"] in (None, "owner"):+ return None+ return row["account_id"]+++def _revoke_key_copy(conn: sqlite3.Connection, key_id: int) -> None:+ conn.execute(+ "UPDATE account_api_keys SET is_active = 0 "+ "WHERE key_hash = (SELECT key_hash FROM api_keys WHERE id = ?)",+ (key_id,),+ )+++def _key_scope(username: str, account_id: Optional[str]) -> Tuple[str, tuple]:+ if account_id is None:+ return "username = ?", (username,)+ return "username = ? AND account_id = ?", (username, account_id)+++def revoke_api_key(+ username: str,+ key_id: int,+ account_id: Optional[str] = None,+) -> bool:"""Soft-delete an API key. Returns True if a matching row was found."""conn = get_connection()try:+ scope, params = _key_scope(username, account_id)cursor = conn.execute(- "UPDATE api_keys SET is_active = 0 WHERE id = ? AND username = ?",- (key_id, username),+ f"UPDATE api_keys SET is_active = 0 WHERE id = ? AND {scope}",+ (key_id, *params),)+ if cursor.rowcount:+ _revoke_key_copy(conn, key_id)conn.commit()return cursor.rowcount > 0finally:@@ -1026,6 +1645,8 @@ def revoke_internal_api_key(key_id: int) -> bool:"UPDATE api_keys SET is_active = 0 WHERE id = ? AND is_internal = 1",(key_id,),)+ if cursor.rowcount:+ _revoke_key_copy(conn, key_id)conn.commit()return cursor.rowcount > 0finally:@@ -1048,7 +1669,8 @@ def is_internal_api_key(raw_key: str) -> bool:conn = get_connection()try:row = conn.execute(- "SELECT is_internal FROM api_keys WHERE key_hash = ?", (key_hash,)+ f"SELECT is_internal FROM api_keys WHERE key_hash {_FENCED_HASH_SQL}",+ _hash_candidates(key_hash),).fetchone()finally:conn.close()@@ -1081,8 +1703,8 @@ def internal_api_key_name(raw_key: str) -> Optional[str]:conn = get_connection()try:row = conn.execute(- "SELECT name FROM api_keys WHERE key_hash = ? AND is_internal = 1 AND is_active = 1",- (key_hash,),+ f"SELECT name FROM api_keys WHERE key_hash {_FENCED_HASH_SQL} AND is_internal = 1 AND is_active = 1",+ _hash_candidates(key_hash),).fetchone()finally:conn.close()@@ -1100,12 +1722,13 @@ def validate_api_key(raw_key: str) -> Optional[str]:def validate_api_key_with_credential(raw_key: str, *, touch: bool = True) -> Optional[Tuple[str, str]]:- """Validate *raw_key* and return ``(username, jwt_secret)``, or ``None``. Also updates- ``last_used_at`` on success. The key check and the credential read share one write transaction,- so the returned version is the one the key was actually valid under. ``touch=False`` drops that- stamp, and with it the write transaction, for a caller that only asks whether the key- authenticates: one request must not count as two uses, and on sqlite the write lock is global,- so an advisory check has no business taking it."""+ verified = validate_api_key_account(raw_key, touch = touch)+ return (verified[0]["username"], verified[1]) if verified else None+++def validate_api_key_account(raw_key: str, *, touch: bool = True) -> Optional[Tuple[dict, str]]:+ """Validate *raw_key* -> ``(account record, jwt_secret)``, or ``None``. The record comes from+ the matching statement, so a namesake cannot bind; ``touch=False`` skips the last-used write."""cache_id = _api_key_cache_id(raw_key)cached_hash = _api_key_hash_cache.get(cache_id)key_hash = cached_hash if cached_hash is not None else _pbkdf2_api_key(raw_key)@@ -1114,8 +1737,15 @@ def validate_api_key_with_credential(if touch:conn.execute("BEGIN IMMEDIATE")cur = conn.execute(- "SELECT id, username, is_active, expires_at FROM api_keys WHERE key_hash = ?",- (key_hash,),+ f"""+ SELECT k.id, k.username, k.is_active, k.expires_at,+ u.account_id, u.role, u.is_active AS account_active,+ COALESCE(u.account_jwt_secret, u.jwt_secret) AS jwt_secret+ FROM api_keys k JOIN auth_user u ON u.username = k.username+ AND (k.account_id = u.account_id OR (k.account_id IS NULL AND u.role = 'owner'))+ WHERE k.key_hash {_FENCED_HASH_SQL}+ """,+ _hash_candidates(key_hash),)row = cur.fetchone()if row is None:@@ -1135,7 +1765,9 @@ def validate_api_key_with_credential(expires = datetime.fromisoformat(row["expires_at"])if datetime.now(timezone.utc) > expires:return None- secret = _current_secret(conn, row["username"])+ if not row["account_active"]:+ return None+ secret = row["jwt_secret"]if secret is None:return Noneif touch:@@ -1144,7 +1776,13 @@ def validate_api_key_with_credential((datetime.now(timezone.utc).isoformat(), row["id"]),)conn.commit()- return row["username"], secret+ record = {+ "account_id": row["account_id"],+ "username": row["username"],+ "role": row["role"],+ "is_active": int(row["account_active"]),+ }+ return record, secretfinally:conn.rollback()conn.close()diff --git a/studio/backend/core/data_recipe/huggingface.py b/studio/backend/core/data_recipe/huggingface.pyindex 7a1219b2c32..e02f06875f3 100644--- a/studio/backend/core/data_recipe/huggingface.py+++ b/studio/backend/core/data_recipe/huggingface.py@@ -3,6 +3,7 @@from __future__ import annotations+from core.training.account_jobs import account_hf_tokenimport jsonfrom pathlib import Path@@ -49,6 +50,7 @@ def publish_recipe_dataset(hf_token: str | None = None,private: bool = False,) -> str:+ hf_token = account_hf_token(hf_token)dataset_path = _resolve_recipe_artifact_path(artifact_path)try:diff --git a/studio/backend/core/data_recipe/jobs/manager.py b/studio/backend/core/data_recipe/jobs/manager.pyindex 3a2e33b3e56..ff8cbab2501 100644--- a/studio/backend/core/data_recipe/jobs/manager.py+++ b/studio/backend/core/data_recipe/jobs/manager.py@@ -3,6 +3,18 @@from __future__ import annotations+from core.training.account_jobs import (+ account_process_spec,+ init_job_owner,+ job_busy,+ job_control,+ job_pump,+ job_read,+ owned_job,+ validate_recipe_access,+ worker_alive,+)+from utils.account_context import account_threadimport asyncioimport jsonimport queue@@ -116,6 +128,12 @@ class Subscription:class JobManager:def __init__(self) -> None:"""Single-job runner (in-mem). Simple on purpose, not a whole platform."""+ init_job_owner(+ self,+ lambda: worker_alive(self),+ lambda: self.cancel(self._job.job_id) if self._job else None,+ self._clear_account_result,+ )self._lock = threading.Lock()self._job: Job | None = Noneself._proc: mp.Process | None = None@@ -125,6 +143,13 @@ class JobManager:self._pump_thread: threading.Thread | None = Noneself._seq: int = 0+ def _clear_account_result(self):+ self._job = None+ self._events.clear()+ # Old subscribers retain their private queues but never receive a successor's events.+ self._subs.clear()++ @owned_job()def start(self,*,@@ -138,6 +163,7 @@ class JobManager:minted by the route layer; revoked on terminal state so the key'slive window is no longer than the run."""+ validate_recipe_access(recipe)llm_columns = recipe.get("columns") or []llm_column_count = 0if isinstance(llm_columns, list):@@ -177,10 +203,16 @@ class JobManager:native_path_secret_removed_for_child_start(),):mp_q = _CTX.Queue()+ process_args, process_kwargs = account_process_spec(+ "core.data_recipe.jobs.worker",+ "run_job_process",+ cache_env,+ {"event_queue": mp_q, "recipe": recipe, "run": run_payload},+ )proc = _CTX.Process(target = run_without_native_path_secret,- args = ("core.data_recipe.jobs.worker", "run_job_process", cache_env),- kwargs = {"event_queue": mp_q, "recipe": recipe, "run": run_payload},+ args = process_args,+ kwargs = process_kwargs,daemon = True,)proc.start()@@ -190,12 +222,13 @@ class JobManager:self._mp_q = mp_qself._proc = proc- self._pump_thread = threading.Thread(target = self._pump_loop, daemon = True)+ self._pump_thread = account_thread(target = self._pump_loop, daemon = True)self._pump_thread.start()self._emit({"type": EVENT_JOB_ENQUEUED, "ts": time.time(), "job_id": job_id})return job_id+ @job_controldef cancel(self, job_id: str) -> bool:"""Hard stop. We terminate the subprocess. Quick + reliable."""with self._lock:@@ -211,6 +244,7 @@ class JobManager:passreturn True+ @job_read(lambda self, *args, **kwargs: None)def get_status(self, job_id: str) -> dict | None:"""UI-friendly structured snapshot; an alternative to SSE."""with self._lock:@@ -272,6 +306,7 @@ class JobManager:"finished_at": job.finished_at,}+ @job_read(lambda self: {"status": "busy" if job_busy(self) else "idle"})def get_current_status(self) -> dict | None:"""Single-job convenience (last/current)."""job_id = self.get_current_job_id()@@ -279,10 +314,12 @@ class JobManager:return Nonereturn self.get_status(job_id)+ @job_read(lambda self, *args, **kwargs: None)def get_current_job_id(self) -> str | None:with self._lock:return None if self._job is None else self._job.job_id+ @job_read(lambda self, *args, **kwargs: None)def get_analysis(self, job_id: str) -> dict | None:"""Final profiling output (only after job completes)."""with self._lock:@@ -290,6 +327,7 @@ class JobManager:return Nonereturn self._job.analysis+ @job_read(lambda self, *args, **kwargs: None)def get_dataset(self,job_id: str,@@ -389,6 +427,7 @@ class JobManager:rows = dataframe.iloc[offset : offset + limit].to_dict(orient = "records")return {"dataset": to_preview_jsonable(rows), "total": total}+ @job_read(lambda self, *args, **kwargs: None)def subscribe(self,job_id: str,@@ -468,6 +507,7 @@ class JobManager:etype = event.get("type") if isinstance(event, dict) else type(event).__name__logger.exception("Data-recipe job pump: failed to handle %s event; skipping", etype)+ @job_pumpdef _pump_loop(self) -> None:"""Background thread: consume worker events and update the job snapshot.diff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.pyindex 9ffc8282e96..5a6373d1b65 100644--- a/studio/backend/core/data_recipe/jobs/worker.py+++ b/studio/backend/core/data_recipe/jobs/worker.py@@ -17,7 +17,8 @@ from typing import Anyfrom ..jsonable import to_jsonable, to_preview_jsonablefrom .constants import EVENT_JOB_COMPLETED, EVENT_JOB_ERROR, EVENT_JOB_STARTED-from ..service import build_config_builder, create_data_designer+from ..service import build_config_builder, create_data_designer, install_public_egress_guard+from utils.paths.lazy import LazyPathfrom utils.paths import ensure_dir, recipe_datasets_root# Fresh spawned interpreter: re-apply main.py's OS-trust-store injection.@@ -26,7 +27,7 @@ from utils.paths.path_utils import drop_appledouble_metadataactivate_native_tls()-_ARTIFACT_ROOT = recipe_datasets_root()+_ARTIFACT_ROOT = LazyPath(recipe_datasets_root)_RE_GITHUB_CURSOR = re.compile(r"\bcursor=[^\s,]+")_RE_SECRET_TOKEN = re.compile(r"\b(?:(?:ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]+|sk-unsloth-[A-Za-z0-9]+)"@@ -82,6 +83,7 @@ def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any])"""Subprocess entrypoint. Sends events to `event_queue`."""import os+ install_public_egress_guard()os.environ["PYTHONWARNINGS"] = "ignore"import warningsdiff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.pyindex fc96427757d..cce87bb17d3 100644--- a/studio/backend/core/data_recipe/service.py+++ b/studio/backend/core/data_recipe/service.py@@ -3,12 +3,15 @@from __future__ import annotations+from core.training.account_jobs import account_path, managed_account, validate_recipe_accessimport base64import ioimport osfrom pathlib import Pathfrom typing import Any+from fastapi import HTTPException+from utils.paths import recipe_datasets_rootfrom .jsonable import to_jsonable@@ -25,6 +28,11 @@ def _encode_bytes_to_base64(value: bytes | bytearray) -> str:def _load_image_file_to_base64(path_value: str, *, base_path: str | None = None) -> str | None:+ account_path(+ Path(base_path) / path_value+ if base_path and not Path(path_value).is_absolute()+ else path_value+ )try:path = Path(path_value)candidates: list[Path] = []@@ -128,14 +136,63 @@ def _apply_data_designer_image_context_patch() -> None:_IMAGE_CONTEXT_PATCHED = True+def _require_public_provider_endpoint(endpoint: str) -> None:+ """The recipe engine dials providers itself, so a managed account's endpoint cannot use the pinned+ transport: require HTTPS, which binds the peer to its certificate rather than to a DNS answer that+ may rebind to loopback or the LAN after this public-address check."""+ if not managed_account():+ return+ from urllib.parse import urlsplit++ from core.inference.providers import public_provider_address++ url = str(endpoint or "")+ try:+ if urlsplit(url).scheme != "https":+ raise ValueError("Managed accounts may only use HTTPS provider endpoints.")+ public_provider_address(url)+ except ValueError as exc:+ raise HTTPException(+ status_code = 403, detail = f"Recipe provider endpoint refused: {exc}"+ ) from exc+++def install_public_egress_guard() -> None:+ """Managed recipe workers: the engine dials providers itself, so every name resolves through this+ guard and a host that rebinds to loopback or the LAN after the endpoint check is refused at connect+ time rather than dialled. Process-wide, so it is installed only in the job subprocess."""+ if not managed_account():+ return+ import ipaddress+ import socket++ resolve = socket.getaddrinfo++ def guarded_getaddrinfo(host, port, *args, **kwargs):+ infos = resolve(host, port, *args, **kwargs)+ for info in infos:+ if not ipaddress.ip_address(str(info[4][0]).split("%", 1)[0]).is_global:+ raise socket.gaierror(+ f"Managed accounts may only reach public-network addresses: {host!r}"+ )+ return infos++ def guarded_gethostbyname(host):+ return str(guarded_getaddrinfo(host, None, socket.AF_INET)[0][4][0])++ socket.getaddrinfo = guarded_getaddrinfo+ socket.gethostbyname = guarded_gethostbyname++def build_model_providers(recipe: dict[str, Any]):from data_designer.config.models import ModelProvider # pyright: ignore[reportMissingImports]providers: list[ModelProvider] = []for provider in recipe.get("model_providers", []):+ _require_public_provider_endpoint(provider.get("endpoint"))api_key = provider.get("api_key")api_key_env = provider.get("api_key_env")- if not api_key and api_key_env:+ if not api_key and api_key_env and not managed_account():api_key = os.getenv(api_key_env)providers.append(ModelProvider(@@ -178,6 +235,19 @@ def recipe_has_stdio_mcp(recipe: dict[str, Any]) -> bool:)+def _require_confinable_mcp_transport(provider_type: str) -> None:+ """Refuse network MCP for managed accounts: the engine opens its own connections and cannot use chat's confined transport."""+ if provider_type not in {"sse", "streamable_http"} or not managed_account():+ return+ raise HTTPException(+ status_code = 403,+ detail = (+ "Recipe MCP servers are unavailable for managed accounts until the recipe "+ "engine uses the account-confined MCP transport."+ ),+ )++def build_mcp_providers(recipe: dict[str, Any]) -> list:from data_designer.config.mcp import LocalStdioMCPProvider, MCPProvider # pyright: ignore[reportMissingImports]@@ -212,9 +282,10 @@ def build_mcp_providers(recipe: dict[str, Any]) -> list:continueif provider_type in {"sse", "streamable_http"}:+ _require_confinable_mcp_transport(provider_type)api_key = provider.get("api_key")api_key_env = provider.get("api_key_env")- if not api_key and api_key_env:+ if not api_key and api_key_env and not managed_account():api_key = os.getenv(str(api_key_env))providers.append(MCPProvider(@@ -253,6 +324,7 @@ def _strip_frontend_model_config_metadata(recipe: dict[str, Any]) -> dict[str, Adef build_config_builder(recipe: dict[str, Any]):+ validate_recipe_access(recipe)_apply_data_designer_image_context_patch()from data_designer.config import DataDesignerConfigBuilder # pyright: ignore[reportMissingImports]from data_designer.config.processors import ProcessorType # pyright: ignore[reportMissingImports]@@ -288,6 +360,8 @@ def build_config_builder(recipe: dict[str, Any]):def create_data_designer(recipe: dict[str, Any], *, artifact_path: str | None = None):+ validate_recipe_access(recipe)+ account_path(artifact_path)_apply_data_designer_image_context_patch()from data_designer.interface.data_designer import DataDesigner # pyright: ignore[reportMissingImports]diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 5b78717be59..e77e2a96133 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -491,11 +491,17 @@ class ExportBackend:return Falsedef scan_checkpoints(- self, outputs_dir: str = str(outputs_root())+ self, outputs_dir: Optional[str] = None) -> List[Tuple[str, List[Tuple[str, str]]]]:- """Scan the outputs folder for training runs and their checkpoints, as [(model_name,- [(display_name, checkpoint_path), ...]), ...]."""+ """+ Scan outputs folder for training runs and their checkpoints.++ Returns: [(model_name, [(display_name, checkpoint_path), ...]), ...]+ """+ if outputs_dir is None:+ outputs_dir = str(outputs_root())from utils.models.checkpoints import scan_checkpoints+return scan_checkpoints(outputs_dir = outputs_dir)def load_checkpoint(@@ -506,9 +512,12 @@ class ExportBackend:trust_remote_code: bool = False,hf_token: HfTokenArg = None,_device_map_override: Optional[dict] = None,+ base_model: Optional[str] = None,) -> Tuple[bool, str]:"""Load a checkpoint for export.+ ``base_model`` is the caller's authorized adapter base; it wins over adapter_config.json.+``hf_token`` authenticates the actual weight load for gated/private checkpoints, matchingthe token the worker used for the security preflight (otherwise a gated repo passes scanningthen 401s at from_pretrained).@@ -529,11 +538,12 @@ class ExportBackend:checkpoint_path_obj = Path(checkpoint_path)adapter_config = checkpoint_path_obj / "adapter_config.json"- base_model = Noneif adapter_config.exists():- base_model = get_base_model_from_lora(checkpoint_path)+ base_model = base_model or get_base_model_from_lora(checkpoint_path)if not base_model:return False, "Could not determine base model for adapter"+ else:+ base_model = Nonemodel_id = base_model or checkpoint_pathdiff --git a/studio/backend/core/export/orchestrator.py b/studio/backend/core/export/orchestrator.pyindex e4f893a921a..97953a42f3c 100644--- a/studio/backend/core/export/orchestrator.py+++ b/studio/backend/core/export/orchestrator.py@@ -6,6 +6,14 @@ subprocess spawned on first checkpoint load and reused for later exports. Switchcheckpoints that need different transformers versions kills the old subprocess and spawns a newone. Pattern follows core/inference/orchestrator.py."""+from core.training.account_jobs import (+ account_process_spec,+ init_job_owner,+ job_control,+ job_read,+ owned_job,+ validate_job_paths,+)import atexitimport structlogfrom collections import deque@@ -40,6 +48,7 @@ class ExportOrchestrator:routes/export.py needs minimal changes."""def __init__(self):+ init_job_owner(self, self.is_export_active, self.cancel_export, self._clear_account_result)self._proc: Optional[mp.Process] = Noneself._cmd_queue: Any = Noneself._resp_queue: Any = None@@ -73,6 +82,14 @@ class ExportOrchestrator:atexit.register(self._cleanup)logger.info("ExportOrchestrator initialized (subprocess mode)")+ # ------------------------------------------------------------------++ def _clear_account_result(self):+ self.current_checkpoint = None+ self.is_vision = self.is_peft = False+ self._last_op = None+ self.clear_logs()+def _append_log(self, entry: Dict[str, Any]) -> None:line = entry.get("line")if not line:@@ -98,6 +115,7 @@ class ExportOrchestrator:self._log_buffer.clear()self._run_start_seq = self._log_seq+ @job_read(lambda self, cursor: ([], cursor))def get_logs_since(self, cursor: int) -> Tuple[List[Dict[str, Any]], int]:with self._log_lock:new_entries = [entry for entry in self._log_buffer if entry["seq"] > cursor]@@ -105,10 +123,12 @@ class ExportOrchestrator:return new_entries, new_entries[-1]["seq"]return [], cursor+ @job_read(lambda self: 0)def get_current_log_seq(self) -> int:with self._log_lock:return self._log_seq+ @job_read(lambda self: 0)def get_run_start_seq(self) -> int:with self._log_lock:return self._run_start_seq@@ -141,13 +161,16 @@ class ExportOrchestrator:"error": None if success else (message or None),}+ @job_read(lambda self: None)def get_last_op(self) -> Optional[Dict[str, Any]]:with self._op_lock:return dict(self._last_op) if self._last_op is not None else None+ @job_read(lambda self: None)def get_active_op_kind(self) -> Optional[str]:return self._active_op_kind+ @job_controldef cancel_export(self) -> bool:"""Terminate the in-flight export subprocess immediately.@@ -221,18 +244,24 @@ class ExportOrchestrator:self._cmd_queue = _CTX.Queue()self._resp_queue = _CTX.Queue()+ process_args, process_kwargs = account_process_spec(+ "core.export.worker",+ "run_export_process",+ cache_env,+ {+ "cmd_queue": self._cmd_queue,+ "resp_queue": self._resp_queue,+ "config": config,+ },+ )# Kept in a local as well as on self: a concurrent _shutdown_subprocess can# see a process that has not finished starting, decide it is not alive and# clear self._proc, and every read below would then be off a None while the# worker is alive and unadopted._spawned_proc = _CTX.Process(target = run_without_native_path_secret,- args = ("core.export.worker", "run_export_process", cache_env),- kwargs = {- "cmd_queue": self._cmd_queue,- "resp_queue": self._resp_queue,- "config": config,- },+ args = process_args,+ kwargs = process_kwargs,daemon = True,)self._proc = _spawned_proc@@ -434,6 +463,9 @@ class ExportOrchestrator:except (EOFError, OSError, ValueError):return events+ # ------------------------------------------------------------------++ @owned_job()def load_checkpoint(self,checkpoint_path: str,@@ -444,13 +476,18 @@ class ExportOrchestrator:hf_token: HfTokenArg = None,allow_ambient: bool = True,subject: Optional[str] = None,+ base_model: Optional[str] = None,) -> Tuple[bool, str]:"""Load a checkpoint for export.Always spawns a fresh subprocess to ensure a clean Python interpreter.+ ``base_model`` pins an already authorized adapter base; the worker then ignores the+ adapter config, which its owner can rewrite after the check."""+ validate_job_paths({"checkpoint_path": checkpoint_path})sub_config = {"checkpoint_path": checkpoint_path,+ "base_model": base_model,"max_seq_length": max_seq_length,"load_in_4bit": load_in_4bit,"trust_remote_code": trust_remote_code,@@ -627,12 +664,14 @@ class ExportOrchestrator:},)+ @owned_job(continuation = True)def _run_export(self, export_type: str, params: dict) -> Tuple[bool, str, Optional[str]]:"""Send an export command and wait for the result.Returns ``(success, message, output_path)``. ``output_path`` is the on-diskdir the worker wrote to (None if it only pushed to Hub or failed pre-write)."""+ validate_job_paths(params)with self._lock:if not self._ensure_subprocess_alive():return (@@ -682,6 +721,7 @@ class ExportOrchestrator:self._active_op_kind = Noneself._export_active = False+ @job_controldef cleanup_memory(self) -> bool:with self._lock:if not self._ensure_subprocess_alive():@@ -716,9 +756,12 @@ class ExportOrchestrator:self._active_op_kind = Noneself._export_active = False- def scan_checkpoints(self, outputs_dir: str = str(outputs_root())) -> List[Tuple[str, list]]:+ def scan_checkpoints(self, outputs_dir: Optional[str] = None) -> List[Tuple[str, list]]:"""Scan for checkpoints — runs locally, no ML imports."""+ outputs_dir = outputs_dir if outputs_dir is not None else str(outputs_root())+ validate_job_paths({"output_dir": outputs_dir})from utils.models.checkpoints import scan_checkpoints+return scan_checkpoints(outputs_dir = outputs_dir)diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.pyindex d5a27512014..2771d2e2f3d 100644--- a/studio/backend/core/export/worker.py+++ b/studio/backend/core/export/worker.py@@ -13,6 +13,7 @@ Pattern follows core/inference/worker.py and core/training/worker.py.from __future__ import annotations+from utils.account_context import account_threadimport contextlibimport errnoimport structlog@@ -148,13 +149,13 @@ def _setup_log_capture(resp_queue: Any) -> None:except Exception:pass- t_out = threading.Thread(+ t_out = account_thread(target = _reader,args = (r_out, "stdout", saved_out_fd),daemon = True,name = "export-log-stdout",)- t_err = threading.Thread(+ t_err = account_thread(target = _reader,args = (r_err, "stderr", saved_err_fd),daemon = True,@@ -257,6 +258,7 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:checkpoint_path,)trust_remote_code = cmd.get("trust_remote_code", False)+ base_model = cmd.get("base_model") or None# Auto-enable trust_remote_code for NemotronH/Nano models.if not trust_remote_code:@@ -288,7 +290,7 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:from utils.models.model_config import get_base_model_from_lora_identifier# Resolve a LOCAL or REMOTE adapter's base so a remote LoRA base is gated too.- _base = get_base_model_from_lora_identifier(checkpoint_path, hf_token)+ _base = base_model or get_base_model_from_lora_identifier(checkpoint_path, hf_token)if _base:requested_security_targets.append(_base)except Exception as exc:@@ -373,6 +375,7 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:load_in_4bit = load_in_4bit,trust_remote_code = trust_remote_code,hf_token = hf_token,+ base_model = base_model,)_send_response(diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.pyindex 6a90c1d8f39..d27d92bd092 100644--- a/studio/backend/core/inference/api_monitor.py+++ b/studio/backend/core/inference/api_monitor.py@@ -17,6 +17,7 @@ from collections import dequefrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Optional+from utils.account_context import current_account_idfrom storage.api_usage_db import (MAX_ENDPOINT_CHARS,MAX_STATUS_CHARS,@@ -175,6 +176,8 @@ class ApiMonitorEntry:updated_at: float# Who this row is attributed to; on a shared row it does not restrict visibility.subject: Optional[str] = None+ # Usernames are reusable and these in-memory rows outlive the account, so the immutable account id fences a replacement off its predecessor's traffic.+ account_id: str = field(default_factory = current_account_id)# True for sk-unsloth callers only: the panel auto-opens on these, not Unsloth's chat.via_api_key: bool = False# Monotonic anchors so duration math survives wall-clock steps (NTP).@@ -304,7 +307,7 @@ class ApiMonitor:):self._entries: deque[ApiMonitorEntry] = deque()# Shared rows one subject cleared: deleting would erase another caller's history.- self._hidden_shared: dict[str, set[str]] = {}+ self._hidden_shared: dict[tuple[str, str], set[str]] = {}self._max_entries = max(0, max_entries)self._lock = threading.Lock()self._callback_condition = threading.Condition(self._lock)@@ -951,7 +954,7 @@ class ApiMonitor:for entry in self._entriesif entry.status == "running"and entry.kind != "lifecycle"- and (subject is None or entry.subject == subject)+ and self._attributed(entry, subject))def clear(self, *, subject: Optional[str] = None) -> None:@@ -967,7 +970,7 @@ class ApiMonitor:self._hidden_shared.clear()return# A running shared row is a load in progress, not history, so it stays.- hidden = self._hidden_shared.setdefault(subject, set())+ hidden = self._hidden_shared.setdefault((current_account_id(), subject), set())for entry in self._entries:if entry.shared and entry.status != "running":hidden.add(entry.id)@@ -977,7 +980,7 @@ class ApiMonitor:self._entries = deque(entryfor entry in self._entries- if entry.shared or entry.subject != subject or entry.status == "running"+ if entry.shared or not self._attributed(entry, subject) or entry.status == "running")def _visible(self, entry: ApiMonitorEntry, subject: Optional[str]) -> bool:@@ -985,8 +988,10 @@ class ApiMonitor:return Trueif entry.shared:# Every subject minus the cleared ones. Before ownership, so a clear hides own rows.- return entry.id not in self._hidden_shared.get(subject, ())- return entry.subject == subject+ if entry.id in self._hidden_shared.get((current_account_id(), subject), ()):+ return False+ return _lifecycle_row_visible_to_caller(entry, subject)+ return entry.subject == subject and entry.account_id == current_account_id()def _attributed(self, entry: ApiMonitorEntry, subject: Optional[str]) -> bool:"""Whether *subject* is the caller this row's API traffic belongs to.@@ -996,7 +1001,7 @@ class ApiMonitor:"""if subject is None:return True- return entry.subject == subject+ return entry.subject == subject and entry.account_id == current_account_id()def _find_locked(self, entry_id: str) -> Optional[ApiMonitorEntry]:for entry in self._entries:@@ -1017,10 +1022,23 @@ class ApiMonitor:self._entries = kept# Keep hidden sets to live rows so they stay bounded by the ring buffer.live = {entry.id for entry in kept}- for subject, hidden in list(self._hidden_shared.items()):+ for key, hidden in list(self._hidden_shared.items()):hidden &= liveif not hidden:- del self._hidden_shared[subject]+ del self._hidden_shared[key]api_monitor = ApiMonitor(enabled = not _api_monitor_disabled())+++def _lifecycle_row_visible_to_caller(entry: "ApiMonitorEntry", subject: str) -> bool:+ """Lifecycle rows name a model path that may sit inside the loading account's workspace, so only the owner and that account see them."""+ if entry.kind != "lifecycle":+ return True+ if entry.account_id == current_account_id() and entry.subject in (None, subject):+ return True+ from utils.account_context import is_owner_context++ if is_owner_context():+ return True+ return Falsediff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.pyindex 18a6b1206ae..0ee9e0cae1a 100644--- a/studio/backend/core/inference/audio_gallery.py+++ b/studio/backend/core/inference/audio_gallery.py@@ -3,7 +3,7 @@"""Disk-backed persistence for generated TTS audio clips.-Each clip is a pair under ``studio_root()/audio``: ``{id}.wav`` holds the bytes and+Each clip is a pair under ``workspace_root()/audio``: ``{id}.wav`` holds the bytes and``{id}.json`` the recipe (a WAV has no portable text chunk). A lone file is not avalid record. Dumb storage: the route owns the schema, this reads, writes and sorts."""@@ -20,7 +20,9 @@ from typing import Any, Optionalfrom core.inference import gallery_flagsfrom loggers import get_logger-from utils.paths import ensure_dir, studio_root+from utils.account_context import is_owner_context+from utils.paths import ensure_account_dir, ensure_dir, studio_root+from utils.paths.storage_roots import account_pathlogger = get_logger(__name__)@@ -29,7 +31,9 @@ _ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")def gallery_dir() -> Path:- return ensure_dir(studio_root() / "audio")+ if is_owner_context():+ return ensure_dir(studio_root() / "audio")+ return ensure_account_dir(account_path("audio"))def save(wav_bytes: bytes, meta: dict[str, Any]) -> dict[str, Any]:diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.pyindex 9ca261f12ca..ffd240adacf 100644--- a/studio/backend/core/inference/chat_generation_runs.py+++ b/studio/backend/core/inference/chat_generation_runs.py@@ -17,6 +17,8 @@ from typing import Any, AsyncIteratorfrom starlette.requests import Requestfrom core.inference.llama_keepwarm import InferenceActivityReservation+from core.training.account_jobs import sweepable_job_accounts+from utils.account_context import run_asfrom loggers import get_loggerfrom models.inference import ChatCompletionRequestfrom state import active_generations@@ -187,6 +189,16 @@ async def _sweep_in_daemon_thread(fn, /, *args, **kwargs):return await future+def _run_id_held_by_another_account(account: Any, run_id: str) -> bool:+ """Client-chosen ids are per account but the supervisor keys by bare id, so a live+ registration under another account is theirs. No registration still cancels."""+ account_id = getattr(account, "account_id", None)+ return any(+ entry.get("run_id") == run_id and entry.get("account_id") != account_id+ for entry in active_generations.snapshot()+ )++class ChatGenerationLeaseSweeper:"""Periodically settle durable runs whose progress lease has expired.@@ -261,15 +273,23 @@ class ChatGenerationLeaseSweeper:async def sweep_once(self) -> list[str]:if not self.enabled:return []- settled = await _sweep_in_daemon_thread(- db.reconcile_runs,- error = _LEASE_ERROR,- stale_after_ms = int(self._timeout * 1000),- )+ settled: list[tuple[Any, str]] = []+ # Deactivated accounts too: their wedged producer never sees the cancel event.+ for account in sweepable_job_accounts():+ settled.extend(+ (account, run_id)+ for run_id in await _sweep_in_daemon_thread(+ run_as,+ account,+ db.reconcile_runs,+ error = _LEASE_ERROR,+ stale_after_ms = int(self._timeout * 1000),+ )+ )if not settled:return []supervisor = getattr(getattr(self.app, "state", None), "chat_generation_supervisor", None)- for run_id in settled:+ for account, run_id in settled:logger.warning("chat_generation_run_lease_expired",run_id = run_id,@@ -277,22 +297,35 @@ class ChatGenerationLeaseSweeper:)if supervisor is None:continue+ if _run_id_held_by_another_account(account, run_id):+ # Another account started a live run under this id; the slot is theirs.+ logger.warning(+ "chat_generation_lease_cancel_skipped",+ run_id = run_id,+ reason = "another account holds the live registration for this id",+ )+ continue# The row is settled, but a producer wedged inside the engine is still holding its slot and activity- # reservation; cancel unwinds it.+ # reservation; cancel unwinds it, bound to the owning account's namespace.try:- supervisor.cancel(run_id)+ run_as(account, supervisor.cancel, run_id)except Exception as exc:logger.warning("chat_generation_lease_cancel_failed", run_id = run_id, error = repr(exc))continueasyncio.create_task(- self._force_cancel_after_grace(supervisor, run_id),+ self._force_cancel_after_grace(supervisor, run_id, account),name = f"chat-generation-lease-force-cancel:{run_id}",)- return settled+ return [run_id for _account, run_id in settled]- async def _force_cancel_after_grace(self, supervisor: Any, run_id: str) -> None:+ async def _force_cancel_after_grace(+ self,+ supervisor: Any,+ run_id: str,+ account: Any = None,+ ) -> None:"""Escalate from the cooperative cancel to cancelling the producer task.supervisor.cancel() only sets a threading.Event, which a producer blocked inside@@ -304,6 +337,9 @@ class ChatGenerationLeaseSweeper:task = getattr(supervisor, "_tasks", {}).get(run_id)if task is None or task.done():return+ if account is not None and _run_id_held_by_another_account(account, run_id):+ # The slot changed hands during the grace period.+ returnlogger.warning("chat_generation_run_force_cancelled",run_id = run_id,diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 56cebbe2987..26aaa526503 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -35,6 +35,7 @@ from core._torchao_stub import (install_xformers_windows_rocm_stub,)from loggers import get_logger+from utils.account_context import account_thread, current_account_idfrom utils.hardware import clear_gpu_cachefrom .diffusion_families import (@@ -1181,6 +1182,8 @@ class DiffusionBackend:self._generation_cancel_lock = threading.Lock()# Cancel Event of the in-flight generation; per-generation so a cancel can't be lost or leakself._active_generate_cancel: Optional[threading.Event] = None+ # Bound with the event under the same lock, so a cancel cannot land on the wrong generation.+ self._active_generate_account: Optional[str] = None# Queued requests; cancel_generate() decides which Stop may signal.self._queued_generate_cancels: set[threading.Event] = set()self._generation_owns_slot = False@@ -1275,6 +1278,7 @@ class DiffusionBackend:if not cancelled:self._queued_generate_cancels.discard(cancel)self._active_generate_cancel = cancel+ self._active_generate_account = current_account_id()self._generation_owns_slot = Trueadmitted = Trueelse:@@ -1289,12 +1293,15 @@ class DiffusionBackend:raise RuntimeError(DIFFUSION_CANCELLED_MSG)if self._teardown_drained.wait(timeout = 0.1):break+ from hub.services.models.account_access import media_generation_slottry:- yield+ with media_generation_slot("diffusion"):+ yieldfinally:with self._generation_cancel_lock:if self._active_generate_cancel is cancel:self._active_generate_cancel = None+ self._active_generate_account = Noneself._generation_owns_slot = Falseself._generate_lock.release()finally:@@ -2003,7 +2010,7 @@ class DiffusionBackend:# Seed with the family fallback; the worker resolves the real base and updates this.self._loading = _LoadingState(repo_id = repo_id, base_repo = fam.base_repo)- threading.Thread(+ account_thread(target = self._run_load,kwargs = dict(repo_id = repo_id,@@ -2177,6 +2184,12 @@ class DiffusionBackend:if self._load_token != token:returnlogger.error("diffusion.load_failed: %s", exc)+ if self._state is not None:+ from .gpu_arbiter import DIFFUSION, restore_owner_account+ from hub.services.models.account_access import restore_resident_metadata++ restore_owner_account(DIFFUSION)+ restore_resident_metadata(DIFFUSION)try:clear_gpu_cache()except Exception: # noqa: BLE001@@ -6134,6 +6147,7 @@ class DiffusionBackend:raise RuntimeError(DIFFUSION_CANCELLED_MSG)if self._active_generate_cancel is cancel:self._active_generate_cancel = None+ self._active_generate_account = None# Components are offloaded and transfer copies dropped; return the pages now.reclaim_offload_host_memory(state.offload_policy, logger = logger)@@ -6167,6 +6181,7 @@ class DiffusionBackend:with self._generation_cancel_lock:if self._active_generate_cancel is cancel:self._active_generate_cancel = None+ self._active_generate_account = Nonewith self._lock:# Sole clear of the published progress state, on every exit, so a crashed generation never leaves# the UI stuck.@@ -6191,18 +6206,20 @@ class DiffusionBackend:"eta_seconds": gen.eta_seconds,}- def cancel_generate(self) -> bool:- """Signal the in-flight generation to stop at its next step boundary. The denoise loop- already watches this event (``_on_step`` sets diffusers' ``_interrupt``, and the- per-chunk check discards a partial batch), but until now only unload() and a superseding- load could set it. Returns False when nothing is running, which the route reports so the- UI can settle its button back to Generate. Best effort by construction: the sampler stops- at the NEXT step callback, so a cancel during the VAE decode or the encode that precedes- step 0 lands when that finishes."""+ def cancel_generate(self, expected_account: Optional[str] = None) -> bool:+ """Stop the in-flight generation at its next step boundary; False when nothing is running.++ Best effort: the sampler stops at the NEXT step callback, so a cancel during the VAE+ decode or the encode before step 0 lands when that finishes."""with self._generation_cancel_lock:# Stop targets the denoising generation, not a serialized waiter.active = self._active_generate_cancelif active is not None:+ if expected_account is not None and self._active_generate_account not in (+ None,+ expected_account,+ ):+ return Falseactive.set()return Trueif self._generation_owns_slot:@@ -6218,8 +6235,21 @@ class DiffusionBackend:cancel.set()return True- def unload(self) -> dict[str, Any]:+ def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:with self._lock:+ if expected_account is not None:+ from .gpu_arbiter import DIFFUSION, GpuBusyForAnotherAccountError+ from hub.services.models.account_access import require_resident_control++ # Recheck under the generation-admitting lock before setting any cancel event.+ if (+ self._active_generate_cancel is not None+ and self._active_generate_account != expected_account+ ):+ raise GpuBusyForAnotherAccountError(DIFFUSION, 1)+ require_resident_control(+ DIFFUSION, self._state.repo_id if self._state is not None else None+ )# Abort an in-flight (lock-free) download so unload returns promptly. Under the lock, like video.py:# begin_load rebinds this attribute, so an unlocked read could set an event the current load no longer# watches.diff --git a/studio/backend/core/inference/diffusion_compat.py b/studio/backend/core/inference/diffusion_compat.pyindex 582417cd3de..36c55e6bf46 100644--- a/studio/backend/core/inference/diffusion_compat.py+++ b/studio/backend/core/inference/diffusion_compat.py@@ -249,15 +249,9 @@ def _read_gguf_header() -> bytes:"""A bounded prefix of a Hub-hosted GGUF, or b"" when it cannot be read.- One wall-clock bound over the WHOLE operation, request included. requests' timeout is an- inactivity timeout: a peer (or an intermediary) that trickles response HEADERS resets it on- every byte, so a deadline armed only once ``get()`` has returned leaves the caller blocked- before the bounded body reader is ever reached -- and this runs on the /images/load route- thread and on the download-plan path, both of which promised to fail open in seconds.-- So the request AND the drain run on a worker this call can walk away from. On timeout the- response, if one exists by then, is half-closed to wake the worker; either way the caller- returns with whatever arrived."""+ One wall-clock bound over the WHOLE operation: requests' own timeout is per-byte, so a+ trickled response would block this fail-open path past any deadline armed after ``get()``.+ Request and drain therefore run on a worker this call can abandon."""try:from huggingface_hub import hf_hub_urlfrom huggingface_hub.utils import build_hf_headers, get_sessiondiff --git a/studio/backend/core/inference/diffusion_controlnet.py b/studio/backend/core/inference/diffusion_controlnet.pyindex d0ac96765a6..a03358eac30 100644--- a/studio/backend/core/inference/diffusion_controlnet.py+++ b/studio/backend/core/inference/diffusion_controlnet.py@@ -21,7 +21,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Optional-from utils.paths.storage_roots import studio_root+from utils.paths.storage_roots import account_pathfrom utils.paths.path_utils import is_appledouble_metadata# Control map types. "passthrough": the supplied image IS the control map. "canny": derive an edge map here.@@ -80,8 +80,8 @@ _CURATED: tuple[ControlNetCatalogEntry, ...] = (def controlnets_dir() -> Path:- """Local directory Unsloth scans for user-provided ControlNet model folders."""- d = studio_root() / "controlnets" / "diffusion"+ """Local directory Unsloth scans for user-provided ControlNet model folders; per-account, with the owner on the install root."""+ d = account_path("controlnets/diffusion")d.mkdir(parents = True, exist_ok = True)return ddiff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.pyindex 285ed2d907a..6f427862681 100644--- a/studio/backend/core/inference/diffusion_engine_router.py+++ b/studio/backend/core/inference/diffusion_engine_router.py@@ -21,6 +21,7 @@ Env knobs:from __future__ import annotationsimport os+import sysimport threadingfrom typing import Any, Callable, Optional@@ -90,6 +91,42 @@ def get_active_diffusion_engine() -> Any:return engine_for(_active_engine_name)+def cancel_generation_for_account(account_id: str) -> bool:+ """Stop an in-flight image generation owned by ``account_id``; True when one was signalled.++ Engines come from ``sys.modules`` (no import, no construction); both are checked because a+ deselected engine can still be draining."""+ cancelled = False+ for module_name, attribute in (+ ("core.inference.diffusion", "_diffusion_backend"),+ ("core.inference.sd_cpp_backend", "_sd_cpp_backend"),+ ):+ module = sys.modules.get(module_name)+ engine = getattr(module, attribute, None) if module is not None else None+ if engine is None or engine._active_generate_account != account_id:+ continue+ # cancel_generate rechecks the owner under its lock.+ if engine.cancel_generate(expected_account = account_id):+ cancelled = True+ return cancelled+++def retire_load_for_account(account_id: str) -> bool:+ """Tear down an in-flight image load ``account_id`` started; True when one was found."""+ from hub.services.models.account_access import retire_media_load++ retired = False+ for module_name, attribute in (+ ("core.inference.diffusion", "_diffusion_backend"),+ ("core.inference.sd_cpp_backend", "_sd_cpp_backend"),+ ):+ module = sys.modules.get(module_name)+ engine = getattr(module, attribute, None) if module is not None else None+ if retire_media_load("diffusion", account_id, engine):+ retired = True+ return retired++def active_engine_name() -> str:return _active_engine_namediff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.pyindex 7fd64ca2f6a..8dcef80c416 100644--- a/studio/backend/core/inference/diffusion_lora.py+++ b/studio/backend/core/inference/diffusion_lora.py@@ -24,7 +24,7 @@ from pathlib import Pathfrom typing import Optionalfrom utils.hf_xet_fallback import hf_hub_download_with_xet_fallback-from utils.paths.storage_roots import studio_root+from utils.paths.storage_roots import account_pathfrom .diffusion_families import DIFFUSION_CANCELLED_MSGfrom utils.paths.path_utils import is_appledouble_metadata@@ -91,8 +91,7 @@ _CURATED: tuple[LoraCatalogEntry, ...] = (def loras_dir() -> Path:- """Local directory Unsloth scans for user-provided diffusion LoRA files."""- d = studio_root() / "loras" / "diffusion"+ d = account_path("loras/diffusion")d.mkdir(parents = True, exist_ok = True)return ddiff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 56781e9ff19..12f6e7a6614 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -713,6 +713,60 @@ def _create_shared_http_client() -> httpx.AsyncClient:_http_client = _create_shared_http_client()+class _PinnedPublicTransport(httpx.AsyncBaseTransport):+ """Managed-account egress: re-resolve per connection, dial one validated public address."""++ def __init__(self):+ # Separate pools retain TLS identity when two names resolve to one IP.+ self._transports: dict[tuple, httpx.AsyncHTTPTransport] = {}++ def _pool(self, origin: tuple) -> httpx.AsyncHTTPTransport:+ if origin not in self._transports:+ self._transports[origin] = httpx.AsyncHTTPTransport(trust_env = False)+ return self._transports[origin]++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ from core.inference.providers import _public_registry_hostname, public_provider_address++ host = request.url.host+ if _public_registry_hostname(host):+ return await self._pool(("registry",)).handle_async_request(request)+ try:+ address = await asyncio.to_thread(public_provider_address, str(request.url))+ except ValueError as exc:+ raise httpx.ConnectError(str(exc), request = request) from exc+ pinned = httpx.Request(+ method = request.method,+ url = request.url.copy_with(host = address),+ headers = request.headers,+ stream = request.stream,+ extensions = {**request.extensions, "sni_hostname": host},+ )+ origin = (request.url.scheme, host, request.url.port)+ return await self._pool(origin).handle_async_request(pinned)++ async def aclose(self) -> None:+ for transport in self._transports.values():+ await transport.aclose()+++_managed_http_client: Optional[httpx.AsyncClient] = None+++def _client() -> httpx.AsyncClient:+ """The shared client for the owner; a pinning client for a managed account."""+ from utils.account_context import is_owner_context++ if is_owner_context():+ return _http_client+ global _managed_http_client+ if _managed_http_client is None:+ _managed_http_client = httpx.AsyncClient(+ transport = _PinnedPublicTransport(), trust_env = False+ )+ return _managed_http_client++# Cap per-image fetch well below Gemini's ~20 MB total request budget._GEMINI_REMOTE_IMAGE_MAX_BYTES = 10 * 1024 * 1024_GEMINI_REMOTE_IMAGE_TIMEOUT_S = 15.0@@ -1297,7 +1351,7 @@ class ExternalProviderClient:)try:- async with _http_client.stream(+ async with _client().stream("POST",url,json = body,@@ -1584,7 +1638,7 @@ class ExternalProviderClient:tool_calls_acc: dict[int, dict[str, Any]] = {}try:- async with _http_client.stream(+ async with _client().stream("POST",url,json = body,@@ -1679,7 +1733,7 @@ class ExternalProviderClient:# the row has neither tokens nor a speed.fallback_body["stream_options"] = {"include_usage": True}try:- async with _http_client.stream(+ async with _client().stream("POST",url,json = fallback_body,@@ -1787,7 +1841,7 @@ class ExternalProviderClient:# Keep the tool on the second call so the model can search again mid-turn.try:- async with _http_client.stream(+ async with _client().stream("POST",url,json = followup_body,@@ -2387,7 +2441,7 @@ class ExternalProviderClient:request_headers["anthropic-beta"] = ",".join(beta_parts)try:- async with _http_client.stream(+ async with _client().stream("POST",url,json = body,@@ -4068,7 +4122,7 @@ class ExternalProviderClient:last_code_exec_result_text: str = ""try:- async with _http_client.stream(+ async with _client().stream("POST",url,json = body,@@ -5131,7 +5185,7 @@ class ExternalProviderClient:attempt_container_id = openai_code_exec_container_idwhile True:attempt_body = _build_body(attempt_container_id)- async with _http_client.stream(+ async with _client().stream("POST",url,json = attempt_body,@@ -6127,7 +6181,7 @@ class ExternalProviderClient:else:body["max_tokens"] = max_tokens- response = await _http_client.post(+ response = await _client().post(f"{self.base_url}/chat/completions",json = body,headers = self._auth_headers(),@@ -6157,7 +6211,7 @@ class ExternalProviderClient:body["speed"] = speedif instructions is not None:body["instructions"] = instructions- response = await _http_client.post(+ response = await _client().post(_append_provider_path(self.base_url, "/audio/speech"),headers = self._auth_headers(),json = body,@@ -6211,7 +6265,7 @@ class ExternalProviderClient:data["timestamp_granularities[]"] = list(timestamp_granularities)headers = self._auth_headers()headers.pop("Content-Type", None)- response = await _http_client.post(+ response = await _client().post(f"{self.base_url}/audio/transcriptions",headers = headers,files = {"file": (filename, audio, content_type)},@@ -6228,7 +6282,7 @@ class ExternalProviderClient:"""GET /models to discover available models. Returns dicts with at least 'id'. All providersexpose /models with the OpenAI {"data": [...]} shape, Anthropic included."""try:- response = await _http_client.get(+ response = await _client().get(f"{self.base_url}/models",headers = self._auth_headers(),timeout = self._timeout,@@ -6295,7 +6349,7 @@ class ExternalProviderClient:async def _list_ollama_native_models(self) -> list[dict[str, Any]]:"""Fallback when Ollama's /v1/models returns an empty or null catalog."""root = self.base_url.removesuffix("/v1").rstrip("/")- response = await _http_client.get(+ response = await _client().get(f"{root}/api/tags",headers = self._auth_headers(),timeout = self._timeout,@@ -6319,7 +6373,7 @@ class ExternalProviderClient:the full JSON would be prohibitive."""url = f"{self.base_url}/models"try:- async with _http_client.stream(+ async with _client().stream("GET",url,headers = self._auth_headers(),@@ -6345,9 +6399,10 @@ class ExternalProviderClient:return headersasync def list_openai_containers(self) -> list[dict[str, Any]]:- """GET /v1/containers; returns raw container records (the route reshapes them). Only valid- against api.openai.com (caller guards is_openai_cloud)."""- response = await _http_client.get(+ """GET /v1/containers; returns raw container records (the route reshapes+ them). Only valid against api.openai.com (caller guards is_openai_cloud).+ """+ response = await _client().get(f"{self.base_url}/containers",headers = self._container_headers(),timeout = self._timeout,@@ -6373,7 +6428,7 @@ class ExternalProviderClient:"minutes": ttl_minutes,},}- response = await _http_client.post(+ response = await _client().post(f"{self.base_url}/containers",json = body,headers = self._container_headers(),diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.pyindex 03af008af58..cd5392c5054 100644--- a/studio/backend/core/inference/gpu_arbiter.py+++ b/studio/backend/core/inference/gpu_arbiter.py@@ -25,6 +25,9 @@ VIDEO = "video"_lock = threading.Lock()_owner: Optional[str] = None_owner_epoch = 0+# Account whose load put the current owner on the GPU, so routes can refuse to evict it.+_owner_account: Optional[str] = None+_prior_account: Optional[str] = Noneclass OwnerChangedError(RuntimeError):@@ -58,6 +61,9 @@ def _evict_chat() -> None:# The driver reclaims the killed VRAM asynchronously, so wait for it to settle before diffusion allocates, else a# warm handoff can transiently OOM.llama._wait_for_vram_settle(since_kill = time.monotonic())+ from hub.services.models.account_access import clear_resident++ clear_resident(CHAT)def _evict_diffusion() -> None:@@ -84,43 +90,140 @@ class GpuOwnerBusyError(RuntimeError):super().__init__(f"GPU is owned by {owner}")+class GpuBusyForAnotherAccountError(GpuOwnerBusyError):+ """Another account is generating on the resident model; routes answer 409 ``gpu_busy``."""++ def __init__(self, owner: str, active: int):+ self.active = active+ super().__init__(owner)++ @property+ def retry_after(self) -> int:+ from core.inference.llama_admission import estimate_gpu_retry_after+ return estimate_gpu_retry_after()++ def as_http_exception(self, path: Optional[str] = None):+ """A retryable refusal without another account's model or conversation ids."""+ from fastapi import HTTPException+ from utils.api_errors import error_body_for_path++ retry_after = self.retry_after+ message = "Another account is generating on the resident model. Retry after it finishes."+ detail = (+ error_body_for_path(path, message, status = 409, code = "gpu_busy", param = "model")+ if path and path.startswith("/v1/")+ else {"error": "gpu_busy", "message": message, "retry_after": retry_after}+ )+ return HTTPException(+ status_code = 409,+ detail = detail,+ headers = {"Retry-After": str(retry_after)},+ )+++def other_accounts_active(account_id: str) -> int:+ from state import active_generations++ # Image and video jobs never enter active_generations, so ask their own trackers too.+ from hub.services.models.account_access import foreign_media_generations+ return active_generations.foreign_count(account_id) + foreign_media_generations(account_id)+++def raise_if_other_accounts_active(account_id: Optional[str] = None) -> None:+ """Guard a destructive reload; call under the lifecycle gate before touching any backend."""+ from utils.account_context import current_account_id++ busy = other_accounts_active(account_id or current_account_id())+ if busy:+ raise GpuBusyForAnotherAccountError(_owner or CHAT, busy)+++def require_no_foreign_generations(+ account_id: Optional[str] = None, *, path: Optional[str] = None+) -> None:+ try:+ raise_if_other_accounts_active(account_id)+ except GpuBusyForAnotherAccountError as exc:+ raise exc.as_http_exception(path) from exc+++def acquire_for_request(+ owner: str,+ register = None,+ **kwargs,+) -> Any:+ try:+ return acquire_for(owner, register, **kwargs)+ except GpuBusyForAnotherAccountError as exc:+ raise exc.as_http_exception() from exc++def acquire_for(owner: str,register: Optional[Callable[[], Any]] = None,*,expected_current: Optional[tuple[Optional[str], int]] = None,allow_evict: bool = True,+ account_id: Optional[str] = None,+ replacing: bool = False,) -> Any:"""Make ``owner`` the sole GPU owner, evicting the other if it holds it.- ``register``, if given, runs under the arbiter lock right after ownership transfers and its- return value is returned. Marking the in-flight load HERE (not after ``acquire_for`` returns)- closes the window where a competing acquire could evict this owner before its load is in-flight,- letting both loaders allocate VRAM at once. It must be quick and not re-enter the arbiter; if it- raises, ownership stays with ``owner``.+ ``register`` runs under the arbiter lock as ownership transfers, so a competing acquire cannot+ evict this owner and let both loaders allocate VRAM at once."""- global _owner, _owner_epoch+ global _owner, _owner_epoch, _owner_account, _prior_accountif owner not in _EVICTORS:raise ValueError(f"unknown GPU owner: {owner!r}")+ from utils.account_context import current_account_id++ acting = account_id or current_account_id()with _lock:if expected_current is not None and (_owner, _owner_epoch) != expected_current:raise OwnerChangedError("The resident GPU model changed; retry the load.")+ if register is not None or replacing:+ raise_if_other_accounts_active(acting)if _owner is not None and _owner != owner:if not allow_evict:raise GpuOwnerBusyError(_owner)+ # Never evict an account mid-generation; the caller retries after its stream ends.+ busy = other_accounts_active(acting)+ if busy:+ raise GpuBusyForAnotherAccountError(_owner, busy)logger.info("gpu_arbiter: evicting %s for %s", _owner, owner)_EVICTORS[_owner]()+ # Records who LOADED the model; a plain re-assert must not hand it to whoever asked last.+ claims = _owner != owner or register is not None or replacing_owner = owner_owner_epoch += 1- return register() if register is not None else None+ result = register() if register is not None else None+ # A raising registration loaded nothing and must not take residency.+ if claims:+ _prior_account, _owner_account = _owner_account, acting+ return result+++def restore_owner_account(owner: str, account_id: Optional[str] = None) -> bool:+ """Hand residency back to the displaced account when a claim's load never committed."""+ global _owner_account, _prior_account+ from utils.account_context import current_account_id++ with _lock:+ acting = account_id or current_account_id()+ if _owner != owner or _owner_account != acting or _prior_account is None:+ return False+ _owner_account, _prior_account = _prior_account, None+ return Truedef release(owner: str) -> None:"""Drop ``owner``'s claim (no-op if it isn't the current owner)."""- global _owner, _owner_epoch+ global _owner, _owner_epoch, _owner_account, _prior_accountwith _lock:if _owner == owner:_owner = None+ _owner_account = None+ _prior_account = None_owner_epoch += 1@@ -131,11 +234,13 @@ def release_if(owner: str, predicate: Callable[[], bool]) -> bool:whose ``acquire_for(register=...)`` re-registers ownership under this lock; evaluating thepredicate under the lock keeps them atomic so ``release`` never clears the newer claim.``predicate`` must be quick and not re-enter the arbiter. Returns True iff ownership was dropped."""- global _owner, _owner_epoch+ global _owner, _owner_epoch, _owner_account, _prior_accountwith _lock:if _owner != owner or not predicate():return False_owner = None+ _owner_account = None+ _prior_account = None_owner_epoch += 1return True@@ -144,6 +249,10 @@ def current_owner() -> Optional[str]:return _owner+def owner_account() -> Optional[str]:+ return _owner_account++def owner_snapshot() -> tuple[Optional[str], int]:with _lock:return _owner, _owner_epochdiff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.pyindex 52cd44dbb9b..337ccd42d24 100644--- a/studio/backend/core/inference/image_gallery.py+++ b/studio/backend/core/inference/image_gallery.py@@ -3,12 +3,9 @@"""Disk-backed persistence for generated images.-Each image is a PNG under ``studio_root()/images`` with its full recipe embedded as PNG text-chunks: a structured ``unsloth`` JSON blob (the source of truth) plus an Automatic1111-style-``parameters`` string for interop. So a downloaded PNG carries its own settings.--Dumb storage: the route owns the metadata schema and passes a plain dict; this only reads/writes/-sorts files.+Each image is a PNG under ``workspace_root()/images`` with its recipe embedded as PNG text chunks:+an ``unsloth`` JSON blob (the source of truth) plus an Automatic1111-style ``parameters`` string,+so a downloaded PNG carries its own settings. The route owns the schema; this only stores files."""from __future__ import annotations@@ -24,7 +21,9 @@ from typing import Any, Optionalfrom core.inference import gallery_flagsfrom loggers import get_logger-from utils.paths import ensure_dir, studio_root+from utils.account_context import is_owner_context+from utils.paths import ensure_account_dir, ensure_dir, studio_root+from utils.paths.storage_roots import account_pathlogger = get_logger(__name__)@@ -35,7 +34,9 @@ _ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")def gallery_dir() -> Path:- return ensure_dir(studio_root() / "images")+ if is_owner_context():+ return ensure_dir(studio_root() / "images")+ return ensure_account_dir(account_path("images"))def _params_text(meta: dict[str, Any]) -> str:diff --git a/studio/backend/core/inference/key_exchange.py b/studio/backend/core/inference/key_exchange.pyindex 27970fbc47f..6087e38ebd5 100644--- a/studio/backend/core/inference/key_exchange.py+++ b/studio/backend/core/inference/key_exchange.py@@ -28,7 +28,6 @@ logger = logging.getLogger(__name__)_ENVELOPE_VERSION = "v1"_ENVELOPE_PARTS = 4-# Pins an envelope to this protocol and version, as the at-rest secrets do._ENVELOPE_AAD = b"unsloth-studio-provider-key-v1"_private_key: rsa.RSAPrivateKey | None = None@@ -121,12 +120,7 @@ def _b64decode_part(value: str, *, what: str, validate: bool) -> bytes:def decrypt_api_key(encrypted_b64: str) -> str:- """Decrypt an API key encrypted with the public key.-- Accepts ``v1.<wrapped AES key>.<nonce>.<ciphertext||tag>``, each part base64, and the- bare RSA-OAEP ciphertext frontend builds predating the envelope send. Base64 has no- ``.``, so the two can never be confused.- """+ """Accepts the ``v1.``-prefixed envelope or a bare legacy RSA-OAEP ciphertext; base64 has no ``.``, so the two cannot be confused."""if _private_key is None:raise RuntimeError("Key pair not initialized. Call init_key_pair() first.")@@ -161,8 +155,7 @@ def decrypt_api_key(encrypted_b64: str) -> str:)raiseelse:- # Lenient, as this path was before the envelope: tightening it could reject a key- # that works today.+ # Lenient as this path was before the envelope: tightening it could reject a working key.legacy_ciphertext = _b64decode_part(encrypted_b64, what = "legacy", validate = False)plaintext = _unwrap_oaep(legacy_ciphertext, what = "legacy")diff --git a/studio/backend/core/inference/llama_admission.py b/studio/backend/core/inference/llama_admission.pyindex 35c80dc5880..8653d3f3bbe 100644--- a/studio/backend/core/inference/llama_admission.py+++ b/studio/backend/core/inference/llama_admission.py@@ -1102,6 +1102,17 @@ def peek_llama_admission_snapshot(key: str) -> Optional[LlamaAdmissionSnapshot]:return queue.snapshot() if queue is not None else None+def estimate_gpu_retry_after() -> int:+ with _QUEUES_LOCK:+ queues = tuple(_QUEUES.values())+ waves = 1+ for queue in queues:+ snapshot = queue.snapshot()+ capacity = max(1, snapshot.capacity)+ waves = max(waves, (snapshot.active + snapshot.queued + capacity - 1) // capacity)+ return min(120, 15 * waves)++def reset_llama_admission_queues() -> None:global _parked_totalwith _QUEUES_LOCK:diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex cd660d97d3a..a58aaf8c14b 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -6248,6 +6248,23 @@ def _metal_capable_host() -> bool:return sys.platform == "darwin"+def _write_direct_stream_key(key: str) -> "Path":+ """Store the direct-streaming key where only the server user can read it."""+ from utils.paths.storage_roots import auth_root++ directory = auth_root()+ directory.mkdir(parents = True, exist_ok = True)+ path = directory / "llama_api_key"+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:+ handle.write(key)+ try:+ os.chmod(path, 0o600)+ except OSError:+ pass+ return path++class LlamaCppBackend:"""Manages a llama-server subprocess for GGUF model inference.@@ -7056,9 +7073,7 @@ class LlamaCppBackend:@propertydef reasoning_effort_levels(self) -> list:- """Discrete reasoning_effort levels the template offers (e.g. GLM-5.2's- ['high', 'max']). Empty unless the style is 'enable_thinking_effort' or- 'reasoning_effort' over a ladder wider than low/medium/high."""+ """Discrete reasoning_effort levels the template offers; empty for the plain low/medium/high ladder."""return self._reasoning_effort_levels@property@@ -7119,8 +7134,6 @@ class LlamaCppBackend:if not thinking_off and effort_on:kwargs["reasoning_effort"] = reasoning_effortelif self._reasoning_style == "reasoning_effort":- # The advertised ladder widens this list, never replaces it: a template- # exposing only ['high', 'max'] must keep gpt-oss's own levels and 'none'._levels = getattr(self, "_reasoning_effort_levels", None) or ()if reasoning_effort in ("none", "low", "medium", "high") or (reasoning_effort in _levels@@ -23564,8 +23577,9 @@ class LlamaCppBackend:if os.getenv("UNSLOTH_DIRECT_STREAM", "0") == "1":self._api_key = _secrets.token_urlsafe(32)- cmd.extend(["--api-key", self._api_key])- logger.info("llama-server started with --api-key for direct streaming")+ # Through a file, not argv: a command line is readable by every process of this Unix user, and the auth directory is not.+ cmd.extend(["--api-key-file", str(_write_direct_stream_key(self._api_key))])+ logger.info("llama-server started with --api-key-file for direct streaming")else:self._api_key = None@@ -30297,14 +30311,12 @@ class LlamaCppBackend:# "auto"; unknown falls back to the stricter "ask". An explicit# confirm_tool_calls=True with no mode is already resolved to "ask" at the# request layer, so it never arrives here as an ambiguous unset.- if permission_mode == "full":- bypass_permissions = True- elif bypass_permissions:- permission_mode = "full"- elif permission_mode is None:- permission_mode = "auto"- elif permission_mode not in ("ask", "auto", "off"):- permission_mode = "ask"+ from state.tool_policy import account_tool_stream, normalize_tool_permissions++ permission_mode, bypass_permissions = normalize_tool_permissions(+ permission_mode, bypass_permissions+ )+ stream_tool_execution = account_tool_stream(stream_tool_execution)if not self.is_loaded:raise RuntimeError("llama-server is not loaded")diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.pyindex 2c558ae9450..3d5b69d856c 100644--- a/studio/backend/core/inference/llama_keepwarm.py+++ b/studio/backend/core/inference/llama_keepwarm.py@@ -3,13 +3,10 @@"""Opt-in idle auto-unload (TTL keep-warm) for the local llama.cpp model.-Off by default (idle seconds = 0). When enabled, a background loop unloads the-loaded GGUF once it has been idle for the configured TTL, freeing VRAM. A-pure-ASGI middleware tracks in-flight inference requests so a long stream that-outlives the TTL is never unloaded mid-response.--The same loop and the same middleware drive the image/video side (media_keepwarm),-so Unsloth has one idle mechanism rather than one per backend.+Off by default (idle seconds = 0). A background loop unloads the GGUF after the TTL, and a+pure-ASGI middleware tracks in-flight requests so a long stream is never unloaded mid-response.+The resident model is shared, so any account's activity resets the one global idle clock. The+same loop and middleware drive media_keepwarm."""from __future__ import annotations@@ -896,6 +893,16 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:logger.info("Idle auto-unload: saved slot KV for restore on reload")elif manifest:_delete_resume_files(manifest)+ # As /unload: a kept claim hides the empty GPU from other accounts. After the+ # stash, so a failed release never loses the reload identity.+ try:+ from hub.services.models.account_access import clear_resident+ from routes.inference import release_chat_gpu_claim++ clear_resident("chat")+ await asyncio.to_thread(release_chat_gpu_claim)+ except Exception as exc: # noqa: BLE001 - the unload already happened+ logger.debug("Idle auto-unload: claim release failed: %s", exc)logger.info("Idle auto-unload: freed GGUF after %ss idle", ttl)# An idle unload stashes for reload and skips note_model_unloaded._note_idle_unload_event(freed)diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.pyindex b14660e0976..9ffbdad2df2 100644--- a/studio/backend/core/inference/local_model_resolver.py+++ b/studio/backend/core/inference/local_model_resolver.py@@ -22,6 +22,7 @@ from typing import Optionalfrom core.inference.model_ids import public_model_idfrom loggers import get_logger+from utils.account_context import account_thread, current_account_id, is_owner_contextlogger = get_logger(__name__)@@ -42,6 +43,27 @@ _CACHE_TTL_S = 5.0# other._lock = threading.Lock()_scan: tuple[float, dict[str, _LocalGgufEntry]] = (0.0, {})+_EMPTY_SCAN: tuple[float, dict[str, _LocalGgufEntry]] = (0.0, {})+# One snapshot per managed account: scanned roots are account private, so a shared snapshot would+# answer the next account with the previous one's paths. The owner keeps ``_scan``.+_managed_scans: dict[str, tuple[float, dict[str, _LocalGgufEntry]]] = {}+++def _snapshot() -> tuple[float, dict[str, _LocalGgufEntry]]:+ """The acting account's published index snapshot."""+ if is_owner_context():+ return _scan+ return _managed_scans.get(current_account_id(), _EMPTY_SCAN)+++def _publish(snapshot: tuple[float, dict[str, _LocalGgufEntry]]) -> None:+ global _scan+ if is_owner_context():+ _scan = snapshot+ else:+ _managed_scans[current_account_id()] = snapshot++# Not _lock: that is held for the whole scan, so the request path would wait on it._warm_lock = threading.Lock()# Repos that finished downloading but are not in the published index yet: nothing else covers them until the next scan,@@ -117,13 +139,7 @@ def _resolve_load_dir(p, loader_id: Optional[str] = None):def _resolve_gguf_load_snapshot(p):- """Newest complete snapshot in this exact cache repo, or the selector fallback.-- A later Hub revision can contain only a newly fetched companion such as an- MTP drafter or mmproj while the complete model weights remain in an older- snapshot. The generic resolver intentionally picks the newest snapshot, but- doing that for GGUF discovery makes the repo disappear from ``/v1/models``.- """+ """Newest *complete* snapshot: a newer revision may hold only a companion, not weights."""snapshots = p / "snapshots"try:if not snapshots.is_dir():@@ -131,8 +147,7 @@ def _resolve_gguf_load_snapshot(p):except OSError:return None- # Reuse the Hub inventory's selection rule, scoped to the row's exact repo- # directory so case-colliding repos cannot cross-load or trigger another root scan.+ # Scoped to this exact repo dir so case-colliding repos cannot cross-load.from hub.utils.gguf import select_gguf_cache_snapshot_for_repo_dirselected = select_gguf_cache_snapshot_for_repo_dir(p)@@ -142,13 +157,6 @@ def _resolve_gguf_load_snapshot(p):def local_gguf_companion_roots(load_path: str, *, repo_level: bool = False) -> tuple[str, ...]:- """Trusted sibling snapshots for a repo-level HF cache resolution.-- The selected snapshot remains first so a colocated companion wins. Other- revisions are returned newest first for the case where a later download- contains only a compatible mmproj. Exact revision paths and paths outside- an exact ``models--*`` cache-repo layout never widen their companion search.- """from pathlib import Pathfrom hub.utils.hf_cache_state import snapshot_selection_key@@ -181,7 +189,6 @@ def local_gguf_companion_roots(load_path: str, *, repo_level: bool = False) -> tdef local_gguf_companion_state(roots: tuple[str, ...]) -> tuple:- """File metadata for trusted snapshots, including newly completed companions."""from pathlib import Pathstate = []@@ -728,8 +735,7 @@ def _build_index() -> dict[str, _LocalGgufEntry]:entry = _local_servable_entry(loader_id, info)if entry is None:continue- # Repo and display aliases intentionally select across revisions. An inactive-cache row's absolute id and- # basename name one exact revision instead: index them only when that revision has its own complete weights.+ # Path-shaped ids name one exact revision, so index them only if that revision has complete weights.path_alias_entry = entryif entry.repo_level_companions and _is_abs_path_id(raw_id):from types import SimpleNamespace@@ -847,11 +853,18 @@ def invalidate_index(*, additions_only: bool = False) -> None:with _lock:now = time.monotonic()_generation += 1- timestamp, retained = _scan- # Publish entries and their trust state together. A lock-free reader sees either the complete old snapshot or- # the complete invalidated one, never a fresh timestamp paired with already-revoked trust.- stamp = -now if additions_only and _snapshot_is_trusted(timestamp, now) else 0.0- _scan = (stamp, retained)++ def _invalidated(snapshot):+ timestamp, retained = snapshot+ # Entries and trust state publish together: a lock-free reader never sees a fresh+ # timestamp paired with revoked trust.+ stamp = -now if additions_only and _snapshot_is_trusted(timestamp, now) else 0.0+ return (stamp, retained)++ # Every account's snapshot: what changed on disk is not scoped to whoever noticed.+ _scan = _invalidated(_scan)+ for account_id, snapshot in list(_managed_scans.items()):+ _managed_scans[account_id] = _invalidated(snapshot)# This may have waited out a scan on _lock, so the warmer that just published can still own the slot with a snapshot# that is stale again. See _warm_pending.with _warm_lock:@@ -860,12 +873,11 @@ def invalidate_index(*, additions_only: bool = False) -> None:def _index() -> dict[str, _LocalGgufEntry]:- global _scan# Build under the lock so concurrent callers with an expired cache don't all run the (multi-dir) scan at once; the# rest wait and reuse the fresh result.with _lock:now = time.monotonic()- ts, cached = _scan+ ts, cached = _snapshot()# `ts > 0`: monotonic() counts from boot, so under a TTL of uptime an invalidated stamp reads as recent and# would serve what was just revokedif ts > 0.0 and now - ts < _CACHE_TTL_S:@@ -874,7 +886,7 @@ def _index() -> dict[str, _LocalGgufEntry]:# Stamp AFTER the scan, not with the pre-scan ``now``: a multi-root scan on an install with many local models# can itself exceed the TTL, which would store the cache already expired and make every request rebuild the# index.- _scan = (time.monotonic(), fresh)+ _publish((time.monotonic(), fresh))# The scan supersedes the notes: whatever landed is in the index now._just_downloaded.clear()return fresh@@ -887,7 +899,7 @@ def index_is_built() -> bool:park the request path on the scan it is trying to stay off. Safe because``_scan`` is only ever rebound, never mutated."""- return _scan[0] > 0.0+ return _snapshot()[0] > 0.0def resolve_trusted_cached_local_gguf(@@ -904,16 +916,16 @@ def resolve_trusted_cached_local_gguf(With ``include_companion_scope=True``, append whether sibling snapshots belongto this repo-level resolution and may be searched for compatible companions."""- snapshot = _scan+ snapshot = _snapshot()resolved = _resolve_from_index(requested,snapshot[1],include_companion_scope = include_companion_scope,)- if resolved is None or _scan is not snapshot:+ if resolved is None or _snapshot() is not snapshot:return Nonetrusted = _snapshot_is_trusted(snapshot[0], time.monotonic())- return resolved if trusted and _scan is snapshot else None+ return resolved if trusted and _snapshot() is snapshot else Nonedef warm_index_soon() -> None:@@ -925,7 +937,7 @@ def warm_index_soon() -> None:for the life of the process. Never blocks, and never touches ``_lock``."""global _warming, _warm_pending- stamp = _scan[0]+ stamp = _snapshot()[0]if stamp > 0.0 and time.monotonic() - stamp < max(_CACHE_TTL_S, _last_scan_s * _WARM_DUTY):returnwith _warm_lock:@@ -958,7 +970,8 @@ def warm_index_soon() -> None:with _warm_lock:_warming = _warm_pending = False- threading.Thread(target = _run, name = "local-model-index-warm", daemon = True).start()+ # Pinned to the caller's account, or the rebuild would publish under the owner's scope.+ account_thread(target = _run, name = "local-model-index-warm", daemon = True).start()def resolve_local_gguf(@@ -986,7 +999,7 @@ def resolve_local_gguf(return Nonerequested = requested.strip()try:- index = _index() if allow_scan else _scan[1]+ index = _index() if allow_scan else _snapshot()[1]return _resolve_from_index(requested,index,@@ -1064,7 +1077,7 @@ def local_target_is_gguf(load_path: Optional[str], loader_id: Optional[str] = Nopassif not isinstance(loader_id, str) or not loader_id.strip():return True- entry = _scan[1].get(loader_id.strip().lower())+ entry = _snapshot()[1].get(loader_id.strip().lower())return entry.is_gguf if entry is not None else Truediff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.pyindex 86ac674f9c6..18cd148d622 100644--- a/studio/backend/core/inference/mcp_client.py+++ b/studio/backend/core/inference/mcp_client.py@@ -7,12 +7,15 @@ import asyncioimport atexitimport concurrent.futuresimport hashlib+import importlib+import ipaddressimport jsonimport mimetypesimport osimport reimport shleximport shutil+import socketimport subprocessimport sysimport threading@@ -20,11 +23,17 @@ import timeimport uuidfrom contextlib import contextmanagerfrom functools import wraps-from typing import Any, Optional+from typing import Any, Optional, get_type_hintsfrom urllib.parse import urlsplit, urlunsplitfrom weakref import WeakKeyDictionaryfrom loggers import get_logger+from utils.account_context import (+ OWNER_ACCOUNT_ID,+ account_thread,+ current_account_id,+ is_owner_context,+)logger = get_logger(__name__)@@ -39,6 +48,93 @@ FAILED_PROBE_COOLOFF_SECONDS = 60.0OAUTH_FAILED_PROBE_COOLOFF_SECONDS = 300.0_oauth_token_store = None+_account_oauth_token_stores: dict[str, Any] = {}+++def _managed_mcp_restricted() -> bool:+ return not is_owner_context()+++def _account_key(value):+ if is_owner_context():+ return value+ return current_account_id(), value+++def _public_mcp_address(url: str) -> str:+ from fastapi import HTTPException+ detail = "Managed accounts may only use public-network HTTP MCP servers."+ try:+ parsed = urlsplit(url)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError("HTTP URL required")+ if parsed.username is not None or parsed.password is not None:+ raise ValueError("Use MCP headers for credentials")+ host = parsed.hostname+ if "%" in host:+ raise ValueError("Scoped addresses are not public")+ port = parsed.port or (443 if parsed.scheme == "https" else 80)+ addresses = socket.getaddrinfo(host, port, type = socket.SOCK_STREAM)+ if not addresses:+ raise ValueError("No addresses")+ for *_, sockaddr in addresses:+ address = ipaddress.ip_address(sockaddr[0])+ address = getattr(address, "ipv4_mapped", None) or address+ if not address.is_global or address.is_multicast or address.is_reserved:+ raise ValueError("Non-public address")+ return addresses[0][4][0]+ except (OSError, ValueError, UnicodeError) as exc:+ raise HTTPException(status_code = 400, detail = detail) from exc+++def validate_mcp_address(url: str) -> None:+ if not _managed_mcp_restricted():+ return+ if is_stdio(url):+ from fastapi import HTTPException+ raise HTTPException(+ status_code = 400,+ detail = "Only the installation owner may register local-command MCP servers.",+ )+ _public_mcp_address(url)+++def _public_http_client_factory(**kwargs):+ """Pin public destinations, including redirects and OAuth discovery; SNI keeps the original hostname and proxy env vars are ignored so they cannot reach the LAN."""+ from mcp.shared._httpx_utils import create_mcp_http_client++ client_type = get_type_hints(create_mcp_http_client)["return"]+ http = importlib.import_module(client_type.__module__.split(".")[0])++ class PublicTransport(http.AsyncBaseTransport):+ def __init__(self):+ # Separate pools retain TLS identity when two names resolve to one IP.+ self.transports = {}++ async def handle_async_request(self, request):+ address = await asyncio.to_thread(_public_mcp_address, str(request.url))+ origin = (request.url.scheme, request.url.host, request.url.port)+ if origin not in self.transports:+ self.transports[origin] = http.AsyncHTTPTransport(trust_env = False)+ pinned = http.Request(+ method = request.method,+ url = request.url.copy_with(host = address),+ headers = request.headers,+ stream = request.stream,+ extensions = {**request.extensions, "sni_hostname": request.url.host},+ )+ return await self.transports[origin].handle_async_request(pinned)++ async def aclose(self):+ for transport in self.transports.values():+ await transport.aclose()++ kwargs["trust_env"] = False+ kwargs["transport"] = PublicTransport()+ kwargs.setdefault("follow_redirects", True)+ if kwargs.get("timeout") is None:+ kwargs["timeout"] = http.Timeout(30.0, read = 300.0)+ return client_type(**kwargs)def is_stdio(address: str) -> bool:@@ -171,6 +267,8 @@ def stdio_mcp_enabled() -> bool:opt-in, where the process tool policy is False merely by the external-host default, not bychoice."""+ if _managed_mcp_restricted():+ return Falseif os.environ.get("UNSLOTH_STUDIO_ALLOW_STDIO_MCP") != "1":return Falsefrom state.tool_policy import get_tool_policy@@ -182,10 +280,13 @@ def stdio_mcp_enabled() -> bool:def stdio_mcp_disabled_reason() -> str:- """User-facing reason local commands are off, mirroring stdio_mcp_enabled(). Telling a user- whose gate is suspended by an active tunnel to set UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 would- re-enable local command execution on a published API, so the suspended cases must name their- actual cause."""+ """User-facing reason local commands are off, mirroring stdio_mcp_enabled().++ Telling a user whose gate is suspended by an active tunnel to set+ UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 would re-enable local command execution on+ a published API, so the suspended cases must name their actual cause."""+ if _managed_mcp_restricted():+ return "Only the installation owner may register local-command MCP servers."from state.tool_policy import get_tool_policyfrom utils.host_policy import loopback_default_active, remote_connector_active@@ -237,6 +338,19 @@ def parse_server_headers(server: dict) -> Optional[dict]:def _oauth_store():global _oauth_token_store+ if not is_owner_context():+ from key_value.aio._utils.sanitization import AlwaysHashStrategy+ from key_value.aio.stores.filetree import FileTreeStore+ from utils.paths.storage_roots import account_path, ensure_dir++ account_id = current_account_id()+ if account_id not in _account_oauth_token_stores:+ _account_oauth_token_stores[account_id] = FileTreeStore(+ data_directory = ensure_dir(account_path("mcp-oauth-tokens")),+ key_sanitization_strategy = AlwaysHashStrategy(),+ collection_sanitization_strategy = AlwaysHashStrategy(),+ )+ return _account_oauth_token_stores[account_id]if _oauth_token_store is None:from key_value.aio._utils.sanitization import AlwaysHashStrategyfrom key_value.aio.stores.filetree import FileTreeStore@@ -444,6 +558,7 @@ def _client(headers: Optional[dict],use_oauth: bool = False,):+ validate_mcp_address(url)from fastmcp import Clientif is_stdio(url):@@ -476,7 +591,12 @@ def _client(transport_cls = (SSETransport if infer_transport_type_from_url(url) == "sse" else StreamableHttpTransport)- return Client(transport_cls(url = url, headers = headers or None, auth = auth))+ kwargs = {}+ if _managed_mcp_restricted():+ kwargs["httpx_client_factory"] = _public_http_client_factory+ if auth is not None:+ auth.httpx_client_factory = _public_http_client_factory+ return Client(transport_cls(url = url, headers = headers or None, auth = auth, **kwargs))_SESSION_IDLE_TTL = 300.0@@ -682,6 +802,7 @@ class _McpSession:if use_oauth and not is_stdio(url):raise ValueError("OAuth MCP servers cannot use a shared session")self.url = url+ self.account_id = current_account_id()self.headers = headersself.client = Noneself.closed = threading.Event()@@ -705,7 +826,7 @@ class _McpSession:self.loop = asyncio.ProactorEventLoop()else:self.loop = asyncio.new_event_loop()- self._thread = threading.Thread(target = self._run_loop, name = "mcp-session", daemon = True)+ self._thread = account_thread(target = self._run_loop, name = "mcp-session", daemon = True)self._thread.start()def _run_loop(self) -> None:@@ -853,8 +974,9 @@ _mcp_cleanup_worker: Optional[threading.Thread] = None# missed and then cached already stale. Bump a generation on every close so that connect discards its session instead# of publishing it. Guarded by _mcp_sessions_lock._mcp_close_all_gen = 0-_mcp_url_close_gen: dict[str, int] = {}-_mcp_cfg_close_gen: dict[tuple, int] = {}+_mcp_account_close_gen: dict[str, int] = {}+_mcp_url_close_gen: dict[str | tuple[str, str], int] = {}+_mcp_cfg_close_gen: dict[str | tuple[str, str], int] = {}_mcp_connects_in_flight = 0_ANY_HEADERS = object()@@ -864,26 +986,27 @@ def _headers_key(headers: Optional[dict]) -> tuple:return tuple(sorted((headers or {}).items()))-def _url_close_key(url: str) -> str:- # Commands/URLs (token args, embedded credentials) and env values can hold secrets and these maps are never- # pruned; key by digest so closed/edited configs don't retain them in memory forever.- return hashlib.sha256(url.encode()).hexdigest()+def _url_close_key(url: str) -> str | tuple[str, str]:+ # Commands/URLs (token args, embedded credentials) and env values can hold+ # secrets and these maps are never pruned; key by digest so closed/edited+ # configs don't retain them in memory forever.+ return _account_key(hashlib.sha256(url.encode()).hexdigest())-def _cfg_close_key(url: str, headers: Optional[dict]) -> str:- return hashlib.sha256(repr((url, _headers_key(headers))).encode()).hexdigest()+def _cfg_close_key(url: str, headers: Optional[dict]) -> str | tuple[str, str]:+ return _account_key(hashlib.sha256(repr((url, _headers_key(headers))).encode()).hexdigest())-def _mcp_close_generation(url: str, headers: Optional[dict]) -> tuple[int, int, int]:+def _mcp_close_generation(url: str, headers: Optional[dict]) -> tuple[tuple[int, int], int, int]:return (- _mcp_close_all_gen,+ (_mcp_close_all_gen, _mcp_account_close_gen.get(current_account_id(), 0)),_mcp_url_close_gen.get(_url_close_key(url), 0),_mcp_cfg_close_gen.get(_cfg_close_key(url, headers), 0),)def _session_key(url: str, headers: Optional[dict], scope: Optional[str]) -> tuple:- return (url, _headers_key(headers), scope or "")+ return (url, _headers_key(headers), scope or "", current_account_id())def _checkout_session(key: tuple) -> tuple[Optional[_McpSession], float]:@@ -1006,7 +1129,7 @@ def _get_session(threading.Thread(target = _session_reaper, name = "mcp-session-reaper", daemon = True).start()- atexit.register(close_mcp_sessions)+ atexit.register(close_mcp_sessions, all_accounts = True)for victim in evicted:logger.info("Evicting LRU idle MCP session: %s", _session_log_id(victim.url))if evicted:@@ -1033,16 +1156,22 @@ def _release_session(session: _McpSession, defer_close: bool = False) -> None:# Re-enforce the cap once a burst's sessions go idle. Insert-time eviction only trims idle sessions, so it can# overshoot while every cached session is busy; reclaim that overshoot here instead of waiting for the idle# reaper. Never evict the session we just used (its last_used is newest).- while len(_mcp_sessions) > _MAX_SESSIONS:+ # The cap is per account: finishing a call must not close a cached session of an account under its own limit.+ account_id = getattr(session, "account_id", None) or current_account_id()+ mine = {+ k: s+ for k, s in _mcp_sessions.items()+ if (k[3] if len(k) > 3 else OWNER_ACCOUNT_ID) == account_id+ }+ while len(mine) > _MAX_SESSIONS:idle = [- (s.last_used, k)- for k, s in _mcp_sessions.items()- if s.in_flight == 0 and s is not session+ (s.last_used, k) for k, s in mine.items() if s.in_flight == 0 and s is not session]if not idle:break_, oldest = min(idle, key = lambda item: item[0])victims.append(_mcp_sessions.pop(oldest))+ mine.pop(oldest)_discard_key_lock(oldest)if close_now and defer_close:# This borrower was the last one on a session that has been discarded, either by its own failure or by a@@ -1081,29 +1210,53 @@ def _evict_lru_locked() -> list:under the cap. Returns the evicted sessions so the caller can close them OUTSIDE the lock. Ifevery session is busy the cache may transiently overshoot rather than kill an in-flight call."""victims: list = []- while len(_mcp_sessions) >= _MAX_SESSIONS:- idle = [(s.last_used, k) for k, s in _mcp_sessions.items() if s.in_flight == 0]+ if len(_mcp_sessions) < _MAX_SESSIONS:+ return victims+ account_id = current_account_id()+ candidates = {+ key: session+ for key, session in _mcp_sessions.items()+ if (key[3] if len(key) > 3 else OWNER_ACCOUNT_ID) == account_id+ }+ while len(candidates) >= _MAX_SESSIONS:+ idle = [(s.last_used, k) for k, s in candidates.items() if s.in_flight == 0]if not idle:break_, oldest = min(idle, key = lambda item: item[0])victims.append(_mcp_sessions.pop(oldest))+ candidates.pop(oldest)_discard_key_lock(oldest)return victims-def close_mcp_sessions(url: Optional[str] = None, headers = _ANY_HEADERS) -> None:+def close_mcp_sessions(+ url: Optional[str] = None,+ headers = _ANY_HEADERS,+ *,+ all_accounts: bool = False,+) -> None:global _mcp_close_all_genhk = None if headers is _ANY_HEADERS else _headers_key(headers)+ account_id = current_account_id()with _mcp_sessions_lock:keys = [- k for k in _mcp_sessions if (url is None or k[0] == url) and (hk is None or k[1] == hk)+ k+ for k in _mcp_sessions+ if (url is None or k[0] == url)+ and (hk is None or k[1] == hk)+ and (all_accounts or (k[3] if len(k) > 3 else OWNER_ACCOUNT_ID) == account_id)]sessions = [_mcp_sessions.pop(k) for k in keys]for key in keys:_discard_key_lock(key)if sessions or _mcp_connects_in_flight:if url is None:- _mcp_close_all_gen += 1+ if all_accounts:+ _mcp_close_all_gen += 1+ else:+ _mcp_account_close_gen[account_id] = (+ _mcp_account_close_gen.get(account_id, 0) + 1+ )elif hk is None:uk = _url_close_key(url)_mcp_url_close_gen[uk] = _mcp_url_close_gen.get(uk, 0) + 1@@ -1294,14 +1447,16 @@ async def list_tools_async(return await asyncio.wait_for(_fetch(), timeout = timeout)-# Discovered-tool cache, keyed by MCP server id. get_enabled_mcp_tools() probes a server only on a cache miss, keeping-# MCP discovery off the chat send's critical path -- tool schemas are stable within a session. The /refresh route-# warms it; a URL/header/OAuth change or a delete evicts it. Successful probes are cached indefinitely.-_tool_cache: dict[str, list[dict]] = {}+# Discovered-tool cache, keyed by MCP server id. get_enabled_mcp_tools() probes a server only+# on a cache miss, keeping MCP discovery off the chat send's critical path -- tool schemas are+# stable within a session. The /refresh route warms it; a URL/header/OAuth change or a delete+# evicts it. Successful probes are cached indefinitely.+_tool_cache: dict[str | tuple[str, str], list[dict]] = {}-# server_id -> monotonic time before which a failed server must not be re-probed (see record_probe_failure). Cleared-# on a successful probe or eviction.-_probe_cooloff_until: dict[str, float] = {}+# server_id -> monotonic time before which a failed server must not be+# re-probed (see record_probe_failure). Cleared on a successful probe or+# eviction.+_probe_cooloff_until: dict[str | tuple[str, str], float] = {}# Coordinate off-loop token-count snapshots with row and schema-cache mutations._mcp_server_snapshot_locks: WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Lock] = (@@ -1332,31 +1487,35 @@ TOOL_CACHE_INVALIDATING_FIELDS = frozenset({"url", "headers_json", "use_oauth",def get_cached_tools(server_id: str) -> Optional[list[dict]]:- return _tool_cache.get(server_id)+ return _tool_cache.get(_account_key(server_id))def cache_tools(server_id: str, tools: list[dict]) -> None:- _tool_cache[server_id] = tools- _probe_cooloff_until.pop(server_id, None)+ _tool_cache[_account_key(server_id)] = tools+ _probe_cooloff_until.pop(_account_key(server_id), None)def record_probe_failure(server_id: str, use_oauth: bool = False) -> None:cooloff = OAUTH_FAILED_PROBE_COOLOFF_SECONDS if use_oauth else FAILED_PROBE_COOLOFF_SECONDS- _probe_cooloff_until[server_id] = time.monotonic() + cooloff+ _probe_cooloff_until[_account_key(server_id)] = time.monotonic() + cooloffdef in_failure_cooloff(server_id: str) -> bool:- return _probe_cooloff_until.get(server_id, 0.0) > time.monotonic()+ return _probe_cooloff_until.get(_account_key(server_id), 0.0) > time.monotonic()def invalidate_tool_cache(server_id: Optional[str] = None) -> None:"""Evict one server's cached tools, or every entry when server_id is None."""if server_id is None:- _tool_cache.clear()- _probe_cooloff_until.clear()+ account_id = current_account_id()+ for cache in (_tool_cache, _probe_cooloff_until):+ for key in list(cache):+ owner = key[0] if isinstance(key, tuple) else OWNER_ACCOUNT_ID+ if owner == account_id:+ cache.pop(key, None)else:- _tool_cache.pop(server_id, None)- _probe_cooloff_until.pop(server_id, None)+ _tool_cache.pop(_account_key(server_id), None)+ _probe_cooloff_until.pop(_account_key(server_id), None)MCP_IMAGES_SENTINEL = "__MCP_IMAGES__:"diff --git a/studio/backend/core/inference/media_auto_switch.py b/studio/backend/core/inference/media_auto_switch.pyindex ff84f967903..faa6ced2fc0 100644--- a/studio/backend/core/inference/media_auto_switch.py+++ b/studio/backend/core/inference/media_auto_switch.py@@ -307,6 +307,7 @@ async def _gated_start_load(the switch out, and holding them would block new chat and video requests for as long as there-plan and the load registration take."""+ from fastapi import HTTPExceptionfrom core.inference.media_keepwarm import admission_gatefrom core.inference.llama_keepwarm import inference_lifecycle_gate@@ -351,7 +352,17 @@ async def _gated_start_load(setup = asyncio.ensure_future(_start_load(owner, pick, current_subject, hf_token))setup.add_done_callback(_consume_detached_error)with contextlib.suppress(asyncio.TimeoutError):- await asyncio.wait_for(asyncio.shield(setup), _SETUP_GRACE_S)+ try:+ await asyncio.wait_for(asyncio.shield(setup), _SETUP_GRACE_S)+ except HTTPException as exc:+ # The final arbiter check also covers a generation registered while load preparation was off the loop.+ if isinstance(exc.detail, dict) and exc.detail.get("error") == "gpu_busy":+ raise busy(+ kind,+ openai_errors,+ retry_after = int(exc.detail["retry_after"]),+ ) from exc+ raisereturn Falsefinally:for held in reversed(locks):diff --git a/studio/backend/core/inference/media_keepwarm.py b/studio/backend/core/inference/media_keepwarm.pyindex c6db9ae1038..259c616f9a8 100644--- a/studio/backend/core/inference/media_keepwarm.py+++ b/studio/backend/core/inference/media_keepwarm.py@@ -20,6 +20,8 @@ frees the host RAM the same weights occupy there, which is just as much the userfrom __future__ import annotations+# Resident media models are shared, so every account refreshes the same global activity clock.+import asyncioimport contextlibimport osdiff --git a/studio/backend/core/inference/media_model_index.py b/studio/backend/core/inference/media_model_index.pyindex d8ce2631c6d..9f7ab460bb5 100644--- a/studio/backend/core/inference/media_model_index.py+++ b/studio/backend/core/inference/media_model_index.py@@ -31,7 +31,7 @@ VIDEO_TASK = "text-to-video"# the scan walks several roots and reads gguf headers, and this runs per request_INDEX_TTL_S = 5.0_index_lock = threading.Lock()-_index: dict[str, tuple[float, dict[str, "MediaModelPick"]]] = {}+_index: dict[tuple[str, str], tuple[float, dict[str, "MediaModelPick"]]] = {}# the video family whose partitions are a load-time choice, not a property of the files_H3_FAMILY = "minimax-h3"@@ -332,15 +332,18 @@ def _mark_ambiguous_builds(index: dict[str, MediaModelPick]) -> dict[str, MediaMdef _cached_index(task: str) -> dict[str, MediaModelPick]:+ from utils.account_context import current_account_id++ key = (current_account_id(), task)now = time.monotonic()with _index_lock:- hit = _index.get(task)+ hit = _index.get(key)if hit is not None and now - hit[0] < _INDEX_TTL_S:return hit[1]built = _mark_ambiguous_builds(_build_index(task))with _index_lock:# stamped after the scan, so one slower than the ttl is not already expired- _index[task] = (time.monotonic(), built)+ _index[key] = (time.monotonic(), built)return builtdiff --git a/studio/backend/core/inference/media_switch_backends.py b/studio/backend/core/inference/media_switch_backends.pyindex 8829a18c92c..9cb9e9147fc 100644--- a/studio/backend/core/inference/media_switch_backends.py+++ b/studio/backend/core/inference/media_switch_backends.py@@ -16,8 +16,13 @@ import functoolsimport timefrom typing import Any, Optional-from core.inference.gpu_arbiter import DIFFUSION, VIDEO-from core.inference.media_switch_errors import probe+from core.inference.gpu_arbiter import (+ DIFFUSION,+ VIDEO,+ GpuBusyForAnotherAccountError,+ raise_if_other_accounts_active,+)+from core.inference.media_switch_errors import busy, probefrom core.inference.media_switch_locks import switcher_count, waiter_countPOLL_S = 0.2@@ -148,6 +153,11 @@ async def drain(# device configuration is resolved once, not on every poll: that cost ~150 round-trips a switchcross_owner = await asyncio.to_thread(load_takes_the_gpu)while True:+ if cross_owner:+ try:+ raise_if_other_accounts_active()+ except GpuBusyForAnotherAccountError as exc:+ raise busy(kind, openai_errors, retry_after = exc.retry_after) from exc# this request is itself tracked and itself a waiter, so it counts as neitherothers = other_request_count(owner, current_request_counted = True, count_pending = count_pendingdiff --git a/studio/backend/core/inference/media_switch_errors.py b/studio/backend/core/inference/media_switch_errors.pyindex bcb8430b127..f67130d998e 100644--- a/studio/backend/core/inference/media_switch_errors.py+++ b/studio/backend/core/inference/media_switch_errors.py@@ -87,14 +87,19 @@ def slow_switch(kind: str, openai_errors: bool):)-def busy(kind: str, openai_errors: bool):+def busy(+ kind: str,+ openai_errors: bool,+ *,+ retry_after: int = RETRY_AFTER_S,+):"""The refusal for a backend that stayed busy for the whole drain."""return refuse(BUSY_MSG.format(kind = kind),status_code = 409,openai_errors = openai_errors,code = "model_busy",- retry_after = RETRY_AFTER_S,+ retry_after = retry_after,)diff --git a/studio/backend/core/inference/openai_auto_download.py b/studio/backend/core/inference/openai_auto_download.pyindex 1c0e17a8b82..37f15e110d0 100644--- a/studio/backend/core/inference/openai_auto_download.py+++ b/studio/backend/core/inference/openai_auto_download.py@@ -33,6 +33,7 @@ from dataclasses import dataclassfrom typing import Optionalfrom loggers import get_logger+from utils.account_context import current_account_idlogger = get_logger(__name__)@@ -54,7 +55,7 @@ _RETRY_AFTER_S = 30# cannot hold the slot_FAILED_HOLD_S = 3 * _RETRY_AFTER_S_MAX_LISTED_VARIANTS = 8-# Probe the selected weight because speech GGUFs need not publish tokenizer sidecars.+# Probe the selected weight: speech GGUFs need not publish tokenizer sidecars._REMOTE_GGUF_SPEECH_PROBE_BYTES = 32 * 1024**2_REMOTE_GGUF_SPEECH_PROBE_TIMEOUT_S = _CODE_PROBE_TIMEOUT_S - 2.0@@ -82,6 +83,8 @@ class _Active:# the client would restart the same failing download.error: Optional[str] = Nonefailed_at: float = 0.0+ # Who asked: another account's busy answer names no repo or quant.+ account_id: Optional[str] = None_lock = threading.Lock()@@ -557,7 +560,9 @@ async def maybe_auto_download(busy = currentelse:adopted = None- provisional = _Active(repo_id = repo_id, started_at = time.time())+ provisional = _Active(+ repo_id = repo_id, started_at = time.time(), account_id = current_account_id()+ )_active = provisionalif busy is not None:@@ -566,13 +571,14 @@ async def maybe_auto_download(# a 2nd download.if not await _is_downloadable_model(repo_id, hf_token):return None+ if busy.account_id == current_account_id():+ what = f"Already downloading '{_public_label(busy.repo_id, busy.variant)}'."+ else:+ what = "Another download is in progress."return AutoDownloadRefusal(status = 503,code = "model_download_busy",- message = (- f"Already downloading '{_public_label(busy.repo_id, busy.variant)}'. "- f"Retry '{requested_model}' once it finishes."- ),+ message = f"{what} Retry '{requested_model}' once it finishes.",retry_after = _RETRY_AFTER_S,)@@ -777,7 +783,6 @@ async def _admit_and_start(default = (None, False),)if definitive and (audio_type is None or audio_type in GGUF_TTS_AUDIO_TYPES):- # Prefer the selected weight; use a supported sidecar only when it is inconclusive.sidecar_audio_type = audio_typemain_files = sorted(getattr(plan, "main_filenames", ()) or ())probed_audio_type, probed_definitive = await _bounded_probe(@@ -981,7 +986,14 @@ async def _dispatch(tracked = activeelse:# Released underneath us: track the job we started, but never stomp a newer owner.- tracked = _Active(repo_id, variant, expected_bytes, monitor_id, time.time())+ tracked = _Active(+ repo_id,+ variant,+ expected_bytes,+ monitor_id,+ time.time(),+ account_id = active.account_id,+ )if _active is None:_active = trackeddiff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.pyindex 5516ee15470..e0aaa2dc2a4 100644--- a/studio/backend/core/inference/providers.py+++ b/studio/backend/core/inference/providers.py@@ -694,6 +694,19 @@ _REGISTRY_HOSTNAMES = frozenset()+def _public_registry_hostname(host: str) -> bool:+ """A shipped public vendor hostname, usable by a managed account without a lookup."""+ host = (host or "").lower().rstrip(".")+ if host not in _REGISTRY_HOSTNAMES:+ return False+ if host == "localhost" or host.endswith(".localhost"):+ return False+ try:+ return ipaddress.ip_address(_canonical_host(host)).is_global+ except ValueError:+ return True++def _metadata_address(address: str) -> bool:"""``_metadata_host`` for a RESOLVED address: the exact services, no net.@@ -839,7 +852,13 @@ def _resolves_to_metadata(hostname: str, port: int | None, scheme: str) -> bool:)-def _reject_non_public(hostname: str, port: int | None, scheme: str) -> None:+def _managed_account_caller() -> bool:+ """True when this validation runs for a managed (non-owner) account."""+ from utils.account_context import is_owner_context+ return not is_owner_context()+++def _reject_non_public(hostname: str, port: int | None, scheme: str, reason: str) -> None:"""Raise when ``hostname`` is, or resolves to, a non-public address."""try:addresses = [ipaddress.ip_address(hostname)]@@ -867,10 +886,37 @@ def _reject_non_public(hostname: str, port: int | None, scheme: str) -> None:resolved = tuple(str(info[4][0]) for info in infos)addresses = [ipaddress.ip_address(address.split("%", 1)[0]) for address in resolved]if not addresses or any(not ip.is_global for ip in addresses):- raise ValueError(- "Provider base URL points at a private address, which is disabled on this "- f"server ({_BLOCK_PRIVATE_ENV}=1)."- )+ raise ValueError(reason)+++def public_provider_address(url: str) -> str:+ """Resolve ``url``'s host now and return one public address to dial, or raise ``ValueError``.++ Re-resolving per connection stops a name rebinding to loopback or the LAN after the+ cached check.+ """+ import socket++ parts = urlsplit(url)+ hostname = (parts.hostname or "").rstrip(".")+ if not hostname:+ raise ValueError("Provider URL must contain a hostname.")+ reason = "Managed accounts may only use public-network provider base URLs."+ try:+ addresses = [ipaddress.ip_address(_canonical_host(hostname))]+ except ValueError:+ try:+ infos = socket.getaddrinfo(+ _transport_host(hostname),+ parts.port or (443 if parts.scheme == "https" else 80),+ type = socket.SOCK_STREAM,+ )+ except (OSError, UnicodeError) as exc:+ raise ValueError("Provider base URL hostname could not be resolved.") from exc+ addresses = [ipaddress.ip_address(str(info[4][0]).split("%", 1)[0]) for info in infos]+ if not addresses or any(not ip.is_global for ip in addresses):+ raise ValueError(reason)+ return str(addresses[0])def validate_provider_base_url(base_url: str) -> str:@@ -883,7 +929,8 @@ def validate_provider_base_url(base_url: str) -> str:loopback, LAN hosts, odd ports, query strings and basic-auth userinfo allstay valid -- Ollama, llama.cpp, vLLM and custom gateways rely on them. Acaller-supplied hostname is resolved far enough to apply the metadata block- to DNS aliases of it; rejecting other private addresses stays opt-in.+ to DNS aliases of it; rejecting other private addresses stays opt-in for the+ owner, and is always on for a managed account (as managed MCP servers are).Normalization is strip + trailing-slash removal only (what the client didbefore), so validating an already-validated URL returns it unchanged.@@ -915,7 +962,21 @@ def validate_provider_base_url(base_url: str) -> str:raise ValueError("Cloud metadata endpoints cannot be used as a provider base URL.")if os.environ.get(_BLOCK_PRIVATE_ENV) == "1":- _reject_non_public(hostname, port, scheme)+ _reject_non_public(+ hostname,+ port,+ scheme,+ "Provider base URL points at a private address, which is disabled on this "+ f"server ({_BLOCK_PRIVATE_ENV}=1).",+ )+ elif _managed_account_caller() and not _public_registry_hostname(hostname):+ # Caller-controlled egress must not reach the owner's loopback models or LAN.+ _reject_non_public(+ hostname,+ port,+ scheme,+ "Managed accounts may only use public-network provider base URLs.",+ )return raw.rstrip("/")diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex e0c069c54d3..49343e10ae9 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -66,7 +66,6 @@ from core.inference.chat_template_helpers import (trailing_assistant_text,)from core.inference.passthrough_healing import nudge_enabled-from core.inference.tool_stream_exec import stream_tool_executionfrom state.tool_approvals import (TOOL_REJECTED_MESSAGE,abort_tool_decision,@@ -630,14 +629,13 @@ def run_safetensors_tool_loop(# keeps the sandbox but never prompts. An explicit confirm_tool_calls=True with# no mode is already resolved to "ask" at the request layer, so it never# arrives here as an ambiguous unset.- if permission_mode == "full":- bypass_permissions = True- elif bypass_permissions:- permission_mode = "full"- elif permission_mode is None:- permission_mode = "auto"- elif permission_mode not in ("ask", "auto", "off"):- permission_mode = "ask"+ from core.inference.tool_stream_exec import stream_tool_execution+ from state.tool_policy import account_tool_stream, normalize_tool_permissions++ permission_mode, bypass_permissions = normalize_tool_permissions(+ permission_mode, bypass_permissions+ )+ stream_tool_execution = account_tool_stream(stream_tool_execution)# Forced first-pass RAG (mirrors the GGUF loop) so doc Qs don't lose to# web_search. Skip only when a retrieval call would actually prompt (askdiff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex e2ee1994671..22806e745bc 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -82,6 +82,7 @@ from core.inference.sd_cpp_engine import ()from core.inference.sd_cpp_server import SdCppServerfrom loggers import get_logger+from utils.account_context import account_thread, current_account_idfrom utils.subprocess_compat import windows_hidden_subprocess_kwargslogger = get_logger(__name__)@@ -1029,6 +1030,7 @@ class SdCppDiffusionBackend:# Replaced (never cleared) per load, so a cancelled asset pull stays cancelled.self._cancel_event = threading.Event()self._active_generate_cancel: Optional[threading.Event] = None+ self._active_generate_account: Optional[str] = None# sd-server started for an in-flight load, before it commits to _state; tracked so an unload can stop it# mid-startup.self._pending_server: Optional[SdCppServer] = None@@ -1263,7 +1265,7 @@ class SdCppDiffusionBackend:),)- threading.Thread(+ account_thread(target = self._run_load,kwargs = dict(repo_id = repo_id,@@ -1662,6 +1664,13 @@ class SdCppDiffusionBackend:if self._load_token != _load_token:returnlogger.error("sd_cpp.load_failed: %s", exc)+ if self._state is not None:+ # Displaced pipeline: give its account back GPU residency, drop its records.+ from .gpu_arbiter import DIFFUSION, restore_owner_account+ from hub.services.models.account_access import restore_resident_metadata++ restore_owner_account(DIFFUSION)+ restore_resident_metadata("diffusion")# Redact filesystem paths before this reaches /images/load-progress (as diffusers does).from utils.native_path_leases import redact_native_paths@@ -2123,7 +2132,9 @@ class SdCppDiffusionBackend:)cancel = threading.Event()- with self._generate_lock:+ from hub.services.models.account_access import media_generation_slot++ with self._generate_lock, media_generation_slot("diffusion"):with self._lock:state = self._stateif state is None:@@ -2142,6 +2153,7 @@ class SdCppDiffusionBackend:if expected_load is not None and expected_load != loaded_id:raise DiffusionModelReplacedError(expected_load, loaded_id)self._active_generate_cancel = cancel+ self._active_generate_account = current_account_id()# Publish an active (step 0) state before the slow pre-generate setup so a reload probe does not read# idle while this holds _generate_lock.self._gen = _SdGen(total_steps = int(steps))@@ -2212,6 +2224,7 @@ class SdCppDiffusionBackend:raise RuntimeError(DIFFUSION_CANCELLED_MSG)if self._active_generate_cancel is cancel:self._active_generate_cancel = None+ self._active_generate_account = Nonereturn {"images": images,"seed": int(seed),@@ -2241,6 +2254,7 @@ class SdCppDiffusionBackend:with self._lock:if self._active_generate_cancel is cancel:self._active_generate_cancel = None+ self._active_generate_account = Nonedef _generate_server(self,@@ -2558,22 +2572,43 @@ class SdCppDiffusionBackend:"eta_seconds": gen.eta_seconds,}- def cancel_generate(self) -> bool:- """Signal the in-flight generation to stop, matching DiffusionBackend.cancel_generate. The- native engine is stricter than best-effort: the runner polls this event and kills the- sd-cli process tree, so the stop lands within the poll interval rather than at the next- step boundary. Returns False when nothing is running."""+ def cancel_generate(self, expected_account: Optional[str] = None) -> bool:+ """Signal the in-flight generation to stop, matching DiffusionBackend.cancel_generate.++ The native engine is stricter than best-effort: the runner polls this event and kills+ the sd-cli process tree, so the stop lands within the poll interval rather than at the+ next step boundary. Returns False when nothing is running."""with self._lock:cancel = self._active_generate_cancelif cancel is None:return False+ # Rechecked under the lock that bound it: the slot may have changed hands.+ if expected_account is not None and self._active_generate_account not in (+ None,+ expected_account,+ ):+ return Falsecancel.set()return True- def unload(self) -> dict[str, Any]:+ # ── Unload / status ──────────────────────────────────────────────────────++ def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:with self._lock:- # Under the lock: begin_load rebinds this attribute, so an unlocked read could set an event the current- # load no longer watches.+ if expected_account is not None:+ from .gpu_arbiter import DIFFUSION, GpuBusyForAnotherAccountError+ from hub.services.models.account_access import require_resident_control++ if (+ self._active_generate_cancel is not None+ and self._active_generate_account != expected_account+ ):+ raise GpuBusyForAnotherAccountError(DIFFUSION, 1)+ require_resident_control(+ DIFFUSION, self._state.repo_id if self._state is not None else None+ )+ # Under the lock: begin_load rebinds this attribute, so an unlocked read could set an event the current load+ # no longer watches.self._cancel_event.set()if self._active_generate_cancel is not None:self._active_generate_cancel.set()diff --git a/studio/backend/core/inference/search_images.py b/studio/backend/core/inference/search_images.pyindex a8030881469..b99f9bdd2a9 100644--- a/studio/backend/core/inference/search_images.py+++ b/studio/backend/core/inference/search_images.py@@ -11,6 +11,10 @@ import jsonimport reimport secretsimport threading+import sys+from types import SimpleNamespace++from utils.account_context import current_account_id, is_owner_contextimport timefrom pathlib import Pathfrom typing import Any@@ -66,6 +70,28 @@ _inflight: dict[str, threading.Lock] = {}_inflight_lock = threading.Lock()+_account_states_lock = threading.Lock()+_account_states: dict[str, SimpleNamespace] = {}+++def _account_state():+ if is_owner_context():+ return sys.modules[__name__]+ with _account_states_lock:+ key = current_account_id()+ if key not in _account_states:+ _account_states[key] = SimpleNamespace(+ _registry = {},+ _cache_generation = 0,+ _full_clear_generation = 0,+ _reaped_at = {},+ _reaped_floor_generation = 0,+ _cleared_unservable = set(),+ _inflight = {},+ )+ return _account_states[key]++def search_images_enabled() -> bool:try:from storage.studio_db import list_chat_settings@@ -106,13 +132,16 @@ def _names_public_host(url: str) -> bool:def _prune_registry_locked(now: float) -> None:- expired = [key for key, entry in _registry.items() if now - entry["created"] > _REGISTRY_TTL_S]+ state = _account_state()+ expired = [+ key for key, entry in state._registry.items() if now - entry["created"] > _REGISTRY_TTL_S+ ]for key in expired:- _registry.pop(key, None)- if len(_registry) > _REGISTRY_MAX_ENTRIES:- oldest = sorted(_registry.items(), key = lambda item: item[1]["created"])- for key, _entry in oldest[: len(_registry) - _REGISTRY_MAX_ENTRIES]:- _registry.pop(key, None)+ state._registry.pop(key, None)+ if len(state._registry) > _REGISTRY_MAX_ENTRIES:+ oldest = sorted(state._registry.items(), key = lambda item: item[1]["created"])+ for key, _entry in oldest[: len(state._registry) - _REGISTRY_MAX_ENTRIES]:+ state._registry.pop(key, None)def register_images(@@ -123,13 +152,14 @@ def register_images(expected_generation: int | None = None,) -> list[dict[str, str]]:# Public entries only; the URLs stay in this process.+ state = _account_state()from .web_access_policy import check_url_accesspublic: list[dict[str, str]] = []persist: list[tuple[str, dict[str, Any], int]] = []now = time.monotonic()with _registry_lock:- generation = _cache_generation+ generation = state._cache_generationif expected_generation is not None and expected_generation != generation:return []_prune_registry_locked(now)@@ -149,7 +179,7 @@ def register_images(if not (_names_public_host(thumbnail) and _names_public_host(source)):continueimage_id = secrets.token_hex(6)- _registry[image_id] = {+ state._registry[image_id] = {"thumbnail": thumbnail,"source": source,"created": now,@@ -166,7 +196,7 @@ def register_images(if subject:entry["subject"] = _clean_text(subject, 80)public.append(entry)- persist.append((image_id, _registry[image_id], generation))+ persist.append((image_id, state._registry[image_id], generation))for image_id, stored, registered_generation in persist:_persist_entry(image_id, stored, registered_generation)if persist:@@ -177,17 +207,19 @@ def register_images(def cache_generation() -> int:+ state = _account_state()with _registry_lock:- return _cache_generation+ return state._cache_generationdef _lookup_locked(image_id: str) -> dict[str, Any] | None:"""Registry read with the TTL applied. The caller holds ``_registry_lock``."""- entry = _registry.get(image_id)+ state = _account_state()+ entry = state._registry.get(image_id)if entry is None:return Noneif time.monotonic() - entry["created"] > _REGISTRY_TTL_S:- _registry.pop(image_id, None)+ state._registry.pop(image_id, None)return Nonereturn dict(entry)@@ -257,8 +289,9 @@ def strip_images_suffix(result: str) -> str:def _cache_dir() -> Path:- from utils.paths import ensure_dir, studio_root- return ensure_dir(studio_root() / _CACHE_DIRNAME)+ from utils.paths import ensure_account_dir+ from utils.paths.storage_roots import account_path+ return ensure_account_dir(account_path(_CACHE_DIRNAME))def _cache_path(image_id: str) -> Path:@@ -400,19 +433,21 @@ def _drop_if_cleared(image_id: str) -> bool:has usually let go by the next request, and once both files are gone the id isordinary again -- nothing resolves it, so it 404s like any other unknown one."""+ state = _account_state()with _registry_lock:- if image_id not in _cleared_unservable:+ if image_id not in state._cleared_unservable:return Truefor path in (_cache_path(image_id), _meta_path(image_id)):try:path.unlink(missing_ok = True)except OSError:return False- _cleared_unservable.discard(image_id)+ state._cleared_unservable.discard(image_id)return Truedef thumbnail_bytes(image_id: str) -> bytes | None:+ state = _account_state()if not IMAGE_ID_RE.fullmatch(image_id or ""):return None# Ahead of that read and of the sidecar below, which both go around the registry.@@ -429,7 +464,7 @@ def thumbnail_bytes(image_id: str) -> bytes | None:# clear had just deleted would be written back. Reading it first is the safe order -- a clear after this point# leaves us holding a stale value, which fails the check.with _registry_lock:- generation = _cache_generation+ generation = state._cache_generationentry = _lookup_locked(image_id)if entry is None:# Not in memory: the process may have restarted since the search. The metadata on disk outlives it, the same way@@ -439,7 +474,7 @@ def thumbnail_bytes(image_id: str) -> bytes | None:return Nonewith _inflight_lock:- gate = _inflight.setdefault(image_id, threading.Lock())+ gate = state._inflight.setdefault(image_id, threading.Lock())try:with gate:try:@@ -475,8 +510,8 @@ def thumbnail_bytes(image_id: str) -> bytes | None:finally:with _inflight_lock:# Only drop the gate this call owns.- if _inflight.get(image_id) is gate and not gate.locked():- _inflight.pop(image_id, None)+ if state._inflight.get(image_id) is gate and not gate.locked():+ state._inflight.pop(image_id, None)def registered_image_ids() -> set[str] | None:@@ -486,9 +521,10 @@ def registered_image_ids() -> set[str] | None:A clear is global while the chat delete it accompanies is not, so anything thatregisters after this snapshot belongs to a chat the delete is keeping."""+ state = _account_state()ids: set[str] = set()with _registry_lock:- ids.update(_registry)+ ids.update(state._registry)for pattern in ("*.jpg", "*.json"):try:ids.update(path.stem for path in _cache_dir().glob(pattern))@@ -519,11 +555,11 @@ def snapshot_and_fence_registrations() -> set[str] | None:in-flight FETCHES: those are keyed per id now, and a bare generation move is not one ofthe signals they read."""- global _cache_generation+ state = _account_state()ids: set[str] = set()with _registry_lock:- ids.update(_registry)- _cache_generation += 1+ ids.update(state._registry)+ state._cache_generation += 1for pattern in ("*.jpg", "*.json"):try:ids.update(path.stem for path in _cache_dir().glob(pattern))@@ -536,11 +572,12 @@ def snapshot_and_fence_registrations() -> set[str] | None:def _reaped_since_locked(image_id: str, generation: int) -> bool:"""Whether a clear covering ``image_id`` landed after ``generation``. Caller holds the lock."""- if _full_clear_generation > generation:+ state = _account_state()+ if state._full_clear_generation > generation:return True- if generation < _reaped_floor_generation:+ if generation < state._reaped_floor_generation:return True- return _reaped_at.get(image_id, 0) > generation+ return state._reaped_at.get(image_id, 0) > generationdef clear_cache(only_ids: set[str] | None = None) -> None:@@ -554,35 +591,35 @@ def clear_cache(only_ids: set[str] | None = None) -> None:refuse a registration racing a clear -- but the in-flight fetch check is per id, so aspared image's fetch is left alone. Aborting it would 404 a card that never retries."""- global _cache_generation, _full_clear_generation, _reaped_floor_generation+ state = _account_state()# The unlinks are under the lock too, so an in-flight fetch cannot slip its write in between the bump and the delete# and leave a cleared thumbnail on disk.with _registry_lock:if only_ids is None:- _registry.clear()+ state._registry.clear()else:for image_id in only_ids:- _registry.pop(image_id, None)- _cache_generation += 1+ state._registry.pop(image_id, None)+ state._cache_generation += 1if only_ids is None:# Nothing survives, so every in-flight fetch has to abort. One number says so for all of them, including ids# this process has never seen.- _full_clear_generation = _cache_generation- _reaped_at.clear()+ state._full_clear_generation = state._cache_generation+ state._reaped_at.clear()else:- if len(_reaped_at) + len(only_ids) > _REAPED_AT_MAX:+ if len(state._reaped_at) + len(only_ids) > _REAPED_AT_MAX:# Out of room. Drop the OLDEST records rather than promoting this to a full clear: doing that aborts# every fetch in flight, including ones for images this clear spared, and an aborted fetch is not a# cheap retry -- the card 404s and useSearchThumbnail never asks again. Raising the floor instead gives# up only on fetches older than every record still held, which the fetch timeout makes unreachable in# practice.- keep_from = sorted(_reaped_at.values())[len(_reaped_at) // 2 :]- floor = keep_from[0] - 1 if keep_from else _cache_generation- for stale_id in [key for key, at in _reaped_at.items() if at <= floor]:- _reaped_at.pop(stale_id, None)- _reaped_floor_generation = max(_reaped_floor_generation, floor)+ keep_from = sorted(state._reaped_at.values())[len(state._reaped_at) // 2 :]+ floor = keep_from[0] - 1 if keep_from else state._cache_generation+ for stale_id in [key for key, at in state._reaped_at.items() if at <= floor]:+ state._reaped_at.pop(stale_id, None)+ state._reaped_floor_generation = max(state._reaped_floor_generation, floor)for image_id in only_ids:- _reaped_at[image_id] = _cache_generation+ state._reaped_at[image_id] = state._cache_generationfor pattern in ("*.jpg", "*.json", "*.tmp"):try:paths = list(_cache_dir().glob(pattern))@@ -601,4 +638,4 @@ def clear_cache(only_ids: set[str] | None = None) -> None:# Still on disk, so remember the id and refuse to serve it until the unlink does land.# `.jpg`/`.json` share a stem; a `.tmp` was never servable, and its stem carries the writer suffix.if pattern != "*.tmp":- _cleared_unservable.add(path.stem)+ state._cleared_unservable.add(path.stem)diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 2cb50e7ffa2..ec493b8b115 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -1189,9 +1189,13 @@ async def stream_with_studio_tools(tool_choice = run.tool_choice if run.tool_choice is not None else "auto"allowed_tool_names = _tool_names(tools)tool_call_timeout = policy.timeout- permission_mode = policy.permission_mode+ from state.tool_policy import account_tool_stream, normalize_tool_permissions++ permission_mode, bypass_permissions = normalize_tool_permissions(+ policy.permission_mode, policy.bypass_permissions+ )+ scoped_tool_stream = account_tool_stream(stream_tool_execution)confirm_tool_calls = policy.confirm_calls- bypass_permissions = policy.bypass_permissionsrag_scope = policy.rag_scope# The promotion allowlist is the selected catalog, never None: an unrestricted parse re-opens markerless tool-call@@ -1728,7 +1732,7 @@ async def stream_with_studio_tools(# The same wrapper the local loops run tools through: live stdout for the card, and a heartbeat so a long# call cannot idle the stream out.- tool_stream = stream_tool_execution(+ tool_stream = scoped_tool_stream(_invoke,tool_name = name,tool_call_id = card_id,diff --git a/studio/backend/core/inference/tool_confinement.py b/studio/backend/core/inference/tool_confinement.pynew file mode 100644index 00000000000..db669e3738d--- /dev/null+++ b/studio/backend/core/inference/tool_confinement.py@@ -0,0 +1,512 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Confine managed-account tool procs: Landlock (Linux), sandbox-exec (macOS), else refuse."""++from __future__ import annotations++import ctypes+import os+from pathlib import Path+import shutil+import sys+from dataclasses import dataclass+from functools import partial+from typing import Callable, Optional++from utils.account_context import is_owner_context++_OVERRIDE_ENV = "UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS"++# Landlock syscall numbers are architecture independent.+_SYS_LANDLOCK_CREATE_RULESET = 444+_SYS_LANDLOCK_ADD_RULE = 445+_SYS_LANDLOCK_RESTRICT_SELF = 446+_LANDLOCK_CREATE_RULESET_VERSION = 1+_LANDLOCK_RULE_PATH_BENEATH = 1+_PR_SET_NO_NEW_PRIVS = 38++_FS_EXECUTE = 1 << 0+_FS_WRITE_FILE = 1 << 1+_FS_READ_FILE = 1 << 2+_FS_READ_DIR = 1 << 3+_FS_MAKE_SYM = 1 << 12+_FS_REFER = 1 << 13 # ABI 2+_FS_TRUNCATE = 1 << 14 # ABI 3+_FS_IOCTL_DEV = 1 << 15 # ABI 5+_SCOPE_SIGNAL = 1 << 1 # ABI 6: signals confined to the same domain+_FS_ABI1_MASK = (1 << 13) - 1++_SYSTEM_READ_ROOTS = (+ "/usr",+ "/lib",+ "/lib32",+ "/lib64",+ "/bin",+ "/sbin",+ "/etc",+ "/opt",+ "/run",+ "/snap",+ "/nix",+ "/var/lib",+ "/proc",+ "/sys",+)+# Pseudo-devices every tool needs, then the accelerator nodes. The rest of /dev stays out: other+# sessions' ptys, same-UID shm objects and, for a root-run Studio, every block and character device.+_DEVICE_NODES = ("/dev/null", "/dev/zero", "/dev/full", "/dev/random", "/dev/urandom", "/dev/tty")+_ACCELERATOR_NODES = (+ "/dev/nvidiactl",+ "/dev/nvidia-uvm",+ "/dev/nvidia-uvm-tools",+ "/dev/nvidia-modeset",+ "/dev/nvidia-caps",+ "/dev/dri",+ "/dev/kfd",+)++# Readable by the service user, so DAC alone does not stop a tool. The rest of /run is readable.+_PRIVATE_RUNTIME_ROOTS = ("/run/user", "/run/secrets", "/run/credentials")+# Secrets a root-run Studio (the Docker image) could otherwise hand a managed tool; the rest of /etc+# (ld.so.cache, nsswitch, hosts, resolv.conf, ssl/certs) is what tool processes need.+_PRIVATE_SYSTEM_PATHS = (+ "/etc/shadow",+ "/etc/shadow-",+ "/etc/gshadow",+ "/etc/gshadow-",+ "/etc/security/opasswd",+ "/etc/sudoers",+ "/etc/sudoers.d",+ "/etc/ssl/private",+ "/etc/pki/tls/private",+ "/etc/letsencrypt",+ "/etc/krb5.keytab",+ "/etc/ipsec.secrets",+ "/etc/docker/key.json",+ "/etc/ssh/ssh_host_*_key",+)+++def _private_system_paths() -> list[str]:+ import glob++ out: list[str] = []+ for pattern in _PRIVATE_SYSTEM_PATHS:+ out.extend(sorted(glob.glob(pattern)) if any(ch in pattern for ch in "*?[") else [pattern])+ return out+++class ToolConfinementUnavailable(RuntimeError):+ """This host cannot confine a managed account's tool process."""+++@dataclass(frozen = True)+class Confinement:+ """``preexec`` runs in the forked child (Linux); ``wrap`` rewrites argv (macOS)."""++ mechanism: str+ preexec: Optional[Callable[[], None]] = None+ wrapper: tuple[str, ...] = ()++ def wrap(self, argv: list[str]) -> list[str]:+ return [*self.wrapper, *argv] if self.wrapper else argv+++def unconfined_tools_allowed() -> bool:+ return (os.environ.get(_OVERRIDE_ENV) or "").strip().lower() in ("1", "true", "yes", "on")+++def refusal_message() -> str:+ return (+ "Code execution is unavailable for this account: this host cannot confine tool "+ "processes to your workspace (Landlock ABI 6 on Linux 6.12 or later, sandbox-exec "+ f"on macOS). The installation owner can set {_OVERRIDE_ENV}=1 to allow unconfined "+ "tool processes for managed accounts."+ )+++def _existing(paths) -> list[str]:+ seen: list[str] = []+ for raw in paths:+ if not raw:+ continue+ try:+ path = os.path.realpath(raw)+ except (OSError, ValueError):+ continue+ if os.path.exists(path) and path not in seen:+ seen.append(path)+ return seen+++def _interpreter_roots() -> list[str]:+ return _existing(+ (+ sys.prefix,+ sys.base_prefix,+ sys.exec_prefix,+ getattr(sys, "base_exec_prefix", ""),+ os.path.dirname(sys.executable),+ os.environ.get("VIRTUAL_ENV", ""),+ )+ )+++def _ensure_dirs(paths) -> list[str]:+ """Landlock rules need existing paths; ``ensure_dir`` refuses a launch racing account delete."""+ from utils.paths.storage_roots import ensure_dir++ roots = []+ for root in paths:+ try:+ ensure_dir(Path(root))+ except OSError:+ continue+ roots.append(str(root))+ return _existing(roots)+++def _readable_account_roots() -> list[str]:+ """Account workspace: readable, never writable, else a tool could rewrite its own grants."""+ from utils.paths.storage_roots import workspace_root+ return _ensure_dirs((workspace_root(),))+++def _writable_roots() -> list[str]:+ from core.inference.tools import sandbox_root+ from utils.paths.storage_roots import project_workspaces_root, tmp_root+ return _ensure_dirs((sandbox_root(), tmp_root(), project_workspaces_root()))+++def _hf_cache_roots() -> tuple[str, ...]:+ """Install-wide HF cache: an ancestor read grant would leak other accounts' repos and tokens."""+ try:+ from utils.hf_cache_settings import known_hf_cache_homes, known_hf_hub_caches+ return tuple(str(p) for p in (*known_hf_cache_homes(), *known_hf_hub_caches()))+ except Exception:+ return ()+++def _protected_roots() -> list[str]:+ from core.inference.tools import shared_sandbox_root+ from utils.paths.storage_roots import (+ shared_project_workspaces_root,+ shared_tmp_root,+ studio_root,+ )+ return _with_shared_bases(+ _existing((studio_root(),)),+ (+ shared_sandbox_root(),+ shared_project_workspaces_root(),+ shared_tmp_root(),+ *_hf_cache_roots(),+ ),+ )+++def _contains(ancestor: str, path: str) -> bool:+ return path == ancestor or path.startswith(ancestor.rstrip(os.sep) + os.sep)+++def _with_shared_bases(roots: list[str], bases) -> list[str]:+ out = list(roots)+ for base in _existing(bases):+ if not any(_contains(root, base) for root in out):+ out.append(base)+ return out+++def _grant_excluding(+ path: str, access: int, protected: list[str], rules: list[tuple[str, int]]+) -> None:+ """Landlock has no deny rule, so grant an ancestor child by child."""+ inside = [p for p in protected if _contains(path, p)]+ if not inside:+ # A plain-file rule may not carry directory rights.+ rules.append((path, access if os.path.isdir(path) else access & ~_FS_READ_DIR))+ return+ if any(p == path for p in inside):+ return+ try:+ children = sorted(os.listdir(path))+ except OSError:+ return+ for name in children:+ child = os.path.join(path, name)+ if not os.path.exists(child):+ # A dangling link cannot carry a rule.+ continue+ if os.path.islink(child):+ # A link opens as its target, so one near a protected root would grant that tree.+ target = os.path.realpath(child)+ if any(_contains(p, target) or _contains(target, p) for p in protected):+ continue+ _grant_excluding(child, access, protected, rules)+++class _RulesetAttr(ctypes.Structure):+ # Later ABIs accept this ABI 1 size, zeroing the rest.+ _fields_ = [("handled_access_fs", ctypes.c_uint64)]+++class _ScopedRulesetAttr(ctypes.Structure):+ _fields_ = [+ ("handled_access_fs", ctypes.c_uint64),+ ("handled_access_net", ctypes.c_uint64),+ ("scoped", ctypes.c_uint64),+ ]+++class _PathBeneathAttr(ctypes.Structure):+ _pack_ = 1+ _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]+++_libc = None+if sys.platform == "linux":+ try:+ import ctypes.util+ _name = ctypes.util.find_library("c")+ _libc = ctypes.CDLL(_name, use_errno = True) if _name else None+ except (OSError, AttributeError):+ _libc = None++_landlock_abi: Optional[int] = None+++def landlock_abi() -> int:+ """Highest Landlock ABI of the running kernel, 0 when unavailable."""+ global _landlock_abi+ if _landlock_abi is not None:+ return _landlock_abi+ abi = 0+ if sys.platform == "linux" and _libc is not None:+ try:+ got = _libc.syscall(+ _SYS_LANDLOCK_CREATE_RULESET, None, 0, _LANDLOCK_CREATE_RULESET_VERSION+ )+ abi = int(got) if got > 0 else 0+ except (OSError, AttributeError, ValueError):+ abi = 0+ _landlock_abi = abi+ return abi+++def _handled_mask(abi: int) -> int:+ mask = _FS_ABI1_MASK+ if abi >= 2:+ mask |= _FS_REFER+ if abi >= 3:+ mask |= _FS_TRUNCATE+ if abi >= 5:+ mask |= _FS_IOCTL_DEV+ return mask+++def _device_nodes() -> list[str]:+ import glob+ return _existing((*_DEVICE_NODES, *_ACCELERATOR_NODES, *sorted(glob.glob("/dev/nvidia[0-9]*"))))+++def _landlock_rules(abi: int, sandbox_site_dir: str) -> list[tuple[str, int]]:+ handled = _handled_mask(abi)+ read = _FS_READ_FILE | _FS_READ_DIR | _FS_EXECUTE+ device = _FS_READ_FILE | _FS_WRITE_FILE | (_FS_IOCTL_DEV if abi >= 5 else 0)+ rules: list[tuple[str, int]] = []+ writable_roots = _writable_roots()+ protected = _protected_roots()+ # /dev is protected too, so a system-root link such as /run/shm cannot grant a device tree.+ system_protected = _with_shared_bases(+ protected, (*_PRIVATE_RUNTIME_ROOTS, "/dev", *_private_system_paths())+ )+ for path in _existing(_SYSTEM_READ_ROOTS):+ _grant_excluding(path, read, system_protected, rules)+ for path in _interpreter_roots():+ _grant_excluding(path, read, protected, rules)+ for path in _existing((sandbox_site_dir,)):+ _grant_excluding(path, read, protected, rules)+ for path in _readable_account_roots():+ rules.append((path, read))+ for path in _device_nodes():+ rules.append((path, device | (_FS_READ_DIR if os.path.isdir(path) else 0)))+ # No symlink creation: the server follows links, so a tool must not plant an escaping one.+ writable = handled & ~_FS_MAKE_SYM+ for path in writable_roots:+ rules.append((path, writable))+ return rules+++def _landlock_preexec(+ handled: int,+ rules: list[tuple[str, int]],+ scoped: int = 0,+) -> None:+ """Runs in the forked child: no imports, no allocation beyond ctypes."""+ libc = _libc+ attr = _ScopedRulesetAttr(handled, 0, scoped) if scoped else _RulesetAttr(handled)+ ruleset_fd = libc.syscall(+ _SYS_LANDLOCK_CREATE_RULESET, ctypes.byref(attr), ctypes.sizeof(attr), 0+ )+ if ruleset_fd < 0:+ raise OSError(ctypes.get_errno(), "landlock_create_ruleset failed")+ try:+ for path, access in rules:+ parent_fd = os.open(path, os.O_PATH | os.O_CLOEXEC)+ try:+ beneath = _PathBeneathAttr(access & handled, parent_fd)+ rc = libc.syscall(+ _SYS_LANDLOCK_ADD_RULE,+ ruleset_fd,+ _LANDLOCK_RULE_PATH_BENEATH,+ ctypes.byref(beneath),+ 0,+ )+ if rc < 0:+ raise OSError(ctypes.get_errno(), f"landlock_add_rule failed for {path}")+ finally:+ os.close(parent_fd)+ if libc.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0:+ raise OSError(ctypes.get_errno(), "PR_SET_NO_NEW_PRIVS failed")+ if libc.syscall(_SYS_LANDLOCK_RESTRICT_SELF, ruleset_fd, 0) < 0:+ raise OSError(ctypes.get_errno(), "landlock_restrict_self failed")+ finally:+ os.close(ruleset_fd)+++# Only ABI 6+ (Linux 6.12) scopes signals; below it a child can kill the server over the shared UID.+_MIN_LANDLOCK_ABI = 6+++def _linux_confinement(sandbox_site_dir: str) -> Optional[Confinement]:+ abi = landlock_abi()+ if abi < _MIN_LANDLOCK_ABI:+ return None+ handled = _handled_mask(abi)+ rules = _landlock_rules(abi, sandbox_site_dir)+ return Confinement(+ mechanism = f"landlock-abi{abi}",+ preexec = partial(_landlock_preexec, handled, rules, _SCOPE_SIGNAL),+ )+++def _sbpl(path: str) -> str:+ return '"' + path.replace("\\", "\\\\").replace('"', '\\"') + '"'+++def _darwin_user_cache_dirs() -> tuple[str, ...]:+ try:+ cache = (os.confstr("CS_DARWIN_USER_CACHE_DIR") or "").rstrip(os.sep)+ except (AttributeError, ValueError, OSError):+ return ()+ if not cache:+ return ()+ bare = cache[len("/private") :] if cache.startswith("/private/") else cache+ return (bare, "/private" + bare)+++def macos_profile(+ *,+ read_roots: list[str],+ hidden_roots: list[str],+ writable_roots: list[str],+ account_read_roots: list[str] = (),+) -> str:+ """sandbox-exec profile; later rules win, so account roots outrank the install deny."""+ lines = [+ "(version 1)",+ "(deny default)",+ "(allow process-fork)",+ "(allow process-exec)",+ "(allow signal (target same-sandbox))",+ "(allow sysctl-read)",+ "(allow mach-lookup)",+ "(allow ipc-posix-shm)",+ "(allow network*)",+ "(allow file-read-metadata)",+ # Pseudo-devices only; the rest of /dev (other sessions' ttys, disks) stays denied.+ '(allow file-read* file-write* (literal "/dev/null") (literal "/dev/zero") (literal "/dev/random")'+ ' (literal "/dev/urandom") (literal "/dev/tty") (literal "/dev/dtracehelper"))',+ '(allow file-ioctl (literal "/dev/tty") (literal "/dev/dtracehelper"))',+ '(allow file-read* (subpath "/dev/fd"))',+ # No shared /private/tmp: the account tmp root is granted with the writable roots.+ '(allow file-read* (subpath "/private/var/db"))',+ # The per-user darwin tree holds every account tmp root: deny it, keep dyld's cache dir.+ '(deny file-read* file-write* (subpath "/private/var/folders") (subpath "/var/folders"))',+ *(f"(allow file-read* (subpath {_sbpl(path)}))" for path in _darwin_user_cache_dirs()),+ ]+ for path in read_roots:+ lines.append(f"(allow file-read* (subpath {_sbpl(path)}))")+ for path in hidden_roots:+ lines.append(f"(deny file-read* file-write* (subpath {_sbpl(path)}))")+ for path in read_roots:+ if not any(_contains(root, path) and root != path for root in hidden_roots):+ continue+ lines.append(f"(allow file-read* (subpath {_sbpl(path)}))")+ for root in hidden_roots:+ if _contains(path, root) and root != path:+ lines.append(f"(deny file-read* file-write* (subpath {_sbpl(root)}))")+ for path in account_read_roots:+ lines.append(f"(allow file-read* (subpath {_sbpl(path)}))")+ for path in writable_roots:+ lines.append(f"(allow file-read* file-write* (subpath {_sbpl(path)}))")+ # file-write* covers symlinks; deny last (later rules win), matching Landlock's held MAKE_SYM.+ lines.append("(deny file-write-create (vnode-type SYMLINK))")+ return "\n".join(lines) + "\n"+++def _macos_confinement(sandbox_site_dir: str) -> Optional[Confinement]:+ sandbox_exec = shutil.which("sandbox-exec")+ if not sandbox_exec:+ return None+ from core.inference.tools import shared_sandbox_root+ from utils.paths.storage_roots import (+ shared_project_workspaces_root,+ shared_tmp_root,+ studio_root,+ )++ read_roots = _existing(+ (+ "/usr",+ "/bin",+ "/sbin",+ "/etc",+ "/private/etc",+ "/System",+ "/Library",+ "/opt",+ "/Applications",+ *_interpreter_roots(),+ sandbox_site_dir,+ )+ )+ writable_roots = _writable_roots()+ hidden_roots = _with_shared_bases(+ _existing((str(studio_root()), str(shared_tmp_root()), os.path.expanduser("~"))),+ (shared_sandbox_root(), str(shared_project_workspaces_root()), *_hf_cache_roots()),+ )+ profile = macos_profile(+ read_roots = read_roots,+ hidden_roots = hidden_roots,+ account_read_roots = _readable_account_roots(),+ writable_roots = writable_roots,+ )+ return Confinement(mechanism = "sandbox-exec", wrapper = (sandbox_exec, "-p", profile))+++def account_confinement(sandbox_site_dir: str) -> Optional[Confinement]:+ """Confinement for the account's next tool child; ``None`` for owner, raises on bad host."""+ if is_owner_context():+ return None+ confinement = None+ if sys.platform == "linux":+ confinement = _linux_confinement(sandbox_site_dir)+ elif sys.platform == "darwin":+ confinement = _macos_confinement(sandbox_site_dir)+ if confinement is not None:+ return confinement+ if unconfined_tools_allowed():+ return Confinement(mechanism = "unconfined-by-owner")+ raise ToolConfinementUnavailable(refusal_message())diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.pyindex 11e77d72e75..abc6053b64e 100644--- a/studio/backend/core/inference/tool_stream_exec.py+++ b/studio/backend/core/inference/tool_stream_exec.py@@ -21,6 +21,7 @@ and healing downstream are untouched.from __future__ import annotations+import contextvarsimport inspectimport queueimport threading@@ -179,8 +180,10 @@ def stream_tool_execution(# poll-interval latency.output_queue.put(done_sentinel)+ # The worker runs in the caller's context, so a tool started for one account cannot resolve another's roots.worker = threading.Thread(- target = _run,+ target = contextvars.copy_context().run,+ args = (_run,),daemon = True,name = f"tool-exec-{tool_name or 'unknown'}",)diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 5825d7a4459..477ddb25abf 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -13,6 +13,7 @@ import hashlibimport jsonimport http.clientimport os+from functools import partialimport signalos.environ["UNSLOTH_IS_PRESENT"] = "1"@@ -72,6 +73,10 @@ from core.inference.mcp_client import (stdio_mcp_enabled,)from storage import mcp_servers_db+from utils.account_context import account_thread, current_account_id, is_owner_context+from core.inference.tool_confinement import ToolConfinementUnavailable, account_confinement+from pathlib import Path+from utils.paths.storage_roots import RetiredAccountError, ensure_dirfrom loggers import get_logger@@ -6674,6 +6679,28 @@ def _sandbox_preexec():pass+def _account_confinement():+ """Confinement for the acting account's next child: None for owner, raises if unavailable."""+ return account_confinement(_SANDBOX_SITE_DIR)+++def _run_preexecs(first, second):+ """Both pre-exec steps in the forked child, in order; no closures, no imports."""+ if first is not None:+ first()+ second()+++def _apply_confinement(confinement, popen_kwargs: dict, argv: list) -> list:+ if confinement is None:+ return argv+ if confinement.preexec is not None and sys.platform != "win32":+ popen_kwargs["preexec_fn"] = partial(+ _run_preexecs, popen_kwargs.get("preexec_fn"), confinement.preexec+ )+ return confinement.wrap(argv)++def _bypass_preexec():"""Minimal pre-exec for bypass exec: os.setsid() only. Required, not a restriction:_kill_process_tree does killpg(getpgid(child)), so without a new session a timeout/cancel@@ -6813,27 +6840,48 @@ def _get_shell_cmd(command: str) -> list[str]:return ["bash", "-c", command]-# Per-session working directories so each chat thread gets its own sandbox. Falls back to ~/studio_sandbox/_default-# for callers without a session_id.-_workdirs: dict[str, str] = {}-# Sessions with a tool call in flight. Deleting a chat unlinks its workdir, and a process whose cwd has been removed-# fails every relative write with ENOENT.-_active_sessions: "dict[str, int]" = {}-# Deletions that arrived mid-call: the thread has gone from history, so nothing would ask for the folder again. Keyed-# like the above and holding every exact id that folded onto the key, since each can be its own directory.-_pending_removals: "dict[str, dict[str, bool]]" = {}+def _shell_argv(command: str, workdir: str, confinement) -> "tuple[list[str], str | None]":+ """Keep a confined account's command text off argv: other accounts' tools can read+ /proc/<pid>/cmdline and Landlock cannot deny per-pid reads."""+ argv = _get_shell_cmd(command)+ if confinement is None or sys.platform == "win32" or argv[1] != "-c":+ return argv, None+ fd, path = tempfile.mkstemp(suffix = ".sh", prefix = ".studio_cmd_", dir = workdir)+ with os.fdopen(fd, "w", encoding = "utf-8") as f:+ f.write(command)+ name = os.path.basename(path)+ return [argv[0], name], name+++# Per-session working directories so each chat thread gets its own sandbox.+# Falls back to ~/studio_sandbox/_default for callers without a session_id.+_workdirs: dict[tuple[str, str], str] = {}+# Sessions with a tool call in flight. Deleting a chat unlinks its workdir, and+# a process whose cwd has been removed fails every relative write with ENOENT.+_active_sessions: "dict[tuple[str, str], int]" = {}+# Deletions that arrived mid-call: the thread has gone from history, so nothing+# would ask for the folder again. Keyed like the above and holding every exact+# id that folded onto the key, since each can be its own directory.+_pending_removals: "dict[tuple[str, str], dict[str, bool]]" = {}_active_sessions_lock = threading.Lock()-# Sessions whose sandbox is being removed right now. A start for one of these waits on the condition rather than on-# the lock, so only that chat is held up.-_removing_sessions: "set[str]" = set()+# Sessions whose sandbox is being removed right now. A start for one of these+# waits on the condition rather than on the lock, so only that chat is held up.+_removing_sessions: "set[tuple[str, str]]" = set()_sessions_free = threading.Condition(_active_sessions_lock)-def _session_key(session_id: "str | None") -> str:- """Lifecycle key for a session id. Case-folded: two ids differing only in case are one directory- on Windows and on a default macOS volume, and keying them apart let a delete land while the- other chat was running a tool in there."""- return (session_id or _ANON_KEY).casefold()+def _workdir_key(session_id: "str | None") -> tuple[str, str]:+ return current_account_id(), session_id or _ANON_KEY+++def _session_key(session_id: "str | None") -> tuple[str, str]:+ """Lifecycle key for a session id.++ Case-folded: two ids differing only in case are one directory on Windows and+ on a default macOS volume, and keying them apart let a delete land while the+ other chat was running a tool in there.+ """+ return current_account_id(), (session_id or _ANON_KEY).casefold()@contextlib.contextmanager@@ -6898,8 +6946,8 @@ def _orphan_records_dir() -> str:by its id: the row that knew the path is gone, and a workspace the user pointed somewherecustom cannot be derived from anything else."""try:- from utils.paths.storage_roots import studio_root- return os.path.join(str(studio_root()), "orphaned-projects")+ from utils.paths.storage_roots import account_path+ return str(account_path("orphaned-projects"))except Exception:# Only if the studio home cannot be resolved at all: beside the sandbox root, whose parent an administrator# may have made read-only.@@ -7127,7 +7175,7 @@ def finish_workspace_delete_when_idle(wait_for_sessions_idle([session], timeout = timeout)collect_orphaned_project_workspaces()- thread = threading.Thread(+ thread = account_thread(target = _wait_and_collect,name = "workspace-delete",daemon = True,@@ -7233,6 +7281,9 @@ def _project_workdir_for(session_id: "str | None") -> "str | None":def _get_project_workdir(session_id: str) -> str | None:+ # Host project paths are single-user only; managed accounts use their sandbox.+ if not is_owner_context():+ return Noneif not session_id.startswith(_PROJECT_SESSION_PREFIX):return Noneproject_id = session_id[len(_PROJECT_SESSION_PREFIX) :]@@ -7540,17 +7591,34 @@ def _legacy_sandbox_root() -> str:return os.path.join(os.path.expanduser("~"), "studio_sandbox")+def shared_sandbox_root() -> str:+ """The base every account's ``sandbox_root`` lives under; confinement hides it first."""+ override = (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip()+ if override:+ return os.path.expanduser(override)+ try:+ from utils.paths.storage_roots import studio_root+ return str(studio_root())+ except Exception:+ return _legacy_sandbox_root()++def sandbox_root() -> str:"""Root of the per-session tool sandboxes. Under the studio home, so UNSLOTH_STUDIO_HOME keepseverything in one place instead of leaving a stray ~/studio_sandbox. Falls back to the legacypath only if the studio root cannot be resolved."""override = (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip()if override:+ if not is_owner_context():+ from utils.paths.storage_roots import external_account_sandbox_root+ return str(external_account_sandbox_root())return os.path.expanduser(override)try:- from utils.paths.storage_roots import studio_root- return os.path.join(str(studio_root()), "sandbox")+ from utils.paths.storage_roots import account_path+ return str(account_path("sandbox"))except Exception:+ if not is_owner_context():+ raisereturn _legacy_sandbox_root()@@ -7636,9 +7704,13 @@ _LEGACY_SHARED_BUCKET = "_invalid"def _legacy_session_dir(session_id: str) -> "str | None":- """This session's directory at the legacy root, while one is still there. Both names, like the- migration itself: a chat from before the upgrade whose id starts with the derived prefix kept- its folder under the literal id."""+ """This session's directory at the legacy root, while one is still there.++ Both names, like the migration itself: a chat from before the upgrade whose+ id starts with the derived prefix kept its folder under the literal id.+ """+ if not is_owner_context():+ return Nonelegacy_root = _legacy_sandbox_root()names = [_sandbox_name(session_id)]if not _usable_session_id(session_id):@@ -7663,7 +7735,7 @@ def _legacy_session_dir(session_id: str) -> "str | None":def _migrate_one_legacy_session(root: str, name: str) -> None:"""Bring one session up from the legacy root, without waiting for the rest."""- if _legacy_sandbox_migrated:+ if not is_owner_context() or _legacy_sandbox_migrated:returnsource = os.path.join(_legacy_sandbox_root(), name)if os.path.islink(source) or not os.path.isdir(source):@@ -7689,7 +7761,7 @@ _legacy_background: "threading.Thread | None" = Nonedef _start_legacy_migration() -> "threading.Thread | None":"""Carry the rest of the tree up, one pass at a time, off this request."""global _legacy_background- if _legacy_sandbox_migrated:+ if not is_owner_context() or _legacy_sandbox_migrated:return Nonewith _legacy_one_lock:if _legacy_background is not None and _legacy_background.is_alive():@@ -7703,7 +7775,7 @@ def _migrate_legacy_sandbox(root: str) -> None:so they move rather than being dropped. A session already present at the new root wins andits legacy copy is left alone, so nothing is silently overwritten."""global _legacy_sandbox_migrated- if _legacy_sandbox_migrated:+ if not is_owner_context() or _legacy_sandbox_migrated:return# Flagged only once the move is done: setting it first let a concurrent call create the destination, which then# read as a collision.@@ -7862,7 +7934,7 @@ def _owned_by_session(workdir: str, session_id: str) -> bool:def _get_workdir(session_id: str | None = None) -> str:"""Return a per-session sandbox dir at mode 0o700."""global _workdirs- key = session_id or _ANON_KEY+ key = _workdir_key(session_id)cached = _workdirs.get(key)if cached is not None and not os.path.isdir(cached):cached = None@@ -7894,8 +7966,11 @@ def _get_workdir(session_id: str | None = None) -> str:_workdirs.pop(key, None)sandbox_root_path = sandbox_root()root_existed = os.path.isdir(sandbox_root_path)- # The folder may still be at the legacy root right after an upgrade. Only this chat's, so a first tool call- # never waits on the whole tree: across filesystems that is a copy of every session.+ # Before anything below creates a directory: a call after deletion must refuse.+ ensure_dir(Path(sandbox_root_path))+ # The folder may still be at the legacy root right after an upgrade.+ # Only this chat's, so a first tool call never waits on the whole tree:+ # across filesystems that is a copy of every session.if session_id:# A pre-upgrade chat whose id already starts with the derived prefix kept its folder under the literal id,# so that name is tried too. Only a usable one: the rest never named a directory.@@ -7952,7 +8027,7 @@ def resolve_sandbox_workdir(session_id: str | None = None) -> str:if project:return projectroot = sandbox_root()- cached = _workdirs.get(session_id or _ANON_KEY)+ cached = _workdirs.get(_workdir_key(session_id))if (cachedand not os.path.islink(cached)@@ -8006,7 +8081,7 @@ def migrate_legacy_sandbox_in_background() -> "threading.Thread":except Exception: # noqa: BLE001 - best effort, like the rest of thislogger.debug("legacy sandbox migration failed", exc_info = True)- thread = threading.Thread(target = _run, name = "sandbox-migrate", daemon = True)+ thread = account_thread(target = _run, name = "sandbox-migrate", daemon = True)thread.start()return thread@@ -8105,6 +8180,7 @@ def sweep_detached_sandboxes(root: "str | None" = None) -> None:_swept_detached = False+_swept_detached_accounts: set[str] = set()def start_sandbox_recovery() -> "threading.Thread | None":@@ -8116,9 +8192,15 @@ def _start_detached_sweep() -> "threading.Thread | None":"""Run the sweep once per process, off the call that noticed."""global _swept_detachedwith _legacy_one_lock:- if _swept_detached:- return None- _swept_detached = True+ if is_owner_context():+ if _swept_detached:+ return None+ _swept_detached = True+ else:+ account_id = current_account_id()+ if account_id in _swept_detached_accounts:+ return None+ _swept_detached_accounts.add(account_id)def _sweep() -> None:sweep_detached_sandboxes()@@ -8126,7 +8208,7 @@ def _start_detached_sweep() -> "threading.Thread | None":# away.collect_orphaned_project_workspaces()- thread = threading.Thread(target = _sweep, name = "sandbox-sweep", daemon = True)+ thread = account_thread(target = _sweep, name = "sandbox-sweep", daemon = True)thread.start()return thread@@ -8247,12 +8329,15 @@ def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:def _claimed_by_this_run(session_id: str, root: str) -> "str | None":- """The directory this process made for this chat, whatever the marker says. Tool code runs in- there and can empty that file or write another id into it, and neither makes the directory- somebody else's: this process wrote the marker with O_EXCL and remembers doing it. Put back- here, so the ordinary routes find it too rather than leaving the files stranded until some- later call happens to repair it."""- cached = _workdirs.get(session_id)+ """The directory this process made for this chat, whatever the marker says.++ Tool code runs in there and can empty that file or write another id into+ it, and neither makes the directory somebody else's: this process wrote the+ marker with O_EXCL and remembers doing it. Put back here, so the ordinary+ routes find it too rather than leaving the files stranded until some later+ call happens to repair it.+ """+ cached = _workdirs.get(_workdir_key(session_id))if not cached or cached not in _claimed_here:return Noneif os.path.islink(cached) or not os.path.isdir(cached):@@ -8333,10 +8418,10 @@ def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:# Nothing says whose this is, and on a case-insensitive volume `foo` and `Foo` are one directory: without the# marker the name is the only evidence, and it names the other chat.return False- _workdirs.pop(session_id, None)- # Resolved BEFORE anything is removed: the record is named by the real path of the spill directory, which cannot- # be derived once the tree is gone. Without this every deleted chat that ever truncated output leaves one small- # file behind for good.+ _workdirs.pop(_workdir_key(session_id), None)+ # Resolved BEFORE anything is removed: the record is named by the real path of the+ # spill directory, which cannot be derived once the tree is gone. Without this every+ # deleted chat that ever truncated output leaves one small file behind for good.forget_record = _spill_record_path(os.path.join(target, _SPILL_DIR))try:if delete_files:@@ -8389,10 +8474,16 @@ _EDIT_FILE_DIFF_WINDOW_LINES = 120def _edit_file_resolve(raw_path: str, session_id: "str | None", disable_sandbox: bool) -> "tuple[str | None, str]":- """Resolve the model's path the way python/terminal resolve theirs. Same rules as the- sitecustomize shim: a code-interpreter habit prefix (/mnt/data, /workspace, ...) keeps its- suffix under the workdir, everything else is relative to it. Containment is checked on the- realpath, so a symlink planted inside cannot reach out."""+ """Resolve the model's path the way python/terminal resolve theirs.++ Same rules as the sitecustomize shim: a code-interpreter habit prefix+ (/mnt/data, /workspace, ...) keeps its suffix under the workdir, everything+ else is relative to it. Containment is checked on the realpath, so a symlink+ planted inside cannot reach out.+ """+ from state.tool_policy import require_tool_access++ require_tool_access(disable_sandbox = disable_sandbox)raw = (raw_path or "").strip()if not raw:return None, "Error: 'path' is required."@@ -9687,6 +9778,9 @@ def execute_tool(observational: the returned result string is identical with or without it. ``website_policy``:hidden server-validated domain limits for web_search."""+ from state.tool_policy import require_tool_access++ require_tool_access(disable_sandbox = disable_sandbox)logger.info(f"execute_tool: name={name}, session_id={session_id}, timeout={timeout}")# Set unconditionally, so a value from an earlier call on this thread can never be read by a later one. That is# what makes a try/finally reset unnecessary here.@@ -10089,7 +10183,7 @@ def _search_knowledge_base_with_budget(release_slot()try:- threading.Thread(target = search, name = "rag-tool-search", daemon = True).start()+ account_thread(target = search, name = "rag-tool-search", daemon = True).start()except Exception:release_slot()raise@@ -14052,8 +14146,8 @@ def _spill_records_dir() -> str:a delete and the prune into an unlink. Held beside the other records this file already keepsoutside the sandboxes."""try:- from utils.paths.storage_roots import studio_root # noqa: PLC0415- return os.path.join(str(studio_root()), "tool-output-records")+ from utils.paths.storage_roots import account_path # noqa: PLC0415+ return str(account_path("tool-output-records"))except Exception:return os.path.join(os.path.dirname(os.path.realpath(sandbox_root())), "tool-output-records"@@ -15172,10 +15266,15 @@ def _python_exec(tmp_path = None_scratch_name = None- workdir = _get_workdir(session_id)- # `_get_workdir(None)` is the shared `_default` sandbox, and a project's chats share one session by design.- # Retaining a result in either, under a path the next chat can list, would leave behind output that existed only- # in this call's own response. See `_spill_scope`, which returns None for exactly those cases.+ try:+ workdir = _get_workdir(session_id)+ confinement = _account_confinement()+ except (ToolConfinementUnavailable, RetiredAccountError) as exc:+ return _truncate(f"Execution error: {exc}")+ # `_get_workdir(None)` is the shared `_default` sandbox, and a project's chats share+ # one session by design. Retaining a result in either, under a path the next chat can+ # list, would leave behind output that existed only in this call's own response. See+ # `_spill_scope`, which returns None for exactly those cases.spill_scope = _spill_scope(session_id, thread_id)spill_dir = workdir if session_id else Nonecall_token = _call_started(workdir)@@ -15214,10 +15313,12 @@ def _python_exec(else:popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW- # -u forces unbuffered child stdout so a bare print() streams live instead of sitting in the pipe's block- # buffer until exit. Applied unconditionally to stay byte-identical with and without streaming; unlike- # PYTHONUNBUFFERED=1 it never pollutes the child's os.environ.- proc = subprocess.Popen([sys.executable, "-u", tmp_path], **popen_kwargs)+ # -u forces unbuffered child stdout so a bare print() streams live+ # instead of sitting in the pipe's block buffer until exit. Applied+ # unconditionally to stay byte-identical with and without streaming;+ # unlike PYTHONUNBUFFERED=1 it never pollutes the child's os.environ.+ argv = _apply_confinement(confinement, popen_kwargs, [sys.executable, "-u", tmp_path])+ proc = subprocess.Popen(argv, **popen_kwargs)# Capture the group before any watcher can reap the leader (see _capture_process_group); None on Windows.pgid = _capture_process_group(proc)@@ -15335,8 +15436,13 @@ def _bash_exec(spill_dir = Nonespill_scope = Nonecall_token = None+ _scratch_name = Nonetry:- workdir = _get_workdir(session_id)+ try:+ workdir = _get_workdir(session_id)+ confinement = _account_confinement()+ except (ToolConfinementUnavailable, RetiredAccountError) as exc:+ return _truncate(f"Execution error: {exc}")# Same scoping as _python_exec: nothing is retained in a sandbox that is shared.spill_scope = _spill_scope(session_id, thread_id)spill_dir = workdir if session_id else None@@ -15361,7 +15467,12 @@ def _bash_exec(else:popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW- proc = subprocess.Popen(_get_shell_cmd(command), **popen_kwargs)+ shell_argv, _scratch_name = _shell_argv(command, workdir, confinement)+ if _scratch_name:+ with _scratch_lock:+ _active_scratch.add(_scratch_name)+ argv = _apply_confinement(confinement, popen_kwargs, shell_argv)+ proc = subprocess.Popen(argv, **popen_kwargs)# Capture the group before any watcher can poll/reap the leader (see _python_exec); None on Windows.pgid = _capture_process_group(proc)@@ -15385,12 +15496,16 @@ def _bash_exec(if timed_out:ended = _timed_out_result(output, timeout, spill_dir, spill_scope)return ended + (- _created_file_sentinels(workdir, _before, None, call_token) if session_id else ""+ _created_file_sentinels(workdir, _before, _scratch_name, call_token)+ if session_id+ else "")if cancel_event is not None and cancel_event.is_set():return "Execution cancelled." + (- _created_file_sentinels(workdir, _before, None, call_token) if session_id else ""+ _created_file_sentinels(workdir, _before, _scratch_name, call_token)+ if session_id+ else "")result = output or ""@@ -15406,7 +15521,7 @@ def _bash_exec()# Only for a chat that has an id (see _python_exec).if session_id:- result += _created_file_sentinels(workdir, _before, None, call_token)+ result += _created_file_sentinels(workdir, _before, _scratch_name, call_token)return resultexcept Exception as e:@@ -15416,3 +15531,10 @@ def _bash_exec(finally:_call_finished(call_token)_forget_tool_pid(locals().get("proc"))+ if _scratch_name:+ with _scratch_lock:+ _active_scratch.discard(_scratch_name)+ try:+ os.unlink(os.path.join(workdir, _scratch_name))+ except OSError:+ passdiff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 06fc68b7ca2..da966adfd69 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -36,6 +36,7 @@ import inspectimport osimport tempfileimport threading+from utils.account_context import account_thread, current_account_idimport timeimport typesfrom dataclasses import dataclass@@ -1062,6 +1063,7 @@ class VideoBackend:# Which job the flag belongs to. The flag alone cannot tell "my job" from "the job that replaced mine", so# finalising is keyed on this. Compared by identity.self._generate_job_token: Optional[object] = None+ self._generate_job_account: Optional[str] = None# The OpenAI /v1/videos job id this run was started under, or None for a Studio-page runself._gen_video_id: Optional[str] = None@@ -1400,7 +1402,7 @@ class VideoBackend:asset_repos = claimed_assets,)- threading.Thread(+ account_thread(target = self._run_load,kwargs = dict(repo_id = repo_id,@@ -1651,6 +1653,12 @@ class VideoBackend:if self._load_token != token:returnlogger.error("video.load_failed: %s", exc)+ if self._state is not None:+ from .gpu_arbiter import VIDEO, restore_owner_account+ from hub.services.models.account_access import restore_resident_metadata++ restore_owner_account(VIDEO)+ restore_resident_metadata(VIDEO)# Free the debris of a failed construction: nothing was committed, so nothing else releases the VRAM.try:clear_gpu_cache()@@ -5089,6 +5097,7 @@ class VideoBackend:)self._generate_job_active = Trueself._generate_job_token = job_token+ self._generate_job_account = current_account_id()self._active_generate_cancel = cancelself._gen_video_id = video_idself._gen = {@@ -5099,7 +5108,7 @@ class VideoBackend:"eta_seconds": None,}break- worker = threading.Thread(+ worker = account_thread(# The token and the /v1/videos job id ride on the target rather than in kwargs: those kwargs are also a# valid generate() call, and callers replay them as one.target = functools.partial(self._run_generate, job_token = job_token, video_id = video_id),@@ -5152,6 +5161,9 @@ class VideoBackend:"model": getattr(state, "repo_id", None),}+ def generate_job_account(self) -> Optional[str]:+ return self._generate_job_account+def _run_generate(self,*,@@ -6193,8 +6205,11 @@ class VideoBackend:except OSError:pass- def generate_progress(self) -> dict[str, Any]:+ def generate_progress(self, expected_account: Optional[str] = None) -> Optional[dict[str, Any]]:+ """Progress under one lock; None if ``expected_account`` no longer owns the job."""with self._lock:+ if expected_account is not None and self._generate_job_account != expected_account:+ return Nonegen = dict(self._gen)# generate() swaps in a bare {"active": False} before the worker records the terminal dict; report active# across that gap.@@ -6232,11 +6247,18 @@ class VideoBackend:self._gen = {"active": False}return True- def cancel_generate(self, expected_video_id: Optional[str] = None) -> bool:- """Signal the in-flight generation to stop at its next step callback."""+ def cancel_generate(+ self,+ expected_video_id: Optional[str] = None,+ expected_account: Optional[str] = None,+ ) -> bool:+ """Stop the in-flight generation; expected_* are rechecked under begin_generate's lock,+ so a cancel of a finished job cannot hit its successor."""with self._lock:if expected_video_id is not None and self._gen_video_id != expected_video_id:return False+ if expected_account is not None and self._generate_job_account != expected_account:+ return Falsecancel = self._active_generate_cancelif cancel is None:return False@@ -6265,8 +6287,20 @@ class VideoBackend:del stateclear_gpu_cache()- def unload(self) -> dict[str, Any]:+ def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:with self._lock:+ if expected_account is not None:+ from .gpu_arbiter import VIDEO, GpuBusyForAnotherAccountError+ from hub.services.models.account_access import require_resident_control++ if (+ self._active_generate_cancel is not None+ and self._generate_job_account != expected_account+ ):+ raise GpuBusyForAnotherAccountError(VIDEO, 1)+ require_resident_control(+ VIDEO, self._state.repo_id if self._state is not None else None+ )self._load_token += 1self._cancel_event.set()self._loading = None@@ -6396,3 +6430,17 @@ def generation_in_flight() -> bool:"""Read the background-job marker without constructing or locking the backend."""backend = _backendreturn backend is not None and bool(backend._generate_job_active)+++def retire_load_for_account(account_id: str) -> bool:+ """Tear down an in-flight video load ``account_id`` started, without constructing the backend."""+ from hub.services.models.account_access import retire_media_load+ return retire_media_load("video", account_id, _backend)+++def generation_account_in_flight() -> Optional[str]:+ """The account whose video job is running, read without constructing the backend."""+ backend = _backend+ if backend is None or not backend._generate_job_active:+ return None+ return backend._generate_job_accountdiff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.pyindex d6fe6d800e3..1b7b873d7e7 100644--- a/studio/backend/core/inference/video_gallery.py+++ b/studio/backend/core/inference/video_gallery.py@@ -3,7 +3,7 @@"""Disk-backed persistence for generated videos.-Each video is a pair under ``studio_root()/videos``: ``{id}.mp4`` holds the bytes, ``{id}.json``+Each video is a pair under ``workspace_root()/videos``: ``{id}.mp4`` holds the bytes, ``{id}.json``holds the recipe (an MP4 has no portable text-chunk like a PNG). The pair travels together; a lonefile is not a valid record. Dumb storage: the route owns the schema; this only reads/writes/sorts."""@@ -21,7 +21,9 @@ from typing import Any, Optionalfrom core.inference import gallery_flagsfrom loggers import get_logger-from utils.paths import ensure_dir, studio_root+from utils.account_context import is_owner_context+from utils.paths import ensure_account_dir, ensure_dir, studio_root+from utils.paths.storage_roots import account_pathlogger = get_logger(__name__)@@ -33,7 +35,9 @@ _THUMBNAIL_WIDTH = 192def gallery_dir() -> Path:- return ensure_dir(studio_root() / "videos")+ if is_owner_context():+ return ensure_dir(studio_root() / "videos")+ return ensure_account_dir(account_path("videos"))def _job_dir() -> Path:diff --git a/studio/backend/core/rag/account_db.py b/studio/backend/core/rag/account_db.pynew file mode 100644index 00000000000..a9e8024ac19--- /dev/null+++ b/studio/backend/core/rag/account_db.py@@ -0,0 +1,26 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""RAG callers stop opening an account's storage once retirement starts."""++from storage import rag_db as _db+from core.training.account_jobs import account_is_retired+++def _require_live_account():+ if account_is_retired():+ raise RuntimeError("Account is retired")+++def get_connection():+ _require_live_account()+ return _db.get_connection()+++def get_metadata_connection():+ _require_live_account()+ return _db.get_metadata_connection()+++def __getattr__(name):+ return getattr(_db, name)diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex 0a40c111905..5d6f82404ef 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -15,6 +15,8 @@ that kills any Unsloth llama-server, so each request re-spawns ours if it died.from __future__ import annotations+from core.training.account_jobs import account_path, managed_account+from utils.account_context import account_threadimport atexitimport loggingimport os@@ -458,6 +460,7 @@ class LlamaServerBackend:``model_name`` is the model the caller pinned; the live setting wouldresolve B's weights for a job still tagging its vectors as A."""+ account_path(model_name, reference = True)model = model_name or config.effective_embedding_model()# Captured once: the path must stay tagged with the repo it was resolved FOR, so a mid-download# setting change reads as stale and respawns.@@ -608,7 +611,7 @@ class LlamaServerBackend:from core.inference.llama_cpp import _hf_offline_if_unreachablefrom utils.utils import call_with_deadline- token = os.environ.get("HF_TOKEN") or None+ token = False if managed_account() else os.environ.get("HF_TOKEN") or Nonerepo = desiredfilename: str | None = Nonefamily: list[str] = []@@ -880,7 +883,7 @@ class LlamaServerBackend:self._kill_process()raise RuntimeError("Studio is shutting down; not starting the embed server")self._port = port- self._stdout_thread = threading.Thread(+ self._stdout_thread = account_thread(target = self._drain_stdout,args = (proc,),daemon = True,diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.pyindex e96494f73b5..7bcd79e6763 100644--- a/studio/backend/core/rag/embeddings.py+++ b/studio/backend/core/rag/embeddings.py@@ -18,6 +18,7 @@ falls back to CPU without changing the embedding space.from __future__ import annotations+from core.training.account_jobs import account_hf_token, account_path, managed_accountimport loggingimport osimport re@@ -139,6 +140,8 @@ class EmbeddingModelDownloadRequiredError(RuntimeError):def _ambient_hf_token() -> str | None:"""The HF token the loader itself would use (HF_TOKEN env or the cached login), sothe scan can reach a gated/private repo instead of failing open. None if unavailable."""+ if managed_account():+ return Falsetry:from huggingface_hub import get_tokenreturn get_token()@@ -175,7 +178,7 @@ def _st_module_subdirs(name: str, token: str | None) -> tuple[str, ...]:local = hf_hub_download(name,"modules.json",- token = token or None,+ token = account_hf_token(token or None),cache_dir = active_hf_hub_cache(),)except EntryNotFoundError:@@ -404,6 +407,7 @@ def _st_accepts_local_files_only(st_cls) -> bool:def _get(model_name: str | None = None):"""Cached SentenceTransformer, (re)loading on a name change. Loaded in fp16 on anaccelerator for a ~1.5x speedup at negligible accuracy loss, fp32 on CPU."""+ account_path(model_name, reference = True)global _model, _namename = model_name or config.effective_embedding_model()# Capture offline state once so the gate and the load agree.@@ -431,6 +435,8 @@ def _get(model_name: str | None = None):# answers by swapping the whole process to llama-server.model_kwargs = dtype_kwargs("float32" if device == "cpu" else "float16"),)+ if managed_account():+ st_kwargs["token"] = Falseload_target = namefrom utils.paths import is_local_pathfrom utils.utils import cached_st_source, hf_cache_snapshot_dirdiff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.pyindex 7d9cbdba972..984d78cfe57 100644--- a/studio/backend/core/rag/folder_sync.py+++ b/studio/backend/core/rag/folder_sync.py@@ -5,6 +5,13 @@from __future__ import annotations+from core.training.account_jobs import (+ account_is_retired,+ account_key,+ account_path,+ job_accounts,+)+from utils.account_context import account_thread, run_asimport hashlibimport jsonimport logging@@ -19,7 +26,7 @@ import weakreffrom datetime import datetime, timezonefrom pathlib import Path, PurePosixPath-from storage import rag_db+from core.rag import account_db as rag_dbfrom utils.paths import ensure_dir, rag_uploads_rootfrom . import config, ingestion, job_leases, store@@ -34,6 +41,8 @@ _thread_stop: threading.Event | None = None_thread_lock = threading.Lock()_worker_lock = threading.Lock()_worker_state = threading.local()+# Scheduling cursor of the single worker; see _next_account_job.+_last_job_account: str | None = None_folder_locks: weakref.WeakValueDictionary[str, threading.RLock] = weakref.WeakValueDictionary()_scope_locks: weakref.WeakValueDictionary[str, threading.RLock] = weakref.WeakValueDictionary()_named_locks_lock = threading.Lock()@@ -60,12 +69,12 @@ class _FolderChanged(RuntimeError):def _folder_lock(folder_id: str) -> threading.RLock:with _named_locks_lock:- return _folder_locks.setdefault(folder_id, threading.RLock())+ return _folder_locks.setdefault(account_key(folder_id), threading.RLock())def _scope_lock(scope: str) -> threading.RLock:with _named_locks_lock:- return _scope_locks.setdefault(scope, threading.RLock())+ return _scope_locks.setdefault(account_key(scope), threading.RLock())def _now() -> str:@@ -121,6 +130,7 @@ def _is_within(root: str, path: str) -> bool:def validate_folder_path(path: str) -> str:"""Apply the existing model scan-folder policy without persisting there."""+ account_path(path)if not path or not path.strip() or "\x00" in path:raise ValueError("Path cannot be empty")expanded = os.path.abspath(os.path.expanduser(path))@@ -1107,6 +1117,8 @@ def _copy_exact(source, target, size: int) -> None:def _check_running() -> None:+ if account_is_retired():+ raise _SyncStoppedstop_event = getattr(_worker_state, "stop_event", _stop)if stop_event.is_set():raise _SyncStopped@@ -1648,13 +1660,16 @@ def reconcile_folder(job_id: str) -> None:except _LeaseLost:lease_lost = Trueexcept _SyncStopped:- _pause_job(job_id)+ # A retired account's database is closed; its rows moved with the roots.+ if not account_is_retired():+ _pause_job(job_id)except Exception as exc:logger.exception("linked-folder job %s failed unexpectedly", job_id)- _fail_job(job_id, exc)+ if not account_is_retired():+ _fail_job(job_id, exc)finally:try:- if not lease_lost:+ if not lease_lost and not account_is_retired():_queue_successor(job_id)finally:del _worker_state.job_id@@ -1742,17 +1757,28 @@ def _worker(stop_event: threading.Event | None = None, project_exists = None) ->_worker_state.stop_event = stop_eventwhile not stop_event.is_set():try:- _recover_startup_state()- if project_exists is not None:- reconcile_retired_scopes(project_exists)- _enqueue_periodic()- break+ accounts = job_accounts()except Exception:logger.warning("linked-folder worker initialization failed", exc_info = True)stop_event.wait(1.0)+ continue+ initialized = 0+ for account in accounts:+ try:+ run_as(account, _initialize_account_sync, project_exists, recover = True)+ initialized += 1+ except Exception:+ # One bad account database must not keep the worker out of the loop.+ logger.warning(+ "linked-folder worker initialization failed for one account",+ exc_info = True,+ )+ if initialized or not accounts:+ break+ stop_event.wait(1.0)while not stop_event.is_set():try:- job = _next_job()+ job = _next_account_job()except Exception:# Writer-lock contention must not retire the only worker; the initialization and periodic paths# retry.@@ -1760,22 +1786,37 @@ def _worker(stop_event: threading.Event | None = None, project_exists = None) ->stop_event.wait(1.0)continueif job:- job_id, folder_id = job+ account, job_id, folder_id = jobtry:- reconcile_folder(job_id)+ run_as(account, reconcile_folder, job_id)except Exception as exc:logger.exception("linked-folder job %s failed unexpectedly", job_id)- _fail_job(job_id, exc)+ try:+ run_as(account, _fail_job, job_id, exc)+ except Exception:+ # One account's bookkeeping must never stop the shared worker.+ logger.warning(+ "could not record the failure of linked-folder job %s",+ job_id,+ exc_info = True,+ )continue_wake.wait(max(1.0, config.FOLDER_SYNC_INTERVAL_S))_wake.clear()if not stop_event.is_set():try:- if project_exists is not None:- reconcile_retired_scopes(project_exists)- _enqueue_periodic()+ accounts = job_accounts()except Exception:logger.warning("linked-folder periodic scheduling failed", exc_info = True)+ accounts = []+ for account in accounts:+ try:+ run_as(account, _initialize_account_sync, project_exists)+ except Exception:+ logger.warning(+ "linked-folder periodic scheduling failed for one account",+ exc_info = True,+ )finally:_worker_state.stop_event = Nonewith _thread_lock:@@ -1863,7 +1904,7 @@ def start_auto_sync(stop_event = threading.Event()_stop.clear()_thread_stop = stop_event- _thread = threading.Thread(+ _thread = account_thread(target = _worker,args = (stop_event, project_exists),daemon = True,@@ -1890,3 +1931,40 @@ def stop_auto_sync(timeout: float = 2.0) -> None:stop_event.set()if thread is not None:thread.join(timeout = timeout)+++def _initialize_account_sync(project_exists, *, recover: bool = False) -> None:+ if recover:+ _recover_startup_state()+ if project_exists is not None:+ reconcile_retired_scopes(project_exists)+ _enqueue_periodic()+++def _next_account_job():+ # Round robin from the account after the last claim: one folder is reconciled at a time,+ # so always restarting at the first account starves everyone behind a backlog.+ global _last_job_account+ accounts = job_accounts()+ start = 0+ for index, account in enumerate(accounts):+ if account.account_id == _last_job_account:+ start = index + 1+ break+ for offset in range(len(accounts)):+ account = accounts[(start + offset) % len(accounts)]+ try:+ job = run_as(account, _next_job)+ except Exception:+ # The order is stable, so one corrupt database would shadow the accounts behind it.+ logger.warning("linked-folder queue selection failed for one account", exc_info = True)+ continue+ if job:+ _last_job_account = account.account_id+ return (account, *job)+ return None+++def retire_account_sync() -> None:+ """Wake the supervisor; retirement checks stop only the retired account."""+ _wake.set()diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.pyindex 6b1ce5a1960..04fb4470e96 100644--- a/studio/backend/core/rag/ingestion.py+++ b/studio/backend/core/rag/ingestion.py@@ -8,6 +8,8 @@ daemon thread, pushing progress onto a per-job queue (streamed as SSE byfrom __future__ import annotations+from core.training.account_jobs import account_is_retired, account_key, account_path+from utils.account_context import account_thread, current_accountimport hashlibimport loggingimport os@@ -16,7 +18,7 @@ import reimport threadingfrom collections.abc import Callable-from storage import rag_db+from core.rag import account_db as rag_dbfrom . import captioner, chunking, config, embeddings, job_leases, parsers, pdf_ocr, store@@ -34,6 +36,8 @@ _SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")_SSE_POLL_SECONDS = 1.0_TERMINAL_JOB_STATUSES = {"completed", "failed", "cancelled"}+_RETIRE_JOIN_SECONDS = 10.0+def _sha256_file(path: str) -> str:h = hashlib.sha256()@@ -68,7 +72,7 @@ def _remove_upload(stored_path: str | None, *, keep_path: str | None = None) ->def _emit(job_id: str, event: dict) -> None:with _jobs_lock:- q = _jobs.get(job_id)+ q = _jobs.get(account_key(job_id))if q is not None:q.put(event)@@ -95,6 +99,8 @@ def _set_job(def _progress(conn, job_id: str, stage: str, progress: float) -> None:+ if account_is_retired():+ raise job_leases.JobLeaseLost("Account is retired")if not job_leases.renew_owned(conn, job_leases.INGESTION, job_id):raise job_leases.JobLeaseLost("Ingestion job lease was reclaimed")_set_job(conn, job_id, status = "running", stage = stage, progress = progress)@@ -110,7 +116,7 @@ def _abort_if_document_deleted(conn, job_id: str, document_id: str) -> bool:indexed and retire the document it was replacing."""conn.execute("BEGIN IMMEDIATE")- if store.get_document(conn, document_id) is not None:+ if not account_is_retired() and store.get_document(conn, document_id) is not None:return Falseconn.rollback()_set_job(conn, job_id, status = "cancelled", stage = "done", progress = 1.0)@@ -444,7 +450,7 @@ def _run(conn.close()job_leases.release(job_leases.INGESTION, job_id)with _jobs_lock:- _workers.pop(job_id, None)+ _workers.pop(account_key(job_id), None)_emit(job_id, None)@@ -475,6 +481,9 @@ def start_ingestion(through instead of paying for a second full read of the file. Must be the lowercasehex sha256 of ``stored_path``; a mismatched value would misfile the document underthe wrong hash, so it is trusted as given and never reverified here."""+ account_path(stored_path)+ if account_is_retired():+ raise RuntimeError("Account is retired")ext = os.path.splitext(stored_path)[1].lower()if ext not in config.UPLOAD_EXTS:raise ValueError(f"unsupported file type: {ext}")@@ -536,7 +545,7 @@ def start_ingestion(job_id = _new_job(conn, existing, scope, status = "completed", progress = 1.0)_remove_upload(stored_path, keep_path = doc.get("stored_path"))with _jobs_lock:- _jobs[job_id] = queue.Queue()+ _jobs[account_key(job_id)] = queue.Queue()_emit(job_id,{"type": "complete", "num_chunks": doc.get("num_chunks") or 0, "deduped": True},@@ -570,7 +579,7 @@ def start_ingestion(try:job_leases.activate(job_leases.INGESTION, job_id)with _jobs_lock:- _jobs[job_id] = queue.Queue()+ _jobs[account_key(job_id)] = queue.Queue()args = (job_id,document_id,@@ -584,7 +593,7 @@ def start_ingestion(if not background:_run(*args)return document_id, job_id- worker = threading.Thread(+ worker = account_thread(target = _run,# effective_model, not the raw model_name, pins the embedder for the whole job: a Settings change# mid-ingestion must not switch tokenizer or embedder between batches.@@ -592,11 +601,11 @@ def start_ingestion(daemon = True,)with _jobs_lock:- _workers[job_id] = worker+ _workers[account_key(job_id)] = workerworker.start()except Exception:with _jobs_lock:- _workers.pop(job_id, None)+ _workers.pop(account_key(job_id), None)job_leases.release(job_leases.INGESTION, job_id)fail_stalled_job(job_id, "Ingestion worker could not start")# _run never entered, so its finally cannot retire the orphan this retry replaced.@@ -612,7 +621,7 @@ def start_ingestion(def job_worker_alive(job_id: str) -> bool:"""Return whether this process still has a live worker for a persisted job."""with _jobs_lock:- worker = _workers.get(job_id)+ worker = _workers.get(account_key(job_id))return worker is not None and worker.is_alive()@@ -689,12 +698,17 @@ def _reap_finished_jobs() -> None:forever. Safe while streaming: ``job_events`` holds its queue reference."""with _jobs_lock:- job_ids = list(_jobs.keys())+ job_ids = [+ key if isinstance(key, str) else key[1]+ for key in _jobs+ if (isinstance(key, str) and current_account().is_owner)+ or (isinstance(key, tuple) and key[0] == current_account().account_id)+ ]for jid in job_ids:row = get_job_status(jid)if row is not None and row.get("status") in _TERMINAL_JOB_STATUSES:with _jobs_lock:- _jobs.pop(jid, None)+ _jobs.pop(account_key(jid), None)def delete_terminal_job(job_id: str) -> bool:@@ -710,7 +724,7 @@ def delete_terminal_job(job_id: str) -> bool:conn.close()if cursor.rowcount:with _jobs_lock:- _jobs.pop(job_id, None)+ _jobs.pop(account_key(job_id), None)return Truereturn False@@ -729,7 +743,7 @@ def job_events(job_id: str):The stream ends only on a terminal status, the ``None`` sentinel, or disconnect."""with _jobs_lock:- q = _jobs.get(job_id)+ q = _jobs.get(account_key(job_id))if q is None:returnterminal = False@@ -772,7 +786,7 @@ def job_events(job_id: str):terminal = Falseif terminal:with _jobs_lock:- _jobs.pop(job_id, None)+ _jobs.pop(account_key(job_id), None)def get_job_status(job_id: str) -> dict | None:@@ -789,3 +803,31 @@ def get_job_status(job_id: str) -> dict | None:return dict(row) if row else Nonefinally:conn.close()+++def retire_account_ingestions() -> None:+ """Stop renewing this account's jobs, then reap their workers before the roots move:+ a thread parked in a long parse only notices retirement at its next checkpoint."""+ with _jobs_lock:+ keys = [+ key+ for key in _workers+ if (isinstance(key, str) and current_account().is_owner)+ or (isinstance(key, tuple) and key[0] == current_account().account_id)+ ]+ for key in keys:+ job_leases.release(job_leases.INGESTION, key if isinstance(key, str) else key[1])+ stragglers = []+ for key in keys:+ with _jobs_lock:+ worker = _workers.get(key)+ # Never join from the worker itself.+ if worker is None or worker is threading.current_thread():+ continue+ worker.join(timeout = _RETIRE_JOIN_SECONDS)+ if worker.is_alive():+ stragglers.append(key if isinstance(key, str) else key[1])+ if stragglers:+ raise RuntimeError(+ f"Retired account ingestion workers have not stopped: {sorted(stragglers)}"+ )diff --git a/studio/backend/core/rag/job_leases.py b/studio/backend/core/rag/job_leases.pyindex 93f529106d7..20dc2dfe807 100644--- a/studio/backend/core/rag/job_leases.py+++ b/studio/backend/core/rag/job_leases.py@@ -5,12 +5,14 @@from __future__ import annotations+from utils.account_context import OWNER, account_thread, current_account, run_as+from core.training.account_jobs import account_is_retiredimport loggingimport threadingimport uuidfrom datetime import datetime, timedelta, timezone-from storage import rag_db+from core.rag import account_db as rag_dblogger = logging.getLogger(__name__)@@ -20,7 +22,7 @@ FOLDER_SYNC = "folder_sync"_OWNER_ID = str(uuid.uuid4())_LEASE_SECONDS = 30_HEARTBEAT_SECONDS = 5-_active: set[tuple[str, str]] = set()+_active: set[tuple[object, str, str]] = set()_lock = threading.Lock()_wake = threading.Event()_thread: threading.Thread | None = None@@ -74,14 +76,14 @@ def activate(kind: str, job_id: str) -> None:"""Renew a committed claim until the local worker releases it."""global _threadwith _lock:- _active.add((kind, job_id))+ _active.add((current_account(), kind, job_id))if _thread is None or not _thread.is_alive():try:- _thread = threading.Thread(target = _heartbeat, daemon = True)+ _thread = account_thread(target = _heartbeat, account = OWNER, daemon = True)_thread.start()except Exception:_thread = None- _active.discard((kind, job_id))+ _active.discard((current_account(), kind, job_id))raise_wake.set()@@ -89,7 +91,9 @@ def activate(kind: str, job_id: str) -> None:def release(kind: str, job_id: str) -> None:"""Stop renewal and remove this process's persisted claim."""with _lock:- _active.discard((kind, job_id))+ _active.discard((current_account(), kind, job_id))+ if account_is_retired():+ returntry:conn = rag_db.get_connection()try:@@ -112,20 +116,31 @@ def _heartbeat() -> None:_wake.wait()_wake.clear()continue- try:- conn = rag_db.get_connection()- try:- deadline = _deadline()- for kind, job_id in active:- conn.execute(- "UPDATE rag_job_leases SET expires_at=? "- "WHERE kind=? AND job_id=? AND owner_id=?",- (deadline, kind, job_id, _OWNER_ID),- )- conn.commit()- finally:- conn.close()- except Exception:- logger.warning("failed to renew RAG job leases", exc_info = True)+ for account in {entry[0] for entry in active}:+ run_as(+ account,+ _renew_account,+ [(kind, job_id) for owner, kind, job_id in active if owner == account],+ )_wake.wait(_HEARTBEAT_SECONDS)_wake.clear()+++def _renew_account(active) -> None:+ if account_is_retired():+ return+ try:+ conn = rag_db.get_connection()+ try:+ deadline = _deadline()+ for kind, job_id in active:+ conn.execute(+ "UPDATE rag_job_leases SET expires_at=? "+ "WHERE kind=? AND job_id=? AND owner_id=?",+ (deadline, kind, job_id, _OWNER_ID),+ )+ conn.commit()+ finally:+ conn.close()+ except Exception:+ logger.warning("failed to renew RAG job leases", exc_info = True)diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 652ff62d395..644fac2f7ba 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -5,6 +5,9 @@from __future__ import annotations+import weakref+from core.training.account_jobs import account_is_retired, account_key, job_accounts+from utils.account_context import arun_as, current_account, run_asimport asyncioimport jsonimport os@@ -1020,6 +1023,8 @@ def _update_assistant(reasoning: str = "",completion_worker_id: str | None = None,) -> None:+ if account_is_retired():+ returnmessage_id = db.discover_and_bind_assistant_message(run["id"])if not message_id:if status not in db.TERMINAL_STATUSES:@@ -1088,12 +1093,17 @@ def _update_assistant()+_supervisors = weakref.WeakSet()++class ResearchSupervisor:def __init__(self,app: Any,poll_seconds: float = 0.5,) -> None:+ _supervisors.add(self)+ self.job_account = Noneself.app = appself.poll_seconds = poll_secondsself.worker_id = uuid.uuid4().hex@@ -1101,9 +1111,11 @@ class ResearchSupervisor:self._task: asyncio.Task | None = Noneself._cancel_events: dict[str, threading.Event] = {}self._lost_leases: set[str] = set()+ self._last_claim_account: str | None = Nonedef start(self) -> None:- db.recover_expired()+ for account in job_accounts():+ run_as(account, db.recover_expired)if self._task is None:self._task = asyncio.create_task(self._loop(), name = "research-supervisor")@@ -1120,19 +1132,22 @@ class ResearchSupervisor:# Polling is intentionally sufficient for one local process; requests never own tasks.passfinally:- await asyncio.to_thread(db.release_worker_leases, self.worker_id)+ for account in job_accounts():+ await asyncio.to_thread(run_as, account, db.release_worker_leases, self.worker_id)def wake(self) -> None:passdef cancel(self, run_id: str) -> None:- self._cancel_events.setdefault(run_id, threading.Event()).set()+ self._cancel_events.setdefault(account_key(run_id), threading.Event()).set()def _cancel_event(self, run_id: str) -> threading.Event:- return self._cancel_events.setdefault(run_id, threading.Event())+ return self._cancel_events.setdefault(account_key(run_id), threading.Event())async def _check_active(self, run_id: str) -> None:- if run_id in self._lost_leases:+ if account_is_retired():+ raise RunCancelled()+ if account_key(run_id) in self._lost_leases:raise LeaseLost()cancelled, owns_lease = await asyncio.gather(asyncio.to_thread(db.is_cancel_requested, run_id),@@ -1257,8 +1272,6 @@ class ResearchSupervisor:def note_server_address(self, server: Any) -> None:state = self.app.state- # run_server publishes the port before it binds and the address only once the listener is- # up, so a known port must not suppress the address.published = getattr(state, "server_request_host", None)if not (isinstance(published, str) and published):host = scope_request_host(server)@@ -1286,11 +1299,15 @@ class ResearchSupervisor:if self._server_port() is None:await asyncio.sleep(self.poll_seconds)continue- run = await asyncio.to_thread(db.claim_next, self.worker_id)+ account, run = await asyncio.to_thread(self._claim_account_run)if run is None:await asyncio.sleep(self.poll_seconds)continue- await self._process(run)+ self.job_account = account+ try:+ await arun_as(account, self._process(run))+ finally:+ self.job_account = Noneexcept asyncio.CancelledError:raiseexcept sqlite3.OperationalError as exc:@@ -1305,6 +1322,27 @@ class ResearchSupervisor:logger.exception("research.supervisor_iteration_failed")await asyncio.sleep(1)+ def _claim_account_run(self):+ # Round robin from the account after the last claim: runs are processed one at a time.+ accounts = job_accounts()+ start = 0+ for index, account in enumerate(accounts):+ if account.account_id == self._last_claim_account:+ start = index + 1+ break+ for offset in range(len(accounts)):+ account = accounts[(start + offset) % len(accounts)]+ try:+ run = run_as(account, db.claim_next, self.worker_id)+ except Exception:+ # The order is stable, so one corrupt database would shadow the accounts behind it.+ logger.exception("research.claim_failed_for_account")+ continue+ if run is not None:+ self._last_claim_account = account.account_id+ return account, run+ return None, None+def _server_port(self) -> int | None:port = getattr(self.app.state, "server_port", None)if not isinstance(port, int) or port <= 0:@@ -1506,6 +1544,7 @@ class ResearchSupervisor:datetime.now(timezone.utc) + timedelta(seconds = _MODEL_CALL_KEY_LIFETIME_SECONDS)).isoformat()key_minted = asyncio.get_running_loop().time()+ account = current_account()token, key = await asyncio.to_thread(auth_storage.create_api_key,username = run["ownerSubject"],@@ -1514,6 +1553,8 @@ class ResearchSupervisor:name = auth_storage.DEEP_RESEARCH_WORKFLOW_KEY_NAME,expires_at = expires,internal = True,+ # Pinned to the claiming account: the username could name a recreated namesake.+ account_id = None if account.is_owner else account.account_id,)config = run["config"]inference = config.get("inferenceRequest") or {}@@ -2038,8 +2079,8 @@ class ResearchSupervisor:await heartbeatexcept asyncio.CancelledError:pass- self._cancel_events.pop(run["id"], None)- self._lost_leases.discard(run["id"])+ self._cancel_events.pop(account_key(run["id"]), None)+ self._lost_leases.discard(account_key(run["id"]))async def _heartbeat(self, run_id: str) -> None:delay = 30.0@@ -2055,14 +2096,14 @@ class ResearchSupervisor:# 120-second lease expires.consecutive_errors += 1if consecutive_errors >= 10:- self._lost_leases.add(run_id)+ self._lost_leases.add(account_key(run_id))self.cancel(run_id)returndelay = 1.0continueconsecutive_errors = 0if not renewed:- self._lost_leases.add(run_id)+ self._lost_leases.add(account_key(run_id))self.cancel(run_id)return@@ -2950,3 +2991,13 @@ class ResearchSupervisor:run = await asyncio.to_thread(db.get_run, run["id"])if actual_status == "cancelled" and not _run_moved_on(run, research_attempt):await asyncio.to_thread(_update_assistant, run, "Research cancelled.", "cancelled")+++def retire_account_research(account) -> None:+ """Cancel this account's in-flight generation without stopping the supervisor."""+ for supervisor in tuple(_supervisors):+ for key, event in list(supervisor._cancel_events.items()):+ if (isinstance(key, str) and account.is_owner) or (+ isinstance(key, tuple) and key[0] == account.account_id+ ):+ event.set()diff --git a/studio/backend/core/training/account_jobs.py b/studio/backend/core/training/account_jobs.pynew file mode 100644index 00000000000..b0b40aa0813--- /dev/null+++ b/studio/backend/core/training/account_jobs.py@@ -0,0 +1,579 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Account ownership and execution boundaries shared by long-running Studio jobs."""++from __future__ import annotations++import importlib+import os+import threading+import weakref+from functools import wraps+from pathlib import Path++from fastapi import HTTPException++from utils.account_context import AccountContext, OWNER, current_account, run_as+from utils.paths.storage_roots import (+ project_workspaces_root,+ resolve_export_write_dir,+ tmp_root,+ workspace_root,+)++_services = weakref.WeakSet()+_services_lock = threading.RLock()+_retired: set[str] = set()+++def _multi_user() -> bool:+ # Lazy: the export worker imports this module on hosts without the auth stack.+ from auth import policy+ return policy.installation_is_multi_user()+++def _has_managed_accounts() -> bool:+ from auth import policy+ return policy.installation_has_managed_accounts()+++def managed_account() -> bool:+ return not current_account().is_owner+++def account_key(value: str):+ """Keep legacy owner keys; namespace in-memory work by immutable account id."""+ account = current_account()+ return value if account.is_owner else (account.account_id, value)+++def account_path(+ value,+ *,+ reference: bool = False,+ shared_cache: bool = False,+):+ """Validate a local path (symlinks resolved). Remote Hub ids only for ``reference`` fields."""+ if not value or not managed_account():+ return value+ raw = str(value)+ path = Path(raw).expanduser()+ if reference and not path.is_absolute() and not path.exists():+ parts = raw.split("/")+ if (+ len(parts) in (1, 2)+ and all(+ part and part not in {".", ".."} and all(c.isalnum() or c in "-_." for c in part)+ for part in parts+ )+ and not raw.startswith((".", "~"))+ ):+ return value+ resolved = path.resolve()++ roots = (workspace_root(), project_workspaces_root(), tmp_root())+ if shared_cache:+ from utils.hf_cache_settings import active_hf_hub_cache+ roots += (Path(active_hf_hub_cache()),)+ if not any(resolved.is_relative_to(root.resolve()) for root in roots):+ raise HTTPException(status_code = 403, detail = "Path is outside this account's workspace")+ return value+++def export_write_path(value):+ if not value or not managed_account():+ return value+ if Path(str(value)).expanduser().is_absolute():+ return account_path(value)+ try:+ resolve_export_write_dir(str(value))+ except ValueError as exc:+ raise HTTPException(status_code = 403, detail = str(exc))+ return value+++def visible_cached_path(value, repo_type: str = "model"):+ if not value or not managed_account():+ return value+ from hub.services.models import account_access++ if account_access.model_visible(str(value), repo_type = repo_type):+ return value+ return account_path(value)+++def account_hf_token(token):+ """False explicitly disables the Hub's environment and saved-token fallback."""+ if managed_account():+ return token.strip() if isinstance(token, str) and token.strip() else False+ return token+++def require_explicit_credentials(values: dict) -> None:+ if not managed_account():+ return+ if values.get("enable_wandb") and not str(values.get("wandb_token") or "").strip():+ raise HTTPException(status_code = 403, detail = "Supply your own W&B API key")+ for key in ("model_name", "base_model", "hf_dataset"):+ reference = values.get(key)+ if (+ reference+ and not Path(str(reference)).is_absolute()+ and not Path(str(reference)).exists()+ ):+ if not isinstance(values.get("hf_token"), str) or not values["hf_token"].strip():+ raise HTTPException(+ status_code = 403,+ detail = "Supply your own Hugging Face token for remote training resources",+ )+ if values.get("push_to_hub") and not values.get("hf_token"):+ raise HTTPException(status_code = 403, detail = "Supply your own Hugging Face token to publish")+ s3 = values.get("s3_dataset") or values.get("s3_config")+ if hasattr(s3, "model_dump"):+ s3 = s3.model_dump()+ if s3 and (+ s3.get("use_iam_role") or not s3.get("access_key_id") or not s3.get("secret_access_key")+ ):+ raise HTTPException(status_code = 403, detail = "Supply your own AWS access keys")+++def validate_job_paths(values: dict, *, cached_resources: bool = False) -> None:+ if not managed_account():+ return+ for key in ("model_name", "base_model", "base_model_id", "hf_dataset"):+ account_path(values.get(key), reference = True)+ for key, repo_type in (+ ("model_local_path", "model"),+ ("dataset_local_path", "dataset"),+ ("model_snapshot_path", "model"),+ ("dataset_snapshot_path", "dataset"),+ ):+ value = values.get(key)+ if value and not cached_resources:+ visible_cached_path(value, repo_type)+ continue+ account_path(value, shared_cache = cached_resources)+ for key, claimed, repo_type in (+ ("model_name", "model_known_cached", "model"),+ ("hf_dataset", "dataset_known_cached", "dataset"),+ ):+ reference = values.get(key)+ # A cached claim pins the shared cache, so the caller's token never authorizes it.+ if values.get(claimed) and reference:+ from hub.services.models import account_access+ account_access.require_model_access(str(reference), repo_type)+ for key in (+ "checkpoint_path",+ "resume_from_checkpoint",+ "output_dir",+ "tensorboard_dir",+ "imatrix_path",+ "data_dir",+ "conditioning_cache_dir",+ "cond_cache_dir",+ "vae_path",+ "text_encoder_path",+ "dataset_path",+ ):+ account_path(values.get(key))+ export_write_path(values.get("save_directory"))+ if isinstance(values.get("imatrix_file"), (str, Path)):+ account_path(values["imatrix_file"])+ for key in ("local_datasets", "local_eval_datasets"):+ for value in values.get(key) or ():+ account_path(value)+ require_explicit_credentials(values)+++def init_job_owner(+ service,+ active,+ cancel,+ clear = None,+) -> None:+ service.job_account = None+ service._result_account = OWNER+ service._account_job_lock = threading.RLock()+ service._account_inflight = 0+ service._account_active = active+ service._account_cancel = cancel+ service._account_clear = clear+ with _services_lock:+ _services.add(service)+++def job_is_foreign(service) -> bool:+ owner = getattr(service, "_result_account", OWNER)+ return (+ isinstance(owner, AccountContext)+ and owner.account_id != current_account().account_id+ and _has_managed_accounts()+ )+++def require_job_owner(service) -> None:+ if job_is_foreign(service):+ raise HTTPException(status_code = 404, detail = "Job not found")+++def refresh_job_owner(service) -> None:+ with service._account_job_lock:+ if not service._account_inflight and not service._account_active():+ service.job_account = None+++def owned_job(*, continuation: bool = False):+ """Hold ownership across validation/spawn and while work is live. Skipped when no managed+ account ever existed."""++ def decorate(fn):+ @wraps(fn)+ def wrapped(self, *args, **kwargs):+ if not _has_managed_accounts():+ return fn(self, *args, **kwargs)+ account = current_account()+ with self._account_job_lock:+ if account.account_id in _retired:+ raise HTTPException(status_code = 403, detail = "Account is retired")+ if continuation:+ require_job_owner(self)+ if job_is_foreign(self) and (self._account_inflight or self._account_active()):+ raise HTTPException(+ status_code = 409, detail = {"code": "job_busy", "message": "Busy"}+ )+ if job_is_foreign(self) and self._account_clear is not None:+ self._account_clear()+ self._result_account = self.job_account = account+ self._account_inflight += 1+ try:+ return fn(self, *args, **kwargs)+ finally:+ with self._account_job_lock:+ self._account_inflight -= 1+ refresh_job_owner(self)++ return wrapped++ return decorate+++def job_control(fn):+ @wraps(fn)+ def wrapped(self, *args, **kwargs):+ lock = getattr(self, "_account_job_lock", None)+ if lock is None or not _has_managed_accounts():+ return fn(self, *args, **kwargs)+ with lock:+ require_job_owner(self)+ self._account_inflight += 1+ try:+ return fn(self, *args, **kwargs)+ finally:+ with lock:+ self._account_inflight -= 1+ refresh_job_owner(self)++ return wrapped+++def job_read(neutral):+ def decorate(fn):+ @wraps(fn)+ def wrapped(self, *args, **kwargs):+ lock = getattr(self, "_account_job_lock", None)+ if lock is None or not _has_managed_accounts():+ return fn(self, *args, **kwargs)+ with lock:+ if self.job_account is not None:+ refresh_job_owner(self)+ if job_is_foreign(self):+ return neutral(self, *args, **kwargs)+ return fn(self, *args, **kwargs)++ return wrapped++ return decorate+++def job_pump(fn):+ @wraps(fn)+ def wrapped(self, *args, **kwargs):+ try:+ return fn(self, *args, **kwargs)+ finally:+ if getattr(self, "job_account", None) is not None:+ refresh_job_owner(self)++ return wrapped+++def account_process_spec(module: str, target: str, env: dict, kwargs: dict):+ if account_is_retired():+ raise HTTPException(status_code = 403, detail = "Account is retired")+ if not managed_account():+ return (module, target, env), kwargs+ return ("core.training.account_jobs", "run_account_child", env), {+ **kwargs,+ "account": current_account(),+ "job_module": module,+ "job_target": target,+ }+++# Model provider credentials the recipe engine reads straight from the environment.+_PROVIDER_SECRET_ENV_VARS = frozenset(+ {+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "NVIDIA_API_KEY",+ "NGC_API_KEY",+ "OPENROUTER_API_KEY",+ "GOOGLE_API_KEY",+ "GEMINI_API_KEY",+ "MISTRAL_API_KEY",+ "TOGETHER_API_KEY",+ "GROQ_API_KEY",+ "XAI_API_KEY",+ "DEEPSEEK_API_KEY",+ "FIREWORKS_API_KEY",+ }+)+++def run_account_child(*, account: AccountContext, job_module: str, job_target: str, **kwargs):+ def execute():+ if not account.is_owner:+ # Child-only: never mutate credentials in the multithreaded server.+ for key in tuple(os.environ):+ if (+ key.startswith(("AWS_", "WANDB_"))+ or key+ in {+ "HF_TOKEN",+ "HF_HUB_TOKEN",+ "HUGGINGFACE_HUB_TOKEN",+ "HUGGINGFACEHUB_API_TOKEN",+ "HUGGING_FACE_HUB_TOKEN",+ "GH_TOKEN",+ "GITHUB_TOKEN",+ }+ or key in _PROVIDER_SECRET_ENV_VARS+ ):+ os.environ.pop(key, None)+ private_tmp = tmp_root()+ private_tmp.mkdir(parents = True, exist_ok = True)+ os.environ.update(+ HF_HUB_DISABLE_IMPLICIT_TOKEN = "1",+ HF_TOKEN_PATH = str(private_tmp / ".no-ambient-hf-token"),+ AWS_EC2_METADATA_DISABLED = "true",+ AWS_SHARED_CREDENTIALS_FILE = str(private_tmp / ".no-ambient-aws-credentials"),+ AWS_CONFIG_FILE = str(private_tmp / ".no-ambient-aws-config"),+ TMPDIR = str(private_tmp),+ )+ target = getattr(importlib.import_module(job_module), job_target)+ return target(**kwargs)++ return run_as(account, execute)+++class AccountRetirementError(RuntimeError):+ """A worker or job of the account could not be stopped; its files stay in place."""+++def retire_account_jobs(account: AccountContext) -> None:+ """Revoke new starts and cancel only this account's work. Call before renaming its dirs."""+ with _services_lock:+ _retired.add(account.account_id)+ services = list(_services)+ errors = []+ for service in services:+ try:+ with service._account_job_lock:+ if service._result_account.account_id == account.account_id:+ if service._account_inflight:+ raise RuntimeError("Account job operation is in flight; retry retirement")+ try:+ run_as(account, service._account_cancel)+ finally:+ proc = getattr(service, "_proc", None)+ if proc is not None and proc.is_alive():+ proc.terminate()+ proc.join(timeout = 5)+ if proc.is_alive():+ proc.kill()+ proc.join(timeout = 3)+ if proc.is_alive():+ raise RuntimeError("Retired account worker has not stopped")+ except Exception as exc:+ errors.append(exc)+ from hub.services.datasets.downloads import retire_account_downloads+ from hub.services.models.downloads import (+ retire_account_downloads as retire_account_model_downloads,+ )+ from core.rag import folder_sync, ingestion+ from core.research_runs import retire_account_research+ from routes.inference import retire_stt_downloads++ for cancel in (+ retire_account_downloads,+ retire_account_model_downloads,+ retire_stt_downloads,+ ingestion.retire_account_ingestions,+ folder_sync.retire_account_sync,+ lambda: retire_account_research(account),+ ):+ try:+ run_as(account, cancel)+ except Exception as exc:+ errors.append(exc)+ if errors:+ raise AccountRetirementError(+ "Could not retire every account job; keep its directories in place"+ ) from errors[0]+++def restore_account_jobs(account_id: str) -> None:+ with _services_lock:+ _retired.discard(account_id)+++def account_is_retired() -> bool:+ return current_account().account_id in _retired+++def job_accounts() -> list[AccountContext]:+ if not _multi_user():+ return [OWNER]+ from auth import storage++ conn = storage.get_connection()+ try:+ rows = conn.execute(+ "SELECT account_id, username, role FROM auth_user WHERE is_active = 1"+ ).fetchall()+ return [AccountContext(*row) for row in rows if row[0] not in _retired]+ finally:+ conn.close()+++def _inactive_job_accounts() -> list[AccountContext]:+ if not _has_managed_accounts():+ return []+ from auth import storage++ conn = storage.get_connection()+ try:+ rows = conn.execute(+ "SELECT account_id, username, role FROM auth_user WHERE is_active = 0"+ ).fetchall()+ return [AccountContext(*row) for row in rows if row[0] not in _retired]+ finally:+ conn.close()+++def startup_reconciliation_accounts() -> list[AccountContext]:+ """Accounts boot-time reconciliation visits; one with no db is skipped (opening creates it)."""+ from utils.paths.storage_roots import studio_db_path++ accounts: list[AccountContext] = []+ seen: set[str] = set()+ for account in (*job_accounts(), *_inactive_job_accounts()):+ if account.account_id in seen:+ continue+ seen.add(account.account_id)+ if account.is_owner:+ accounts.append(account)+ continue+ try:+ if run_as(account, studio_db_path).is_file():+ accounts.append(account)+ except (OSError, ValueError):+ continue+ return accounts+++def sweepable_job_accounts() -> list[AccountContext]:+ """Boot-reconcile set: a deactivated account still holds a registration and GPU reservation."""+ return startup_reconciliation_accounts()+++def validate_recipe_access(recipe) -> None:+ if not managed_account():+ return+ if isinstance(recipe, list):+ for value in recipe:+ validate_recipe_access(value)+ elif isinstance(recipe, dict):+ seed_type = recipe.get("seed_type")+ if seed_type in {"hf", "github_repo"} and not str(recipe.get("token") or "").strip():+ raise HTTPException(status_code = 403, detail = "Supply your own seed-source token")+ for key, value in recipe.items():+ if key in {"api_key_env", "token_env", "hf_token_env"} and value:+ raise HTTPException(status_code = 403, detail = "Supply your own provider credential")+ # Env-resolved before literals: a bare variable name would send the host credential.+ if key in {"api_key", "token", "hf_token"} and isinstance(value, str):+ if value in os.environ:+ raise HTTPException(+ status_code = 403, detail = "Supply your own provider credential"+ )+ if key in {+ "path",+ "paths",+ "file_path",+ "file_paths",+ "data_files",+ "local_path",+ "artifact_path",+ "base_path",+ }:+ for path in value if isinstance(value, list) else [value]:+ if isinstance(path, str):+ if seed_type == "hf" and key == "path":+ remote = path.removeprefix("hf://")+ parts = remote.split("/")+ if (+ not remote.startswith("datasets/")+ or len(parts) < 3+ or any(part in {"", ".", ".."} for part in parts)+ or "\\" in remote+ ):+ raise HTTPException(+ status_code = 403, detail = "Invalid Hugging Face seed path"+ )+ else:+ account_path(path)+ if isinstance(value, (dict, list)):+ validate_recipe_access(value)+++async def account_event_stream(service, events):+ """Recheck ownership for every frame, including streams opened before a start."""+ try:+ async for event in events:+ if job_is_foreign(service):+ yield 'event: busy\ndata: {"status":"busy"}\n\n'+ return+ yield event+ finally:+ await events.aclose()+++def job_busy(service) -> bool:+ active = getattr(service, "_account_active", None)+ return bool(getattr(service, "_account_inflight", 0) or (active and active()))+++def worker_alive(+ service,+ *,+ process: str = "_proc",+ pump: str = "_pump_thread",+) -> bool:+ """A finalizer still writing the prior result also owns the service slot."""+ proc = getattr(service, process, None)+ thread = getattr(service, pump, None)+ return bool(+ (proc is not None and proc.is_alive())+ or (thread is not None and thread is not threading.current_thread() and thread.is_alive())+ )diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.pyindex 86bc9b47375..26b98a84482 100644--- a/studio/backend/core/training/diffusion_training_service.py+++ b/studio/backend/core/training/diffusion_training_service.py@@ -17,6 +17,18 @@ runs a scripted target on a thread.from __future__ import annotations+from core.training.account_jobs import (+ account_is_retired,+ init_job_owner,+ job_busy,+ job_control,+ job_pump,+ job_read,+ owned_job,+ validate_job_paths,+ worker_alive,+)+from utils.account_context import account_threadimport contextlibimport jsonimport math@@ -75,7 +87,23 @@ def _run_diffusion_child(*, event_queue: Any, stop_queue: Any, config: dict) ->def _default_target(*, event_queue: Any, stop_queue: Any, config: dict) -> None:# First thing in the child (before torch): self-bind to parent death and scrub the native path# secret, like the other workers.+ account = config.pop("_job_account", None)+ if account is not None:+ from core.training.account_jobs import run_account_child+ from utils.native_path_leases import run_without_native_path_secret++ run_without_native_path_secret(+ run_account_child,+ account = account,+ job_module = "core.training.diffusion_training_service",+ job_target = "_run_diffusion_child",+ event_queue = event_queue,+ stop_queue = stop_queue,+ config = config,+ )+ returnfrom utils.native_path_leases import run_without_native_path_secret+run_without_native_path_secret(_run_diffusion_child, event_queue = event_queue, stop_queue = stop_queue, config = config)@@ -106,9 +134,9 @@ def _llm_training_active() -> bool:# One JSON file per terminal run, not the LLM sqlite, so diffusion runs stay off the LLM Runs page.def _runs_dir() -> Path:- from utils.paths.storage_roots import studio_root+ from utils.paths.storage_roots import tensorboard_root- d = studio_root() / "runs" / "diffusion"+ d = tensorboard_root() / "diffusion"d.mkdir(parents = True, exist_ok = True)return d@@ -417,6 +445,12 @@ class DiffusionTrainingService:ctx: Any = None,target: Optional[Callable[..., None]] = None,) -> None:+ init_job_owner(+ self,+ lambda: worker_alive(self, pump = "_pump") or self.is_active(),+ lambda: self.stop(save = False),+ self._clear_account_result,+ )self._ctx = ctx if ctx is not None else _CTXself._target = target if target is not None else _default_targetself._lock = threading.Lock()@@ -450,12 +484,18 @@ class DiffusionTrainingService:# The active job's start config, scrubbed of secrets, kept for the run record.self._config: dict[str, Any] = {}+ # ── lifecycle ────────────────────────────────────────────────────────────+ def _clear_account_result(self):+ self._state = _idle_state()+ self._config = {}+def is_active(self) -> bool:with self._lock:if self._reserved:return Truereturn self._proc is not None and self._proc.is_alive()+ @owned_job()def reserve(self) -> None:"""Mark a diffusion-training start as in flight so the image/video load guards (which readis_active) refuse a concurrent load BEFORE the route frees resident GPU models. Without this@@ -492,6 +532,7 @@ class DiffusionTrainingService:)self._reserved = True+ @job_controldef unreserve(self) -> None:"""Clear the reservation set by reserve(). Only touches the reservation flag, never_proc, so a live job stays active on success and a failed start is fully rolled back."""@@ -551,11 +592,13 @@ class DiffusionTrainingService:with self._lock:self._gpu_admissions = max(0, self._gpu_admissions - 1)+ @owned_job()def start(self, config: dict) -> str:"""Validate ``config``, spawn the trainer, and start pumping its events.Raises ValueError for an unusable config (before any spawn) and RuntimeError if ajob is already running. Returns the new job id."""+ validate_job_paths(config)# Validate before spawning, and keep the normalised config: it carries the resolved family the# recipe overrides are keyed on, which the raw request dict need not name.from .diffusion_lora_trainer import _config_from_dict@@ -584,6 +627,8 @@ class DiffusionTrainingService:self._stop_signalled = Falseevent_queue = self._ctx.Queue()self._stop_queue = self._ctx.Queue()+ if self.job_account is not None:+ config = {**config, "_job_account": self.job_account}self._proc = self._ctx.Process(target = self._target,kwargs = {@@ -621,14 +666,17 @@ class DiffusionTrainingService:# Record the config with the fields this family's loop REPLACES set to what it will actually run:# the trainer applies the same table in the child, so without this Previous runs described a# recipe no step ever used.- self._config = {k: v for k, v in dict(config).items() if k != "hf_token"}+ self._config = {+ k: v for k, v in dict(config).items() if k not in {"hf_token", "_job_account"}+ }self._config.update(train_recipe_overrides(normalized_cfg))- self._pump = threading.Thread(+ self._pump = account_thread(target = self._pump_loop, args = (event_queue, self._proc), daemon = True)self._pump.start()return job_id+ @job_controldef stop(self, save: bool = True) -> bool:"""Request a clean stop: the trainer finishes the current step, then either savesa partial adapter (``save=True``, the default) or discards the run (``save=False``,@@ -660,6 +708,13 @@ class DiffusionTrainingService:self._state["updated_at"] = time.time()return True+ @job_read(+ lambda self: {+ **_idle_state(),+ "status": "busy" if job_busy(self) else "idle",+ "message": "Busy" if job_busy(self) else "",+ }+ )def status(self) -> dict[str, Any]:with self._lock:snap = dict(self._state)@@ -667,6 +722,8 @@ class DiffusionTrainingService:snap["active"] = self._proc is not None and self._proc.is_alive()return snap+ # ── event pump ───────────────────────────────────────────────────────────+ @job_pumpdef _pump_loop(self, event_queue: Any, proc: Any) -> None:while True:try:@@ -738,6 +795,8 @@ class DiffusionTrainingService:deleting them then destroys the predecessor that was just handed back. The state half stillapplies either way."""+ if account_is_retired():+ delete = Falsewith self._lock:own = list(self._own_checkpoints) if delete else []self._state["resume_blocked_reason"] = (@@ -764,6 +823,8 @@ class DiffusionTrainingService:used to write the JSON that Previous runs and its Resume action are built from. Thestatus recorded is the one that is true if nothing else ever happens -- the run wasinterrupted -- and the terminal write replaces it in place."""+ if account_is_retired():+ returntry:with self._lock:s = dict(self._state)diff --git a/studio/backend/core/training/s3_dataset.py b/studio/backend/core/training/s3_dataset.pyindex d1c7e92e2d9..91fd91b40f0 100644--- a/studio/backend/core/training/s3_dataset.py+++ b/studio/backend/core/training/s3_dataset.py@@ -16,6 +16,12 @@ Credentials are read once to build the client and never logged or persisted.from __future__ import annotations+from core.training.account_jobs import (+ account_path,+ managed_account,+ require_explicit_credentials,+)+from utils.paths import ensure_dir, tmp_rootimport loggingimport osimport shutil@@ -68,6 +74,7 @@ def _build_s3_client(s3_config: dict):Uses explicit access keys when provided, otherwise falls back to thedefault credential chain (IAM role / instance profile / env / shared creds)."""+ require_explicit_credentials({"s3_dataset": s3_config})import boto3region = s3_config.get("region") or "us-east-1"@@ -185,7 +192,11 @@ def prepare_s3_dataset_download(_validate_single_extension_family(keys)owns_temp_dir = dest_dir is None- target_dir = dest_dir or tempfile.mkdtemp(prefix = "unsloth_s3_dataset_")+ account_path(dest_dir)+ target_dir = dest_dir or tempfile.mkdtemp(+ prefix = "unsloth_s3_dataset_",+ **({"dir": str(ensure_dir(tmp_root()))} if managed_account() else {}),+ )try:os.makedirs(target_dir, exist_ok = True)diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 4444cf3ca79..d85735030fc 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -3,6 +3,7 @@"""Unsloth training backend: integrates Unsloth training with the FastAPI backend."""+from utils.account_context import account_threadimport gcimport osimport sys@@ -2350,7 +2351,6 @@ class UnslothTrainer:return result_datasetdef _preprocess_audio_eval_split(self, eval_dataset, preprocess, custom_format_mapping):- """Preprocess eval data, warning and dropping it on failure."""if eval_dataset is None:return Noneif self.should_stop:@@ -2391,7 +2391,6 @@ class UnslothTrainer:return formatteddef _audio_eval_config(self, training_args):- """Build audio evaluation arguments and return the eval dataset."""eval_dataset = training_args.get("eval_dataset", None)eval_steps = training_args.get("eval_steps", 0.00)if eval_dataset is None:@@ -3410,7 +3409,7 @@ class UnslothTrainer:Seq2SeqTrainingArguments as _Seq2SeqTrainingArguments,)- self.training_thread = threading.Thread(+ self.training_thread = account_thread(target = self._train_worker,args = (dataset,),kwargs = {diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 1f751026363..9c4d0d71a50 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -10,6 +10,20 @@ orchestrates the subprocess lifecycle, pumps events from the worker's mp.Queue,exposes the same API to routes/training.py. Pattern follows data_recipe/jobs/manager.py."""+from core.training.account_jobs import (+ account_is_retired,+ account_process_spec,+ init_job_owner,+ job_busy,+ job_control,+ job_is_foreign,+ job_pump,+ job_read,+ owned_job,+ validate_job_paths,+ worker_alive,+)+from utils.account_context import account_thread, current_accountimport json as _jsonimport mathimport multiprocessing as mp@@ -78,6 +92,7 @@ class TrainingStartRequestRecord:message: strerror: Optional[str] = Noneerror_code: Optional[str] = None+ account_id: str = field(default_factory = lambda: current_account().account_id)class TrainingStartCancellationCapacityError(RuntimeError):@@ -564,6 +579,8 @@ def _cleanup_cancelled_checkpoints(output_dir: Union[str, os.PathLike]) -> None:Completed ``checkpoint-<int>/`` dirs survive. Symlinked output_dir / childrenare skipped so containment can't be bypassed."""+ if account_is_retired():+ returnout = Path(output_dir)if not out.exists() or not out.is_dir() or out.is_symlink():return@@ -873,12 +890,12 @@ class _MLXTrainerAdapter:status_message = "Initializing MLX training...",)- self.training_thread = threading.Thread(+ self.training_thread = account_thread(target = self._run_training_thread,args = (config, event_queue, stop_queue),daemon = True,)- self._pump_thread = threading.Thread(+ self._pump_thread = account_thread(target = self._pump_events,args = (event_queue, self.training_thread),daemon = True,@@ -1089,6 +1106,20 @@ class TrainingBackend:FLUSH_THRESHOLD: int = 10def __init__(self):+ init_job_owner(+ self,+ lambda: (+ self._pending_start_request_id is not None+ or worker_alive(self)+ or self.is_training_active()+ ),+ lambda: (+ self.cancel_start_request(self._pending_start_request_id)+ if self._pending_start_request_id+ else self.stop_training(save = False, expected_job_id = self.current_job_id or "")+ ),+ self._clear_account_result,+ )self._proc: Optional[mp.Process] = None# True from the sidecar-swap handshake until the worker is recorded (startup counts as active).self._spawn_in_progress: bool = False@@ -1157,9 +1188,36 @@ class TrainingBackend:logger.info("TrainingBackend initialized (subprocess mode)")+ def _clear_account_result(self):+ self._progress = TrainingProgress()+ for name in (+ "loss_history",+ "lr_history",+ "step_history",+ "grad_norm_history",+ "grad_norm_step_history",+ "eval_loss_history",+ "eval_step_history",+ ):+ getattr(self, name).clear()+ self.current_job_id = self.current_start_request_id = None+ self._status_start_request_id = self._output_dir = None+ self.eval_enabled = False++ def _require_start_request_account(self, start_request_id):+ record = self._start_requests.get(start_request_id)+ if record is None:+ cancelled = self._start_cancel_tombstones.get(start_request_id)+ record = cancelled[1] if cancelled else None+ if record is not None and record.account_id != current_account().account_id:+ from auth.policy import require_account_scope+ require_account_scope(record.account_id)++ @owned_job()def reserve_start_request(self, start_request_id: str, job_id: str) -> tuple[str, TrainingStartRequestRecord]:+ self._require_start_request_account(start_request_id)with self._lock:self._prune_start_cancel_tombstones_locked()existing = self._start_requests.get(start_request_id)@@ -1200,12 +1258,14 @@ class TrainingBackend:self._prune_start_requests_locked()return "reserved", record+ @job_read(lambda self, *args, **kwargs: None)def peek_start_request(self, start_request_id: str) -> Optional[TrainingStartRequestRecord]:"""The lookup half of reserve_start_request(), with no reservation.Returns the record a retry would replay (live or cancellation-tombstoned), refreshingthe tombstone TTL as the reserve path does so a retry keeps a cancellation alive, orNone when the id is unknown and the caller is free to reserve it."""+ self._require_start_request_account(start_request_id)with self._lock:self._prune_start_cancel_tombstones_locked()existing = self._start_requests.get(start_request_id)@@ -1221,6 +1281,7 @@ class TrainingBackend:)return record+ @job_pumpdef resolve_start_request(self,start_request_id: str,@@ -1230,6 +1291,7 @@ class TrainingBackend:error: Optional[str] = None,error_code: Optional[str] = None,) -> Optional[TrainingStartRequestRecord]:+ self._require_start_request_account(start_request_id)if state not in {"accepted", "rejected"}:raise ValueError(f"Invalid training start request state: {state}")with self._lock:@@ -1250,9 +1312,11 @@ class TrainingBackend:self._pending_start_request_id = Nonereturn record+ @job_controldef cancel_start_request(self, start_request_id: str) -> tuple[Literal["cancelled", "superseded"], TrainingStartRequestRecord]:+ self._require_start_request_account(start_request_id)from .lifecycle import training_lifecycle_guardreserved_cancel_tombstone = False@@ -1408,7 +1472,9 @@ class TrainingBackend:record = self._start_requests.get(start_request_id)return bool(record is not None and record.state == "pending" and record.job_id == job_id)+ @job_read(lambda self, *args, **kwargs: None)def get_start_request(self, start_request_id: str) -> Optional[TrainingStartRequestRecord]:+ self._require_start_request_account(start_request_id)with self._lock:self._prune_start_cancel_tombstones_locked()record = self._start_requests.get(start_request_id)@@ -1417,6 +1483,7 @@ class TrainingBackend:cancelled = self._start_cancel_tombstones.get(start_request_id)return cancelled[1] if cancelled is not None else None+ @job_read(lambda self, *args, **kwargs: None)def status_start_request(self) -> Optional[TrainingStartRequestRecord]:with self._lock:if self._status_start_request_id is None:@@ -1460,7 +1527,9 @@ class TrainingBackend:self._spawn_in_progress = Falseself._new_job_spawn_id = None+ @job_controldef acknowledge_start_request(self, start_request_id: str) -> bool:+ self._require_start_request_account(start_request_id)with self._lock:self._prune_start_cancel_tombstones_locked()record = self._start_requests.get(start_request_id)@@ -1532,6 +1601,7 @@ class TrainingBackend:del self._start_requests[request_id]overflow -= 1+ @owned_job()def start_training(self,job_id: str,@@ -1543,6 +1613,7 @@ class TrainingBackend:) -> bool:# Reserve before lifecycle locking and validation: routes call start_training from worker threads,# so this compare-and-set stops two requests reaching the spawn.+ validate_job_paths(kwargs, cached_resources = True)with self._new_job_spawn_reservation(job_id) as spawn_reserved:if not spawn_reserved:logger.warning("Training subprocess already running")@@ -1709,14 +1780,20 @@ class TrainingBackend:event_queue = _CTX.Queue()stop_queue = _CTX.Queue()- proc = _CTX.Process(- target = run_without_native_path_secret,- args = ("core.training.worker", "run_training_process", cache_env),- kwargs = {+ process_args, process_kwargs = account_process_spec(+ "core.training.worker",+ "run_training_process",+ cache_env,+ {"event_queue": event_queue,"stop_queue": stop_queue,"config": config,},+ )+ proc = _CTX.Process(+ target = run_without_native_path_secret,+ args = process_args,+ kwargs = process_kwargs,daemon = True,)from utils.process_lifetime import adopt_pid, is_process_shutting_down@@ -1848,7 +1925,9 @@ class TrainingBackend:return False# Assign handles and start the pump under the lock, else a poll sees a live _proc with no pump.- new_pump = threading.Thread(target = self._pump_loop, daemon = True)+ new_pump = account_thread(+ target = self._pump_loop, account = self._result_account, daemon = True+ )with self._lock:self._pump_running = Falseself._event_queue = event_queue@@ -1869,6 +1948,7 @@ class TrainingBackend:)return True+ @job_controldef stop_training(self,save: bool = True,@@ -1948,6 +2028,7 @@ class TrainingBackend:self._start_stop_watchdog(cancel = not save, expected_job_id = run_id)return True+ @job_controldef reset_training_state(self, expected_job_id: Optional[str] = None) -> str:from .lifecycle import training_lifecycle_guard@@ -2026,8 +2107,9 @@ class TrainingBackend:and self._stop_watchdog_proc is proc):return- watchdog = threading.Thread(+ watchdog = account_thread(target = self._stop_watchdog_loop,+ account = self._result_account,args = (proc, cancel, self.current_job_id),kwargs = {"grace_s": grace_s, "terminal_seen": terminal_seen},name = f"stop-watchdog-{self.current_job_id or 'unknown'}",@@ -2275,7 +2357,7 @@ class TrainingBackend:if self._pump_thread is not None and self._pump_thread.is_alive():self._pump_thread.join(timeout = 8.0)- if cancelled and output_dir:+ if cancelled and output_dir and not account_is_retired():try:_cleanup_cancelled_checkpoints(output_dir)except Exception:@@ -2423,14 +2505,20 @@ class TrainingBackend:):event_queue = _CTX.Queue()stop_queue = _CTX.Queue()- new_proc = _CTX.Process(- target = run_without_native_path_secret,- args = ("core.training.worker", "run_training_process", cache_env),- kwargs = {+ process_args, process_kwargs = account_process_spec(+ "core.training.worker",+ "run_training_process",+ cache_env,+ {"event_queue": event_queue,"stop_queue": stop_queue,"config": config,},+ )+ new_proc = _CTX.Process(+ target = run_without_native_path_secret,+ args = process_args,+ kwargs = process_kwargs,daemon = True,)from utils.process_lifetime import adopt_pid, is_process_shutting_down@@ -2482,7 +2570,9 @@ class TrainingBackend:logger.info("Training subprocess respawned with Xet disabled (pid=%s)", new_proc.pid)- new_pump = threading.Thread(target = self._pump_loop, daemon = True)+ new_pump = account_thread(+ target = self._pump_loop, account = self._result_account, daemon = True+ )with self._lock:self._in_model_load = Falseself._event_queue = event_queue@@ -2518,7 +2608,9 @@ class TrainingBackend:"Training event pump thread died while the worker is still running; ""restarting it so progress updates resume.")- new_pump = threading.Thread(target = self._pump_loop, daemon = True)+ new_pump = account_thread(+ target = self._pump_loop, account = self._result_account, daemon = True+ )self._pump_thread = new_pumpnew_pump.start()return True@@ -2592,6 +2684,7 @@ class TrainingBackend:return False+ @job_read(lambda self, *args, **kwargs: None)def active_output_dir(self) -> Optional[str]:if not self.is_training_active():return None@@ -2606,6 +2699,12 @@ class TrainingBackend:output_dir = _output_dir_from_resume_checkpoint(resume_from_checkpoint)return str(output_dir) if output_dir else None+ @job_read(+ lambda self, *args, **kwargs: (+ None,+ TrainingProgress(status_message = "Busy" if job_busy(self) else "Ready to train"),+ )+ )def get_training_status(self, theme: str = "light") -> Tuple:with self._lock:progress = self._progress@@ -2616,6 +2715,7 @@ class TrainingBackend:plot = self._create_loss_plot(progress, theme)return (plot, progress)+ @job_read(lambda self, *args, **kwargs: None)def refresh_plot_for_theme(self, theme: str) -> "Optional[plt.Figure]":if theme and isinstance(theme, str) and theme in ["light", "dark"]:self.current_theme = theme@@ -2634,6 +2734,10 @@ class TrainingBackend:@propertydef training_progress(self):+ if job_is_foreign(self._backend):+ return TrainingProgress(+ status_message = "Busy" if job_busy(self._backend) else "Ready to train"+ )return self._backend._progress@training_progress.setter@@ -2641,6 +2745,10 @@ class TrainingBackend:self._backend._progress = valuedef get_training_progress(self):+ if job_is_foreign(self._backend):+ return TrainingProgress(+ status_message = "Busy" if job_busy(self._backend) else "Ready to train"+ )return self._backend._progressdef _update_progress(self, **kwargs):@@ -2666,6 +2774,7 @@ class TrainingBackend:etype = event.get("type") if isinstance(event, dict) else type(event).__name__logger.exception("Training event pump: failed to handle %s event; skipping", etype)+ @job_pumpdef _pump_loop(self) -> None:"""Background thread: consume subprocess events and update state.@@ -3111,6 +3220,8 @@ class TrainingBackend:def _persist_output_dir(self) -> None:# Re-queue the claimed batch at the front so it retries on the next flush.+ if account_is_retired():+ returnwith self._lock:if (not self._output_dir@@ -3181,6 +3292,8 @@ class TrainingBackend:caller create at a time, and ``_db_run_created`` is published only after``create_run`` commits, so a concurrent finalize never runs ``finish_run`` against anot-yet-inserted row (a zero-row UPDATE that would leave the run stuck as running)."""+ if account_is_retired():+ returnself._run_intent_lock.acquire()with self._lock:if (@@ -3251,6 +3364,8 @@ class TrainingBackend:progress are snapshotted under the lock and threaded through the flush/finish calls,so a new run racing between this claim and the DB writes can't be flushed or markedstopped under the old run's finalize."""+ if account_is_retired():+ returnwith self._provenance_lock:with self._lock:if expected_job_id is not None and self.current_job_id != expected_job_id:@@ -3309,6 +3424,8 @@ class TrainingBackend:metric batch, and progress snapshot are all taken under the lock, so a concurrentflush can't double-remove metrics and a racing new run can't redirect the write toa different job. A finalizer passes ``run_id`` to pin the target to its captured run."""+ if account_is_retired():+ returnwith self._lock:target = run_id if run_id is not None else self.current_job_idif not self._metric_buffer or not target or not self._db_run_created:diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex acf4613d085..e803597392e 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -7,6 +7,7 @@ Pattern follows core/data_recipe/jobs/worker.py."""from __future__ import annotations+from utils.account_context import account_threadfrom loggers import get_loggerimport importlibimport importlib.metadata@@ -2204,7 +2205,7 @@ def _start_worker_stop_poller(except (EOFError, OSError, ValueError):return- stop_thread = threading.Thread(target = poll_stop, daemon = True)+ stop_thread = account_thread(target = poll_stop, daemon = True)stop_thread.start()return stop_thread@@ -3987,7 +3988,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->pass_tqdm_stop.wait(3)- _tqdm_thread = _th.Thread(target = _monitor_tqdm, daemon = True)+ _tqdm_thread = account_thread(target = _monitor_tqdm, daemon = True)_tqdm_thread.start()training_type = config.get("training_type", "LoRA/QLoRA")diff --git a/studio/backend/hub/services/datasets/cache_inventory.py b/studio/backend/hub/services/datasets/cache_inventory.pyindex d1a5b7b1d5c..d5961015026 100644--- a/studio/backend/hub/services/datasets/cache_inventory.py+++ b/studio/backend/hub/services/datasets/cache_inventory.py@@ -5,6 +5,7 @@from __future__ import annotations+from core.training.account_jobs import managed_accountimport asyncioimport mathimport os@@ -602,9 +603,14 @@ def _scan_hf_dataset_caches() -> list[dict]:async def list_cached_datasets_response() -> dict:- """List dataset repos already downloaded into the HF cache."""try:- return {"cached": await asyncio.to_thread(_scan_hf_dataset_caches)}+ rows = await asyncio.to_thread(_scan_hf_dataset_caches)+ if managed_account():+ from hub.services.models import account_access+ rows = await asyncio.to_thread(+ account_access.filter_model_rows, rows, repo_type = "dataset"+ )+ return {"cached": rows}except Exception as exc:logger.error("Error listing cached datasets: %s", exc, exc_info = True)raise HTTPException(@@ -615,11 +621,15 @@ async def list_cached_datasets_response() -> dict:async def delete_cached_dataset_response(repo_id: str, cache_path: Optional[str] = None) -> dict:"""Remove a cached dataset repo from the HF cache."""+ if managed_account():+ raise HTTPException(+ status_code = 403, detail = "Only the installation owner can delete shared dataset caches"+ )if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400, detail = "Invalid repo_id format")repo_key = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")- if not downloads.registry.begin_delete(repo_key):+ if not downloads.begin_delete(repo_key):raise HTTPException(status_code = 400,detail = "Cancel the active download before deleting.",@@ -627,7 +637,7 @@ async def delete_cached_dataset_response(repo_id: str, cache_path: Optional[str]try:return await asyncio.to_thread(_delete_cached_dataset_blocking, repo_key, cache_path)finally:- downloads.registry.end_delete(repo_key)+ downloads.end_delete(repo_key)hf_cache_scan.invalidate_hf_cache_scans()diff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.pyindex a483b0d9363..a2088a637da 100644--- a/studio/backend/hub/services/datasets/downloads.py+++ b/studio/backend/hub/services/datasets/downloads.py@@ -5,6 +5,8 @@from __future__ import annotations+from core.training.account_jobs import account_hf_token, account_is_retired, managed_account+from utils.account_context import current_accountimport asyncioimport threadingimport time@@ -22,6 +24,7 @@ from hub.schemas.downloads import ()from hub.services import snapshot_progressfrom hub.services import download_lifecycle+from hub.services.models import account_accessfrom hub.utils import download_manifestfrom hub.utils import download_registryfrom hub.utils import inventory_scan as hf_cache_scan@@ -48,12 +51,65 @@ _DATASET_SIZE_TIMEOUT_SECONDS = 5.0_dataset_size_cache_lock = threading.Lock()_registry = download_registry.get_datasets_registry()+_account_registries = {}+_account_registry_lock = threading.Lock()+# The HF cache is shared across per-account registries, so a reservation must reach all of them.+_deleting: set[str] = set()+++def _account_registry():+ if not managed_account():+ return _registry+ with _account_registry_lock:+ account_id = current_account().account_id+ registry = _account_registries.get(account_id)+ if registry is None:+ registry = download_registry.DownloadRegistry()+ for reserved in _deleting:+ registry.begin_delete(reserved)+ _account_registries[account_id] = registry+ return registry+++def begin_delete(repo_id: str) -> bool:+ """Reserve *repo_id* until :func:`end_delete`: deleting under a live download strands blobs."""+ key = download_registry.normalize_repo_key(repo_id)+ with _account_registry_lock:+ reserved = []+ for registry in (_registry, *_account_registries.values()):+ if not registry.begin_delete(repo_id):+ for done in reserved:+ done.end_delete(repo_id)+ return False+ reserved.append(registry)+ _deleting.add(key)+ return True+++def end_delete(repo_id: str) -> None:+ key = download_registry.normalize_repo_key(repo_id)+ with _account_registry_lock:+ _deleting.discard(key)+ for registry in (_registry, *_account_registries.values()):+ registry.end_delete(repo_id)def _download_job_key(repo_id: str) -> str:return download_registry.normalize_repo_key(repo_id)+def _claim_dataset_download(registry, key: str, transport: str, **kwargs) -> tuple[bool, str]:+ """One dataset repo at a time across accounts: a second worker purges the first one's partials."""+ repo_id = kwargs.get("repo_id") or key+ with _account_registry_lock:+ for other in (_registry, *_account_registries.values()):+ if other is registry:+ continue+ for ref in other.active_job_refs(repo_id):+ return False, ref.state+ return registry.claim(key, transport, **kwargs)++def get_dataset_snapshot_metadata_cached(repo_id: str, hf_token: Optional[str] = None) -> tuple[int, frozenset[str]]:@@ -62,6 +118,7 @@ def get_dataset_snapshot_metadata_cached(The dataset worker downloads every sibling, so the denominator is the fullsibling-size sum and the hashes cover every file. Consumed by the shared``snapshot_progress`` accounting."""+ hf_token = account_hf_token(hf_token)token_fp = hf_cache_scan.token_fingerprint(hf_token)cache_key = (repo_id, token_fp)with _dataset_size_cache_lock:@@ -121,20 +178,27 @@ async def get_dataset_download_progress_response(Scans the ``datasets--owner--name`` cache dir and shares the blob accountingwith the model path via ``snapshot_progress``. Returns ``cache_path`` for theUI."""+ hf_token = account_hf_token(hf_token)+ registry = _account_registry()+ if managed_account():+ # The dataset cache is shared, so reading it needs the same grant as the model path.+ await asyncio.to_thread(+ account_access.require_download_progress_access, registry, repo_id, "dataset"+ )return await snapshot_progress.snapshot_progress_response(repo_type = "dataset",repo_id = repo_id,job_key = _download_job_key(repo_id),expected_bytes = expected_bytes,hf_token = hf_token,- registry = _registry,+ registry = registry,metadata_resolver = get_dataset_snapshot_metadata_cached,)def _dataset_status(key: str, *, repo_id: Optional[str] = None) -> DatasetDownloadJobStatus:state, error, generation = download_lifecycle.idle_status(- _registry,+ _account_registry(),key,repo_type = "dataset",repo_id = repo_id,@@ -154,12 +218,19 @@ async def download_dataset_response(``allow_ambient_token=False`` keeps the worker anonymous when the caller sent no token, forrepos named over the API rather than chosen here."""+ if account_is_retired():+ raise HTTPException(status_code = 403, detail = "Account is retired")+ hf_token = account_hf_token(hf_token)+ allow_ambient_token = allow_ambient_token and not managed_account()repo_id = body.repo_id.strip()if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400,detail = f"Invalid repo_id: {repo_id!r}",)+ if managed_account():+ # Before the claim: a conflict reply would otherwise reveal another account's job.+ await asyncio.to_thread(account_access.authorize_download, repo_id, "dataset", hf_token)# Canonicalize so two different-cased paste-ins share one job + cache dir.repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")key = _download_job_key(repo_id)@@ -178,7 +249,9 @@ async def download_dataset_response(cache_paths = get_hf_cache_paths()cache_env = cache_paths.child_env({})- claimed, claim_state = _registry.claim(+ registry = _account_registry()+ claimed, claim_state = _claim_dataset_download(+ registry,key,transport,repo_type = "dataset",@@ -186,11 +259,11 @@ async def download_dataset_response(hub_cache = str(cache_paths.hub_cache),xet_cache = str(cache_paths.xet_cache),)- generation = _registry.current_generation(key)+ generation = registry.current_generation(key)if not claimed:# Both come from adoptable: an in-progress delete leaves no job, and only an in-flight job of this# repo attached to anything.- adoptable = _registry.adoptable(key)+ adoptable = registry.adoptable(key)return {"repo_id": repo_id,"state": claim_state,@@ -199,11 +272,14 @@ async def download_dataset_response("generation": generation,# An adopted job keeps the transport it started on, so report it rather than let the caller assume# the one it asked for.- "transport": _registry.job_transport(key),+ "transport": registry.job_transport(key),# And its cancel marker: a run that fell back from Xet to HTTP still cancels into a restart-only# partial.- "cancel_transport": _registry.job_cancel_transport(key),+ "cancel_transport": registry.job_cancel_transport(key),}+ # Record ownership with the claim, not at launch: retirement scans this registry, and an+ # unattributed job makes its cancel raise "Download not found" and abort the deletion.+ download_lifecycle.record_download_account(registry, key)download_manifest.clear_cancel_marker("dataset",repo_id,@@ -212,7 +288,7 @@ async def download_dataset_response()state = download_lifecycle.launch_worker(- _registry,+ registry,key,spawn = lambda: download_lifecycle.spawn_worker(["--repo-id", repo_id, "--dataset"],@@ -255,7 +331,7 @@ async def cancel_dataset_download_response(body: CancelDatasetDownloadRequest) -key = _download_job_key(repo_id)state = download_lifecycle.cancel_worker(- _registry,+ _account_registry(),key,generation = body.generation,label = f"dataset {repo_id}",@@ -284,7 +360,7 @@ async def get_active_dataset_downloads_response(repo_id: str = "") -> ActiveDown)return ActiveDownloadsResponse(downloads = download_lifecycle.active_download_refs(- _registry,+ _account_registry(),canonical_repo_id,with_variant = False,)@@ -298,6 +374,13 @@ async def get_dataset_transport_status_response(repo_id: str) -> dict:repo_id = repo_id.strip()if not _is_valid_repo_id(repo_id):return {"has_partial": False, "last_transport": None, "resumable": False}+ if managed_account():+ await asyncio.to_thread(+ account_access.require_download_progress_access,+ _account_registry(),+ repo_id,+ "dataset",+ )return {"has_partial": has_active_incomplete_blobs("dataset", repo_id),"last_transport": download_registry.read_active_transport_marker("dataset", repo_id),@@ -306,3 +389,29 @@ async def get_dataset_transport_status_response(repo_id: str) -> dict:registry = _registry+++def retire_account_downloads() -> None:+ registry = (+ _registry+ if current_account().is_owner+ else _account_registries.get(current_account().account_id)+ )+ if registry is None:+ return+ stragglers = []+ for job in registry.active_job_refs():+ download_lifecycle.cancel_worker(+ registry, job.key, generation = job.generation, label = "dataset", logger = logger+ )+ proc = registry.get_process(job.key)+ if proc is None:+ continue+ try:+ proc.wait(timeout = 10)+ except Exception:+ stragglers.append(job.key)+ if stragglers:+ raise RuntimeError(+ f"Retired account dataset downloads have not stopped: {sorted(stragglers)}"+ )diff --git a/studio/backend/hub/services/datasets/formatting.py b/studio/backend/hub/services/datasets/formatting.pyindex 8c455691888..9593d1913f8 100644--- a/studio/backend/hub/services/datasets/formatting.py+++ b/studio/backend/hub/services/datasets/formatting.py@@ -5,6 +5,11 @@from __future__ import annotations+from core.training.account_jobs import (+ account_hf_token,+ account_path,+ visible_cached_path,+)import base64import errnoimport io@@ -302,6 +307,21 @@ def _load_processed_hf_preview_slice(return preview_slice, total_rows+def _cached_preview_visible(request: CheckFormatRequest) -> bool:+ # A cache hit is not authorization: the shared cache holds other accounts' private repos.+ from hub.services.models import account_access++ if not account_access.managed_account():+ return True+ if account_access.model_visible(request.dataset_name, repo_type = "dataset"):+ return True+ local_path = getattr(request, "local_path", None)+ return bool(local_path) and account_access.model_visible(+ str(local_path),+ repo_type = "dataset",+ )++def _load_any_cached_hf_preview_slice(request: CheckFormatRequest,preview_size: int,@@ -312,6 +332,8 @@ def _load_any_cached_hf_preview_slice(# sentinel. Neither reaches the network, so read first and gate the answer: reading our# own disk is not the leak, handing it back is. Gating first probed /auth-check for a# prefer-local request that had ruled the network out and then missed the cache anyway.+ if not _cached_preview_visible(request):+ return Nonecached_preview = _load_cached_hf_preview_slice(request, preview_size)if cached_preview is None:try:@@ -355,6 +377,9 @@ def check_format_response(its previous implementation used, preserving source column order when theonly data filename has no split label."""+ hf_token = account_hf_token(hf_token)+ account_path(request.dataset_name, reference = True)+ visible_cached_path(getattr(request, "local_path", None), "dataset")try:from itertools import islice@@ -577,6 +602,9 @@ def ai_assist_mapping_response(a conversion strategy, then validate it. Falls back to simple columnclassification if the advisor fails."""+ hf_token = account_hf_token(hf_token)+ account_path(request.dataset_name, reference = True)+ visible_cached_path(getattr(request, "local_path", None), "dataset")try:from hub.utils.llm_assist import llm_conversion_advisordiff --git a/studio/backend/hub/services/datasets/local.py b/studio/backend/hub/services/datasets/local.pyindex 28655b26fb4..12042f5cd8c 100644--- a/studio/backend/hub/services/datasets/local.py+++ b/studio/backend/hub/services/datasets/local.py@@ -10,7 +10,6 @@ import jsonimport uuidfrom contextlib import suppressfrom pathlib import Path-from fastapi import HTTPException, UploadFilefrom hub.schemas.datasets import (@@ -20,6 +19,8 @@ from hub.schemas.datasets import ()from hub.utils.paths import dataset_uploads_root, ensure_dir, recipe_datasets_rootfrom utils.upload_limits import get_upload_limit_mb, upload_limit_bytes, upload_limit_label+from utils.paths.lazy import LazyPath+from utils.paths.storage_roots import own_entry, within_accountfrom utils.paths.path_utils import (any_not_appledouble_metadata,drop_appledouble_metadata,@@ -34,8 +35,8 @@ DATA_EXTS = _TABULAR_EXTS + _ARCHIVE_EXTSLOCAL_FILE_EXTS = (".json", ".jsonl", ".csv", ".parquet")LOCAL_UPLOAD_EXTS = {".csv", ".json", ".jsonl", ".parquet"}LOCAL_UPLOAD_CHUNK_BYTES = 1024 * 1024-LOCAL_DATASETS_ROOT = recipe_datasets_root()-DATASET_UPLOAD_DIR = dataset_uploads_root()+LOCAL_DATASETS_ROOT = LazyPath(recipe_datasets_root)+DATASET_UPLOAD_DIR = LazyPath(dataset_uploads_root)def _safe_read_metadata(path: Path) -> dict | None:@@ -137,6 +138,8 @@ def _build_recipe_dataset_items() -> list[LocalDatasetItem]:for entry in LOCAL_DATASETS_ROOT.iterdir():if not entry.is_dir() or not entry.name.startswith("recipe_"):continue+ if not within_account(entry):+ continueparquet_dir = entry / "parquet-files"if not parquet_dir.exists() or not any_not_appledouble_metadata(parquet_dir.glob("*.parquet")@@ -146,7 +149,7 @@ def _build_recipe_dataset_items() -> list[LocalDatasetItem]:rows = Nonemetadata_summary = Nonemetadata_path = entry / "metadata.json"- if metadata_path.exists():+ if own_entry(metadata_path):metadata_payload = _safe_read_metadata(metadata_path)rows = _safe_read_rows_from_metadata(metadata_payload)metadata_summary = _safe_read_metadata_summary(metadata_payload)@@ -174,7 +177,7 @@ def _build_uploaded_dataset_items() -> list[LocalDatasetItem]:for path in DATASET_UPLOAD_DIR.iterdir():if not path.is_file() or path.suffix.lower() not in LOCAL_UPLOAD_EXTS:continue- if is_appledouble_metadata(path):+ if is_appledouble_metadata(path) or not within_account(path):continuetry:if path.stat().st_size == 0:diff --git a/studio/backend/hub/services/datasets/local_options.py b/studio/backend/hub/services/datasets/local_options.pyindex 92fb4b3b5ad..c48e58e8f67 100644--- a/studio/backend/hub/services/datasets/local_options.py+++ b/studio/backend/hub/services/datasets/local_options.py@@ -3,6 +3,7 @@from __future__ import annotations+from core.training.account_jobs import visible_cached_pathimport jsonimport osimport re@@ -716,10 +717,17 @@ def _sorted_options(options: set[tuple[str, str]], dataset: str = "") -> list[Dadef local_dataset_options(request: LocalDatasetOptionsRequest) -> LocalDatasetOptionsResponse:+ visible_cached_path(request.local_path, "dataset")repo_id = request.dataset_name.strip()if not is_valid_repo_id(repo_id):return LocalDatasetOptionsResponse(cache_available = False, splits = [])+ if not request.local_path:+ # The lookup spans the shared cache; a hit there is not authorization.+ from hub.services.models import account_access+ if not account_access.model_visible(repo_id, repo_type = "dataset"):+ return LocalDatasetOptionsResponse(cache_available = False, splits = [])+selected = (dataset_cache_path_from_cache_path(request.local_path, repo_id)if request.local_pathdiff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex 02b5d3898d5..55ac2f737ad 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -15,6 +15,9 @@ from typing import Callable, Mapping, Optional, Sequencefrom fastapi import HTTPException+from hub.services.models import account_access+from utils.account_context import OWNER_ACCOUNT_ID, account_thread, current_account_id+from hub.schemas.downloads import ActiveDownload, DownloadJobStatefrom hub.utils import download_manifestfrom hub.utils import download_registry@@ -25,6 +28,41 @@ from hub.utils.state_dir import RepoTypelogger = logging.getLogger(__name__)+_job_accounts: dict[tuple[int, str], str] = {}+_job_accounts_lock = threading.Lock()+++def record_download_account(registry, key: str) -> None:+ """Attribute *key* the instant the claim succeeds: until then it names the last downloader."""+ if account_access.account_scope() is None:+ return+ with _job_accounts_lock:+ _job_accounts[(id(registry), key)] = current_account_id()+++def download_belongs_to_account(registry, key: str) -> bool:+ if account_access.account_scope() is None:+ return True+ with _job_accounts_lock:+ owner = _job_accounts.get((id(registry), key), OWNER_ACCOUNT_ID)+ return owner == current_account_id()+++def require_download_account(registry, key: str) -> None:+ if not download_belongs_to_account(registry, key):+ raise HTTPException(status_code = 404, detail = "Download not found")+++def require_live_account(registry, key: str) -> None:+ """Called right after ownership is recorded, so no claim racing retirement reaches spawn."""+ from core.training.account_jobs import account_is_retired++ if not account_is_retired():+ return+ registry.set_job(key, "error", "Account is retired")+ raise HTTPException(status_code = 403, detail = "Account is retired")++def backend_dir() -> Path:return Path(__file__).resolve().parent.parent.parent@@ -140,7 +178,15 @@ def spawn_worker(cache_env: Optional[Mapping[str, str]] = None,allow_ambient_token: bool = True,) -> subprocess.Popen:- """Spawn the download worker. XET and ``hf_transfer`` write chunks out of order, so their partials can't resume under a sequential writer; the HTTP path stays sequential so SIGKILL -> resume is byte-identical. ``protected_blob_hashes`` are blobs a concurrent same-repo peer is writing, excluded from the cache-prep purge so a shared ``.incomplete`` (e.g. bundled mmproj) is never deleted."""+ """Spawn the download worker.++ XET and ``hf_transfer`` write chunks out of order, so their partials can't+ resume under a sequential writer; the HTTP path stays sequential so+ SIGKILL -> resume is byte-identical. ``protected_blob_hashes`` are blobs a+ concurrent same-repo peer is writing, excluded from the cache-prep purge so a+ shared ``.incomplete`` (e.g. bundled mmproj) is never deleted.+ """+ allow_ambient_token = allow_ambient_token and not account_access.managed_account()cwd = backend_dir()mode = download_registry.TRANSPORT_XET if use_xet else download_registry.TRANSPORT_HTTPfrom utils.hf_cache_settings import get_hf_cache_paths@@ -305,6 +351,8 @@ def finalize_worker_exit(metadata = registry.get_job_metadata(key)state = classify_exit(rc, cancel_requested = cancel_requested)if state == "complete":+ if repo_id and repo_type:+ account_access.record_model_grant(repo_id, repo_type)hf_cache_scan.invalidate_hf_cache_scans()registry.set_job(key, "complete")# Where /v1 learns a new model exists: its resolver answers from a cached scan with no watcher, so it would report the model absent and serve whatever is resident. Models only, since noting a dataset id as a local model would refuse a bare request naming it instead of letting a foreign id fall through.@@ -1021,7 +1069,8 @@ def register_worker(finally:hf_cache_scan.invalidate_hf_cache_scans()- threading.Thread(target = _watch, name = watch_name, daemon = True).start()+ # Always pinned, so a policy cache miss cannot unbind a job.+ account_thread(target = _watch, name = watch_name, daemon = True).start()return True@@ -1040,7 +1089,16 @@ def launch_worker(watch_name: str,allow_ambient_token: bool = True,) -> str:- # Only the Xet success-recording consumes this, and sampling lazy-loads unsloth_zoo, so torch and transformers, on the request path.+ # Only the Xet success-recording consumes this, and sampling lazy-loads unsloth_zoo, so torch and+ # transformers, on the request path.+ if account_access.account_scope() is not None:+ record_download_account(registry, key)+ require_live_account(registry, key)+ try:+ account_access.authorize_download(repo_id, repo_type, hf_token)+ except HTTPException:+ registry.set_job(key, "error", "Repository not found")+ raise_baseline: Optional[int] = Noneif transport == download_registry.TRANSPORT_XET:# Before spawn(), deliberately: a small download can finalize its blobs while we are still registering the process, and a later baseline would show no growth for a real transfer.@@ -1095,6 +1153,7 @@ def cancel_worker(label: str,logger,) -> str:+ require_download_account(registry, key)proc = registry.get_process(key)# No worker process yet: arm a pending cancel so register_process kills it on arrival during the claim-to-register window.if proc is None:@@ -1140,6 +1199,9 @@ def idle_status() -> tuple[DownloadJobState, Optional[str], int]:state = registry.get_job(key)generation = registry.current_generation(key)+ # A repo with no job has no recorded owner; a 404 there strands a client hydrating a download.+ if state.state != "idle":+ require_download_account(registry, key)if (state.state == "idle"and repo_id@@ -1158,6 +1220,8 @@ def active_download_refs() -> list[ActiveDownload]:downloads: list[ActiveDownload] = []for ref in registry.active_job_refs(repo_id):+ if not download_belongs_to_account(registry, ref.key):+ continuemetadata = ref.metadataif with_variant:ref_repo_id = metadata.repo_id if metadata is not None else ref.key.split("::", 1)[0]diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pynew file mode 100644index 00000000000..184dfe07f64--- /dev/null+++ b/studio/backend/hub/services/models/account_access.py@@ -0,0 +1,876 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Account boundaries shared by model services and inference routes."""++from __future__ import annotations++import re+import json+import os+import sqlite3+import sys+import threading+import time+from collections import deque+from concurrent.futures import Future+from datetime import datetime, timezone+from contextlib import closing, contextmanager+from functools import wraps+from pathlib import Path++from fastapi import HTTPException+from fastapi.responses import JSONResponse+from huggingface_hub import HfApi++from auth import policy+from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError+from utils.paths import storage_roots+from utils.paths.storage_roots import project_workspaces_root, studio_db_path, workspace_root++from utils.account_context import (+ OWNER,+ AccountContext,+ account_thread,+ current_account,+ current_account_id,+ is_owner_context,+)++_ACCOUNT_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")+++def media_link_target(media_id: str) -> str:+ if is_owner_context():+ return media_id+ return f"{current_account().account_id}:{media_id}"+++_link_accounts: dict[str, tuple[int, AccountContext | None]] = {}+_link_accounts_lock = threading.Lock()+++def _signed_link_account(account_id: str) -> AccountContext | None:+ """Keyed on policy generation so deactivation revokes links at once, not at TTL."""+ generation = policy.account_generation()+ with _link_accounts_lock:+ cached = _link_accounts.get(account_id)+ if cached is not None and cached[0] == generation:+ return cached[1]+ from auth.storage import get_account_by_id++ account = get_account_by_id(account_id)+ with _link_accounts_lock:+ if len(_link_accounts) >= 256:+ _link_accounts.clear()+ _link_accounts[account_id] = (generation, account)+ return account+++def media_link_account(target: str | None, media_id: str) -> AccountContext | None:+ if target == media_id:+ return OWNER+ if not target:+ return None+ account_id, sep, signed_id = target.partition(":")+ if not sep or signed_id != media_id or not _ACCOUNT_ID.fullmatch(account_id):+ return None+ if account_id == OWNER.account_id:+ return OWNER+ account = _signed_link_account(account_id)+ return None if account is None or account.is_owner else account+++def managed_account() -> bool:+ return not is_owner_context()+++def account_scope() -> str | None:+ """None keeps legacy install-wide scope; any managed-account record scopes owner work too."""+ if not is_owner_context():+ return current_account_id()+ return current_account_id() if policy.installation_has_managed_accounts() else None+++_resident_accounts: dict[str, tuple[str, frozenset[str]]] = {}++_generation_accounts: dict[str, dict[str, int]] = {}+_generation_lock = threading.Lock()+++@contextmanager+def media_generation(modality: str):+ """Recorded even on one-account installs: an account created mid-generation sees it foreign."""+ account_id = current_account_id()+ with _generation_lock:+ counts = _generation_accounts.setdefault(modality, {})+ counts[account_id] = counts.get(account_id, 0) + 1+ try:+ yield+ finally:+ with _generation_lock:+ counts = _generation_accounts.get(modality) or {}+ remaining = counts.get(account_id, 0) - 1+ if remaining > 0:+ counts[account_id] = remaining+ else:+ counts.pop(account_id, None)+ if not counts:+ _generation_accounts.pop(modality, None)+++_generation_holders: dict[str, list[str]] = {}+++@contextmanager+def media_generation_slot(modality: str):+ """Entered only with the slot held, so a queued request is not the running one."""+ account_id = current_account_id()+ with _generation_lock:+ _generation_holders.setdefault(modality, []).append(account_id)+ try:+ yield+ finally:+ with _generation_lock:+ holders = _generation_holders.get(modality) or []+ if account_id in holders:+ holders.remove(account_id)+ if not holders:+ _generation_holders.pop(modality, None)+++def tracked_generation_account() -> Optional[str]:+ return account_scope()+++def generation_is_mine(modality: str) -> bool:+ if account_scope() is None:+ return False+ account_id = current_account_id()+ with _generation_lock:+ holders = _generation_holders.get(modality)+ if holders:+ return account_id in holders+ return bool(_generation_accounts.get(modality, {}).get(account_id))+++def generation_is_foreign(modality: str) -> bool:+ # account_scope, not login mode: a deactivated account's job keeps running and stays foreign.+ if account_scope() is None:+ return False+ account_id = current_account_id()+ with _generation_lock:+ holders = _generation_holders.get(modality)+ if holders:+ return any(holder != account_id for holder in holders)+ return any(+ account != account_id and count+ for account, count in _generation_accounts.get(modality, {}).items()+ )+++def foreign_media_generations(account_id: str) -> int:+ """Other accounts' image and video work, tracked outside ``active_generations``."""+ total = 0+ with _generation_lock:+ for modality, counts in _generation_accounts.items():+ holders = _generation_holders.get(modality)+ if holders:+ continue+ total += sum(count for account, count in counts.items() if account != account_id)+ for holders in _generation_holders.values():+ total += sum(1 for holder in holders if holder != account_id)+ # sys.modules, not an import: no video job is in flight before its module loads.+ video = sys.modules.get("core.inference.video")+ reserved = video.generation_account_in_flight() if video is not None else None+ if reserved is not None and reserved != account_id:+ total += 1+ return total+++# A failed load leaves the previous model resident, still owned by its account.+_prior_resident_accounts: dict[str, tuple[str, frozenset[str]]] = {}+# What each publish displaced, so a load that never commits can restore it.+_uncommitted_resident: dict[str, tuple] = {}+_uncommitted_components: dict[str, tuple] = {}+++def note_resident_account(modality: str, *references: str) -> None:+ """CPU residents have no GPU lease, so record load provenance at the route boundary."""+ if policy.installation_has_managed_accounts():+ previous = _resident_accounts.get(modality)+ _uncommitted_resident[modality] = (+ current_account_id(),+ previous,+ _prior_resident_accounts.get(modality),+ )+ if previous is not None and previous[1] != frozenset(references):+ _prior_resident_accounts[modality] = previous+ _resident_accounts[modality] = (current_account_id(), frozenset(references))+++# Admits a media load and scans for one at retirement, so neither slips between the other's steps.+media_load_lock = threading.Lock()+++def require_live_account() -> None:+ """A tombstoned or disabled account starts nothing and shares nothing."""+ if managed_account():+ from core.training.account_jobs import account_is_retired+ from state import active_generations++ if account_is_retired():+ raise HTTPException(status_code = 403, detail = "Account is retired")+ if active_generations.fenced(current_account_id()):+ raise HTTPException(status_code = 403, detail = "Account is disabled")+++def admit_media_load(modality: str, start, *references: str):+ """Start a load under the retirement scan's lock, so a tombstoned account starts none."""+ with media_load_lock:+ require_live_account()+ result = start()+ note_resident_account(modality, *references)+ return result+++def retire_media_load(modality: str, account_id: str, engine) -> bool:+ """Tear down ``engine``'s in-flight load when ``account_id`` started it; True when one was."""+ with media_load_lock:+ resident = _resident_accounts.get(modality)+ if engine is None or resident is None or resident[0] != account_id:+ return False+ if not engine.loading_repo_ids():+ return False+ engine.unload()+ return True+++# Accounts sharing the resident: its loader plus every account whose matching load reused it.+_resident_sharers: dict[str, set[str]] = {}+_sharers_lock = threading.Lock()+++def publish_resident(modality: str, *references: str) -> None:+ """A new resident: recorded as before, with its loader as the only sharer."""+ if not policy.installation_has_managed_accounts():+ return+ require_live_account()+ note_resident_account(modality, *references)+ with _sharers_lock:+ _resident_sharers[modality] = {current_account_id()}+++def join_resident(modality: str) -> None:+ """A matching load reused the resident: the caller shares it from now on."""+ if not policy.installation_has_managed_accounts():+ return+ require_live_account()+ with _sharers_lock:+ _resident_sharers.setdefault(modality, set()).add(current_account_id())+++def release_shared_resident(modality: str) -> bool:+ """Drop the caller's share while others keep the model; False leaves the share for a real unload."""+ if not policy.installation_has_managed_accounts():+ return False+ account_id = current_account_id()+ with _sharers_lock:+ sharers = _resident_sharers.get(modality)+ if not sharers or account_id not in sharers or len(sharers) == 1:+ return False+ sharers.discard(account_id)+ return True+++def clear_resident(modality: str) -> None:+ """The backend was torn down; the next load publishes afresh."""+ with _sharers_lock:+ _resident_sharers.pop(modality, None)+++def retire_resident_shares(account_id: str) -> None:+ """A deactivated or deleted account shares nothing; other sharers keep the model."""+ with _sharers_lock:+ for sharers in _resident_sharers.values():+ sharers.discard(account_id)+++def resident_shared_with(modality: str, account_id: str) -> bool:+ with _sharers_lock:+ return account_id in _resident_sharers.get(modality, ())+++_resident_components: dict[str, tuple[str, frozenset[str]]] = {}+++def note_resident_components(modality: str, primary: str, *references: str) -> None:+ """A generation on a shared resident must clear its base repo and baked adapters too."""+ if policy.installation_has_managed_accounts():+ _uncommitted_components[modality] = (+ current_account_id(),+ _resident_components.get(modality),+ None,+ )+ _resident_components[modality] = (+ str(primary or ""),+ frozenset(r for r in references if isinstance(r, str) and r),+ )+++def restore_resident_metadata(modality: str) -> bool:+ """Undo a failed load's records; no-op once another load took residency."""+ if not policy.installation_has_managed_accounts():+ return False+ account_id = current_account_id()+ restored = False+ for published, live in (+ (_uncommitted_resident, _resident_accounts),+ (_uncommitted_components, _resident_components),+ ):+ entry = published.get(modality)+ if entry is None or entry[0] != account_id:+ continue+ del published[modality]+ _, previous, prior = entry+ if previous is None:+ live.pop(modality, None)+ else:+ live[modality] = previous+ if live is _resident_accounts:+ if prior is None:+ _prior_resident_accounts.pop(modality, None)+ else:+ _prior_resident_accounts[modality] = prior+ restored = True+ return restored+++def resident_hidden(modality: str | None = None, reference: str | None = None) -> bool:+ if not managed_account():+ return False+ if modality is not None and resident_shared_with(modality, current_account_id()):+ return False+ from core.inference import gpu_arbiter++ owner = gpu_arbiter.current_owner()+ if owner is not None and (modality is None or owner == modality):+ return gpu_arbiter.owner_account() != current_account_id()+ if reference:+ account, references = _resident_accounts.get(modality, (OWNER.account_id, frozenset()))+ if reference not in references:+ prior = _prior_resident_accounts.get(modality)+ if prior is not None and reference in prior[1]:+ account, references = prior+ return account != current_account_id() or reference not in references+ return False+++def hidden_resident_response():+ return JSONResponse(content = {"loaded": True, "yours": False})+++def hidden_chat_status_response():+ """The chat status shape (``loaded`` is a list there), with nothing of the resident."""+ return JSONResponse(content = {"loaded": [], "loading": [], "yours": False})+++def gpu_busy_error(path: str | None = None) -> HTTPException:+ from core.inference import gpu_arbiter+ from state import active_generations++ account_id = current_account_id()+ error = gpu_arbiter.GpuBusyForAnotherAccountError(+ gpu_arbiter.current_owner() or gpu_arbiter.CHAT,+ active_generations.foreign_count(account_id),+ )+ return error.as_http_exception(path)+++def require_idle_other_accounts(path: str | None = None) -> None:+ # Managed accounts, not login mode: deactivating the last drops the count mid-generation.+ if policy.installation_has_managed_accounts():+ from core.inference.gpu_arbiter import require_no_foreign_generations+ require_no_foreign_generations(current_account_id(), path = path)+++def require_resident_control(modality: str, reference: str | None = None) -> None:+ require_idle_other_accounts()+ if resident_hidden(modality, reference):+ raise HTTPException(status_code = 404, detail = "Model not found")+++def gpu_busy_route(handler):+ @wraps(handler)+ async def wrapped(*args, **kwargs):+ try:+ return await handler(*args, **kwargs)+ except GpuBusyForAnotherAccountError:+ error = gpu_busy_error()+ return JSONResponse(status_code = 409, content = error.detail, headers = error.headers)+ except HTTPException as exc:+ if isinstance(exc.detail, dict) and exc.detail.get("error") == "gpu_busy":+ return JSONResponse(status_code = 409, content = exc.detail, headers = exc.headers)+ raise++ return wrapped+++def ambient_hf_token():+ return False if managed_account() else os.environ.get("HF_TOKEN")+++def account_hf_token(token):+ """False is the Hub's anonymous sentinel; None would lend the installation token."""+ if managed_account() and (not token or (isinstance(token, str) and not token.strip())):+ return False+ return token+++def require_installation_owner() -> None:+ if managed_account():+ raise HTTPException(status_code = 403, detail = "Only the installation owner can do this")+++_PUBLIC_TTL = 300.0+_PRIVATE_TTL = 30.0+_public_repos: dict[tuple[str, str], tuple[float, bool]] = {}+_public_lock = threading.Lock()+_public_flights: dict[tuple[str, str], Future] = {}+_PROBE_FANOUT = 8+++_UNKNOWN_TTL = 30.0+_PROOF_TTL = 7 * 24 * 3600.0+_DEFINITIVE_HUB_STATUSES = (401, 403, 404)+++def _public_verdicts_path() -> Path:+ from utils.paths.storage_roots import cache_root+ return cache_root() / "public_repos.json"+++def _load_public_verdicts() -> dict[str, float]:+ try:+ data = json.loads(_public_verdicts_path().read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return {}+ if not isinstance(data, dict):+ return {}+ oldest = time.time() - _PROOF_TTL+ return {+ name: float(stamp)+ for name, stamp in data.items()+ if isinstance(name, str) and isinstance(stamp, (int, float)) and float(stamp) > oldest+ }+++def _remember_public_verdict(name: str, public: bool) -> None:+ verdicts = _load_public_verdicts()+ if public:+ verdicts[name] = time.time()+ elif name in verdicts:+ del verdicts[name]+ else:+ return+ path = _public_verdicts_path()+ try:+ path.parent.mkdir(parents = True, exist_ok = True)+ staging = path.with_name(path.name + ".tmp")+ staging.write_text(json.dumps(verdicts, sort_keys = True), encoding = "utf-8")+ os.replace(staging, path)+ except OSError:+ pass+++def _hub_public_answer(repo_id: str, repo_type: str) -> bool | None:+ """True when the Hub says public, False for private/gated/missing, None when unaskable."""+ try:+ info = HfApi().repo_info(repo_id, repo_type = repo_type, token = False, timeout = 5.0)+ except Exception as exc: # noqa: BLE001 - classified below, never trusted as public+ status = getattr(getattr(exc, "response", None), "status_code", None)+ if status in _DEFINITIVE_HUB_STATUSES:+ return False+ return None+ return getattr(info, "private", None) is False and not getattr(info, "gated", False)+++def _public_verdict(repo_id: str, repo_type: str) -> bool | None:+ key = (repo_type, repo_id.lower())+ with _public_lock:+ cached = _public_repos.get(key)+ return cached[1] if cached is not None and cached[0] > time.monotonic() else None+++def repo_is_public(repo_id: str, repo_type: str = "model") -> bool:+ """Only an anonymous Hub answer proves a shared-cache repo public."""+ key = (repo_type, repo_id.lower())+ name = f"{repo_type}:{repo_id.lower()}"+ with _public_lock:+ cached = _public_repos.get(key)+ if cached is not None and cached[0] > time.monotonic():+ return cached[1]+ flight = _public_flights.get(key)+ leading = flight is None+ if leading:+ flight = _public_flights[key] = Future()+ if not leading:+ return flight.result()+ try:+ answer = _hub_public_answer(repo_id, repo_type)+ with _public_lock:+ if answer is None:+ public = name in _load_public_verdicts()+ ttl = _UNKNOWN_TTL+ else:+ public = answer+ _remember_public_verdict(name, public)+ ttl = _PUBLIC_TTL if public else _PRIVATE_TTL+ if len(_public_repos) >= 4096:+ _public_repos.clear()+ _public_repos[key] = (time.monotonic() + ttl, public)+ except BaseException as exc:+ flight.set_exception(exc)+ raise+ else:+ flight.set_result(public)+ return public+ finally:+ with _public_lock:+ _public_flights.pop(key, None)+++def _hub_probe_targets(references, repo_type: str, grants: set[str]) -> set[str]:+ """Distinct repo ids ``model_visible`` would ask the Hub about, cheapest checks first."""+ candidates = {}+ for reference in references:+ if not isinstance(reference, str) or not reference:+ continue+ reference = reference.strip()+ if reference.startswith(("./", "../", "~")):+ continue+ cached = _cached_repo(Path(reference))+ if cached is not None and cached[1] == repo_type:+ repo_id = cached[0]+ if _grant_key(repo_id, repo_type) not in grants:+ candidates.setdefault(repo_id, repo_id)+ continue+ parts = reference.split(":", 1)[0].split("/")+ if len(parts) < 2 or not all(parts[:2]):+ continue+ repo_id = "/".join(parts[:2])+ if _grant_key(repo_id, repo_type) not in grants:+ candidates.setdefault(repo_id, reference)+ if not candidates:+ return set()+ now = time.monotonic()+ with _public_lock:+ unknown = {+ repo_id: reference+ for repo_id, reference in candidates.items()+ if (entry := _public_repos.get((repo_type, repo_id.lower()))) is None or entry[0] <= now+ }+ # A local path that happens to spell a repo id resolves against the cache, not the Hub.+ return {+ repo_id+ for repo_id, reference in unknown.items()+ if not Path(reference).expanduser().exists()+ }+++def _warm_public_repos(repo_ids: set[str], repo_type: str) -> None:+ """Probe unknown repos concurrently; helpers are joined so none outlives the request."""+ if len(repo_ids) < 2:+ return+ pending = deque(repo_ids)++ def drain() -> None:+ while True:+ try:+ repo_id = pending.popleft()+ except IndexError:+ return+ try:+ repo_is_public(repo_id, repo_type)+ except Exception: # noqa: BLE001 - the serial pass below asks again and decides+ pass++ helpers = [+ account_thread(target = drain, daemon = True, name = "studio-repo-probe")+ for _ in range(min(_PROBE_FANOUT, len(pending)) - 1)+ ]+ for helper in helpers:+ helper.start()+ try:+ drain()+ finally:+ for helper in helpers:+ helper.join()+++def _grant_key(repo_id: str, repo_type: str) -> str:+ return f"{repo_type}:{repo_id.strip().lower()}"+++def model_grants() -> set[str]:+ """This account's grants only; absent or malformed records confer no access."""+ path = studio_db_path()+ if not path.is_file():+ return set()+ try:+ with closing(sqlite3.connect(str(path))) as conn:+ row = conn.execute(+ "SELECT value_json FROM app_settings WHERE key = 'model_grants'"+ ).fetchone()+ grants = json.loads(row[0]) if row else []+ return (+ {key for key in grants if isinstance(key, str)} if isinstance(grants, list) else set()+ )+ except (sqlite3.Error, ValueError, TypeError):+ return set()+++def record_model_grant(repo_id: str, repo_type: str = "model") -> None:+ """Record a grant in the initiating account's studio.db; transactional for concurrent writes."""+ if not managed_account() or not repo_id:+ return+ from core.training.account_jobs import account_is_retired++ if account_is_retired():+ return+ # Held across the write so a late completion cannot recreate a retired account's workspace.+ with storage_roots.root_retirement_lock:+ path = studio_db_path()+ try:+ storage_roots.ensure_account_dir(path.parent)+ except storage_roots.RetiredAccountError:+ return+ _write_grant(path, _grant_key(repo_id, repo_type))+++def _write_grant(path: Path, key: str) -> None:+ with closing(sqlite3.connect(str(path), timeout = 5.0)) as conn, conn:+ conn.execute(+ "CREATE TABLE IF NOT EXISTS app_settings (key TEXT NOT NULL PRIMARY KEY, value_json TEXT NOT NULL, updated_at TEXT NOT NULL)"+ )+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute(+ "SELECT value_json FROM app_settings WHERE key = 'model_grants'"+ ).fetchone()+ try:+ prior = json.loads(row[0]) if row else []+ except (ValueError, TypeError):+ prior = []+ grants = (+ {key for key in prior if isinstance(key, str)} if isinstance(prior, list) else set()+ )+ grants.add(key)+ conn.execute(+ "INSERT INTO app_settings (key, value_json, updated_at) VALUES ('model_grants', ?, ?) "+ "ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at",+ (json.dumps(sorted(grants)), datetime.now(timezone.utc).isoformat()),+ )+++def repo_visible(+ repo_id: str,+ repo_type: str = "model",+ *,+ grants: set[str] | None = None,+) -> bool:+ if not managed_account():+ return True+ if not repo_id:+ return False+ granted = model_grants() if grants is None else grants+ return _grant_key(repo_id, repo_type) in granted or repo_is_public(repo_id, repo_type)+++def _cached_repo(path: Path) -> tuple[str, str] | None:+ for part in reversed(path.parts):+ for prefix, repo_type in (("models--", "model"), ("datasets--", "dataset")):+ if part.startswith(prefix):+ pieces = part[len(prefix) :].split("--")+ if len(pieces) in (1, 2) and all(pieces):+ return "/".join(pieces), repo_type+ return None+++def model_visible(+ reference: str,+ *,+ grants: set[str] | None = None,+ repo_type: str = "model",+) -> bool:+ """Grants cover repo ids and cache snapshot/file spellings; other local paths stay private."""+ if not managed_account():+ return True+ if not isinstance(reference, str) or not reference:+ return False+ reference = reference.strip()+ path = Path(reference).expanduser()+ if path.is_absolute() or reference.startswith(("./", "../", "~")) or path.exists():+ try:+ resolved = path.resolve()+ own_roots = (workspace_root(), project_workspaces_root())+ if any(resolved.is_relative_to(root.resolve()) for root in own_roots):+ return True+ from utils.hf_cache_settings import known_hf_hub_caches++ if not any(resolved.is_relative_to(root.resolve()) for root in known_hf_hub_caches()):+ return False+ cached = _cached_repo(path)+ if cached is not None:+ # Snapshots point at their own repo's blobs; cross-repo links are refused.+ actual = _cached_repo(resolved)+ return actual == cached and repo_visible(cached[0], cached[1], grants = grants)+ except (OSError, RuntimeError, ValueError):+ return False+ return False+ repo_id = reference.split(":", 1)[0]+ parts = repo_id.split("/")+ if not all(parts[:2]):+ return False+ repo_id = "/".join(parts[:2])+ return repo_visible(repo_id, repo_type, grants = grants)+++def require_model_access(reference: str, repo_type: str = "model") -> None:+ if not model_visible(reference, repo_type = repo_type):+ raise HTTPException(status_code = 404, detail = "Model not found")+++def _row_reference(row):+ get = row.get if isinstance(row, dict) else lambda key, default = None: getattr(row, key, default)+ return get("path") or get("local_path") or get("repo_id") or get("model_id") or get("id")+++def filter_model_rows(rows, *, repo_type: str = "model"):+ """Filter after shared scans/caches; never store a caller's filtered catalog globally."""+ if not managed_account():+ return rows+ grants = model_grants()+ rows = list(rows)+ references = [_row_reference(row) for row in rows]+ _warm_public_repos(_hub_probe_targets(references, repo_type, grants), repo_type)+ return [+ row+ for row, reference in zip(rows, references)+ if model_visible(reference, grants = grants, repo_type = repo_type)+ ]+++def private_directory(path: str, folder: str) -> str:+ """Rebase import-time owner defaults; refuse account-external scans."""+ if not managed_account():+ return path+ from utils.paths.storage_roots import studio_root++ legacy = studio_root() / folder+ target = workspace_root() / folder if Path(path).resolve() == legacy.resolve() else Path(path)+ # The project workspace counts as the account's own, matching within_account().+ own_roots = (workspace_root(), project_workspaces_root())+ resolved = target.resolve()+ if not any(resolved.is_relative_to(root.resolve()) for root in own_roots):+ raise HTTPException(status_code = 404, detail = "Directory not found")+ return str(target)+++def authorize_download(repo_id: str, repo_type: str, hf_token) -> None:+ """A cache hit is not proof the requester may read private Hub content."""+ if not managed_account():+ return+ try:+ api = HfApi()+ token = account_hf_token(hf_token)+ info = api.repo_info(repo_id, repo_type = repo_type, token = token, timeout = 5.0)+ if getattr(info, "gated", False):+ # Gated repo metadata is public even when the caller cannot read its files.+ api.auth_check(repo_id, repo_type = repo_type, token = token)+ except Exception as exc: # noqa: BLE001 - a cached file is never a grant+ raise HTTPException(status_code = 404, detail = "Repository not found") from exc+++def require_media_references(request) -> None:+ require_media_adapters(request)+ for name in ("gguf_filename", "transformer_prequant_path"):+ reference = getattr(request, name, None)+ if not isinstance(reference, str) or not reference:+ continue+ path = Path(reference).expanduser()+ if name == "transformer_prequant_path":+ require_model_access(str(path.resolve()))+ elif path.is_absolute():+ require_model_access(reference)+ elif ".." in path.parts:+ raise HTTPException(status_code = 404, detail = "Model not found")+ elif Path(request.model_path).is_absolute():+ require_model_access(str(Path(request.model_path) / path))+++def resident_components(status: dict, modality: str | None = None) -> list[str]:+ repo_id = status.get("repo_id")+ references = [repo_id, status.get("base_repo")]+ primary, components = _resident_components.get(modality, ("", frozenset()))+ # Baked adapters are absent from status(), so the load's authorized list stands in.+ if primary and repo_id and primary == repo_id:+ references.extend(sorted(components))+ return [ref for ref in references if isinstance(ref, str) and ref]+++def require_media_generation_access(status: dict, modality: str | None = None) -> None:+ """Recheck the actual resident before a cache-only generation reuses it."""+ if managed_account() and status.get("loaded"):+ for reference in resident_components(status, modality):+ require_model_access(reference)+++def foreign_work_active() -> bool:+ if not policy.installation_has_managed_accounts():+ return False+ from state import active_generations+ return bool(active_generations.foreign_count(current_account_id()))+++def require_download_progress_access(+ registry,+ repo_id: str,+ repo_type: str = "model",+) -> None:+ if not managed_account():+ return+ from hub.services import download_lifecycle+ if not any(+ download_lifecycle.download_belongs_to_account(registry, ref.key)+ for ref in registry.active_job_refs(repo_id)+ ):+ require_model_access(repo_id, repo_type)+++def require_media_adapters(request) -> None:+ if not managed_account():+ return+ for reference in media_adapter_references(request):+ require_model_access(reference)+++def media_adapter_references(request) -> list[str]:+ """Resolve catalog aliases to the repo or path each adapter loads."""+ references: list[str] = []+ loras = getattr(request, "loras", None)+ controlnet = getattr(request, "controlnet", None)+ groups = []+ if loras:+ from core.inference import diffusion_lora+ groups.append((loras, diffusion_lora.list_loras()))+ if controlnet:+ from core.inference import diffusion_controlnet+ groups.append(([controlnet], diffusion_controlnet.list_controlnets()))+ for selections, entries in groups:+ by_id = {entry.id: entry for entry in entries}+ for selection in selections:+ entry = by_id.get(selection.id)+ references.append(+ (entry.local_path or entry.repo_id) if entry is not None else selection.id+ )+ return referencesdiff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex 69dd918788f..e9ea9a8e2e2 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -5,6 +5,7 @@from __future__ import annotations+import jsonimport asyncioimport threading@@ -81,6 +82,12 @@ _last_confirmed_inventory: dict[str, list[dict]] = {}_LOCAL_SIZE_IDENTITY_PREFIX = "size:"+def _account_access():+ """Imported on use: the CLI reads this inventory without FastAPI, which account_access needs."""+ from hub.services.models import account_access+ return account_access++def get_repo_snapshot_metadata_cached(repo_id: str, hf_token: Optional[str] = None) -> tuple[int, frozenset[str]]:@@ -667,7 +674,12 @@ async def list_cached_gguf_response(hf_token: Optional[str] = None):"""List GGUF repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""try:scan = await _shared_cached_inventory_scan("gguf", _scan_cached_gguf)- return {"cached": scan.rows, "scan_confirmed": scan.confirmed}+ rows = (+ await asyncio.to_thread(_account_access().filter_model_rows, scan.rows)+ if _account_access().managed_account()+ else scan.rows+ )+ return {"cached": rows, "scan_confirmed": scan.confirmed}except Exception as e:from fastapi import HTTPExceptionlogger.error(@@ -1142,7 +1154,12 @@ async def list_cached_models_response(hf_token: Optional[str] = None):"""List non-GGUF model repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""try:scan = await _shared_cached_inventory_scan("models", _scan_cached_models)- return {"cached": scan.rows, "scan_confirmed": scan.confirmed}+ rows = (+ await asyncio.to_thread(_account_access().filter_model_rows, scan.rows)+ if _account_access().managed_account()+ else scan.rows+ )+ return {"cached": rows, "scan_confirmed": scan.confirmed}except Exception as e:from fastapi import HTTPExceptionlogger.error(diff --git a/studio/backend/hub/services/models/companion_cleanup.py b/studio/backend/hub/services/models/companion_cleanup.pyindex 5b80a2a1fbb..d6144320670 100644--- a/studio/backend/hub/services/models/companion_cleanup.py+++ b/studio/backend/hub/services/models/companion_cleanup.py@@ -11,6 +11,7 @@ Sizes are real on-disk blob bytes from the HF cache scan, deduped per blob, notfrom __future__ import annotationsimport asyncio+from dataclasses import replacefrom pathlib import Pathfrom typing import Optional@@ -54,6 +55,18 @@ def _repo_blob_bytes(repo_info, *, only = None) -> int:_repo_holds_denoiser = companion_assets.repo_holds_denoiser+def _account_scans() -> list:+ """A managed caller previews only the repos its grants cover; other accounts' downloads stay unseen."""+ scans = cache_inventory.all_hf_cache_scans()+ access = cache_inventory._account_access()+ if not access.managed_account():+ return scans+ return [+ replace(scan, repos = frozenset(access.filter_model_rows(list(scan.repos or ()))))+ for scan in scans+ ]++def _repos_by_id(cache_scans) -> dict[str, list]:out: dict[str, list] = {}for scan in cache_scans or ():@@ -127,7 +140,7 @@ def _variant_is_a_required_companion_asset(repo_id: str, variant: str) -> bool:def _delete_impact_blocking(repo_id: str, variant: Optional[str]) -> dict:- scans = cache_inventory.all_hf_cache_scans()+ scans = _account_scans()by_id = _repos_by_id(scans)key = repo_id.strip().lower()repos = by_id.get(key, [])@@ -203,7 +216,7 @@ async def delete_impact_response(repo_id: str, variant: Optional[str] = None) ->def _orphan_companions_blocking() -> dict:- scans = cache_inventory.all_hf_cache_scans()+ scans = _account_scans()by_id = _repos_by_id(scans)required = companion_assets.required_companion_bases(scans)known = companion_assets.known_companion_base_ids()diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex 4c1593b9119..0b66dcd99a0 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -5,6 +5,8 @@from __future__ import annotations+from hub.services.models import account_access+import asyncioimport errnofrom pathlib import Path@@ -726,7 +728,16 @@ async def delete_cached_model_response(cache_path: Optional[str] = None,only_if_orphan: bool = False,):- """Delete a cached model repo (or a specific GGUF variant) from the HF cache. When *variant* is provided, only the GGUF files matching that quant label are removed (e.g. ``UD-Q4_K_XL``); otherwise the entire repo is deleted. Refuses if the model is currently loaded for inference. *only_if_orphan* is Free up space's precondition: 409 rather than delete when the repo has become an installed checkpoint since the list the caller is acting on was built."""+ """Delete a cached model repo (or a specific GGUF variant) from the HF cache.++ When *variant* is provided, only the GGUF files matching that quant label+ are removed (e.g. ``UD-Q4_K_XL``). Otherwise the entire repo is deleted.+ Refuses if the model is currently loaded for inference.++ *only_if_orphan* is Free up space's precondition: 409 rather than delete when the repo has+ become an installed checkpoint since the list the caller is acting on was built.+ """+ account_access.require_installation_owner()if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400, detail = "Invalid repo_id format")variant = (variant or "").strip() or Nonediff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex e028f4be3cd..3ae7767daf2 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -31,7 +31,7 @@ from hub.utils.paths import ()from hub.services import snapshot_progressfrom hub.services import download_lifecycle-from hub.services.models import cache_inventory, gguf_variants+from hub.services.models import account_access, cache_inventory, gguf_variantslogger = get_logger(__name__)@@ -170,13 +170,25 @@ async def download_model_response(*,allow_ambient_token: bool = True,):- """Start a background download for a HuggingFace model. ``allow_ambient_token=False`` keeps the worker anonymous when the caller sent no token, for repos named over the API rather than chosen here."""+ """Start a background download for a HuggingFace model.++ ``allow_ambient_token=False`` keeps the worker anonymous when the caller sent+ no token, for repos named over the API rather than chosen here.+ """+ from core.training.account_jobs import account_is_retired++ if account_is_retired():+ raise HTTPException(status_code = 403, detail = "Account is retired")+ hf_token = account_access.account_hf_token(hf_token)+ allow_ambient_token = allow_ambient_token and not account_access.managed_account()repo_id = body.repo_id.strip()if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400,detail = f"Invalid repo_id: {repo_id!r}",)+ if account_access.managed_account():+ await asyncio.to_thread(account_access.authorize_download, repo_id, "model", hf_token)# Canonicalize so two different-cased paste-ins share one job + cache dir.repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")@@ -279,6 +291,7 @@ async def download_model_response()generation = _registry.current_generation(key)if not claimed:+ download_lifecycle.require_download_account(_registry, key)if claim_state == "admission_blocked":raise _load_in_flight_error(repo_id)if claim_state == "scope_file_mismatch":@@ -303,6 +316,10 @@ async def download_model_response(# And its cancel marker: a run that fell back from Xet to HTTP still cancels into a restart-only partial."cancel_transport": _registry.job_cancel_transport(key),}+ # Record ownership with the claim, not at launch, or the last downloader keeps the key.+ download_lifecycle.record_download_account(_registry, key)+ # Only then read the tombstone: an account retired during the awaits must not spawn.+ download_lifecycle.require_live_account(_registry, key)download_manifest.clear_cancel_marker("model",repo_id,@@ -348,6 +365,28 @@ async def download_model_response(}+def retire_account_downloads() -> None:+ """Cancel and reap this account's model downloads before its roots are renamed aside."""+ stragglers = []+ for job in _registry.active_job_refs():+ if not download_lifecycle.download_belongs_to_account(_registry, job.key):+ continue+ download_lifecycle.cancel_worker(+ _registry, job.key, generation = job.generation, label = "model", logger = logger+ )+ proc = _registry.get_process(job.key)+ if proc is None:+ continue+ try:+ proc.wait(timeout = 10)+ except Exception:+ stragglers.append(job.key)+ if stragglers:+ raise RuntimeError(+ f"Retired account model downloads have not stopped: {sorted(stragglers)}"+ )++async def cancel_download_model_response(body: CancelDownloadRequest):"""Cancel an in-flight model download (SIGKILL; HF cache resumes on next download)."""repo_id = body.repo_id.strip()@@ -460,7 +499,17 @@ async def get_model_transport_status_response(gguf_variant: str = "",hf_token: Optional[str] = None,) -> dict:- """Last transport used for this repo, whether any partial blobs exist, and whether that partial supports byte-level resume. ``resumable`` is True only for an HTTP partial: XET partials report ``has_partial`` but never resume, because ``hf_xet`` rewrites the destination from scratch every call (network resume happens transparently via its chunk cache)."""+ """Return last transport used for this repo + whether any partial blobs+ exist + whether that partial supports byte-level resume.++ ``resumable`` is True only when an HTTP partial exists. XET partials+ are reported via ``has_partial`` but always have ``resumable=False``+ because ``hf_xet`` rewrites the destination from scratch on every+ call (network resume happens transparently via its chunk cache).+ """+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_download_progress_access, _registry, repo_id)+ hf_token = account_access.account_hf_token(hf_token)repo_id = repo_id.strip()if not _is_valid_repo_id(repo_id):return {"has_partial": False, "last_transport": None, "resumable": False}@@ -553,6 +602,9 @@ async def get_gguf_download_progress_response(hf_token: Optional[str] = None,) -> dict:"""Return download progress for a specific GGUF variant."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_download_progress_access, _registry, repo_id)+ hf_token = account_access.account_hf_token(hf_token)expected_total = max(expected_bytes, 0)progress_variant = variant.strip() or Noneif progress_variant is not None and not _is_valid_gguf_variant(progress_variant):@@ -649,7 +701,18 @@ async def get_download_progress_response(expected_bytes: int = 0,hf_token: Optional[str] = None,) -> dict:- """Download progress for any HuggingFace model repo, from completed blobs and in-progress (.incomplete) files in the local HF cache. Uses the caller-supplied expected total when available, else queries and caches HF metadata. ``cache_path`` is the realpath of the snapshot dir (or the cache repo root before one exists) so the UI can show where the weights live."""+ """Return download progress for any HuggingFace model repo.++ Checks the local HF cache for completed blobs and in-progress+ (.incomplete) downloads. Uses the caller-supplied expected total+ when available; otherwise queries HF metadata and caches it.+ Also returns ``cache_path``: the realpath of the snapshot directory+ (or the cache repo root if no snapshot exists yet) so the UI can+ show users where the weights actually live on disk.+ """+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_download_progress_access, _registry, repo_id)+ hf_token = account_access.account_hf_token(hf_token)return await snapshot_progress.snapshot_progress_response(repo_type = "model",repo_id = repo_id,diff --git a/studio/backend/hub/services/models/folder_browser.py b/studio/backend/hub/services/models/folder_browser.pyindex 45fe758a73a..4b38152dcb4 100644--- a/studio/backend/hub/services/models/folder_browser.py+++ b/studio/backend/hub/services/models/folder_browser.py@@ -5,6 +5,9 @@from __future__ import annotations+from hub.services.models import account_access+from utils.paths.storage_roots import workspace_root+import osfrom pathlib import Pathfrom typing import Optional@@ -39,6 +42,8 @@ def _build_browse_allowlist(*media_roots* / *drive_roots* let the caller pass already-probedremovable-media and Windows drive roots so they aren't scanned again (adisconnected mapped drive can make each probe slow); probed here when ``None``."""+ if account_access.managed_account():+ return [workspace_root().resolve()]from hub.storage.scan_folders import list_scan_folderscandidates: list[Path] = []diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex b8a1ee5a463..b8a26168255 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -5,6 +5,8 @@from __future__ import annotations+from hub.services.models import account_access+import asyncioimport hashlibimport re@@ -1038,6 +1040,21 @@ async def get_gguf_variants_answer(with file sizes, whether the model supports vision, and the recommendeddefault variant."""+ if local_path:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, local_path)+ hf_token = account_access.account_hf_token(hf_token)+ if account_access.managed_account():+ try:+ await asyncio.to_thread(account_access.require_model_access, repo_id)+ except HTTPException:+ # No grant exists before the first download, so for a private repo the caller's own+ # token proves Hub access instead. A cache-only request without a token needs the grant.+ if not isinstance(hf_token, str) or not hf_token.strip():+ raise+ if is_local_path(repo_id) or not _is_valid_repo_id(repo_id):+ raise+ await asyncio.to_thread(account_access.authorize_download, repo_id, "model", hf_token)# Returned with the listing because the HF cache answers before local_path, so a caller cannot infer# the copy from the request alone.answered_from: list[Optional[str]] = [None]diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex c0f835fa6e5..fb9919ce6fb 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -5,6 +5,7 @@from __future__ import annotations+import asyncioimport osfrom pathlib import Path@@ -89,6 +90,12 @@ _gguf_variant_state_summary = model_common._gguf_variant_state_summary_is_diffusers_pipeline_dir = model_common._is_diffusers_pipeline_dir+def _account_access():+ """Imported on use: the CLI reads this inventory without FastAPI, which account_access needs."""+ from hub.services.models import account_access+ return account_access++def _http_error(status_code: int, detail: str):from fastapi import HTTPExceptionreturn HTTPException(status_code = status_code, detail = detail)@@ -966,6 +973,13 @@ async def _scan_local_models_response()+async def _account_local_response(response):+ if not _account_access().managed_account():+ return response+ models = await asyncio.to_thread(_account_access().filter_model_rows, response.models)+ return response.model_copy(update = {"models": models})++async def list_local_models_response(models_dir: str = "./models") -> LocalModelListResponse:"""Coalesce overlapping local inventory requests for the same models root."""@@ -1018,19 +1032,20 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModelepoch,)try:- return await hf_cache_scan.shared_scan(+ response = await hf_cache_scan.shared_scan(_local_inventory_flights,key,lambda expected_epoch = epoch, folders = custom_folders, roots = sources: (scan_and_classify(expected_epoch, folders, roots)),)+ return await _account_local_response(response)except _LocalCacheChanged as changed:superseded = changed.responsecontinue# Invalidations are outpacing the walk, so answer with the freshest scan instead of rescanning forever.logger.warning("Local inventory kept racing cache invalidations; serving the last scan")- return await asyncio.to_thread(classify, superseded)+ return await _account_local_response(await asyncio.to_thread(classify, superseded))def get_models_folder_response() -> dict:@@ -1060,6 +1075,7 @@ def get_scan_folders_response() -> dict:def add_scan_folder_response(path: str) -> dict:+ path = _account_access().private_directory(path, "")try:folder, inserted = add_scan_folder_with_status(_coerce_scan_folder_path(path))except ValueError as e:diff --git a/studio/backend/hub/storage/scan_folders.py b/studio/backend/hub/storage/scan_folders.pyindex 2fa3a57b994..17fbcc9b67b 100644--- a/studio/backend/hub/storage/scan_folders.py+++ b/studio/backend/hub/storage/scan_folders.py@@ -11,8 +11,8 @@ from __future__ import annotationsimport osimport platformimport sqlite3-import threadingfrom datetime import datetime, timezone+from pathlib import Pathfrom storage.studio_db import get_connectionfrom hub.utils.paths import normalize_path@@ -23,10 +23,6 @@ from utils.paths.sensitive import ()-_schema_lock = threading.Lock()-_schema_ready = False--def _denied_path_prefixes() -> list[str]:system = platform.system()if system == "Linux":@@ -83,31 +79,9 @@ def contains_sensitive_path_component(path: str) -> bool:return _contains_sensitive_path_component(path)-def _ensure_schema(conn: sqlite3.Connection) -> None:- global _schema_ready- if _schema_ready:- return- with _schema_lock:- if _schema_ready:- return- collation = "COLLATE NOCASE" if platform.system() == "Windows" else ""- conn.execute(- f"""- CREATE TABLE IF NOT EXISTS scan_folders (- id INTEGER PRIMARY KEY AUTOINCREMENT,- path TEXT NOT NULL UNIQUE {collation},- created_at TEXT NOT NULL- )- """- )- conn.commit()- _schema_ready = True--def list_scan_folders() -> list[dict]:conn = get_connection()try:- _ensure_schema(conn)rows = conn.execute("SELECT id, path, created_at FROM scan_folders ORDER BY created_at").fetchall()@@ -132,6 +106,10 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:raise ValueError("The filesystem root cannot be registered")if _contains_sensitive_path_component(normalized):raise ValueError("Credential or configuration directories are not allowed")+ from utils.paths.storage_roots import within_account++ if not within_account(Path(normalized)):+ raise ValueError("Path is outside this account's workspace")is_win = platform.system() == "Windows"check = os.path.normcase(normalized) if is_win else normalized@@ -147,7 +125,6 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:conn = get_connection()try:- _ensure_schema(conn)now = datetime.now(timezone.utc).isoformat()if is_win:existing = conn.execute(@@ -196,7 +173,6 @@ def remove_scan_folder(id: int) -> bool:return Falseconn = get_connection()try:- _ensure_schema(conn)cursor = conn.execute("DELETE FROM scan_folders WHERE id = ?", (id,))conn.commit()return cursor.rowcount > 0diff --git a/studio/backend/hub/tests/conftest.py b/studio/backend/hub/tests/conftest.pyindex a19f4c74051..9ca16fc35bf 100644--- a/studio/backend/hub/tests/conftest.py+++ b/studio/backend/hub/tests/conftest.py@@ -147,7 +147,7 @@ def _isolate_studio_home(_hub_studio_home_root, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))for name, module in tuple(sys.modules.items()):if name.startswith(("storage.", "hub.storage.")) and hasattr(module, "_schema_ready"):- monkeypatch.setattr(module, "_schema_ready", False)+ monkeypatch.setattr(module, "_schema_ready", set())@pytest.fixture(autouse = True)diff --git a/studio/backend/hub/tests/test_download_lifecycle.py b/studio/backend/hub/tests/test_download_lifecycle.pyindex 0f1121d1634..702b401cac4 100644--- a/studio/backend/hub/tests/test_download_lifecycle.py+++ b/studio/backend/hub/tests/test_download_lifecycle.py@@ -56,11 +56,18 @@ class _Proc:class _ImmediateThread:- def __init__(self, *, target, **_kwargs):- self.target = target+ def __init__(+ self,+ *,+ target,+ args = (),+ kwargs = None,+ **_kwargs,+ ):+ self.target, self.args, self.kwargs = target, args, kwargs or {}def start(self):- self.target()+ self.target(*self.args, **self.kwargs)def test_resolve_effective_use_xet(monkeypatch):diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 5a0475b297a..62bfcd36b24 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -5088,11 +5088,18 @@ def test_model_download_watcher_invalidates_hf_cache_scan(monkeypatch):return SimpleNamespace(state = "complete", error = None)class _ImmediateThread:- def __init__(self, *, target, **_kwargs):- self._target = target+ def __init__(+ self,+ *,+ target,+ args = (),+ kwargs = None,+ **_kwargs,+ ):+ self._target, self._args, self._kwargs = target, args, kwargs or {}def start(self):- self._target()+ self._target(*self._args, **self._kwargs)_shared_setup_12(_Registry, monkeypatch)_shared_setup_18(monkeypatch)diff --git a/studio/backend/hub/utils/paths.py b/studio/backend/hub/utils/paths.pyindex 018787afb9c..96d319e5707 100644--- a/studio/backend/hub/utils/paths.py+++ b/studio/backend/hub/utils/paths.py@@ -7,8 +7,6 @@ from __future__ import annotationsimport osimport re-import sys-import tempfileimport threadingfrom collections import OrderedDictfrom pathlib import Path@@ -16,12 +14,23 @@ from typing import Optionalfrom loggers import get_loggerfrom utils.paths import path_utils as _path_utils-from utils.paths.path_utils import wsl_automount_root# One policy, defined in utils.paths.storage_roots: the copy that used to live here drifted, and a# BOM'd settings.json was honoured by one side and dropped by the other (#9748).from utils.paths.storage_roots import (hermes_model_dirs,+ studio_root,+ cache_root,+ assets_root,+ datasets_root,+ dataset_uploads_root,+ recipe_datasets_root,+ outputs_root,+ exports_root,+ tmp_root,+ ensure_dir,+ legacy_hf_cache_dir,+ hf_default_cache_dir,lmstudio_model_dirs,ollama_model_dirs,well_known_model_dirs,@@ -30,91 +39,29 @@ from utils.paths.storage_roots import (logger = get_logger(__name__)# Re-export shim: marks them used so the import-hoist safety net does not flag them.-_REEXPORTED = (hermes_model_dirs, lmstudio_model_dirs, ollama_model_dirs, well_known_model_dirs)---def _infer_studio_home_from_venv() -> Optional[Path]:- try:- prefix = Path(sys.prefix).resolve()- except (OSError, ValueError):- return None- if prefix.name != "unsloth_studio":- return None- candidate = prefix.parent- shim_name = "unsloth.exe" if os.name == "nt" else "unsloth"- try:- if (candidate / "share" / "studio.conf").is_file() or (- candidate / "bin" / shim_name- ).is_file():- return candidate- except OSError:- return None- return None---def studio_root() -> Path:- override = (os.environ.get("UNSLOTH_STUDIO_HOME") or "").strip()- if not override:- override = (os.environ.get("STUDIO_HOME") or "").strip()- if override:- try:- return Path(override).expanduser().resolve()- except (OSError, ValueError):- return Path(override).expanduser()- inferred = _infer_studio_home_from_venv()- if inferred is not None:- return inferred- return Path.home() / ".unsloth" / "studio"---def cache_root() -> Path:- return studio_root() / "cache"---def assets_root() -> Path:- return studio_root() / "assets"---def datasets_root() -> Path:- return assets_root() / "datasets"---def dataset_uploads_root() -> Path:- return datasets_root() / "uploads"---def recipe_datasets_root() -> Path:- return datasets_root() / "recipes"---def outputs_root() -> Path:- return studio_root() / "outputs"---def exports_root() -> Path:- return studio_root() / "exports"---def tmp_root() -> Path:- return Path(tempfile.gettempdir()) / "unsloth-studio"---def ensure_dir(path: Path) -> Path:- path.mkdir(parents = True, exist_ok = True)- return path---def legacy_hf_cache_dir() -> Path:- return cache_root() / "huggingface" / "hub"---def hf_default_cache_dir() -> Path:- return Path.home() / ".cache" / "huggingface" / "hub"+_REEXPORTED = (+ hermes_model_dirs,+ lmstudio_model_dirs,+ ollama_model_dirs,+ well_known_model_dirs,+ studio_root,+ cache_root,+ assets_root,+ datasets_root,+ dataset_uploads_root,+ recipe_datasets_root,+ outputs_root,+ exports_root,+ tmp_root,+ ensure_dir,+ legacy_hf_cache_dir,+ hf_default_cache_dir,+)# normalize_path reads these at call time and tests set them, so they stay attributes of this module._IS_WSL = _path_utils._IS_WSL-_WSL_AUTOMOUNT_ROOT = wsl_automount_root()+_WSL_AUTOMOUNT_ROOT = _path_utils._WSL_AUTOMOUNT_ROOTdef normalize_path(path: str) -> str:diff --git a/studio/backend/loggers/config.py b/studio/backend/loggers/config.pyindex 781fc6824c7..c437b3467f6 100644--- a/studio/backend/loggers/config.py+++ b/studio/backend/loggers/config.py@@ -10,6 +10,7 @@ integration, log-level filtering, and logger caching.import loggingimport osimport sys+import threadingfrom typing import Optionalimport structlog@@ -426,6 +427,31 @@ def quiet_third_party_progress_bars() -> None:_redirect_every_bar_output()+_STDOUT_LOCK = threading.Lock()+++class _CurrentStdoutLogger:+ """A structlog logger that resolves ``sys.stdout`` per record, since ``PrintLogger`` binds the stream at build time and loses records once a tee or capture replaces stdout."""++ def msg(self, message: str) -> None:+ stream = sys.stdout+ if stream is None:+ return+ with _STDOUT_LOCK:+ stream.write(message + "\n")+ stream.flush()++ log = debug = info = warn = warning = msg+ fatal = failure = err = error = critical = exception = msg++ def __repr__(self) -> str:+ return "<CurrentStdoutLogger>"+++def _current_stdout_logger_factory(*args) -> _CurrentStdoutLogger:+ return _CurrentStdoutLogger()++class LogConfig:"""Structured logging configuration for the application."""@@ -485,7 +511,7 @@ class LogConfig:),],wrapper_class = structlog.make_filtering_bound_logger(log_level),- logger_factory = structlog.PrintLoggerFactory(file = sys.stdout),+ logger_factory = _current_stdout_logger_factory,cache_logger_on_first_use = True,)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 5bd36a2e823..30dad4fe3d4 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -327,7 +327,7 @@ from hub.utils.download_registry import (from routes.settings import router as settings_routerfrom routes.prompts import router as prompts_routerfrom routes.profile_stats import router as profile_stats_router-from auth import storage+from auth import policy as auth_policy, storagefrom auth.authentication import get_current_subjectfrom utils.hardware import (start_background_detection,@@ -650,23 +650,39 @@ async def lifespan(app: FastAPI):except Exception as exc:_lifespan_log.warning("studio.db WAL keeper failed at startup: %s", exc)- # Reap workers/runs orphaned by a previous crash before new work starts.- try:- from storage.studio_db import cleanup_orphaned_runs- cleanup_orphaned_runs()- except Exception as exc:- _lifespan_log.warning("cleanup_orphaned_runs failed at startup: %s", exc)+ from utils.account_context import OWNER as _owner_account, run_as as _run_astry:- from storage.chat_generation_runs_db import reconcile_orphaned_runs- reconciled_chat_runs = reconcile_orphaned_runs()- if reconciled_chat_runs:- _lifespan_log.warning(- "Marked %s interrupted chat generation run(s) failed after restart.",- reconciled_chat_runs,- )+ from core.training.account_jobs import startup_reconciliation_accounts+ _reconcile_accounts = startup_reconciliation_accounts()except Exception as exc:- _lifespan_log.warning("chat generation orphan reconciliation failed: %s", exc)+ _lifespan_log.warning("could not enumerate accounts to reconcile: %s", exc)+ _reconcile_accounts = [_owner_account]++ for _account in _reconcile_accounts:+ try:+ from storage.studio_db import cleanup_orphaned_runs+ _run_as(_account, cleanup_orphaned_runs)+ except Exception as exc:+ _lifespan_log.warning("cleanup_orphaned_runs failed at startup: %s", exc)++ try:+ from storage.chat_generation_runs_db import reconcile_orphaned_runs+ reconciled_chat_runs = _run_as(_account, reconcile_orphaned_runs)+ if reconciled_chat_runs:+ _lifespan_log.warning(+ "Marked %s interrupted chat generation run(s) failed after restart.",+ reconciled_chat_runs,+ )+ except Exception as exc:+ _lifespan_log.warning("chat generation orphan reconciliation failed: %s", exc)++ # Each account has its own rag.db, so its stuck ingestion jobs are only visible from inside it.+ try:+ from storage.rag_db import reconcile_orphaned_ingestion_jobs+ _run_as(_account, reconcile_orphaned_ingestion_jobs)+ except Exception as exc:+ _lifespan_log.warning("reconcile_orphaned_ingestion_jobs failed at startup: %s", exc)try:# The boot pass above only settles runs orphaned by the previous process. A run that wedges while this one@@ -696,12 +712,6 @@ async def lifespan(app: FastAPI):app.state.llama_cpp_freshness = None_start_llama_cpp_probes_if_enabled(app)- try:- from storage.rag_db import reconcile_orphaned_ingestion_jobs- reconcile_orphaned_ingestion_jobs()- except Exception as exc:- _lifespan_log.warning("reconcile_orphaned_ingestion_jobs failed at startup: %s", exc)-# Embeddings stay cold until ingestion or retrieval actually requests vectors._start_helper_precache_if_enabled()@@ -1411,6 +1421,11 @@ from utils.remote_access_settings import RemoteAccessStopResponseMiddleware # napp.add_middleware(RemoteAccessStopResponseMiddleware)app.include_router(auth_router, prefix = "/api/auth", tags = ["auth"])+app.include_router(+ __import__("routes.accounts", fromlist = ["router"]).router,+ prefix = "/api/accounts",+ tags = ["accounts"],+)app.include_router(training_router, prefix = "/api/train", tags = ["training"])app.include_router(models_router, prefix = "/api/models", tags = ["models"])app.include_router(chat_history_router, prefix = "/api/chat", tags = ["chat"])@@ -1681,6 +1696,18 @@ async def liveness_check():return alive+async def _desktop_shell_subject(request: Request) -> Optional[str]:+ """Owner subject for a request carrying the desktop secret, None without one: on a multi-account install desktop-login mints no session, so the shell proves ownership with the secret itself."""+ secret = request.headers.get("x-desktop-secret")+ if secret is None:+ return None+ from starlette.concurrency import run_in_threadpool++ if await run_in_threadpool(storage.validate_desktop_secret, secret) is None:+ raise HTTPException(status_code = 401, detail = "Desktop authentication failed")+ return storage.DEFAULT_ADMIN_USERNAME++@app.get("/api/health")async def health_check(request: Request):"""Liveness plus launcher capability bits; host fingerprint gated on a bearer.@@ -1734,22 +1761,23 @@ async def health_check(request: Request):if os.environ.get(DISABLE_ENV_VAR) == "1" and not mlx_repairing:# Nothing is detecting until a hardware-dependent operation runs; say so instead of making clients poll.base["hardware_detection_deferred"] = True+ subject = await _desktop_shell_subject(request)auth = request.headers.get("authorization", "")bearer = auth.split(" ", 1)[1] if auth.lower().startswith("bearer ") else None- try:- from auth.authentication import credentials_for_token- from auth.authentication import get_current_subject as _gcs-- # resolved rather than built, so a scope covering this route answers it in full- creds = await credentials_for_token(request, bearer)- if creds is None:+ if subject is None:+ try:+ from auth.authentication import credentials_for_token+ from auth.authentication import get_current_subject as _gcs++ creds = await credentials_for_token(request, bearer)+ if creds is None:+ return base+ # Must await: a bare coroutine is truthy and would skip the auth check+ subject = await _gcs(creds)+ except HTTPException:+ return base+ except Exception:return base- # Must await: a bare coroutine is truthy and would skip the auth check- subject = await _gcs(creds)- except HTTPException:- return base- except Exception:- return baseif not subject:return base@@ -1838,7 +1866,10 @@ def studio_download_transport_capabilities(return asdict(get_download_transport_capabilities(probe = probe))[email protected]("/api/shutdown")+ "/api/shutdown",+ dependencies = [Depends(get_current_subject), Depends(auth_policy.require_owner)],+)async def shutdown_server(request: Request, current_subject: str = Depends(get_current_subject)):"""Gracefully shut down the Unsloth Studio server.@@ -1846,6 +1877,18 @@ async def shutdown_server(request: Request, current_subject: str = Depends(get_cwithout the CLI or killing the process manually."""+ return _schedule_shutdown(request)++[email protected]("/api/desktop/shutdown")+async def desktop_shutdown_server(request: Request):+ """The desktop shell's quit path, authenticated by its secret."""+ if await _desktop_shell_subject(request) is None:+ raise HTTPException(status_code = 401, detail = "Desktop authentication failed")+ return _schedule_shutdown(request)+++def _schedule_shutdown(request: Request) -> dict:async def _delayed_shutdown():await asyncio.sleep(0.2) # Let the HTTP response return firsttrigger = getattr(request.app.state, "trigger_shutdown", None)@@ -2163,6 +2206,12 @@ def _inject_bootstrap(html_bytes: bytes, app: FastAPI):if not storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME):return html_bytes, None+ from auth.policy import installation_has_managed_accounts++ # A local browser may belong to any account, including a deactivated one.+ if installation_has_managed_accounts():+ return html_bytes, None+bootstrap_pw = getattr(app.state, "bootstrap_password", None)if not bootstrap_pw:return html_bytes, Nonediff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.pyindex 9f255967eb2..7ac1827cfd3 100644--- a/studio/backend/models/auth.py+++ b/studio/backend/models/auth.py@@ -5,9 +5,9 @@from typing import Optional-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validator-from auth.storage import MIN_PASSWORD_LENGTH+from auth.storage import MIN_PASSWORD_LENGTH, validate_account_usernameclass AuthLoginRequest(BaseModel):@@ -37,6 +37,20 @@ class AuthStatusResponse(BaseModel):"unsloth",description = "Default admin username for first-boot UI prefill.",)+ login_mode: str = Field(+ "single",+ description = (+ "'single' when one account exists, so the form posts default_username without asking; "+ "'multi' when a username has to be entered. Never lists accounts."+ ),+ )+ full_access: bool = Field(+ True,+ description = (+ "Whether the unsandboxed tool modes (Full access, bypass permissions) may be "+ "offered. False whenever another account exists, active or not."+ ),+ )requires_password_change: bool = Field(...,description = "True if the seeded admin must still change the default password",@@ -107,3 +121,35 @@ class ApiKeyListResponse(BaseModel):"""List of API keys for the authenticated user."""api_keys: list[ApiKeyResponse]+++class CreateAccountRequest(BaseModel):+ username: str++ @field_validator("username")+ @classmethod+ def validate_username(cls, value: str) -> str:+ return validate_account_username(value)+++class AccountActiveRequest(BaseModel):+ is_active: bool+++class AccountResponse(BaseModel):+ account_id: str+ username: str+ role: str+ is_active: bool+ created_at: str+ setup_code_pending: bool+++class AccountListResponse(BaseModel):+ accounts: list[AccountResponse]+++class AccountSetupResponse(BaseModel):+ account: AccountResponse+ setup_code: str+ setup_code_expires_at: strdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 5193125c219..586968186b1 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1766,8 +1766,6 @@ class CompactionContentPart(BaseModel):class InputAudio(BaseModel):- # Non-empty: an empty payload is not lifted, so the turn would otherwise proceed as- # text alone and answer "transcribe this" about a recording that was never sent.data: str = Field(..., min_length = 1, description = "Base64-encoded audio, without a data: prefix.")@@ -1777,15 +1775,11 @@ class InputAudio(BaseModel):class InputAudioContentPart(BaseModel):- """Audio content part in a multimodal message, in OpenAI's documented shape."""-type: Literal["input_audio"]input_audio: InputAudioclass UnknownContentPart(BaseModel):- """Catch-all for unmodelled part types, mirroring ``ResponsesUnknownContentPart``."""-type: strmodel_config = {"extra": "allow"}@@ -1806,8 +1800,7 @@ _KNOWN_CONTENT_PART_TAGS = frozenset(def _content_part_discriminator(v):tag = v.get("type") if isinstance(v, dict) else getattr(v, "type", None)- # A list or dict tag is unhashable, so testing membership would raise TypeError out of- # request validation as a 500. Declining to name a member leaves pydantic to report it.+ # An unhashable tag would raise TypeError out of validation as a 500.if not isinstance(tag, str):return Nonereturn tag if tag in _KNOWN_CONTENT_PART_TAGS else "unknown"diff --git a/studio/backend/models/users.py b/studio/backend/models/users.pyindex 738c76c576c..2207ac2da00 100644--- a/studio/backend/models/users.py+++ b/studio/backend/models/users.py@@ -3,6 +3,8 @@"""Pydantic models for authentication tokens."""+from typing import Optional+from pydantic import BaseModel, Field@@ -22,3 +24,11 @@ class Token(BaseModel):must_change_password: bool = Field(..., description = "True when the user must change the seeded default password")+ account_id: Optional[str] = Field(+ None,+ description = (+ "Immutable id of the signed-in account, the same key storage is partitioned by. "+ "Usernames are reusable, so a client that keeps per-account state must compare this "+ "instead. Null only when an older server issued the credential."+ ),+ )diff --git a/studio/backend/picker/routes/templates.py b/studio/backend/picker/routes/templates.pyindex f410fc104e2..e204af7173c 100644--- a/studio/backend/picker/routes/templates.py+++ b/studio/backend/picker/routes/templates.py@@ -10,6 +10,7 @@ from fastapi import APIRouter, Body, Depends, Queryfrom auth.authentication import get_current_subjectfrom hub.dependencies import get_request_hf_token+from hub.services.models import account_accessfrom hub.utils.hf_tokens import HfTokenArgfrom ..schemas import (@@ -38,6 +39,7 @@ async def get_default_chat_template_route(hf_token: HfTokenArg = Depends(get_request_hf_token),current_subject: str = Depends(get_current_subject),) -> ModelTemplateResponse:+ await asyncio.to_thread(account_access.require_model_access, model_name)# A cache miss falls through to the hub, and offline that costs one retry backoff per candidate template file.from core.inference.llama_cpp import _hf_offline_if_unreachable_fordiff --git a/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py b/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.pyindex 2ba60b3ac92..2256c11ace1 100644--- a/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py+++ b/studio/backend/plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py@@ -8,13 +8,14 @@ import refrom pathlib import Pathfrom typing import Any+from utils.paths.lazy import LazyPathfrom utils.paths import ensure_dir, unstructured_seed_cache_rootDEFAULT_CHUNK_SIZE = 1200DEFAULT_CHUNK_OVERLAP = 200MAX_CHUNK_SIZE = 20000_MIN_BREAK_RATIO = 0.6-_CACHE_DIR = unstructured_seed_cache_root()+_CACHE_DIR = LazyPath(unstructured_seed_cache_root)_PANDAS = Nonediff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.pynew file mode 100644index 00000000000..ebd852fa4b1--- /dev/null+++ b/studio/backend/routes/accounts.py@@ -0,0 +1,169 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Owner-managed account lifecycle. Private roots are retired, never erased."""++import sqlite3+from contextlib import contextmanager+from datetime import datetime, timezone+from pathlib import Path++from fastapi import APIRouter, Depends, HTTPException, Response, status++from auth import policy, storage+from auth.authentication import get_current_subject+from models.auth import (+ AccountActiveRequest,+ AccountListResponse,+ AccountResponse,+ AccountSetupResponse,+ CreateAccountRequest,+)+from hub.services.models import account_access+from state import active_generations+from utils.account_context import AccountContext, run_as+from utils.paths import storage_roots+++router = APIRouter(dependencies = [Depends(get_current_subject), Depends(policy.require_owner)])+++@contextmanager+def _account_errors():+ try:+ yield+ except LookupError:+ raise HTTPException(status_code = 404, detail = "Account not found")+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc))+ except sqlite3.IntegrityError:+ raise HTTPException(status_code = 409, detail = "Username is unavailable")+++def retire_account_roots(account: AccountContext):+ """Signal this account's work, then rename each private root aside (children first, as roots+ may nest). Returns a callable that renames them back if a later step fails."""+ if account.is_owner or account.account_id == "owner":+ raise ValueError("The installation owner cannot be retired")+ active_generations.fence(account.account_id)+ active_generations.cancel_all(account.account_id)+ account_access.retire_resident_shares(account.account_id)+ from core.inference.mcp_client import close_mcp_sessions, invalidate_tool_cache+ from core.training.account_jobs import retire_account_jobs++ retire_account_jobs(account)+ from core.inference.video import generation_account_in_flight, get_video_backend+ from core.training.account_jobs import AccountRetirementError++ from core.inference.diffusion_engine_router import cancel_generation_for_account++ # Signal both media generations before raising, so one delete retry stops them all.+ video_active = generation_account_in_flight() == account.account_id+ if video_active:+ get_video_backend().cancel_generate(expected_account = account.account_id)+ image_active = cancel_generation_for_account(account.account_id)+ if video_active or image_active:+ raise AccountRetirementError("Media generation is still active; retry deletion")+ # A load the account started before its tombstone is torn down here; one after it is refused.+ from core.inference import video as video_module+ from core.inference.diffusion_engine_router import retire_load_for_account+ from routes.inference import retire_account_loads++ retire_load_for_account(account.account_id)+ video_module.retire_load_for_account(account.account_id)+ retire_account_loads(account.account_id)+ run_as(account, close_mcp_sessions)+ run_as(account, invalidate_tool_cache)+ from storage.studio_db import close_wal_keeper_for++ close_wal_keeper_for(run_as(account, storage_roots.workspace_root) / "studio.db")+ roots = {root.absolute() for root in run_as(account, storage_roots.managed_account_roots)}+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")+ moved: list[tuple[Path, Path]] = []++ def restore() -> None:+ # A root that will not come back stays listed, so the caller hears where its data is.+ stranded: list[tuple[Path, Path, OSError]] = []+ with storage_roots.root_retirement_lock:+ for root, destination in reversed(moved):+ try:+ Path.rename(destination, root)+ except OSError as exc:+ stranded.append((root, destination, exc))+ moved[:] = [(root, destination) for root, destination, _ in stranded]+ if stranded:+ raise AccountRetirementError(+ "Could not restore retired directories; the data remains at "+ + ", ".join(str(destination) for _, destination, _ in stranded)+ ) from stranded[0][2]++ # Same lock as ensure_account_dir: the rename never lands between its check and mkdir.+ with storage_roots.root_retirement_lock:+ try:+ for root in sorted(roots, key = lambda path: len(path.parts), reverse = True):+ # Rename a symlink itself; never resolve it into another account's data.+ if not root.exists() and not root.is_symlink():+ continue+ destination = root.with_name(f"{root.name}-deleted-{stamp}")+ suffix = 0+ while destination.exists() or destination.is_symlink():+ suffix += 1+ destination = root.with_name(f"{root.name}-deleted-{stamp}-{suffix}")+ Path.rename(root, destination)+ moved.append((root, destination))+ except OSError:+ # All or nothing: reactivation restores no roots, so a half-retired account is empty.+ restore()+ raise+ return restore++[email protected]("", response_model = AccountListResponse)+def list_accounts():+ return {"accounts": storage.list_accounts()}++[email protected]("", response_model = AccountSetupResponse, status_code = status.HTTP_201_CREATED)+def create_account(payload: CreateAccountRequest):+ with _account_errors():+ return storage.issue_account_setup_code(username = payload.username)++[email protected]("/{account_id}/setup-code", response_model = AccountSetupResponse)+def regenerate_setup_code(account_id: str):+ with _account_errors():+ return storage.issue_account_setup_code(account_id = account_id)++[email protected]("/{account_id}", response_model = AccountResponse)+def set_account_active(account_id: str, payload: AccountActiveRequest):+ with _account_errors():+ result = storage.set_account_active(account_id, payload.is_active)+ if payload.is_active:+ # A delete that failed after retiring the jobs left the id tombstoned in-process.+ from core.training.account_jobs import restore_account_jobs+ restore_account_jobs(account_id)+ active_generations.lift_fence(account_id)+ else:+ from routes.inference import retire_account_loads++ # Fence first, so a request registering after the sweep is cancelled too.+ active_generations.fence(account_id)+ active_generations.cancel_all(account_id)+ retire_account_loads(account_id)+ account_access.retire_resident_shares(account_id)+ return result++[email protected]("/{account_id}", status_code = status.HTTP_204_NO_CONTENT)+def delete_account(account_id: str):+ from core.training.account_jobs import AccountRetirementError+ with _account_errors():+ try:+ storage.delete_account(account_id, retire_account_roots)+ except (OSError, AccountRetirementError) as exc:+ detail = "Could not retire account files. The account is disabled; retry deletion."+ if isinstance(exc, AccountRetirementError):+ detail = f"{detail} {exc}"+ raise HTTPException(status_code = 409, detail = detail)+ return Response(status_code = status.HTTP_204_NO_CONTENT)diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex a7a7b422624..ce87b555a81 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -30,7 +30,8 @@ from models.auth import (RefreshTokenRequest,)from models.users import Token-from auth import storage, hashing+from auth import storage, hashing, policy+from utils.account_context import OWNER_ACCOUNT_IDfrom auth.authentication import (authenticated_via_desktop_jwt,authenticated_without_credential,@@ -45,6 +46,15 @@ from auth.authentication import (router = APIRouter()+def _account_id_of(username: str) -> "str | None":+ """Immutable account id for ``username``, or None. Names are reusable, so state must not key+ on the name: a recreated account would inherit its predecessor's data."""+ if username == storage.DEFAULT_ADMIN_USERNAME:+ return OWNER_ACCOUNT_ID+ account = storage.get_account(username)+ return account.account_id if account is not None else None++def _require_a_credential_of_its_own(what: str):"""Refuse a caller that nothing but keyless API access let in. For effects that outlive the setting: turningkeyless access back off does not withdraw a key it handed out, restore one it destroyed, or undo a sign-out@@ -408,9 +418,13 @@ def auth_status() -> AuthStatusResponse:else True)# Only while the default password stands: that is what the deadline fires on.+ from auth.policy import full_access_permitted, login_mode+return AuthStatusResponse(initialized = storage.is_initialized(),default_username = storage.DEFAULT_ADMIN_USERNAME,+ login_mode = login_mode(),+ full_access = full_access_permitted(),requires_password_change = requires_change,bootstrap_deadline_seconds = (bootstrap_deadline_remaining_seconds() if requires_change else None@@ -418,10 +432,26 @@ def auth_status() -> AuthStatusResponse:)+def _login_failure_detail() -> str:+ """Recovery hint for a rejected login. The name shown is a placeholder, not the submitted."""+ if policy.installation_is_multi_user():+ return (+ "Incorrect username, password or setup code. Ask the installation owner to reset "+ f"the account, by running this on the Studio host: {_reset_password_command()} "+ "--username <name>"+ )+ return (+ f"Incorrect password. To reset it, run this in your terminal: {_reset_password_command()}"+ )++@router.post("/login", response_model = Token)async def login(payload: AuthLoginRequest, request: Request) -> Token:"""Login with username/password. Per-account + per-IP rate-limited."""- key = _bucket_key(request, payload.username)+ username = (+ payload.username.casefold() if policy.installation_is_multi_user() else payload.username+ )+ key = _bucket_key(request, username)unknown_key = _unknown_user_key(request)blocked_for = max(_login_blocked(key), _login_blocked(unknown_key))if blocked_for > 0:@@ -432,34 +462,42 @@ async def login(payload: AuthLoginRequest, request: Request) -> Token:headers = {"Retry-After": str(blocked_for)},)- record = storage.get_user_and_secret(payload.username)+ record = storage.get_user_and_secret(username)if record is None:- # Record under one sentinel key per IP so attacker-controlled username- # cardinality can't allocate unbounded buckets.- _record_login_failure(unknown_key)+ # Per-name buckets as for real accounts: a shared unknown bucket is an existence oracle.+ hashing.equalize_login_work(payload.password)+ _record_login_failure(key)raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED,- detail = f"Incorrect password. To reset it, run this in your terminal: {_reset_password_command()}",+ detail = _login_failure_detail(),)- salt, pwd_hash, jwt_secret, must_change_password = record- if not hashing.verify_password(payload.password, salt, pwd_hash):+ if username == storage.DEFAULT_ADMIN_USERNAME:+ salt, pwd_hash, jwt_secret, must_change_password = record+ verified = hashing.verify_password(payload.password, salt, pwd_hash)+ else:+ record = storage.authenticate_account_login(username, payload.password)+ verified = record is not None+ if record is not None:+ salt, pwd_hash, jwt_secret, must_change_password = record+ if not verified:_record_login_failure(key)raise HTTPException(status_code = status.HTTP_401_UNAUTHORIZED,- detail = f"Incorrect password. To reset it, run this in your terminal: {_reset_password_command()}",+ detail = _login_failure_detail(),)_clear_login_bucket(key)_clear_login_bucket(unknown_key)# Issue against the credential version just verified.- access_token = create_access_token(subject = payload.username, secret = jwt_secret)- refresh_token = create_refresh_token(subject = payload.username, secret = jwt_secret)+ access_token = create_access_token(subject = username, secret = jwt_secret)+ refresh_token = create_refresh_token(subject = username, secret = jwt_secret)return Token(access_token = access_token,refresh_token = refresh_token,token_type = "bearer",must_change_password = must_change_password,+ account_id = _account_id_of(username),)@@ -471,18 +509,19 @@ async def logout() -> Response:"""Revoke refresh tokens for the subject; the access token is stateless and expires on its own."""try:- storage.revoke_user_refresh_tokens(current_subject)+ storage.revoke_user_refresh_tokens(current_subject, account_id = _key_account_scope())except Exception:pass- try:- request.app.state.bootstrap_password = None- except AttributeError:- pass+ if current_subject == storage.DEFAULT_ADMIN_USERNAME:+ try:+ request.app.state.bootstrap_password = None+ except AttributeError:+ passreturn Response(status_code = status.HTTP_204_NO_CONTENT)@router.post("/desktop-login", response_model = Token)-async def desktop_login(payload: DesktopLoginRequest) -> Token:+async def desktop_login(payload: DesktopLoginRequest) -> Token | Response:"""Exchange a local desktop secret for normal admin-subject tokens."""verified = storage.validate_desktop_secret_with_credential(payload.secret)if verified is None:@@ -492,11 +531,21 @@ async def desktop_login(payload: DesktopLoginRequest) -> Token:)username, jwt_secret = verified+ from auth.policy import installation_is_multi_user++ if installation_is_multi_user():+ # The secret proves the shell owns the backend, not which account is using it.+ return Response(+ content = '{"login_required":true,"login_mode":"multi"}',+ media_type = "application/json",+ )+return Token(access_token = create_access_token(subject = username, desktop = True, secret = jwt_secret),refresh_token = create_refresh_token(subject = username, desktop = True, secret = jwt_secret),token_type = "bearer",must_change_password = False,+ account_id = _account_id_of(username),)@@ -510,6 +559,9 @@ async def refresh(payload: RefreshTokenRequest) -> Token:detail = "Invalid or expired refresh token",)username, is_desktop, jwt_secret = consumed+ account = storage.get_account(username)+ if is_desktop:+ is_desktop = account is not None and account.is_ownernew_access_token = create_access_token(subject = username, desktop = is_desktop, secret = jwt_secret)new_refresh_token = create_refresh_token(subject = username, desktop = is_desktop, secret = jwt_secret@@ -520,6 +572,7 @@ async def refresh(payload: RefreshTokenRequest) -> Token:refresh_token = new_refresh_token,token_type = "bearer",must_change_password = False if is_desktop else storage.requires_password_change(username),+ account_id = account.account_id if account is not None else None,)@@ -538,7 +591,7 @@ async def set_desktop_initial_password(already-authenticated desktop session may set it while the seeded credentialis still in place. Once set, change-password owns every later change."""- if not is_desktop:+ if not is_desktop or current_subject != storage.DEFAULT_ADMIN_USERNAME:raise HTTPException(status_code = status.HTTP_403_FORBIDDEN,detail = "This action requires the Unsloth desktop app.",@@ -588,6 +641,7 @@ async def set_desktop_initial_password(refresh_token = refresh_token,token_type = "bearer",must_change_password = False,+ account_id = _account_id_of(current_subject),)@@ -624,25 +678,34 @@ async def change_password(detail = "New password must be different from the current password",)- # Single transaction: a separate refresh-token purge could fail after the password commit, leaving pre-change- # tokens able to mint access tokens. Conditional on the hash just verified, so a concurrent reset-password- # cannot be overwritten by it.- new_secret = storage.update_password(- current_subject,- payload.new_password,- revoke_refresh_tokens = True,- expect_password_hash = pwd_hash,- preserve_desktop_secret = is_desktop,- )+ # Single transaction: a separate refresh-token purge could fail after the password commit,+ # leaving pre-change tokens able to mint access tokens. Conditional on the hash just+ # verified, so a concurrent reset-password cannot be overwritten by it.+ if current_subject == storage.DEFAULT_ADMIN_USERNAME:+ new_secret = storage.update_password(+ current_subject,+ payload.new_password,+ revoke_refresh_tokens = True,+ expect_password_hash = pwd_hash,+ preserve_desktop_secret = is_desktop,+ )+ else:+ new_secret = storage.update_account_password(+ current_subject,+ payload.new_password,+ expect_password_hash = pwd_hash,+ expect_secret = _jwt_secret,+ )if new_secret is None:raise HTTPException(status_code = status.HTTP_409_CONFLICT,detail = "The password changed while this request was in flight. Sign in again.",)- try:- request.app.state.bootstrap_password = None- except AttributeError:- pass+ if current_subject == storage.DEFAULT_ADMIN_USERNAME:+ try:+ request.app.state.bootstrap_password = None+ except AttributeError:+ passaccess_token = create_access_token(subject = current_subject, desktop = is_desktop, secret = new_secret)@@ -654,6 +717,7 @@ async def change_password(refresh_token = refresh_token,token_type = "bearer",must_change_password = False,+ account_id = _account_id_of(current_subject),)@@ -669,6 +733,13 @@ def _row_to_api_key_response(row: dict) -> ApiKeyResponse:)+def _key_account_scope() -> "str | None":+ from utils.account_context import current_account, is_owner_context+ if is_owner_context():+ return None+ return current_account().account_id++@router.post("/api-keys", response_model = CreateApiKeyResponse)async def create_api_key(payload: CreateApiKeyRequest,@@ -689,6 +760,7 @@ async def create_api_key(name = payload.name,expires_at = expires_at,expect_gen = generation,+ account_id = _key_account_scope(),)except storage.CredentialRotated:raise HTTPException(@@ -707,7 +779,7 @@ def list_api_keys(_own_credential: None = Depends(_require_a_credential_of_its_own("Managing API keys")),) -> ApiKeyListResponse:"""List all API keys for the authenticated user (raw keys are never exposed)."""- rows = storage.list_api_keys(current_subject)+ rows = storage.list_api_keys(current_subject, account_id = _key_account_scope())return ApiKeyListResponse(api_keys = [_row_to_api_key_response(r) for r in rows],)@@ -720,7 +792,7 @@ async def revoke_api_key(_own_credential: None = Depends(_require_a_credential_of_its_own("Managing API keys")),) -> dict:"""Revoke (soft-delete) an API key."""- if not storage.revoke_api_key(current_subject, key_id):+ if not storage.revoke_api_key(current_subject, key_id, account_id = _key_account_scope()):raise HTTPException(status_code = status.HTTP_404_NOT_FOUND,detail = "API key not found",diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.pyindex fedea1ecd61..9b80743b0dc 100644--- a/studio/backend/routes/chat_generation_runs.py+++ b/studio/backend/routes/chat_generation_runs.py@@ -10,6 +10,7 @@ import jsonimport reimport sqlite3from concurrent.futures import ThreadPoolExecutor+from functools import partialfrom typing import Anyfrom fastapi import APIRouter, Depends, Header, HTTPException, Query, Request@@ -17,6 +18,9 @@ from fastapi.responses import StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom auth.authentication import get_current_subject+from auth import policy+from state import active_generations+from utils.account_context import current_account, current_account_id, run_asfrom core.inference.llama_keepwarm import inference_lifecycle_gatefrom models.inference import ChatCompletionRequestfrom storage import chat_generation_runs_db as db@@ -148,8 +152,7 @@ def _sanitize_request(payload: CreateChatGenerationRun) -> dict[str, Any]:status_code = 422,detail = safe_validation_errors(exc.errors()),) from exc- # The refusal the completion route runs on entry. Without it a part no path can serve is- # queued at 202 and fails asynchronously in the supervisor, where the caller cannot see it.+ # Without this an unservable part is queued at 202 and fails where the caller cannot see it.from routes.inference import _messages_have_input_audio, _reject_unsupported_content_parts_reject_unsupported_content_parts(request)@@ -178,7 +181,6 @@ def _sanitize_request(payload: CreateChatGenerationRun) -> dict[str, Any]:detail = "Durable chat runs are available only for local inference",)# A media turn has no replayable transcript and its payload persists verbatim, so a base64 blob would live in- # request_json for the life of the thread. A recording rides in a content part too, not just the field.if any(raw.get(field) not in (None, "") for field in _MEDIA_FIELDS) or _messages_have_input_audio(request.messages):@@ -223,6 +225,31 @@ def _require_run(run_id: str) -> dict[str, Any]:return run+def cancel_account_run(request: Request, run_id: str, *, supervisor_name: str) -> None:+ """Signal only the caller's registration: another account may legitimately reuse a bare+ cancel ID, so it is never stashed."""+ if policy.installation_has_managed_accounts():+ active_generations.cancel_run(run_id, account_id = current_account_id())+ if supervisor_name == "chat_generation_supervisor":+ return+ supervisor = getattr(request.app.state, supervisor_name, None)+ if supervisor is not None:+ supervisor.cancel(run_id)+ elif supervisor_name == "chat_generation_supervisor":+ from routes.inference import _cancel_by_cancel_id_or_stash+ active_generations.cancel_run(run_id)+ _cancel_by_cancel_id_or_stash(run_id)+++def _require_available_supervisor_run_id(run_id: str) -> None:+ """A legacy supervisor keys tasks by bare ID, and start() no-ops on a held id, so a foreign+ active slot must be refused or an admitted owner run would never be scheduled."""+ if policy.installation_has_managed_accounts():+ for entry in active_generations.snapshot():+ if entry["run_id"] == run_id:+ policy.require_account_scope(entry.get("account_id"))++def _event_cursor(after: int | None, last_event_id: str | None) -> int:if after is not None and after > _SQLITE_MAX_INTEGER:raise HTTPException(status_code = 400, detail = "Event cursor is too large")@@ -250,6 +277,7 @@ async def create_chat_generation_run(# Serialize the off-loop commit with model lifecycle work, so a run is registered either before the gate opens or# after an unload/swap, never mid-swap.async with inference_lifecycle_gate():+ _require_available_supervisor_run_id(payload.runId)try:run, created = await asyncio.to_thread(db.create_run,@@ -300,9 +328,11 @@ def cancel_chat_generation_run(run = db.request_cancel(run_id)if run is None:raise HTTPException(status_code = 404, detail = "Chat generation run not found")- supervisor = getattr(request.app.state, "chat_generation_supervisor", None)- if supervisor is not None and run["status"] in {"cancelling", "cancelled"}:- supervisor.cancel(run_id)+ if run["status"] in {"cancelling", "cancelled"} and (+ getattr(request.app.state, "chat_generation_supervisor", None) is not None+ or policy.installation_has_managed_accounts()+ ):+ cancel_account_run(request, run_id, supervisor_name = "chat_generation_supervisor")return run@@ -316,6 +346,10 @@ async def chat_generation_events():_require_run(run_id)cursor = _event_cursor(after, last_event_id)+ wait_for_events = db.wait_for_events+ if policy.installation_has_managed_accounts():+ # run_in_executor does not copy ContextVars, unlike asyncio.to_thread.+ wait_for_events = partial(run_as, current_account(), db.wait_for_events)async def stream():nonlocal cursor@@ -330,7 +364,7 @@ async def chat_generation_events(while True:events = await loop.run_in_executor(_EVENT_WAIT_EXECUTOR,- db.wait_for_events,+ wait_for_events,run_id,cursor,15,diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 231a4cfb9ee..6ada14ba102 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -23,6 +23,8 @@ from pydantic import ()from auth.authentication import get_current_subject+from auth import policy+from routes.chat_generation_runs import cancel_account_runfrom core.inference.llama_server_args import (BATCH_MAX,BATCH_MIN,@@ -697,11 +699,11 @@ def patch_thread(def _cancel_deleted_research_runs(request: Request, run_ids: list[str]) -> None:"""Signal workers for active runs captured by the deletion transaction."""supervisor = getattr(request.app.state, "research_supervisor", None)- if supervisor is None:+ if supervisor is None and not policy.installation_has_managed_accounts():returnfor run_id in run_ids:try:- supervisor.cancel(run_id)+ cancel_account_run(request, run_id, supervisor_name = "research_supervisor")except Exception: # noqa: BLE001 - cancellation is best-effort after commitlogger.warning("chat_history.cancel_deleted_research_failed run_id=%s",@@ -727,8 +729,10 @@ def _cancel_active_research(request: Request, thread_ids: list[str]) -> None:for run in active:try:status = research_runs_db.request_cancel(run["id"])- if supervisor is not None and status == "cancelling":- supervisor.cancel(run["id"])+ if status == "cancelling" and (+ supervisor is not None or policy.installation_has_managed_accounts()+ ):+ cancel_account_run(request, run["id"], supervisor_name = "research_supervisor")except Exception: # noqa: BLE001logger.warning("chat_history.cancel_active_research_failed run_id=%s",@@ -747,11 +751,12 @@ def _cancel_research_runs(request: Request, run_ids: list[str]) -> None:returnsupervisor = getattr(request.app.state, "research_supervisor", None)for run_id in run_ids:- # The row is usually already gone here, which makes request_cancel raise: the supervisor is what- # actually stops the worker, so it is told first and the status update is the best-effort half.- if supervisor is not None:+ # The row is usually already gone here, which makes request_cancel raise:+ # the supervisor is what actually stops the worker, so it is told first+ # and the status update is the best-effort half.+ if supervisor is not None or policy.installation_has_managed_accounts():try:- supervisor.cancel(run_id)+ cancel_account_run(request, run_id, supervisor_name = "research_supervisor")except Exception: # noqa: BLE001logger.warning("Could not signal research run %s", run_id, exc_info = True)try:@@ -782,17 +787,9 @@ def _cancel_chat_generation_runs(request: Request, run_ids: list[str]) -> None:"""Cancel durable producers whose rows were captured before thread cascade."""if not run_ids:return- supervisor = getattr(request.app.state, "chat_generation_supervisor", None)for run_id in run_ids:try:- if supervisor is not None:- supervisor.cancel(run_id)- else:- from routes.inference import _cancel_by_cancel_id_or_stash- from state import active_generations-- active_generations.cancel_run(run_id)- _cancel_by_cancel_id_or_stash(run_id)+ cancel_account_run(request, run_id, supervisor_name = "chat_generation_supervisor")except Exception: # noqa: BLE001 - deletion must still completelogger.warning("Could not signal chat generation run %s", run_id, exc_info = True)@@ -1416,6 +1413,12 @@ def record_import_ledger(return ChatImportLedgerRecordResponse(accepted = accepted, inserted = inserted)+def _snapshot_chat_images() -> Optional[set[str]]:+ """Registry and thumbnail cache are account-scoped, so this bounds the reap to the caller."""+ from core.inference.search_images import snapshot_and_fence_registrations+ return snapshot_and_fence_registrations()++@router.delete("")async def clear_history(request: Request,@@ -1435,17 +1438,21 @@ async def clear_history()def _clear_rows() -> tuple[list[str], list[str], list[str], bool, Optional[set]]:- """The clear, and the image snapshot the reap will be bounded to. Both in ONE threadpool call,- so there is no await between them. Split across two, the event loop can run another request- in the gap: a chat created there survives the transaction, but its images register before- the snapshot and the reap takes them. Narrowed, NOT closed: another worker thread can still- register between the commit and the read, and only holding ``_registry_lock`` across the- transaction would close that. Every image registration in the process takes that lock and- this transaction is a BEGIN IMMEDIATE that waits out contention for seconds, so paying for- it means stalling every search in every chat for the length of a clear, to buy back a window- a few instructions wide."""- from core.inference.search_images import snapshot_and_fence_registrations-+ """The clear, and the image snapshot the reap will be bounded to.++ Both in ONE threadpool call, so there is no await between them. Split across two,+ the event loop can run another request in the gap: a chat created there survives+ the transaction, but its images register before the snapshot and the reap takes+ them, leaving its cards 404ing out of thumbnail_bytes.++ Narrowed, NOT closed, and the difference is worth stating. Another worker thread can+ still register between the commit and the read a few instructions later, and only one+ thing would truly close that: holding ``_registry_lock`` across the transaction. That+ lock is what every image registration in the process takes, and this transaction is a+ BEGIN IMMEDIATE that waits out contention for seconds, so paying for it means stalling+ every search in every chat for the length of a clear. The window bought back is a few+ instructions wide and its cost is one chat's thumbnails re-fetching. Not worth it.+ """if payload is None:cleared, cleared_runs, cleared_chat_runs = clear_chat_history(include_chat_generation_runs = True@@ -1455,7 +1462,7 @@ async def clear_history(cleared_runs,cleared_chat_runs,False,- snapshot_and_fence_registrations(),+ _snapshot_chat_images(),)# Answered by the transaction itself: read beforehand it is a guess, and the one BEGIN IMMEDIATE# puts second replays while still believing it cleared. `replayed` is whichever the transaction did.@@ -1474,7 +1481,7 @@ async def clear_history(True,unreaped_clear_operation_image_ids(payload.operationId),)- snapshot = snapshot_and_fence_registrations()+ snapshot = _snapshot_chat_images()# Recorded before the reap runs.record_clear_operation_reap_scope(payload.operationId, snapshot)return cleared, cleared_runs, cleared_chat_runs, False, snapshotdiff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex c9bb9b90560..7bfb1dac019 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -5,6 +5,8 @@from __future__ import annotations+from utils.account_context import current_account+from core.training.account_jobs import account_event_streamimport copyimport timefrom datetime import datetime, timedelta, timezone@@ -309,7 +311,7 @@ def _inject_local_providers(# hidden from the user's key list; the caller revokes it when the job terminates.expires_at = (datetime.now(timezone.utc) + timedelta(hours = 24)).isoformat()token, row = storage.create_api_key(- username = "unsloth",+ username = current_account().username,name = "data-recipe workflow",expires_at = expires_at,internal = True,@@ -651,7 +653,7 @@ async def job_events(request: Request, job_id: str):mgr.unsubscribe(sub)return StreamingResponse(- gen(),+ account_event_stream(mgr, gen()),media_type = "text/event-stream",headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.pyindex ce238ab5cb8..4b9a58c64c7 100644--- a/studio/backend/routes/data_recipe/seed.py+++ b/studio/backend/routes/data_recipe/seed.py@@ -5,6 +5,7 @@from __future__ import annotations+from core.training.account_jobs import account_path, managed_accountimport base64import binasciiimport json@@ -24,6 +25,7 @@ from core.data_recipe.jsonable import to_preview_jsonablefrom hub.utils.dataset_cache import refuse_unauthorized_dataset_previewfrom hub.utils.hf_tokens import HfTokenArg, hf_token_argfrom loggers import get_logger+from utils.paths.lazy import LazyPathfrom utils.paths import ensure_dir, seed_uploads_root, unstructured_uploads_rootfrom utils.utils import log_and_http_errorfrom utils.upload_limits import (@@ -68,8 +70,8 @@ DATA_EXTS = (".parquet", ".jsonl", ".json", ".csv")DEFAULT_SPLIT = "train"LOCAL_UPLOAD_EXTS = {".csv", ".json", ".jsonl"}UNSTRUCTURED_ALLOWED_EXTS = {".pdf", ".docx", ".txt", ".md"}-SEED_UPLOAD_DIR = seed_uploads_root()-UNSTRUCTURED_UPLOAD_ROOT = unstructured_uploads_root()+SEED_UPLOAD_DIR = LazyPath(seed_uploads_root)+UNSTRUCTURED_UPLOAD_ROOT = LazyPath(unstructured_uploads_root)_SAFE_ID_RE = re.compile(r"^[a-zA-Z0-9_-]+$")# Frontend-generated upload namespace (UUID4 hex); legacy node ids (n1, ...) never match,# since those directories can be shared by several recipes.@@ -209,6 +211,7 @@ def _decode_base64_payload(content_base64: str) -> bytes:def _read_preview_rows_from_local_file(path: Path, preview_size: int) -> list[dict[str, Any]]:+ account_path(path)try:import pandas as pdexcept ImportError as exc:@@ -261,6 +264,7 @@ def _read_preview_rows_from_local_file(path: Path, preview_size: int) -> list[didef _read_preview_rows_from_unstructured_file(*, path: Path, preview_size: int, chunk_size: int | None, chunk_overlap: int | None) -> list[dict[str, Any]]:+ account_path(path)chunking = _chunking()if chunking is None:raise HTTPException(@@ -335,7 +339,7 @@ def inspect_seed_dataset(# From the caller: a hardcoded False takes the ambient fallback from UI sessions too.token = hf_token_arg(_normalize_optional_text(payload.hf_token),- allow_ambient_token = allow_ambient_token,+ allow_ambient_token = allow_ambient_token and not managed_account(),)preview_size = int(payload.preview_size)refuse_unauthorized_dataset_preview(token, dataset_name)@@ -520,6 +524,7 @@ def _read_native_drop(lease: str, budget: int) -> tuple[str, bytes]:except NativePathLeaseError as exc:raise HTTPException(400, str(exc)) from exc+ account_path(grant.canonical_path)_require_unstructured_ext(grant.canonical_path.name)try:size_bytes = grant.canonical_path.stat().st_size@@ -824,5 +829,7 @@ def get_github_env_token_status() -> dict:The value is never returned; the UI uses this to tell the user theycan leave the token field blank."""+ if managed_account():+ return {"has_token": False}has_token = bool(os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN"))return {"has_token": has_token}diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex 43b1ba040fa..0f7aa91a978 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -3,6 +3,13 @@"""Export API routes: checkpoint discovery and model export operations."""+from core.training.account_jobs import (+ account_event_stream,+ job_busy,+ job_is_foreign,+ require_job_owner,+ validate_job_paths,+)import asyncioimport jsonimport os@@ -21,6 +28,7 @@ if str(backend_path) not in sys.path:sys.path.insert(0, str(backend_path))from auth.authentication import allow_ambient_hf_token, get_current_subject+from hub.services.models import account_accessfrom hub.utils.hf_tokens import HfTokenArg, hf_token_argfrom utils.utils import safe_error_detail@@ -91,6 +99,18 @@ def _resolve_export_hf_token(return hf_token_arg(token, allow_ambient_token = allow_ambient)+def _authorized_adapter_base(checkpoint_path: str) -> Optional[str]:+ """The adapter's config names the base the worker loads, so it is authorized like the checkpoint."""+ if not account_access.managed_account():+ return None+ from utils.models import get_base_model_from_lora++ base = get_base_model_from_lora(checkpoint_path)+ if base:+ account_access.require_model_access(base)+ return base or None++@router.post("/load-checkpoint", response_model = ExportOperationResponse)async def load_checkpoint(request: LoadCheckpointRequest,@@ -104,6 +124,8 @@ async def load_checkpoint(chat model here -- if the GPU runs out of memory the load/export fails witha clear error instead of tearing down the user's other running workloads."""+ validate_job_paths(request.model_dump())+ base_model = await asyncio.to_thread(_authorized_adapter_base, request.checkpoint_path)try:await _ensure_export_supported()backend = get_export_backend()@@ -112,6 +134,7 @@ async def load_checkpoint(success, message = await asyncio.to_thread(backend.load_checkpoint,checkpoint_path = request.checkpoint_path,+ base_model = base_model,max_seq_length = request.max_seq_length,load_in_4bit = request.load_in_4bit,trust_remote_code = request.trust_remote_code,@@ -175,6 +198,7 @@ async def cancel_export(current_subject: str = Depends(get_current_subject)):Only the export subprocess is killed; training and inference run in theirown subprocesses and keep going."""+ require_job_owner(get_export_backend())try:backend = get_export_backend()cancelled = await asyncio.to_thread(backend.cancel_export)@@ -193,6 +217,14 @@ async def cancel_export(current_subject: str = Depends(get_current_subject)):@router.get("/status", response_model = ExportStatusResponse)async def get_export_status(current_subject: str = Depends(get_current_subject)):"""Get export backend status (loaded checkpoint, model type, PEFT flag)."""+ if job_is_foreign(get_export_backend()):+ return ExportStatusResponse(+ current_checkpoint = None,+ is_vision = False,+ is_peft = False,+ is_export_active = bool(get_export_backend().is_export_active()),+ active_op_kind = "busy" if job_busy(get_export_backend()) else None,+ )try:backend = get_export_backend()last_op = backend.get_last_op()@@ -330,6 +362,7 @@ async def export_merged_model(Wraps ExportBackend.export_merged_model."""+ validate_job_paths(request.model_dump())try:await _ensure_export_supported()backend = get_export_backend()@@ -380,6 +413,7 @@ async def export_base_model(Wraps ExportBackend.export_base_model."""+ validate_job_paths(request.model_dump())try:await _ensure_export_supported()backend = get_export_backend()@@ -429,6 +463,7 @@ async def export_gguf(Wraps ExportBackend.export_gguf."""+ validate_job_paths(request.model_dump())try:await _ensure_export_supported()backend = get_export_backend()@@ -482,6 +517,7 @@ async def export_lora_adapter(Wraps ExportBackend.export_lora_adapter."""+ validate_job_paths(request.model_dump())try:await _ensure_export_supported()backend = get_export_backend()@@ -591,6 +627,9 @@ async def stream_export_logs(idle_since: Optional[float] = Nonetry:while True:+ if job_is_foreign(backend):+ yield _format_sse('{"status":"busy"}', event = "busy")+ returnif await request.is_disconnected():return@@ -647,7 +686,7 @@ async def stream_export_logs(passreturn StreamingResponse(- event_generator(),+ account_event_stream(get_export_backend(), event_generator()),media_type = "text/event-stream",headers = {"Cache-Control": "no-cache",diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 458c16d0005..4e8c2645ba1 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -42,6 +42,16 @@ from typing import (import functoolsimport jsonimport httpx+from hub.services.models import account_access+from hub.services.models.account_access import media_link_account, media_link_target+from utils.account_context import (+ OWNER_ACCOUNT_ID,+ account_thread,+ current_account,+ current_account_id,+ run_as,+)+from utils.security.consent import MANAGED_REMOTE_CODE_REFUSAL, managed_remote_code_refusedfrom loggers import get_loggerfrom loggers.media_progress import (log_media_generation_progress,@@ -3138,7 +3148,7 @@ from core.inference.anthropic_compat import (AnthropicStreamEmitter,AnthropicPassthroughEmitter,)-from auth import storage as auth_storage+from auth import policy as auth_policy, storage as auth_storagefrom auth.authentication import API_KEY_PREFIX, get_current_subjectfrom state import active_generations@@ -4030,6 +4040,16 @@ def _passthrough_client_tools(payload):return payload.tools or None+def _admit_tool_access(payload) -> None:+ """Refuse full access before a stream opens and 400 is no longer possible."""+ from state.tool_policy import require_tool_access+ require_tool_access(+ getattr(payload, "permission_mode", None),+ bypass_permissions = bool(getattr(payload, "bypass_permissions", False)),+ disable_sandbox = bool(getattr(payload, "disable_sandbox", False)),+ )++def _permission_mode_confirm(payload) -> bool:"""Effective confirm-gate intent for Unsloth's own local tool loop.@@ -4404,6 +4424,13 @@ _PENDING_CANCELS: dict[str, float] = {}_PENDING_CANCEL_TTL_S = 30.0+def _account_cancel_key(key):+ # Tuples cannot collide with the legacy string ids of one-account installs.+ if account_access.managed_account():+ return current_account_id(), key+ return key++def _prune_pending(now: float) -> None:for k in [k for k, ts in _PENDING_CANCELS.items() if now - ts > _PENDING_CANCEL_TTL_S]:_PENDING_CANCELS.pop(k, None)@@ -4427,7 +4454,7 @@ class _TrackedCancel:kind = "chat",):self.event = event- self.keys = tuple(k for k in keys if k)+ self.keys = tuple(_account_cancel_key(k) for k in keys if k)# kind reaches the swap prompt: embeddings and raw completions have no conversation, so# naming them chats would offer to stop something the user never started from a thread.self._active = active_generations.ActiveGeneration(@@ -4486,7 +4513,7 @@ def _cancel_by_keys(keys) -> int:with _CANCEL_LOCK:_prune_pending(time.monotonic())for k in keys:- bucket = _CANCEL_REGISTRY.get(k)+ bucket = _CANCEL_REGISTRY.get(_account_cancel_key(k))if bucket:events.update(bucket)for ev in events:@@ -4497,6 +4524,7 @@ def _cancel_by_keys(keys) -> int:def _cancel_by_cancel_id_or_stash(cancel_id: str) -> int:"""Atomic lookup-or-stash; pairs with _TrackedCancel.__enter__ toclose the TOCTOU race."""+ cancel_id = _account_cancel_key(cancel_id)now = time.monotonic()events: set[threading.Event] = set()with _CANCEL_LOCK:@@ -7139,7 +7167,11 @@ async def _lease_ollama_model_ref(return Noneloop = asyncio.get_running_loop()lease_future = loop.run_in_executor(- _OLLAMA_LEASE_EXECUTOR, acquire_ollama_model_ref, request.model_path+ _OLLAMA_LEASE_EXECUTOR,+ run_as,+ current_account(),+ acquire_ollama_model_ref,+ request.model_path,)try:lease = await asyncio.shield(lease_future)@@ -7163,6 +7195,15 @@ async def _lease_ollama_model_ref(return lease.path+def _defers_access_to_native_grant(request) -> bool:+ """A native selection sends a label, so the check waits for the lease's canonical path."""+ return bool(+ account_access.managed_account()+ and getattr(request, "native_path_lease", None)+ and not is_ollama_manifest_ref(request.model_path)+ )++def _resolve_model_identifier_for_request(request: LoadRequest | ValidateModelRequest,*,@@ -7303,9 +7344,14 @@ async def _wait_for_model_switch_idle(still be refused, so they must not shorten the protection they provide."""from core.inference.llama_keepwarm import other_inference_request_count+ from core.inference.gpu_arbiter import require_no_foreign_generations+ # account_scope(), not login mode: deactivation only signals its generation, not the decode.+ account_id = account_access.account_scope()deadline = None if timeout_s is None else time.monotonic() + timeout_swhile True:+ if account_id is not None:+ require_no_foreign_generations(account_id)queued_switches = _switch_waiter_count()if current_request_counted and queued_switches > 0:queued_switches -= 1@@ -7314,7 +7360,12 @@ async def _wait_for_model_switch_idle(include_pending = False,)if cancel_pending:- active_others -= min(active_others, active_generations.count())+ cancellable = (+ active_generations.count(account_id)+ if account_id is not None+ else active_generations.count()+ )+ active_others -= min(active_others, cancellable)if active_others <= queued_switches:returnif deadline is not None and time.monotonic() >= deadline:@@ -7436,7 +7487,7 @@ def _target_is_vision(return bool(is_vision_model(load_path,- hf_token = os.environ.get("HF_TOKEN"),+ hf_token = account_access.ambient_hf_token(),gguf_variant = gguf_variant,require_image = need_image,gguf_companion_roots = gguf_companion_roots or None,@@ -7460,7 +7511,7 @@ def _target_accepts_audio_input(load_path: str) -> bool:return is_audio_input_type(detect_audio_type(load_path,- hf_token = os.environ.get("HF_TOKEN"),+ hf_token = account_access.ambient_hf_token(),local_files_only = True,))@@ -8419,7 +8470,7 @@ def _classify_and_probe_residency(def _innermost_indexed_owner(path: str) -> Optional[str]:"""Longest catalog-listed model path containing *path*, or None if none does."""best = None- for info in _CATALOG_CACHE["models"] or ():+ for info in _account_catalog_cache()["models"] or ():listed = getattr(info, "path", None)if not listed:continue@@ -8587,6 +8638,64 @@ async def _reject_unservable_model()+async def _require_named_model_access(+ named_model: str, fastapi_request: Optional[Request] = None+) -> None:+ """Authorize a named model via the account catalog, or an uncached Hub ref via caller token."""+ try:+ await asyncio.to_thread(account_access.require_model_access, named_model)+ return+ except HTTPException as refusal:+ if refusal.status_code != 404:+ raise+ from core.inference.openai_auto_download import split_model_ref++ alias = (split_model_ref(named_model)[0] or "").strip().lower()+ if alias:+ await _cached_local_catalog()+ if await asyncio.to_thread(_own_local_model_for_alias, alias) is not None:+ return+ if await _caller_token_authorizes_download(named_model, fastapi_request):+ return+ raise HTTPException(status_code = 404, detail = "Model not found")+++async def _caller_token_authorizes_download(+ named_model: str, fastapi_request: Optional[Request]+) -> bool:+ """Whether the caller's own Hub token authorizes fetching an uncached Hub reference."""+ from core.inference.openai_auto_download import is_downloadable_ref, split_model_ref+ from utils.openai_auto_switch_settings import get_openai_auto_download_enabled++ if fastapi_request is None or not get_openai_auto_download_enabled():+ return False+ reference = named_model.strip()+ if reference.startswith(("./", "../", "~", "/")) or not is_downloadable_ref(reference):+ return False+ # Only the caller's own token, never the server's ambient one.+ hf_token = _auto_download_hf_token(fastapi_request)+ if not hf_token:+ return False+ try:+ await asyncio.to_thread(+ account_access.authorize_download, split_model_ref(reference)[0], "model", hf_token+ )+ except HTTPException:+ return False+ return True+++def _own_local_model_for_alias(alias: str) -> Optional[str]:+ for info in _account_catalog_cache()["models"] or ():+ cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))+ path = getattr(info, "path", None)+ if not cid or not path or cid.strip().lower() != alias:+ continue+ if account_access.model_visible(path):+ return path+ return None++async def _maybe_auto_switch_model(requested_model: Optional[str],fastapi_request: Request,@@ -8631,6 +8740,24 @@ async def _maybe_auto_switch_model(:func:`_preflight_audio_for_switch`. ``image_preflight`` does the same fornon-GGUF image count and byte validation."""+ # The reload-only sentinel means an omitted model, not a name.+ named_model = requested_model if requested_model != _RELOAD_ONLY_MODEL else None+ if account_access.managed_account():+ if named_model:+ await _require_named_model_access(named_model, fastapi_request)+ elif account_access.resident_hidden("chat", _loaded_slot_ident()):+ raise HTTPException(status_code = 404, detail = "Model not found")++ async def _refuse_foreign_resident() -> None:+ """Serve a named model only if the resident is the caller's own or answers to the name."""+ if not named_model or not account_access.managed_account():+ return+ if not account_access.resident_hidden("chat", _loaded_slot_ident()):+ return+ if await asyncio.to_thread(_loaded_identity_satisfies, named_model):+ return+ raise HTTPException(status_code = 404, detail = "Model not found")+from utils.openai_auto_switch_settings import (get_openai_auto_switch_enabled,get_model_override,@@ -8723,6 +8850,7 @@ async def _maybe_auto_switch_model(# No switching to do, but a named model must still not be answered by another.# Reject first: a request that is turned away here must not claim the slot.await _reject_unservable_model(requested_model, fastapi_request)+ await _refuse_foreign_resident()# Auto-switch off: this non-preview turn uses the resident model, claim it.if claim_resident:_claim_slot_for_non_preview(fastapi_request)@@ -8939,6 +9067,10 @@ async def _maybe_auto_switch_model(_set_preview_resident(None)_record_serving_alias()return+ from core.inference.gpu_arbiter import require_no_foreign_generations++ switch_path = getattr(getattr(fastapi_request, "url", None), "path", None)+ require_no_foreign_generations(path = switch_path)# Loading a non-GGUF model unloads the resident GGUF, and these endpoints read# llama.cpp alone, so the swap would strand them with nothing to serve.if gguf_only and not target_is_gguf and resolved is not None:@@ -9093,6 +9225,7 @@ async def _maybe_auto_switch_model(_set_preview_resident(None)_record_serving_alias()return+ require_no_foreign_generations(path = switch_path)# Apply the saved launch config so an API swap loads as the picker# would. Order: variant-qualified keys before bare ids, and the# load path before the advertised id, since the settings UI keys@@ -9240,9 +9373,27 @@ async def _maybe_auto_switch_model(if waiter_noted:_note_switch_waiter(key, -1)- await _resolve_and_switch()+ try:+ await _resolve_and_switch()+ except HTTPException as exc:+ path = getattr(getattr(fastapi_request, "url", None), "path", None)+ if (+ path+ and path.startswith("/v1/")+ and isinstance(exc.detail, dict)+ and exc.detail.get("error") == "gpu_busy"+ ):+ raise HTTPException(+ status_code = 409,+ detail = error_body_for_path(+ path, exc.detail["message"], status = 409, code = "gpu_busy", param = "model"+ ),+ headers = exc.headers,+ ) from exc+ raise# The switch may have missed, so refuse rather than answer as whatever is resident.await _reject_unservable_model(requested_model, fastapi_request)+ await _refuse_foreign_resident()async def _auto_switch_from_request_body(@@ -9354,6 +9505,25 @@ def _loaded_slot_ident() -> Optional[str]:return None+def release_chat_gpu_claim() -> bool:+ """Drop the CHAT claim once nothing is resident or loading, else the arbiter hides an empty GPU+ from other accounts. release_if runs under the arbiter lock, so a re-registered load keeps it."""+ from core.inference.gpu_arbiter import CHAT, release_if+ from core.inference.llama_cpp import chat_load_active++ def chat_idle() -> bool:+ llama = get_llama_cpp_backend()+ # is_active, not is_loaded: a starting model holds VRAM, and an HF load has no process yet.+ if llama.is_active or chat_load_active():+ return False+ backend = _peek_inference_backend()+ return not getattr(backend, "active_model_name", None) and not tuple(+ getattr(backend, "loading_models", ()) or ()+ )++ return release_if(CHAT, chat_idle)++def _preview_same_checkpoint(loaded: str, requested: str) -> bool:"""True when the resident slot already serves the preview's checkpoint. Exact stringmatch first: it is the fast path and the only comparison that makes sense for a non-path@@ -9393,6 +9563,9 @@ def _claim_slot_for_non_preview(fastapi_request) -> None:async def load_model_for_preview(request: LoadRequest, fastapi_request: Request, current_subject: str) -> None:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.model_path)+ account_access.require_idle_other_accounts()from core.inference.llama_keepwarm import (inference_lifecycle_gate,note_preview_swap,@@ -13634,11 +13807,19 @@ def _raise_or_cancel_active_generations(run ahead of preflight checks that can still reject the load (see_load_model_impl)."""- if not active_generations.count():+ from core.inference.gpu_arbiter import require_no_foreign_generations++ scope = account_access.account_scope()+ if scope is not None:+ # Before the count and the cancel: a foreign generation refuses the swap, so cancelling+ # first would end the caller's chats for nothing. Keyed on account_scope(), whose count+ # drops while a deactivated account's generation still holds the GPU.+ require_no_foreign_generations(scope)+ if not active_generations.count(scope):return 0if not force:- thread_ids = active_generations.active_thread_ids()- running = active_generations.count()+ thread_ids = active_generations.active_thread_ids(scope)+ running = active_generations.count(scope)raise HTTPException(status_code = 409,detail = {@@ -13656,7 +13837,7 @@ def _raise_or_cancel_active_generations(if not cancel:# Refusal-only pass: the caller cancels later, once nothing can still reject the load.return 0- cancelled = active_generations.cancel_all()+ cancelled = active_generations.cancel_all(scope)if cancelled:logger.info("model_swap_cancelled_active_generations",@@ -13850,7 +14031,8 @@ async def get_active_generations(slot count actually in use, which the VRAM fit may have cut below therequested --parallel; chats beyond it queue rather than fail."""- entries = active_generations.snapshot()+ scope = account_access.account_scope()+ entries = active_generations.snapshot(scope)# A tracker's model can be a native local path (the legacy stream records active_model_name# verbatim); redact here, the one place that serialises it.for _entry in entries:@@ -13864,7 +14046,7 @@ async def get_active_generations(return {"active": entries,"count": len(entries),- "thread_ids": active_generations.active_thread_ids(),+ "thread_ids": active_generations.active_thread_ids(scope),"parallel_slots": max(1, int(slots)),}@@ -13978,6 +14160,22 @@ def _cancel_for_shutdown(attempt: _ScopedLoadAttempt) -> None:attempt.cancel_complete.set()+def retire_account_loads(account_id: str) -> int:+ """Cancel every /load the account owns. Runs after its tombstone, which refuses later ones."""+ with _scoped_load_attempts_lock:+ attempts = {+ attempt.token: attempt+ for attempt in (*_pending_load_attempts.values(), *_scoped_load_attempts.values())+ if attempt.subject == account_id+ }+ running = _running_load_attempt+ if running is not None and running.subject == account_id:+ attempts[running.token] = running+ for attempt in attempts.values():+ _cancel_for_shutdown(attempt)+ return len(attempts)++def begin_load_lifecycle() -> None:"""Clear the shutdown latch so a restarted server accepts loads again."""global _loads_shutting_down@@ -13994,6 +14192,8 @@ def _prune_scoped_load_cancel_tombstones(now: float) -> None:def _begin_load_attempt(request: LoadRequest, current_subject: str) -> _ScopedLoadAttempt:+ if account_access.account_scope() is not None:+ current_subject = current_account_id()attempt = _ScopedLoadAttempt(token = uuid.uuid4().hex,request_id = request.load_request_id,@@ -14036,6 +14236,8 @@ def _finish_load_attempt(attempt: _ScopedLoadAttempt) -> None:def _cancel_scoped_load_attempt(request: UnloadRequest, current_subject: str) -> tuple[Optional[_ScopedLoadAttempt], bool]:+ if account_access.account_scope() is not None:+ current_subject = current_account_id()request_id = request.cancel_load_request_idif request_id is None:return None, False@@ -14090,7 +14292,7 @@ async def _run_tracked_load_model_impl(try:if attempt.cancel_event.is_set():raise HTTPException(status_code = 409, detail = "Model load cancelled")- return await _load_model_impl(+ response = await _load_model_impl(request,fastapi_request,current_subject,@@ -14098,6 +14300,7 @@ async def _run_tracked_load_model_impl(on_reload_confirmed = on_reload_confirmed,load_cancel_event = attempt.cancel_event,)+ return responsefinally:if attempt.cancel_event.is_set() and not attempt.cancel_complete.is_set():if not await asyncio.to_thread(@@ -14116,6 +14319,7 @@ async def _run_tracked_load_model_impl(@router.post("/load", response_model = LoadResponse)+@account_access.gpu_busy_routeasync def load_model(request: LoadRequest,fastapi_request: Request,@@ -14232,6 +14436,13 @@ async def _run_gguf_load_attempt(llama_backend, intent, load_cancel_event) -> boreturn False+def _require_resolved_base_access(config) -> None:+ """Grants apply to the base in an adapter's config, so it cannot pull a foreign cached base."""+ base = getattr(config, "base_model", None)+ if account_access.managed_account() and isinstance(base, str) and base.strip():+ account_access.require_model_access(base.strip())++async def _load_model_impl(request: LoadRequest,fastapi_request: Request,@@ -14245,11 +14456,20 @@ async def _load_model_impl(anonymous_hf_access: bool = False,speech_codec_path: Optional[str] = None,):+ native_access_deferred = _defers_access_to_native_grant(request)+ if account_access.managed_account() and not native_access_deferred:+ await asyncio.to_thread(account_access.require_model_access, request.model_path)+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )from core.inference.llama_cpp import LlamaServerNotFoundErrordef _raise_if_scoped_load_cancelled() -> None:if load_cancel_event is not None and load_cancel_event.is_set():raise HTTPException(status_code = 409, detail = "Model load cancelled")+ # Retirement sweeps registered attempts; a load it raced is refused here, before the GPU.+ account_access.require_live_account()# Auto-switch and preview call this impl directly, without a _ScopedLoadAttempt,# so the shutdown sweep has no event to set for them. Reading the latch here puts@@ -14343,6 +14563,8 @@ async def _load_model_impl(resolved_ollama_path = resolved_ollama_path,))+ if native_access_deferred:+ await asyncio.to_thread(account_access.require_model_access, model_identifier)# Keep the inventory ref public while loading the materialized artifact.public_model_identifier = _public_model_identifier(request.model_path, model_identifier)@@ -14363,7 +14585,7 @@ async def _load_model_impl(# Reclaim the GPU for chat (evicting a resident Images/Video pipeline) only once the load is known viable; the# already-loaded fast paths below re-assert CHAT themselves. Deferred past validation so a doomed load evicts nothing.from core.inference.gpu_arbiter import (- acquire_for,+ acquire_for_request,current_owner,release,CHAT,@@ -14409,6 +14631,7 @@ async def _load_model_impl(logger.info("Model already loaded (GGUF): %s, skipping reload", model_log_label)# A no-op Unsloth load of a preview-owned checkpoint still claims it._set_preview_resident(None)+ account_access.join_resident("chat")return _gguf_load_response(llama_backend,"already_loaded",@@ -14437,7 +14660,7 @@ async def _load_model_impl(# held) to correct a drifted owner. Unless the resident server is a confirmed# zero-VRAM one, which coexists with an image/video pipeline.if not llama_backend.holds_no_vram:- await asyncio.to_thread(acquire_for, CHAT)+ await asyncio.to_thread(acquire_for_request, CHAT)return reusedif not (request.gguf_variant or is_direct_gguf_request):if (@@ -14472,7 +14695,8 @@ async def _load_model_impl(# Requested chat model already resident: assert CHAT ownership (no-op when held) to correct a drifted owner.# Owns no GPU, so the arbiter would cancel a generation for nothing.if not _resident_audio_holds_no_gpu(backend):- await asyncio.to_thread(acquire_for, CHAT)+ await asyncio.to_thread(acquire_for_request, CHAT)+ account_access.join_resident("chat")return LoadResponse(status = "already_loaded",model = model_log_label if native_grant_backed else backend.active_model_name,@@ -14544,6 +14768,7 @@ async def _load_model_impl(status_code = 400,detail = f"Invalid model identifier: {model_log_label}",)+ await asyncio.to_thread(_require_resolved_base_access, config)# Resolve inherited extras once before command-dependent preflights.extra_llama_args = _resolve_inherited_extra_args(@@ -14641,6 +14866,7 @@ async def _load_model_impl(# Config-resolved dedupe must run first: a duplicate must not refuse/cancel active chats.# Refusal is non-destructive; defer forced cancellation past every remaining rejection.+ account_access.require_idle_other_accounts()if on_reload_confirmed is not None:on_reload_confirmed(cancel = False)cancel_pending = on_reload_confirmed is not None and bool(request.force_cancel_active)@@ -14831,7 +15057,7 @@ async def _load_model_impl(if not allow_gpu_owner_eviction:handoff_kwargs["allow_evict"] = Falseawait asyncio.to_thread(- acquire_for,+ acquire_for_request,CHAT,lambda: gguf_load_stack.enter_context(chat_load_in_flight()),**handoff_kwargs,@@ -15042,6 +15268,11 @@ async def _load_model_impl(llama_backend._is_local_model = bool(native_grant_backed or config.is_local)if _gguf_is_audio:logger.info(f"GGUF model detected as audio: audio_type={_gguf_audio}")+ account_access.publish_resident(+ "chat",+ request.model_path,+ model_log_label if native_grant_backed else public_model_identifier,+ )return _gguf_load_response(llama_backend,@@ -15123,6 +15354,9 @@ async def _load_model_impl(speech_codec_kw = ({"audio_codec_path": speech_codec_path} if speech_codec_path is not None else {})+ # The inference worker is not bound to the account, so refuse here.+ if request.trust_remote_code and managed_remote_code_refused():+ raise HTTPException(status_code = 403, detail = MANAGED_REMOTE_CODE_REFUSAL)try:success = await asyncio.to_thread(backend.load_model,@@ -15218,6 +15452,11 @@ async def _load_model_impl(from core.inference.llama_keepwarm import note_model_loadednote_model_loaded()+ account_access.publish_resident(+ "chat",+ request.model_path,+ model_log_label if native_grant_backed else config.identifier,+ )# Load inference configuration parametersinference_config = load_inference_config(config.identifier)@@ -15320,6 +15559,8 @@ async def _load_model_impl(from core.inference.gpu_arbiter import GpuOwnerBusyErrorfrom utils.transformers_version import SidecarSwapInProgress+ if isinstance(e, account_access.GpuBusyForAnotherAccountError):+ raise account_access.gpu_busy_error() from eif isinstance(e, GpuOwnerBusyError):raiseif isinstance(e, SidecarSwapInProgress):@@ -15495,6 +15736,13 @@ async def validate_model(Checks that ModelConfig.from_identifier() can resolve model_path, but doesNOT load model weights into GPU memory."""+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )+ native_access_deferred = _defers_access_to_native_grant(request)+ if account_access.managed_account() and not native_access_deferred:+ await asyncio.to_thread(account_access.require_model_access, request.model_path)from core.inference.llama_cpp import (LlamaServerNotFoundError,_hf_offline_if_unreachable_for,@@ -15517,6 +15765,8 @@ async def validate_model(resolved_ollama_path = resolved_ollama_path,))+ if native_access_deferred:+ await asyncio.to_thread(account_access.require_model_access, model_identifier)# The frontend validates before it loads, so this needs the same guard as# /load; otherwise the stall just moves here and /load is never reached.@@ -15999,6 +16249,19 @@ async def check_transformers_upgrade_route("""from utils.transformers_version import latest_tier_active_for+ if account_access.managed_account():+ for ref in (+ request.model_name,+ request.model_local_path,+ request.model_snapshot_path,+ request.model_snapshot_repo_id,+ ):+ if isinstance(ref, str) and ref:+ await asyncio.to_thread(account_access.require_model_access, ref)+ # None reads as ambient-authorized downstream and keeps the hub-cache fallback open.+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )model_name = request.model_name# Inspect what the load will open, not what the identifier resolves to today.load_target = await asyncio.to_thread(_upgrade_check_config_target, request)@@ -16102,9 +16365,10 @@ async def check_transformers_upgrade_route()-# studio_router only: admin action, kept off the OpenAI-compatible /v1 mount.@studio_router.post(- "/install-latest-transformers", response_model = InstallLatestTransformersResponse+ "/install-latest-transformers",+ response_model = InstallLatestTransformersResponse,+ dependencies = [Depends(get_current_subject), Depends(auth_policy.require_owner)],)async def install_latest_transformers_route(request: InstallLatestTransformersRequest, current_subject: str = Depends(get_current_subject)@@ -16447,6 +16711,9 @@ async def estimate_memory(fourfold on the cache dtype alone. Where the header cannot supply the dims thisanswers ``kv_estimable = false`` rather than quoting an assumed total."""+ native_access_deferred = _defers_access_to_native_grant(request)+ if account_access.managed_account() and not native_access_deferred:+ await asyncio.to_thread(account_access.require_model_access, request.model_path)from core.inference.llama_cpp import _args_place_tensors_on_cpufrom core.inference.llama_server_args import _effective_tensor_parallel@@ -16464,6 +16731,8 @@ async def estimate_memory(except HTTPException:# An expired lease is not worth a red error under a settings panel.return EstimateMemoryResponse(available = False, reason = "unsupported_source")+ if native_access_deferred:+ await asyncio.to_thread(account_access.require_model_access, model_identifier)# Blank Parallel Slots means the server default (4 in a standard launch), not one,# and /load resolves it the same way: pricing 1 underestimated the KV cache and the@@ -16602,6 +16871,7 @@ async def estimate_memory(@router.post("/unload", response_model = UnloadResponse)+@account_access.gpu_busy_routeasync def unload_model(request: UnloadRequest, current_subject: str = Depends(get_current_subject)):"""Unload a model from memory.@@ -16620,10 +16890,21 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):Unload a model from memory.Routes to the correct backend (llama-server for GGUF, Unsloth otherwise)."""+ if (+ request.cancel_load_request_id is None+ and account_access.managed_account()+ and account_access.release_shared_resident("chat")+ ):+ # Other accounts still share the model: only this account's share ends, nothing is unloaded.+ return UnloadResponse(status = "unloaded", model = request.model_path)+ account_access.require_resident_control(+ "chat", _loaded_slot_ident() if account_access.managed_account() else None+ )# A deliberate unload means "stay unloaded": drop any idle reload stash so the# next /v1 request can't resurrect this model. The idle loop unloads via the# backend directly (not this route), so clearing here never fights keep-warm.from core.inference.llama_keepwarm import inference_lifecycle_gate, note_model_unloaded+try:# Hidden Audio cleanup is cancellation, not a manual eject. Bind it to the# exact client load attempt so a delayed request can never stop a newer@@ -16763,6 +17044,8 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):# loop would block this route's own padding.await asyncio.to_thread(llama_backend.unload_model)note_model_unloaded()+ account_access.clear_resident("chat")+ await asyncio.to_thread(release_chat_gpu_claim)api_monitor.record_lifecycle(event = "unload",model = _lifecycle_model_label(_unloaded, _unloaded_variant),@@ -16788,6 +17071,8 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):backend.unload_model, _resident_standard_model_name(backend, request.model_path))note_model_unloaded()+ account_access.clear_resident("chat")+ await asyncio.to_thread(release_chat_gpu_claim)api_monitor.record_lifecycle(event = "unload",model = _lifecycle_model_label(request.model_path),@@ -16870,6 +17155,8 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):_direct_llama_is_busy(),))+ if account_access.resident_hidden("chat", active_model):+ active_model, context_length = None, Noneactive_requests = api_monitor.active_count(subject = current_subject)# Slots the rows cannot see: direct llama calls (RAG caption/OCR) open no row, logging# may be off, and another subject's work is not counted here. The queue readout beside@@ -16945,6 +17232,10 @@ async def generate_stream(For vision models, provide image_base64 (base64-encoded image)."""+ if account_access.managed_account() and await asyncio.to_thread(+ lambda: account_access.resident_hidden("chat", _loaded_slot_ident())+ ):+ raise HTTPException(status_code = 404, detail = "Model not found")# Enforce the preview-swap reject FIRST, before reading any backend state. If a public# preview loaded a different checkpoint while this native Unsloth request waited on the# keep-warm gate, the middleware flagged the scope; the loaded-model and image-capability@@ -17246,24 +17537,42 @@ async def get_status(current_subject: str = Depends(get_current_subject)):Get current inference backend status.Reports whichever backend (Unsloth or llama-server) is active."""+ if account_access.resident_hidden("chat"):+ return account_access.hidden_chat_status_response()try:llama_backend = get_llama_cpp_backend()+ if account_access.managed_account() and account_access.resident_hidden(+ "chat", _loaded_slot_ident()+ ):+ return account_access.hidden_chat_status_response()# The cold subprocess and GitHub probes must not block the event loop or# consume the default executor used by local token streaming._supports_mtp, _freshness = await asyncio.get_running_loop().run_in_executor(- _STATUS_PROBE_EXECUTOR, _probe_llama_cpp_status, llama_backend+ _STATUS_PROBE_EXECUTOR,+ run_as,+ current_account(),+ _probe_llama_cpp_status,+ llama_backend,)_stale = bool(_freshness.get("stale"))_installed_tag = _freshness.get("installed_tag")_latest_tag = _freshness.get("latest_tag")with _scoped_load_attempts_lock:++ def visible_attempt(attempt):+ return attempt is not None and (+ not account_access.managed_account() or attempt.subject == current_account_id()+ )+_tracked_loading_id = (- _running_load_attempt.model_path if _running_load_attempt is not None else ""+ _running_load_attempt.model_path if visible_attempt(_running_load_attempt) else "")if not _tracked_loading_id:- _queued = next(iter(_pending_load_attempts.values()), None)+ _queued = next(+ (a for a in _pending_load_attempts.values() if visible_attempt(a)), None+ )_tracked_loading_id = _queued.model_path if _queued is not None else ""# The attempt holds what the client sent, which for an on-device model is a path._tracked_loading_id = _loading_public_id(_tracked_loading_id) or ""@@ -17473,6 +17782,8 @@ async def get_load_progress(current_subject: str = Depends(get_current_subject))Returns an empty payload (``phase=null, bytes=0``) when no load is inflight. The frontend should stop polling once ``phase`` becomes ``ready``."""+ if account_access.resident_hidden("chat"):+ return account_access.hidden_resident_response()try:llama_backend = get_llama_cpp_backend()progress = llama_backend.load_progress()@@ -17715,6 +18026,12 @@ async def audio_download_plan(request: LoadRequest, current_subject: str = Depends(get_current_subject)):"""Stage native-audio checkpoints and companion codecs through Download Manager."""+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.model_path)from core.inference.native_audio import native_audio_download_planfrom utils.native_path_leases import redact_native_paths@@ -18299,7 +18616,12 @@ def _prepare_runtime_fallback_checkpoint(if stt_sidecar.is_model_downloaded(model):returntry:- stt_sidecar.start_model_download(model, hf_token)+ if account_access.account_scope() is None:+ stt_sidecar.start_model_download(model, hf_token)+ else:+ _start_account_stt_download(+ stt_sidecar, "transformers", model, account_access.account_hf_token(hf_token)+ )except Exception as exc: # noqa: BLE001 - preparation is best effort, never fatal# Another dictation model already downloading is the common case, and the caller# is about to report "not downloaded" anyway.@@ -18346,6 +18668,161 @@ def _stt_lifecycle() -> tuple:return backend.load_stt_model, backend.unload_stt_model+_stt_download_accounts: dict[str, str] = {}+_stt_download_lock = threading.Lock()+_stt_grant_pending: dict[str, threading.Event] = {}+++def _start_account_stt_download(+ module,+ engine,+ model,+ hf_token,+ revision = None,+):+ args = (model, hf_token, revision) if engine == "transformers" else (model, hf_token)+ if account_access.account_scope() is None:+ return module.start_model_download(*args)+ from core.training.account_jobs import account_is_retired++ with _stt_download_lock:+ # Shares retire_stt_downloads' lock: a start is either swept by it or sees this tombstone.+ if account_is_retired():+ raise HTTPException(status_code = 403, detail = "Account is retired")+ if module.download_status().get("downloading"):+ if _stt_download_accounts.get(engine, OWNER_ACCOUNT_ID) != current_account_id():+ raise HTTPException(+ status_code = 409, detail = {"error": "download_busy", "retry_after": 1}+ )+ return module.start_model_download(*args)+ pending = _stt_grant_pending.get(engine)+ if pending is not None and not pending.is_set():+ raise HTTPException(+ status_code = 409, detail = {"error": "download_busy", "retry_after": 1}+ )+ repo = _stt_repo_reference(model, engine)+ account_access.authorize_download(repo, "model", hf_token)+ module.start_model_download(*args)+ _stt_download_accounts[engine] = current_account_id()+ account = current_account_id()+ settled = _stt_grant_pending[engine] = threading.Event()++ def watch():+ try:+ while True:+ status = module.download_status()+ if not status.get("downloading"):+ break+ time.sleep(0.1)+ if status.get("error") or status.get("cancelled"):+ return+ with _stt_download_lock:+ if _stt_download_accounts.get(engine) != account:+ return+ downloaded = getattr(module, "is_model_downloaded", None)+ complete = (+ downloaded(model)+ if downloaded is not None+ else module._cached_model_path(model) is not None+ )+ if complete:+ account_access.record_model_grant(repo)++ finally:+ settled.set()++ account_thread(target = watch, name = f"stt-grant-{engine}", daemon = True).start()+++def retire_stt_downloads() -> None:+ """Cancel and reap this account's dictation downloads, which keep their own registry."""+ if account_access.account_scope() is None:+ return+ account = current_account_id()+ claimed = []+ with _stt_download_lock:+ for engine, owner in list(_stt_download_accounts.items()):+ if owner != account:+ continue+ module = _stt_download_module(engine)+ try:+ module.cancel_model_download()+ finally:+ _stt_download_accounts.pop(engine, None)+ claimed.append((engine, module))+ stragglers = []+ for engine, module in claimed:+ deadline = time.monotonic() + 10+ while module.download_status().get("downloading"):+ if time.monotonic() >= deadline:+ stragglers.append(engine)+ break+ time.sleep(0.1)+ else:+ _stt_grant_pending.pop(engine, None)+ if stragglers:+ raise RuntimeError(+ f"Retired account dictation downloads have not stopped: {sorted(stragglers)}"+ )+++def _cancel_account_stt_download(module, engine):+ with _stt_download_lock:+ if (+ account_access.account_scope() is not None+ and _stt_download_accounts.get(engine, OWNER_ACCOUNT_ID) != current_account_id()+ ):+ return {"downloading": False, "cancelled": False}+ cancelled = module.cancel_model_download()+ return {**module.download_status(), "cancelled": cancelled}+++def _stt_repo_reference(model, engine):+ from core.inference import stt_ggml_sidecar, stt_mtmd_sidecar, stt_sidecar++ selected = _resolve_serving_stt_engine(engine)+ if selected == "gguf":+ return stt_ggml_sidecar.GGML_STT_REPOS.get(+ model or stt_ggml_sidecar.DEFAULT_GGML_STT_MODEL, model+ )+ if selected == "mtmd":+ spec = stt_mtmd_sidecar.MTMD_STT_MODELS.get(model)+ return spec.repo if spec else model+ return stt_sidecar.resolve_model_repo(model)+++def _stt_resolved_model_id(model, engine):+ """The id the sidecar records for this request, resolved as its loader does."""+ from core.inference import stt_ggml_sidecar, stt_mtmd_sidecar, stt_sidecar+ try:+ if engine == "gguf":+ return stt_ggml_sidecar.resolve_ggml_model_id(model)+ if engine == "mtmd":+ return stt_mtmd_sidecar.resolve_mtmd_model_id(model)+ return stt_sidecar.resolve_model_id(model)+ except Exception: # noqa: BLE001 - an id the loader would refuse is not what it loaded+ return None+++def _account_stt_status(status):+ for engine in ("transformers", "gguf", "mtmd"):+ section = status[engine]+ loaded = section.get("loaded_model")+ if account_access.resident_hidden(f"stt:{engine}", loaded):+ section["loaded_model"] = None+ section["loaded"], section["yours"] = True, False+ if engine == "transformers":+ status["loaded_model"] = None+ section["downloaded_models"] = [+ model+ for model in section.get("downloaded_models", [])+ if account_access.model_visible(_stt_repo_reference(model, engine))+ ]+ if _stt_download_accounts.get(engine, OWNER_ACCOUNT_ID) != current_account_id():+ section["download"] = {"downloading": False}+ return status++@studio_router.get("/audio/stt/status")async def stt_status(model: Optional[str] = None, current_subject: str = Depends(get_current_subject)@@ -18355,6 +18832,10 @@ async def stt_status(``model`` extends the Transformers ``downloaded_models`` check to acustom Hugging Face repository beyond the curated defaults."""+ if account_access.managed_account() and model:+ await asyncio.to_thread(+ account_access.require_model_access, _stt_repo_reference(model, "transformers")+ )from core.inference import stt_ggml_sidecar, stt_mtmd_sidecar, stt_sidecarfrom core.inference.stt_sidecar import (DEFAULT_STT_MODEL,@@ -18371,7 +18852,7 @@ async def stt_status(]if model and model not in STT_MODELS and stt_sidecar.is_model_downloaded(model):transformers_downloaded.append(model)- return JSONResponse(+ response = JSONResponse(content = {"available": is_available(),"loaded_model": sidecar.loaded_model,@@ -18427,6 +18908,11 @@ async def stt_status(},})+ if account_access.managed_account():+ status = json.loads(response.body)+ status = await asyncio.to_thread(_account_stt_status, status)+ return JSONResponse(content = status)+ return response@studio_router.post("/audio/stt/download")@@ -18441,6 +18927,7 @@ async def stt_download(Hub's GGUF variant planner cannot express; a Transformers checkpoint is awhole snapshot). Progress is reported by /audio/stt/status."""+ hf_token = account_access.account_hf_token(hf_token)from core.inference import stt_ggml_sidecar, stt_sidecarfrom core.inference.stt_sidecar import (SttModelCompatibilityError,@@ -18460,13 +18947,17 @@ async def stt_download(# Pin the download to the commit that was just validated so the# repo cannot be swapped between validation and snapshot_download.await asyncio.to_thread(- module.start_model_download,+ _start_account_stt_download,+ module,+ engine,payload.model,hf_token,validated.get("revision"),)else:- await asyncio.to_thread(module.start_model_download, payload.model, hf_token)+ await asyncio.to_thread(+ _start_account_stt_download, module, engine, payload.model, hf_token+ )except SttModelIdError as e:raise HTTPException(status_code = 422, detail = str(e))except SttModelCompatibilityError as e:@@ -18487,10 +18978,8 @@ async def stt_download_cancel(engine = _resolve_serving_stt_engine(payload.engine if payload else None)module = _stt_download_module(engine)- cancelled = await asyncio.to_thread(module.cancel_model_download)- # This request's result last: download_status() carries its own historical- # "cancelled", which would otherwise report a no-op as a cancellation.- return JSONResponse(content = {**module.download_status(), "cancelled": cancelled})+ status = await asyncio.to_thread(_cancel_account_stt_download, module, engine)+ return JSONResponse(content = status)@studio_router.post("/audio/stt/load")@@ -18500,6 +18989,10 @@ async def stt_load(current_subject: str = Depends(get_current_subject),):"""Load the selected STT model after the user starts local dictation."""+ if account_access.managed_account():+ await asyncio.to_thread(+ account_access.require_model_access, _stt_repo_reference(payload.model, payload.engine)+ )from core.inference.stt_sidecar import (SttLoadCancelledError,SttModelBusyError,@@ -18545,7 +19038,15 @@ async def stt_load(raise HTTPException(status_code = 500, detail = safe_error_detail(e))finally:await _stop_local_disconnect_cancel_watcher(disconnect_watcher)- return JSONResponse(content = {"loaded_model": sidecar.loaded_model, "device": sidecar.device})+ # The load lock is released and another account may have switched engines, so claim only ours.+ loaded = sidecar.loaded_model+ if loaded is not None and loaded == _stt_resolved_model_id(payload.model, engine):+ account_access.note_resident_account(f"stt:{engine}", loaded)+ else:+ loaded = None+ return JSONResponse(+ content = {"loaded_model": loaded, "device": sidecar.device if loaded else None}+ )@studio_router.post("/audio/stt/validate")@@ -18555,6 +19056,7 @@ async def stt_validate(hf_token: HfTokenArg = Depends(get_request_hf_token),):"""Verify a Hub repository is a Whisper checkpoint before downloading it."""+ hf_token = account_access.account_hf_token(hf_token)from core.inference.stt_sidecar import (SttModelCompatibilityError,SttModelIdError,@@ -18593,6 +19095,14 @@ async def stt_unload(# actually served by the Transformers fallback, so unload must target# that same engine or the resident model is never freed.engines = [_resolve_serving_stt_engine(engine)]+ if account_access.managed_account():+ engines = [+ candidate+ for candidate in (engines or ["transformers", "gguf", "mtmd"])+ if not account_access.resident_hidden(+ f"stt:{candidate}", _stt_sidecar_for(candidate).loaded_model+ )+ ]# Every engine is attempted even if one raises, so failing to free one never# skips the other (both can be resident after a switch)._, unload_stt = _stt_lifecycle()@@ -18638,6 +19148,10 @@ async def _transcribe_audio_result() -> dict:"""STT for already-decoded bytes, sidecar errors mapped to HTTP statuses.Returns the sidecar's result dict so callers own the response shape."""+ if account_access.managed_account():+ await asyncio.to_thread(+ account_access.require_model_access, _stt_repo_reference(model, engine)+ )from core.inference.stt_sidecar import (SttAudioDecodeError,SttAudioTooLongError,@@ -18681,6 +19195,9 @@ async def _transcribe_audio_result(await asyncio.to_thread(functools.partial(load_stt, model, serving_engine, cancel_event, device = device))+ loaded = getattr(sidecar, "loaded_model", None)+ if loaded is not None and loaded == _stt_resolved_model_id(model, serving_engine):+ account_access.note_resident_account(f"stt:{serving_engine}", loaded)if cancel_event is None:result = await asyncio.to_thread(sidecar.transcribe, raw, model, language, fast)else:@@ -20682,7 +21199,9 @@ async def _proxy_to_external_provider(include_api_key = bool(studio_tool_payloads),)cancel_event = threading.Event()- cancel_keys = tuple(key for key in (payload.cancel_id, payload.session_id) if key)+ cancel_keys = tuple(+ _account_cancel_key(key) for key in (payload.cancel_id, payload.session_id) if key+ )async def _codex_stream():current_access_token = access_token@@ -20750,7 +21269,11 @@ async def _proxy_to_external_provider(_prune_pending(now)for key in cancel_keys:_CANCEL_REGISTRY.setdefault(key, set()).add(cancel_event)- if payload.cancel_id and _PENDING_CANCELS.pop(payload.cancel_id, None) is not None:+ if (+ payload.cancel_id+ and _PENDING_CANCELS.pop(_account_cancel_key(payload.cancel_id), None)+ is not None+ ):should_cancel = Trueif should_cancel:cancel_event.set()@@ -21566,12 +22089,15 @@ class _DroppedFrameKeepalive:@router.post("/chat/completions")+@account_access.gpu_busy_routeasync def openai_chat_completions(payload: ChatCompletionRequest,request: Request,current_subject: str = Depends(get_current_subject),):+ _admit_tool_access(payload)from auth.authentication import request_admitted_without_credential+if (payload.provider_id or payload.provider_type) and request_admitted_without_credential(request):@@ -26023,6 +26549,10 @@ def _openai_model_objects() -> list[dict]:Shared by the LIST and RETRIEVE handlers so both report the same ids andfield shape."""+ if account_access.managed_account() and account_access.resident_hidden(+ "chat", _loaded_slot_ident()+ ):+ return []models: list[dict] = []_created = int(time.time())@@ -26136,15 +26666,15 @@ def _advertised_local_path(model: str) -> Optional[str]:advertised a local model the resolver index has not picked up yet, which isevidence the name means something other than the resident one."""- if _ADVERTISED_CACHE["at"] != _CATALOG_CACHE["at"]:+ if _account_advertised_cache()["at"] != _account_catalog_cache()["at"]:paths = {}- for info in _CATALOG_CACHE["models"] or ():+ for info in _account_catalog_cache()["models"] or ():cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))path = getattr(info, "path", None)if cid and path:paths.setdefault(cid.strip().lower(), path)- _ADVERTISED_CACHE.update(at = _CATALOG_CACHE["at"], paths = paths)- return _ADVERTISED_CACHE["paths"].get(model.strip().lower())+ _account_advertised_cache().update(at = _account_catalog_cache()["at"], paths = paths)+ return _account_advertised_cache()["paths"].get(model.strip().lower())_CATALOG_TTL_S = 30.0@@ -26156,6 +26686,23 @@ _catalog_locks: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()_catalog_locks_guard = threading.Lock()+_managed_catalogs: dict[str, dict] = {}+_managed_catalogs_lock = threading.Lock()+++def _account_catalog_cache():+ if not account_access.managed_account():+ return _CATALOG_CACHE+ with _managed_catalogs_lock:+ return _managed_catalogs.setdefault(current_account_id(), {"at": 0.0, "models": []})+++def _account_advertised_cache():+ if not account_access.managed_account():+ return _ADVERTISED_CACHE+ return _account_catalog_cache().setdefault("advertised", {"at": None, "paths": {}})++def _catalog_lock() -> asyncio.Lock:loop = asyncio.get_running_loop()with _catalog_locks_guard:@@ -26193,13 +26740,18 @@ def _media_owner(task: str) -> str:def _resident_media_status(task: str) -> Optional[dict]:+ if account_access.resident_hidden(_media_owner(task)):+ return Nonefrom core.inference.media_keepwarm import engine_if_imported+try:engine = engine_if_imported(_media_owner(task))status = engine.status() if engine is not None else Noneexcept Exception as exc: # noqa: BLE001logger.debug("%s status unavailable for /v1/models: %s", task, exc)return None+ if status and account_access.resident_hidden(_media_owner(task), status.get("repo_id")):+ return Nonereturn status if status and status.get("loaded") else None@@ -26280,6 +26832,10 @@ def _media_model_objects(catalog: list, created: int, catalog_at: float) -> listfor task in _MEDIA_MODEL_TASKS:status = _resident_media_status(task)for model_id, pick, local in picks_by_task.get(task, ()):+ if account_access.managed_account() and not account_access.model_visible(+ pick.model_path+ ):+ continueloaded = bool(status) and satisfied_by(status, model_id, pick)if not loaded and not local:continue@@ -26419,6 +26975,13 @@ def _stt_model_objects(created: int, catalog_at: Optional[float] = None) -> listquant = extract_quant_token(spec.model_file)if quant:obj["quant"] = quant+ if account_access.managed_account():+ repo = spec.repo if spec is not None else model_id+ if not account_access.model_visible(repo):+ continue+ engine = "mtmd" if spec is not None else "transformers"+ if account_access.resident_hidden(f"stt:{engine}", model_id):+ obj["loaded"] = Falseobjects.append(obj)return objects@@ -26435,24 +26998,27 @@ async def _cached_local_catalog() -> list:# Validity is keyed on "at" (set only after a scan), not on list contents, so# an empty/errored scan is still cached instead of rescanning on every poll.now = time.monotonic()- if _CATALOG_CACHE["at"] and (now - _CATALOG_CACHE["at"]) <= _CATALOG_TTL_S:- return _CATALOG_CACHE["models"]+ if _account_catalog_cache()["at"] and (now - _account_catalog_cache()["at"]) <= _CATALOG_TTL_S:+ return _account_catalog_cache()["models"]async with _catalog_lock():now = time.monotonic()- if _CATALOG_CACHE["at"] and (now - _CATALOG_CACHE["at"]) <= _CATALOG_TTL_S:- return _CATALOG_CACHE["models"]+ if (+ _account_catalog_cache()["at"]+ and (now - _account_catalog_cache()["at"]) <= _CATALOG_TTL_S+ ):+ return _account_catalog_cache()["models"]try:from routes.models import collect_local_models- _CATALOG_CACHE["models"] = await asyncio.to_thread(+ _account_catalog_cache()["models"] = await asyncio.to_thread(lambda: _classified_catalog(collect_local_models(Path("./models").resolve())))except Exception as exc:logger.debug("model catalog scan failed: %s", exc)- _CATALOG_CACHE["models"] = []+ _account_catalog_cache()["models"] = []# Stamp after the scan, not the pre-scan "now": a scan slower than the TTL# would otherwise leave the cache already expired, so every waiter rescans.- _CATALOG_CACHE["at"] = time.monotonic()- return _CATALOG_CACHE["models"]+ _account_catalog_cache()["at"] = time.monotonic()+ return _account_catalog_cache()["models"]# One tuple, published in a single assignment: the fast path below reads it without the@@ -26631,10 +27197,15 @@ async def _openai_catalog_objects() -> list[dict]:# Downloaded but unloaded: GGUF via llama.cpp, other weights via the orchestrator.catalog = await _cached_local_catalog()- catalog_at = _CATALOG_CACHE["at"]- for info, is_gguf, quants, loaded in await asyncio.to_thread(- _servable_catalog_rows, catalog, catalog_at- ):+ catalog_at = _account_catalog_cache()["at"]+ rows = await asyncio.to_thread(_servable_catalog_rows, catalog, catalog_at)+ if account_access.managed_account():+ catalog = await asyncio.to_thread(account_access.filter_model_rows, catalog)+ visible = {id(info) for info in catalog}+ rows = [row for row in rows if id(row[0]) in visible]+ for info, is_gguf, quants, loaded in rows:+ if account_access.resident_hidden("chat"):+ loaded = Falsecid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))if not cid or cid in by_id:continue@@ -26663,8 +27234,8 @@ async def _openai_catalog_objects() -> list[dict]:media = await asyncio.to_thread(lambda: (- _media_model_objects(catalog, _created, _CATALOG_CACHE["at"])- + _stt_model_objects(_created, _CATALOG_CACHE["at"])+ _media_model_objects(catalog, _created, _account_catalog_cache()["at"])+ + _stt_model_objects(_created, _account_catalog_cache()["at"])))for obj in media:@@ -26782,6 +27353,7 @@ def _completions_prompt_present(body: dict) -> bool:@router.post("/completions")+@account_access.gpu_busy_routeasync def openai_completions(request: Request, current_subject: str = Depends(get_current_subject)):"""OpenAI-compatible text completions endpoint (non-chat).@@ -27501,6 +28073,7 @@ def _embeddings_input_present(body: dict) -> bool:@router.post("/embeddings")+@account_access.gpu_busy_routeasync def openai_embeddings(request: Request, current_subject: str = Depends(get_current_subject)):"""OpenAI-compatible embeddings: the resident embedding GGUF when one is loaded,else Studio's configured embedding model."""@@ -29796,6 +30369,7 @@ async def _responses_stream(@router.post("/responses")+@account_access.gpu_busy_routeasync def openai_responses(payload: ResponsesRequest,request: Request,@@ -29808,6 +30382,7 @@ async def openai_responses(internally, and returns a response matching the Responses API schema(output array, input_tokens/output_tokens, named SSE events for streaming)."""+ _admit_tool_access(payload)for history_param in ("previous_response_id", "conversation"):if getattr(payload, history_param, None) is not None:raise HTTPException(@@ -30448,6 +31023,10 @@ async def chat_count_tokens(Unlike the /v1 count endpoints this never auto-switches: ``model`` is informational. Thecaller is a background recount with no abort signal, so switching could drag the backend backto the model loaded when the count started, a reload the client's guards cannot undo."""+ if account_access.managed_account() and await asyncio.to_thread(+ lambda: account_access.resident_hidden("chat", _loaded_slot_ident())+ ):+ raise HTTPException(status_code = 404, detail = "Model not found")# Admitted only while nothing generates, and stood down at the next checkpoint if that changes:# admission is not atomic with the work, and true mutual exclusion would put a lock in front of# generation startup, which is the cost this avoids. Refusing here also covers the second tab or@@ -30823,6 +31402,7 @@ def _set_or_prepend_system_message(@router.post("/messages")+@account_access.gpu_busy_routeasync def anthropic_messages(payload: AnthropicMessagesRequest,request: Request,@@ -30836,6 +31416,7 @@ async def anthropic_messages(responses in Anthropic Messages API format (streaming SSE or non-streamingJSON)."""+ _admit_tool_access(payload)llama_backend = get_llama_cpp_backend()# Default-off parity: with no automatic load possible and nothing loaded, 503@@ -35220,6 +35801,17 @@ async def diffusion_download_plan(Validates the same way /images/load does, so an unloadable pick fails here rather thanafter a multi-GB download."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_references, request)+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.model_path)+ if request.base_repo:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.base_repo)+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )from core.inference.diffusion import (get_diffusion_backend,resolve_local_single_file,@@ -35363,6 +35955,7 @@ def _assert_native_precision_unset(@studio_router.post("/images/load", response_model = DiffusionStatusResponse)+@account_access.gpu_busy_routeasync def load_diffusion_model(request: DiffusionLoadRequest, current_subject: str = Depends(get_current_subject)):@@ -35380,6 +35973,18 @@ async def load_diffusion_model_gated(Media auto-switch awaits this rather than the route so the idle unload can tell anAPI-loaded pipeline from one the user picked on the Images page."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_references, request)+ account_access.require_idle_other_accounts()+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.model_path)+ if request.base_repo:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.base_repo)+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )from core.inference.diffusion import (get_diffusion_backend,resolve_local_single_file,@@ -35397,7 +36002,12 @@ async def load_diffusion_model_gated(predict_engine,select_and_activate_engine,)- from core.inference.gpu_arbiter import acquire_for, release, DIFFUSION+ from core.inference.gpu_arbiter import (+ acquire_for_request,+ require_no_foreign_generations,+ release,+ DIFFUSION,+ )from core.inference.media_keepwarm import note_load_origin as note_media_load_originfrom hub.utils.gguf import extract_quant_tokenfrom core.inference.sd_cpp_engine import ENGINE_DIFFUSERS, ENGINE_SD_CPP@@ -35501,6 +36111,8 @@ async def load_diffusion_model_gated(preflighted = engine_for(pending_name)await asyncio.to_thread(_preflight, preflighted)+ # begin_load signals whatever generation is running, so guard on every device, not just GPU.+ require_no_foreign_generations()# Pick the engine for this host (diffusers on GPU, native sd.cpp otherwise), installing sd-cli if needed, BEFORE evicting chat.engine = await asyncio.to_thread(select_and_activate_engine, fam, hf_token = request.hf_token, model_kind = kind@@ -35567,14 +36179,19 @@ async def load_diffusion_model_gated(def _begin_load():# Under the router transition lock: begin_load on a deactivated engine leaves a resident model nothing can reach.- return begin_load_on(engine, _start_engine_load)+ return begin_load_on(+ engine,+ lambda: account_access.admit_media_load(+ "diffusion", _start_engine_load, request.model_path+ ),+ )if needs_gpu:# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts DIFFUSION before# the load is marked, finds nothing to cancel, and both allocate at once. The training admission wraps the same span.def _acquire_and_begin():with _diffusion_training_admission():- return acquire_for(DIFFUSION, _begin_load)+ return acquire_for_request(DIFFUSION, _begin_load)status_dict = await asyncio.to_thread(_acquire_and_begin)else:@@ -35589,10 +36206,18 @@ async def load_diffusion_model_gated(extract_quant_token(request.gguf_filename) if kind == "gguf" else None,user_action = user_initiated,)+ account_access.note_resident_components(+ "diffusion",+ request.model_path,+ request.base_repo,+ *account_access.media_adapter_references(request),+ )reset_media_load_progress("image")return DiffusionStatusResponse(**annotate_status(status_dict))except (ValueError, FileNotFoundError) as exc:raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))+ except account_access.GpuBusyForAnotherAccountError as exc:+ raise account_access.gpu_busy_error() from excexcept RuntimeError as exc:# A load is already in progress.raise HTTPException(status_code = 409, detail = str(exc))@@ -35643,6 +36268,7 @@ def _generate_failure_detail(message: str) -> str:@studio_router.post("/images/generate", response_model = DiffusionGenerateResponse)+@account_access.gpu_busy_routeasync def generate_diffusion_image(request: DiffusionGenerateRequest, current_subject: str = Depends(get_current_subject)):@@ -35651,58 +36277,78 @@ async def generate_diffusion_image(from core.inference.diffusion_families import (DIFFUSION_CANCELLED_MSG,DIFFUSION_NOT_LOADED_MSG,+ DiffusionModelReplacedError,+ load_identity,)backend = get_active_diffusion_engine()- # Ahead of the run, like the video route: milestones are keyed on the previous poll, so a- # run starting at or above where the last one stopped would read as it and log nothing.- reset_media_generation_progress("image")- try:- result = await asyncio.to_thread(- backend.generate,- prompt = request.prompt,- negative_prompt = request.negative_prompt,- width = request.width,- height = request.height,- steps = request.steps,- guidance = request.guidance,- seed = request.seed,- batch_size = request.batch_size,- prompts = request.prompts,- seeds = request.seeds,- init_image = request.init_image,- mask_image = request.mask_image,- strength = request.strength,- upscale = request.upscale,- reference_images = request.reference_images,- loras = [(l.id, l.weight) for l in request.loras] if request.loras else None,- controlnet = (- (- request.controlnet.id,- request.controlnet.image,- request.controlnet.control_type,- request.controlnet.strength,- request.controlnet.guidance_start,- request.controlnet.guidance_end,+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_adapters, request)+ result = None+ for attempt in range(2):+ expected_load = None+ if account_access.managed_account():+ status = backend.status()+ await asyncio.to_thread(+ account_access.require_media_generation_access, status, "diffusion"+ )+ if status.get("loaded"):+ expected_load = load_identity(+ status.get("repo_id"), status.get("base_repo"), status.get("family"))- if request.controlnet- else None- ),- )- except ValueError as exc:- # Bad client input (undecodable image/mask, or an unsupported workflow): a 400 with the reason, not a generic 500.- raise HTTPException(status_code = 400, detail = str(exc))- except RuntimeError as exc:- # Only "no model loaded" / user-cancelled are client-state (409); both engines raise these two EXACT messages. The- # native engine also raises RuntimeError for failures whose text embeds the sd-cli tail, so match the sentinels exactly.- msg = str(exc)- if msg in (DIFFUSION_NOT_LOADED_MSG, DIFFUSION_CANCELLED_MSG):- raise HTTPException(status_code = 409, detail = msg)- logger.error("diffusion.generate_failed: %s", exc, exc_info = True)- raise HTTPException(status_code = 500, detail = _generate_failure_detail(msg))- except Exception as exc:- logger.error("diffusion.generate_failed: %s", exc, exc_info = True)- raise HTTPException(status_code = 500, detail = "Image generation failed.")+ # Ahead of the run: milestones key off the previous poll, so a resumed range logs nothing.+ reset_media_generation_progress("image")+ try:+ with account_access.media_generation("diffusion"):+ result = await asyncio.to_thread(+ backend.generate,+ expected_load = expected_load,+ prompt = request.prompt,+ negative_prompt = request.negative_prompt,+ width = request.width,+ height = request.height,+ steps = request.steps,+ guidance = request.guidance,+ seed = request.seed,+ batch_size = request.batch_size,+ prompts = request.prompts,+ seeds = request.seeds,+ init_image = request.init_image,+ mask_image = request.mask_image,+ strength = request.strength,+ upscale = request.upscale,+ reference_images = request.reference_images,+ loras = [(l.id, l.weight) for l in request.loras] if request.loras else None,+ controlnet = (+ (+ request.controlnet.id,+ request.controlnet.image,+ request.controlnet.control_type,+ request.controlnet.strength,+ request.controlnet.guidance_start,+ request.controlnet.guidance_end,+ )+ if request.controlnet+ else None+ ),+ )+ break+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc))+ except DiffusionModelReplacedError as exc:+ if attempt > 0:+ raise HTTPException(status_code = 409, detail = str(exc))+ continue+ except RuntimeError as exc:+ # Match these two EXACT client-state messages (409); other RuntimeErrors are failures.+ msg = str(exc)+ if msg in (DIFFUSION_NOT_LOADED_MSG, DIFFUSION_CANCELLED_MSG):+ raise HTTPException(status_code = 409, detail = msg)+ logger.error("diffusion.generate_failed: %s", exc, exc_info = True)+ raise HTTPException(status_code = 500, detail = _generate_failure_detail(msg))+ except Exception as exc:+ logger.error("diffusion.generate_failed: %s", exc, exc_info = True)+ raise HTTPException(status_code = 500, detail = "Image generation failed.")# Persist each image with its full recipe. BOTH engines batch with a distinct seed per image, returned in ``seeds``, so each is individually reproducible.created_at = time.time()@@ -35784,7 +36430,8 @@ async def generate_diffusion_image(global _diffusion_persist_active_diffusion_persist_active += 1try:- records = await asyncio.to_thread(_persist)+ with account_access.media_generation("diffusion"):+ records = await asyncio.to_thread(_persist)except Exception as exc:logger.error("diffusion.persist_failed: %s", exc)raise HTTPException(status_code = 500, detail = "Failed to save the generated image.")@@ -36055,11 +36702,20 @@ async def clear_gallery_audio(current_subject: str = Depends(get_current_subject@studio_router.post("/images/unload", response_model = DiffusionStatusResponse)+@account_access.gpu_busy_routeasync def unload_diffusion_model(current_subject: str = Depends(get_current_subject)):+ account_access.require_resident_control("diffusion")from core.inference.diffusion_engine_router import annotate_status, get_active_diffusion_enginefrom core.inference.gpu_arbiter import release_if, DIFFUSION- status_dict = await asyncio.to_thread(get_active_diffusion_engine().unload)+ if account_access.managed_account():+ account_access.require_resident_control(+ "diffusion", get_active_diffusion_engine().status().get("repo_id")+ )+ unload = get_active_diffusion_engine().unload+ if account_access.account_scope() is not None:+ unload = functools.partial(unload, expected_account = current_account_id())+ status_dict = await asyncio.to_thread(unload)# Drop DIFFUSION ownership only if nothing is resident AND no load is in flight, or a later chat load skips eviction and# OOMs the new pipeline. An in-flight load reads is_loaded False, so gate on loading_repo_ids() and use release_if.engine = get_active_diffusion_engine()@@ -36073,8 +36729,14 @@ async def unload_diffusion_model(current_subject: str = Depends(get_current_subj@studio_router.get("/images/status", response_model = DiffusionStatusResponse)async def diffusion_status(current_subject: str = Depends(get_current_subject)):+ if account_access.resident_hidden("diffusion"):+ return account_access.hidden_resident_response()from core.inference.diffusion_engine_router import active_status- return DiffusionStatusResponse(**active_status())++ status_dict = active_status()+ if account_access.resident_hidden("diffusion", status_dict.get("repo_id")):+ return account_access.hidden_resident_response()+ return DiffusionStatusResponse(**status_dict)@studio_router.get("/images/info", response_model = DiffusionInferenceInfoResponse)@@ -36089,8 +36751,14 @@ async def diffusion_inference_info(current_subject: str = Depends(get_current_su@studio_router.get("/images/load-progress", response_model = DiffusionLoadProgressResponse)async def diffusion_load_progress(current_subject: str = Depends(get_current_subject)):+ if account_access.resident_hidden("diffusion"):+ return account_access.hidden_resident_response()from core.inference.diffusion_engine_router import get_active_diffusion_engine+ if account_access.managed_account() and account_access.resident_hidden(+ "diffusion", get_active_diffusion_engine().status().get("repo_id")+ ):+ return account_access.hidden_resident_response()progress = get_active_diffusion_engine().load_progress()log_media_load_progress("image", progress.get("phase"), progress.get("fraction"))return DiffusionLoadProgressResponse(**progress)@@ -36098,8 +36766,22 @@ async def diffusion_load_progress(current_subject: str = Depends(get_current_sub@studio_router.get("/images/generate-progress", response_model = DiffusionGenerateProgressResponse)async def diffusion_generate_progress(current_subject: str = Depends(get_current_subject)):+ if account_access.managed_account() and account_access.generation_is_foreign("diffusion"):+ return account_access.hidden_resident_response()+ mine = account_access.generation_is_mine("diffusion")+ if not mine and account_access.resident_hidden("diffusion"):+ return account_access.hidden_resident_response()from core.inference.diffusion_engine_router import get_active_diffusion_engine+ if (+ not mine+ and account_access.managed_account()+ and account_access.resident_hidden(+ "diffusion", get_active_diffusion_engine().status().get("repo_id")+ )+ ):+ return account_access.hidden_resident_response()+progress = get_active_diffusion_engine().generate_progress()log_media_generation_progress("image", progress)# A finished generation still persisting its gallery record counts as active, so a reload probe keeps polling.@@ -36118,11 +36800,30 @@ async def cancel_diffusion_generation(current_subject: str = Depends(get_currentsentinel, which this module already maps to a 409. ``cancelled`` is False when nothing wasrunning, so the page can settle its button back to Generate rather than wait for ageneration that already finished."""+ if account_access.generation_is_foreign("diffusion"):+ return {"cancelled": False}+ mine = account_access.generation_is_mine("diffusion")+ if not mine and (+ account_access.foreign_work_active() or account_access.resident_hidden("diffusion")+ ):+ return {"cancelled": False}from core.inference.diffusion_engine_router import get_active_diffusion_engine- cancelled = await asyncio.get_running_loop().run_in_executor(- _CANCEL_EXECUTOR, get_active_diffusion_engine().cancel_generate- )+ if (+ not mine+ and account_access.managed_account()+ and account_access.resident_hidden(+ "diffusion", get_active_diffusion_engine().status().get("repo_id")+ )+ ):+ return {"cancelled": False}++ # The slot can change hands before the executor callback, so the engine rechecks under the lock.+ expected = account_access.tracked_generation_account()+ cancel = get_active_diffusion_engine().cancel_generate+ if expected is not None:+ cancel = functools.partial(cancel, expected_account = expected)+ cancelled = await asyncio.get_running_loop().run_in_executor(_CANCEL_EXECUTOR, cancel)return {"cancelled": cancelled}@@ -36166,7 +36867,7 @@ _IMAGE_LINK_SECRET = _secrets.token_bytes(32)def _sign_image_id(image_id: str) -> str:exp = int(time.time()) + _IMAGE_LINK_TTL- payload = f"{image_id}.{exp}"+ payload = f"{media_link_target(image_id)}.{exp}"sig = _hmac.new(_IMAGE_LINK_SECRET, payload.encode(), _hashlib.sha256).hexdigest()return f"{payload}.{sig}"@@ -36208,9 +36909,10 @@ async def get_gallery_image_file_signed(image_id: str, token: str = Query(...)):authenticated route, and the token names the single image it may serve."""from core.inference import image_gallery- if _verify_image_link_token(token) != image_id:+ account = media_link_account(_verify_image_link_token(token), image_id)+ if account is None:raise HTTPException(status_code = 401, detail = "Invalid or expired image link.")- path = await asyncio.to_thread(image_gallery.owned_image_path, image_id)+ path = await asyncio.to_thread(run_as, account, image_gallery.owned_image_path, image_id)if path is None:raise HTTPException(status_code = 404, detail = "Image not found.")data = await asyncio.to_thread(path.read_bytes)@@ -36226,6 +36928,7 @@ async def get_gallery_image_file_signed(image_id: str, token: str = Query(...)):response_model = ImageGenerationResponse,response_model_exclude_none = True,)+@account_access.gpu_busy_routeasync def openai_image_generations(body: ImageGenerationRequest,request: Request,@@ -36319,6 +37022,11 @@ async def _generate_openai_images(# Mirror /v1/completions and /v1/embeddings, which 503 when their backend is not loaded.raise HTTPException(status_code = 503, detail = _NO_IMAGE_MODEL_MSG)+ if account_access.managed_account():+ await asyncio.to_thread(+ account_access.require_media_generation_access, status, "diffusion"+ )+# An edit-only model needs an input image this API cannot supply; refuse with a 400 rather than a backend 500.workflows = status.get("workflows") or []if workflows and "txt2img" not in workflows:@@ -36336,18 +37044,19 @@ async def _generate_openai_images(steps, guidance = default_generation_params(status.get("repo_id"), status.get("base_repo"))reset_media_generation_progress("image")try:- result = await asyncio.to_thread(- backend.generate,- prompt = body.prompt,- width = width,- height = height,- steps = steps,- guidance = guidance,- batch_size = body.n,- expected_load = load_identity(- status.get("repo_id"), status.get("base_repo"), status.get("family")- ),- )+ with account_access.media_generation("diffusion"):+ result = await asyncio.to_thread(+ backend.generate,+ prompt = body.prompt,+ width = width,+ height = height,+ steps = steps,+ guidance = guidance,+ batch_size = body.n,+ expected_load = load_identity(+ status.get("repo_id"), status.get("base_repo"), status.get("family")+ ),+ )breakexcept DiffusionModelReplacedError:if attempt > 0:@@ -36432,7 +37141,8 @@ async def _generate_openai_images(global _diffusion_persist_active_diffusion_persist_active += 1try:- data = await asyncio.to_thread(_persist)+ with account_access.media_generation("diffusion"):+ data = await asyncio.to_thread(_persist)except Exception as exc: # noqa: BLE001logger.error("openai_images.persist_failed: %s", exc)raise HTTPException(status_code = 500, detail = "Failed to save the generated image.")diff --git a/studio/backend/routes/llama.py b/studio/backend/routes/llama.pyindex 4367c37b974..89ccfe1014b 100644--- a/studio/backend/routes/llama.py+++ b/studio/backend/routes/llama.py@@ -25,6 +25,7 @@ from typing import Literal, Optionalfrom fastapi import APIRouter, Depends, Queryfrom pydantic import BaseModel, Field+from auth import policyfrom auth.authentication import get_current_subjectfrom loggers import get_loggerfrom utils.llama_cpp_update import (@@ -197,7 +198,12 @@ async def llama_update_status(return resp[email protected]("/update", response_model = LlamaUpdateActionResponse)+# Replaces the installation's llama and whisper executables for everyone, so it is owner-only.+ "/update",+ response_model = LlamaUpdateActionResponse,+ dependencies = [Depends(get_current_subject), Depends(policy.require_owner)],+)async def llama_update(current_subject: str = Depends(get_current_subject),) -> LlamaUpdateActionResponse:@@ -301,7 +307,11 @@ async def llama_backend_status(return LlamaBackendStatusResponse(**status)[email protected]("/backend", response_model = LlamaUpdateActionResponse)+ "/backend",+ response_model = LlamaUpdateActionResponse,+ dependencies = [Depends(get_current_subject), Depends(policy.require_owner)],+)async def llama_backend_switch(request: LlamaBackendRequest, current_subject: str = Depends(get_current_subject)) -> LlamaUpdateActionResponse:diff --git a/studio/backend/routes/llama_compat.py b/studio/backend/routes/llama_compat.pyindex 95cb9844c47..3d1f08b17f1 100644--- a/studio/backend/routes/llama_compat.py+++ b/studio/backend/routes/llama_compat.py@@ -175,10 +175,27 @@ def _server_props() -> dict:@router.get("/v1/props", include_in_schema = False)@router.get("/v1/props/", include_in_schema = False)async def llama_props(current_subject: str = Depends(get_current_subject)):- """llama-server-compatible ``GET /props``."""+ """llama-server-compatible ``GET /props``. The body reveals the resident model, so another account gets the same answer ``/api/inference/status`` gives it."""+ if await asyncio.to_thread(_resident_hidden_from_caller):+ from hub.services.models.account_access import hidden_resident_response+ return hidden_resident_response()return await asyncio.to_thread(_server_props)+def _resident_hidden_from_caller() -> bool:+ from hub.services.models import account_access++ if not account_access.managed_account():+ return False+ if account_access.resident_hidden("chat"):+ return True+ try:+ slot = _inference()._loaded_slot_ident()+ except Exception: # noqa: BLE001 - a backend that cannot say has nothing to hide+ return False+ return bool(slot) and account_access.resident_hidden("chat", slot)++@router.get("/version", include_in_schema = False)@router.get("/version/", include_in_schema = False)async def studio_version(current_subject: str = Depends(get_current_subject)):diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex f58f82a2f60..099bb3c5b6f 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -55,7 +55,8 @@ from utils.utils import safe_curated_detail, log_and_http_errorlogger = structlog.get_logger(__name__)-router = APIRouter()++router = APIRouter(dependencies = [Depends(get_current_subject)])# Only a UI session may define a local command; API keys keep http(s) MCP. Annotated, not a Depends default:# these routes are also called directly by the tests, where a Depends object is truthy and would read as "API key".diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 770e5fd9b50..9fac18afea8 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -7,7 +7,6 @@ import jsonimport osimport shutilimport sys-import threadingimport timeimport uuidimport weakref@@ -24,6 +23,7 @@ from core.inference.memory_contract import (project_kv_cache_estimate,)from core.inference.model_ids import display_model_name+from hub.services.models import account_accessfrom hub.services.models import catalog_classification as _catalog_classificationfrom utils import gguf_archs as _gguf_archsfrom hub.services.models.catalog_classification import (@@ -71,6 +71,7 @@ _gguf_family_buildable = _catalog_classification._gguf_family_buildable_is_h3_bundle_gguf_hint = _catalog_classification._is_h3_bundle_gguf_hintSPEECH_GGUF_ARCHS = _gguf_archs.SPEECH_GGUF_ARCHSis_speech_gguf_architecture = _gguf_archs.is_speech_gguf_architecture+from utils.account_context import account_threadfrom utils.utils import canonical_model_repo_id, log_and_http_errorimport re as _re@@ -207,6 +208,7 @@ def _resolve_hub_token(header_token: HfTokenArg, query_token: Optional[str]) ->returning ``header_token`` itself would return whatever a caller that bypassedFastAPI's injection left in the parameter -- an unresolved ``Depends`` object."""+ header_token = account_access.account_hf_token(header_token)header_explicit = _normalize_hf_token(header_token)if header_explicit:return header_explicit@@ -1377,6 +1379,8 @@ async def list_local_models(try:models = await _shared_compat_local_inventory_scan(models_root, sources)+ if account_access.managed_account():+ models = await asyncio.to_thread(account_access.filter_model_rows, models)return LocalModelListResponse(models_dir = str(models_root),hf_cache_dir = str(hf_cache_dir),@@ -1410,6 +1414,8 @@ async def add_scan_folder_endpoint(body: AddScanFolderRequest, current_subject: str = Depends(get_current_subject)):"""Register a new directory to scan for local models."""+ if account_access.managed_account():+ body = body.model_copy(update = {"path": account_access.private_directory(body.path, "")})from storage.studio_db import add_scan_folder_with_statustry:@@ -1532,6 +1538,7 @@ async def get_recommended_folders(current_subject: str = Depends(get_current_subweights are returned, so an empty LM Studio/Ollama scaffold no longershows up as a suggestion."""+ account_access.require_installation_owner()from utils.paths.storage_roots import lmstudio_model_dirsfolders: list[str] = []@@ -1963,6 +1970,11 @@ def browse_folders(so traversal can't escape. Sorting: model-bearing dirs, then plain,then hidden (if ``show_hidden=true``)."""+ from utils.paths.storage_roots import workspace_root++ managed = account_access.managed_account()+ if managed:+ path = account_access.private_directory(path or str(workspace_root()), "")from utils.paths import hf_default_cache_dir, well_known_model_dirsfrom utils.paths import external_mediafrom storage.studio_db import (@@ -1972,12 +1984,21 @@ def browse_folders()# Probe removable-media and Windows drive roots once; allowlist and chips reuse the result.- media_roots = [- *external_media.linux_run_media_mount_roots(),- *external_media.macos_volume_roots(),- ]- drive_roots = external_media.windows_drive_roots()- allowed_roots = _build_browse_allowlist(media_roots, drive_roots)+ # A managed account browses its workspace only, and its chips name nothing outside it.+ media_roots = (+ []+ if managed+ else [+ *external_media.linux_run_media_mount_roots(),+ *external_media.macos_volume_roots(),+ ]+ )+ drive_roots = [] if managed else external_media.windows_drive_roots()+ allowed_roots = (+ [workspace_root().resolve()]+ if managed+ else _build_browse_allowlist(media_roots, drive_roots)+ )try:target = _resolve_browse_target(path, allowed_roots)@@ -2086,25 +2107,29 @@ def browse_folders(seen_sug.add(resolved)suggestions.append(resolved)- _add_sug(Path.home())- for p in media_roots:- _add_sug(p)- for p in drive_roots:- _add_sug(p)- try:- _add_sug(hf_default_cache_dir())- except Exception:- pass- try:- for folder in list_scan_folders():- _add_sug(Path(folder.get("path", "")))- except Exception as exc:- logger.debug("browse-folders: could not load scan folders: %s", exc)- try:- for p in well_known_model_dirs():+ if managed:+ for root in allowed_roots:+ _add_sug(root)+ else:+ _add_sug(Path.home())+ for p in media_roots:+ _add_sug(p)+ for p in drive_roots:_add_sug(p)- except Exception as exc:- logger.debug("browse-folders: could not load well-known dirs: %s", exc)+ try:+ _add_sug(hf_default_cache_dir())+ except Exception:+ pass+ try:+ for folder in list_scan_folders():+ _add_sug(Path(folder.get("path", "")))+ except Exception as exc:+ logger.debug("browse-folders: could not load scan folders: %s", exc)+ try:+ for p in well_known_model_dirs():+ _add_sug(p)+ except Exception as exc:+ logger.debug("browse-folders: could not load well-known dirs: %s", exc)return BrowseFoldersResponse(current = str(target),@@ -2133,9 +2158,20 @@ async def list_models(current_subject: str = Depends(get_current_subject)):inference_backend = await asyncio.to_thread(get_inference_backend)default_models = inference_backend.default_models+ if account_access.managed_account():+ default_models = [+ m+ for m in default_models+ if await asyncio.to_thread(account_access.model_visible, m)+ ]loaded_models = []+ hide_resident = account_access.resident_hidden(+ "chat", getattr(inference_backend, "active_model_name", None)+ )for model_name, model_data in inference_backend.models.items():+ if hide_resident:+ continue_is_vision = model_data.get("is_vision", False)_audio_type = model_data.get("audio_type")model_info = ModelDetails(@@ -2156,7 +2192,10 @@ async def list_models(current_subject: str = Depends(get_current_subject)):from routes.inference import _llama_status_model_ids, get_llama_cpp_backendllama_backend = get_llama_cpp_backend()- if llama_backend.is_loaded and llama_backend.model_identifier:+ hide_resident = hide_resident or account_access.resident_hidden(+ "chat", getattr(llama_backend, "model_identifier", None)+ )+ if not hide_resident and llama_backend.is_loaded and llama_backend.model_identifier:display_id, _reported_identifier = _llama_status_model_ids(llama_backend)loaded_models.append(ModelDetails(@@ -2313,6 +2352,32 @@ def _model_config_inspection_target(return snapshot+async def _require_model_access_or_caller_token(+ model_name: str,+ hf_token,+ *,+ local_path: Optional[str] = None,+ prefer_local_cache: bool = False,+) -> None:+ """Managed access check that also accepts the caller's own Hub token, since a remote preflight+ precedes the first download and its grant. Local and cache-only selections keep the check."""+ if not account_access.managed_account():+ return+ try:+ await asyncio.to_thread(account_access.require_model_access, model_name)+ except HTTPException as exc:+ if (+ exc.status_code != 404+ or local_path+ or prefer_local_cache+ or is_local_path(model_name)+ or not isinstance(hf_token, str)+ or not hf_token.strip()+ ):+ raise+ await asyncio.to_thread(account_access.authorize_download, model_name, "model", hf_token)++@router.get("/config/{model_name:path}")async def get_model_config(model_name: str,@@ -2324,9 +2389,18 @@ async def get_model_config(current_subject: str = Depends(get_current_subject),):"""Get configuration for a specific model (wraps load_model_defaults)."""+ if local_path:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, local_path)hf_token = hf_token_arg(_normalize_hf_token(header_hf_token) or _normalize_hf_token(hf_token),- allow_ambient_token = allow_ambient_token,+ allow_ambient_token = allow_ambient_token and not account_access.managed_account(),+ )+ await _require_model_access_or_caller_token(+ model_name,+ hf_token,+ local_path = local_path,+ prefer_local_cache = prefer_local_cache,)from core.inference.llama_cpp import _hf_offline_if_unreachable_forfrom utils.models.model_config import shared_hub_model_info@@ -2490,6 +2564,11 @@ async def scan_model_remote_code(POST (not GET) so the ``hf_token`` for gated repos travels in the body andnever lands in a URL, browser history, or access log."""+ if account_access.managed_account():+ for ref in (model_name, model_local_path, model_snapshot_path, model_snapshot_repo_id):+ if isinstance(ref, str) and ref:+ await asyncio.to_thread(account_access.require_model_access, ref)+ allow_ambient_token = False# Without this an absent body token reads as None, i.e. ambient-authorized, and the# scan returns source snippets from a cached private repo.hf_token = hf_token_arg(hf_token, allow_ambient_token = allow_ambient_token)@@ -2763,6 +2842,7 @@ async def discard_remote_code_download(``*.gguf``) -- i.e. a model the user actually downloaded. The frontend onlycalls this when the scan reported ``created_by_scan``."""+ account_access.require_installation_owner()if is_local_path(model_name):return {"deleted": False, "reason": "local"}if not _is_valid_repo_id(model_name):@@ -2889,6 +2969,8 @@ async def scan_loras(Returns training outputs (outputs_dir) and exported models(exports_dir) in one list, distinguished by the source field."""+ exports_dir = account_access.private_directory(exports_dir, "exports")+ outputs_dir = account_access.private_directory(outputs_dir, "outputs")try:resolved_outputs_dir = str(resolve_output_dir(outputs_dir))resolved_exports_dir = str(resolve_export_dir(exports_dir))@@ -2962,6 +3044,8 @@ async def scan_diffusion_loras(from core.inference import diffusion_loraentries = diffusion_lora.list_loras(family = family)+ if account_access.managed_account():+ entries = await asyncio.to_thread(account_access.filter_model_rows, entries)return {"loras": [{@@ -2995,6 +3079,8 @@ async def scan_diffusion_controlnets(from core.inference import diffusion_controlnetentries = diffusion_controlnet.list_controlnets(family = family)+ if account_access.managed_account():+ entries = await asyncio.to_thread(account_access.filter_model_rows, entries)return {"controlnets": [{@@ -3459,6 +3545,8 @@ async def get_lora_base_model(lora_path: str, current_subject: str = Depends(getThis endpoint wraps the backend get_base_model_from_lora function."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, lora_path)try:base_model = get_base_model_from_lora(lora_path)@@ -3500,8 +3588,10 @@ async def check_vision_model("""hf_token = hf_token_arg(_normalize_hf_token(header_hf_token) or _normalize_hf_token(hf_token),- allow_ambient_token = allow_ambient_token,+ allow_ambient_token = allow_ambient_token and not account_access.managed_account(),)+ # After the token, so a private repo classifies before its first download.+ await _require_model_access_or_caller_token(model_name, hf_token)try:logger.info(f"Checking if vision model: {model_name}")# Authenticate so a gated/private VLM classifies correctly (else 404 -> non-vision). Offline@@ -3546,8 +3636,10 @@ async def check_embedding_model("""hf_token = hf_token_arg(_normalize_hf_token(header_hf_token) or _normalize_hf_token(hf_token),- allow_ambient_token = allow_ambient_token,+ allow_ambient_token = allow_ambient_token and not account_access.managed_account(),)+ # After the token, so a private repo classifies before its first download.+ await _require_model_access_or_caller_token(model_name, hf_token)try:logger.info(f"Checking if embedding model: {model_name}")# Same guard as /check-vision: is_embedding_model hits the hub with a 15s timeout.@@ -3634,7 +3726,7 @@ async def _read_native_context_length_bounded(model: str, is_local: bool) -> Optslots.release()return Nonetry:- threading.Thread(target = worker, name = "native-ctx", daemon = True).start()+ account_thread(target = worker, name = "native-ctx", daemon = True).start()except RuntimeError:slots.release() # thread never ran, so it will never releasereturn None@@ -3874,6 +3966,8 @@ async def get_kv_cache_estimate(null for ngram, which drafts from the generated text and costs no VRAM, andfor models with no drafter -- the caller draws no segment either way."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, repo_id)# The header read, the HF cache walk, the drafter lookup and the capability probe are all blocking disk work,# and this route is called once per visible row, so run it in a worker. n_ctx and n_parallel are bound as@@ -4345,6 +4439,8 @@ async def get_gguf_variants(current_subject: str = Depends(get_current_subject),):"""List GGUF quantization variants for a HF repo or local directory."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, repo_id)try:hf_token = _resolve_hub_token(hf_token_header, hf_token)from hub.services.models import gguf_variants as hub_gguf_variants@@ -4795,7 +4891,8 @@ def _preferred_gguf_copy(async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):"""List GGUF repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""try:- return {"cached": cached_gguf_rows()}+ # Off the loop: the filter can probe the Hub per ungranted repo.+ return {"cached": await asyncio.to_thread(cached_gguf_rows)}except Exception as e:logger.error(f"Error listing cached GGUF repos: {e}", exc_info = True)return {"cached": []}@@ -4861,9 +4958,11 @@ def cached_gguf_rows(cache_scans = None) -> list[dict]:logger.warning(f"Skipping cached GGUF repo {repo_label}: {e}")continue# Newest download first; stable repo_id tie-break for equal/missing mtimes.- return sorted(- seen_lower.values(),- key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),+ return account_access.filter_model_rows(+ sorted(+ seen_lower.values(),+ key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),+ ))@@ -4899,7 +4998,8 @@ async def list_cached_models():"""List non-GGUF model repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""try:- return {"cached": cached_model_rows()}+ # Off the loop: the filter can probe the Hub per ungranted repo.+ return {"cached": await asyncio.to_thread(cached_model_rows)}except Exception as e:logger.error(f"Error listing cached models: {e}", exc_info = True)return {"cached": []}@@ -5141,9 +5241,11 @@ def cached_model_rows(cache_scans = None) -> list[dict]:continue# Local-only list path: update checks are GGUF-only and happen lazily when variants are viewed.- return sorted(- seen_lower.values(),- key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),+ return account_access.filter_model_rows(+ sorted(+ seen_lower.values(),+ key = lambda c: (-(c.get("last_modified") or 0.0), c["repo_id"].lower()),+ ))@@ -5164,7 +5266,9 @@ async def delete_cached_model(current_subject: str = Depends(get_current_subject),):"""Compatibility route backed by the shared multi-cache deletion service."""+ account_access.require_installation_owner()from hub.services.models import deletion+return await deletion.delete_cached_model_response(repo_id, variant, hf_token, cache_path)@@ -5270,6 +5374,8 @@ async def get_cached_model_path(current_subject: str = Depends(get_current_subject),):"""Absolute on-disk path of a cached repo or one of its GGUF variants."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, repo_id)if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400, detail = "Invalid repo_id format")path = await asyncio.to_thread(_resolve_cached_model_path, repo_id, variant.strip() or None)@@ -5283,6 +5389,9 @@ async def reveal_cached_model(current_subject: str = Depends(get_current_subject),):"""Reveal a cached repo (or one GGUF variant's file) in the OS file manager."""+ account_access.require_installation_owner()+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, repo_id)from utils.paths.path_utils import reveal_in_file_managerif not _is_valid_repo_id(repo_id):@@ -5309,6 +5418,7 @@ async def list_checkpoints(Scans the outputs folder for training runs and their checkpoints."""+ outputs_dir = account_access.private_directory(outputs_dir, "outputs")try:resolved_outputs_dir = str(resolve_output_dir(outputs_dir))raw_models = scan_checkpoints(outputs_dir = resolved_outputs_dir)@@ -5343,7 +5453,7 @@ async def list_checkpoints(# Successful estimates only, keyed by model id. Failures aren't cached so they can recover.-_EXPORT_SIZE_CACHE: dict[str, tuple[int, int, str]] = {}+_EXPORT_SIZE_CACHE: dict[object, tuple[int, int, str]] = {}def _is_sizable_local_path(model: str) -> bool:@@ -5390,10 +5500,16 @@ def _is_sizable_local_path(model: str) -> bool:def _export_size_cached(model: str, hf_token: Optional[str]) -> tuple[Optional[int], Optional[int], str]:- """Estimate a model's fp16/bf16-equivalent size in bytes (+ total params). Memoizes successful results by- model id; never raises (failures return (None, None, "unavailable") and are not cached). Blocking I/O;- call off-thread."""- cached = _EXPORT_SIZE_CACHE.get(model)+ """Estimate a model's fp16/bf16-equivalent size in bytes (+ total params).++ Memoizes successful results by model id; never raises (failures return+ (None, None, "unavailable") and are not cached). Blocking I/O; call off-thread.+ """+ # Keyed per managed account: a relative model name is private to a workspace.+ cache_key = (+ (account_access.current_account_id(), model) if account_access.managed_account() else model+ )+ cached = _EXPORT_SIZE_CACHE.get(cache_key)if cached is not None:return cachedtry:@@ -5413,7 +5529,7 @@ def _export_size_cached(if not fp16_bytes or fp16_bytes <= 0:return None, None, source or "unavailable"result = (int(fp16_bytes), int(fp16_bytes) // 2, source)- _EXPORT_SIZE_CACHE[model] = result+ _EXPORT_SIZE_CACHE[cache_key] = resultreturn resultexcept Exception as e: # a size hint must never break exportlogger.warning("Could not estimate export size for '%s': %s", model, e)@@ -5431,6 +5547,7 @@ async def get_export_size(Returns nulls with HTTP 200 when the size can't be determined. The HF token(for gated repos) comes from the X-HF-Token header so it never hits URLs/logs."""+ await _require_model_access_or_caller_token(model, _normalize_hf_token(hf_token))if is_local_path(model):if not _is_sizable_local_path(model):return ExportSizeResponse(diff --git a/studio/backend/routes/preview.py b/studio/backend/routes/preview.pyindex 437b6472efe..018fadfd895 100644--- a/studio/backend/routes/preview.py+++ b/studio/backend/routes/preview.py@@ -28,7 +28,8 @@ from utils.client_ip import client_ipfrom utils.models.checkpoints import list_preview_targets, resolve_preview_checkpointfrom utils.preview_rate_limit import check_rate_limitfrom utils.preview_sharing_settings import get_preview_sharing_enabled-from utils.preview_token import sign_preview_ref, verify_preview_ref+from utils.account_context import bind_account, reset_account+from utils.preview_token import preview_token_account, sign_preview_reflogger = get_logger(__name__)@@ -52,12 +53,34 @@ def _extract_token(request: Request) -> str | None:return None-def _verify_or_404(run: str, checkpoint: str | None, request: Request) -> None:+def _verify_or_404(run: str, checkpoint: str | None, request: Request):+ """The account the capability opens, or 404. Never says which check failed."""ref = run if not checkpoint else f"{run}/{checkpoint}"- if not verify_preview_ref(ref, _extract_token(request)):+ account = preview_token_account(ref, _extract_token(request))+ if account is None:raise HTTPException(status_code = 404, detail = "Not found")if not get_preview_sharing_enabled():raise HTTPException(status_code = 404, detail = "Not found")+ return account+++# The public routes carry no credential, so the capability decides whose outputs the ref resolves in.+async def _latest_account(run: str, request: Request):+ account = _verify_or_404(run, None, request)+ token = bind_account(account)+ try:+ yield account+ finally:+ reset_account(token)+++async def _checkpoint_account(run: str, checkpoint: str, request: Request):+ account = _verify_or_404(run, checkpoint, request)+ token = bind_account(account)+ try:+ yield account+ finally:+ reset_account(token)def _enforce_rate_limit(request: Request) -> None:@@ -135,8 +158,6 @@ async def _serve_chat(run: str, checkpoint: str | None, payload: ChatCompletionRequest, request: Request):path = _resolve_or_4xx(run, checkpoint)- # Before the lock and the load: openai_chat_completions refuses these too, but only after a- # checkpoint load that can evict the resident model on its way to the same 400._reject_unsupported_content_parts(payload)is_lora = (path / "adapter_config.json").exists()payload = _sanitize_preview_payload(payload, is_lora)@@ -198,18 +219,16 @@ async def list_previews(return {"object": "list", "data": previews, "sharing_enabled": sharing_on}[email protected]("/{run}/v1/chat/completions")[email protected]("/{run}/v1/chat/completions", dependencies = [Depends(_latest_account)])async def preview_chat_latest(run: str, payload: ChatCompletionRequest, request: Request):- _verify_or_404(run, None, request)_enforce_rate_limit(request)return await _serve_chat(run, None, payload, request)[email protected]("/{run}/{checkpoint}/v1/chat/completions")[email protected]("/{run}/{checkpoint}/v1/chat/completions", dependencies = [Depends(_checkpoint_account)])async def preview_chat_checkpoint(run: str, checkpoint: str, payload: ChatCompletionRequest, request: Request):- _verify_or_404(run, checkpoint, request)_enforce_rate_limit(request)return await _serve_chat(run, checkpoint, payload, request)@@ -232,15 +251,13 @@ def _models_response(run: str, checkpoint: str | None):# The models/page GET routes only stat the checkpoint dir (no GPU), so they are# token-gated but not rate-limited; only the GPU-backed chat path is throttled.[email protected]("/{run}/v1/models")[email protected]("/{run}/v1/models", dependencies = [Depends(_latest_account)])async def preview_models_latest(run: str, request: Request):- _verify_or_404(run, None, request)return _models_response(run, None)[email protected]("/{run}/{checkpoint}/v1/models")[email protected]("/{run}/{checkpoint}/v1/models", dependencies = [Depends(_checkpoint_account)])async def preview_models_checkpoint(run: str, checkpoint: str, request: Request):- _verify_or_404(run, checkpoint, request)return _models_response(run, checkpoint)@@ -288,13 +305,13 @@ def _preview_page(run: str, checkpoint: str | None) -> HTMLResponse:)[email protected]("/{run}", response_class = HTMLResponse)[email protected]("/{run}", response_class = HTMLResponse, dependencies = [Depends(_latest_account)])async def preview_page_latest(run: str, request: Request):- _verify_or_404(run, None, request)return _preview_page(run, None)[email protected]("/{run}/{checkpoint}", response_class = HTMLResponse)+ "/{run}/{checkpoint}", response_class = HTMLResponse, dependencies = [Depends(_checkpoint_account)]+)async def preview_page_checkpoint(run: str, checkpoint: str, request: Request):- _verify_or_404(run, checkpoint, request)return _preview_page(run, checkpoint)diff --git a/studio/backend/routes/profile_stats.py b/studio/backend/routes/profile_stats.pyindex c5b1c93bcb9..4d81ca2049e 100644--- a/studio/backend/routes/profile_stats.py+++ b/studio/backend/routes/profile_stats.py@@ -31,17 +31,7 @@ async def get_profile_stats(tz: str = Query("", max_length = 64),current_subject: str = Depends(get_current_subject),) -> dict[str, Any]:- """Usage stats from this install, with API receipts scoped to the caller.-- Unsloth chat and training history is legacy install-wide data because those- tables have no subject column. Authenticated external API usage is always- filtered to ``current_subject`` and cannot cross accounts.-- Days and hours are bucketed in the caller's timezone so a remote browser- does not read the server's calendar. ``tz`` is an IANA name, which carries- each date's own daylight-saving offset; ``tz_offset_minutes`` is the- ``Date.getTimezoneOffset()`` fallback for hosts with no tzdata.- """+ """Usage stats from the caller's database, bucketed in the caller's timezone (``tz``, or the ``tz_offset_minutes`` fallback)."""try:# A cold pass parses every message's metadata JSON: ~90 ms at 10k messages, ~1.2 s at 260k. Off the event# loop so it cannot stall token streaming when Settings is opened mid-generation.diff --git a/studio/backend/routes/provider_credentials.py b/studio/backend/routes/provider_credentials.pyindex 164f6fc4279..2d8f8177d57 100644--- a/studio/backend/routes/provider_credentials.py+++ b/studio/backend/routes/provider_credentials.py@@ -18,6 +18,8 @@ from fastapi import HTTPExceptionfrom storage import credential_secrets+from hub.services.models import account_access+from utils.account_context import current_account_idlogger = structlog.get_logger(__name__)@@ -30,7 +32,12 @@ def provider_config_guard(provider_id: str) -> asyncio.Lock:"""Serialize one provider's routing metadata and installation credential."""loop = asyncio.get_running_loop()locks = _provider_config_locks.setdefault(loop, {})- return locks.setdefault(provider_id, asyncio.Lock())+ key = (+ (current_account_id(), provider_id)+ if account_access.account_scope() is not None+ else provider_id+ )+ return locks.setdefault(key, asyncio.Lock())def serialize_provider_config(handler):diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex eded18a6d81..44fee68b917 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -50,11 +50,13 @@ from models.providers import (ProviderUpdate,)from storage import credential_secrets, providers_db+from hub.services.models import account_accessfrom utils.utils import safe_curated_detail, log_and_http_errorlogger = structlog.get_logger(__name__)-router = APIRouter()++router = APIRouter(dependencies = [Depends(get_current_subject)])def _provider_response(row: dict) -> ProviderResponse:@@ -500,6 +502,8 @@ async def delete_provider_config(via_api_key: bool = Depends(authenticated_via_api_key),):"""Idempotently delete a saved provider and its installation credential."""+ if account_access.managed_account() and providers_db.get_provider(provider_id) is None:+ raise HTTPException(status_code = 404, detail = "Provider config not found")require_ui_session(via_api_key)await openai_codex_auth.cancel_provider_flows(provider_id)credential_secrets.get_or_create_credential_encryption_key()diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex 0a324275e69..cb492ef234a 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -12,6 +12,7 @@ Nothing logs a traceback for it: the condition is fixed for the session and rag_from __future__ import annotations+from core.training.account_jobs import account_pathimport hashlibimport hmacimport json@@ -33,6 +34,13 @@ from pydantic import BaseModel, Fieldfrom auth.authentication import get_current_subject, request_admitted_without_credentialfrom core.rag import config, folder_sync, ingestion, retrieval, storefrom storage import rag_db+from utils.account_context import (+ OWNER,+ AccountContext,+ bind_account,+ current_account,+ reset_account,+)from utils.paths import ensure_dir, rag_uploads_rootlogger = logging.getLogger(__name__)@@ -190,6 +198,7 @@ def _save_native_path_upload(lease: str) -> tuple[str, str, str]:except NativePathLeaseError as exc:raise HTTPException(status_code = 400, detail = str(exc)) from exc+ account_path(grant.canonical_path)# Path.name is one component, so a "\" in it is part of the name, as in "AC\DC.pdf".filename = _document_label(grant.canonical_path.name)try:@@ -991,29 +1000,43 @@ _CONTENT_TYPES = {}+# The signed token carries the account it was minted for; empty means the owner.+_DOCUMENT_TOKEN_VERSION = "v2"+++def _document_mac(document_id: str, exp: str, account_id: str) -> str:+ payload = f"rag:{_DOCUMENT_TOKEN_VERSION}:{account_id}:{document_id}.{exp}"+ return hmac.new(_PREVIEW_SECRET, payload.encode(), hashlib.sha256).hexdigest()++def _sign_document(document_id: str) -> str:- exp = int(time.time()) + _PREVIEW_TTL- payload = f"{document_id}.{exp}"- sig = hmac.new(_PREVIEW_SECRET, payload.encode(), hashlib.sha256).hexdigest()- return f"{payload}.{sig}"+ account = current_account()+ account_id = "" if account.is_owner else account.account_id+ exp = str(int(time.time()) + _PREVIEW_TTL)+ return f"{exp}.{account_id}.{_document_mac(document_id, exp, account_id)}"-def _verify_document_token(token: str) -> str | None:+def _verify_document_token(document_id: str, token: str) -> AccountContext | None:+ """The account whose uploads ``token`` opens for ``document_id``, or None once deactivated."""try:- document_id, exp_s, sig = token.rsplit(".", 2)+ exp_s, account_id, sig = token.split(".", 2)except ValueError:return None- expected = hmac.new(- _PREVIEW_SECRET, f"{document_id}.{exp_s}".encode(), hashlib.sha256- ).hexdigest()- if not hmac.compare_digest(sig, expected):+ if "." in sig:+ return None+ if not hmac.compare_digest(sig, _document_mac(document_id, exp_s, account_id)):return Nonetry:if int(exp_s) < int(time.time()):return Noneexcept ValueError:return None- return document_id+ if not account_id:+ return OWNER+ from auth.storage import get_account_by_id++ account = get_account_by_id(account_id)+ return None if account is None or account.is_owner else account@router.get("/documents/{document_id}/preview-target")@@ -1089,23 +1112,27 @@ def document_file_signed(document_id: str, token: str = Query(...)) -> FileResporequests work."""# Token first: this is the one endpoint with no bearer, and _require_rag() now opens# a connection on its first call, which is not work an unverified token should buy.- signed_id = _verify_document_token(token)- if signed_id != document_id:+ account = _verify_document_token(document_id, token)+ if account is None:raise HTTPException(status_code = 401, detail = "Invalid or expired token")- _require_rag()- conn = _rag_connection()+ # No auth dependency on this route, so without this bind every read hits the owner's store.+ marker = bind_account(account)try:- doc = store.get_visible_document(conn, document_id)- if doc is not None:- _require_document_owner(conn, doc)+ _require_rag()+ conn = _rag_connection()+ try:+ doc = store.get_visible_document(conn, document_id)+ if doc is not None:+ _require_document_owner(conn, doc)+ finally:+ conn.close()+ stored_path = (doc or {}).get("stored_path")+ if not doc or not stored_path or not os.path.isfile(stored_path):+ raise HTTPException(status_code = 404, detail = "Document file not found")+ if not _is_managed_preview_path(stored_path):+ raise HTTPException(status_code = 403, detail = "Forbidden")finally:- conn.close()- stored_path = (doc or {}).get("stored_path")- if not doc or not stored_path or not os.path.isfile(stored_path):- raise HTTPException(status_code = 404, detail = "Document file not found")- # Confine to the uploads root (defense in depth).- if not _is_managed_preview_path(stored_path):- raise HTTPException(status_code = 403, detail = "Forbidden")+ reset_account(marker)ext = os.path.splitext(doc["filename"])[1].lower()return FileResponse(stored_path,diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex df7171e4ae6..ebc1a3c988e 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -5,6 +5,7 @@from __future__ import annotations+from utils.account_context import current_account, run_asimport asyncioimport jsonimport re@@ -565,6 +566,8 @@ async def research_events(# off the default executor: parked followers there starved the run's own db writes.events = await loop.run_in_executor(_EVENT_WAIT_EXECUTOR,+ run_as,+ current_account(),db.wait_for_events,run_id,cursor,diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 71d48a61686..01fb3fd3b9b 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -1,6 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Settings policy: the account, shared and owner routers decide who may reach each+/api/settings path."""+import functoolsimport hashlibimport re@@ -28,6 +31,8 @@ from auth.authentication import (get_current_subject,)from auth.storage import rotate_preview_link_secret+from auth import policy+from utils.account_context import OWNER, bind_account, current_account, reset_accountfrom hub.utils.hf_tokens import cache_reads_authorized, cached_read_refused, hf_token_argfrom routes.provider_credentials import current_credential_write, require_ui_session@@ -171,7 +176,26 @@ from utils.media_generation_preset_settings import (upsert_media_generation_preset,)++async def _require_installation_owner(current_subject: str = Depends(get_current_subject)) -> None:+ await policy.require_owner()+++async def _shared_policy_read(current_subject: str = Depends(get_current_subject)):+ marker = None+ if not current_account().is_owner:+ marker = bind_account(OWNER)+ try:+ yield+ finally:+ if marker is not None:+ reset_account(marker)++router = APIRouter()+_account_settings_router = APIRouter()+_owner_settings_router = APIRouter(dependencies = [Depends(_require_installation_owner)])+_shared_settings_router = APIRouter(dependencies = [Depends(_shared_policy_read)])logger = get_logger(__name__)@@ -408,7 +432,7 @@ def _get_generation_preset_settings(kind, schema):return response+@_account_settings_router.get("/generation-presets/image",response_model = ImageGenerationPresetSettings,)@@ -418,7 +442,7 @@ def get_image_generation_preset_settings(return _get_generation_preset_settings("image", ImageGenerationPresetSettings)[email protected]("/generation-presets/image")+@_account_settings_router.put("/generation-presets/image")def update_image_generation_preset_settings(payload: ImageGenerationPresetState, current_subject: str = Depends(get_current_subject)) -> dict[str, bool]:@@ -432,7 +456,7 @@ def update_image_generation_preset_settings(return {"saved": True}+@_account_settings_router.get("/generation-presets/video",response_model = VideoGenerationPresetSettings,)@@ -442,7 +466,7 @@ def get_video_generation_preset_settings(return _get_generation_preset_settings("video", VideoGenerationPresetSettings)[email protected]("/generation-presets/video")+@_account_settings_router.put("/generation-presets/video")def update_video_generation_preset_settings(payload: VideoGenerationPresetState, current_subject: str = Depends(get_current_subject)) -> dict[str, bool]:@@ -471,21 +495,21 @@ def _upsert_custom_generation_preset(return {"saved": True}[email protected]("/generation-presets/image/custom")+@_account_settings_router.put("/generation-presets/image/custom")def upsert_custom_image_generation_preset(payload: ImageGenerationPreset, current_subject: str = Depends(get_current_subject)) -> dict[str, bool]:return _upsert_custom_generation_preset("image", payload)[email protected]("/generation-presets/video/custom")+@_account_settings_router.put("/generation-presets/video/custom")def upsert_custom_video_generation_preset(payload: VideoGenerationPreset, current_subject: str = Depends(get_current_subject)) -> dict[str, bool]:return _upsert_custom_generation_preset("video", payload)[email protected]("/generation-presets/{kind}/custom")+@_account_settings_router.delete("/generation-presets/{kind}/custom")def delete_custom_generation_preset(kind: Literal["image", "video"],name: str,@@ -528,7 +552,7 @@ class HuggingFaceTokenResponse(BaseModel):has_token: bool = False[email protected]("/hugging-face-token", response_model = HuggingFaceTokenResponse)+@_account_settings_router.get("/hugging-face-token", response_model = HuggingFaceTokenResponse)def get_hugging_face_token(_current_subject: str = Depends(get_current_subject),via_api_key: bool = Depends(authenticated_via_api_key),@@ -538,7 +562,7 @@ def get_hugging_face_token(return HuggingFaceTokenResponse(token = token, has_token = token is not None)[email protected]("/hugging-face-token", response_model = HuggingFaceTokenResponse)+@_account_settings_router.put("/hugging-face-token", response_model = HuggingFaceTokenResponse)def update_hugging_face_token(payload: HuggingFaceTokenPayload,credential: tuple = Depends(get_current_credential),@@ -553,7 +577,9 @@ def update_hugging_face_token(return HuggingFaceTokenResponse(token = payload.token, has_token = True)[email protected]("/hugging-face-token/migrate", response_model = HuggingFaceTokenResponse)+@_account_settings_router.put(+ "/hugging-face-token/migrate", response_model = HuggingFaceTokenResponse+)def migrate_hugging_face_token(payload: HuggingFaceTokenPayload,credential: tuple = Depends(get_current_credential),@@ -568,7 +594,7 @@ def migrate_hugging_face_token(return HuggingFaceTokenResponse(token = token, has_token = token is not None)[email protected]("/hugging-face-token", response_model = HuggingFaceTokenResponse)+@_account_settings_router.delete("/hugging-face-token", response_model = HuggingFaceTokenResponse)def clear_hugging_face_token(credential: tuple = Depends(get_current_credential),via_api_key: bool = Depends(authenticated_via_api_key),@@ -1022,14 +1048,14 @@ def _llama_cpp_path_response() -> LlamaCppPathResponse:)[email protected]("/hugging-face-cache", response_model = HuggingFaceCacheResponse)+@_owner_settings_router.get("/hugging-face-cache", response_model = HuggingFaceCacheResponse)def get_hugging_face_cache(current_subject: str = Depends(get_current_subject),) -> HuggingFaceCacheResponse:return _hugging_face_cache_response()[email protected]("/hugging-face-cache", response_model = HuggingFaceCacheResponse)+@_owner_settings_router.put("/hugging-face-cache", response_model = HuggingFaceCacheResponse)def update_hugging_face_cache(payload: HuggingFaceCachePayload, current_subject: str = Depends(get_current_subject)) -> HuggingFaceCacheResponse:@@ -1042,12 +1068,12 @@ def update_hugging_face_cache(return _hugging_face_cache_response()[email protected]("/llama-cpp-path", response_model = LlamaCppPathResponse)+@_owner_settings_router.get("/llama-cpp-path", response_model = LlamaCppPathResponse)def get_llama_cpp_path(current_subject: str = Depends(get_current_subject)) -> LlamaCppPathResponse:return _llama_cpp_path_response()[email protected]("/llama-cpp-path", response_model = LlamaCppPathResponse)+@_owner_settings_router.put("/llama-cpp-path", response_model = LlamaCppPathResponse)def update_llama_cpp_path(payload: LlamaCppPathPayload,current_subject: str = Depends(get_current_subject),@@ -1070,12 +1096,12 @@ def update_llama_cpp_path(return _llama_cpp_path_response()[email protected]("/upload-limit", response_model = UploadLimitResponse)+@_shared_settings_router.get("/upload-limit", response_model = UploadLimitResponse)def get_upload_limit(current_subject: str = Depends(get_current_subject)) -> UploadLimitResponse:return _upload_limit_response(get_upload_limit_mb())[email protected]("/upload-limit", response_model = UploadLimitResponse)+@_owner_settings_router.put("/upload-limit", response_model = UploadLimitResponse)def update_upload_limit(payload: UploadLimitPayload, current_subject: str = Depends(get_current_subject)) -> UploadLimitResponse:@@ -1092,14 +1118,14 @@ def update_upload_limit(return _upload_limit_response(limit_mb)[email protected]("/helper-precache", response_model = HelperPrecacheResponse)+@_shared_settings_router.get("/helper-precache", response_model = HelperPrecacheResponse)def get_helper_precache(current_subject: str = Depends(get_current_subject),) -> HelperPrecacheResponse:return _helper_precache_response()[email protected]("/helper-precache", response_model = HelperPrecacheResponse)+@_owner_settings_router.put("/helper-precache", response_model = HelperPrecacheResponse)def update_helper_precache(payload: HelperPrecachePayload, current_subject: str = Depends(get_current_subject)) -> HelperPrecacheResponse:@@ -1116,14 +1142,14 @@ def update_helper_precache(return _helper_precache_response(enabled)[email protected]("/download-transport", response_model = DownloadTransportResponse)+@_shared_settings_router.get("/download-transport", response_model = DownloadTransportResponse)def get_download_transport(current_subject: str = Depends(get_current_subject),) -> DownloadTransportResponse:return _download_transport_response()[email protected]("/download-transport", response_model = DownloadTransportResponse)+@_owner_settings_router.put("/download-transport", response_model = DownloadTransportResponse)def update_download_transport(payload: DownloadTransportPayload, current_subject: str = Depends(get_current_subject)) -> DownloadTransportResponse:@@ -1140,7 +1166,7 @@ def update_download_transport(return _download_transport_response(mode)[email protected]("/xet-notice/reserve", response_model = XetNoticeResponse)+@_owner_settings_router.post("/xet-notice/reserve", response_model = XetNoticeResponse)def post_xet_notice_reserve(payload: XetNoticeReservePayload, current_subject: str = Depends(get_current_subject)) -> XetNoticeResponse:@@ -1158,7 +1184,9 @@ def post_xet_notice_reserve(return XetNoticeResponse(**result)[email protected]("/igpu-carveout-notice/dismiss", response_model = IgpuCarveoutNoticeResponse)+@_account_settings_router.post(+ "/igpu-carveout-notice/dismiss", response_model = IgpuCarveoutNoticeResponse+)def post_igpu_carveout_notice_dismiss(payload: IgpuCarveoutNoticeDismissPayload, current_subject: str = Depends(get_current_subject)) -> IgpuCarveoutNoticeResponse:@@ -1182,14 +1210,14 @@ def post_igpu_carveout_notice_dismiss(return IgpuCarveoutNoticeResponse(dismissed_at_gb = stored)[email protected]("/chat-preferences", response_model = ChatPreferencesResponse)+@_account_settings_router.get("/chat-preferences", response_model = ChatPreferencesResponse)def get_chat_preferences(current_subject: str = Depends(get_current_subject),) -> ChatPreferencesResponse:return _chat_preferences_response()[email protected]("/chat-preferences", response_model = ChatPreferencesResponse)+@_account_settings_router.put("/chat-preferences", response_model = ChatPreferencesResponse)def update_chat_preferences(payload: ChatPreferencesPayload, current_subject: str = Depends(get_current_subject)) -> ChatPreferencesResponse:@@ -1206,7 +1234,7 @@ def update_chat_preferences(return _chat_preferences_response(enabled)[email protected]("/chat-preferences/migrate", response_model = ChatPreferencesResponse)+@_account_settings_router.post("/chat-preferences/migrate", response_model = ChatPreferencesResponse)def migrate_chat_preferences(payload: ChatPreferencesMigrationPayload, current_subject: str = Depends(get_current_subject)) -> ChatPreferencesResponse:@@ -1223,12 +1251,12 @@ def migrate_chat_preferences(return _chat_preferences_response(enabled)[email protected]("/model-memory", response_model = ModelMemoryResponse)+@_owner_settings_router.get("/model-memory", response_model = ModelMemoryResponse)def get_model_memory(current_subject: str = Depends(get_current_subject)) -> ModelMemoryResponse:return _model_memory_response()[email protected]("/model-memory", response_model = ModelMemoryResponse)+@_owner_settings_router.put("/model-memory", response_model = ModelMemoryResponse)def update_model_memory(payload: ModelMemoryPayload, current_subject: str = Depends(get_current_subject)) -> ModelMemoryResponse:@@ -1254,6 +1282,8 @@ _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."""+ if not current_account().is_owner:+ subject = current_account().account_idsubject = (subject or "").strip()if not subject:return LAST_LOCAL_MODEL_SETTING_KEY@@ -1297,7 +1327,7 @@ class LastLocalModelResponse(BaseModel):server_now: Optional[int] = None[email protected]("/last-local-model", response_model = LastLocalModelResponse)+@_account_settings_router.get("/last-local-model", response_model = LastLocalModelResponse)def get_last_local_model(current_subject: str = Depends(get_current_subject),) -> LastLocalModelResponse:@@ -1312,7 +1342,7 @@ def get_last_local_model(return LastLocalModelResponse(**payload.model_dump(exclude = {"client_now"}), server_now = _now)[email protected]("/last-local-model", response_model = LastLocalModelResponse)+@_account_settings_router.put("/last-local-model", response_model = LastLocalModelResponse)def update_last_local_model(payload: LastLocalModelPayload, current_subject: str = Depends(get_current_subject)) -> LastLocalModelResponse:@@ -1351,12 +1381,12 @@ def update_last_local_model()[email protected]("/vram-budget", response_model = VramBudgetResponse)+@_owner_settings_router.get("/vram-budget", response_model = VramBudgetResponse)def get_vram_budget(current_subject: str = Depends(get_current_subject)) -> VramBudgetResponse:return _vram_budget_response()[email protected]("/vram-budget", response_model = VramBudgetResponse)+@_owner_settings_router.put("/vram-budget", response_model = VramBudgetResponse)def update_vram_budget(payload: VramBudgetPayload, current_subject: str = Depends(get_current_subject)) -> VramBudgetResponse:@@ -1381,12 +1411,12 @@ class CodingAgentsResponse(BaseModel):detected: list[str][email protected]("/coding-agents", response_model = CodingAgentsResponse)+@_owner_settings_router.get("/coding-agents", response_model = CodingAgentsResponse)def get_coding_agents(current_subject: str = Depends(get_current_subject)) -> CodingAgentsResponse:return CodingAgentsResponse(detected = detect_installed_coding_agents())[email protected]("/openai-auto-switch", response_model = OpenAIAutoSwitchResponse)+@_owner_settings_router.get("/openai-auto-switch", response_model = OpenAIAutoSwitchResponse)def get_openai_auto_switch(current_subject: str = Depends(get_current_subject),) -> OpenAIAutoSwitchResponse:@@ -1403,7 +1433,7 @@ def get_openai_auto_switch()[email protected]("/openai-auto-switch", response_model = OpenAIAutoSwitchResponse)+@_owner_settings_router.put("/openai-auto-switch", response_model = OpenAIAutoSwitchResponse)def update_openai_auto_switch(payload: OpenAIAutoSwitchPayload, current_subject: str = Depends(get_current_subject)) -> OpenAIAutoSwitchResponse:@@ -1450,7 +1480,7 @@ def update_openai_auto_switch()[email protected]("/openai-auto-switch/overrides", response_model = ModelOverridesResponse)+@_owner_settings_router.get("/openai-auto-switch/overrides", response_model = ModelOverridesResponse)def get_openai_auto_switch_overrides(model_id: Optional[str] = None,alias_id: Optional[str] = None,@@ -1587,7 +1617,7 @@ def _serialized_override_write(func):return wrapper[email protected]("/openai-auto-switch/overrides", response_model = ModelOverridesResponse)+@_owner_settings_router.put("/openai-auto-switch/overrides", response_model = ModelOverridesResponse)@_serialized_override_writedef update_openai_auto_switch_override(payload: ModelOverridePayload, current_subject: str = Depends(get_current_subject)@@ -1956,7 +1986,7 @@ def _no_embedding_weights_error(candidates: list[str]) -> str:)[email protected]("/embedding-model", response_model = EmbeddingModelResponse)+@_owner_settings_router.get("/embedding-model", response_model = EmbeddingModelResponse)def get_embedding_model(current_subject: str = Depends(get_current_subject),) -> EmbeddingModelResponse:@@ -2550,7 +2580,9 @@ def _resolve_embedding_model_plan()[email protected]("/embedding-model/resolve", response_model = EmbeddingModelResolveResponse)+@_owner_settings_router.get(+ "/embedding-model/resolve", response_model = EmbeddingModelResolveResponse+)def resolve_embedding_model(model: str,# Header, not a query param: keeps a gated-repo token out of URLs and logs.@@ -2579,7 +2611,7 @@ def resolve_embedding_model(return _resolve_embedding_model_plan(resolved, token)[email protected]("/embedding-model", response_model = EmbeddingModelResponse)+@_owner_settings_router.put("/embedding-model", response_model = EmbeddingModelResponse)def update_embedding_model(payload: EmbeddingModelPayload,allow_ambient_token: bool = Depends(allow_ambient_hf_token),@@ -2753,7 +2785,7 @@ def update_embedding_model(return _embedding_model_response()[email protected]("/embedding-model/unload", response_model = EmbeddingModelResponse)+@_owner_settings_router.post("/embedding-model/unload", response_model = EmbeddingModelResponse)def unload_embedding_model(current_subject: str = Depends(get_current_subject),) -> EmbeddingModelResponse:@@ -2767,7 +2799,7 @@ def unload_embedding_model(return _embedding_model_response()[email protected]("/embedding-model", response_model = EmbeddingModelResponse)+@_owner_settings_router.delete("/embedding-model", response_model = EmbeddingModelResponse)def reset_embedding_model(current_subject: str = Depends(get_current_subject),) -> EmbeddingModelResponse:@@ -2781,7 +2813,7 @@ class PreviewLinkRotateResponse(BaseModel):rotated: bool = True[email protected]("/preview-links/rotate", response_model = PreviewLinkRotateResponse)+@_owner_settings_router.post("/preview-links/rotate", response_model = PreviewLinkRotateResponse)def rotate_preview_links(current_subject: str = Depends(get_current_subject),) -> PreviewLinkRotateResponse:@@ -2848,7 +2880,7 @@ def _remote_access_response(request: Request) -> RemoteAccessResponse:return RemoteAccessResponse(**remote_access_status(request.app.state))[email protected]("/remote-access", response_model = RemoteAccessResponse)+@_owner_settings_router.get("/remote-access", response_model = RemoteAccessResponse)def get_remote_access(request: Request,current_subject: str = Depends(get_current_subject),@@ -2857,7 +2889,7 @@ def get_remote_access(return _remote_access_response(request)[email protected]("/remote-access/start", response_model = RemoteAccessResponse)+@_owner_settings_router.post("/remote-access/start", response_model = RemoteAccessResponse)def start_remote_access_route(request: Request,current_subject: str = Depends(get_current_subject),@@ -2871,7 +2903,7 @@ def start_remote_access_route(return response[email protected]("/remote-access/stop", response_model = RemoteAccessResponse)+@_owner_settings_router.post("/remote-access/stop", response_model = RemoteAccessResponse)def stop_remote_access_route(request: Request,current_subject: str = Depends(get_current_subject),@@ -2894,7 +2926,7 @@ def stop_remote_access_route(return response[email protected]("/remote-access/auto-start", response_model = RemoteAccessResponse)+@_owner_settings_router.put("/remote-access/auto-start", response_model = RemoteAccessResponse)def update_remote_access_auto_start(request: Request,payload: RemoteAccessAutoStartPayload,@@ -2945,7 +2977,7 @@ def _lan_access_response(request: Request) -> LanAccessResponse:return LanAccessResponse(**lan_access_status(request.app))[email protected]("/lan-access", response_model = LanAccessResponse)+@_owner_settings_router.get("/lan-access", response_model = LanAccessResponse)def get_lan_access(request: Request,current_subject: str = Depends(get_current_subject),@@ -2954,7 +2986,7 @@ def get_lan_access(return _lan_access_response(request)[email protected]("/lan-access/start", response_model = LanAccessResponse)+@_owner_settings_router.post("/lan-access/start", response_model = LanAccessResponse)def start_lan_access_route(request: Request,current_subject: str = Depends(get_current_subject),@@ -2968,7 +3000,7 @@ def start_lan_access_route(return response[email protected]("/lan-access/stop", response_model = LanAccessResponse)+@_owner_settings_router.post("/lan-access/stop", response_model = LanAccessResponse)def stop_lan_access_route(request: Request,current_subject: str = Depends(get_current_subject),@@ -2982,7 +3014,7 @@ def stop_lan_access_route(return response[email protected]("/lan-access/auto-start", response_model = LanAccessResponse)+@_owner_settings_router.put("/lan-access/auto-start", response_model = LanAccessResponse)def update_lan_access_auto_start(request: Request,payload: LanAccessAutoStartPayload,@@ -3000,7 +3032,7 @@ def update_lan_access_auto_start(return _lan_access_response(request)[email protected]("/lan-access/port", response_model = LanAccessResponse)+@_owner_settings_router.put("/lan-access/port", response_model = LanAccessResponse)def update_lan_access_port(request: Request,payload: LanAccessPortPayload,@@ -3019,14 +3051,14 @@ def update_lan_access_port(return response[email protected]("/preview-sharing", response_model = PreviewSharingResponse)+@_owner_settings_router.get("/preview-sharing", response_model = PreviewSharingResponse)def get_preview_sharing(current_subject: str = Depends(get_current_subject),) -> PreviewSharingResponse:return PreviewSharingResponse(enabled = get_preview_sharing_enabled())[email protected]("/preview-sharing", response_model = PreviewSharingResponse)+@_owner_settings_router.put("/preview-sharing", response_model = PreviewSharingResponse)def update_preview_sharing(payload: PreviewSharingPayload, current_subject: str = Depends(get_current_subject)) -> PreviewSharingResponse:@@ -3045,14 +3077,14 @@ def update_preview_sharing(return PreviewSharingResponse(enabled = enabled)[email protected]("/current-date-prompt", response_model = CurrentDatePromptResponse)+@_account_settings_router.get("/current-date-prompt", response_model = CurrentDatePromptResponse)def get_current_date_prompt(current_subject: str = Depends(get_current_subject),) -> CurrentDatePromptResponse:return CurrentDatePromptResponse(enabled = get_current_date_prompt_enabled())[email protected]("/current-date-prompt", response_model = CurrentDatePromptResponse)+@_account_settings_router.put("/current-date-prompt", response_model = CurrentDatePromptResponse)def update_current_date_prompt(payload: CurrentDatePromptPayload, current_subject: str = Depends(get_current_subject)) -> CurrentDatePromptResponse:@@ -3093,7 +3125,7 @@ def _keyless_api_access_response(request: Request) -> KeylessApiAccessResponse:)[email protected]("/keyless-api-access", response_model = KeylessApiAccessResponse)+@_owner_settings_router.get("/keyless-api-access", response_model = KeylessApiAccessResponse)def get_keyless_api_access(request: Request,current_subject: str = Depends(get_current_subject),@@ -3102,7 +3134,7 @@ def get_keyless_api_access(return _keyless_api_access_response(request)[email protected]("/keyless-api-access", response_model = KeylessApiAccessResponse)+@_owner_settings_router.put("/keyless-api-access", response_model = KeylessApiAccessResponse)def update_keyless_api_access(request: Request,payload: KeylessApiAccessPayload,@@ -3396,7 +3428,7 @@ class PersonalizationResponse(PersonalizationPayload):greetingSlothSaved: bool = False[email protected]("/personalization", response_model = PersonalizationResponse)+@_account_settings_router.get("/personalization", response_model = PersonalizationResponse)def get_personalization_settings(current_subject: str = Depends(get_current_subject),) -> PersonalizationResponse:@@ -3424,7 +3456,7 @@ def _merge_personalization(base: dict, overlay: dict) -> dict:return merged[email protected]("/personalization", response_model = PersonalizationPayload)+@_account_settings_router.put("/personalization", response_model = PersonalizationPayload)def update_personalization_settings(payload: PersonalizationPayload, current_subject: str = Depends(get_current_subject)) -> PersonalizationPayload:@@ -3485,7 +3517,7 @@ class DebugLogResponse(BaseModel):size_bytes: int = 0[email protected]("/debug/logs/sources", response_model = DebugLogSourcesResponse)+@_owner_settings_router.get("/debug/logs/sources", response_model = DebugLogSourcesResponse)def get_debug_log_sources(current_subject: str = Depends(get_current_subject),_ui_session: None = Depends(_require_ui_session),@@ -3505,7 +3537,7 @@ def get_debug_log_sources()[email protected]("/debug/logs", response_model = DebugLogResponse)+@_owner_settings_router.get("/debug/logs", response_model = DebugLogResponse)def get_debug_log(source: Optional[str] = None,cursor: Optional[str] = None,@@ -3570,3 +3602,8 @@ def get_debug_log(file_logging_disabled = debug_log_sources.source_is_frozen(source_id),size_bytes = result.size_bytes,)+++router.include_router(_account_settings_router)+router.include_router(_shared_settings_router)+router.include_router(_owner_settings_router)diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex 313d4098935..f8a71b3c5f5 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -1,6 +1,20 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""+Training API routes+"""++from core.training.account_jobs import (+ account_event_stream,+ account_hf_token,+ account_path,+ job_busy,+ job_is_foreign,+ managed_account,+ require_job_owner,+ validate_job_paths,+)import contextlibimport jsonimport os@@ -254,6 +268,9 @@ def _run_active(backend) -> bool:def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset") -> list[str]:+ """Resolve and validate a list of local dataset paths. Returns validated absolute paths."""+ for path in paths:+ account_path(path)validated = []missing = []for dataset_path in paths:@@ -454,7 +471,7 @@ def _remote_untrainable_model_format(model_name: str, hf_token: Optional[str]) -try:info = hf_model_info(repo_id,- token = hf_token,+ token = account_hf_token(hf_token),timeout = timeout,)break@@ -584,6 +601,8 @@ def _preflight_hf_dataset_request(request: TrainingStartRequest) -> None:),)if cached_path is not None:+ # No Hub probe ran and no cached claim was made, so grants must authorize it.+ _authorize_cache_fallback(dataset_id, "dataset")returnraise _hf_preflight_error(409,@@ -690,6 +709,14 @@ def _detect_local_gguf(path: Path) -> Optional[str]:return None+def _authorize_cache_fallback(model_name: str, repo_type: str = "model") -> None:+ """A shared-cache snapshot was never authorized by the caller's token, so grants must be."""+ if managed_account():+ from hub.services.models import account_access+ reference = canonical_model_repo_id(model_name) if repo_type == "model" else model_name+ account_access.require_model_access(reference, repo_type)++def _reject_untrainable_model_request(request: TrainingStartRequest, actual_model_repo_id: Optional[str] = None) -> _ModelPreflightResult:@@ -751,6 +778,8 @@ def _reject_untrainable_model_request(request.model_name,model_local_path,)+ if snapshot and not model_local_path:+ _authorize_cache_fallback(request.model_name)if snapshot:path = Path(snapshot)if offline_mode and not request.resume_from_checkpoint:@@ -796,6 +825,7 @@ def _reject_untrainable_model_request()if snapshot is None:raise+ _authorize_cache_fallback(request.model_name)path = Path(snapshot)cached_model_pin = (canonical_model_repo_id(request.model_name),@@ -1149,6 +1179,13 @@ async def start_training(Initiates training in the background and returns immediately. Use /statusto check progress."""+ if managed_account():+ from utils.paths import tensorboard_root++ directory = request.tensorboard_dir+ if not directory or not Path(directory).is_absolute():+ request.tensorboard_dir = str(tensorboard_root() / (directory or ""))+ validate_job_paths(request.model_dump())backend = Nonereserved_start_request_id = Nonestart_task: Optional[asyncio.Task[bool]] = None@@ -1756,6 +1793,7 @@ async def stop_training(save (bool): If True (default), save the model at the current checkpoint.expected_job_id (str): Identifier of the job the caller intends to stop."""+ require_job_owner(get_training_backend())try:backend = get_training_backend()outcome = await asyncio.to_thread(@@ -1797,6 +1835,7 @@ async def reset_training(body: Optional[TrainingResetRequest] = None, current_subject: str = Depends(get_current_subject)):"""Reset training state so the user can return to configuration."""+ require_job_owner(get_training_backend())try:backend = get_training_backend()result = await asyncio.to_thread(@@ -1848,6 +1887,13 @@ def _training_status_identity(backend) -> TrainingStatusIdentitySnapshot:def _build_training_status(backend, identity: TrainingStatusIdentitySnapshot, is_active: bool) -> TrainingStatus:+ if job_is_foreign(backend):+ return TrainingStatus(+ job_id = "",+ phase = "idle",+ is_training_running = False,+ message = "Busy" if job_busy(backend) else "Ready to train",+ )owner_job_id = identity.current_job_idjob_id = owner_job_idstart_request_id = identity.current_start_request_id@@ -2011,6 +2057,16 @@ async def get_training_metrics("""Get training metrics (loss, learning rate, steps)."""+ if job_is_foreign(get_training_backend()):+ return TrainingMetricsResponse(+ job_id = "",+ loss_history = [],+ lr_history = [],+ step_history = [],+ current_loss = None,+ current_lr = None,+ current_step = None,+ )try:backend = get_training_backend()job_id = getattr(backend, "current_job_id", "") or ""@@ -2088,6 +2144,9 @@ async def stream_training_progress(async def event_generator():backend = get_training_backend()+ if job_is_foreign(backend):+ yield 'event: busy\ndata: {"status":"busy"}\n\n'+ returnbackend_job_id = getattr(backend, "current_job_id", "") or ""job_id = expected_job_id if expected_job_id is not None else backend_job_id@@ -2268,6 +2327,9 @@ async def stream_training_progress()while True:+ if job_is_foreign(backend):+ yield 'event: busy\ndata: {"status":"busy"}\n\n'+ returnif not is_current_job():returnis_active = await asyncio.to_thread(run_active)@@ -2424,7 +2486,7 @@ async def stream_training_progress()return StreamingResponse(- event_generator(),+ account_event_stream(get_training_backend(), event_generator()),media_type = "text/event-stream",headers = {"Cache-Control": "no-cache",@@ -2637,8 +2699,12 @@ def _resolve_diffusion_data_dir(raw: str) -> Path:# Route a bare name through the same protected resolver the CRUD routes use, so a symlink to an external# directory is rejected here too. A broken symlink is included so it is rejected, not passed on.if direct.is_dir() or direct.is_symlink():- return _resolve_dataset_folder(value)- return resolve_dataset_path(raw)+ resolved = _resolve_dataset_folder(value)+ account_path(resolved)+ return resolved+ resolved = resolve_dataset_path(raw)+ account_path(resolved)+ return resolveddef _preflight_diffusion_resume(@@ -2740,6 +2806,8 @@ async def start_diffusion_training(except ValueError as e:raise HTTPException(status_code = 400, detail = str(e))+ validate_job_paths(config)+# Validate the config BEFORE freeing resident GPU workloads, so a refused start never tears down the user's# chat/Images model. service.start() re-runs this before spawn.from core.training.diffusion_lora_trainer import _config_from_dictdiff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex e41463b4ea3..a145d9e0bc8 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -17,6 +17,7 @@ from __future__ import annotationsimport asyncioimport base64import hashlib as _hashlib+import inspectimport hmac as _hmacimport re as _reimport secrets as _secrets@@ -34,6 +35,9 @@ from starlette.datastructures import UploadFilefrom auth.authentication import get_current_subject, request_admitted_without_credentialfrom core.inference.model_ids import public_model_idfrom hub.dependencies import get_hf_token+from hub.services.models import account_access+from hub.services.models.account_access import media_link_account, media_link_target+from utils.account_context import run_asfrom loggers import get_loggerfrom loggers.media_progress import (byte_fraction,@@ -59,6 +63,7 @@ from models.inference import (VideoLoadRequest,VideoStatusResponse,)+from utils.account_context import current_account_id, is_owner_contextfrom utils.api_errors import openai_error_bodyfrom utils.upload_limits import VIDEO_INPUT_REFERENCE_MAX_BYTES@@ -132,6 +137,17 @@ async def video_download_plan():"""The repos + files this pick needs, so the frontend stages them through the Hubdownload manager instead of the load downloading inline. Mirrors /images/download-plan."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_references, request)+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.model_path)+ if request.base_repo:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.base_repo)+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )from core.inference.diffusion import resolve_local_single_filefrom core.inference.video import (assert_video_precision_available,@@ -210,6 +226,7 @@ async def video_download_plan(@router.post("/video/load", response_model = VideoStatusResponse)+@account_access.gpu_busy_routeasync def load_video_model(request: VideoLoadRequest, current_subject: str = Depends(get_current_subject)):@@ -225,12 +242,29 @@ async def load_video_model_gated("""Everything ``POST /video/load`` does, plus who asked for it. Media auto-switch awaits this rather than theroute so the idle unload can tell an API-loaded pipeline from one the user picked on the Video page."""+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_references, request)+ account_access.require_idle_other_accounts()+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.model_path)+ if request.base_repo:+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_model_access, request.base_repo)+ if account_access.managed_account():+ request = request.model_copy(+ update = {"hf_token": account_access.account_hf_token(request.hf_token)}+ )from core.inference.diffusion import resolve_local_single_filefrom core.inference.diffusion_device import (resolve_diffusion_device_target,resolve_selected_cuda_ordinal,)- from core.inference.gpu_arbiter import VIDEO, acquire_for, release+ from core.inference.gpu_arbiter import (+ VIDEO,+ acquire_for_request,+ release,+ require_no_foreign_generations,+ )from core.inference.media_keepwarm import note_load_originfrom hub.utils.gguf import extract_quant_tokenfrom core.inference.video import (@@ -299,7 +333,7 @@ async def load_video_model_gated(# no-op).device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)- def _begin_load():+ def _start_load():# Kicks the (slow) load onto a background thread and returns at once; begin_load itself validates# network-free.return backend.begin_load(@@ -326,6 +360,11 @@ async def load_video_model_gated(gpu_ordinal = gpu_ordinal,)+ def _begin_load():+ return account_access.admit_media_load("video", _start_load, request.model_path)++ # begin_load signals whatever generation is running, so guard on every device.+ require_no_foreign_generations()if device != "cpu":# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts VIDEO# before the load is marked, finds nothing to cancel, and both allocate at once. The training admission wraps@@ -333,7 +372,7 @@ async def load_video_model_gated(from routes.inference import _diffusion_training_admissiondef _acquire_and_begin():with _diffusion_training_admission():- return acquire_for(VIDEO, _begin_load)+ return acquire_for_request(VIDEO, _begin_load)status_dict = await asyncio.to_thread(_acquire_and_begin)else:@@ -348,10 +387,18 @@ async def load_video_model_gated(request.h3_task or _derived_h3_task(request.gguf_filename, kind),user_action = user_initiated,)+ account_access.note_resident_components(+ "video",+ request.model_path,+ request.base_repo,+ *account_access.media_adapter_references(request),+ )reset_media_load_progress("video")return VideoStatusResponse(**status_dict)except (ValueError, FileNotFoundError) as exc:raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))+ except account_access.GpuBusyForAnotherAccountError as exc:+ raise account_access.gpu_busy_error() from excexcept RuntimeError as exc:# A video load is already in progress.raise HTTPException(status_code = 409, detail = str(exc))@@ -359,15 +406,80 @@ async def load_video_model_gated(@router.get("/video/load-progress", response_model = VideoLoadProgressResponse)async def video_load_progress(current_subject: str = Depends(get_current_subject)):+ if account_access.resident_hidden("video"):+ return account_access.hidden_resident_response()from core.inference.video import get_video_backend+ if account_access.managed_account() and account_access.resident_hidden(+ "video", get_video_backend().status().get("repo_id")+ ):+ return account_access.hidden_resident_response()progress = get_video_backend().load_progress()fraction = byte_fraction(progress.get("downloaded_bytes"), progress.get("expected_bytes"))log_media_load_progress("video", progress.get("phase"), fraction)return VideoLoadProgressResponse(**progress)+_generation_account: Optional[str] = None+_generation_lock = threading.Lock()+++def _note_generation_account() -> None:+ global _generation_account+ from utils.account_context import current_account+ with _generation_lock:+ _generation_account = current_account().account_id+++def _reserved_generation_account(backend) -> Optional[str]:+ reserved = getattr(backend, "generate_job_account", None)+ return reserved() if callable(reserved) else None+++def _generation_started_by(backend) -> Optional[str]:+ """The backend's own reservation wins: it is taken before begin_generate returns."""+ reserved = _reserved_generation_account(backend)+ if reserved is not None:+ return reserved+ with _generation_lock:+ return _generation_account+++def _read_generate_progress(backend, expected_account):+ """Recheck progress against the authorized reservation, if the backend supports it."""+ if expected_account is None:+ return backend.generate_progress()+ try:+ params = inspect.signature(backend.generate_progress).parameters+ except (TypeError, ValueError):+ params = {}+ accepts = "expected_account" in params or any(+ p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()+ )+ if not accepts:+ return backend.generate_progress()+ return backend.generate_progress(expected_account = expected_account)+++_UNREAD = object()+++def _generation_hidden(backend, started_by = _UNREAD) -> bool:+ """A caller that acts on the reservation passes the read it will act on."""+ if started_by is _UNREAD:+ started_by = _generation_started_by(backend)+ if started_by is not None:+ # Owner included: administering the machine covers a resident model, not a clip's prompt.+ from utils.account_context import current_account+ return started_by != current_account().account_id+ return account_access.resident_hidden("video") or (+ account_access.managed_account()+ and account_access.resident_hidden("video", backend.status().get("repo_id"))+ )++@router.post("/video/generate", response_model = VideoGenerateResponse)+@account_access.gpu_busy_routeasync def generate_video(request: VideoGenerateRequest,current_subject: str = Depends(get_current_subject),@@ -386,6 +498,7 @@ async def generate_video(from core.inference.video import get_video_backendfrom core.inference.video_families import (VIDEO_GENERATION_BUSY_MSG,+ VIDEO_MODEL_CHANGED_MSG,VIDEO_NOT_LOADED_MSG,VideoShapeError,)@@ -447,47 +560,64 @@ async def generate_video(raise HTTPException(status_code = 400, detail = str(exc))backend = get_video_backend()- # The real rule is the LOADED family's, applied by begin_generate under the same lock that reserves the state,- # so a concurrent load cannot leave the shape judged against one family and denoised by another. Unloaded still- # falls through to the not-loaded 409, and a family with no declared presets keeps the old SIZE snapping, though- # frame_step is declared regardless.- try:- await asyncio.to_thread(- backend.begin_generate,- prompt = request.prompt,- negative_prompt = request.negative_prompt,- width = request.width,- height = request.height,- num_frames = request.num_frames,- fps = request.fps,- steps = request.steps,- guidance = request.guidance,- guidance_2 = request.guidance_2,- seed = request.seed,- first_frame = request.first_frame,- last_frame = request.last_frame,- reference_images = request.reference_images,- reference_videos = [r.model_dump() for r in request.reference_videos or []] or None,- reference_audios = request.reference_audios,- reference_image_size = request.reference_image_size,- flow_shift = request.flow_shift,- audio_flow_shift = request.audio_flow_shift,- )- except VideoShapeError as exc:- # 422 before the 400 below, and it must stay first: VideoShapeError IS a ValueError.- raise HTTPException(status_code = 422, detail = str(exc))- except ValueError as exc:- # Bad client input -- a 400 with the reason, not a generic 500.- raise HTTPException(status_code = 400, detail = str(exc))- except RuntimeError as exc:- # Only the not-loaded / busy sentinels are client-state (409); match exactly so an unrelated failure cannot leak- # its message.- msg = str(exc)- if msg in (VIDEO_NOT_LOADED_MSG, VIDEO_GENERATION_BUSY_MSG):- raise HTTPException(status_code = 409, detail = msg)- logger.error("video.generate_failed: %s", exc, exc_info = True)- raise HTTPException(status_code = 500, detail = "Video generation failed.")+ generate_kwargs = dict(+ prompt = request.prompt,+ negative_prompt = request.negative_prompt,+ width = request.width,+ height = request.height,+ num_frames = request.num_frames,+ fps = request.fps,+ steps = request.steps,+ guidance = request.guidance,+ guidance_2 = request.guidance_2,+ seed = request.seed,+ first_frame = request.first_frame,+ last_frame = request.last_frame,+ reference_images = request.reference_images,+ reference_videos = [r.model_dump() for r in request.reference_videos or []] or None,+ reference_audios = request.reference_audios,+ reference_image_size = request.reference_image_size,+ flow_shift = request.flow_shift,+ audio_flow_shift = request.audio_flow_shift,+ )+ # Authorize the exact resident token from generation_snapshot and pin it to the reservation,+ # so a load committing in the gap cannot render another account's weights here; on a mismatch,+ # re-authorize once and retry. begin_generate judges shape against the LOADED family under the+ # same lock that reserves the state, so a concurrent load cannot judge and denoise against two.+ for attempt in range(2):+ expected_state = None+ if account_access.managed_account():+ status, expected_state = await asyncio.to_thread(backend.generation_snapshot)+ await asyncio.to_thread(account_access.require_media_generation_access, status, "video")+ try:+ await asyncio.to_thread(+ backend.begin_generate,+ **generate_kwargs,+ **({"expected_state": expected_state} if expected_state is not None else {}),+ )+ except VideoShapeError as exc:+ # Must stay before the 400 below: VideoShapeError IS a ValueError.+ raise HTTPException(status_code = 422, detail = str(exc))+ except ValueError as exc:+ # Bad client input: 400 with the reason, not a generic 500.+ raise HTTPException(status_code = 400, detail = str(exc))+ except RuntimeError as exc:+ # Only the not-loaded / busy / replaced sentinels are 409; match exactly so+ # an unrelated failure cannot leak its message.+ msg = str(exc)+ if msg == VIDEO_MODEL_CHANGED_MSG and attempt == 0:+ continue+ if msg in (+ VIDEO_NOT_LOADED_MSG,+ VIDEO_GENERATION_BUSY_MSG,+ VIDEO_MODEL_CHANGED_MSG,+ ):+ raise HTTPException(status_code = 409, detail = msg)+ logger.error("video.generate_failed: %s", exc, exc_info = True)+ raise HTTPException(status_code = 500, detail = "Video generation failed.")+ break+ _note_generation_account()reset_media_generation_progress("video")return VideoGenerateResponse()@@ -496,7 +626,21 @@ async def generate_video(async def video_generate_progress(current_subject: str = Depends(get_current_subject)):from core.inference.video import get_video_backend- progress = get_video_backend().generate_progress()+ backend = get_video_backend()+ # One reservation read serves the visibility check; the backend rechecks the owner under+ # its lock, since begin_generate runs on a worker thread and a successor can reserve mid-poll.+ reserved = _reserved_generation_account(backend)+ if reserved is not None:+ started_by = reserved+ else:+ with _generation_lock:+ started_by = _generation_account+ if _generation_hidden(backend, started_by):+ return account_access.hidden_resident_response()+ progress = _read_generate_progress(backend, reserved)+ if progress is None:+ # The reservation changed hands mid-poll; the successor's progress is not ours to see.+ return account_access.hidden_resident_response()log_media_generation_progress("video", progress)return VideoGenerateProgressResponse(**progress)@@ -504,23 +648,57 @@ async def video_generate_progress(current_subject: str = Depends(get_current_sub@router.post("/video/generate/cancel")async def cancel_video_generation(current_subject: str = Depends(get_current_subject)):from core.inference.video import get_video_backend- cancelled = await asyncio.to_thread(get_video_backend().cancel_generate)++ backend = get_video_backend()+ # One read serves check and recheck: a second read could name a successor and hand it back+ # as expected_account.+ reserved = _reserved_generation_account(backend)+ if reserved is not None:+ started_by = reserved+ else:+ with _generation_lock:+ started_by = _generation_account+ if _generation_hidden(backend, started_by):+ return {"cancelled": False}+ if started_by is None and account_access.foreign_work_active():+ return {"cancelled": False}+ if reserved is None:+ # No reservation yet: bind the cancel to the caller, else an account reserving before the+ # executor runs would receive it.+ from utils.account_context import current_account+ expected = current_account().account_id+ else:+ expected = reserved+ cancelled = await asyncio.to_thread(backend.cancel_generate, expected_account = expected)return {"cancelled": cancelled}@router.get("/video/status", response_model = VideoStatusResponse)async def video_status(current_subject: str = Depends(get_current_subject)):+ if account_access.resident_hidden("video"):+ return account_access.hidden_resident_response()from core.inference.video import get_video_backend- return VideoStatusResponse(**get_video_backend().status())++ status_dict = get_video_backend().status()+ if account_access.resident_hidden("video", status_dict.get("repo_id")):+ return account_access.hidden_resident_response()+ return VideoStatusResponse(**status_dict)@router.post("/video/unload", response_model = VideoStatusResponse)+@account_access.gpu_busy_routeasync def unload_video_model(current_subject: str = Depends(get_current_subject)):+ account_access.require_resident_control("video")from core.inference.gpu_arbiter import VIDEO, release_iffrom core.inference.video import get_video_backendbackend = get_video_backend()- status_dict = await asyncio.to_thread(backend.unload)+ if account_access.managed_account():+ account_access.require_resident_control("video", backend.status().get("repo_id"))+ unload_kwargs = {}+ if account_access.account_scope() is not None:+ unload_kwargs["expected_account"] = current_account_id()+ status_dict = await asyncio.to_thread(backend.unload, **unload_kwargs)# Drop VIDEO ownership only if nothing is resident AND no load is in flight; the check and release must be ATOMIC# (release_if). Mirrors images.await asyncio.to_thread(@@ -594,7 +772,7 @@ _VIDEO_LINK_SECRET = _secrets.token_bytes(32)def _sign_video_id(video_id: str) -> str:exp = int(_time.time()) + _VIDEO_LINK_TTL- payload = f"{video_id}.{exp}"+ payload = f"{media_link_target(video_id)}.{exp}"sig = _hmac.new(_VIDEO_LINK_SECRET, payload.encode(), _hashlib.sha256).hexdigest()return f"{payload}.{sig}"@@ -650,9 +828,10 @@ async def get_gallery_video_file_signed(video_id: str, token: str = Query(...)):the token names the single clip it may serve."""from core.inference import video_gallery- if _verify_video_link_token(token) != video_id:+ account = media_link_account(_verify_video_link_token(token), video_id)+ if account is None:raise HTTPException(status_code = 401, detail = "Invalid or expired video link.")- path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)+ path = await asyncio.to_thread(run_as, account, video_gallery.owned_video_path, video_id)if path is None:raise HTTPException(status_code = 404, detail = "Video not found.")from fastapi.responses import FileResponse@@ -809,6 +988,14 @@ class _VideoJob:_jobs: dict[str, _VideoJob] = {}_jobs_lock = threading.Lock()+_managed_jobs: dict[str, dict[str, _VideoJob]] = {}+++def _account_jobs() -> dict[str, _VideoJob]:+ """Called under _jobs_lock; the owner's registry and ids stay unchanged."""+ if is_owner_context():+ return _jobs+ return _managed_jobs.setdefault(current_account_id(), {})def _forget_openai_job(video_id: str) -> bool:@@ -818,7 +1005,7 @@ def _forget_openai_job(video_id: str) -> bool:with _jobs_lock:if not video_gallery.forget_job(video_id):return False- _jobs.pop(video_id, None)+ _account_jobs().pop(video_id, None)return True@@ -968,19 +1155,19 @@ def _remember_job(job: _VideoJob) -> None:from core.inference import video_gallerywith _jobs_lock:- pending = [existing for existing in _jobs.values() if not existing.terminal]+ pending = [existing for existing in _account_jobs().values() if not existing.terminal]for existing in pending:persisted = _job_from_record(video_gallery.get_job(existing.id) or {})if persisted is not None and persisted.terminal:with _jobs_lock:- if _jobs.get(existing.id) is existing:- _jobs[existing.id] = persisted+ if _account_jobs().get(existing.id) is existing:+ _account_jobs()[existing.id] = persistedwith _jobs_lock:- _jobs[job.id] = job- excess = len(_jobs) - _MAX_REMEMBERED_JOBS+ _account_jobs()[job.id] = job+ excess = len(_account_jobs()) - _MAX_REMEMBERED_JOBSif excess > 0:- for stale in [j for j in _jobs.values() if j.terminal][:excess]:- _jobs.pop(stale.id, None)+ for stale in [j for j in _account_jobs().values() if j.terminal][:excess]:+ _account_jobs().pop(stale.id, None)try:video_gallery.save_job(job.id, asdict(job))except OSError as exc:@@ -1016,11 +1203,11 @@ def _job_from_record(record: dict) -> Optional[_VideoJob]:def _hydrate_job(video_id: str) -> None:from core.inference import video_gallerywith _jobs_lock:- if video_id in _jobs:+ if video_id in _account_jobs():returnjob = _job_from_record(video_gallery.get_job(video_id) or {})if job is not None:- _jobs.setdefault(job.id, job)+ _account_jobs().setdefault(job.id, job)def _hydrate_jobs() -> list[_VideoJob]:@@ -1031,7 +1218,7 @@ def _hydrate_jobs() -> list[_VideoJob]:]jobs.sort(key = lambda job: job.created_at, reverse = True)for job in jobs[:_MAX_REMEMBERED_JOBS]:- _jobs.setdefault(job.id, job)+ _account_jobs().setdefault(job.id, job)return jobs@@ -1041,7 +1228,7 @@ def _sync_jobs() -> None:from core.inference.video_families import VIDEO_CANCELLED_MSGwith _jobs_lock:- open_jobs = [job for job in _jobs.values() if not job.terminal]+ open_jobs = [job for job in _account_jobs().values() if not job.terminal]if not open_jobs:returngen = get_video_backend().generate_progress()@@ -1050,8 +1237,8 @@ def _sync_jobs() -> None:persisted_job = _job_from_record(video_gallery.get_job(job.id) or {})if persisted_job is not None and persisted_job.terminal:with _jobs_lock:- if _jobs.get(job.id) is job:- _jobs[job.id] = persisted_job+ if _account_jobs().get(job.id) is job:+ _account_jobs()[job.id] = persisted_jobcontinuestatus: Optional[str] = Noneprogress = 0@@ -1084,7 +1271,7 @@ def _sync_jobs() -> None:"message": "The generation ended before a clip was saved.",}with _jobs_lock:- if _jobs.get(job.id) is not job:+ if _account_jobs().get(job.id) is not job:continueif job.terminal:continue@@ -1128,7 +1315,7 @@ def _lookup_video(video_id: str) -> Optional[VideoJob]:_hydrate_job(video_id)_sync_jobs()with _jobs_lock:- job = _jobs.get(video_id)+ job = _account_jobs().get(video_id)if job is not None and job.status != "completed":return _job_to_openai(job)record = video_gallery.get_record(video_id)@@ -1144,7 +1331,7 @@ def _all_videos() -> list[VideoJob]:_sync_jobs()with _jobs_lock:jobs = {job.id: job for job in persisted_jobs}- jobs.update(_jobs)+ jobs.update(_account_jobs())records = video_gallery.list_videos(None, 0, valid = _valid_gallery_video_record)records.extend(video_gallery.list_videos(None, 0, valid = _valid_gallery_video_record, archived = True)@@ -1249,6 +1436,7 @@ async def _reference_to_data_url(reference: Any) -> Optional[str]:@openai_router.post("/videos", response_model = VideoJob)+@account_access.gpu_busy_routeasync def openai_create_video(request: Request,current_subject: str = Depends(get_current_subject),@@ -1386,56 +1574,66 @@ async def _create_openai_video(raise _openai_video_error(400, str(exc), param = "input_reference")backend = get_video_backend()- expected_state = None- if pin_requested_model:- status, expected_state = await asyncio.to_thread(backend.generation_snapshot)- if not await asyncio.to_thread(- resident_answers_media_request, status, body.model, owner = VIDEO- ):- raise _openai_video_error(- 409,- VIDEO_MODEL_CHANGED_MSG,- code = "model_changed",- param = "model",- )- else:- status = await asyncio.to_thread(backend.status)- if not status.get("loaded"):- raise HTTPException(status_code = 503, detail = _NO_VIDEO_MODEL_MSG)- defaults = status.get("defaults") or {}- num_frames = _frames_for_seconds(seconds, defaults) if seconds is not None else Nonevideo_id = _VIDEO_JOB_ID_PREFIX + uuid.uuid4().hex- try:- generate_kwargs = dict(- prompt = body.prompt,- width = width,- height = height,- duration_s = seconds,- input_reference = reference,- video_id = video_id,- )- if expected_state is not None:- generate_kwargs["expected_state"] = expected_state- resolved = await asyncio.to_thread(backend.begin_generate, **generate_kwargs)- except VideoShapeError as exc:- raise _openai_video_error(- 400, str(exc), param = "seconds" if "frame count" in str(exc) else "size"- )- except ValueError as exc:- raise _openai_video_error(- 400, str(exc), param = "input_reference" if reference is not None else None- )- except RuntimeError as exc:- msg = str(exc)- if msg == VIDEO_NOT_LOADED_MSG:+ # Managed callers are authorized against the exact resident state, pinned to the reservation;+ # on a mismatch, re-authorize once and retry, as /video/generate does.+ pin_state = pin_requested_model or account_access.managed_account()+ for attempt in range(2):+ expected_state = None+ if pin_state:+ status, expected_state = await asyncio.to_thread(backend.generation_snapshot)+ if pin_requested_model and not await asyncio.to_thread(+ resident_answers_media_request, status, body.model, owner = VIDEO+ ):+ raise _openai_video_error(+ 409,+ VIDEO_MODEL_CHANGED_MSG,+ code = "model_changed",+ param = "model",+ )+ else:+ status = await asyncio.to_thread(backend.status)+ if not status.get("loaded"):raise HTTPException(status_code = 503, detail = _NO_VIDEO_MODEL_MSG)- if msg == VIDEO_GENERATION_BUSY_MSG:- raise _openai_video_error(409, msg)- if msg == VIDEO_MODEL_CHANGED_MSG:- raise _openai_video_error(409, msg, code = "model_changed", param = "model")- logger.error("openai_videos.generate_failed: %s", exc, exc_info = True)- raise HTTPException(status_code = 500, detail = "Video generation failed.")-+ if account_access.managed_account():+ await asyncio.to_thread(account_access.require_media_generation_access, status, "video")+ defaults = status.get("defaults") or {}+ num_frames = _frames_for_seconds(seconds, defaults) if seconds is not None else None+ try:+ generate_kwargs = dict(+ prompt = body.prompt,+ width = width,+ height = height,+ duration_s = seconds,+ input_reference = reference,+ video_id = video_id,+ )+ if expected_state is not None:+ generate_kwargs["expected_state"] = expected_state+ resolved = await asyncio.to_thread(backend.begin_generate, **generate_kwargs)+ except VideoShapeError as exc:+ raise _openai_video_error(+ 400, str(exc), param = "seconds" if "frame count" in str(exc) else "size"+ )+ except ValueError as exc:+ raise _openai_video_error(+ 400, str(exc), param = "input_reference" if reference is not None else None+ )+ except RuntimeError as exc:+ msg = str(exc)+ if msg == VIDEO_NOT_LOADED_MSG:+ raise HTTPException(status_code = 503, detail = _NO_VIDEO_MODEL_MSG)+ if msg == VIDEO_GENERATION_BUSY_MSG:+ raise _openai_video_error(409, msg)+ if msg == VIDEO_MODEL_CHANGED_MSG:+ if attempt == 0:+ continue+ raise _openai_video_error(409, msg, code = "model_changed", param = "model")+ logger.error("openai_videos.generate_failed: %s", exc, exc_info = True)+ raise HTTPException(status_code = 500, detail = "Video generation failed.")+ break++ _note_generation_account()reset_media_generation_progress("video")# begin_generate hands back the canvas it resolved. Without it a reference-imagediff --git a/studio/backend/state/active_generations.py b/studio/backend/state/active_generations.pyindex 9b17627d25b..a97312a1da4 100644--- a/studio/backend/state/active_generations.py+++ b/studio/backend/state/active_generations.py@@ -23,10 +23,14 @@ import timeimport uuidfrom typing import Any, Optional+from utils.account_context import current_account_id+# Keyed by handle, not thread_id: a tool continuation can register before the previous leg# unregisters, and one key would drop the other._ACTIVE: dict[str, dict[str, Any]] = {}_LOCK = threading.Lock()+# Disabled or retired accounts: a generation registering late for one starts cancelled.+_FENCED: set[str] = set()class ActiveGeneration:@@ -41,6 +45,7 @@ class ActiveGeneration:"cancel_event","model","kind",+ "account_id","_handle","_borrowed",)@@ -53,7 +58,9 @@ class ActiveGeneration:run_id: Optional[str] = None,model: Optional[str] = None,kind: str = "chat",+ account_id: Optional[str] = None,):+ self.account_id = account_id or current_account_id()self.thread_id = thread_id or Noneself.run_id = run_id or Noneself.cancel_event = cancel_event@@ -68,7 +75,11 @@ class ActiveGeneration:# tracker with that same event and run, so borrow the outer registration.if self.run_id:for entry in _ACTIVE.values():- if entry["run_id"] != self.run_id or entry["event"] is not self.cancel_event:+ if (+ entry["run_id"] != self.run_id+ or entry["event"] is not self.cancel_event+ or entry["account_id"] != self.account_id+ ):continueif self.thread_id:entry["thread_id"] = self.thread_id@@ -85,9 +96,12 @@ class ActiveGeneration:"run_id": self.run_id,"model": self.model,"kind": self.kind,+ "account_id": self.account_id,"started_at": time.time(),"event": self.cancel_event,}+ if self.account_id in _FENCED:+ self.cancel_event.set()return selfdef __exit__(self, *exc) -> bool:@@ -101,10 +115,12 @@ class ActiveGeneration:return False-def snapshot() -> list[dict[str, Any]]:- """In-flight generations, newest last. Drops the Event: this is a response."""+def snapshot(account_id: Optional[str] = None) -> list[dict[str, Any]]:+ """In-flight generations, newest last; ``account_id`` None (all) is shutdown/arbiter only."""with _LOCK:- entries = list(_ACTIVE.values())+ entries = [+ e for e in _ACTIVE.values() if account_id is None or e["account_id"] == account_id+ ]entries.sort(key = lambda e: e["started_at"])return [{@@ -113,41 +129,49 @@ def snapshot() -> list[dict[str, Any]]:"run_id": e["run_id"],"model": e["model"],"kind": e["kind"],+ "account_id": e["account_id"],"started_at": e["started_at"],}for e in entries]-def active_thread_ids() -> list[str]:+def active_thread_ids(account_id: Optional[str] = None) -> list[str]:"""Distinct conversation ids with a generation in flight, in start order.A first turn that races persistence has no thread id yet: count() sees it,this cannot name it."""seen: list[str] = []- for e in snapshot():+ for e in snapshot(account_id):tid = e["thread_id"]if tid and tid not in seen:seen.append(tid)return seen-def count() -> int:- """Number of generations currently in flight."""+def count(account_id: Optional[str] = None) -> int:with _LOCK:- return len(_ACTIVE)+ if account_id is None:+ return len(_ACTIVE)+ return sum(1 for e in _ACTIVE.values() if e["account_id"] == account_id)++def foreign_count(account_id: str) -> int:+ """Generations in flight for OTHER accounts, which a load or unload must not interrupt."""+ with _LOCK:+ return sum(1 for e in _ACTIVE.values() if e["account_id"] != account_id)-def cancel_all() -> int:- """Signal every in-flight generation to stop. Returns how many were signalled.- Only sets the cancel events; each stream tears itself down. Entries are- removed by their own __exit__, so one mid-cleanup is neither lost nor double- counted.- """+def cancel_all(account_id: Optional[str] = None) -> int:+ """Signal in-flight generations to stop, returning the count. Request-driven callers must pass+ ``account_id``; None means everyone and is for shutdown only."""with _LOCK:- events = [e["event"] for e in _ACTIVE.values()]+ events = [+ e["event"]+ for e in _ACTIVE.values()+ if account_id is None or e["account_id"] == account_id+ ]for ev in events:try:ev.set()@@ -156,12 +180,17 @@ def cancel_all() -> int:return len(events)-def cancel_thread(thread_id: str) -> int:- """Signal only the generations belonging to ``thread_id``."""+def cancel_thread(thread_id: str, account_id: Optional[str] = None) -> int:+ """Signal ``thread_id``'s generations; thread ids are client-chosen, so scope by account."""if not thread_id:return 0+ scope = account_id or current_account_id()with _LOCK:- events = [e["event"] for e in _ACTIVE.values() if e["thread_id"] == thread_id]+ events = [+ e["event"]+ for e in _ACTIVE.values()+ if e["thread_id"] == thread_id and e["account_id"] == scope+ ]for ev in events:try:ev.set()@@ -170,12 +199,16 @@ def cancel_thread(thread_id: str) -> int:return len(events)-def cancel_run(run_id: str) -> int:- """Signal only the generation registered for a durable Studio run."""+def cancel_run(run_id: str, account_id: Optional[str] = None) -> int:if not run_id:return 0+ scope = account_id or current_account_id()with _LOCK:- events = [e["event"] for e in _ACTIVE.values() if e["run_id"] == run_id]+ events = [+ e["event"]+ for e in _ACTIVE.values()+ if e["run_id"] == run_id and e["account_id"] == scope+ ]for ev in events:try:ev.set()@@ -184,7 +217,24 @@ def cancel_run(run_id: str) -> int:return len(events)+def fence(account_id: str) -> None:+ """Deactivation or retirement: work registering after ``cancel_all`` is cancelled on entry."""+ with _LOCK:+ _FENCED.add(account_id)+++def lift_fence(account_id: str) -> None:+ with _LOCK:+ _FENCED.discard(account_id)+++def fenced(account_id: str) -> bool:+ with _LOCK:+ return account_id in _FENCED++def reset_for_tests() -> None:"""Drop every entry. Test-only; never called from request paths."""with _LOCK:_ACTIVE.clear()+ _FENCED.clear()diff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.pyindex bab612eae7c..0938a11f71e 100644--- a/studio/backend/state/tool_policy.py+++ b/studio/backend/state/tool_policy.py@@ -28,6 +28,7 @@ passthrough guard are built around.import contextvarsfrom contextlib import contextmanager+from functools import partial, wrapsfrom typing import Iterator, Optional_tool_policy: Optional[bool] = None@@ -39,6 +40,51 @@ _force_disabled: contextvars.ContextVar[bool] = contextvars.ContextVar()+def require_tool_access(+ permission_mode: Optional[str] = None,+ *,+ bypass_permissions: bool = False,+ disable_sandbox: bool = False,+) -> None:+ if permission_mode != "full" and not bypass_permissions and not disable_sandbox:+ return+ from auth.policy import full_access_permitted+ from fastapi import HTTPException++ if not full_access_permitted():+ raise HTTPException(+ status_code = 400,+ detail = "Full access is unavailable while more than one account exists.",+ )+++def normalize_tool_permissions(+ permission_mode: Optional[str], bypass_permissions: bool+) -> tuple[str, bool]:+ require_tool_access(permission_mode, bypass_permissions = bypass_permissions)+ if permission_mode == "full" or bypass_permissions:+ return "full", True+ if permission_mode is None:+ return "auto", False+ if permission_mode not in ("ask", "auto", "off"):+ return "ask", False+ return permission_mode, False+++def account_tool_stream(stream):+ from utils.account_context import current_account, is_owner_context, run_as++ if is_owner_context():+ return stream+ account = current_account()++ @wraps(stream)+ def scoped(invoke, *args, **kwargs):+ return stream(partial(run_as, account, invoke), *args, **kwargs)++ return scoped++def get_tool_policy() -> Optional[bool]:if _force_disabled.get():return Falsediff --git a/studio/backend/storage/api_usage_db.py b/studio/backend/storage/api_usage_db.pyindex 60304f9b0b8..63a0ece54e3 100644--- a/studio/backend/storage/api_usage_db.py+++ b/studio/backend/storage/api_usage_db.py@@ -16,6 +16,7 @@ from dataclasses import dataclassfrom typing import Callable, Optionalfrom storage.studio_db import get_connection, is_sqlite_busy_error+from utils.account_context import AccountContext, current_account, run_as# Kept aligned with the API monitor's defensive upper bound; the storage layer validates@@ -172,6 +173,12 @@ def record_api_usage(receipt: ApiUsageReceipt) -> bool:return inserted+@dataclass(frozen = True, slots = True)+class _QueuedReceipt:+ account: AccountContext+ receipt: ApiUsageReceipt++_STOP = object()@@ -195,7 +202,7 @@ class ApiUsageWriter:with self._state_lock:if self._stopped:return False- self._queue.put_nowait(receipt)+ self._queue.put_nowait(_QueuedReceipt(current_account(), receipt))return Truedef stop(self, timeout: float = _WORKER_DRAIN_TIMEOUT_SECONDS) -> bool:@@ -228,7 +235,7 @@ class ApiUsageWriter:busy_failures = 0while True:try:- self._sink(item) # type: ignore[arg-type]+ run_as(item.account, self._sink, item.receipt)breakexcept sqlite3.OperationalError as exc:if not _is_busy_error(exc):diff --git a/studio/backend/storage/chat_generation_runs_db.py b/studio/backend/storage/chat_generation_runs_db.pyindex e7dd4edd2f4..c05c267f10c 100644--- a/studio/backend/storage/chat_generation_runs_db.py+++ b/studio/backend/storage/chat_generation_runs_db.py@@ -11,9 +11,11 @@ import secretsimport sqlite3import threadingimport time+from pathlib import Pathfrom typing import Any, Iterable, Unionfrom storage.studio_db import get_connection+from utils.paths import studio_db_pathACTIVE_STATUSES = frozenset({"queued", "running", "cancelling"})TERMINAL_STATUSES = frozenset({"cancelled", "completed", "failed"})@@ -23,8 +25,7 @@ _RUN_TOMBSTONE_PREFIX = "chat-generation-run-tombstone:"ChatGenerationEventInput = Union[tuple[str, dict[str, Any]], tuple[str, dict[str, Any], int]]# Progress lease columns live here rather than in _ensure_schema so the base table stays owned by-# studio_db; named _schema_ready to match the flag the test harness resets.-_schema_ready = False+_schema_ready: set[Path] = set()_schema_lock = threading.Lock()@@ -36,15 +37,27 @@ def now_ms() -> int:return int(time.time() * 1000)+def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()+++def _database_path(conn: sqlite3.Connection) -> Path:+ """The file this connection opened, so polling paths do not resolve the account root twice."""+ row = conn.execute("PRAGMA database_list").fetchone()+ return Path(row[2]) if row and row[2] else studio_db_path()++def _connect() -> sqlite3.Connection:"""get_connection plus the one-off progress-lease migration for this database."""- global _schema_readyconn = get_connection()- if _schema_ready:+ db_path = _database_path(conn)+ if db_path in _schema_ready:return conntry:with _schema_lock:- if not _schema_ready:+ schema_path = db_path.resolve()+ if schema_path not in _schema_ready:columns = {row[1]for row in conn.execute("PRAGMA table_info(chat_generation_runs)").fetchall()@@ -62,7 +75,7 @@ def _connect() -> sqlite3.Connection:if "duplicate column" not in str(exc).lower():raiseconn.commit()- _schema_ready = True+ _schema_ready.add(schema_path)except sqlite3.OperationalError:# A writer holds the database, and the columns are additive, so let this call through and migrate# later rather than turning contention into a failed history read.diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex fc45fff247f..fa0e43d3500 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -12,6 +12,7 @@ import loggingimport osimport sqlite3import threading+from pathlib import Pathfrom datetime import datetime, timezonefrom typing import Optional@@ -33,7 +34,7 @@ _FORMAT_VERSION = 1_NONCE_BYTES = 12_schema_lock = threading.Lock()-_schema_ready = False+_schema_ready: set[Path] = set()def _associated_data(credential_kind: str, scope_id: str) -> bytes:@@ -60,8 +61,12 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.commit()+def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()++def get_connection() -> sqlite3.Connection:- global _schema_readydb_path = studio_db_path()ensure_dir(db_path.parent)conn = sqlite3.connect(str(db_path), timeout = 5.0)@@ -71,12 +76,13 @@ def get_connection() -> sqlite3.Connection:os.chmod(db_path, 0o600)except OSError:pass- if not _schema_ready:+ if db_path not in _schema_ready:with _schema_lock:- if not _schema_ready:+ schema_path = db_path.resolve()+ if schema_path not in _schema_ready:try:_ensure_schema(conn)- _schema_ready = True+ _schema_ready.add(schema_path)except Exception:conn.close()raisediff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.pyindex d5f7190e2b5..b3c59c1f3e5 100644--- a/studio/backend/storage/mcp_servers_db.py+++ b/studio/backend/storage/mcp_servers_db.py@@ -3,13 +3,14 @@import sqlite3import threading+from pathlib import Pathfrom datetime import datetime, timezonefrom typing import Optionalfrom utils.paths import studio_db_path, ensure_dir_schema_lock = threading.Lock()-_schema_ready = False+_schema_ready: set[Path] = set()def _ensure_schema(conn: sqlite3.Connection) -> None:@@ -40,18 +41,23 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:)+def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()++def get_connection() -> sqlite3.Connection:- global _schema_readydb_path = studio_db_path()ensure_dir(db_path.parent)conn = sqlite3.connect(str(db_path))conn.row_factory = sqlite3.Row- if not _schema_ready:+ if db_path not in _schema_ready:with _schema_lock:- if not _schema_ready:+ schema_path = db_path.resolve()+ if schema_path not in _schema_ready:try:_ensure_schema(conn)- _schema_ready = True+ _schema_ready.add(schema_path)except Exception:conn.close()raise@@ -68,6 +74,9 @@ def create_server(builtin_id: Optional[str] = None,builtin_config_json: Optional[str] = None,) -> None:+ from core.inference.mcp_client import validate_mcp_address++ validate_mcp_address(url)now = datetime.now(timezone.utc).isoformat()conn = get_connection()try:@@ -100,6 +109,9 @@ def update_server(id: str, changes: dict) -> bool:"""Apply column updates and bump ``updated_at``. Returns True on a hit."""if not changes:return False+ if "url" in changes:+ from core.inference.mcp_client import validate_mcp_address+ validate_mcp_address(changes["url"])bool_cols = {"is_enabled", "use_oauth"}sets, params = [], []for col, value in changes.items():diff --git a/studio/backend/storage/profile_stats_db.py b/studio/backend/storage/profile_stats_db.pyindex d8819293852..72341661784 100644--- a/studio/backend/storage/profile_stats_db.py+++ b/studio/backend/storage/profile_stats_db.py@@ -25,6 +25,8 @@ from loggers import get_loggerfrom storage.api_usage_db import canonical_api_subjectfrom storage.studio_db import count_chat_message_attachments, get_connection+from utils.account_context import current_account_id+from utils.paths import studio_db_pathlogger = get_logger(__name__)@@ -43,7 +45,7 @@ RECENT_RUNS = 5CACHE_TTL_SECONDS = 20.0_cache_lock = threading.Lock()-_cache: dict[str, Any] = {"fingerprint": None, "expires_at": 0.0, "payload": None}+_cache: dict[str, dict[str, Any]] = {}def _as_float(value: Any) -> Optional[float]:@@ -613,15 +615,24 @@ def compute_profile_stats(subject = canonical_api_subject(subject)conn = get_connection()try:- fingerprint = (_fingerprint(conn, subject), days, tz_offset_minutes, tz_name)+ # The path is in the fingerprint, so a reused account id cannot read another database.+ fingerprint = (+ str(studio_db_path()),+ _fingerprint(conn, subject),+ days,+ tz_offset_minutes,+ tz_name,+ )now = time.monotonic()+ account_id = current_account_id()with _cache_lock:+ cached = _cache.get(account_id)if (- _cache["payload"] is not None- and _cache["fingerprint"] == fingerprint- and _cache["expires_at"] > now+ cached is not None+ and cached["fingerprint"] == fingerprint+ and cached["expires_at"] > now):- return _cache["payload"]+ return cached["payload"]started = time.perf_counter()fold = _fold_messages(conn, zone)@@ -712,17 +723,16 @@ def compute_profile_stats()with _cache_lock:- _cache["fingerprint"] = fingerprint- _cache["expires_at"] = time.monotonic() + CACHE_TTL_SECONDS- _cache["payload"] = payload+ _cache[account_id] = {+ "fingerprint": fingerprint,+ "expires_at": time.monotonic() + CACHE_TTL_SECONDS,+ "payload": payload,+ }return payloadfinally:conn.close()def invalidate_profile_stats_cache() -> None:- """Drop the memoised payload (used by tests and after history wipes)."""with _cache_lock:- _cache["fingerprint"] = None- _cache["expires_at"] = 0.0- _cache["payload"] = None+ _cache.pop(current_account_id(), None)diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex a24c8da6b47..b93f156f1cd 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -15,6 +15,7 @@ import jsonimport loggingimport sqlite3import threading+from pathlib import Pathfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom datetime import datetime, timezone@@ -25,7 +26,7 @@ logger = logging.getLogger(__name__)from utils.paths import studio_db_path, ensure_dir_schema_lock = threading.Lock()-_schema_ready = False+_schema_ready: set[Path] = set()_UNSET = object()@@ -57,7 +58,6 @@ def _row_models(row: sqlite3.Row) -> tuple[list[str], list[str]]:def _ensure_schema(conn: sqlite3.Connection) -> None:- """Create the llm_providers table if absent. Called once per process."""conn.execute("PRAGMA journal_mode=WAL")conn.execute("""@@ -83,19 +83,23 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE llm_providers ADD COLUMN max_output_tokens INTEGER")+def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()++def get_connection() -> sqlite3.Connection:- """Open studio.db with WAL mode, create table once per process."""- global _schema_readydb_path = studio_db_path()ensure_dir(db_path.parent)conn = sqlite3.connect(str(db_path))conn.row_factory = sqlite3.Row- if not _schema_ready:+ if db_path not in _schema_ready:with _schema_lock:- if not _schema_ready:+ schema_path = db_path.resolve()+ if schema_path not in _schema_ready:try:_ensure_schema(conn)- _schema_ready = True+ _schema_ready.add(schema_path)except Exception:conn.close()raisediff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex 956582131b6..7c7cdb9558a 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -17,6 +17,7 @@ import loggingimport reimport sqlite3import threading+from pathlib import Pathfrom datetime import datetime, timezonelogger = logging.getLogger(__name__)@@ -43,7 +44,7 @@ class RagExtensionUnavailable(RuntimeError):_schema_lock = threading.Lock()-_schema_ready = False+_schema_ready: set[Path] = set()# The dylib is either there or it is not, and the UI polls the KB list on a timer, so one warning# per process says everything the repeats would._unavailable_lock = threading.Lock()@@ -54,7 +55,6 @@ _extension_loaded = Falsedef _warn_unavailable_once(exc: BaseException | None = None) -> None:- """Log the sqlite-vec unavailability at most once per process."""global _unavailable_warnedwith _unavailable_lock:if _unavailable_warned:@@ -286,9 +286,14 @@ def ensure_linked_folder_columns(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE linked_folders ADD COLUMN withheld_paths TEXT")+def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()++def get_connection() -> sqlite3.Connection:"""Open rag.db (WAL + sqlite-vec loaded, schema created once). Raises if the extension is unavailable."""- global _schema_ready, _extension_loaded+ global _extension_loadedif not RAG_AVAILABLE:raise RagExtensionUnavailable(_RAG_UNAVAILABLE_MSG)@@ -311,12 +316,13 @@ def get_connection() -> sqlite3.Connection:# database does next. A monotonic flip, so no lock._extension_loaded = True- if not _schema_ready:+ if db_path not in _schema_ready:with _schema_lock:- if not _schema_ready:+ schema_path = db_path.resolve()+ if schema_path not in _schema_ready:try:_ensure_schema(conn)- _schema_ready = True+ _schema_ready.add(schema_path)except Exception:conn.close()raisediff --git a/studio/backend/storage/research_runs_db.py b/studio/backend/storage/research_runs_db.pyindex 98892a5091e..eca3f27bd7e 100644--- a/studio/backend/storage/research_runs_db.py+++ b/studio/backend/storage/research_runs_db.py@@ -5,6 +5,7 @@from __future__ import annotations+from core.training.account_jobs import account_is_retiredimport hashlibimport jsonimport sqlite3@@ -13,7 +14,7 @@ import timefrom typing import Anyfrom core.inference.web_access_policy import check_url_access-from storage.studio_db import get_connection+from storage.studio_db import get_connection as _studio_connectionACTIVE_STATUSES = frozenset({"planning", "awaiting_approval", "queued", "running", "paused", "cancelling"}@@ -23,6 +24,12 @@ ALL_STATUSES = ACTIVE_STATUSES | TERMINAL_STATUSES_EVENTS_CHANGED = threading.Condition()+def get_connection():+ if account_is_retired():+ raise RuntimeError("Account is retired")+ return _studio_connection()++class ResearchConflictError(RuntimeError):passdiff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 7b161ac1195..5b5e95ae672 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -23,7 +23,9 @@ logger = logging.getLogger(__name__)from typing import Any, Iterable, Optional+from utils.account_context import is_owner_contextfrom utils.paths import (+ ensure_account_dir,ensure_dir,project_workspaces_root,studio_db_path,@@ -97,7 +99,7 @@ def contains_sensitive_path_component(path: str) -> bool:_schema_lock = threading.Lock()-_schema_ready = False+_schema_ready: set[Path] = set()_SQLITE_IN_CHUNK_SIZE = 900_PROJECT_WORKSPACE_SUBDIRS = ("sandbox",)_CHAT_ATTACHMENT_INVENTORY_VERSION = 1@@ -297,7 +299,6 @@ def _replace_inventory_update_trigger(conn: sqlite3.Connection) -> None:def _ensure_schema(conn: sqlite3.Connection) -> None:- """Create tables and indexes if they don't exist. Called once per process."""conn.execute("PRAGMA journal_mode=WAL")conn.execute("""@@ -1211,50 +1212,76 @@ def _apply_wal_synchronous(conn: sqlite3.Connection) -> None:conn.execute("PRAGMA synchronous=NORMAL")+def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()++def get_connection(- busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS, *, check_same_thread: bool = True+ busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS,+ *,+ check_same_thread: bool = True,+ _manage_keeper: bool = True,) -> sqlite3.Connection:- """Open studio.db with WAL mode, create tables once per process, enable foreign keys."""- global _schema_readydb_path = studio_db_path()- ensure_dir(db_path.parent)+ ensure_account_dir(db_path.parent)conn = sqlite3.connect(str(db_path), timeout = busy_timeout_seconds, check_same_thread = check_same_thread)conn.row_factory = sqlite3.Row# foreign_keys is session-scoped; set per connectionconn.execute("PRAGMA foreign_keys=ON")- if not _schema_ready:+ if db_path not in _schema_ready:with _schema_lock:- if not _schema_ready:+ schema_path = db_path.resolve()+ if schema_path not in _schema_ready:try:_ensure_schema(conn)conn.commit()- _schema_ready = True+ # Both spellings, so a symlinked path skips the resolve next time.+ _schema_ready.update((schema_path, db_path))except Exception:conn.close()raise_apply_wal_synchronous(conn)+ # main.py only keeps the owner's DB open, so a managed account would checkpoint on every close.+ if (+ _manage_keeper+ and not is_owner_context()+ and db_path not in _wal_keepers+ and db_path not in _wal_unsupported+ ):+ try:+ open_wal_keeper(replace = False)+ except Exception:+ conn.close()+ raisereturn conn# Every accessor here opens and closes its own connection, so a writer is routinely the last# WAL participant, and sqlite checkpoints the WAL back into studio.db on that close. At the# durable chat stream's flush cadence that is several rewrites a second (#9934).-_wal_keeper: sqlite3.Connection | None = None+_wal_keepers: dict[Path, sqlite3.Connection] = {}_wal_keeper_lock = threading.Lock()+_wal_unsupported: set[Path] = set()-def open_wal_keeper() -> bool:- """Hold this database's WAL open for the process. Returns whether a keeper is engaged."""- # Replace rather than inherit: a keeper from an earlier lifespan can belong to another- # database or a dead thread, and reusing it would keep nothing for the current one.- close_wal_keeper()- global _wal_keeper+def open_wal_keeper(*, replace: bool = True) -> bool:+ """Hold this database's WAL open. ``replace = False`` leaves an existing keeper alone."""+ db_path = studio_db_path().resolve()with _wal_keeper_lock:+ if not replace:+ if db_path in _wal_keepers:+ return True+ if db_path in _wal_unsupported:+ return False+ previous = _wal_keepers.pop(db_path, None)+ if previous is not None:+ _close_keeper(previous)# Only ever runs the pragma below, on this thread. check_same_thread is off so a# keeper stranded by an earlier lifespan can still be closed from this one.- conn = get_connection(check_same_thread = False)+ conn = get_connection(check_same_thread = False, _manage_keeper = False)try:# What is in force, not what was asked for: journal_mode=WAL declines silently# on filesystems without shared-memory support and persists in the file. Nothing@@ -1266,25 +1293,37 @@ def open_wal_keeper() -> bool:return Falseif not isinstance(mode, str) or mode.lower() != "wal":conn.close()+ _wal_unsupported.add(db_path)logger.info("studio.db is in %s mode, not WAL; WAL keeper not engaged.", mode)return False- _wal_keeper = conn+ _wal_unsupported.discard(db_path)+ _wal_keepers[db_path] = connreturn True-def close_wal_keeper() -> None:- """Release the keeper; last-close checkpointing resumes."""- global _wal_keeper- with _wal_keeper_lock:- conn, _wal_keeper = _wal_keeper, None- if conn is None:- return+def _close_keeper(conn: sqlite3.Connection) -> None:try:conn.close()except Exception as exc:logger.warning("Could not close the studio.db WAL keeper: %s", exc)+def close_wal_keeper_for(path: str | Path) -> None:+ db_path = Path(path).resolve()+ with _wal_keeper_lock:+ conn = _wal_keepers.pop(db_path, None)+ if conn is not None:+ _close_keeper(conn)+++def close_wal_keeper() -> None:+ with _wal_keeper_lock:+ for conn in _wal_keepers.values():+ _close_keeper(conn)+ _wal_keepers.clear()+ _wal_unsupported.clear()++def create_run(id: str,model_name: str,@@ -1788,6 +1827,12 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:raise ValueError("The filesystem root cannot be registered")if _contains_sensitive_path_component(normalized):raise ValueError("Credential or configuration directories are not allowed")+ # A registered folder joins the browse allowlist and model index, so it must be the acting+ # account's own.+ from utils.paths.storage_roots import within_account++ if not within_account(Path(normalized)):+ raise ValueError("Path is outside this account's workspace")# Windows: normcase for the denylist check but store original casing (e.g. C:\Models).is_win = platform.system() == "Windows"diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 19ffe04e18a..9047eddde5b 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -108,7 +108,7 @@ def _isolate_studio_home(_studio_home_root, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))for name, module in tuple(sys.modules.items()):if name.startswith(("storage.", "hub.storage.")) and hasattr(module, "_schema_ready"):- monkeypatch.setattr(module, "_schema_ready", False)+ monkeypatch.setattr(module, "_schema_ready", set())# Pytest CLI options@@ -781,7 +781,7 @@ def rag_home(tmp_path, monkeypatch, linkable_temp_base):root = linkable_temp_base / tmp_path.nameroot.mkdir(parents = True, exist_ok = True)monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(root))- monkeypatch.setattr(rag_db, "_schema_ready", False)+ monkeypatch.setattr(rag_db, "_schema_ready", set())return root@@ -807,8 +807,10 @@ def stub_embeddings(monkeypatch):import hashlibimport math- from core.rag import embeddings+ from core.rag import config, embeddings+ # Pin the backend: "auto" reprobes the hardware (nvidia-smi) on every use.+ monkeypatch.setattr(config, "EMBED_BACKEND", "sentence-transformers")dim = 32def _vec(text: str):diff --git a/studio/backend/tests/multi_account/__init__.py b/studio/backend/tests/multi_account/__init__.pynew file mode 100644index 00000000000..32014236c6a--- /dev/null+++ b/studio/backend/tests/multi_account/__init__.py@@ -0,0 +1,2 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0diff --git a/studio/backend/tests/multi_account/conftest.py b/studio/backend/tests/multi_account/conftest.pynew file mode 100644index 00000000000..8abbee6fe04--- /dev/null+++ b/studio/backend/tests/multi_account/conftest.py@@ -0,0 +1,43 @@+# 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 secrets++import pytest+from fastapi.testclient import TestClient++from auth import policy, storage+from utils.account_context import OWNER, bind_account, reset_account++from .support import make_app+++def isolated_auth(tmp_path, monkeypatch):+ home = tmp_path / "install"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "Documents"))+ monkeypatch.delenv("UNSLOTH_STUDIO_PROJECTS_HOME", raising = False)+ monkeypatch.setattr(storage, "DB_PATH", home / "auth" / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", home / "auth" / ".bootstrap_password")+ monkeypatch.setattr(storage, "_credential_encryption_key_cache", None)+ policy.invalidate_account_cache()+ token = bind_account(OWNER)+ try:+ yield storage+ finally:+ reset_account(token)+ policy.invalidate_account_cache()+++def accounts(isolated_auth):+ for username in ("unsloth", "alice", "bob"):+ isolated_auth.create_initial_user(username, "account-password", secrets.token_urlsafe(32))+ return {name: isolated_auth.get_account(name) for name in ("unsloth", "alice", "bob")}+++def account_client(isolated_auth):+ with TestClient(make_app()) as client:+ yield clientdiff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.pynew file mode 100644index 00000000000..f97986ec017--- /dev/null+++ b/studio/backend/tests/multi_account/factories.py@@ -0,0 +1,197 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Resource factories for route isolation tests. Add a table entry to cover another route."""++import hashlib+import json+import sqlite3+from contextlib import closing+from pathlib import Path++from auth import storage+from utils.account_context import run_as+from utils.paths import workspace_root++from .factory_base import Factory, call_seeder, format_path, merge, seeder+from .seed import MESSAGE_ID, SENTINEL, THREAD_ID, seed_studio_db++PROJECT_ID = "matrix-project"+RUN_ID = "matrix-run"+SERVER_ID = "matrix-server"+EDITED = "matrix-edited"+MESSAGE = {+ "id": MESSAGE_ID,+ "threadId": THREAD_ID,+ "role": "user",+ "content": [{"type": "text", "text": SENTINEL}],+ "createdAt": 1000,+}++__all__ = ["Factory", "FACTORIES", "SKIPPED", "format_path", "seed_resource", "snapshot_resource"]+++def studio_db_path(account) -> Path:+ return run_as(account, workspace_root) / "studio.db"+++def studio_connection(account):+ return closing(sqlite3.connect(studio_db_path(account)))+++@seeder("chat")+def seed_chat(account) -> dict[str, str]:+ with studio_connection(account) as conn:+ conn.execute(+ "INSERT INTO chat_threads (id,title,model_type,created_at,updated_at) VALUES (?,?,?,1000,1000)",+ (THREAD_ID, SENTINEL, "base"),+ )+ conn.execute(+ "INSERT INTO chat_messages (id,thread_id,role,content_json,created_at) VALUES (?,?,?,?,1000)",+ (MESSAGE_ID, THREAD_ID, "user", json.dumps(MESSAGE["content"])),+ )+ conn.commit()+ return {"thread_id": THREAD_ID, "message_id": MESSAGE_ID}+++@seeder("project")+def seed_project(account) -> dict[str, str]:+ root = run_as(account, workspace_root)+ with studio_connection(account) as conn:+ conn.execute(+ "INSERT INTO chat_projects (id,name,root_path,created_at,updated_at) VALUES (?,?,?,1000,1000)",+ (PROJECT_ID, SENTINEL, str(root / "projects" / PROJECT_ID)),+ )+ conn.commit()+ return {"project_id": PROJECT_ID}+++@seeder("training")+def seed_training(account) -> dict[str, str]:+ with studio_connection(account) as conn:+ conn.execute(+ "INSERT INTO training_runs (id,status,model_name,dataset_name,config_json,started_at,display_name) "+ "VALUES (?,'completed','local/model','local/dataset','{}','2026-01-01T00:00:00+00:00',?)",+ (RUN_ID, SENTINEL),+ )+ conn.commit()+ return {"run_id": RUN_ID}+++@seeder("api-key")+def seed_api_key(account) -> dict[str, str]:+ _, row = storage.create_api_key(account.username, name = SENTINEL)+ return {"key_id": str(row["id"])}+++@seeder("mcp")+def seed_mcp(account) -> dict[str, str]:+ from storage import mcp_servers_db+ run_as(+ account,+ mcp_servers_db.create_server,+ SERVER_ID,+ SENTINEL,+ "http://8.8.8.8:9/mcp",+ headers_json = None,+ is_enabled = False,+ use_oauth = False,+ )+ return {"server_id": SERVER_ID}+++CORE_FACTORIES = {+ "routes.chat_history:GET:/threads/{thread_id}": Factory("chat", fragment = SENTINEL),+ "routes.chat_history:PATCH:/threads/{thread_id}": Factory(+ "chat", {"title": EDITED}, fragment = EDITED+ ),+ "routes.chat_history:GET:/threads/{thread_id}/messages": Factory("chat", fragment = SENTINEL),+ "routes.chat_history:GET:/threads/{thread_id}/messages/{message_id}": Factory(+ "chat", fragment = SENTINEL+ ),+ "routes.chat_history:PUT:/threads/{thread_id}/messages/{message_id}": Factory(+ "chat", MESSAGE, fragment = SENTINEL+ ),+ "routes.chat_history:PUT:/threads/{thread_id}/messages": Factory(+ "chat", {"messages": [MESSAGE]}, fragment = SENTINEL+ ),+ "routes.chat_history:GET:/projects/{project_id}": Factory("project", fragment = SENTINEL),+ "routes.chat_history:PATCH:/projects/{project_id}": Factory(+ "project", {"name": EDITED}, fragment = EDITED+ ),+ "routes.training_history:GET:/runs/{run_id}": Factory("training", fragment = SENTINEL),+ "routes.training_history:PATCH:/runs/{run_id}": Factory(+ "training", {"display_name": EDITED}, fragment = EDITED+ ),+ "routes.auth:DELETE:/api-keys/{key_id}": Factory("api-key"),+ "routes.mcp_servers:PUT:/{server_id}": Factory(+ "mcp", {"display_name": EDITED}, fragment = EDITED+ ),+ "routes.mcp_servers:DELETE:/{server_id}": Factory("mcp", success = 204),+}+++from . import ( # noqa: E402 domain tables import Factory and register their seeders first+ factories_chat,+ factories_media,+ factories_providers,+ factories_rag,+ factories_runs,+ factories_training,+)++DOMAINS = (+ factories_chat,+ factories_media,+ factories_providers,+ factories_rag,+ factories_runs,+ factories_training,+)++FACTORIES = merge(CORE_FACTORIES, *(domain.FACTORIES for domain in DOMAINS))++SKIPPED = merge(*(domain.SKIPPED for domain in DOMAINS))+++def initialize_workspaces(accounts: dict) -> None:+ for account in accounts.values():+ path = run_as(account, workspace_root) / "studio.db"+ seed_studio_db(path, populated = False)+ with closing(sqlite3.connect(path)) as conn:+ conn.executescript("""+ CREATE TABLE mcp_servers (+ id TEXT PRIMARY KEY, display_name TEXT NOT NULL, url TEXT NOT NULL,+ headers_json TEXT, is_enabled INTEGER NOT NULL DEFAULT 1,+ use_oauth INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL+ );+ """)+++def seed_resource(+ factory: Factory,+ account,+ actor: str = "right",+) -> dict[str, str]:+ params = dict(call_seeder(factory.name, account, actor))+ params.update(factory.extra_params)+ return params+++_VOLATILE = (".db-wal", ".db-shm", ".db-journal")+++def snapshot_resource(account) -> tuple:+ """Logical snapshot avoids WAL/checkpoint differences on a read-only rejected request."""+ root: Path = run_as(account, workspace_root)+ entries = []+ for path in sorted(root.rglob("*")) if root.exists() else []:+ if not path.is_file() or path.name.endswith(_VOLATILE):+ continue+ relative = str(path.relative_to(root))+ if path.suffix == ".db":+ with closing(sqlite3.connect(path)) as conn:+ entries.append((relative, tuple(conn.iterdump())))+ else:+ entries.append((relative, hashlib.sha256(path.read_bytes()).hexdigest()))+ return tuple(entries)diff --git a/studio/backend/tests/multi_account/factories_chat.py b/studio/backend/tests/multi_account/factories_chat.pynew file mode 100644index 00000000000..d8f0f42c529--- /dev/null+++ b/studio/backend/tests/multi_account/factories_chat.py@@ -0,0 +1,216 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from .factory_base import Factory, seeder++CHAT_SENTINEL = "chat-domain resource: café / 日本語"+ATTACHMENT_TEXT = "chat-domain attachment body: café / 日本語"++RUN_THREAD_ID = "chat-run-thread"+RUN_USER_MESSAGE_ID = "chat-run-user-message"+RUN_ASSISTANT_MESSAGE_ID = "chat-run-assistant-message"+RUN_ID = "chat-run-queued"+DONE_RUN_ID = "chat-run-completed"++ATTACHMENT_THREAD_ID = "chat-attachment-thread"+ATTACHMENT_MESSAGE_ID = "chat-attachment-message"+ATTACHMENT_ID = "chat-attachment-id"++PROJECT_ID = "chat-project"++FORK_THREAD_ID = "chat-fork-source-thread"+FORK_MESSAGE_ID = "chat-fork-source-message"+FORK_NEW_THREAD_ID = "chat-fork-new-thread"+FORKED_CHILD_THREAD_ID = "chat-fork-existing-child"++RUN_REQUEST_PAYLOAD = {+ "model": "local/model",+ "messages": [{"role": "user", "content": CHAT_SENTINEL}],+ "stream": True,+ "thread_id": RUN_THREAD_ID,+ "generation_run_id": RUN_ID,+}+++def _thread(thread_id: str, **extra) -> dict:+ return {+ "id": thread_id,+ "title": CHAT_SENTINEL,+ "modelType": "base",+ "modelId": "local/model",+ "createdAt": 1000,+ "updatedAt": 1000,+ **extra,+ }+++def _user_message(message_id: str, thread_id: str, **extra) -> dict:+ return {+ "id": message_id,+ "threadId": thread_id,+ "role": "user",+ "content": [{"type": "text", "text": CHAT_SENTINEL}],+ "createdAt": 1000,+ **extra,+ }+++def _seed_run(account, run_id: str):+ from storage import chat_generation_runs_db, studio_db+ from utils.account_context import run_as++ run_as(account, studio_db.upsert_chat_thread, _thread(RUN_THREAD_ID))+ message = _user_message(RUN_USER_MESSAGE_ID, RUN_THREAD_ID)+ run_as(account, studio_db.upsert_chat_message, message)+ run, _ = run_as(+ account,+ chat_generation_runs_db.create_run,+ run_id = run_id,+ owner_subject = account.username,+ thread_id = RUN_THREAD_ID,+ user_message_id = RUN_USER_MESSAGE_ID,+ assistant_message_id = RUN_ASSISTANT_MESSAGE_ID,+ request_payload = {**RUN_REQUEST_PAYLOAD, "generation_run_id": run_id},+ )+ return run+++@seeder("chat-generation-run")+def seed_chat_generation_run(account) -> dict[str, str]:+ _seed_run(account, RUN_ID)+ return {"run_id": RUN_ID}+++@seeder("chat-generation-run-events")+def seed_chat_generation_run_events(account) -> dict[str, str]:+ from storage import chat_generation_runs_db+ from utils.account_context import run_as++ _seed_run(account, DONE_RUN_ID)+ worker_token = run_as(account, chat_generation_runs_db.get_worker_token, DONE_RUN_ID)+ run_as(+ account,+ chat_generation_runs_db.finish_run,+ DONE_RUN_ID,+ worker_token = worker_token,+ status = "completed",+ finish_reason = "stop",+ pending_events = [("chunk", {"delta": CHAT_SENTINEL})],+ )+ return {"run_id": DONE_RUN_ID}+++@seeder("chat-attachment")+def seed_chat_attachment(account) -> dict[str, str]:+ from storage import studio_db+ from utils.account_context import run_as++ run_as(account, studio_db.upsert_chat_thread, _thread(ATTACHMENT_THREAD_ID))+ run_as(+ account,+ studio_db.upsert_chat_message,+ _user_message(+ ATTACHMENT_MESSAGE_ID,+ ATTACHMENT_THREAD_ID,+ attachments = [+ {+ "id": ATTACHMENT_ID,+ "name": "notes.txt",+ "type": "file",+ "contentType": "text/plain",+ "content": [{"type": "text", "text": ATTACHMENT_TEXT}],+ }+ ],+ ),+ )+ return {"message_id": ATTACHMENT_MESSAGE_ID, "attachment_id": ATTACHMENT_ID}+++@seeder("chat-project")+def seed_chat_project_for_delete(account) -> dict[str, str]:+ from storage import studio_db+ from utils.account_context import run_as++ run_as(+ account,+ studio_db.upsert_chat_project,+ {"id": PROJECT_ID, "name": CHAT_SENTINEL, "createdAt": 1000, "updatedAt": 1000},+ )+ return {"project_id": PROJECT_ID}+++@seeder("chat-fork-source")+def seed_chat_fork_source(account) -> dict[str, str]:+ from storage import studio_db+ from utils.account_context import run_as++ run_as(account, studio_db.upsert_chat_thread, _thread(FORK_THREAD_ID))+ run_as(account, studio_db.upsert_chat_message, _user_message(FORK_MESSAGE_ID, FORK_THREAD_ID))+ return {"thread_id": FORK_THREAD_ID, "message_id": FORK_MESSAGE_ID}+++@seeder("chat-fork-tree")+def seed_chat_fork_tree(account) -> dict[str, str]:+ from storage import studio_db+ from utils.account_context import run_as++ seed_chat_fork_source(account)+ run_as(+ account,+ studio_db.fork_chat_thread,+ source_thread_id = FORK_THREAD_ID,+ branch_message_id = FORK_MESSAGE_ID,+ new_thread_id = FORKED_CHILD_THREAD_ID,+ new_title = f"fork of {CHAT_SENTINEL}",+ created_at = 1001,+ id_factory = lambda: FORKED_CHILD_THREAD_ID + "-message",+ )+ return {"thread_id": FORK_THREAD_ID, "message_id": FORK_MESSAGE_ID}+++# Both count routes answer 200 for any thread id, so the foreign-account expectation is 200.+_FORK_COUNT_REASON = (+ "Fork counts aggregate per account: another account counts its own empty database, not alice's."+)++FACTORIES = {+ "routes.chat_generation_runs:GET:/{run_id}": Factory("chat-generation-run", fragment = RUN_ID),+ "routes.chat_generation_runs:POST:/{run_id}/cancel": Factory(+ "chat-generation-run", fragment = '"status":"cancelled"'+ ),+ "routes.chat_generation_runs:POST:/{run_id}/events": Factory(+ "chat-generation-run-events", fragment = "event: run.completed"+ ),+ "routes.chat_history:GET:/attachments/{message_id}/{attachment_id}/file": Factory(+ "chat-attachment", fragment = ATTACHMENT_TEXT+ ),+ "routes.chat_history:DELETE:/attachments/{message_id}/{attachment_id}": Factory(+ "chat-attachment", fragment = '"ok":true'+ ),+ "routes.chat_history:DELETE:/projects/{project_id}": Factory(+ "chat-project", fragment = CHAT_SENTINEL+ ),+ "routes.chat_history:POST:/threads/{thread_id}/fork": Factory(+ "chat-fork-source",+ {"messageId": FORK_MESSAGE_ID, "newThreadId": FORK_NEW_THREAD_ID, "createdAt": 2000},+ fragment = CHAT_SENTINEL,+ ),+ "routes.chat_history:GET:/threads/{thread_id}/forks": Factory(+ "chat-fork-tree",+ fragment = f'"{FORK_MESSAGE_ID}":1',+ absent = f'"{FORK_MESSAGE_ID}"',+ owner = (200,),+ wrong = (200,),+ reason = _FORK_COUNT_REASON,+ ),+ "routes.chat_history:GET:/threads/{thread_id}/messages/{message_id}/forks": Factory(+ "chat-fork-tree",+ fragment = '"count":1',+ absent = '"count":1',+ owner = (200,),+ wrong = (200,),+ reason = _FORK_COUNT_REASON,+ ),+}++SKIPPED: dict = {}diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.pynew file mode 100644index 00000000000..28416da54e7--- /dev/null+++ b/studio/backend/tests/multi_account/factories_media.py@@ -0,0 +1,267 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from .factory_base import Factory, seeder++# ASCII on purpose: it has to survive JSON escaping, a PNG text chunk and a JPEG comment.+SENTINEL = "media-sentinel-prompt"++VIDEO_ID = "media-video-clip"+SANDBOX_SESSION = "media-sandbox-session"+SANDBOX_FILE = "notes.txt"+SEARCH_IMAGE_ID = "a1b2c3d4e5f6"+MODEL_ID = "media-local-model-Q4_K_M"++IMAGE_LINK_QUERY: dict[str, str] = {}+VIDEO_LINK_QUERY: dict[str, str] = {}+++def _image_meta() -> dict:+ return {+ "prompt": SENTINEL,+ "negative_prompt": None,+ "width": 8,+ "height": 8,+ "steps": 1,+ "guidance": 1.0,+ "seed": 7,+ "model": "media/none",+ # GalleryImage dates an image with an epoch float, where audio and video use ISO strings.+ "created_at": 1767225600.0,+ }+++@seeder("media-image")+def seed_image(account) -> dict[str, str]:+ from PIL import Image++ from core.inference import image_gallery+ from routes.inference import _sign_image_id+ from utils.account_context import run_as++ image = Image.new("RGB", (8, 8), (10, 20, 30))+ record = run_as(account, image_gallery.save, image, _image_meta())+ IMAGE_LINK_QUERY["token"] = run_as(account, _sign_image_id, record["id"])+ return {"image_id": record["id"]}+++def _wav_bytes() -> bytes:+ import io+ import wave++ buf = io.BytesIO()+ with wave.open(buf, "wb") as handle:+ handle.setnchannels(1)+ handle.setsampwidth(2)+ handle.setframerate(8000)+ handle.writeframes(b"\x00\x00" * 64)+ return buf.getvalue()+++@seeder("media-audio")+def seed_audio(account) -> dict[str, str]:+ from core.inference import audio_gallery+ from utils.account_context import run_as++ meta = {+ "prompt": SENTINEL,+ "model": "media/none",+ "audio_type": "speech",+ "sample_rate": 8000,+ "duration_s": 0.008,+ "created_at": "2026-01-01T00:00:00+00:00",+ }+ record = run_as(account, audio_gallery.save, _wav_bytes(), meta)+ return {"audio_id": record["id"]}+++def _mp4_bytes() -> bytes:+ import io++ import av++ buf = io.BytesIO()+ with av.open(buf, "w", format = "mp4") as container:+ stream = container.add_stream("libx264", rate = 8)+ stream.width, stream.height, stream.pix_fmt = 64, 64, "yuv420p"+ stream.options = {"crf": "40", "preset": "ultrafast"}+ for index in range(4):+ frame = av.VideoFrame(64, 64, "yuv420p")+ for plane in frame.planes:+ plane.update(bytes([16 + index * 40]) * plane.buffer_size)+ for packet in stream.encode(frame):+ container.mux(packet)+ for packet in stream.encode():+ container.mux(packet)+ return buf.getvalue()+++@seeder("media-video")+def seed_video(account) -> dict[str, str]:+ from core.inference import video_gallery+ from routes.video import _sign_video_id+ from utils.account_context import run_as++ meta = {+ "prompt": SENTINEL,+ "negative_prompt": None,+ "width": 64,+ "height": 64,+ "num_frames": 4,+ "fps": 8,+ "duration_s": 0.5,+ "steps": 1,+ "guidance": 1.0,+ "seed": 7,+ "model": "media/none",+ "created_at": "2026-01-01T00:00:00+00:00",+ }+ run_as(account, video_gallery.save, _mp4_bytes(), meta, VIDEO_ID)+ VIDEO_LINK_QUERY["token"] = run_as(account, _sign_video_id, VIDEO_ID)+ return {"video_id": VIDEO_ID}+++@seeder("media-search-image")+def seed_search_image(account) -> dict[str, str]:+ import io++ from PIL import Image++ from core.inference import search_images+ from utils.account_context import run_as++ buf = io.BytesIO()+ Image.new("RGB", (8, 8), (200, 100, 50)).save(+ buf, format = "JPEG", comment = SENTINEL.encode("ascii")+ )+ directory = run_as(account, search_images._cache_dir)+ (directory / f"{SEARCH_IMAGE_ID}.jpg").write_bytes(buf.getvalue())+ return {"image_id": SEARCH_IMAGE_ID}+++@seeder("media-sandbox")+def seed_sandbox(account) -> dict[str, str]:+ import os++ from core.inference.tools import get_sandbox_workdir+ from utils.account_context import run_as++ workdir = run_as(account, get_sandbox_workdir, SANDBOX_SESSION)+ with open(os.path.join(workdir, SANDBOX_FILE), "w", encoding = "utf-8") as handle:+ handle.write(SENTINEL)+ return {"session_id": SANDBOX_SESSION, "filename": SANDBOX_FILE}+++@seeder("media-monitor")+def seed_monitor(account) -> dict[str, str]:+ from core.inference.api_monitor import api_monitor+ from utils.account_context import run_as++ entry_id = run_as(+ account,+ api_monitor.start,+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "media/none",+ prompt = SENTINEL,+ subject = account.username,+ )+ return {"entry_id": entry_id}+++@seeder("media-model")+def seed_model(account) -> dict[str, str]:+ import struct++ from core.inference import local_model_resolver+ from routes import inference+ from storage import studio_db+ from utils.account_context import run_as+ from utils.paths import workspace_root++ folder = run_as(account, workspace_root) / "local-models"+ folder.mkdir(parents = True, exist_ok = True)+ header = b"GGUF" + struct.pack("<I", 3) + struct.pack("<QQ", 0, 0)+ (folder / f"{MODEL_ID}.gguf").write_bytes(header + b"\x00" * 256)+ run_as(account, studio_db.add_scan_folder_with_status, str(folder))+ # Drop the catalog's own 30s memo, so the request rescans instead of reusing a stale root.+ inference._CATALOG_CACHE.update(at = 0.0, models = [])+ inference._managed_catalogs.clear()+ inference._SERVABLE_SCAN_CACHE["entry"] = None+ local_model_resolver.invalidate_index()+ return {"model_id": MODEL_ID}+++_LINK_IS_THE_CREDENTIAL = (+ "the signed link is the credential rather than the bearer, so every holder of it is served "+ "while the minting account is active"+)++FACTORIES = {+ "routes.inference:GET:/images/gallery/{image_id}/file": Factory(+ "media-image", fragment = SENTINEL+ ),+ "routes.inference:GET:/images/gallery/{image_id}/file-signed": Factory(+ "media-image",+ fragment = SENTINEL,+ query = IMAGE_LINK_QUERY,+ owner = (200,),+ wrong = (200,),+ unauthenticated = (200,),+ reason = _LINK_IS_THE_CREDENTIAL,+ ),+ "routes.inference:PATCH:/images/gallery/{image_id}": Factory(+ "media-image", {"archived": True}, fragment = SENTINEL+ ),+ "routes.inference:DELETE:/images/gallery/{image_id}": Factory("media-image"),+ "routes.inference:GET:/audio/gallery/{audio_id}/file": Factory("media-audio"),+ "routes.inference:PATCH:/audio/gallery/{audio_id}": Factory(+ "media-audio", {"archived": True}, fragment = SENTINEL+ ),+ "routes.inference:DELETE:/audio/gallery/{audio_id}": Factory("media-audio"),+ "routes.video:GET:/video/gallery/{video_id}/file": Factory("media-video"),+ "routes.video:GET:/video/gallery/{video_id}/file-signed": Factory(+ "media-video",+ query = VIDEO_LINK_QUERY,+ owner = (200,),+ wrong = (200,),+ unauthenticated = (200,),+ reason = _LINK_IS_THE_CREDENTIAL,+ ),+ "routes.video:GET:/video/gallery/{video_id}/signed-url": Factory(+ "media-video", fragment = "file-signed"+ ),+ "routes.video:GET:/video/gallery/{video_id}/export": Factory("media-video"),+ "routes.video:PATCH:/video/gallery/{video_id}": Factory(+ "media-video", {"archived": True}, fragment = SENTINEL+ ),+ "routes.video:DELETE:/video/gallery/{video_id}": Factory("media-video"),+ "routes.video:GET:/videos/{video_id}": Factory("media-video", fragment = SENTINEL),+ "routes.video:GET:/videos/{video_id}/content": Factory("media-video"),+ "routes.video:DELETE:/videos/{video_id}": Factory("media-video", fragment = VIDEO_ID),+ "routes.inference:GET:/search-images/{image_id}": Factory(+ "media-search-image", fragment = SENTINEL+ ),+ "routes.inference:GET:/monitor/{entry_id}": Factory("media-monitor", fragment = SENTINEL),+ "routes.inference:GET:/models/{model_id:path}": Factory("media-model", fragment = MODEL_ID),+ "routes.inference:GET:/sandbox/{session_id}": Factory(+ "media-sandbox",+ fragment = SANDBOX_FILE,+ absent = SANDBOX_FILE,+ owner = (200,),+ wrong = (200,),+ reason = "a session id resolves inside the caller's own sandbox root, so another account "+ "is listed its own empty directory rather than refused",+ ),+ "routes.inference:GET:/sandbox/{session_id}/{filename:path}": Factory(+ "media-sandbox", fragment = SENTINEL+ ),+ "routes.inference:HEAD:/sandbox/{session_id}/{filename:path}": Factory("media-sandbox"),+}++SKIPPED = {+ "routes.inference:POST:/sandbox/{session_id}/reveal": (+ "opens the backend host's file manager, so a success spawns xdg-open on a machine with "+ "no desktop session and the only in-process outcome is the 500 that failure maps to"+ ),+}diff --git a/studio/backend/tests/multi_account/factories_providers.py b/studio/backend/tests/multi_account/factories_providers.pynew file mode 100644index 00000000000..6422b98e3b4--- /dev/null+++ b/studio/backend/tests/multi_account/factories_providers.py@@ -0,0 +1,376 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from .factory_base import Factory, seeder++PROVIDER_ID = "prov-openai-config"+MIGRATE_PROVIDER_ID = "prov-openai-migrate"+CODEX_PROVIDER_ID = "prov-codex-config"+CODEX_FLOW_ID = "prov-codex-flow"+MCP_SERVER_ID = "prov-mcp-server"+PROMPT_ENTRY_ID = "prov-prompt-entry"+PROMPT_LIST_ID = "prov-prompt-list"+RETIRABLE_USERNAME = "prov-retirable"++SENTINEL = "prov-sentinel café / 日本語"+EDITED = "prov-edited"+SAVED_API_KEY = "prov-saved-api-key"+MIGRATED_API_KEY = "prov-migrated-api-key"++# Managed accounts may only hold a public HTTP MCP address, so the probe goes to a dead public port.+MCP_URL = "http://8.8.8.8:9/mcp"++# Filled by the migrate seeder: the key must be encrypted with this process's RSA public key.+MIGRATION_BODY: dict = {"encrypted_api_key": ""}+++def _encrypt_api_key(plaintext: str) -> str:+ import base64++ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import padding++ from core.inference import key_exchange++ if key_exchange.get_public_key_fingerprint() is None:+ key_exchange.init_key_pair()+ public_key = serialization.load_pem_public_key(key_exchange.get_public_key_pem().encode())+ ciphertext = public_key.encrypt(+ plaintext.encode("utf-8"),+ padding.OAEP(+ mgf = padding.MGF1(algorithm = hashes.SHA256()),+ algorithm = hashes.SHA256(),+ label = None,+ ),+ )+ return base64.b64encode(ciphertext).decode("ascii")+++def _create_provider(provider_id: str, provider_type: str, display_name: str) -> None:+ from core.inference.providers import get_base_url+ from storage import providers_db++ providers_db.delete_provider(provider_id)+ providers_db.create_provider(+ id = provider_id,+ provider_type = provider_type,+ display_name = display_name,+ base_url = get_base_url(provider_type),+ models = [],+ available_models = [],+ )+++def _drop_in_process_flows(provider_id: str) -> None:+ from core.inference import openai_codex_auth as codex_auth+ for flow_id, flow in list(codex_auth._flows.items()):+ if flow.provider_id != provider_id:+ continue+ codex_auth._flows.pop(flow_id, None)+ for task in (flow.task, flow.cleanup_task):+ if task is not None:+ try:+ task.cancel()+ except Exception:+ pass+ if flow.server is not None:+ try:+ flow.server.close()+ except Exception:+ pass+ flow.server = None+++@seeder("prov-provider")+def seed_provider(account) -> dict[str, str]:+ from storage import credential_secrets+ from utils.account_context import run_as++ run_as(account, _create_provider, PROVIDER_ID, "openai", SENTINEL)+ run_as(account, credential_secrets.save_provider_api_key, PROVIDER_ID, SAVED_API_KEY)+ return {"provider_id": PROVIDER_ID}+++@seeder("prov-provider-without-key")+def seed_provider_without_key(account) -> dict[str, str]:+ from utils.account_context import run_as++ run_as(account, _create_provider, MIGRATE_PROVIDER_ID, "openai", SENTINEL)+ MIGRATION_BODY["encrypted_api_key"] = _encrypt_api_key(MIGRATED_API_KEY)+ return {"provider_id": MIGRATE_PROVIDER_ID}+++@seeder("prov-codex-provider")+def seed_codex_provider(account) -> dict[str, str]:+ from utils.account_context import run_as++ run_as(account, _create_provider, CODEX_PROVIDER_ID, "openai_codex", SENTINEL)+ _drop_in_process_flows(CODEX_PROVIDER_ID)+ return {"provider_id": CODEX_PROVIDER_ID}+++@seeder("prov-codex-connected")+def seed_codex_connected(account) -> dict[str, str]:+ from core.inference import openai_codex_auth as codex_auth+ from utils.account_context import run_as++ run_as(account, _create_provider, CODEX_PROVIDER_ID, "openai_codex", SENTINEL)+ _drop_in_process_flows(CODEX_PROVIDER_ID)+ run_as(+ account,+ codex_auth.save_oauth_bundle,+ CODEX_PROVIDER_ID,+ {+ "access_token": "prov-access-token",+ "refresh_token": "prov-refresh-token",+ "expires_at": 4102444800,+ "account_id": "prov-chatgpt-account",+ },+ )+ return {"provider_id": CODEX_PROVIDER_ID}+++@seeder("prov-codex-flow")+def seed_codex_flow(account) -> dict[str, str]:+ import time++ from core.inference import openai_codex_auth as codex_auth+ from utils.account_context import run_as++ run_as(account, _create_provider, CODEX_PROVIDER_ID, "openai_codex", SENTINEL)+ _drop_in_process_flows(CODEX_PROVIDER_ID)+ now = time.time()+ flow = codex_auth.OAuthFlow(+ id = CODEX_FLOW_ID,+ provider_id = CODEX_PROVIDER_ID,+ method = "browser",+ created_at = now,+ expires_at = now + 900,+ state = "prov-oauth-state",+ verifier = "prov-oauth-verifier",+ redirect_uri = "http://localhost:1455/auth/callback",+ authorization_url = "https://auth.openai.com/oauth/authorize?state=prov-oauth-state",+ status = "pending",+ marker = "prov-oauth-marker",+ )+ run_as(+ account,+ codex_auth.save_oauth_flow_marker,+ CODEX_PROVIDER_ID,+ "prov-oauth-marker",+ flow,+ )+ return {"provider_id": CODEX_PROVIDER_ID, "flow_id": CODEX_FLOW_ID}+++@seeder("prov-mcp-refresh")+def seed_mcp_refresh(account) -> dict[str, str]:+ from storage import mcp_servers_db+ from utils.account_context import run_as++ run_as(+ account,+ mcp_servers_db.create_server,+ MCP_SERVER_ID,+ SENTINEL,+ MCP_URL,+ headers_json = None,+ is_enabled = False,+ use_oauth = False,+ )+ return {"server_id": MCP_SERVER_ID}+++@seeder("prov-prompt-entry")+def seed_prompt_entry(account) -> dict[str, str]:+ from storage import studio_db+ from utils.account_context import run_as++ run_as(+ account,+ studio_db.upsert_prompt_entry,+ {+ "id": PROMPT_ENTRY_ID,+ "name": SENTINEL,+ "text": SENTINEL,+ "createdAt": 1000,+ "updatedAt": 1000,+ },+ )+ return {"entry_id": PROMPT_ENTRY_ID}+++@seeder("prov-prompt-list")+def seed_prompt_list(account) -> dict[str, str]:+ from storage import studio_db+ from utils.account_context import run_as++ run_as(+ account,+ studio_db.upsert_prompt_list,+ {+ "id": PROMPT_LIST_ID,+ "name": SENTINEL,+ "items": [PROMPT_ENTRY_ID],+ "createdAt": 1000,+ "updatedAt": 1000,+ },+ )+ return {"list_id": PROMPT_LIST_ID}+++@seeder("prov-account")+def seed_account(account) -> dict[str, str]:+ return {"account_id": account.account_id}+++@seeder("prov-retirable-account")+def seed_retirable_account(account) -> dict[str, str]:+ """A managed account of its own, whose deletion retires a private root the matrix's unchanged-workspace assertion would misread as erased."""+ from auth import storage+ from storage import studio_db+ from utils.account_context import AccountContext, run_as++ for row in storage.list_accounts():+ if row["username"] == RETIRABLE_USERNAME:+ storage.delete_account(row["account_id"], lambda _context: None)+ issued = storage.issue_account_setup_code(username = RETIRABLE_USERNAME)+ account_id = issued["account"]["account_id"]+ # First database use creates the private root, so the retire has a directory to move.+ run_as(AccountContext(account_id, RETIRABLE_USERNAME, "user"), studio_db.list_prompt_entries)+ return {"account_id": account_id}+++PROMPT_ENTRY_BODY = {+ "id": PROMPT_ENTRY_ID,+ "name": EDITED,+ "text": EDITED,+ "createdAt": 1000,+ "updatedAt": 2000,+}+PROMPT_LIST_BODY = {+ "id": PROMPT_LIST_ID,+ "name": EDITED,+ "items": [PROMPT_ENTRY_ID],+ "createdAt": 1000,+ "updatedAt": 2000,+}++_PROMPT_UPSERT_REASON = (+ "PUT is an upsert keyed only by id inside the caller's own database, so a foreign caller "+ "writes its own row and never sees alice's; the snapshot proves hers is untouched"+)+_PROMPT_DELETE_REASON = (+ "DELETE is an idempotent no-op scoped to the caller's own database, so a foreign caller "+ "gets 204 after deleting nothing; the snapshot proves alice's row survived"+)+_PROVIDER_DELETE_OWNER_REASON = (+ "the owner is not a managed account, so its delete falls through to the idempotent path "+ "and removes nothing from its own database"+)+_ACCOUNTS_DELETE_REASON = (+ "owner administration route behind require_owner, inverted like its siblings; the target is "+ "a disposable account because a real owner delete renames the target's whole private root"+)+_ACCOUNTS_SELF_REASON = (+ "owner administration route behind require_owner, so the contract inverts: the owner "+ "succeeds against alice, both managed accounts are refused, and it cannot administer itself"+)++FACTORIES = {+ "routes.providers:PUT:/{provider_id}": Factory(+ "prov-provider", {"display_name": EDITED}, fragment = EDITED+ ),+ "routes.providers:DELETE:/{provider_id}": Factory(+ "prov-provider",+ success = 204,+ owner = (204,),+ reason = _PROVIDER_DELETE_OWNER_REASON,+ ),+ "routes.providers:PUT:/{provider_id}/api-key/migrate": Factory(+ "prov-provider-without-key",+ MIGRATION_BODY,+ fragment = '"has_api_key":true',+ ),+ "routes.openai_codex_auth:GET:/{provider_id}/codex/models": Factory(+ "prov-codex-provider", fragment = '"source":"curated"'+ ),+ "routes.openai_codex_auth:POST:/{provider_id}/oauth/start": Factory(+ "prov-codex-provider",+ {"method": "browser"},+ fragment = '"status":"pending"',+ ),+ "routes.openai_codex_auth:DELETE:/{provider_id}/oauth": Factory(+ "prov-codex-connected", success = 204+ ),+ "routes.openai_codex_auth:GET:/{provider_id}/oauth/flows/{flow_id}": Factory(+ "prov-codex-flow", fragment = CODEX_FLOW_ID+ ),+ "routes.openai_codex_auth:DELETE:/{provider_id}/oauth/flows/{flow_id}": Factory(+ "prov-codex-flow", success = 204+ ),+ "routes.mcp_servers:POST:/{server_id}/refresh": Factory(+ "prov-mcp-refresh", fragment = '"ok":false'+ ),+ "routes.prompts:PUT:/entries/{entry_id}": Factory(+ "prov-prompt-entry",+ PROMPT_ENTRY_BODY,+ fragment = EDITED,+ owner = (200,),+ wrong = (200,),+ reason = _PROMPT_UPSERT_REASON,+ ),+ "routes.prompts:DELETE:/entries/{entry_id}": Factory(+ "prov-prompt-entry",+ success = 204,+ owner = (204,),+ wrong = (204,),+ reason = _PROMPT_DELETE_REASON,+ ),+ "routes.prompts:PUT:/lists/{list_id}": Factory(+ "prov-prompt-list",+ PROMPT_LIST_BODY,+ fragment = EDITED,+ owner = (200,),+ wrong = (200,),+ reason = _PROMPT_UPSERT_REASON,+ ),+ "routes.prompts:DELETE:/lists/{list_id}": Factory(+ "prov-prompt-list",+ success = 204,+ owner = (204,),+ wrong = (204,),+ reason = _PROMPT_DELETE_REASON,+ ),+ "routes.accounts:PATCH:/{account_id}": Factory(+ "prov-account",+ {"is_active": False},+ owner = (200,),+ right = (403,),+ wrong = (403,),+ self_expected = (400,),+ reason = _ACCOUNTS_SELF_REASON,+ ),+ "routes.accounts:DELETE:/{account_id}": Factory(+ "prov-retirable-account",+ success = 204,+ owner = (204,),+ right = (403,),+ wrong = (403,),+ reason = _ACCOUNTS_DELETE_REASON,+ ),+ "routes.accounts:POST:/{account_id}/setup-code": Factory(+ "prov-account",+ owner = (200,),+ right = (403,),+ wrong = (403,),+ self_expected = (400,),+ reason = _ACCOUNTS_SELF_REASON,+ ),+}++SKIPPED = {+ "routes.openai_codex_auth:POST:/{provider_id}/oauth/flows/{flow_id}/complete": (+ "completing a flow exchanges the pasted authorization code with auth.openai.com"+ ),+}diff --git a/studio/backend/tests/multi_account/factories_rag.py b/studio/backend/tests/multi_account/factories_rag.pynew file mode 100644index 00000000000..ba990572448--- /dev/null+++ b/studio/backend/tests/multi_account/factories_rag.py@@ -0,0 +1,298 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from .factory_base import Factory, seeder++KB_ID = "rag-matrix-kb"+DOCUMENT_ID = "rag-matrix-document"+JOB_ID = "rag-matrix-job"+FOLDER_JOB_ID = "rag-matrix-folder-job"+PROJECT_ID = "rag-matrix-project"+THREAD_ID = "rag-matrix-thread"+FILENAME = "rag-matrix-sentinel.txt"+KB_NAME = "rag-matrix-kb-name"+EDITED = "rag-matrix-edited"+CONTENT = b"rag matrix sentinel document body\n"+# Unsigned, so verify_native_path_lease rejects it before any folder is created.+BAD_LEASE = {"nativePathLease": "rag-matrix-invalid-lease"}+++def _connection(account):+ from storage import rag_db+ from utils.account_context import run_as+ return run_as(account, rag_db.get_connection)+++def _uploads_dir(account):+ from utils.account_context import run_as+ from utils.paths import ensure_dir, rag_uploads_root+ return run_as(account, lambda: ensure_dir(rag_uploads_root()))+++def _store_file(account) -> str:+ path = _uploads_dir(account) / FILENAME+ path.write_bytes(CONTENT)+ return str(path)+++def _create_kb(conn) -> None:+ from core.rag import store+ store.create_kb(conn, name = KB_NAME, description = None, kb_id = KB_ID)+++def _create_document(account, conn, *, scope: str, **columns) -> None:+ import hashlib++ from core.rag import store+ store.create_document(+ conn,+ scope = scope,+ filename = FILENAME,+ sha256 = hashlib.sha256(CONTENT).hexdigest(),+ status = "completed",+ stored_path = _store_file(account),+ document_id = DOCUMENT_ID,+ **columns,+ )+++@seeder("rag-kb")+def seed_rag_kb(account) -> dict[str, str]:+ conn = _connection(account)+ try:+ _create_kb(conn)+ finally:+ conn.close()+ return {"kb_id": KB_ID}+++@seeder("rag-document")+def seed_rag_document(account) -> dict[str, str]:+ from core.rag import store++ conn = _connection(account)+ try:+ _create_kb(conn)+ _create_document(account, conn, scope = store.kb_scope(KB_ID), kb_id = KB_ID)+ finally:+ conn.close()+ return {"document_id": DOCUMENT_ID, "kb_id": KB_ID}+++@seeder("rag-job")+def seed_rag_job(account) -> dict[str, str]:+ from core.rag import store++ conn = _connection(account)+ try:+ _create_kb(conn)+ _create_document(account, conn, scope = store.kb_scope(KB_ID), kb_id = KB_ID)+ conn.execute(+ "INSERT INTO ingestion_jobs(id, document_id, scope, status, stage, progress, "+ "created_at) VALUES(?,?,?,'completed','done',1.0,'2026-01-01T00:00:00+00:00')",+ (JOB_ID, DOCUMENT_ID, store.kb_scope(KB_ID)),+ )+ conn.commit()+ finally:+ conn.close()+ return {"job_id": JOB_ID, "document_id": DOCUMENT_ID}+++@seeder("rag-folder")+def seed_rag_folder(account) -> dict[str, str]:+ from core.rag import folder_sync+ from utils.account_context import run_as+ from utils.paths import workspace_root++ conn = _connection(account)+ try:+ _create_kb(conn)+ finally:+ conn.close()+ linked = run_as(account, workspace_root) / "rag-matrix-linked"+ linked.mkdir(parents = True, exist_ok = True)+ (linked / FILENAME).write_bytes(CONTENT)+ folder = run_as(+ account,+ lambda: folder_sync.create_folder(+ scope_type = "knowledge_base",+ scope_id = KB_ID,+ path = str(linked),+ name = KB_NAME,+ auto_sync = False,+ ),+ )+ conn = _connection(account)+ try:+ conn.execute(+ "INSERT INTO linked_folder_sync_jobs(id, folder_id, kind, status, stage, progress, "+ "created_at, completed_at) VALUES(?,?,'sync','completed','done',1.0,"+ "'2026-01-01T00:00:00+00:00','2026-01-01T00:00:01+00:00')",+ (FOLDER_JOB_ID, folder["id"]),+ )+ conn.commit()+ finally:+ conn.close()+ return {"folder_id": folder["id"], "job_id": FOLDER_JOB_ID}+++@seeder("rag-project")+def seed_rag_project(account) -> dict[str, str]:+ import sqlite3+ from contextlib import closing++ from utils.account_context import run_as+ from utils.paths import studio_db_path++ with closing(sqlite3.connect(run_as(account, studio_db_path))) as conn:+ conn.execute(+ "INSERT INTO chat_projects (id,name,root_path,created_at,updated_at) "+ "VALUES (?,?,NULL,1000,1000)",+ (PROJECT_ID, KB_NAME),+ )+ conn.commit()+ return {"project_id": PROJECT_ID}+++@seeder("rag-project-document")+def seed_rag_project_document(account) -> dict[str, str]:+ from core.rag import store++ seed_rag_project(account)+ conn = _connection(account)+ try:+ _create_document(+ account, conn, scope = store.project_scope(PROJECT_ID), project_id = PROJECT_ID+ )+ finally:+ conn.close()+ return {"project_id": PROJECT_ID, "document_id": DOCUMENT_ID}+++@seeder("rag-thread-document")+def seed_rag_thread_document(account) -> dict[str, str]:+ from core.rag import store++ conn = _connection(account)+ try:+ _create_document(account, conn, scope = store.thread_scope(THREAD_ID), thread_id = THREAD_ID)+ finally:+ conn.close()+ return {"thread_id": THREAD_ID, "document_id": DOCUMENT_ID}+++_LIST_SCOPE = (+ "the scope is not resolved to an owner, so an unknown kb/thread lists that account's own "+ "empty scope with 200 instead of 404"+)+_INGESTION_SSE = (+ "the ingestion event stream is keyed by an in-process per-account queue, so a foreign "+ "account finds none and gets an immediate 200 [DONE] without reading this account's rows"+)+_MULTIPART = (+ "the JSON-only matrix client cannot send the multipart upload, so the owning account stops "+ "at 400 after the ownership check that returns 404 to everyone else"+)+_MULTIPART_UNSCOPED = (+ "thread uploads have no thread-existence check and need a multipart body the JSON matrix "+ "client cannot send, so every actor stops at the same 400 and no case can discriminate"+)+_LEASE = (+ "linking needs a signed desktop path grant, so the owning account stops at 400 after the "+ "ownership check that returns 404 to everyone else"+)++FACTORIES = {+ "routes.rag:PATCH:/knowledge-bases/{kb_id}": Factory("rag-kb", {"name": EDITED}),+ "routes.rag:DELETE:/knowledge-bases/{kb_id}": Factory("rag-kb"),+ "routes.rag:GET:/knowledge-bases/{kb_id}/documents": Factory(+ "rag-document",+ fragment = FILENAME,+ absent = FILENAME,+ owner = (200,),+ wrong = (200,),+ reason = _LIST_SCOPE,+ ),+ "routes.rag:POST:/knowledge-bases/{kb_id}/documents": Factory(+ "rag-kb",+ success = 400,+ fragment = "No file was provided",+ self_expected = (400,),+ reason = _MULTIPART,+ ),+ "routes.rag:POST:/knowledge-bases/{kb_id}/linked-folders": Factory(+ "rag-kb",+ BAD_LEASE,+ success = 400,+ fragment = "Native path grant",+ self_expected = (400,),+ reason = _LEASE,+ ),+ "routes.rag:DELETE:/documents/{document_id}": Factory("rag-document"),+ "routes.rag:GET:/documents/{document_id}/file-url": Factory(+ "rag-document", fragment = "file-signed"+ ),+ "routes.rag:GET:/documents/{document_id}/preview-target": Factory(+ "rag-document", fragment = FILENAME+ ),+ "routes.rag:GET:/jobs/{job_id}": Factory("rag-job", fragment = DOCUMENT_ID),+ "routes.rag:GET:/jobs/{job_id}/events": Factory(+ "rag-job",+ fragment = "[DONE]",+ absent = DOCUMENT_ID,+ owner = (200,),+ wrong = (200,),+ reason = _INGESTION_SSE,+ ),+ "routes.rag:POST:/jobs/{job_id}/events": Factory(+ "rag-job",+ fragment = "[DONE]",+ absent = DOCUMENT_ID,+ owner = (200,),+ wrong = (200,),+ reason = _INGESTION_SSE,+ ),+ "routes.rag:GET:/linked-folder-jobs/{job_id}": Factory("rag-folder", fragment = FOLDER_JOB_ID),+ "routes.rag:GET:/linked-folder-jobs/{job_id}/events": Factory("rag-folder", fragment = "[DONE]"),+ "routes.rag:POST:/linked-folder-jobs/{job_id}/events": Factory("rag-folder", fragment = "[DONE]"),+ "routes.rag:PATCH:/linked-folders/{folder_id}": Factory(+ "rag-folder", {"name": EDITED}, fragment = EDITED+ ),+ "routes.rag:DELETE:/linked-folders/{folder_id}": Factory("rag-folder"),+ "routes.rag:POST:/linked-folders/{folder_id}/sync": Factory("rag-folder"),+ "routes.rag:POST:/linked-folders/{folder_id}/rebuild": Factory("rag-folder"),+ "routes.rag:GET:/projects/{project_id}/documents": Factory(+ "rag-project-document", fragment = FILENAME+ ),+ "routes.rag:POST:/projects/{project_id}/documents": Factory(+ "rag-project",+ success = 400,+ fragment = "No file was provided",+ self_expected = (400,),+ reason = _MULTIPART,+ ),+ "routes.rag:POST:/projects/{project_id}/linked-folders": Factory(+ "rag-project",+ BAD_LEASE,+ success = 400,+ fragment = "Native path grant",+ self_expected = (400,),+ reason = _LEASE,+ ),+ "routes.rag:GET:/threads/{thread_id}/documents": Factory(+ "rag-thread-document",+ fragment = FILENAME,+ absent = FILENAME,+ owner = (200,),+ wrong = (200,),+ reason = _LIST_SCOPE,+ ),+}++SKIPPED = {+ "routes.rag:POST:/threads/{thread_id}/documents": _MULTIPART_UNSCOPED,+ "routes.rag:GET:/documents/{document_id}/file-signed": (+ "signed document downloads resolve in the owner's store for every account, so the route "+ "404s for the account that minted the token; product finding, see report"+ ),+}diff --git a/studio/backend/tests/multi_account/factories_runs.py b/studio/backend/tests/multi_account/factories_runs.pynew file mode 100644index 00000000000..9ff0b5464d5--- /dev/null+++ b/studio/backend/tests/multi_account/factories_runs.py@@ -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++"""Durable Deep Research run routes and the public per-checkpoint preview routes."""++import json++from .factory_base import Factory, seeder++MARKER = "runs-matrix-sentinel"+THREAD_ID = "runs-thread"+USER_MESSAGE_ID = "runs-user-message"+RUN_ID = "runs-research-run"+PLAN = {"title": MARKER, "steps": [{"title": MARKER, "query": MARKER}]}+UPDATE_PLAN_BODY = {"plan": PLAN, "expectedRevision": 0}+# Filled by the seeder from the product's own canonical hash, so approve matches the stored plan.+APPROVE_BODY = {"planRevision": 1, "planHash": ""}++PREVIEW_RUN = "runs-preview-run"+PREVIEW_CHECKPOINT = "checkpoint-1"+UNSUPPORTED_PART = "runs-unsupported-part"+PREVIEW_CHAT_BODY = {+ "model": PREVIEW_RUN,+ "messages": [{"role": "user", "content": [{"type": UNSUPPORTED_PART, "value": MARKER}]}],+}+PREVIEW_RUN_KEY: dict = {}+PREVIEW_CHECKPOINT_KEY: dict = {}+++def _link_holder(seeded, actor: str):+ from auth import storage+ from utils.account_context import OWNER++ if actor == "unauthenticated":+ return None+ if actor == "owner":+ return OWNER+ if actor == "wrong":+ return storage.get_account("bob")+ return seeded+++def _create_research_run(account) -> None:+ from storage import research_runs_db as db+ from storage.studio_db import upsert_chat_message, upsert_chat_thread+ from utils.account_context import run_as++ run_as(+ account,+ upsert_chat_thread,+ {+ "id": THREAD_ID,+ "title": MARKER,+ "modelType": "base",+ "modelId": "local/model",+ "createdAt": 1000,+ "updatedAt": 1000,+ },+ )+ run_as(+ account,+ upsert_chat_message,+ {+ "id": USER_MESSAGE_ID,+ "threadId": THREAD_ID,+ "role": "user",+ "content": [{"type": "text", "text": MARKER}],+ "createdAt": 1000,+ },+ )+ run_as(+ account,+ db.create_run,+ run_id = RUN_ID,+ owner_subject = account.username,+ thread_id = THREAD_ID,+ user_message_id = USER_MESSAGE_ID,+ assistant_message_id = None,+ config = {"model": "local/model", "question": MARKER},+ )+++@seeder("runs-research")+def seed_research_run(account) -> dict[str, str]:+ _create_research_run(account)+ return {"run_id": RUN_ID}+++@seeder("runs-research-planned")+def seed_planned_research_run(account) -> dict[str, str]:+ from storage import research_runs_db as db+ from utils.account_context import run_as++ _create_research_run(account)+ planned = run_as(account, db.set_plan, RUN_ID, PLAN, 0)+ APPROVE_BODY["planRevision"] = planned["planRevision"]+ APPROVE_BODY["planHash"] = planned["planHash"]+ return {"run_id": RUN_ID}+++@seeder("runs-research-stopped")+def seed_stopped_research_run(account) -> dict[str, str]:+ """A terminal run whose events are all committed, so its event stream ends at once."""+ from storage import research_runs_db as db+ from utils.account_context import run_as++ seed_planned_research_run(account)+ run_as(account, db.request_cancel, RUN_ID)+ return {"run_id": RUN_ID}+++@seeder("runs-preview")+def seed_preview_run(account, actor: str = "right") -> dict[str, str]:+ from utils.paths import outputs_root+ from utils.account_context import run_as+ from utils.preview_token import sign_preview_ref++ run = run_as(account, outputs_root) / PREVIEW_RUN+ (run / PREVIEW_CHECKPOINT).mkdir(parents = True, exist_ok = True)+ run.joinpath("adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": MARKER}), encoding = "utf-8"+ )+ run.joinpath(PREVIEW_CHECKPOINT, "adapter_config.json").write_text("{}", encoding = "utf-8")+ holder = _link_holder(account, actor)+ PREVIEW_RUN_KEY.clear()+ PREVIEW_CHECKPOINT_KEY.clear()+ if holder is not None:+ PREVIEW_RUN_KEY["k"] = sign_preview_ref(PREVIEW_RUN, holder)+ PREVIEW_CHECKPOINT_KEY["k"] = sign_preview_ref(+ f"{PREVIEW_RUN}/{PREVIEW_CHECKPOINT}", holder+ )+ return {"run": PREVIEW_RUN, "checkpoint": PREVIEW_CHECKPOINT}+++_LINK_REASON = (+ "public share link: the signed capability is the credential, so each actor presents its own "+ "link and only the minting account's opens the run"+)+_CHAT_REASON = (+ "covered only to the pre-load parameter guard: an unsupported content part is refused before "+ "the preview lock, so no checkpoint is ever loaded"+)+++def _preview(fragment: str, query: dict, **overrides) -> Factory:+ return Factory(+ "runs-preview",+ fragment = fragment,+ query = query,+ unauthenticated = (404,),+ deactivated = (404,),+ **{"reason": _LINK_REASON, **overrides},+ )+++FACTORIES = {+ "routes.research_runs:GET:/{run_id}": Factory("runs-research", fragment = MARKER),+ "routes.research_runs:PUT:/{run_id}/plan": Factory(+ "runs-research", UPDATE_PLAN_BODY, fragment = '"status":"awaiting_approval"'+ ),+ "routes.research_runs:POST:/{run_id}/approve": Factory(+ "runs-research-planned", APPROVE_BODY, fragment = '"status":"queued"'+ ),+ "routes.research_runs:POST:/{run_id}/cancel": Factory(+ "runs-research", fragment = '"status":"cancelling"'+ ),+ "routes.research_runs:POST:/{run_id}/retry": Factory(+ "runs-research-stopped", fragment = '"status":"awaiting_approval"'+ ),+ "routes.research_runs:GET:/{run_id}/events": Factory(+ "runs-research-stopped", fragment = "event: run.cancelled"+ ),+ "routes.research_runs:POST:/{run_id}/events": Factory(+ "runs-research-stopped", fragment = "event: run.cancelled"+ ),+ "routes.preview:GET:/{run}": _preview(PREVIEW_RUN, PREVIEW_RUN_KEY),+ "routes.preview:GET:/{run}/{checkpoint}": _preview(+ f"{PREVIEW_RUN}/{PREVIEW_CHECKPOINT}", PREVIEW_CHECKPOINT_KEY+ ),+ "routes.preview:GET:/{run}/v1/models": _preview(f'"id":"{PREVIEW_RUN}"', PREVIEW_RUN_KEY),+ "routes.preview:GET:/{run}/{checkpoint}/v1/models": _preview(+ f'"id":"{PREVIEW_RUN}/{PREVIEW_CHECKPOINT}"', PREVIEW_CHECKPOINT_KEY+ ),+ "routes.preview:POST:/{run}/v1/chat/completions": _preview(+ UNSUPPORTED_PART,+ PREVIEW_RUN_KEY,+ body = PREVIEW_CHAT_BODY,+ success = 400,+ reason = f"{_LINK_REASON}; {_CHAT_REASON}",+ ),+ "routes.preview:POST:/{run}/{checkpoint}/v1/chat/completions": _preview(+ UNSUPPORTED_PART,+ PREVIEW_CHECKPOINT_KEY,+ body = PREVIEW_CHAT_BODY,+ success = 400,+ reason = f"{_LINK_REASON}; {_CHAT_REASON}",+ ),+}++SKIPPED: dict = {}diff --git a/studio/backend/tests/multi_account/factories_training.py b/studio/backend/tests/multi_account/factories_training.pynew file mode 100644index 00000000000..1e77adaf096--- /dev/null+++ b/studio/backend/tests/multi_account/factories_training.py@@ -0,0 +1,261 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Factories for the training, diffusion dataset, scan folder and data recipe object routes."""++from .factory_base import Factory, seeder++SENTINEL = "Alice's training resource: café / 日本語"+EDITED = "training-matrix-edited"+START_REQUEST_ID = "training-matrix-start-request"+START_JOB_ID = "training-matrix-job"+DIFFUSION_JOB_ID = "a1b2c3d4e5f607182930a4b5c6d7e8f9"+DATASET_NAME = "training-matrix-dataset"+IMAGE_NAME = "training-matrix-image.png"+RECIPE_JOB_ID = "f9e8d7c6b5a40312092a8b7c6d5e4f30"+BLOCK_ID = "0123456789abcdef0123456789abcdef"+FILE_ID = "fedcba9876543210fedcba9876543210"+SCAN_FOLDER_DIRNAME = "training-matrix-scan-folder"++PNG_1X1 = (+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmM"+ "IQAAAABJRU5ErkJggg=="+)++_SCAN_FOLDER_REASON = (+ "Removing a scan folder id is an idempotent delete in the caller's own studio.db, so a "+ "foreign account is told ok without seeing or touching alice's row."+)+_PUBLISH_REASON = (+ "Publishing uploads to the Hub, so the owning account is taken only as far as the 409 that "+ "proves it resolved its own preview job, while a foreign account resolves no job at all and "+ "is refused for a missing artifact path."+)+_BLOCK_REASON = (+ "Removing an upload block is an idempotent delete under the caller's own uploads root, so a "+ "foreign account is told ok with deleted false."+)+_EVENTS_REASON = (+ "The owning account's SSE stream ends only when the client disconnects, which an in-process "+ "TestClient request cannot do, so the case would hang rather than return."+)+++def _claim_in_process_job(service) -> None:+ from utils.account_context import current_account+ with service._account_job_lock:+ service._result_account = service.job_account = current_account()+++@seeder("training-start-request")+def seed_training_start_request(account) -> dict[str, str]:+ from core.training import get_training_backend+ from core.training.training import TrainingStartRequestRecord+ from utils.account_context import run_as++ backend = get_training_backend()++ def install() -> None:+ _claim_in_process_job(backend)+ record = TrainingStartRequestRecord(+ start_request_id = START_REQUEST_ID,+ job_id = START_JOB_ID,+ state = "rejected",+ message = SENTINEL,+ error = "Training start failed validation",+ )+ with backend._lock:+ backend._start_requests[START_REQUEST_ID] = record+ backend._start_cancel_tombstones.pop(START_REQUEST_ID, None)+ backend._start_cancel_tombstone_reservations.pop(START_REQUEST_ID, None)+ backend.current_start_request_id = None+ backend.current_job_id = None+ backend._pending_start_request_id = None+ backend._status_start_request_id = None++ run_as(account, install)+ return {"start_request_id": START_REQUEST_ID}+++@seeder("training-diffusion-run")+def seed_diffusion_run(account) -> dict[str, str]:+ import json++ from utils.account_context import run_as+ from utils.paths.storage_roots import tensorboard_root++ def install() -> None:+ folder = tensorboard_root() / "diffusion"+ folder.mkdir(parents = True, exist_ok = True)+ (folder / f"{DIFFUSION_JOB_ID}.json").write_text(+ json.dumps(+ {+ "job_id": DIFFUSION_JOB_ID,+ "status": "completed",+ "message": SENTINEL,+ "step": 100,+ "total_steps": 100,+ "saved": True,+ "config": {},+ }+ ),+ encoding = "utf-8",+ )++ run_as(account, install)+ return {"job_id": DIFFUSION_JOB_ID}+++@seeder("training-diffusion-dataset")+def seed_diffusion_dataset(account) -> dict[str, str]:+ import base64++ from utils.account_context import run_as+ from utils.paths import datasets_root++ def install() -> None:+ folder = datasets_root() / DATASET_NAME+ folder.mkdir(parents = True, exist_ok = True)+ image = folder / IMAGE_NAME+ image.write_bytes(base64.b64decode(PNG_1X1))+ image.with_suffix(".txt").write_text(SENTINEL, encoding = "utf-8")++ run_as(account, install)+ return {"name": DATASET_NAME, "filename": IMAGE_NAME}+++@seeder("training-scan-folder")+def seed_scan_folder(account) -> dict[str, str]:+ from storage.studio_db import add_scan_folder_with_status+ from utils.account_context import run_as+ from utils.paths import workspace_root++ def install() -> str:+ folder = workspace_root() / SCAN_FOLDER_DIRNAME+ folder.mkdir(parents = True, exist_ok = True)+ row, _ = add_scan_folder_with_status(str(folder))+ return str(row["id"])++ return {"folder_id": run_as(account, install)}+++@seeder("training-recipe-job")+def seed_recipe_job(account) -> dict[str, str]:+ from core.data_recipe.jobs import get_job_manager+ from core.data_recipe.jobs.types import Job+ from utils.account_context import run_as++ manager = get_job_manager()++ def install() -> None:+ _claim_in_process_job(manager)+ job = Job(job_id = RECIPE_JOB_ID, status = "completed", started_at = 1000.0)+ job.finished_at = 2000.0+ job.execution_type = "preview"+ job.analysis = {"summary": SENTINEL}+ job.dataset = [{"text": SENTINEL}]+ job.rows = 1+ job.cols = 1+ with manager._lock:+ manager._job = job+ manager._proc = None+ manager._mp_q = None+ manager._events.clear()+ manager._subs.clear()+ manager._seq = 0++ run_as(account, install)+ return {"job_id": RECIPE_JOB_ID}+++@seeder("training-unstructured-upload")+def seed_unstructured_upload(account) -> dict[str, str]:+ import json++ from utils.account_context import run_as+ from utils.paths import unstructured_uploads_root++ def install() -> None:+ block = unstructured_uploads_root() / BLOCK_ID+ block.mkdir(parents = True, exist_ok = True)+ (block / f"{FILE_ID}.txt").write_text(SENTINEL, encoding = "utf-8")+ (block / f"{FILE_ID}.extracted.txt").write_text(SENTINEL, encoding = "utf-8")+ (block / f"{FILE_ID}.meta.json").write_text(+ json.dumps({"original_filename": "training-matrix.txt", "size_bytes": 1}),+ encoding = "utf-8",+ )++ run_as(account, install)+ return {"block_id": BLOCK_ID, "file_id": FILE_ID}+++FACTORIES = {+ "routes.training_history:DELETE:/runs/{run_id}": Factory("training", fragment = "deleted"),+ "routes.training:GET:/start-requests/{start_request_id}": Factory(+ "training-start-request", fragment = SENTINEL+ ),+ "routes.training:POST:/start-requests/{start_request_id}/acknowledge": Factory(+ "training-start-request", fragment = "ok"+ ),+ "routes.training:POST:/start-requests/{start_request_id}/cancel": Factory(+ "training-start-request", fragment = SENTINEL+ ),+ "routes.training:GET:/diffusion/runs/{job_id}": Factory(+ "training-diffusion-run", fragment = SENTINEL+ ),+ "routes.training:GET:/diffusion/dataset/{name}/images": Factory(+ "training-diffusion-dataset", fragment = SENTINEL+ ),+ "routes.training:GET:/diffusion/dataset/{name}/image/{filename}": Factory(+ "training-diffusion-dataset", fragment = "IHDR"+ ),+ "routes.training:DELETE:/diffusion/dataset/{name}/image/{filename}": Factory(+ "training-diffusion-dataset", fragment = IMAGE_NAME+ ),+ "routes.training:PUT:/diffusion/dataset/{name}/caption/{filename}": Factory(+ "training-diffusion-dataset", {"caption": EDITED}, fragment = EDITED+ ),+ "routes.models:DELETE:/scan-folders/{folder_id}": Factory(+ "training-scan-folder",+ owner = (200,),+ wrong = (200,),+ reason = _SCAN_FOLDER_REASON,+ ),+ "routes.data_recipe.jobs:GET:/jobs/{job_id}/status": Factory(+ "training-recipe-job", fragment = RECIPE_JOB_ID+ ),+ "routes.data_recipe.jobs:GET:/jobs/{job_id}/analysis": Factory(+ "training-recipe-job", fragment = SENTINEL+ ),+ "routes.data_recipe.jobs:GET:/jobs/{job_id}/dataset": Factory(+ "training-recipe-job", fragment = SENTINEL+ ),+ "routes.data_recipe.jobs:POST:/jobs/{job_id}/cancel": Factory(+ "training-recipe-job", fragment = RECIPE_JOB_ID+ ),+ "routes.data_recipe.jobs:POST:/jobs/{job_id}/publish": Factory(+ "training-recipe-job",+ {"repo_id": "training-matrix/dataset", "description": SENTINEL, "hf_token": "hf_matrix"},+ success = 409,+ fragment = "Only completed full runs can be published.",+ owner = (400,),+ wrong = (400,),+ reason = _PUBLISH_REASON,+ ),+ "routes.data_recipe.seed:DELETE:/seed/unstructured-block/{block_id}": Factory(+ "training-unstructured-upload",+ fragment = "true",+ absent = "true",+ owner = (200,),+ wrong = (200,),+ reason = _BLOCK_REASON,+ ),+ "routes.data_recipe.seed:DELETE:/seed/unstructured-file/{block_id}/{file_id}": Factory(+ "training-unstructured-upload", fragment = "ok"+ ),+}++SKIPPED = {+ "routes.data_recipe.jobs:GET:/jobs/{job_id}/events": _EVENTS_REASON,+ "routes.data_recipe.jobs:POST:/jobs/{job_id}/events": _EVENTS_REASON,+}diff --git a/studio/backend/tests/multi_account/factory_base.py b/studio/backend/tests/multi_account/factory_base.pynew file mode 100644index 00000000000..44632229427--- /dev/null+++ b/studio/backend/tests/multi_account/factory_base.py@@ -0,0 +1,80 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Shared factory vocabulary for the route isolation matrix: a factory names a seeder that creates the resource inside the acting account and returns the route's path parameters, with actor expectations defaulting to the isolation contract (owner and other account 404, unauthenticated 401/403, deactivated 401)."""++from __future__ import annotations++import inspect+import re+from dataclasses import dataclass, field+from typing import Callable++SEEDERS: dict[str, Callable] = {}++_CONVERTER = re.compile(r"\{([^}:]+):[^}]+\}")+++def seeder(name: str):+ def decorate(function: Callable) -> Callable:+ assert name not in SEEDERS, f"duplicate seeder: {name}"+ SEEDERS[name] = function+ return function++ return decorate+++def call_seeder(name: str, account, actor: str):+ function = SEEDERS[name]+ if "actor" in inspect.signature(function).parameters:+ return function(account, actor = actor)+ return function(account)+++def format_path(path: str, params: dict) -> str:+ return _CONVERTER.sub(r"{\1}", path).format(**params)+++@dataclass(frozen = True)+class Factory:+ name: str+ body: dict | list | None = None+ success: int = 200+ fragment: str | None = None+ absent: str | None = None+ owner: tuple[int, ...] = (404,)+ wrong: tuple[int, ...] = (404,)+ unauthenticated: tuple[int, ...] = (401, 403)+ deactivated: tuple[int, ...] = (401,)+ right: tuple[int, ...] | None = None+ self_expected: tuple[int, ...] | None = None+ reason: str = ""+ query: dict = field(default_factory = dict)+ extra_params: dict = field(default_factory = dict)++ def expected(self, actor: str) -> tuple[int, ...]:+ return {+ "owner": self.owner,+ "right": self.right or (self.success,),+ "wrong": self.wrong,+ "unauthenticated": self.unauthenticated,+ "deactivated": self.deactivated,+ }[actor]++ @property+ def deviates(self) -> bool:+ return (+ self.owner != (404,)+ or self.wrong != (404,)+ or self.right is not None+ or self.self_expected is not None+ )+++def merge(*tables: dict) -> dict:+ merged: dict = {}+ for table in tables:+ for key, value in table.items():+ assert key not in merged, f"duplicate factory key: {key}"+ merged[key] = value+ return mergeddiff --git a/studio/backend/tests/multi_account/inventory.py b/studio/backend/tests/multi_account/inventory.pynew file mode 100644index 00000000000..cb4d78a6253--- /dev/null+++ b/studio/backend/tests/multi_account/inventory.py@@ -0,0 +1,134 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Inventory the real APIRouters of every routes module; run from studio/backend: python -m tests.multi_account.inventory --output ../../artifacts/route_inventory.md"""++import argparse+import importlib+import pkgutil+import re+from dataclasses import dataclass+from pathlib import Path++from fastapi import APIRouter++import routes+++@dataclass(frozen = True)+class RouteCase:+ module: str+ path: str+ method: str+ parameters: tuple[str, ...]+ router: APIRouter++ @property+ def key(self) -> str:+ return f"{self.module}:{self.method}:{self.path}"++ @property+ def object_parameters(self) -> tuple[str, ...]:+ return tuple(name for name in self.parameters if looks_like_object_id(name))+++def looks_like_object_id(name: str) -> bool:+ return bool(re.search(r"(^id$|_ids?$|_uuid$|_ref$)", name)) or name in {+ "filename",+ "session",+ "name",+ "ref",+ "slug",+ "run",+ "checkpoint",+ }+++def walk_router(router, prefix: str = ""):+ """FastAPI <=0.128 flattens includes; >=0.141 stores lazy _IncludedRouter entries."""+ for route in router.routes:+ original = getattr(route, "original_router", None)+ if original is not None:+ context = route.include_context+ yield from walk_router(original, prefix + context.prefix)+ elif hasattr(route, "path") and hasattr(route, "endpoint"):+ yield prefix + route.path, route+++def collect_routes() -> tuple[RouteCase, ...]:+ found = {}+ modules = [routes]+ modules.extend(+ importlib.import_module(info.name)+ for info in sorted(+ pkgutil.walk_packages(routes.__path__, prefix = "routes."), key = lambda info: info.name+ )+ )+ seen_routers = set()+ for module in modules:+ for router in vars(module).values():+ if not isinstance(router, APIRouter) or id(router) in seen_routers:+ continue+ seen_routers.add(id(router))+ for path, route in walk_router(router):+ origin = route.endpoint.__module__+ if not origin.startswith("routes."):+ continue+ params = tuple(re.findall(r"\{([^}:]+)(?::[^}]+)?\}", path))+ for method in sorted(getattr(route, "methods", None) or {"WEBSOCKET"}):+ case = RouteCase(origin, path, method, params, router)+ found.setdefault(case.key, case)+ return tuple(found[key] for key in sorted(found))+++ROUTES = collect_routes()+OBJECT_ROUTES = tuple(case for case in ROUTES if case.object_parameters)+++def render_inventory() -> str:+ from .factories import FACTORIES, SKIPPED++ covered = sum(case.key in FACTORIES for case in OBJECT_ROUTES)+ skipped = sum(case.key in SKIPPED for case in OBJECT_ROUTES)+ lines = [+ "# Studio route isolation inventory",+ "",+ "Generated from imported APIRouters under studio/backend/routes. Paths are router-relative; "+ "mount aliases outside routes (main.py, hub, picker, MCP mounts) are outside this inventory.",+ "",+ f"{len(ROUTES)} route/method pairs; {len(OBJECT_ROUTES)} have object-like parameters; "+ f"{covered} have factories; {skipped} are skipped with a stated reason; "+ f"{len(OBJECT_ROUTES) - covered - skipped} are uncovered.",+ "",+ "Each object route produces five cases: owner reading Alice's resource, Alice, Bob, "+ "unauthenticated, and a deactivated Alice with a previously issued JWT. "+ "A separate completeness assertion fails for routes without a factory. "+ "A factory means exercised, not necessarily passing. See pytest outcomes for pending behavior.",+ "",+ "| Module | Method | Router path | Object parameters | Factory / gap |",+ "| --- | --- | --- | --- | --- |",+ ]+ for case in ROUTES:+ coverage = (+ FACTORIES[case.key].name+ if case.key in FACTORIES+ else SKIPPED.get(case.key)+ or ("**uncovered**" if case.object_parameters else "no object-like path parameter")+ )+ lines.append(+ f"| {case.module} | {case.method} | `{case.path}` | "+ f"{', '.join(case.object_parameters) or '-'} | {coverage} |"+ )+ return "\n".join(lines) + "\n"+++def main() -> None:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--output", type = Path, required = True)+ args = parser.parse_args()+ args.output.parent.mkdir(parents = True, exist_ok = True)+ args.output.write_text(render_inventory(), encoding = "utf-8")+++if __name__ == "__main__":+ main()diff --git a/studio/backend/tests/multi_account/legacy_probe.py b/studio/backend/tests/multi_account/legacy_probe.pynew file mode 100644index 00000000000..78cd37f42ac--- /dev/null+++ b/studio/backend/tests/multi_account/legacy_probe.py@@ -0,0 +1,78 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Fresh-process upgrade simulation; main is deliberately imported after seeding."""++import importlib+import json+import os+from contextlib import closing+from pathlib import Path++from .seed import (+ MESSAGE_ID,+ PASSWORD,+ SENTINEL,+ THREAD_ID,+ old_auth_row,+ seed_legacy_install,+)+++def main() -> None:+ home = Path(os.environ["UNSLOTH_STUDIO_HOME"])+ original = seed_legacy_install(home)+ auth_row = old_auth_row(home / "auth" / "auth.db")+ application = importlib.import_module("main")+ for name, payload in original.items():+ assert (home / name).read_bytes() == payload, f"Import changed {name}"+ assert not (home / "accounts").exists()++ from fastapi.testclient import TestClient+ from auth import policy, storage+ from storage import credential_secrets, rag_db, studio_db+ from core.rag import store+ from utils.account_context import OWNER+ from utils.paths import workspace_root+ from core.inference.tools import sandbox_root++ assert storage.get_account("unsloth") == OWNER+ assert old_auth_row(home / "auth" / "auth.db") == auth_row+ assert workspace_root() == home+ assert Path(sandbox_root()) == home / "sandbox"+ assert studio_db.get_chat_thread(THREAD_ID)["title"] == SENTINEL+ assert studio_db.get_chat_message(THREAD_ID, MESSAGE_ID)["content"][0]["text"] == SENTINEL+ assert studio_db.list_chat_settings()["theme"] == "dark"+ assert studio_db.get_app_setting("legacy-owner-setting") == {"preserve": True}+ assert credential_secrets.get_hf_token() == "hf_legacy_private"+ with closing(rag_db.get_metadata_connection()) as conn:+ assert store.get_kb(conn, "legacy-kb")["name"] == SENTINEL+ assert policy.login_mode() == "single"++ client = TestClient(application.app)+ try:+ response = client.get("/api/auth/status")+ assert response.status_code == 200, response.text+ assert response.json() == {+ "initialized": True,+ "default_username": "unsloth",+ "requires_password_change": False,+ "bootstrap_deadline_seconds": None,+ "login_mode": "single",+ "full_access": True,+ }+ login = client.post("/api/auth/login", json = {"username": "unsloth", "password": PASSWORD})+ assert login.status_code == 200, login.text+ assert login.json()["access_token"]+ finally:+ client.close()+ for name, payload in original.items():+ if name != "auth/auth.db":+ assert (home / name).read_bytes() == payload, f"Owner read changed {name}"+ assert old_auth_row(home / "auth" / "auth.db") == auth_row+ assert not (home / "accounts").exists()+ print(json.dumps({"preserved_files": len(original), "owner_login": True}))+++if __name__ == "__main__":+ main()diff --git a/studio/backend/tests/multi_account/legacy_studio_schema.sql b/studio/backend/tests/multi_account/legacy_studio_schema.sqlnew file mode 100644index 00000000000..e197c48c68e--- /dev/null+++ b/studio/backend/tests/multi_account/legacy_studio_schema.sql@@ -0,0 +1,408 @@+-- SPDX-License-Identifier: AGPL-3.0-only++-- Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++-- Frozen sqlite_master from mu/base~1 (cc0cdab40e), populated only with sqlite in tests.++PRAGMA journal_mode=WAL;++CREATE TABLE api_usage_events (+ id TEXT NOT NULL PRIMARY KEY,+ subject TEXT NOT NULL,+ endpoint TEXT NOT NULL,+ model TEXT NOT NULL,+ status TEXT NOT NULL,+ prompt_tokens INTEGER NOT NULL,+ completion_tokens INTEGER NOT NULL,+ total_tokens INTEGER NOT NULL,+ created_at INTEGER NOT NULL+ ) WITHOUT ROWID+ ;++CREATE TABLE app_settings (+ key TEXT NOT NULL PRIMARY KEY,+ value_json TEXT NOT NULL,+ updated_at TEXT NOT NULL+ );++CREATE TABLE chat_attachment_inventory (+ message_id TEXT NOT NULL REFERENCES chat_messages(id) ON DELETE CASCADE,+ attachment_id TEXT NOT NULL,+ name TEXT NOT NULL,+ type TEXT,+ content_type TEXT,+ size_bytes INTEGER,+ PRIMARY KEY(message_id, attachment_id)+ ) WITHOUT ROWID+ ;++CREATE TABLE chat_attachment_inventory_state (+ singleton INTEGER NOT NULL PRIMARY KEY CHECK(singleton = 1),+ inventory_version INTEGER NOT NULL DEFAULT 0,+ dirty INTEGER NOT NULL DEFAULT 1,+ backfilled_at INTEGER NOT NULL+ );++CREATE TABLE chat_attachment_tombstones (+ thread_id TEXT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,+ message_id TEXT NOT NULL,+ attachment_id TEXT NOT NULL,+ deleted_at INTEGER NOT NULL,+ PRIMARY KEY(thread_id, message_id, attachment_id)+ ) WITHOUT ROWID+ ;++CREATE TABLE chat_clear_operations (+ id TEXT NOT NULL PRIMARY KEY,+ active_research_run_ids_json TEXT NOT NULL,+ deleted_thread_ids_json TEXT NOT NULL DEFAULT '[]',+ cleared_at INTEGER NOT NULL,+ reapable_image_ids_json TEXT,+ caches_cleared_at INTEGER+ ) WITHOUT ROWID+ ;++CREATE TABLE chat_generation_events (+ run_id TEXT NOT NULL REFERENCES chat_generation_runs(id) ON DELETE CASCADE,+ seq INTEGER NOT NULL,+ event_type TEXT NOT NULL,+ payload_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ PRIMARY KEY(run_id, seq)+ ) WITHOUT ROWID+ ;++CREATE TABLE chat_generation_runs (+ id TEXT NOT NULL PRIMARY KEY,+ owner_subject TEXT NOT NULL,+ thread_id TEXT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,+ user_message_id TEXT NOT NULL REFERENCES chat_messages(id) ON DELETE CASCADE,+ assistant_message_id TEXT NOT NULL REFERENCES chat_messages(id) ON DELETE CASCADE,+ request_hash TEXT NOT NULL,+ request_json TEXT NOT NULL,+ worker_token TEXT NOT NULL,+ status TEXT NOT NULL CHECK(status IN (+ 'queued', 'running', 'cancelling', 'cancelled', 'completed', 'failed'+ )),+ cancel_requested INTEGER NOT NULL DEFAULT 0,+ last_event_seq INTEGER NOT NULL DEFAULT 0,+ finish_reason TEXT,+ error_message TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ started_at INTEGER,+ completed_at INTEGER+ );++CREATE TABLE chat_legacy_imports (+ legacy_thread_id TEXT NOT NULL PRIMARY KEY,+ imported_at INTEGER NOT NULL+ ) WITHOUT ROWID+ ;++CREATE TABLE chat_messages (+ id TEXT NOT NULL PRIMARY KEY,+ thread_id TEXT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,+ parent_id TEXT,+ role TEXT NOT NULL,+ content_json TEXT NOT NULL,+ attachments_json TEXT,+ metadata_json TEXT,+ created_at INTEGER NOT NULL+ );++CREATE TABLE chat_projects (+ id TEXT NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ instructions TEXT,+ root_path TEXT,+ archived INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );++CREATE TABLE chat_settings (+ key TEXT NOT NULL PRIMARY KEY,+ value_json TEXT NOT NULL,+ updated_at TEXT NOT NULL+ );++CREATE TABLE chat_settings_quarantine (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ key TEXT NOT NULL,+ value_json TEXT NOT NULL,+ reason TEXT NOT NULL,+ quarantined_at TEXT NOT NULL+ );++CREATE TABLE chat_thread_tombstones (+ id TEXT NOT NULL PRIMARY KEY,+ deleted_at INTEGER NOT NULL+ ) WITHOUT ROWID+ ;++CREATE TABLE chat_threads (+ id TEXT NOT NULL PRIMARY KEY,+ title TEXT NOT NULL,+ model_type TEXT NOT NULL,+ model_id TEXT,+ model_gguf_variant TEXT,+ pair_id TEXT,+ project_id TEXT,+ archived INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER,+ openai_code_exec_container_id TEXT,+ anthropic_code_exec_container_id TEXT,+ forked_from_thread_id TEXT,+ forked_from_message_id TEXT,+ settings_json TEXT, settings_seqs TEXT,+ FOREIGN KEY(project_id) REFERENCES chat_projects(id) ON DELETE CASCADE+ );++CREATE TABLE credential_secrets (+ credential_kind TEXT NOT NULL,+ scope_id TEXT NOT NULL,+ format_version INTEGER NOT NULL,+ nonce BLOB NOT NULL,+ ciphertext BLOB NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (credential_kind, scope_id)+ ) WITHOUT ROWID+ ;++CREATE TABLE prompt_entries (+ id TEXT NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ text TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );++CREATE TABLE prompt_lists (+ id TEXT NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ items_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );++CREATE TABLE research_document_sources (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ run_id TEXT NOT NULL REFERENCES research_runs(id) ON DELETE CASCADE,+ step_position INTEGER,+ source_key TEXT NOT NULL,+ document_id TEXT,+ chunk_id TEXT,+ filename TEXT NOT NULL,+ page INTEGER,+ score REAL,+ snippet TEXT,+ fetched_at INTEGER NOT NULL,+ UNIQUE(run_id, source_key)+ );++CREATE TABLE research_events (+ run_id TEXT NOT NULL REFERENCES research_runs(id) ON DELETE CASCADE,+ seq INTEGER NOT NULL,+ event_type TEXT NOT NULL,+ data_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ PRIMARY KEY(run_id, seq)+ ) WITHOUT ROWID+ ;++CREATE TABLE research_plan_steps (+ run_id TEXT NOT NULL REFERENCES research_runs(id) ON DELETE CASCADE,+ position INTEGER NOT NULL,+ title TEXT NOT NULL,+ query TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'pending',+ result_json TEXT,+ started_at INTEGER,+ completed_at INTEGER,+ PRIMARY KEY(run_id, position)+ ) WITHOUT ROWID+ ;++CREATE TABLE research_runs (+ id TEXT NOT NULL PRIMARY KEY,+ owner_subject TEXT NOT NULL,+ thread_id TEXT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,+ user_message_id TEXT NOT NULL REFERENCES chat_messages(id) ON DELETE CASCADE,+ assistant_message_id TEXT REFERENCES chat_messages(id) ON DELETE SET NULL,+ status TEXT NOT NULL CHECK(status IN (+ 'planning', 'awaiting_approval', 'queued', 'running', 'paused',+ 'cancelling', 'cancelled', 'completed', 'failed'+ )),+ plan_json TEXT,+ plan_revision INTEGER NOT NULL DEFAULT 0,+ plan_hash TEXT,+ config_json TEXT NOT NULL,+ cancel_requested INTEGER NOT NULL DEFAULT 0,+ lease_owner TEXT,+ lease_expires_at INTEGER,+ heartbeat_at INTEGER,+ retry_count INTEGER NOT NULL DEFAULT 0,+ error_message TEXT,+ report_text TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ started_at INTEGER,+ completed_at INTEGER,+ next_event_seq INTEGER NOT NULL DEFAULT 1+ );++CREATE TABLE research_sources (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ run_id TEXT NOT NULL REFERENCES research_runs(id) ON DELETE CASCADE,+ step_position INTEGER,+ url TEXT NOT NULL,+ title TEXT,+ snippet TEXT,+ fetched_at INTEGER NOT NULL,+ UNIQUE(run_id, url)+ );++CREATE TABLE research_thread_claims (+ owner_subject TEXT NOT NULL,+ thread_id TEXT NOT NULL PRIMARY KEY REFERENCES chat_threads(id) ON DELETE CASCADE,+ created_at INTEGER NOT NULL+ ) WITHOUT ROWID+ ;++CREATE TABLE scan_folders (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ path TEXT NOT NULL UNIQUE ,+ created_at TEXT NOT NULL+ );++CREATE TABLE training_metrics (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ run_id TEXT NOT NULL REFERENCES training_runs(id) ON DELETE CASCADE,+ step INTEGER NOT NULL,+ loss REAL,+ learning_rate REAL,+ grad_norm REAL,+ eval_loss REAL,+ epoch REAL,+ num_tokens INTEGER,+ elapsed_seconds REAL,+ UNIQUE(run_id, step)+ );++CREATE TABLE training_runs (+ id TEXT NOT NULL PRIMARY KEY,+ status TEXT NOT NULL DEFAULT 'running',+ model_name TEXT NOT NULL,+ dataset_name TEXT NOT NULL,+ config_json TEXT NOT NULL,+ started_at TEXT NOT NULL,+ ended_at TEXT,+ total_steps INTEGER,+ final_step INTEGER,+ final_loss REAL,+ output_dir TEXT,+ error_message TEXT,+ duration_seconds REAL,+ loss_sparkline TEXT,+ display_name TEXT,+ resume_blocked INTEGER NOT NULL DEFAULT 0,+ resumed_from_run_id TEXT+ );++CREATE INDEX idx_api_usage_events_created_at ON api_usage_events(created_at);++CREATE INDEX idx_api_usage_events_subject_created_at ON api_usage_events(subject, created_at);++CREATE INDEX idx_chat_generation_runs_owner_thread_status ON chat_generation_runs(owner_subject, thread_id, status);++CREATE INDEX idx_chat_generation_runs_thread_status ON chat_generation_runs(thread_id, status);++CREATE INDEX idx_chat_messages_thread_id_created_at ON chat_messages(thread_id, created_at);++CREATE INDEX idx_chat_projects_archived_updated_at ON chat_projects(archived, updated_at);++CREATE INDEX idx_chat_threads_model_type_created_at ON chat_threads(model_type, created_at);++CREATE INDEX idx_chat_threads_pair_id ON chat_threads(pair_id);++CREATE INDEX idx_chat_threads_project_id ON chat_threads(project_id);++CREATE INDEX idx_metrics_run_id ON training_metrics(run_id);++CREATE INDEX idx_prompt_entries_created_at ON prompt_entries(created_at);++CREATE INDEX idx_prompt_lists_created_at ON prompt_lists(created_at);++CREATE INDEX idx_research_document_sources_run ON research_document_sources(run_id, id);++CREATE INDEX idx_research_runs_lease ON research_runs(status, lease_expires_at);++CREATE INDEX idx_research_runs_owner_thread_status ON research_runs(owner_subject, thread_id, status);++CREATE INDEX idx_research_sources_run ON research_sources(run_id, id);++CREATE TRIGGER chat_attachment_inventory_dirty_delete+ AFTER DELETE ON chat_messages+ BEGIN+ INSERT INTO chat_attachment_inventory_state+ (singleton, inventory_version, dirty, backfilled_at)+ VALUES (1, 0, 1, 0)+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;+ END;++CREATE TRIGGER chat_attachment_inventory_dirty_insert+ AFTER INSERT ON chat_messages+ BEGIN+ INSERT INTO chat_attachment_inventory_state+ (singleton, inventory_version, dirty, backfilled_at)+ VALUES (1, 0, 1, 0)+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;+ END;++CREATE TRIGGER chat_attachment_inventory_dirty_update+ AFTER UPDATE OF attachments_json, content_json ON chat_messages+ BEGIN+ INSERT INTO chat_attachment_inventory_state+ (singleton, inventory_version, dirty, backfilled_at)+ VALUES (1, 0, 1, 0)+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;+ END;++CREATE TRIGGER reject_second_active_chat_generation_insert+ BEFORE INSERT ON chat_generation_runs+ WHEN NEW.status IN ('queued','running','cancelling')+ AND EXISTS (+ SELECT 1 FROM chat_generation_runs+ WHERE thread_id = NEW.thread_id+ AND status IN ('queued','running','cancelling')+ )+ BEGIN+ SELECT RAISE(ABORT, 'thread already has an active chat generation');+ END;++CREATE TRIGGER reject_second_active_chat_generation_update+ BEFORE UPDATE OF thread_id, status ON chat_generation_runs+ WHEN NEW.status IN ('queued','running','cancelling')+ AND EXISTS (+ SELECT 1 FROM chat_generation_runs+ WHERE thread_id = NEW.thread_id+ AND id != NEW.id+ AND status IN ('queued','running','cancelling')+ )+ BEGIN+ SELECT RAISE(ABORT, 'thread already has an active chat generation');+ END;++CREATE TRIGGER tombstone_chat_generation_run_id+ BEFORE DELETE ON chat_generation_runs+ BEGIN+ INSERT OR REPLACE INTO app_settings (key, value_json, updated_at)+ VALUES (+ 'chat-generation-run-tombstone:' || OLD.id,+ 'true',+ CAST(strftime('%s', 'now') AS INTEGER) * 1000+ );+ END;diff --git a/studio/backend/tests/multi_account/perf_utils.py b/studio/backend/tests/multi_account/perf_utils.pynew file mode 100644index 00000000000..5fe853adbf2--- /dev/null+++ b/studio/backend/tests/multi_account/perf_utils.py@@ -0,0 +1,113 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Local Git-only baseline materialization; no network or other worker checkout is read."""++from __future__ import annotations++import io+import json+import os+import subprocess+import sys+import tarfile+from pathlib import Path++REPO = Path(__file__).resolve().parents[4]+PROBE = REPO / "tests/studio/multi_account/perf/probe.py"+SCRATCH = REPO / "temp" / "multi_account_perf"+++def baseline_ref() -> str | None:+ """The pre-account commit to measure against: UNSLOTH_STUDIO_PERF_BASE_REF, else the merge base with upstream main."""+ explicit = os.environ.get("UNSLOTH_STUDIO_PERF_BASE_REF")+ candidates = [explicit] if explicit else []+ for upstream in ("origin/main", "upstream/main", "main"):+ candidates.append(f"merge-base:{upstream}")+ for candidate in candidates:+ if candidate.startswith("merge-base:"):+ command = ["git", "merge-base", "HEAD", candidate.split(":", 1)[1]]+ else:+ command = ["git", "rev-parse", "--verify", f"{candidate}^{{commit}}"]+ result = subprocess.run(command, cwd = REPO, capture_output = True, text = True)+ revision = result.stdout.strip()+ if result.returncode == 0 and revision and revision != _head():+ return revision+ return None+++def _head() -> str:+ return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd = REPO, text = True).strip()+++def materialize_revision(ref: str, destination: Path) -> Path:+ destination = destination.resolve()+ assert destination.is_relative_to(REPO), "Revision snapshots must stay in this clone"+ revision = subprocess.check_output(+ ["git", "rev-parse", "--verify", f"{ref}^{{commit}}"], cwd = REPO, text = True+ ).strip()+ payload = subprocess.check_output(+ ["git", "archive", "--format=tar", revision, "studio/backend"], cwd = REPO+ )+ destination.mkdir(parents = True, exist_ok = False)+ with tarfile.open(fileobj = io.BytesIO(payload)) as archive:+ for member in archive.getmembers():+ assert not member.issym() and not member.islnk()+ assert (destination / member.name).resolve().is_relative_to(destination)+ archive.extractall(destination, filter = "data")+ return destination / "studio/backend"+++def run_probe(+ backend: Path,+ home: Path,+ *,+ mode: str,+ samples: int = 2000,+ history_samples: int = 200,+) -> dict:+ home = home.resolve()+ assert home.is_relative_to(REPO), "Probe data must stay in this clone"+ home.parent.mkdir(parents = True, exist_ok = True)+ runtime = home.parent / (home.name + "-runtime")+ for leaf in ("tmp", "hf", "cache", "Documents"):+ (runtime / leaf).mkdir(parents = True, exist_ok = True)+ env = dict(os.environ)+ env.update(+ PYTHONDONTWRITEBYTECODE = "1",+ PYTHONPATH = str(backend),+ UNSLOTH_STUDIO_HOME = str(home),+ HF_HOME = str(runtime / "hf"),+ HF_HUB_CACHE = str(runtime / "hf" / "hub"),+ HF_HUB_OFFLINE = "1",+ TMPDIR = str(runtime / "tmp"),+ XDG_CACHE_HOME = str(runtime / "cache"),+ UNSLOTH_STUDIO_DOCUMENTS_HOME = str(runtime / "Documents"),+ UNSLOTH_ALLOW_CPU = "1",+ UNSLOTH_IS_PRESENT = "1",+ UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE = "1",+ UNSLOTH_DIFFUSION_ATTENTION_INSTALL = "0",+ )+ result = subprocess.run(+ [+ sys.executable,+ str(PROBE),+ "--backend",+ str(backend),+ "--helpers",+ str(Path(__file__).parent),+ "--mode",+ mode,+ "--samples",+ str(samples),+ "--history-samples",+ str(history_samples),+ ],+ cwd = backend,+ env = env,+ capture_output = True,+ text = True,+ timeout = 300,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ return json.loads(result.stdout.splitlines()[-1])diff --git a/studio/backend/tests/multi_account/seed.py b/studio/backend/tests/multi_account/seed.pynew file mode 100644index 00000000000..dffd51b714c--- /dev/null+++ b/studio/backend/tests/multi_account/seed.py@@ -0,0 +1,136 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Frozen pre-account data. Seeding uses sqlite and files, never product storage APIs."""++import hashlib+import json+import sqlite3+from contextlib import closing+from pathlib import Path++LEGACY_REF = "cc0cdab40e"+PASSWORD = "legacy-owner-password"+SALT = "0123456789abcdef0123456789abcdef"+JWT_SECRET = "legacy-jwt-secret-that-is-longer-than-32-bytes"+OLD_AUTH_COLUMNS = (+ "id",+ "username",+ "password_salt",+ "password_hash",+ "jwt_secret",+ "must_change_password",+)+OLD_AUTH_SCHEMA = """+CREATE TABLE auth_user (+ id INTEGER PRIMARY KEY,+ username TEXT UNIQUE NOT NULL,+ password_salt TEXT NOT NULL,+ password_hash TEXT NOT NULL,+ jwt_secret TEXT NOT NULL,+ must_change_password INTEGER NOT NULL DEFAULT 0+);+CREATE TABLE app_secrets (key TEXT PRIMARY KEY, value TEXT NOT NULL);+"""+THREAD_ID = "legacy-thread"+MESSAGE_ID = "legacy-message"+SENTINEL = "Owner's saved conversation: café / 日本語"+++def seed_studio_db(path: Path, *, populated: bool = True) -> None:+ path.parent.mkdir(parents = True, exist_ok = True)+ with closing(sqlite3.connect(path)) as conn:+ conn.executescript(+ Path(__file__).with_name("legacy_studio_schema.sql").read_text(encoding = "utf-8")+ )+ if populated:+ conn.execute(+ "INSERT INTO chat_threads (id,title,model_type,model_id,created_at,updated_at) "+ "VALUES (?,?,?,?,?,?)",+ (THREAD_ID, SENTINEL, "base", "legacy/model", 1000, 1000),+ )+ conn.execute(+ "INSERT INTO chat_messages (id,thread_id,role,content_json,created_at) "+ "VALUES (?,?,?,?,?)",+ (+ MESSAGE_ID,+ THREAD_ID,+ "user",+ json.dumps([{"type": "text", "text": SENTINEL}]),+ 1000,+ ),+ )+ conn.execute(+ "INSERT INTO chat_settings VALUES (?,?,?)", ("theme", '"dark"', "2026-01-01")+ )+ conn.execute(+ "INSERT INTO app_settings VALUES (?,?,?)",+ ("legacy-owner-setting", '{"preserve":true}', "2026-01-01"),+ )+ # Fixed AES-GCM vector: key bytes(range(32)), nonce bytes(range(12)), AAD b'unsloth-studio-credential\0hf_token\0default', plaintext b'hf_legacy_private'.+ conn.execute(+ "INSERT INTO credential_secrets VALUES (?,?,?,?,?,?,?)",+ (+ "hf_token",+ "default",+ 1,+ bytes(range(12)),+ bytes.fromhex(CREDENTIAL_HEX),+ "2026-01-01",+ "2026-01-01",+ ),+ )+ conn.execute("INSERT OR REPLACE INTO chat_attachment_inventory_state VALUES (1,1,0,1000)")+ conn.commit()+ conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")+++CREDENTIAL_HEX = "2f648977a082a378f41ee7f9d89f1919e62d7f5cd10fc5977ef1f485c413ea1920"+++def seed_legacy_install(home: Path) -> dict[str, bytes]:+ auth_path = home / "auth" / "auth.db"+ auth_path.parent.mkdir(parents = True)+ with closing(sqlite3.connect(auth_path)) as conn:+ conn.executescript(OLD_AUTH_SCHEMA)+ digest = hashlib.pbkdf2_hmac("sha256", PASSWORD.encode(), SALT.encode(), 100_000).hex()+ conn.execute(+ "INSERT INTO auth_user VALUES (1,?,?,?,?,0)",+ ("unsloth", SALT, digest, JWT_SECRET),+ )+ conn.execute(+ "INSERT INTO app_secrets VALUES (?,?)",+ ("credential_encryption_key_v1", bytes(range(32)).hex()),+ )+ conn.commit()+ seed_studio_db(home / "studio.db")+ rag_path = home / "rag" / "rag.db"+ rag_path.parent.mkdir(parents = True)+ with closing(sqlite3.connect(rag_path)) as conn:+ conn.execute(+ "CREATE TABLE knowledge_bases (id TEXT PRIMARY KEY, name TEXT NOT NULL, "+ "description TEXT, embedding_model TEXT, created_at TEXT NOT NULL)"+ )+ conn.execute(+ "INSERT INTO knowledge_bases VALUES ('legacy-kb',?,NULL,NULL,'2026-01-01')", (SENTINEL,)+ )+ conn.commit()+ for leaf in (+ "outputs/my-finetune/checkpoint-100/adapter_model.safetensors",+ "sandbox/legacy-thread/workspace/notes.txt",+ "rag/documents/legacy-document/original.pdf",+ "assets/uploads/legacy-dataset.jsonl",+ ):+ path = home / leaf+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(b"\x00legacy\r\n" + leaf.encode() + b"\xff")+ return {+ str(path.relative_to(home)): path.read_bytes() for path in home.rglob("*") if path.is_file()+ }+++def old_auth_row(path: Path) -> tuple:+ with closing(sqlite3.connect(path)) as conn:+ return conn.execute(+ f"SELECT {','.join(OLD_AUTH_COLUMNS)} FROM auth_user WHERE username = ?", ("unsloth",)+ ).fetchone()diff --git a/studio/backend/tests/multi_account/support.py b/studio/backend/tests/multi_account/support.pynew file mode 100644index 00000000000..8298bf03fc1--- /dev/null+++ b/studio/backend/tests/multi_account/support.py@@ -0,0 +1,25 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Small real-router application shared by integration tests and the perf runner."""++from fastapi import Depends, FastAPI++from auth import authentication+from routes import auth, chat_history+++def make_app() -> FastAPI:+ app = FastAPI()+ app.include_router(auth.router, prefix = "/api/auth")+ app.include_router(chat_history.router, prefix = "/api/chat")++ @app.get("/account-probe")+ async def account_probe(subject: str = Depends(authentication.get_current_subject)):+ return {"subject": subject}++ return app+++def bearer(username: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {authentication.create_access_token(subject = username)}"}diff --git a/studio/backend/tests/multi_account/test_alice_bob_matrix.py b/studio/backend/tests/multi_account/test_alice_bob_matrix.pynew file mode 100644index 00000000000..7cfbc3988a8--- /dev/null+++ b/studio/backend/tests/multi_account/test_alice_bob_matrix.py@@ -0,0 +1,174 @@+# 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 sqlite3+from contextlib import closing++import pytest+from fastapi import APIRouter, FastAPI+from fastapi.testclient import TestClient++from auth import policy+from storage import studio_db+from utils.account_context import run_as++from .factories import (+ FACTORIES,+ SKIPPED,+ format_path,+ initialize_workspaces,+ seed_resource,+ snapshot_resource,+)+from .inventory import (+ OBJECT_ROUTES,+ ROUTES,+ collect_routes,+ looks_like_object_id,+ render_inventory,+ walk_router,+)+from .support import bearer++ACTORS = ("owner", "right", "wrong", "unauthenticated", "deactivated")+++def matrix_parameters():+ for case in OBJECT_ROUTES:+ if case.key in FACTORIES:+ for actor in ACTORS:+ yield pytest.param(case, actor, id = f"{case.key}[{actor}]")+++def test_object_route_factory_completeness(capsys):+ uncovered = [+ case.key for case in OBJECT_ROUTES if case.key not in FACTORIES and case.key not in SKIPPED+ ]+ covered = [case.key for case in OBJECT_ROUTES if case.key in FACTORIES]+ skipped = [case.key for case in OBJECT_ROUTES if case.key in SKIPPED]+ with capsys.disabled():+ print(+ f"\nroute isolation matrix: {len(OBJECT_ROUTES)} object routes, "+ f"{len(covered)} covered by factory, {len(skipped)} skipped with reason, "+ f"{len(covered) * len(ACTORS)} actor cases"+ )+ assert not uncovered, uncovered+++def test_skipped_routes_are_real_object_routes_with_a_reason():+ keys = {case.key for case in OBJECT_ROUTES}+ assert set(SKIPPED) <= keys, sorted(set(SKIPPED) - keys)+ assert all(reason.strip() for reason in SKIPPED.values())+ assert not set(SKIPPED) & set(FACTORIES)+++def test_factories_that_leave_the_default_contract_state_a_reason():+ unexplained = [+ key for key, factory in FACTORIES.items() if factory.deviates and not factory.reason.strip()+ ]+ assert not unexplained, unexplained++[email protected]("case,actor", list(matrix_parameters()))+def test_object_route_account_matrix(case, actor, request):+ accounts = request.getfixturevalue("accounts")+ auth_db = request.getfixturevalue("isolated_auth")+ factory = FACTORIES[case.key]+ initialize_workspaces(accounts)+ params = seed_resource(factory, accounts["alice"], actor)+ before = snapshot_resource(accounts["alice"])+ username = {"owner": "unsloth", "right": "alice", "wrong": "bob", "deactivated": "alice"}.get(+ actor+ )+ headers = bearer(username) if username else {}+ if actor == "deactivated":+ with closing(sqlite3.connect(auth_db.DB_PATH)) as conn:+ conn.execute("UPDATE auth_user SET is_active=0 WHERE username='alice'")+ conn.commit()+ policy.invalidate_account_cache()++ app = FastAPI()+ app.include_router(case.router, prefix = "/matrix")+ with TestClient(app, raise_server_exceptions = False) as client:+ response = client.request(+ case.method,+ "/matrix" + format_path(case.path, params),+ headers = headers,+ params = factory.query,+ json = factory.body,+ )+ assert response.status_code in factory.expected(actor), (+ case.key,+ actor,+ response.status_code,+ response.text,+ )+ if actor == "right":+ if factory.fragment:+ assert factory.fragment in response.text+ else:+ assert snapshot_resource(accounts["alice"]) == before+ if factory.absent:+ assert factory.absent not in response.text, response.text+ if factory.name == "api-key":+ assert len(auth_db.list_api_keys("alice")) == 1+++ "case", [case for case in OBJECT_ROUTES if case.key in FACTORIES], ids = lambda case: case.key+)+def test_owner_can_still_use_own_resource(case, accounts):+ initialize_workspaces(accounts)+ factory = FACTORIES[case.key]+ params = seed_resource(factory, accounts["unsloth"])+ app = FastAPI()+ app.include_router(case.router, prefix = "/matrix")+ with TestClient(app, raise_server_exceptions = False) as client:+ response = client.request(+ case.method,+ "/matrix" + format_path(case.path, params),+ headers = bearer("unsloth"),+ params = factory.query,+ json = factory.body,+ )+ assert response.status_code in (factory.self_expected or (factory.success,)), response.text+++def test_first_database_use_in_each_account_initializes_its_schema(accounts):+ for account in accounts.values():+ assert run_as(account, studio_db.list_chat_threads) == []+++def test_inventory_contains_hidden_routes_and_no_duplicate_method_paths():+ assert ROUTES == collect_routes()+ assert len({case.key for case in ROUTES}) == len(ROUTES)+ assert "routes.rag:GET:/jobs/{job_id}/events" in {case.key for case in ROUTES}+ assert set(FACTORIES) <= {+ case.key for case in OBJECT_ROUTES+ }, "A registered route disappeared or changed shape"+ generated = {+ (parameter.values[0].key, parameter.values[1]) for parameter in matrix_parameters()+ }+ assert generated == {+ (case.key, actor) for case in OBJECT_ROUTES if case.key in FACTORIES for actor in ACTORS+ }+ report = render_inventory()+ assert all(f"`{case.path}`" in report for case in OBJECT_ROUTES)+++def test_nested_router_prefixes_are_collected():+ nested, parent = APIRouter(), APIRouter()++ @nested.get("/{item_id}", include_in_schema = False)+ def get_item(item_id: str):+ return item_id++ parent.include_router(nested, prefix = "/items")+ assert [path for path, _ in walk_router(parent)] == ["/items/{item_id}"]+++ "name", ["id", "thread_id", "run_id", "job_id", "server_id", "key_id", "filename", "ref"]+)+def test_object_parameter_detection(name):+ assert looks_like_object_id(name)diff --git a/studio/backend/tests/multi_account/test_browse_folders_managed.py b/studio/backend/tests/multi_account/test_browse_folders_managed.pynew file mode 100644index 00000000000..00bbac24323--- /dev/null+++ b/studio/backend/tests/multi_account/test_browse_folders_managed.py@@ -0,0 +1,20 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's folder browser is confined to its workspace, suggestions included."""++from routes import models as models_routes+from utils.account_context import AccountContext, run_as+from utils.paths.storage_roots import workspace_root++ALICE = AccountContext("a" * 32, "alice")+++def test_managed_browse_suggests_only_the_workspace(isolated_auth):+ root = run_as(ALICE, workspace_root)+ (root / "models").mkdir(parents = True)+ response = run_as(ALICE, models_routes.browse_folders, None, False, "alice")+ assert response.current == str(root.resolve())+ assert response.parent is None+ assert response.suggestions == [str(root.resolve())]+ assert [entry.name for entry in response.entries] == ["models"]diff --git a/studio/backend/tests/multi_account/test_chat_load_retirement.py b/studio/backend/tests/multi_account/test_chat_load_retirement.pynew file mode 100644index 00000000000..4c33df235c2--- /dev/null+++ b/studio/backend/tests/multi_account/test_chat_load_retirement.py@@ -0,0 +1,68 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Retiring an account cancels its chat loads; a retired account never becomes a resident sharer."""++import inspect+import threading+import uuid++import pytest+from fastapi import HTTPException++from auth import policy+from core.training import account_jobs as jobs+from hub.services.models import account_access as access+from routes import accounts, inference+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def _attempt(subject, request_id = None):+ return inference._ScopedLoadAttempt(+ token = uuid.uuid4().hex,+ request_id = request_id,+ model_path = "org/model",+ subject = subject,+ cancel_event = threading.Event(),+ cancel_complete = threading.Event(),+ )+++def test_retirement_cancels_only_the_accounts_loads(monkeypatch):+ pending, scoped, running = (+ _attempt(ALICE.account_id),+ _attempt(ALICE.account_id, "r1"),+ _attempt(ALICE.account_id),+ )+ bob = _attempt(BOB.account_id)+ monkeypatch.setattr(inference, "_pending_load_attempts", {a.token: a for a in (pending, bob)})+ monkeypatch.setattr(inference, "_scoped_load_attempts", {(ALICE.account_id, "r1"): scoped})+ monkeypatch.setattr(inference, "_running_load_attempt", running)+ assert inference.retire_account_loads(ALICE.account_id) == 3+ for attempt in (pending, scoped, running):+ assert attempt.cancel_event.is_set() and attempt.cancel_complete.is_set()+ assert not bob.cancel_event.is_set()+ assert "retire_account_loads(account.account_id)" in inspect.getsource(+ accounts.retire_account_roots+ )+++def test_retired_account_neither_publishes_nor_joins_a_resident(monkeypatch):+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_retired", {ALICE.account_id})+ monkeypatch.setattr(access, "_resident_sharers", {})+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_uncommitted_resident", {})+ for call in (+ lambda: access.publish_resident("chat", "org/model"),+ lambda: access.join_resident("chat"),+ ):+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, call)+ assert exc.value.status_code == 403+ assert access._resident_sharers == {} and access._uncommitted_resident == {}+ run_as(BOB, access.join_resident, "chat")+ assert access._resident_sharers == {"chat": {BOB.account_id}}diff --git a/studio/backend/tests/multi_account/test_chat_load_status.py b/studio/backend/tests/multi_account/test_chat_load_status.pynew file mode 100644index 00000000000..e8e477a8540--- /dev/null+++ b/studio/backend/tests/multi_account/test_chat_load_status.py@@ -0,0 +1,87 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A load's preflight identity must stay private before it obtains GPU residency."""++import sys+import threading+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "studio/backend"))++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from routes import inference+from utils.account_context import bind_account, reset_account+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.router, prefix = "/api/inference")+ return TestClient(app)+++def test_foreign_preflight_model_is_not_in_status(monkeypatch, accounts):+ entered, finish = threading.Event(), threading.Event()+ secret_model = "alice/private-unreleased-checkpoint"+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(inference, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(+ inference, "get_llama_cpp_backend", lambda: SimpleNamespace(is_loaded = False)+ )+ monkeypatch.setattr(inference, "_probe_llama_cpp_status", lambda _: (False, {}))+ monkeypatch.setattr(inference, "_running_load_attempt", None)+ monkeypatch.setattr(inference, "_pending_load_attempts", {})+ inference.begin_load_lifecycle()++ def slow_access(reference):+ assert reference == secret_model+ entered.set()+ assert finish.wait(10)+ # End the simulated slow Hub authorization without downloading anything.+ raise HTTPException(status_code = 404, detail = "Model not found")++ monkeypatch.setattr(access, "require_model_access", slow_access)+ load_result = {}++ def load():+ with client_for(accounts["alice"]) as client:+ load_result["response"] = client.post(+ "/api/inference/load", json = {"model_path": secret_model}+ )++ worker = threading.Thread(target = load)+ worker.start()+ try:+ assert entered.wait(10), "real load handler never reached preflight"+ assert gpu_arbiter.current_owner() is None+ with client_for(accounts["alice"]) as client:+ mine = client.get("/api/inference/status")+ assert mine.status_code == 200+ assert secret_model in mine.json()["loading"]+ with client_for(accounts["unsloth"]) as client:+ assert secret_model in client.get("/api/inference/status").json()["loading"]+ with client_for(accounts["bob"]) as client:+ response = client.get("/api/inference/status")+ assert response.status_code == 200+ assert secret_model not in response.text, response.text+ finally:+ finish.set()+ worker.join(10)+ assert not worker.is_alive()diff --git a/studio/backend/tests/multi_account/test_chat_shared_resident.py b/studio/backend/tests/multi_account/test_chat_shared_resident.pynew file mode 100644index 00000000000..5c30c9e171c--- /dev/null+++ b/studio/backend/tests/multi_account/test_chat_shared_resident.py@@ -0,0 +1,223 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Accounts whose matching load reused the resident chat model share it: both see and use it,+one leaving does not evict the other, and a replacement or teardown starts the set afresh."""++import asyncio+import sys+import threading+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "studio/backend"))++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from auth import policy+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from models.inference import LoadRequest+from routes import inference+from state import active_generations+from studio.backend.tests.llama_backend_double import FakeLlamaCppBackend+from utils.account_context import bind_account, reset_account, run_as++RESIDENT = "unsloth/shared-gguf"+VARIANT = "Q4_K_M"+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.router, prefix = "/api/inference")+ return TestClient(app)+++class FakeLlama(FakeLlamaCppBackend):+ """The surface /load's reuse path, /unload and /status read."""++ is_diffusion = False+ is_audio = False+ has_audio_input = False+ has_video_input = False+ requires_trust_remote_code = False+ supports_reasoning = False+ reasoning_style = "enable_thinking"+ reasoning_effort_levels: list = []+ reasoning_always_on = False+ supports_preserve_thinking = False+ tensor_parallel = False+ disable_vision = False+ vision_disabled_by_user = False+ gpu_memory_mode = "auto"+ gpu_layers = 0+ n_cpu_moe = 0+ n_moe_layers = 0++ def __init__(self):+ self.is_active = True+ self.is_loaded = True+ self.model_identifier = RESIDENT+ self.hf_variant = VARIANT+ self.chat_template_override = None+ self.holds_no_vram = False+ self._audio_probed = True+ self._openai_gguf_companion_roots = ()+ self._openai_gguf_companion_state = ()+ self.unloaded = False++ def __getattr__(self, name):+ # Status reads many optional runtime fields; an unset one reads as the real backend's None.+ if name.startswith("__"):+ raise AttributeError(name)+ return None++ def adopt_load_intent_if_matched(self, intent):+ return True++ def unload_model(self):+ self.is_active = False+ self.is_loaded = False+ self.model_identifier = None+ self.unloaded = True+ return True+++def shared(monkeypatch, accounts):+ """Bob loaded RESIDENT; the arbiter and the resident record say so."""+ llama = FakeLlama()+ standard = SimpleNamespace(+ active_model_name = None,+ models = {},+ get_loading_model = lambda: None,+ loading_models = (),+ )+ for name in ("_resident_accounts", "_prior_resident_accounts", "_resident_sharers"):+ monkeypatch.setattr(access, name, {})+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", accounts["bob"].account_id)+ monkeypatch.setattr(gpu_arbiter, "_prior_account", None)+ monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: llama)+ monkeypatch.setattr(inference, "get_inference_backend", lambda: standard)+ monkeypatch.setattr(inference, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(inference, "_probe_llama_cpp_status", lambda _: (False, {}))+ monkeypatch.setattr(inference, "_running_load_attempt", None)+ monkeypatch.setattr(inference, "_pending_load_attempts", {})+ active_generations.reset_for_tests()+ run_as(accounts["bob"], access.publish_resident, "chat", RESIDENT)+ return llama+++def reuse_load(monkeypatch, account):+ """Run the real /load implementation down its GGUF reuse path as ``account``."""+ responses = []+ monkeypatch.setattr(+ inference,+ "_resolve_model_identifier_for_request",+ lambda *a, **k: (RESIDENT, RESIDENT, False),+ )+ monkeypatch.setattr(inference, "resolve_effective_chat_template_override", lambda *a, **k: None)+ monkeypatch.setattr(inference, "_active_gguf_intent", lambda *a, **k: object())+ monkeypatch.setattr(access, "require_model_access", lambda *a, **k: None)++ def response(_backend, status, *a, **k):+ responses.append(status)+ return SimpleNamespace(status = status, model = RESIDENT)++ monkeypatch.setattr(inference, "_gguf_load_response", response)+ fastapi_request = SimpleNamespace(+ app = SimpleNamespace(state = SimpleNamespace(llama_parallel_slots = 1))+ )+ request = LoadRequest(model_path = RESIDENT, gguf_variant = VARIANT)+ result = run_as(+ account,+ lambda: asyncio.run(+ inference._load_model_impl(request, fastapi_request, current_subject = account.username)+ ),+ )+ assert responses == ["already_loaded"], responses+ return result+++def status_for(account):+ with client_for(account) as client:+ response = client.get("/api/inference/status")+ assert response.status_code == 200, response.text+ return response.json()+++def sees_resident(account):+ body = status_for(account)+ return body.get("model_identifier") == RESIDENT and "yours" not in body+++def test_a_matching_load_shares_the_resident_without_a_reload(monkeypatch, shared, accounts):+ assert sees_resident(accounts["bob"])+ assert not sees_resident(accounts["alice"])+ reuse_load(monkeypatch, accounts["alice"])+ assert not shared.unloaded+ print(f"sharers: {access._resident_sharers}")+ assert sees_resident(accounts["alice"]) and sees_resident(accounts["bob"])+ assert run_as(accounts["alice"], inference._openai_model_objects) != []+ assert sees_resident(accounts["unsloth"])+ # A repeat load by the same account is one membership.+ reuse_load(monkeypatch, accounts["alice"])+ assert access._resident_sharers["chat"] == {+ accounts["alice"].account_id,+ accounts["bob"].account_id,+ }+++def test_a_sharer_leaving_keeps_the_model_for_the_others(monkeypatch, shared, accounts):+ reuse_load(monkeypatch, accounts["alice"])+ # Bob is mid-generation: alice's share release must not be a gpu_busy refusal.+ with run_as(accounts["bob"], active_generations.ActiveGeneration, threading.Event()):+ with client_for(accounts["alice"]) as client:+ left = client.post("/api/inference/unload", json = {"model_path": RESIDENT})+ assert left.status_code == 200, left.text+ assert not shared.unloaded+ assert sees_resident(accounts["bob"])+ assert not sees_resident(accounts["alice"])+ assert status_for(accounts["alice"]) == {"loaded": [], "loading": [], "yours": False}+ # The last sharer's unload is a real teardown and clears the set.+ with client_for(accounts["bob"]) as client:+ gone = client.post("/api/inference/unload", json = {"model_path": RESIDENT})+ assert gone.status_code == 200, gone.text+ assert shared.unloaded+ assert "chat" not in access._resident_sharers+++def test_a_replacement_starts_the_sharers_afresh(monkeypatch, shared, accounts):+ reuse_load(monkeypatch, accounts["alice"])+ run_as(accounts["bob"], access.publish_resident, "chat", "bob/other-model")+ assert access._resident_sharers["chat"] == {accounts["bob"].account_id}+ assert run_as(accounts["alice"], access.resident_hidden, "chat", "bob/other-model")+++def test_retirement_and_eviction_drop_shares(monkeypatch, shared, accounts):+ reuse_load(monkeypatch, accounts["alice"])+ access.retire_resident_shares(accounts["alice"].account_id)+ assert not sees_resident(accounts["alice"]) and sees_resident(accounts["bob"])+ access.clear_resident("chat")+ assert "chat" not in access._resident_sharers+++def test_single_account_installs_record_nothing(monkeypatch):+ monkeypatch.setattr(access, "_resident_sharers", {})+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: False)+ access.publish_resident("chat", RESIDENT)+ access.join_resident("chat")+ assert access._resident_sharers == {}+ assert access.release_shared_resident("chat") is Falsediff --git a/studio/backend/tests/multi_account/test_chat_unload_ownership.py b/studio/backend/tests/multi_account/test_chat_unload_ownership.pynew file mode 100644index 00000000000..276e5d12299--- /dev/null+++ b/studio/backend/tests/multi_account/test_chat_unload_ownership.py@@ -0,0 +1,138 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A chat teardown must drop the CHAT claim, or every other account sees a phantom resident."""++import asyncio+import sys+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "studio/backend"))++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter, llama_keepwarm+from hub.services.models import account_access as access+from routes import inference+from utils.account_context import bind_account, reset_account++RESIDENT = "alice/private-gguf"+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.router, prefix = "/api/inference")+ return TestClient(app)+++class FakeLlama:+ """Only the surface /unload and /status read; teardown flips residency like the real one."""++ def __init__(self):+ self.is_active = True+ self.is_loaded = True+ self.model_identifier = RESIDENT+ self.hf_variant = None+ self.chat_template_override = None+ self.unloaded = False++ def unload_model(self):+ self.is_active = False+ self.is_loaded = False+ self.model_identifier = None+ self.unloaded = True+ return True+++def chat_resident(monkeypatch, accounts):+ llama = FakeLlama()+ standard = SimpleNamespace(+ active_model_name = None,+ models = {},+ get_loading_model = lambda: None,+ loading_models = (),+ )+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_prior_resident_accounts", {})+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", accounts["alice"].account_id)+ monkeypatch.setattr(gpu_arbiter, "_prior_account", None)+ monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: llama)+ monkeypatch.setattr(inference, "get_inference_backend", lambda: standard)+ monkeypatch.setattr(inference, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(inference, "_probe_llama_cpp_status", lambda _: (False, {}))+ monkeypatch.setattr(inference, "_running_load_attempt", None)+ monkeypatch.setattr(inference, "_pending_load_attempts", {})+ return llama+++def bob_status(accounts):+ with client_for(accounts["bob"]) as client:+ return client.get("/api/inference/status")+++def test_manual_unload_releases_chat_ownership(chat_resident, accounts):+ with client_for(accounts["alice"]) as client:+ unload = client.post("/api/inference/unload", json = {"model_path": RESIDENT})+ assert unload.status_code == 200, unload.text+ assert chat_resident.unloaded, "the fake backend was never torn down"++ response = bob_status(accounts)+ assert response.status_code == 200, response.text+ body = response.json()+ # The hidden-resident answer is exactly {"loaded": True, "yours": False}; the real+ # status has no "yours" key and reports "loaded" as the list of resident models.+ assert "yours" not in body, f"phantom resident after unload: {body}"+ assert body.get("loaded") == [], f"phantom resident after unload: {body}"+ assert body.get("active_model") is None, body+ assert gpu_arbiter.current_owner() is None+ assert gpu_arbiter.owner_account() is None+++def test_idle_auto_unload_releases_chat_ownership(chat_resident, accounts, monkeypatch):+ monkeypatch.setattr(llama_keepwarm, "_is_idle", lambda ttl: True)+ monkeypatch.setattr(llama_keepwarm, "_note_activity", lambda: None)+ monkeypatch.setattr(+ "utils.openai_auto_switch_settings.get_auto_unload_idle_seconds", lambda: 1.0+ )+ monkeypatch.setattr("utils.openai_auto_switch_settings.get_auto_unload_api_only", lambda: False)+ monkeypatch.setattr("utils.openai_auto_switch_settings.get_auto_unload_keep_kv", lambda: False)++ async def one_tick():+ task = asyncio.ensure_future(llama_keepwarm.idle_unload_loop(poll_seconds = 0.01))+ for _ in range(500):+ await asyncio.sleep(0.01)+ if chat_resident.unloaded:+ break+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ asyncio.run(one_tick())+ assert chat_resident.unloaded, "idle loop never tore the backend down"++ response = bob_status(accounts)+ assert response.status_code == 200, response.text+ body = response.json()+ # The hidden-resident answer is exactly {"loaded": True, "yours": False}; the real+ # status has no "yours" key and reports "loaded" as the list of resident models.+ assert "yours" not in body, f"phantom resident after idle unload: {body}"+ assert body.get("loaded") == [], f"phantom resident after idle unload: {body}"+ assert body.get("active_model") is None, body+ assert gpu_arbiter.current_owner() is None+ assert gpu_arbiter.owner_account() is Nonediff --git a/studio/backend/tests/multi_account/test_companion_cleanup_account_filter.py b/studio/backend/tests/multi_account/test_companion_cleanup_account_filter.pynew file mode 100644index 00000000000..90617247f36--- /dev/null+++ b/studio/backend/tests/multi_account/test_companion_cleanup_account_filter.py@@ -0,0 +1,43 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Delete previews and orphan listings read only the repos the calling account may see."""++from dataclasses import dataclass++from hub.services.models import account_access as access+from hub.services.models import cache_inventory, companion_cleanup+from utils.account_context import AccountContext, OWNER, run_as++ALICE = AccountContext("a" * 32, "alice")+++@dataclass(frozen = True)+class Scan:+ repos: frozenset+++@dataclass(frozen = True)+class Repo:+ repo_id: str+ repo_type: str = "model"+ revisions: tuple = ()+++def _repo(repo_id):+ return Repo(repo_id)+++def test_managed_previews_see_only_visible_repos(monkeypatch):+ mine, theirs = _repo("alice/base"), _repo("bob/private-base")+ scans = [Scan(repos = frozenset({mine, theirs}))]+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: scans)+ monkeypatch.setattr(+ access,+ "filter_model_rows",+ lambda rows, **_: [row for row in rows if row.repo_id.startswith("alice/")],+ )+ assert run_as(OWNER, companion_cleanup._account_scans) is scans+ filtered = run_as(ALICE, companion_cleanup._account_scans)+ assert [scan.repos for scan in filtered] == [frozenset({mine})]+ assert set(companion_cleanup._repos_by_id(filtered)) == {"alice/base"}diff --git a/studio/backend/tests/multi_account/test_cross_platform_paths.py b/studio/backend/tests/multi_account/test_cross_platform_paths.pynew file mode 100644index 00000000000..2c624e0878a--- /dev/null+++ b/studio/backend/tests/multi_account/test_cross_platform_paths.py@@ -0,0 +1,104 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Lexical Windows checks; these do not claim to run Windows ACL or filesystem semantics."""++import ntpath+import re+import unicodedata+import uuid+from pathlib import PureWindowsPath++import pytest++from utils.account_context import AccountContext, OWNER, run_as+from utils.paths import storage_roots++ACCOUNT_ID = "0123456789abcdef0123456789abcdef"+ROOT = PureWindowsPath(r"C:\Users\Research Engineer\AppData\Local\UnslothStudio")+RESERVED = {+ "CON",+ "PRN",+ "AUX",+ "NUL",+ *(f"COM{i}" for i in range(1, 10)),+ *(f"LPT{i}" for i in range(1, 10)),+}+LEAVES = (+ r"studio.db",+ r"outputs\Llama-3.1-8B-Instruct\checkpoint-10000\adapter_model.safetensors",+ r"exports\Llama-3.1-8B-Instruct-Q4_K_M.gguf",+ r"rag\documents\0123456789abcdef0123456789abcdef\quarterly-research-report.pdf",+ r"sandbox\0123456789abcdef0123456789abcdef\workspace\analysis\results.csv",+ r"assets\datasets\0123456789abcdef0123456789abcdef\training-data.jsonl",+)+++def utf16_units(path: str) -> int:+ return len(path.encode("utf-16-le")) // 2+++ "username",+ sorted(RESERVED)+ + [+ "CON.txt",+ "aux.",+ "..",+ "alice/bob",+ "alice\\bob",+ "Élodie",+ "E\u0301lodie",+ "Alice",+ "ALICE",+ "alice",+ ],+)+def test_username_never_becomes_a_windows_storage_component(monkeypatch, username):+ monkeypatch.setattr(storage_roots, "studio_root", lambda: ROOT)+ account = AccountContext(ACCOUNT_ID, username)+ actual = str(run_as(account, storage_roots.workspace_root))+ expected = ntpath.join(str(ROOT), "accounts", ACCOUNT_ID)+ assert actual == expected+ assert ntpath.commonpath([str(ROOT), actual]) == str(ROOT)+ assert re.fullmatch(r"[0-9a-f]{32}", ntpath.basename(actual))+ assert ntpath.basename(actual).upper() not in RESERVED+ for form in ("NFC", "NFD"):+ assert unicodedata.normalize(form, actual) == expected+++def test_owner_windows_layout_is_unchanged(monkeypatch):+ monkeypatch.setattr(storage_roots, "studio_root", lambda: ROOT)+ assert run_as(OWNER, storage_roots.workspace_root) == ROOT+ assert run_as(OWNER, storage_roots.studio_db_path) == ROOT / "studio.db"+++def test_distinct_generated_account_ids_do_not_collide_under_case_folding(isolated_auth):+ ids = []+ for username in ("alice", "ALICE", "café", "cafe\u0301", "CON"):+ isolated_auth.create_initial_user(username, "account-password", uuid.uuid4().hex)+ account_id = isolated_auth.get_account(username).account_id+ assert uuid.UUID(hex = account_id).version == 4+ ids.append(account_id)+ assert len({ntpath.normcase(ntpath.join("accounts", value)) for value in ids}) == len(ids)++[email protected]("leaf", LEAVES)+def test_max_path_budget_for_realistic_leaves(leaf):+ owner_path = ntpath.join(str(ROOT), leaf)+ account_path = ntpath.join(str(ROOT), "accounts", ACCOUNT_ID, leaf)+ # MAX_PATH includes the trailing NUL. The fixed accounts/hex component adds 42 UTF-16 units.+ assert utf16_units(account_path) - utf16_units(owner_path) == 42+ assert utf16_units(account_path) + 1 <= 260+ budget = 259 - utf16_units(ntpath.join("accounts", ACCOUNT_ID, leaf)) - 1+ assert utf16_units(str(ROOT)) <= budget+ at_limit = ntpath.join("C:\\" + "x" * (budget - 3), "accounts", ACCOUNT_ID, leaf)+ assert utf16_units(at_limit) == 259+ assert utf16_units(at_limit + "x") + 1 > 260+++def test_path_budget_counts_utf16_units_not_unicode_code_points():+ assert utf16_units("📁") == 2+ assert utf16_units("é") == 1+ assert utf16_units("e\u0301") == 2+ assert utf16_units(ACCOUNT_ID) == 32diff --git a/studio/backend/tests/multi_account/test_deactivation_cancels_loads.py b/studio/backend/tests/multi_account/test_deactivation_cancels_loads.pynew file mode 100644index 00000000000..871bb043a1d--- /dev/null+++ b/studio/backend/tests/multi_account/test_deactivation_cancels_loads.py@@ -0,0 +1,46 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Disabling an account cancels its chat loads and fences the ones still in preflight."""++import threading+import uuid++import pytest+from fastapi import HTTPException++from auth import storage+from hub.services.models import account_access as access+from routes import inference+from studio.backend.tests.test_account_lifecycle import auth_env, headers, matrix # noqa: F401+from utils.account_context import run_as+++def _attempt(subject):+ return inference._ScopedLoadAttempt(+ token = uuid.uuid4().hex,+ request_id = None,+ model_path = "org/model",+ subject = subject,+ cancel_event = threading.Event(),+ cancel_complete = threading.Event(),+ )+++def test_deactivation_sweeps_loads_and_fences_late_ones(matrix, monkeypatch):+ client, _, _ = matrix+ alice, bob = storage.get_account("alice"), storage.get_account("bob")+ pending, other = _attempt(alice.account_id), _attempt(bob.account_id)+ monkeypatch.setattr(inference, "_pending_load_attempts", {a.token: a for a in (pending, other)})+ monkeypatch.setattr(inference, "_scoped_load_attempts", {})+ monkeypatch.setattr(inference, "_running_load_attempt", None)+ run_as(alice, access.require_live_account)+ url = f"/api/accounts/{alice.account_id}"+ assert client.patch(url, headers = headers(), json = {"is_active": False}).status_code == 200+ assert pending.cancel_event.is_set() and not other.cancel_event.is_set()+ with pytest.raises(HTTPException) as exc:+ run_as(alice, access.require_live_account)+ assert (exc.value.status_code, exc.value.detail) == (403, "Account is disabled")+ run_as(bob, access.require_live_account)+ assert client.patch(url, headers = headers(), json = {"is_active": True}).status_code == 200+ run_as(alice, access.require_live_account)diff --git a/studio/backend/tests/multi_account/test_downgrade_sim.py b/studio/backend/tests/multi_account/test_downgrade_sim.pynew file mode 100644index 00000000000..be652908366--- /dev/null+++ b/studio/backend/tests/multi_account/test_downgrade_sim.py@@ -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++"""Old named-column readers ignore new identity/setup columns: owner data compatibility only, not safe multi-account service by an old build."""++import sqlite3+from contextlib import closing++from auth import policy+from utils.account_context import run_as+from utils.paths import workspace_root++from .seed import OLD_AUTH_COLUMNS, SENTINEL, THREAD_ID, old_auth_row, seed_legacy_install+++def test_old_named_column_reads_and_owner_password_write_remain_valid(isolated_auth):+ home = isolated_auth.DB_PATH.parent.parent+ original = seed_legacy_install(home)+ before = old_auth_row(isolated_auth.DB_PATH)+ assert isolated_auth.get_account("unsloth").account_id == "owner"+ isolated_auth.create_initial_user("alice", "alice-password", "alice-jwt-secret" * 3)+ alice = isolated_auth.get_account("alice")+ managed = run_as(alice, workspace_root) / "outputs" / "adapter.bin"+ managed.parent.mkdir(parents = True)+ managed.write_bytes(b"private-alice-model")+ with closing(sqlite3.connect(isolated_auth.DB_PATH)) as conn:+ columns = {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}+ assert set(OLD_AUTH_COLUMNS) < columns+ assert {"account_id", "is_active", "setup_code_hash", "setup_code_expires_at"} <= columns+ conn.execute(+ "UPDATE auth_user SET password_salt=?, password_hash=?, jwt_secret=?, "+ "must_change_password=0 WHERE username=?",+ ("old-reset-salt", "old-reset-hash", "old-reset-secret", "unsloth"),+ )+ conn.commit()+ after = old_auth_row(isolated_auth.DB_PATH)+ assert after[:2] == before[:2]+ assert after[2:5] == ("old-reset-salt", "old-reset-hash", "old-reset-secret")+ assert isolated_auth.get_account("alice") == alice+ assert isolated_auth.get_user_record("alice")["jwt_secret"] == "alice-jwt-secret" * 3+ with closing(sqlite3.connect(home / "studio.db")) as conn:+ assert conn.execute(+ "SELECT title FROM chat_threads WHERE id=?", (THREAD_ID,)+ ).fetchone() == (SENTINEL,)+ assert conn.execute(+ "SELECT value_json FROM chat_settings WHERE key='theme'"+ ).fetchone() == ('"dark"',)+ assert (home / "studio.db").read_bytes() == original["studio.db"]+ assert managed.read_bytes() == b"private-alice-model"+ assert policy.login_mode() == "multi"+++def test_old_auth_read_ignores_deactivation_explicitly(isolated_auth, accounts):+ with closing(sqlite3.connect(isolated_auth.DB_PATH)) as conn:+ conn.execute("UPDATE auth_user SET is_active=0 WHERE username='alice'")+ conn.commit()+ legacy = conn.execute(+ "SELECT password_salt,password_hash,jwt_secret,must_change_password "+ "FROM auth_user WHERE username=?",+ ("alice",),+ ).fetchone()+ assert legacy is not None+ assert isolated_auth.get_user_record("alice")["is_active"] == 0diff --git a/studio/backend/tests/multi_account/test_export_adapter_base.py b/studio/backend/tests/multi_account/test_export_adapter_base.pynew file mode 100644index 00000000000..161f2f01a0a--- /dev/null+++ b/studio/backend/tests/multi_account/test_export_adapter_base.py@@ -0,0 +1,52 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An export load authorizes the adapter's base with the caller's account and pins it for the worker."""++import json++import pytest+from fastapi import HTTPException++from routes import export as route+from utils.account_context import AccountContext, OWNER, run_as+from utils.paths import outputs_root++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def _adapter(account, name, base):+ path = run_as(account, lambda: outputs_root() / name)+ path.mkdir(parents = True, exist_ok = True)+ (path / "adapter_config.json").write_text(+ json.dumps({"peft_type": "LORA", "base_model_name_or_path": base})+ )+ return path+++def test_foreign_adapter_base_is_refused(isolated_auth):+ foreign = run_as(BOB, lambda: outputs_root() / "base")+ foreign.mkdir(parents = True)+ adapter = _adapter(ALICE, "adapter", str(foreign))+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, route._authorized_adapter_base, str(adapter))+ assert exc.value.status_code == 404+++def test_own_adapter_base_is_pinned_into_the_worker_config(isolated_auth, monkeypatch):+ from core.export.orchestrator import ExportOrchestrator++ own = run_as(ALICE, lambda: outputs_root() / "base")+ own.mkdir(parents = True)+ adapter = _adapter(ALICE, "adapter", str(own))+ assert run_as(ALICE, route._authorized_adapter_base, str(adapter)) == str(own)+ assert run_as(OWNER, route._authorized_adapter_base, str(adapter)) is None++ backend = ExportOrchestrator()+ configs = []+ monkeypatch.setattr(backend, "_spawn_subprocess", configs.append)+ monkeypatch.setattr(backend, "_wait_response", lambda *a, **k: {"success": True, "message": ""})+ monkeypatch.setattr(backend, "_ensure_subprocess_alive", lambda: False)+ run_as(ALICE, backend.load_checkpoint, str(adapter), base_model = str(own))+ assert configs[0]["base_model"] == str(own)diff --git a/studio/backend/tests/multi_account/test_hot_path_cost.py b/studio/backend/tests/multi_account/test_hot_path_cost.pynew file mode 100644index 00000000000..2e60a264ce6--- /dev/null+++ b/studio/backend/tests/multi_account/test_hot_path_cost.py@@ -0,0 +1,51 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Compare actual warm-path I/O against pre-contract code in an isolated process."""++import shutil+import uuid++import pytest++from .perf_utils import REPO, SCRATCH, baseline_ref, materialize_revision, run_probe++[email protected](scope = "module")+def measured_costs():+ ref = baseline_ref()+ if ref is None:+ pytest.skip("no pre-account baseline commit is reachable from this clone")+ scratch = SCRATCH / uuid.uuid4().hex+ scratch.mkdir(parents = True)+ try:+ baseline = materialize_revision(ref, scratch / "baseline")+ yield (+ run_probe(baseline, scratch / "baseline-home", mode = "cost"),+ run_probe(REPO / "studio/backend", scratch / "head-home", mode = "cost"),+ )+ finally:+ shutil.rmtree(scratch, ignore_errors = True)+++ "operation,connections,queries,mkdir_calls",+ [+ ("status", 3, 3, 3),+ ("authenticated_get", 1, 1, 1),+ ("workspace_1000", 0, 0, 0),+ ],+)+def test_one_account_adds_no_hot_path_io(+ measured_costs, operation, connections, queries, mkdir_calls+):+ baseline, head = measured_costs+ measured = baseline[operation]+ assert measured["connections"] == connections+ assert measured["queries"] == queries+ assert measured["mkdir_calls"] == mkdir_calls+ assert measured["directories_created"] == 0+ # The auth schema setup is cached per file, so head may run fewer statements, never more.+ assert head[operation]["statements"] <= measured["statements"]+ compare = {key: value for key, value in measured.items() if key != "statements"}+ assert {key: head[operation][key] for key in compare} == comparediff --git a/studio/backend/tests/multi_account/test_legacy_upgrade_sim.py b/studio/backend/tests/multi_account/test_legacy_upgrade_sim.pynew file mode 100644index 00000000000..6912a6edde2--- /dev/null+++ b/studio/backend/tests/multi_account/test_legacy_upgrade_sim.py@@ -0,0 +1,29 @@+# 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 json+import os+import subprocess+import sys+from pathlib import Path+++def test_populated_legacy_install_survives_app_import_and_owner_reads(tmp_path):+ backend = Path(__file__).resolve().parents[2]+ env = dict(os.environ)+ env.update(+ UNSLOTH_STUDIO_HOME = str(tmp_path / "legacy-install"),+ UNSLOTH_STUDIO_DOCUMENTS_HOME = str(tmp_path / "Documents"),+ PYTHONPATH = str(backend),+ PYTHONDONTWRITEBYTECODE = "1",+ )+ result = subprocess.run(+ [sys.executable, "-m", "tests.multi_account.legacy_probe"],+ cwd = backend,+ env = env,+ capture_output = True,+ text = True,+ timeout = 120,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert json.loads(result.stdout.splitlines()[-1]) == {"preserved_files": 7, "owner_login": True}diff --git a/studio/backend/tests/multi_account/test_login_mode_transitions.py b/studio/backend/tests/multi_account/test_login_mode_transitions.pynew file mode 100644index 00000000000..a1223b91b9c--- /dev/null+++ b/studio/backend/tests/multi_account/test_login_mode_transitions.py@@ -0,0 +1,145 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++from __future__ import annotations+import sqlite3+import threading+from concurrent.futures import ThreadPoolExecutor+from contextlib import closing++import pytest++from auth import policy+++def status(+ client,+ *,+ count: int,+ full_access: bool | None = None,+) -> None:+ response = client.get("/api/auth/status")+ assert response.status_code == 200+ body = response.json()+ assert set(body) == {+ "initialized",+ "default_username",+ "requires_password_change",+ "bootstrap_deadline_seconds",+ "login_mode",+ "full_access",+ }+ assert body["initialized"] == (count > 0)+ assert body["default_username"] == "unsloth"+ assert body["login_mode"] == ("multi" if count > 1 else "single")+ assert "alice" not in response.text and "bob" not in response.text+ # Full access needs the install to itself: no managed account, active or not.+ if full_access is None:+ full_access = count <= 1+ assert policy.full_access_permitted() == full_access+ assert body["full_access"] == full_access+++def test_zero_one_two_back_to_one_and_zero(isolated_auth, account_client):+ status(account_client, count = 0)+ isolated_auth.create_initial_user("unsloth", "owner-password", "owner-secret" * 4)+ status(account_client, count = 1)+ isolated_auth.create_initial_user("alice", "alice-password", "alice-secret" * 4)+ status(account_client, count = 2)+ isolated_auth.delete_user("alice")+ status(account_client, count = 1)+ isolated_auth.delete_user("unsloth")+ status(account_client, count = 0)+++def test_activation_changes_mode_when_mutator_invalidates_cache(isolated_auth, account_client):+ for username in ("unsloth", "alice"):+ isolated_auth.create_initial_user(username, "account-password", username * 12)+ status(account_client, count = 2)+ for active, count in ((0, 1), (1, 2)):+ with closing(sqlite3.connect(isolated_auth.DB_PATH)) as conn:+ conn.execute("UPDATE auth_user SET is_active=? WHERE username='alice'", (active,))+ conn.commit()+ policy.invalidate_account_cache()+ status(account_client, count = count, full_access = False)+++def test_concurrent_creation_refreshes_a_warm_single_mode(isolated_auth, account_client):+ isolated_auth.create_initial_user("unsloth", "owner-password", "owner-secret" * 4)+ status(account_client, count = 1)+ barrier = threading.Barrier(3)++ def create(username):+ barrier.wait(timeout = 10)+ isolated_auth.create_initial_user(username, "account-password", username * 12)++ with ThreadPoolExecutor(max_workers = 2) as pool:+ futures = [pool.submit(create, username) for username in ("alice", "bob")]+ barrier.wait(timeout = 10)+ for future in futures:+ future.result(timeout = 30)+ assert isolated_auth.count_active_accounts() == 3+ assert (+ len({isolated_auth.get_account(name).account_id for name in ("unsloth", "alice", "bob")})+ == 3+ )+ status(account_client, count = 3)+++def test_duplicate_concurrent_creation_has_one_winner(isolated_auth):+ isolated_auth.create_initial_user("unsloth", "owner-password", "owner-secret" * 4)+ assert policy.login_mode() == "single"+ barrier = threading.Barrier(2)++ def create():+ barrier.wait(timeout = 10)+ try:+ isolated_auth.create_initial_user("alice", "alice-password", "alice-secret" * 4)+ return "created"+ except sqlite3.IntegrityError:+ return "duplicate"++ with ThreadPoolExecutor(max_workers = 2) as pool:+ results = list(pool.map(lambda _: create(), range(2)))+ assert sorted(results) == ["created", "duplicate"]+ assert isolated_auth.count_active_accounts() == 2+ assert policy.login_mode() == "multi"+++def test_invalidation_racing_a_stale_count_does_not_poison_cache(isolated_auth, monkeypatch):+ isolated_auth.create_initial_user("unsloth", "owner-password", "owner-secret" * 4)+ entered, release = threading.Event(), threading.Event()+ real_counts = isolated_auth.account_counts++ def delayed_count():+ counts = real_counts()+ entered.set()+ assert release.wait(10)+ return counts++ monkeypatch.setattr(isolated_auth, "account_counts", delayed_count)+ with ThreadPoolExecutor(max_workers = 1) as pool:+ pending = pool.submit(policy.login_mode)+ try:+ assert entered.wait(10)+ isolated_auth.create_initial_user("alice", "alice-password", "alice-secret" * 4)+ finally:+ release.set()+ assert pending.result(timeout = 10) == "single"+ monkeypatch.setattr(isolated_auth, "account_counts", real_counts)+ assert policy.login_mode() == "multi"+++def test_deactivated_account_cannot_keep_using_a_previously_issued_api_key(+ isolated_auth, accounts, account_client+):+ raw_key, _ = isolated_auth.create_api_key("alice", name = "before-deactivation")+ headers = {"Authorization": f"Bearer {raw_key}"}+ assert account_client.get("/account-probe", headers = headers).status_code == 200+ with closing(sqlite3.connect(isolated_auth.DB_PATH)) as conn:+ conn.execute("UPDATE auth_user SET is_active=0 WHERE username='alice'")+ conn.commit()+ policy.invalidate_account_cache()+ response = account_client.get("/account-probe", headers = headers)+ assert response.status_code == 401, response.textdiff --git a/studio/backend/tests/multi_account/test_media_unload_handoff.py b/studio/backend/tests/multi_account/test_media_unload_handoff.pynew file mode 100644index 00000000000..ed2b2b9054e--- /dev/null+++ b/studio/backend/tests/multi_account/test_media_unload_handoff.py@@ -0,0 +1,245 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CPU reproduction: an authorized image unload cancels a later foreign generation."""++import sys+import secrets+import threading+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "studio/backend"))++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import get_current_subject+from core.inference import diffusion_engine_router, gpu_arbiter+from core.inference.diffusion import DiffusionBackend+from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG+from hub.services.models import account_access as access+from routes import inference, video+from state import active_generations+from utils.account_context import bind_account, reset_account+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.studio_router, prefix = "/api/inference")+ app.include_router(video.router, prefix = "/api/inference")+ return TestClient(app)++[email protected]("unloader", ["alice", "unsloth"])+def test_unload_does_not_cancel_foreign_generation_started_after_route_check(+ monkeypatch, accounts, unloader+):+ """Real HTTP handlers and DiffusionBackend slot/teardown; no model or GPU required."""+ backend = DiffusionBackend()+ arrived, proceed, generating, finish = (threading.Event() for _ in range(4))+ cancel = threading.Event()+ responses = {}+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ for name in ("_resident_accounts", "_generation_accounts", "_generation_holders"):+ monkeypatch.setattr(access, name, {})+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.DIFFUSION)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", accounts[unloader].account_id)+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ # Replace only the model-dependent surface; reservation, cancellation and teardown are real.+ monkeypatch.setattr(+ backend,+ "status",+ lambda: {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ },+ )++ def generate(**kwargs):+ with backend._generation_slot(cancel):+ generating.set()+ while not finish.is_set() and not cancel.wait(0.01):+ pass+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)++ real_unload = backend.unload++ def paused_unload(*args, **kwargs):+ arrived.set()+ assert proceed.wait(10), "unload barrier timed out"+ return real_unload(*args, **kwargs)++ monkeypatch.setattr(backend, "generate", generate)+ monkeypatch.setattr(backend, "unload", paused_unload)++ def post(+ account,+ key,+ path,+ body = None,+ ):+ with client_for(account) as client:+ responses[key] = client.post("/api/inference/" + path, json = body)++ unload_thread = threading.Thread(+ target = post, args = (accounts[unloader], "unload", "images/unload")+ )+ generate_thread = threading.Thread(+ target = post,+ args = (accounts["bob"], "generate", "images/generate", {"prompt": "Bob's private prompt"}),+ )+ active_generations.reset_for_tests()+ try:+ assert policy.installation_has_managed_accounts()+ unload_thread.start()+ assert arrived.wait(10), "unload did not pass route ownership checks"+ generate_thread.start()+ assert generating.wait(10), "Bob never took the real generation slot"+ proceed.set()+ unload_thread.join(10)+ assert not unload_thread.is_alive()+ response = responses["unload"]+ assert not cancel.is_set(), f"{unloader}'s unload cancelled Bob's generation: HTTP {response.status_code} {response.text}"+ assert response.status_code == 409+ assert response.json()["error"] == "gpu_busy"+ assert int(response.headers["retry-after"]) > 0+ finally:+ proceed.set()+ finish.set()+ for thread in (unload_thread, generate_thread):+ if thread.ident is not None:+ thread.join(10)+ active_generations.reset_for_tests()+++def test_video_unload_does_not_cancel_later_foreign_reservation(monkeypatch, accounts):+ from core.inference import video as video_module++ backend = video_module.VideoBackend()+ arrived, proceed, generating, finish = (threading.Event() for _ in range(4))+ render_done = threading.Event()+ results = {}+ family = SimpleNamespace(+ name = "wan", default_fps = 24, default_num_frames = 49, frame_step = 4, frame_offset = 1+ )+ backend._state = SimpleNamespace(+ family = family, h3_task = None, engine = "diffusers", repo_id = "org/public-video"+ )+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+ monkeypatch.setattr(video_module, "validate_video_request_shape", lambda *a, **k: None)+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", accounts["alice"].account_id)+ for name in ("_resident_accounts", "_generation_accounts", "_generation_holders"):+ monkeypatch.setattr(access, name, {})+ monkeypatch.setattr(backend, "status", lambda: {"loaded": True, "repo_id": "org/public-video"})+ monkeypatch.setattr(backend, "generation_snapshot", lambda: (backend.status(), backend._state))+ monkeypatch.setattr(+ backend, "_resolve_keyframes", lambda *a, **k: (None, None, 512, 512, "t2v")+ )+ monkeypatch.setattr(backend, "_resolve_references", lambda *a, **k: None)+ monkeypatch.setattr(backend, "_resolve_flow_shifts", lambda *a, **k: (None, None))+ monkeypatch.setattr(backend, "_teardown_state_locked", lambda: None)++ def render(**kwargs):+ try:+ with backend._generate_lock:+ generating.set()+ while not finish.is_set() and not backend._active_generate_cancel.wait(0.01):+ pass+ finally:+ render_done.set()++ monkeypatch.setattr(backend, "_run_generate", render)+ real_unload = backend.unload++ def paused_unload(*args, **kwargs):+ arrived.set()+ assert proceed.wait(10)+ return real_unload(*args, **kwargs)++ monkeypatch.setattr(backend, "unload", paused_unload)++ def unload():+ with client_for(accounts["alice"]) as client:+ results["unload"] = client.post("/api/inference/video/unload")++ thread = threading.Thread(target = unload)+ thread.start()+ try:+ assert arrived.wait(10)+ with client_for(accounts["bob"]) as client:+ response = client.post(+ "/api/inference/video/generate", json = {"prompt": "private", "steps": 5}+ )+ assert response.status_code == 200, response.text+ assert generating.wait(10)+ assert backend.generate_job_account() == accounts["bob"].account_id+ cancel = backend._active_generate_cancel+ proceed.set()+ thread.join(10)+ assert not thread.is_alive()+ assert (+ not cancel.is_set()+ ), f"Alice's unload cancelled Bob's video: HTTP {results['unload'].status_code}"+ assert results["unload"].status_code == 409+ assert results["unload"].json()["error"] == "gpu_busy"+ finally:+ finish.set()+ proceed.set()+ thread.join(10)+ if generating.is_set():+ assert render_done.wait(10)++[email protected]("kind", ["diffusers", "sd_cpp", "video"])[email protected]("managed", [False, True], ids = ["single-user", "managed-install"])+def test_own_unload_still_cancels_and_returns_200(monkeypatch, isolated_auth, kind, managed):+ """The new foreign guard must preserve intentional cancellation of one's own work."""+ from core.inference import video as video_module+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend++ isolated_auth.create_initial_user("unsloth", "password", secrets.token_urlsafe(32))+ if managed:+ for name in ("alice", "bob"):+ isolated_auth.create_initial_user(name, "password", secrets.token_urlsafe(32))+ owner = isolated_auth.get_account("unsloth")+ assert policy.installation_has_managed_accounts() is managed+ backend = {+ "diffusers": DiffusionBackend,+ "sd_cpp": SdCppDiffusionBackend,+ "video": video_module.VideoBackend,+ }[kind]()+ cancel = threading.Event()+ backend._active_generate_cancel = cancel+ if kind == "video":+ backend._generate_job_account = owner.account_id+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+ path = "video/unload"+ else:+ backend._active_generate_account = owner.account_id+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ path = "images/unload"+ monkeypatch.setattr(gpu_arbiter, "_owner", "video" if kind == "video" else "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", owner.account_id)+ for name in ("_resident_accounts", "_generation_accounts", "_generation_holders"):+ monkeypatch.setattr(access, name, {})+ with client_for(owner) as client:+ response = client.post("/api/inference/" + path)+ assert response.status_code == 200, response.text+ assert response.json()["loaded"] is False+ assert cancel.is_set()diff --git a/studio/backend/tests/multi_account/test_perf_gate.py b/studio/backend/tests/multi_account/test_perf_gate.pynew file mode 100644index 00000000000..079ec888c94--- /dev/null+++ b/studio/backend/tests/multi_account/test_perf_gate.py@@ -0,0 +1,68 @@+# 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 copy+import importlib.util+import os+import sqlite3+from contextlib import closing++import pytest++from .perf_utils import PROBE+++def load_script(name):+ path = PROBE.with_name(name + ".py")+ spec = importlib.util.spec_from_file_location("account_perf_" + name, path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++ "endpoint,metric",+ [+ ("status", "p50_ms"),+ ("status", "p95_ms"),+ ("history", "p50_ms"),+ ("history", "p95_ms"),+ ],+)+def test_gate_rejects_each_percentile_above_five_percent(endpoint, metric):+ module = load_script("compare")+ baseline = {name: {"p50_ms": 10.0, "p95_ms": 20.0} for name in ("status", "history")}+ results = {"base": baseline, "head": copy.deepcopy(baseline)}+ results["head"][endpoint][metric] = baseline[endpoint][metric] * 1.05+ assert module.regressions(results) == []+ results["head"][endpoint][metric] += 0.0001+ assert len(module.regressions(results)) == 1+++def test_percentiles_use_all_samples():+ module = load_script("probe")+ assert module.summarize(list(range(1, 101))) == {"samples": 100, "p50_ms": 50.5, "p95_ms": 95}+++def test_io_counter_observes_real_connections_queries_and_mkdirs(tmp_path):+ module = load_script("probe")++ def extra_work():+ os.mkdir(tmp_path / "new-directory")+ with closing(sqlite3.connect(tmp_path / "extra.db")) as conn:+ assert conn.execute("SELECT 1").fetchone() == (1,)++ assert module.measure_cost(extra_work) == {+ "connections": 1,+ "queries": 1,+ "statements": 1,+ "mkdir_calls": 1,+ "directories_created": 1,+ }+++def test_io_counter_distinguishes_existing_directory_attempts(tmp_path):+ module = load_script("probe")+ result = module.measure_cost(lambda: tmp_path.mkdir(exist_ok = True))+ assert result["mkdir_calls"] == 1+ assert result["directories_created"] == 0diff --git a/studio/backend/tests/multi_account/test_routing_invariance.py b/studio/backend/tests/multi_account/test_routing_invariance.pynew file mode 100644index 00000000000..75023f2809d--- /dev/null+++ b/studio/backend/tests/multi_account/test_routing_invariance.py@@ -0,0 +1,104 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Per-request I/O never depends on how many accounts exist, and the owner's routing is fixed."""++import os+import secrets+import sqlite3+from collections import Counter+from unittest.mock import patch++from auth import policy, storage+from core.inference.llama_admission import get_llama_admission_queue+from hub.services.models import account_access as access+from state import active_generations+from utils.account_context import OWNER, AccountContext, run_as++from .support import bearer++PATHS = ("/api/auth/status", "/account-probe", "/api/chat/threads")+++def _create(names):+ for name in names:+ storage.create_initial_user(name, "account-password", secrets.token_urlsafe(32))+ policy.invalidate_account_cache()+++def _vector(client, headers, path) -> dict:+ """sqlite connections, statements, mkdirs and auth.db count queries for one warm request."""+ counters = Counter()+ connect, mkdir, count = sqlite3.connect, os.mkdir, storage.account_counts++ def open_connection(*args, **kwargs):+ counters["connections"] += 1+ conn = connect(*args, **kwargs)+ conn.set_trace_callback(+ lambda _: counters.__setitem__("statements", counters["statements"] + 1)+ )+ return conn++ def create_directory(*args, **kwargs):+ counters["mkdir"] += 1+ return mkdir(*args, **kwargs)++ def counted(*args, **kwargs):+ counters["account_counts"] += 1+ return count(*args, **kwargs)++ for _ in range(2):+ assert client.get(path, headers = headers).status_code == 200+ with (+ patch.object(sqlite3, "connect", open_connection),+ patch.object(os, "mkdir", create_directory),+ patch.object(storage, "account_counts", counted),+ ):+ assert client.get(path, headers = headers).status_code == 200+ return dict(counters)+++def _vectors(client, username):+ headers = bearer(username)+ return {path: _vector(client, headers, path) for path in PATHS}+++def test_owner_requests_cost_the_same_with_zero_and_many_accounts(isolated_auth, account_client):+ _create(["unsloth"])+ alone = _vectors(account_client, "unsloth")+ _create([f"user{index:02d}" for index in range(12)])+ crowded = _vectors(account_client, "unsloth")+ assert alone["/account-probe"]["connections"] >= 1, "the counters must observe the auth lookup"+ assert crowded == alone+ assert all(vector.get("account_counts", 0) == 0 for vector in alone.values())+++def test_managed_requests_do_not_grow_with_account_count(isolated_auth, account_client):+ _create(["unsloth", "alice"])+ few = _vectors(account_client, "alice")+ _create([f"user{index:02d}" for index in range(12)])+ assert _vectors(account_client, "alice") == few+ assert all(vector.get("account_counts", 0) == 0 for vector in few.values())+++def test_owner_routing_facts_and_shared_queue(isolated_auth, account_client):+ _create(["unsloth"])+ headers = bearer("unsloth")+ for path in PATHS:+ assert account_client.get(path, headers = headers).status_code == 200+ assert run_as(OWNER, access.account_scope) is None+ assert run_as(OWNER, access.resident_hidden, "chat") is False+ assert access._resident_sharers == {}+ assert active_generations._FENCED == set()++ _create(["alice"])+ alice = storage.get_account("alice")+ managed = AccountContext(alice.account_id, alice.username, alice.role)+ assert run_as(OWNER, access.account_scope) == "owner"+ assert run_as(managed, access.account_scope) == alice.account_id+ assert run_as(OWNER, access.resident_hidden, "chat") is False+ # Admission queues are keyed by the resident server, never by the calling account.+ key = "http://127.0.0.1:1"+ assert run_as(OWNER, get_llama_admission_queue, key) is run_as(+ managed, get_llama_admission_queue, key+ )diff --git a/studio/backend/tests/test_account_auto_download_busy_message.py b/studio/backend/tests/test_account_auto_download_busy_message.pynew file mode 100644index 00000000000..542482e3ac6--- /dev/null+++ b/studio/backend/tests/test_account_auto_download_busy_message.py@@ -0,0 +1,50 @@+# 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 single-flight auto-download slot names its repo and quant only to the account that started it."""++import asyncio+import time++import pytest++from core.inference import openai_auto_download as auto+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+PRIVATE = "alice/private-checkpoint-GGUF"+++def alice_downloading(monkeypatch):+ monkeypatch.setattr(+ auto,+ "_active",+ auto._Active(+ repo_id = PRIVATE, variant = "Q4_K_M", started_at = time.time(), account_id = ALICE.account_id+ ),+ )++ async def downloadable(repo_id, hf_token):+ return True++ monkeypatch.setattr(auto, "_is_downloadable_model", downloadable)+ monkeypatch.setattr(auto, "_is_not_servable", lambda repo_id, hf_token: False)+++def _refusal(account):+ return run_as(account, lambda: asyncio.run(auto.maybe_auto_download("bob/public-GGUF:Q4_K_M")))+++def test_another_account_gets_a_generic_busy_answer(alice_downloading):+ refusal = _refusal(BOB)+ print(f"bob sees: {refusal.message}")+ assert refusal is not None and refusal.code == "model_download_busy"+ assert "alice" not in refusal.message and "Q4_K_M'" not in refusal.message.split("Retry")[0]+ assert "bob/public-GGUF:Q4_K_M" in refusal.message+++def test_the_downloading_account_still_sees_its_own_repo(alice_downloading):+ refusal = _refusal(ALICE)+ assert refusal is not None and PRIVATE in refusal.messagediff --git a/studio/backend/tests/test_account_auto_download_token.py b/studio/backend/tests/test_account_auto_download_token.pynew file mode 100644index 00000000000..e32c5e13db7--- /dev/null+++ b/studio/backend/tests/test_account_auto_download_token.py@@ -0,0 +1,144 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import authentication, policy+from core.inference import llama_keepwarm, local_model_resolver+from hub.services.models import account_access as access+from routes import inference, models+from utils import openai_auto_switch_settings+from utils.account_context import OWNER, AccountContext, arun_as++ALICE = AccountContext("a" * 32, "alice")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(inference, "_managed_catalogs", {})+ monkeypatch.setattr(inference, "_CATALOG_CACHE", {"at": 0.0, "models": []})+ monkeypatch.setattr(inference, "_ADVERTISED_CACHE", {"at": None, "paths": {}})+ # A first-time private repo is not public to an anonymous probe.+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: False)+ yield+++def _request():+ return SimpleNamespace(+ headers = {"X-Unsloth-HF-Token": "alice-token"},+ scope = {},+ state = SimpleNamespace(),+ url = SimpleNamespace(path = "/v1/chat/completions"),+ )+++def downloads(monkeypatch):+ """Uncached, unresolvable private repo; record whether auto-download is reached."""+ monkeypatch.setattr(openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: True)+ monkeypatch.setattr(+ openai_auto_switch_settings, "get_openai_auto_download_enabled", lambda: True+ )+ monkeypatch.setattr(openai_auto_switch_settings, "idle_unload_is_configured", lambda: False)++ # The Hub answers this private repo only for the caller's own token.+ class _Hub:+ def repo_info(+ self,+ repo_id,+ repo_type = "model",+ token = None,+ timeout = None,+ ):+ if token != "alice-token":+ raise RuntimeError("401")+ return SimpleNamespace(private = True, gated = False)++ monkeypatch.setattr(access, "HfApi", _Hub)+ monkeypatch.setattr(inference, "_loaded_identity_satisfies", lambda *a, **k: False)+ monkeypatch.setattr(inference, "_claim_slot_for_non_preview", lambda *a, **k: None)+ monkeypatch.setattr(+ local_model_resolver, "resolve_trusted_cached_local_gguf", lambda *a, **k: None+ )+ monkeypatch.setattr(local_model_resolver, "resolve_local_gguf", lambda *a, **k: None)+ monkeypatch.setattr(llama_keepwarm, "get_last_unloaded_model", lambda: None)+ monkeypatch.setattr(+ authentication, "request_admitted_without_credential", lambda *a, **k: False+ )+ monkeypatch.setattr(inference, "_classified_catalog", lambda rows: rows)+ monkeypatch.setattr(models, "collect_local_models", lambda path: [])+ seen = []++ async def record(requested_model, fastapi_request, **kwargs):+ seen.append((requested_model, inference._auto_download_hf_token(fastapi_request)))++ monkeypatch.setattr(inference, "_maybe_auto_download_model", record)+ return seen+++def test_the_owner_reaches_auto_download_for_an_uncached_private_repo(downloads):+ asyncio.run(+ arun_as(OWNER, inference._maybe_auto_switch_model("org/private", _request(), "owner"))+ )+ assert downloads == [("org/private", "alice-token")]+++def test_a_managed_caller_with_a_token_reaches_auto_download_for_an_uncached_private_repo(+ downloads,+):+ """The pre-check must not 404 an unresolved Hub reference before the caller's own+ token can authorize the download."""+ asyncio.run(+ arun_as(ALICE, inference._maybe_auto_switch_model("org/private", _request(), "alice"))+ )+ assert downloads == [("org/private", "alice-token")]+++def test_a_managed_caller_still_cannot_reach_another_accounts_cached_private_model(+ monkeypatch, downloads, tmp_path+):+ """A cached foreign private model stays a 404 and never triggers a download."""+ monkeypatch.setattr(access, "model_visible", lambda *a, **k: False)+ monkeypatch.setattr(inference, "_own_local_model_for_alias", lambda alias: None)+ cached = tmp_path / "hub" / "models--org--private" / "snapshots" / "abc"+ cached.mkdir(parents = True)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ arun_as(ALICE, inference._maybe_auto_switch_model(str(cached), _request(), "alice"))+ )+ assert exc.value.status_code == 404+ assert downloads == []+++def test_a_managed_caller_without_a_usable_token_is_still_refused(monkeypatch, downloads):+ """A wrong token proves nothing, so the refusal stands and no download starts."""+ request = _request()+ request.headers = {"X-Unsloth-HF-Token": "bob-token"}+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ arun_as(ALICE, inference._maybe_auto_switch_model("org/private", request, "alice"))+ )+ assert exc.value.status_code == 404+ assert downloads == []+++def test_a_managed_caller_that_sends_no_token_is_still_refused(monkeypatch, downloads):+ request = _request()+ request.headers = {}+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ arun_as(ALICE, inference._maybe_auto_switch_model("org/private", request, "alice"))+ )+ assert exc.value.status_code == 404+ assert downloads == []diff --git a/studio/backend/tests/test_account_cached_listing_offload.py b/studio/backend/tests/test_account_cached_listing_offload.pynew file mode 100644index 00000000000..3b6175e8e85--- /dev/null+++ b/studio/backend/tests/test_account_cached_listing_offload.py@@ -0,0 +1,165 @@+# 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 compatibility cached listings must probe the Hub off the event loop."""++from __future__ import annotations++import asyncio+import sys+import time+import types+from pathlib import Path+from types import SimpleNamespace++import pytest++# Keep this test runnable without optional logging deps.+if "structlog" not in sys.modules:++ class _DummyLogger:+ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ sys.modules["structlog"] = types.SimpleNamespace(+ BoundLogger = _DummyLogger,+ get_logger = lambda *args, **kwargs: _DummyLogger(),+ )++import routes.models as models_route+from auth import policy+from hub.services.models import account_access as access+from utils.account_context import OWNER, AccountContext, arun_as++ALICE = AccountContext("a" * 32, "alice")++PROBE_SECONDS = 0.5+# Well above scheduling jitter, well below one probe.+MAX_STALL = 0.2+++def _repo(repo_id: str, repo_path: Path) -> SimpleNamespace:+ snapshot = repo_path / "snapshots" / "rev"+ snapshot.mkdir(parents = True, exist_ok = True)+ weight = snapshot / "model.safetensors"+ weight.write_bytes(b"0" * 16)+ return SimpleNamespace(+ repo_id = repo_id,+ repo_type = "model",+ repo_path = repo_path,+ revisions = [+ SimpleNamespace(+ commit_hash = "rev",+ snapshot_path = snapshot,+ files = [+ SimpleNamespace(file_name = weight.name, size_on_disk = 16, blob_path = str(weight))+ ],+ )+ ],+ )+++def slow_hub(monkeypatch, tmp_path):+ """Two ungranted cached repos, each answered by a slow anonymous Hub probe."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_public_repos", {})+ monkeypatch.setattr(access, "_public_flights", {})++ probes: list[str] = []++ def answer(repo_id, repo_type):+ probes.append(repo_id)+ time.sleep(PROBE_SECONDS)+ return True++ monkeypatch.setattr(access, "_hub_public_answer", answer)++ cache = tmp_path / "hub"+ repos = [+ _repo("Org/Ungranted-One", cache / "models--Org--Ungranted-One"),+ _repo("Org/Ungranted-Two", cache / "models--Org--Ungranted-Two"),+ ]+ monkeypatch.setattr(models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = repos)])+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: cache)+ monkeypatch.setattr(models_route, "_is_hidden_model", lambda *a, **k: False)+ # GGUF listing helpers: keep the row builders trivial so only the filter costs anything.+ monkeypatch.setattr(models_route, "_repo_gguf_size_bytes", lambda repo_info: 16)+ monkeypatch.setattr(models_route, "_repo_gguf_last_modified", lambda repo_info: 1.0)+ monkeypatch.setattr(models_route, "_repo_gguf_load_id", lambda *a, **k: None)+ monkeypatch.setattr(models_route, "_gguf_copy_is_usable", lambda *a, **k: True)+ monkeypatch.setattr(models_route, "_cached_gguf_row_has_vision", lambda *a, **k: False)+ monkeypatch.setattr(models_route, "_repo_gguf_task", lambda *a, **k: "text-generation")+ # Non-GGUF listing helpers.+ monkeypatch.setattr(models_route, "_repo_has_gguf_files", lambda repo_info: False)+ monkeypatch.setattr(models_route, "_repo_model_selection", lambda *a, **k: (None, None))+ monkeypatch.setattr(+ models_route, "_recovered_repo_is_unusable_by_repo_id", lambda *a, **k: False+ )+ monkeypatch.setattr(models_route, "_cached_repo_partial", lambda *a, **k: False)+ monkeypatch.setattr(models_route, "_repo_pipeline_missing_denoiser", lambda *a, **k: False)+ monkeypatch.setattr(models_route, "_cached_repo_task", lambda *a, **k: None)+ monkeypatch.setattr(models_route, "_repo_is_diffusers", lambda *a, **k: False)+ monkeypatch.setattr(models_route, "_repo_has_pipeline_index", lambda *a, **k: True)+ monkeypatch.setattr(models_route, "_repo_model_format", lambda *a, **k: None)+ monkeypatch.setattr(models_route, "_repo_model_can_chat", lambda *a, **k: True)+ monkeypatch.setattr(models_route, "_is_sd_cpp_companion_repo", lambda repo_id: False)+ monkeypatch.setattr(models_route, "_blob_mtime", lambda f: 1.0)+ return probes+++async def _stall_during(coro):+ """Longest gap an unrelated event-loop task suffers while ``coro`` runs."""+ ticks = [time.perf_counter()]++ async def ticker():+ while True:+ await asyncio.sleep(0.01)+ ticks.append(time.perf_counter())++ watcher = asyncio.create_task(ticker())+ await asyncio.sleep(0.05)+ result = await coro+ # Record the caller's own resume point: a task cancelled before it can tick again+ # would otherwise hide the gap the blocking call just created.+ ticks.append(time.perf_counter())+ watcher.cancel()+ gaps = [later - earlier for earlier, later in zip(ticks, ticks[1:])]+ return result, max(gaps)++[email protected]("route", ["cached-gguf", "cached-models"])+def test_cached_listings_probe_the_hub_off_the_event_loop(slow_hub, route):+ def call():+ if route == "cached-gguf":+ return models_route.list_cached_gguf(current_subject = "alice")+ return models_route.list_cached_models(current_subject = "alice", hf_token = None)++ async def scenario():+ return await _stall_during(arun_as(ALICE, call()))++ payload, stall = asyncio.run(scenario())++ assert len(payload["cached"]) == 2, payload+ assert slow_hub, "the managed listing must have probed the Hub"+ assert stall < MAX_STALL, f"event loop blocked for {stall:.2f}s during /{route}"++[email protected]("route", ["cached-gguf", "cached-models"])+def test_single_owner_listings_skip_the_probe_entirely(slow_hub, monkeypatch, route):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)++ def call():+ if route == "cached-gguf":+ return models_route.list_cached_gguf(current_subject = "owner")+ return models_route.list_cached_models(current_subject = "owner", hf_token = None)++ async def scenario():+ return await _stall_during(arun_as(OWNER, call()))++ payload, stall = asyncio.run(scenario())++ assert len(payload["cached"]) == 2, payload+ assert slow_hub == [], "the owner must not probe the Hub"+ assert stall < MAX_STALLdiff --git a/studio/backend/tests/test_account_cached_resource_paths.py b/studio/backend/tests/test_account_cached_resource_paths.pynew file mode 100644index 00000000000..1311f274ace--- /dev/null+++ b/studio/backend/tests/test_account_cached_resource_paths.py@@ -0,0 +1,173 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import HTTPException++from auth import policy+from core.training import account_jobs as jobs+from hub.services.models import account_access+from utils import hf_cache_settings+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+++def shared_cache(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ cache = tmp_path / "hub-cache"+ (cache / "models--public--model" / "snapshots" / "rev").mkdir(parents = True)+ (cache / "models--private--model" / "snapshots" / "rev").mkdir(parents = True)+ (cache / "datasets--public--set" / "snapshots" / "rev").mkdir(parents = True)+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(cache))+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])+ monkeypatch.setattr(account_access, "model_grants", lambda: set())+ monkeypatch.setattr(+ account_access,+ "repo_is_public",+ lambda repo_id, repo_type = "model": not repo_id.startswith("private/"),+ )+ return cache+++def _snapshot(cache: Path, prefix: str, repo: str) -> str:+ owner, name = repo.split("/")+ return str(cache / f"{prefix}--{owner}--{name}" / "snapshots" / "rev")+++def test_a_visible_cached_model_and_dataset_start_a_managed_training_run(shared_cache):+ """The picker sends the cache path of the row the inventory showed; refusing it left a managed account unable to train on any cached selection at all."""+ config = {+ "model_name": "public/model",+ "model_local_path": _snapshot(shared_cache, "models", "public/model"),+ "hf_dataset": "public/set",+ "dataset_local_path": _snapshot(shared_cache, "datasets", "public/set"),+ "hf_token": "alice-token",+ }+ run_as(ALICE, jobs.validate_job_paths, config)+++def test_a_cached_model_the_account_cannot_see_is_still_refused(shared_cache):+ with pytest.raises(HTTPException) as exc:+ run_as(+ ALICE,+ jobs.validate_job_paths,+ {+ "model_name": "private/model",+ "model_local_path": _snapshot(shared_cache, "models", "private/model"),+ "hf_token": "alice-token",+ },+ )+ assert exc.value.status_code == 403+++def test_a_path_outside_the_shared_cache_is_still_refused(shared_cache, tmp_path):+ with pytest.raises(HTTPException) as exc:+ run_as(+ ALICE,+ jobs.validate_job_paths,+ {"model_local_path": str(tmp_path / "elsewhere" / "model"), "hf_token": "t"},+ )+ assert exc.value.status_code == 403+++def test_the_dataset_picker_can_read_a_visible_cached_dataset(shared_cache):+ from hub.schemas.datasets import LocalDatasetOptionsRequest+ from hub.services.datasets import local_options++ visible = LocalDatasetOptionsRequest(+ dataset_name = "public/set",+ local_path = _snapshot(shared_cache, "datasets", "public/set"),+ )+ run_as(ALICE, local_options.local_dataset_options, visible)++ hidden = LocalDatasetOptionsRequest(+ dataset_name = "private/set",+ local_path = _snapshot(shared_cache, "datasets", "private/set"),+ )+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, local_options.local_dataset_options, hidden)+ assert exc.value.status_code == 403+++def test_a_cached_claim_on_an_invisible_repo_is_refused(shared_cache):+ """``model_known_cached`` makes the preflight pin the shared cache copy locally, so the caller's own Hub token never authorizes the repo: check it here or nothing does."""+ with pytest.raises(HTTPException) as exc:+ run_as(+ ALICE,+ jobs.validate_job_paths,+ {+ "model_name": "private/model",+ "model_known_cached": True,+ "hf_token": "alice-token",+ },+ )+ assert exc.value.status_code == 404+++def test_a_cached_dataset_claim_on_an_invisible_repo_is_refused(shared_cache):+ with pytest.raises(HTTPException) as exc:+ run_as(+ ALICE,+ jobs.validate_job_paths,+ {"hf_dataset": "private/set", "dataset_known_cached": True, "hf_token": "t"},+ )+ assert exc.value.status_code == 404+++def test_a_cached_claim_on_a_visible_repo_still_starts(shared_cache):+ run_as(+ ALICE,+ jobs.validate_job_paths,+ {+ "model_name": "public/model",+ "model_known_cached": True,+ "hf_dataset": "public/set",+ "dataset_known_cached": True,+ "hf_token": "alice-token",+ },+ )++[email protected]("repo,expected", [("private/model", 404), ("public/model", None)])+def test_a_cache_fallback_after_a_refused_remote_probe_needs_a_grant(+ shared_cache, monkeypatch, repo, expected+):+ """The remote probe refused the caller's token, so the shared cache copy another account left behind is not a grant; a bare repo id must clear require_model_access."""+ from routes import training+ from models.training import TrainingStartRequest++ def refused(model_name, hf_token):+ raise HTTPException(status_code = 422, detail = {"code": "hf_model_access_denied"})++ monkeypatch.setattr(training, "_remote_untrainable_model_format", refused)+ from core.training import training as core_training++ monkeypatch.setattr(+ core_training,+ "_resolve_model_snapshot",+ lambda model_name, local_path: _snapshot(shared_cache, "models", model_name),+ )+ monkeypatch.setattr(+ training, "_has_trainable_local_weights", lambda *a, **k: True, raising = False+ )+ request = TrainingStartRequest(+ model_name = repo,+ dataset_name = "public/set",+ hf_token = "x",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ )+ if expected is None:+ result = run_as(ALICE, training._reject_untrainable_model_request, request)+ assert result.cached_model_pin[0] == repo+ else:+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, training._reject_untrainable_model_request, request)+ assert exc.value.status_code == expecteddiff --git a/studio/backend/tests/test_account_capability_probe_caller_token.py b/studio/backend/tests/test_account_capability_probe_caller_token.pynew file mode 100644index 00000000000..35efe813ce6--- /dev/null+++ b/studio/backend/tests/test_account_capability_probe_caller_token.py@@ -0,0 +1,112 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed user's valid HF token must also work for capability and size probes."""++from contextlib import nullcontext+from types import SimpleNamespace++import pytest++from studio.backend.tests.test_account_lifecycle import auth_env, headers+from auth import storage+from hub.services.models import account_access as access+from utils.account_context import run_as++REPO = "org/private-model"+TOKEN = "hf_alice_private_access"+++def probe_env(auth_env, monkeypatch):+ from routes import models+ from core.inference import llama_cpp++ client, _, _ = auth_env+ storage.create_initial_user(+ "alice", "alice-password", "alice-jwt-secret-for-test-at-least-32-bytes"+ )+ storage.create_initial_user("bob", "bob-password", "bob-jwt-secret-for-test-at-least-32-bytes")+ client.app.include_router(models.router, prefix = "/api/models")+ monkeypatch.setattr(access, "_public_repos", {})+ calls = []++ def repo_info(+ repo_id,+ *,+ token = None,+ **kwargs,+ ):+ calls.append(token)+ if token != TOKEN:+ exc = Exception("Repository not found")+ exc.response = SimpleNamespace(status_code = 404)+ raise exc+ return SimpleNamespace(private = True, gated = False)++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = repo_info))+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable_for", lambda _: nullcontext())+ monkeypatch.setattr(models, "resolve_cached_repo_id_case", lambda name: name)+ monkeypatch.setattr(models, "is_vision_model", lambda *a, **k: True)+ monkeypatch.setattr(models, "is_embedding_model", lambda *a, **k: True)+ monkeypatch.setattr(models, "_export_size_cached", lambda *a, **k: (123, 45, "hub"))+ return client, calls+++def _token_headers(username = "alice"):+ return {**headers(username), "X-Unsloth-HF-Token": TOKEN, "X-HF-Token": TOKEN}+++def test_check_vision_accepts_callers_valid_token(probe_env):+ client, _ = probe_env+ alice = storage.get_account("alice")+ assert run_as(alice, access.model_grants) == set()+ response = client.get(f"/api/models/check-vision/{REPO}", headers = _token_headers())+ print(f"check-vision: HTTP {response.status_code} body={response.text}")+ assert response.status_code == 200, response.text+ assert response.json()["is_vision"] is True+ assert run_as(alice, access.model_grants) == set()+++def test_check_embedding_accepts_callers_valid_token(probe_env):+ client, _ = probe_env+ response = client.get(f"/api/models/check-embedding/{REPO}", headers = _token_headers())+ print(f"check-embedding: HTTP {response.status_code} body={response.text}")+ assert response.status_code == 200, response.text+ assert response.json()["is_embedding"] is True+++def test_export_size_accepts_callers_valid_token(probe_env):+ client, _ = probe_env+ response = client.get(+ "/api/models/export-size", params = {"model": REPO}, headers = _token_headers()+ )+ print(f"export-size: HTTP {response.status_code} body={response.text}")+ assert response.status_code == 200, response.text+ assert response.json()["fp16_bytes"] == 123++[email protected]("token", [None, "hf_wrong"])[email protected]("path", ["check-vision/" + REPO, "check-embedding/" + REPO, "export-size"])+def test_missing_or_wrong_token_remains_hidden(probe_env, token, path):+ client, _ = probe_env+ request_headers = headers("bob")+ if token:+ request_headers["X-Unsloth-HF-Token"] = token+ request_headers["X-HF-Token"] = token+ params = {"model": REPO} if path == "export-size" else None+ response = client.get(f"/api/models/{path}", params = params, headers = request_headers)+ assert response.status_code == 404, response.text+++def test_owner_is_unaffected(probe_env):+ client, _ = probe_env+ for path, params in (+ ("check-vision/" + REPO, None),+ ("check-embedding/" + REPO, None),+ ("export-size", {"model": REPO}),+ ):+ response = client.get(+ f"/api/models/{path}", params = params, headers = _token_headers("unsloth")+ )+ assert response.status_code == 200, response.textdiff --git a/studio/backend/tests/test_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.pynew file mode 100644index 00000000000..eec9faf4adf--- /dev/null+++ b/studio/backend/tests/test_account_chat_settings.py@@ -0,0 +1,646 @@+# 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 asyncio+import hashlib+import json+import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI, Request+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import authenticated_via_api_key, get_current_subject+from routes import (+ chat_generation_runs,+ chat_history,+ profile_stats,+ prompts,+ research_runs,+ settings,+)+from state import active_generations+from storage import (+ api_usage_db,+ chat_generation_runs_db,+ profile_stats_db,+ research_runs_db,+ studio_db,+)+from utils import keyless_api_access+from utils.account_context import (+ OWNER,+ AccountContext,+ arun_as,+ bind_account,+ current_account_id,+ reset_account,+ run_as,+)+from utils.paths import studio_db_path++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+ACCOUNTS = {account.username: account for account in (OWNER, ALICE, BOB)}++[email protected](autouse = True)+def account_databases(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ for account in ACCOUNTS.values():+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.setattr(chat_generation_runs_db, "_schema_ready", set())+ run_as(account, chat_generation_runs_db.get_run, "initialize-schema")+ active_generations.reset_for_tests()+ keyless_api_access._reset_scope_cache()+ profile_stats_db.invalidate_profile_stats_cache()+ yield+ active_generations.reset_for_tests()+ keyless_api_access._reset_scope_cache()+ profile_stats_db.invalidate_profile_stats_cache()+++def client(monkeypatch):+ app = FastAPI()++ async def subject(request: Request):+ account = ACCOUNTS[request.headers.get("x-test-account", "alice")]+ marker = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(marker)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(chat_history.router, prefix = "/chat")+ app.include_router(chat_generation_runs.router, prefix = "/runs")+ app.include_router(settings.router, prefix = "/settings")+ app.include_router(prompts.router, prefix = "/prompts")+ app.include_router(profile_stats.router, prefix = "/profile")+ app.include_router(research_runs.router, prefix = "/research")++ async def remove_sandboxes(*args):+ return 0, []++ monkeypatch.setattr(chat_history, "_remove_sandboxes", remove_sandboxes)+ monkeypatch.setattr(chat_history, "_remove_conversation_archives", lambda *args, **kwargs: None)+ with TestClient(app) as test_client:+ yield test_client+++def seed_chat(+ account,+ thread_id = "private",+ text = "private text",+):+ def seed():+ studio_db.upsert_chat_thread(+ {+ "id": thread_id,+ "title": text,+ "modelType": "base",+ "modelId": text,+ "createdAt": 1,+ }+ )+ studio_db.upsert_chat_message(+ {+ "id": "message",+ "threadId": thread_id,+ "role": "user",+ "createdAt": 2,+ "content": [{"type": "text", "text": text}],+ "attachments": [+ {+ "id": "attachment",+ "name": "private.txt",+ "type": "file",+ "contentType": "text/plain",+ "content": [{"type": "text", "text": text}],+ }+ ],+ }+ )++ run_as(account, seed)+++def seed_run(+ account,+ run_id = "run",+ thread_id = "private",+):+ return run_as(+ account,+ chat_generation_runs_db.create_run,+ run_id = run_id,+ owner_subject = account.username,+ thread_id = thread_id,+ user_message_id = "message",+ assistant_message_id = "reply",+ request_payload = {"model": "local", "messages": [{"role": "user", "content": "Hello"}]},+ )[0]+++ "method,path,body",+ [+ ("GET", "/chat/threads/private", None),+ ("PATCH", "/chat/threads/private", {"title": "stolen"}),+ ("GET", "/chat/threads/private/messages", None),+ ("GET", "/chat/threads/private/messages/message", None),+ (+ "PUT",+ "/chat/threads/private/messages/message",+ {+ "id": "message",+ "threadId": "private",+ "role": "user",+ "createdAt": 2,+ "attachments": [{"id": "attachment", "name": "renamed.txt"}],+ },+ ),+ (+ "POST",+ "/chat/threads/private/fork",+ {+ "messageId": "message",+ "newThreadId": "stolen",+ "createdAt": 3,+ },+ ),+ ("GET", "/chat/attachments/message/attachment/file", None),+ ("DELETE", "/chat/attachments/message/attachment", None),+ ("GET", "/runs/run", None),+ ("POST", "/runs/run/cancel", None),+ ("POST", "/runs/run/events", None),+ ],+)+def test_foreign_ids_do_not_authorize_reads_or_writes(client, method, path, body):+ seed_chat(BOB)+ seed_run(BOB)+ response = client.request(method, path, json = body)+ assert response.status_code == 404, response.text+ assert run_as(BOB, studio_db.get_chat_thread, "private")["title"] == "private text"+ assert run_as(BOB, chat_generation_runs_db.get_run, "run")["status"] == "queued"+++def test_list_export_and_delete_stay_in_the_account(client):+ seed_chat(BOB)+ seed_run(BOB)+ assert client.get("/chat/threads").json() == {"threads": []}+ assert client.get("/runs/active?threadId=private").json() == {"runs": []}+ assert client.get("/chat/attachments").json()["attachments"] == []+ assert client.get("/chat/export").json()["threadCount"] == 0+ bob_event = threading.Event()+ with run_as(+ BOB, active_generations.ActiveGeneration, bob_event, thread_id = "private", run_id = "run"+ ):+ assert (+ client.request("DELETE", "/chat/threads", json = {"ids": ["private"]}).status_code == 200+ )+ assert not bob_event.is_set()+ assert run_as(BOB, studio_db.get_chat_thread, "private") is not None+ assert run_as(BOB, studio_db.get_chat_attachment, "message", "attachment") is not None++[email protected]("supervisor_name", ["chat_generation_supervisor", "research_supervisor"])+def test_cancellation_never_uses_an_unscoped_supervisor(supervisor_name):+ calls = []+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(+ **{+ supervisor_name: SimpleNamespace(cancel = calls.append),+ }+ )+ )+ )+ alice_event, bob_event = threading.Event(), threading.Event()+ with (+ run_as(ALICE, active_generations.ActiveGeneration, alice_event, run_id = "same"),+ run_as(BOB, active_generations.ActiveGeneration, bob_event, run_id = "same"),+ ):+ run_as(+ ALICE,+ chat_generation_runs.cancel_account_run,+ request,+ "same",+ supervisor_name = supervisor_name,+ )+ assert alice_event.is_set() and not bob_event.is_set()+ assert calls == ([] if supervisor_name == "chat_generation_supervisor" else ["same"])+++ "cleanup",+ [+ chat_history._cancel_deleted_research_runs,+ chat_history._cancel_research_runs,+ chat_history._cancel_chat_generation_runs,+ ],+)[email protected]("supervisor_present", [True, False])+def test_thread_cleanup_scopes_run_ids(cleanup, supervisor_present):+ calls = []+ supervisor = SimpleNamespace(cancel = calls.append) if supervisor_present else None+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(+ research_supervisor = supervisor,+ chat_generation_supervisor = supervisor,+ )+ )+ )+ alice_event, bob_event = threading.Event(), threading.Event()+ with (+ run_as(ALICE, active_generations.ActiveGeneration, alice_event, run_id = "same"),+ run_as(BOB, active_generations.ActiveGeneration, bob_event, run_id = "same"),+ ):+ run_as(ALICE, cleanup, request, ["same"])+ assert alice_event.is_set() and not bob_event.is_set()+ research = supervisor_present and cleanup is not chat_history._cancel_chat_generation_runs+ assert calls == (["same"] if research else [])+++def test_cancel_route_scopes_same_id_in_two_accounts(client):+ for account in (ALICE, BOB):+ seed_chat(account)+ seed_run(account)+ alice_event, bob_event = threading.Event(), threading.Event()+ with (+ run_as(ALICE, active_generations.ActiveGeneration, alice_event, run_id = "run"),+ run_as(BOB, active_generations.ActiveGeneration, bob_event, run_id = "run"),+ ):+ assert client.post("/runs/run/cancel").status_code == 200+ assert alice_event.is_set() and not bob_event.is_set()+ assert run_as(BOB, chat_generation_runs_db.get_run, "run")["status"] == "queued"+++def test_create_refuses_a_foreign_supervisor_slot_before_writing(client, monkeypatch):+ seed_chat(ALICE)+ monkeypatch.setattr(+ chat_generation_runs, "_sanitize_request", lambda payload: payload.requestPayload+ )+ body = {+ "runId": "same",+ "threadId": "private",+ "userMessageId": "message",+ "assistantMessageId": "reply",+ "requestPayload": {"model": "local"},+ }+ with run_as(BOB, active_generations.ActiveGeneration, threading.Event(), run_id = "same"):+ assert client.post("/runs", json = body).status_code == 404+ assert run_as(ALICE, chat_generation_runs_db.get_run, "same") is None+++def test_event_wait_executor_retains_account_context(client, monkeypatch):+ for account in (OWNER, ALICE):+ seed_chat(account, text = account.username)+ seed_run(account)+ run_as(account, chat_generation_runs_db.request_cancel, "run")+ seen = []+ original = chat_generation_runs_db.wait_for_events++ def wait(*args):+ seen.append(current_account_id())+ return original(*args)++ monkeypatch.setattr(chat_generation_runs_db, "wait_for_events", wait)+ response = client.post("/runs/run/events")+ assert response.status_code == 200+ assert seen == [ALICE.account_id]+ events = [+ json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: ")+ ]+ expected = run_as(ALICE, chat_generation_runs_db.list_events, "run")+ assert [(event["seq"], event["createdAt"]) for event in events] == [+ (event["seq"], event["createdAt"]) for event in expected+ ]+++def test_clear_history_reaps_only_its_own_images_and_leaves_foreign_runs(client, monkeypatch):+ from core.inference import search_images++ calls = []+ monkeypatch.setattr(+ search_images,+ "snapshot_and_fence_registrations",+ lambda: calls.append(("snapshot", current_account_id())) or set(),+ )+ monkeypatch.setattr(+ search_images,+ "clear_cache",+ lambda *args: calls.append(("clear", current_account_id())),+ )+ for account in (ALICE, BOB):+ seed_chat(account)+ seed_run(account)+ bob_event = threading.Event()+ with run_as(+ BOB, active_generations.ActiveGeneration, bob_event, thread_id = "private", run_id = "run"+ ):+ for _ in range(2):+ response = client.request(+ "DELETE", "/chat", json = {"ids": ["private"], "operationId": "same-clear"}+ )+ assert response.status_code == 200, response.text+ assert not bob_event.is_set()+ assert calls == [("snapshot", ALICE.account_id), ("clear", ALICE.account_id)]+ assert run_as(BOB, studio_db.get_chat_thread, "private") is not None+++OWNER_PATHS = [+ (method, path)+ for path, methods in {+ "/hugging-face-cache": ("GET", "PUT"),+ "/llama-cpp-path": ("GET", "PUT"),+ "/upload-limit": ("PUT",),+ "/helper-precache": ("PUT",),+ "/download-transport": ("PUT",),+ "/xet-notice/reserve": ("POST",),+ "/model-memory": ("GET", "PUT"),+ "/vram-budget": ("GET", "PUT"),+ "/coding-agents": ("GET",),+ "/openai-auto-switch": ("GET", "PUT"),+ "/openai-auto-switch/overrides": ("GET", "PUT"),+ "/embedding-model": ("GET", "PUT", "DELETE"),+ "/embedding-model/resolve": ("GET",),+ "/embedding-model/unload": ("POST",),+ "/preview-links/rotate": ("POST",),+ "/remote-access": ("GET",),+ "/remote-access/start": ("POST",),+ "/remote-access/stop": ("POST",),+ "/remote-access/auto-start": ("PUT",),+ "/lan-access": ("GET",),+ "/lan-access/start": ("POST",),+ "/lan-access/stop": ("POST",),+ "/lan-access/auto-start": ("PUT",),+ "/lan-access/port": ("PUT",),+ "/preview-sharing": ("GET", "PUT"),+ "/keyless-api-access": ("GET", "PUT"),+ "/debug/logs/sources": ("GET",),+ "/debug/logs": ("GET",),+ }.items()+ for method in methods+]++[email protected]("method,path", OWNER_PATHS)+def test_every_owner_setting_rejects_managed_accounts(client, method, path):+ response = client.request(method, "/settings" + path, json = {})+ assert response.status_code == 403, response.text+++ "path,body",+ [+ ("/personalization", {"profile": {"displayName": "Alice"}}),+ ("/chat-preferences", {"show_model_disclaimer": True}),+ ("/current-date-prompt", {"enabled": False}),+ ],+)+def test_personal_settings_do_not_change_owner_rows(client, path, body):+ owner_record = {+ "version": 1,+ "profile": {"displayName": "Original owner"},+ "future": {"keep": True},+ }+ studio_db.upsert_app_settings({"personalization": owner_record})+ with studio_db.get_connection() as conn:+ before = tuple(+ conn.execute("SELECT * FROM app_settings WHERE key = 'personalization'").fetchone()+ )+ assert client.put("/settings" + path, json = body).status_code == 200+ with studio_db.get_connection() as conn:+ after = tuple(+ conn.execute("SELECT * FROM app_settings WHERE key = 'personalization'").fetchone()+ )+ assert after == before+ assert studio_db.get_app_setting("personalization") == owner_record+++def test_shared_policy_reads_owner_storage_and_restores_context(client, monkeypatch):+ seen = []+ monkeypatch.setattr(+ settings, "get_upload_limit_mb", lambda: seen.append(current_account_id()) or 100+ )+ assert client.get("/settings/upload-limit").status_code == 200+ assert seen == [OWNER.account_id]+ assert (+ client.put("/settings/personalization", json = {"profile": {"nickname": "alice"}}).status_code+ == 200+ )+ assert (+ run_as(ALICE, studio_db.get_app_setting, "personalization")["profile"]["nickname"]+ == "alice"+ )+ assert studio_db.get_app_setting("personalization", None) is None+++def test_owner_setting_keeps_200_and_single_account_policy_is_inert(client, monkeypatch):+ monkeypatch.setattr(+ settings,+ "_llama_cpp_path_response",+ lambda: settings.LlamaCppPathResponse(source = "default", editable = True, available = False),+ )+ response = client.get("/settings/llama-cpp-path", headers = {"x-test-account": "unsloth"})+ assert response.status_code == 200, response.text+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ # Deactivating the last managed account must not open an owner-only setting to a request still bound to it.+ owner = client.get("/settings/llama-cpp-path", headers = {"x-test-account": "unsloth"})+ assert owner.status_code == 200+ assert client.get("/settings/llama-cpp-path").status_code == 403+++def test_managed_last_model_key_survives_username_rename(client):+ payload = {"id": "alice-model", "kind": "gguf"}+ assert client.put("/settings/last-local-model", json = payload).status_code == 200+ renamed = AccountContext(ALICE.account_id, "new-name")+ result = run_as(renamed, settings.get_last_local_model, current_subject = renamed.username)+ assert result.id == "alice-model"+ digest = hashlib.sha256(b"unsloth").hexdigest()[:32]+ assert settings._last_local_model_key("unsloth") == f"last_local_model_load:{digest}"+++def test_owner_chats_prompts_and_settings_survive_alice(client):+ seed_chat(OWNER, text = "owner chat")+ seed_chat(ALICE, text = "alice chat")+ studio_db.upsert_chat_settings_merge({"autoTitle": False})+ assert client.put("/chat/settings", json = {"autoTitle": True}).status_code == 200+ prompt = {"id": "same", "name": "Owner", "text": "owner prompt", "createdAt": 1, "updatedAt": 1}+ studio_db.upsert_prompt_entry(prompt)+ assert (+ client.put("/prompts/entries/same", json = {**prompt, "text": "alice prompt"}).status_code+ == 200+ )+ assert client.delete("/prompts/entries/same").status_code == 204+ assert client.get("/chat/export").json()["threads"][0]["title"] == "alice chat"+ assert studio_db.list_prompt_entries()[0]["text"] == "owner prompt"+ assert studio_db.list_chat_settings()["autoTitle"] is False+ assert studio_db.get_chat_thread("private")["title"] == "owner chat"+ assert studio_db_path().name == "studio.db" and "accounts" not in str(studio_db_path())+++def test_keyless_cache_is_always_populated_from_the_owner():+ studio_db.upsert_app_settings(+ {"keyless_api_access_scope": "off", "keyless_api_access_tools": False}+ )+ run_as(+ ALICE,+ studio_db.upsert_app_settings,+ {"keyless_api_access_scope": "full", "keyless_api_access_tools": True},+ )+ assert run_as(ALICE, keyless_api_access.get_keyless_api_access_settings) == ("off", False)+ assert keyless_api_access.get_keyless_api_access_settings() == ("off", False)+ with pytest.raises(ValueError, match = "owner"):+ run_as(ALICE, keyless_api_access.set_keyless_api_access, "full", tools = True)+ assert keyless_api_access.get_keyless_api_access_settings() == ("off", False)+++def test_profile_cache_cannot_follow_a_reused_username(monkeypatch):+ seed_chat(ALICE, text = "Alice model")+ seed_chat(BOB, text = "Bob model")+ for account in (ALICE, BOB):+ run_as(+ account,+ studio_db.upsert_chat_message,+ {+ "id": "reply",+ "threadId": "private",+ "role": "assistant",+ "createdAt": 3,+ "content": [{"type": "text", "text": "reply"}],+ },+ )+ renamed_bob = AccountContext(BOB.account_id, "alice")++ async def stats(account):+ return await arun_as(+ account,+ profile_stats.get_profile_stats(+ days = 30,+ tz_offset_minutes = 0,+ tz = "",+ current_subject = "alice",+ ),+ )++ alice = asyncio.run(stats(ALICE))+ bob = asyncio.run(stats(renamed_bob))+ assert "Alice model" in str(alice)+ assert "Alice model" not in str(bob)+ assert "Bob model" in str(bob)+++def test_alternating_accounts_keep_their_cached_profile_stats(monkeypatch):+ """An actor change must not invalidate a cache the storage layer already keys by account."""+ folds = []+ fold_messages = profile_stats_db._fold_messages+ monkeypatch.setattr(+ profile_stats_db,+ "_fold_messages",+ lambda *args: folds.append(current_account_id()) or fold_messages(*args),+ )++ async def stats(account):+ return await arun_as(+ account,+ profile_stats.get_profile_stats(+ days = 30,+ tz_offset_minutes = 0,+ tz = "",+ current_subject = "reader",+ ),+ )++ payloads = [asyncio.run(stats(account)) for account in (ALICE, BOB, ALICE, BOB)]+ assert payloads[0] is payloads[2]+ assert payloads[1] is payloads[3]+ assert folds == [ALICE.account_id, BOB.account_id]+++def test_api_usage_statistics_read_only_the_account_database(client):+ receipt = api_usage_db.ApiUsageReceipt(+ id = "receipt",+ subject = "bob",+ endpoint = "/v1/chat/completions",+ model = "bob-model",+ status = "completed",+ prompt_tokens = 10,+ completion_tokens = 20,+ total_tokens = 30,+ created_at = 1,+ via_api_key = True,+ )+ run_as(BOB, api_usage_db.record_api_usage, receipt)+ response = client.get("/profile/stats")+ assert response.status_code == 200, response.text+ assert "bob-model" not in response.text+++def test_single_account_cancel_still_calls_the_original_supervisor(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ calls = []+ request = SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(+ chat_generation_supervisor = SimpleNamespace(cancel = calls.append),+ )+ )+ )+ chat_generation_runs.cancel_account_run(+ request, "old-run", supervisor_name = "chat_generation_supervisor"+ )+ assert calls == ["old-run"]+++def test_single_account_cancel_without_supervisor_keeps_existing_behavior(client, monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ seed_chat(OWNER)+ seed_run(OWNER)+ calls = []+ monkeypatch.setattr(+ chat_generation_runs, "cancel_account_run", lambda *args, **kwargs: calls.append(args)+ )+ response = client.post("/runs/run/cancel", headers = {"x-test-account": "unsloth"})+ assert response.status_code == 200+ assert calls == []+++def test_deep_research_foreign_run_is_not_visible_or_cancellable(client):+ seed_chat(BOB)+ run_as(+ BOB,+ research_runs_db.create_run,+ run_id = "research",+ owner_subject = "bob",+ thread_id = "private",+ user_message_id = "message",+ assistant_message_id = None,+ config = {},+ )+ assert client.get("/research/active?threadId=private").json() == {"runs": [], "hasRun": False}+ assert client.get("/research/research").status_code == 404+ assert client.post("/research/research/cancel").status_code == 404+ assert run_as(BOB, research_runs_db.get_run, "research")["status"] == "planning"+++def test_research_cleanup_reaches_the_account_keyed_supervisor():+ from core import research_runs as research_runs_core++ supervisor = research_runs_core.ResearchSupervisor.__new__(+ research_runs_core.ResearchSupervisor+ )+ supervisor._cancel_events = {}+ request = SimpleNamespace(+ app = SimpleNamespace(state = SimpleNamespace(research_supervisor = supervisor))+ )+ alice_event = run_as(ALICE, supervisor._cancel_event, "same")+ bob_event = run_as(BOB, supervisor._cancel_event, "same")+ run_as(ALICE, chat_history._cancel_research_runs, request, ["same"])+ assert alice_event.is_set() and not bob_event.is_set()diff --git a/studio/backend/tests/test_account_contract.py b/studio/backend/tests/test_account_contract.pynew file mode 100644index 00000000000..60f07317f80--- /dev/null+++ b/studio/backend/tests/test_account_contract.py@@ -0,0 +1,356 @@+# 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 account contract every isolation change builds on: one account resolves EXACTLY as it did before accounts existed, and a second account can never reach the first one's storage or generations."""++from __future__ import annotations++import asyncio+import secrets+import sqlite3+import threading+from pathlib import Path++import pytest++from utils.account_context import (+ OWNER,+ OWNER_ACCOUNT_ID,+ AccountContext,+ account_thread,+ arun_as,+ bind_account,+ current_account,+ current_account_id,+ is_owner_context,+ reset_account,+ run_as,+)++ALICE = AccountContext("a1b2c3d4e5f6a7b8", "alice", "user")+BOB = AccountContext("0f0e0d0c0b0a0908", "bob", "user")+++def studio_home(tmp_path, monkeypatch):+ home = tmp_path / "studio"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ monkeypatch.delenv("UNSLOTH_STUDIO_PROJECTS_HOME", raising = False)+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "Documents"))+ return home+++def auth_db(tmp_path, monkeypatch):+ from auth import policy, storage++ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth" / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / "auth" / ".bootstrap_password")+ policy.invalidate_account_cache()+ yield storage+ policy.invalidate_account_cache()+++def test_the_default_context_is_the_owner():+ assert current_account() == OWNER+ assert current_account_id() == OWNER_ACCOUNT_ID+ assert is_owner_context() is True+++def test_bind_and_reset_restore_the_previous_account():+ token = bind_account(ALICE)+ try:+ assert current_account() == ALICE+ assert is_owner_context() is False+ finally:+ reset_account(token)+ assert current_account() == OWNER+++def test_run_as_binds_for_the_call_only():+ seen = run_as(ALICE, current_account_id)+ assert seen == ALICE.account_id+ assert current_account() == OWNER+++def test_run_as_refuses_a_coroutine():+ async def later():+ return current_account_id()++ with pytest.raises(TypeError):+ run_as(ALICE, later)+++def test_arun_as_keeps_the_binding_across_the_await():+ async def later():+ await asyncio.sleep(0)+ return current_account_id()++ assert asyncio.run(arun_as(ALICE, later())) == ALICE.account_id+ assert current_account() == OWNER+++def test_a_plain_thread_does_not_inherit_the_binding():+ seen: list[str] = []+ token = bind_account(ALICE)+ try:+ t = threading.Thread(target = lambda: seen.append(current_account_id()))+ t.start()+ t.join(5)+ finally:+ reset_account(token)+ assert seen == [OWNER_ACCOUNT_ID]+++def test_account_thread_captures_the_account_at_creation():+ seen: list[str] = []+ token = bind_account(ALICE)+ try:+ t = account_thread(target = lambda: seen.append(current_account_id()))+ finally:+ reset_account(token)+ t.start()+ t.join(5)+ assert seen == [ALICE.account_id]+++def test_the_owner_keeps_every_historical_path(studio_home):+ from utils.paths import storage_roots as r++ expected = {+ r.workspace_root: studio_home,+ r.studio_db_path: studio_home / "studio.db",+ r.assets_root: studio_home / "assets",+ r.outputs_root: studio_home / "outputs",+ r.exports_root: studio_home / "exports",+ r.rag_root: studio_home / "rag",+ r.tensorboard_root: studio_home / "runs",+ r.cache_root: studio_home / "cache",+ r.auth_db_path: studio_home / "auth" / "auth.db",+ }+ for fn, want in expected.items():+ assert fn() == want, fn.__name__+ assert "accounts" not in str(r.tmp_root())+ assert r.project_workspaces_root().parts[-2:] == ("Unsloth Studio", "Projects")+++def test_a_managed_account_is_rooted_under_its_id(studio_home):+ from utils.paths import storage_roots as r++ base = studio_home / "accounts" / ALICE.account_id+ assert run_as(ALICE, r.workspace_root) == base+ assert run_as(ALICE, r.studio_db_path) == base / "studio.db"+ assert run_as(ALICE, r.assets_root) == base / "assets"+ assert run_as(ALICE, r.rag_root) == base / "rag"+ assert run_as(ALICE, r.tensorboard_root) == base / "runs"+ assert run_as(ALICE, r.tmp_root).parts[-2:] == ("accounts", ALICE.account_id)+ assert run_as(ALICE, r.project_workspaces_root).parts[-3:] == (+ "Accounts",+ ALICE.account_id,+ "Projects",+ )+ assert run_as(ALICE, r.cache_root) == studio_home / "cache"+ assert run_as(ALICE, r.auth_db_path) == studio_home / "auth" / "auth.db"+++def test_two_accounts_never_share_a_private_root(studio_home):+ from utils.paths import storage_roots as r+ for fn in (r.workspace_root, r.studio_db_path, r.rag_db_path, r.outputs_root, r.tmp_root):+ assert run_as(ALICE, fn) != run_as(BOB, fn), fn.__name__+ assert run_as(ALICE, fn) != fn(), fn.__name__+++def test_root_resolution_creates_nothing(studio_home):+ from utils.paths import storage_roots as r+ for fn in (r.workspace_root, r.studio_db_path, r.assets_root, r.tmp_root):+ fn()+ run_as(ALICE, fn)+ assert not studio_home.exists()+++def test_an_old_auth_db_gains_the_identity_columns_with_the_owner_pinned(auth_db, tmp_path):+ db = tmp_path / "auth" / "auth.db"+ db.parent.mkdir(parents = True)+ conn = sqlite3.connect(db)+ conn.execute(+ "CREATE TABLE auth_user (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, "+ "password_salt TEXT NOT NULL, password_hash TEXT NOT NULL, jwt_secret TEXT NOT NULL)"+ )+ conn.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret) VALUES ('unsloth','s','h','j')"+ )+ conn.commit()+ conn.close()++ record = auth_db.get_user_record("unsloth")+ assert record["account_id"] == OWNER_ACCOUNT_ID+ assert record["role"] == "owner"+ assert record["is_active"] == 1+ assert auth_db.get_account("unsloth") == OWNER+ assert auth_db.count_active_accounts() == 1+++def test_the_seeded_owner_is_the_owner_and_a_second_account_is_not(auth_db):+ auth_db.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ auth_db.create_initial_user("alice", "alice-password", secrets.token_urlsafe(32))+ owner = auth_db.get_account("unsloth")+ alice = auth_db.get_account("alice")+ assert owner == OWNER+ assert alice.role == "user"+ assert alice.account_id not in ("", OWNER_ACCOUNT_ID, "alice")+ assert len(alice.account_id) == 32+++def test_login_mode_follows_the_account_count(auth_db):+ from auth import policy++ auth_db.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ assert policy.login_mode() == "single"+ assert policy.installation_is_multi_user() is False+ assert policy.full_access_permitted() is True+ auth_db.create_initial_user("alice", "alice-password", secrets.token_urlsafe(32))+ assert policy.login_mode() == "multi"+ assert policy.full_access_permitted() is False+ auth_db.delete_user("alice")+ assert policy.login_mode() == "single"+++def test_the_policy_cache_costs_nothing_on_the_hot_path(auth_db, monkeypatch):+ from auth import policy++ auth_db.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ assert policy.installation_is_multi_user() is False+ calls = []+ monkeypatch.setattr(auth_db, "account_counts", lambda: calls.append(1) or (1, 0))+ for _ in range(50):+ policy.installation_is_multi_user()+ assert calls == []+++def test_auth_status_reports_login_mode(auth_db):+ from routes import auth as auth_routes++ auth_db.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ assert auth_routes.auth_status().login_mode == "single"+ auth_db.create_initial_user("alice", "alice-password", secrets.token_urlsafe(32))+ status = auth_routes.auth_status()+ assert status.login_mode == "multi"+ assert "alice" not in status.model_dump_json()+++def test_a_request_is_bound_to_the_account_its_token_names(auth_db):+ from auth import authentication+ from fastapi.security import HTTPAuthorizationCredentials++ auth_db.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ auth_db.create_initial_user("alice", "alice-password", secrets.token_urlsafe(32))+ alice = auth_db.get_account("alice")++ async def resolve(token):+ creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)+ subject, _gen = await authentication._get_current_credential(+ creds, allow_password_change = False+ )+ return subject, current_account()++ subject, bound = asyncio.run(resolve(authentication.create_access_token(subject = "alice")))+ assert subject == "alice"+ assert bound == alice+ subject, bound = asyncio.run(resolve(authentication.create_access_token(subject = "unsloth")))+ assert (subject, bound) == ("unsloth", OWNER)+++def test_generations_are_scoped_to_their_account():+ from state import active_generations as ag++ ag.reset_for_tests()+ ev_a, ev_b = threading.Event(), threading.Event()+ with (+ run_as(ALICE, ag.ActiveGeneration, ev_a, thread_id = "t1"),+ run_as(BOB, ag.ActiveGeneration, ev_b, thread_id = "t1"),+ ):+ assert ag.count() == 2+ assert ag.count(ALICE.account_id) == 1+ assert ag.foreign_count(ALICE.account_id) == 1+ assert run_as(ALICE, ag.cancel_thread, "t1") == 1+ assert ev_a.is_set() and not ev_b.is_set()+ assert ag.cancel_all(ALICE.account_id) == 1+ assert not ev_b.is_set()+ assert ag.cancel_all() == 2+ assert ev_b.is_set()+ ag.reset_for_tests()+++def test_a_load_never_evicts_another_accounts_active_generation(monkeypatch):+ from core.inference import gpu_arbiter as arb+ from state import active_generations as ag++ ag.reset_for_tests()+ evicted = []+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: evicted.append("chat"))+ monkeypatch.setitem(arb._EVICTORS, arb.DIFFUSION, lambda: evicted.append("diffusion"))+ arb.release(arb.CHAT)+ arb.release(arb.DIFFUSION)++ run_as(ALICE, arb.acquire_for, arb.CHAT)+ assert arb.owner_account() == ALICE.account_id+ with run_as(ALICE, ag.ActiveGeneration, threading.Event(), thread_id = "t1"):+ with pytest.raises(arb.GpuBusyForAnotherAccountError):+ run_as(BOB, arb.acquire_for, arb.DIFFUSION)+ assert evicted == []+ run_as(ALICE, arb.acquire_for, arb.DIFFUSION)+ assert evicted == ["chat"]+ run_as(BOB, arb.acquire_for, arb.CHAT)+ assert evicted == ["chat", "diffusion"]+ assert arb.owner_account() == BOB.account_id+ arb.release(arb.CHAT)+ ag.reset_for_tests()+++def test_reusing_a_resident_model_leaves_the_loader_in_control(monkeypatch):+ """An already-loaded fast path re-asserts CHAT as a claim on the GPU, not a load, so it must not rewrite the account that loaded what is resident: doing so hid the loader from its own model."""+ from auth import policy+ from core.inference import gpu_arbiter as arb+ from hub.services.models import account_access as access+ from state import active_generations as ag++ ag.reset_for_tests()+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: None)+ monkeypatch.setitem(arb._EVICTORS, arb.DIFFUSION, lambda: None)+ arb.release(arb.CHAT)+ arb.release(arb.DIFFUSION)++ assert run_as(ALICE, arb.acquire_for, arb.CHAT, lambda: "loaded") == "loaded"+ assert arb.owner_account() == ALICE.account_id++ run_as(BOB, arb.acquire_for_request, arb.CHAT)+ assert arb.owner_account() == ALICE.account_id+ assert not run_as(ALICE, access.resident_hidden, "chat")++ run_as(BOB, arb.acquire_for, arb.CHAT, lambda: None)+ assert arb.owner_account() == BOB.account_id+ run_as(ALICE, arb.acquire_for, arb.CHAT, replacing = True)+ assert arb.owner_account() == ALICE.account_id+ run_as(BOB, arb.acquire_for, arb.DIFFUSION)+ assert arb.owner_account() == BOB.account_id++ arb.release(arb.DIFFUSION)+ ag.reset_for_tests()+++def test_the_owner_alone_behaves_exactly_as_before(monkeypatch):+ from core.inference import gpu_arbiter as arb+ from state import active_generations as ag++ ag.reset_for_tests()+ evicted = []+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: evicted.append("chat"))+ monkeypatch.setitem(arb._EVICTORS, arb.DIFFUSION, lambda: evicted.append("diffusion"))+ arb.release(arb.CHAT)+ arb.acquire_for(arb.CHAT)+ with ag.ActiveGeneration(threading.Event(), thread_id = "t1"):+ arb.acquire_for(arb.DIFFUSION)+ assert evicted == ["chat"]+ assert ag.cancel_all() == 0+ arb.release(arb.DIFFUSION)diff --git a/studio/backend/tests/test_account_credential_binding.py b/studio/backend/tests/test_account_credential_binding.pynew file mode 100644index 00000000000..1641faabf85--- /dev/null+++ b/studio/backend/tests/test_account_credential_binding.py@@ -0,0 +1,194 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An API key binds the account it was validated for; a deactivated account keeps the host closed until deleted."""++import asyncio+import secrets++import jwt+import pytest+from fastapi import HTTPException++from auth import authentication, policy, storage+from utils.account_context import OWNER, current_account, reset_account+++def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield storage+ policy.invalidate_account_cache()+++def _managed(username: str) -> dict:+ return storage.issue_account_setup_code(username = username)["account"]+++def _credentials(token):+ return authentication.HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)+++def _authenticate(token: str):+ from utils.account_context import _current # noqa: PLC0415++ before = _current.get()++ async def go():+ result = await authentication._get_current_credential(+ _credentials(token), allow_password_change = False+ )+ return result, current_account()++ try:+ return asyncio.run(go())+ finally:+ _current.set(before)+++def test_api_key_is_bound_from_the_row_it_was_validated_against(auth_db):+ alice = _managed("alice")+ raw = storage.create_api_key(alice["username"], name = "cli")[0]+ verified = storage.validate_api_key_account(raw)+ assert verified is not None+ record, secret = verified+ assert record["account_id"] == alice["account_id"]+ assert record["role"] == "user" and record["username"] == "alice"+ assert storage.validate_api_key_with_credential(raw) == ("alice", secret)+++def test_api_key_of_a_replaced_username_never_binds_the_replacement(auth_db, monkeypatch):+ old = _managed("alice")+ raw = storage.create_api_key("alice", name = "cli")[0]+ old_record, secret = storage.validate_api_key_account(raw)+ storage.delete_account(old["account_id"], lambda account: None)+ new = _managed("alice")+ assert new["account_id"] != old["account_id"]++ with pytest.raises(HTTPException) as exc:+ _authenticate(raw)+ assert exc.value.status_code == 401++ monkeypatch.setattr(+ authentication, "validate_api_key_account", lambda key: (old_record, secret)+ )+ (username, _generation), bound = _authenticate(raw)+ assert username == "alice"+ assert bound.account_id == old["account_id"]+ assert bound.account_id != new["account_id"]+++def test_api_key_of_a_deactivated_account_does_not_validate(auth_db):+ alice = _managed("alice")+ raw = storage.create_api_key("alice", name = "cli")[0]+ assert storage.validate_api_key_account(raw) is not None+ storage.set_account_active(alice["account_id"], False)+ assert storage.validate_api_key_account(raw) is None+ with pytest.raises(HTTPException) as exc:+ _authenticate(raw)+ assert exc.value.status_code == 401+++def test_owner_api_key_binds_the_owner(auth_db):+ raw = storage.create_api_key("unsloth", name = "cli")[0]+ (username, _generation), bound = _authenticate(raw)+ assert username == "unsloth"+ assert bound == OWNER+++def test_deactivated_account_keeps_full_access_closed_until_deleted(auth_db):+ assert policy.full_access_permitted() is True+ alice = _managed("alice")+ assert policy.login_mode() == "multi"+ assert policy.full_access_permitted() is False++ storage.set_account_active(alice["account_id"], False)+ assert policy.login_mode() == "single"+ assert policy.installation_is_multi_user() is False+ assert policy.managed_account_count() == 1+ assert policy.full_access_permitted() is False++ storage.set_account_active(alice["account_id"], True)+ assert policy.full_access_permitted() is False++ storage.delete_account(alice["account_id"], lambda account: None)+ assert policy.login_mode() == "single"+ assert policy.managed_account_count() == 0+ assert policy.full_access_permitted() is True+++def test_status_reports_full_access_with_a_deactivated_account(auth_db):+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+ from routes import auth as auth_routes++ app = FastAPI()+ app.include_router(auth_routes.router, prefix = "/api/auth")+ client = TestClient(app)+ assert client.get("/api/auth/status").json()["full_access"] is True+ alice = _managed("alice")+ storage.set_account_active(alice["account_id"], False)+ body = client.get("/api/auth/status").json()+ assert body["login_mode"] == "single"+ assert body["full_access"] is False+ assert "alice" not in client.get("/api/auth/status").text+++def test_the_owner_login_id_needs_no_account_lookup(auth_db, monkeypatch):+ """The owner's username is reserved, so its id is constant; a managed name must be resolved because it can be reused."""+ from routes import auth as auth_routes++ alice = _managed("alice")+ get_account = storage.get_account++ def unexpected(username):+ raise AssertionError("the owner's account id is fixed")++ monkeypatch.setattr(storage, "get_account", unexpected)+ assert auth_routes._account_id_of(storage.DEFAULT_ADMIN_USERNAME) == "owner"+ monkeypatch.setattr(storage, "get_account", get_account)+ assert auth_routes._account_id_of("alice") == alice["account_id"]+++def test_a_token_that_fails_to_verify_binds_nothing(auth_db):+ """Publishing the unverified ``sub`` claim into the request ContextVar before the signature check binds an account the caller never proved."""+ alice = _managed("alice")+ forged = jwt.encode({"sub": alice["username"]}, secrets.token_urlsafe(48), algorithm = "HS256")++ async def go():+ try:+ await authentication._get_current_credential(+ _credentials(forged), allow_password_change = False+ )+ except HTTPException as refused:+ return refused.status_code, current_account()+ raise AssertionError("a forged token must be refused")++ assert asyncio.run(go()) == (401, OWNER)+++def test_unreadable_auth_db_keeps_the_host_closed(auth_db, monkeypatch):+ def boom():+ raise OSError("auth.db unreadable")++ monkeypatch.setattr(storage, "account_counts", boom)+ policy.invalidate_account_cache()+ assert policy.login_mode() == "single"+ assert policy.full_access_permitted() is False+++def test_a_transient_auth_db_failure_is_not_cached(auth_db, monkeypatch):+ counts = storage.account_counts++ def boom():+ raise OSError("auth.db unreadable")++ monkeypatch.setattr(storage, "account_counts", boom)+ policy.invalidate_account_cache()+ assert policy.full_access_permitted() is False+ monkeypatch.setattr(storage, "account_counts", counts)+ assert policy.full_access_permitted() is Truediff --git a/studio/backend/tests/test_account_dataset_preview_access.py b/studio/backend/tests/test_account_dataset_preview_access.pynew file mode 100644index 00000000000..b4a86d180de--- /dev/null+++ b/studio/backend/tests/test_account_dataset_preview_access.py@@ -0,0 +1,133 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import json+from pathlib import Path++import pytest+from fastapi import HTTPException++from auth import policy+from hub.schemas.datasets import CheckFormatRequest+from hub.services.datasets import formatting+from hub.services.models import account_access+from utils import hf_cache_settings+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")++SECRET = "bob-private-row"+++def _cache_dataset(cache: Path, repo: str, text: str) -> Path:+ owner, name = repo.split("/")+ snapshot = cache / f"datasets--{owner}--{name}" / "snapshots" / "rev"+ snapshot.mkdir(parents = True)+ (snapshot / "train.jsonl").write_text(+ json.dumps({"instruction": "q", "output": text}) + "\n",+ encoding = "utf-8",+ )+ return snapshot+++def shared_cache(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(formatting, "ensure_audio_decoding", lambda: True)+ cache = tmp_path / "hub-cache"+ cache.mkdir()+ _cache_dataset(cache, "private/set", SECRET)+ _cache_dataset(cache, "public/set", "public-row")+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(cache))+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])+ monkeypatch.setattr(account_access, "model_grants", lambda: set())+ monkeypatch.setattr(+ account_access,+ "repo_is_public",+ lambda repo_id, repo_type = "model": not repo_id.startswith("private/"),+ )+ # The shared cache-read gate answers for the credential; the account gate is under test.+ from hub.utils import hf_tokens++ monkeypatch.setattr(+ hf_tokens,+ "cache_reads_authorized",+ lambda hf_token, **kwargs: True,+ )+ return cache+++def _preview(dataset_name: str, prefer_local_cache: bool = True):+ return run_as(+ ALICE,+ formatting.check_format_response,+ CheckFormatRequest(+ dataset_name = dataset_name,+ prefer_local_cache = prefer_local_cache,+ ),+ "bogus-token",+ )+++def offline_hub(monkeypatch):+ class _NoHubApi:+ def __init__(self, *args, **kwargs):+ pass++ def list_repo_files(self, *args, **kwargs):+ raise ConnectionError("offline")++ import datasets++ real_load_dataset = datasets.load_dataset++ def _offline_load_dataset(*args, **kwargs):+ if "path" in kwargs:+ raise ConnectionError("offline")+ return real_load_dataset(*args, **kwargs)++ monkeypatch.setattr("huggingface_hub.HfApi", _NoHubApi)+ monkeypatch.setattr(datasets, "load_dataset", _offline_load_dataset)+++def test_managed_account_cannot_preview_another_accounts_cached_private_dataset(shared_cache):+ with pytest.raises(HTTPException) as exc:+ _preview("private/set")+ assert exc.value.status_code == 404+ assert SECRET not in json.dumps(exc.value.detail)+++def test_managed_account_still_previews_a_public_cached_dataset(shared_cache):+ response = _preview("public/set")+ assert SECRET not in json.dumps(response.preview_samples)+ assert response.preview_samples+++def test_managed_account_still_previews_its_own_granted_cached_dataset(shared_cache, monkeypatch):+ monkeypatch.setattr(account_access, "model_grants", lambda: {"dataset:private/set"})+ response = _preview("private/set")+ assert response.preview_samples+++def test_owner_preview_is_unchanged(shared_cache):+ response = formatting.check_format_response(+ CheckFormatRequest(dataset_name = "private/set", prefer_local_cache = True),+ "bogus-token",+ )+ assert response.preview_samples+++def test_online_fallback_cannot_reach_another_accounts_cached_private_dataset(+ shared_cache, offline_hub+):+ with pytest.raises(Exception) as exc:+ _preview("private/set", prefer_local_cache = False)+ assert SECRET not in json.dumps(getattr(exc.value, "detail", str(exc.value)))+++def test_online_fallback_still_serves_a_public_cached_dataset(shared_cache, offline_hub):+ assert _preview("public/set", prefer_local_cache = False).preview_samplesdiff --git a/studio/backend/tests/test_account_deactivated_account_fences.py b/studio/backend/tests/test_account_deactivated_account_fences.pynew file mode 100644index 00000000000..f79d421583a--- /dev/null+++ b/studio/backend/tests/test_account_deactivated_account_fences.py@@ -0,0 +1,197 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Deactivating the last managed account must not open the foreign-work fences.++set_account_active() only signals a generation; it does not wait for it to unwind, and a+wedged producer can hold its GPU reservation indefinitely. Dropping the ACTIVE count to one+makes installation_is_multi_user() False while the deactivated account's chat generation and+its supervisor task are both still live, so every fence keyed on the login mode opens:+the owner tears the shared backend down underneath that generation, and an owner run reusing+the same client-chosen run id is admitted into a slot the foreign supervisor task still owns.+Both must key on account_scope() / installation_has_managed_accounts() instead.+"""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from routes import chat_generation_runs as run_routes+from routes import inference+from state import active_generations+from utils.account_context import (+ OWNER,+ AccountContext,+ arun_as,+ bind_account,+ reset_account,+ run_as,+)++ALICE = AccountContext("a" * 32, "alice")+++def deactivatable(monkeypatch, tmp_path):+ """A one-managed-account install whose only managed account can be deactivated."""+ multi = {"value": True}+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: multi["value"])+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_generation_accounts", {})+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ active_generations.reset_for_tests()+ yield multi+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(inference.router, prefix = "/api/inference")+ app.include_router(inference.studio_router, prefix = "/api/inference")+ return TestClient(app)+++def test_owner_unload_refuses_a_deactivated_accounts_live_generation(deactivatable):+ """Item 3971721488: /unload's resident-control fence and the active-generation+ refusal both go blind once the sole managed account is deactivated."""+ event = threading.Event()+ with run_as(ALICE, active_generations.ActiveGeneration, event, model = "org/alice-private"):+ deactivatable["value"] = False+ assert policy.installation_is_multi_user() is False+ assert policy.installation_has_managed_accounts() is True+ with client_for(OWNER) as client:+ response = client.post(+ "/api/inference/unload",+ json = {"model_path": "org/public", "force_cancel_active": True},+ )+ assert response.status_code == 409, response.text+ assert response.json()["error"] == "gpu_busy"+ assert not event.is_set()+++def test_swap_gate_still_sees_a_deactivated_accounts_generation(deactivatable):+ """The refusal-only half of the same gate, called directly: account_scope() counts+ zero owner generations and returns before require_no_foreign_generations()."""+ event = threading.Event()+ with run_as(ALICE, active_generations.ActiveGeneration, event, model = "org/alice-private"):+ deactivatable["value"] = False+ with pytest.raises(HTTPException) as excinfo:+ run_as(+ OWNER,+ lambda: inference._raise_or_cancel_active_generations(+ force = True, action = "Unloading", cancel = True+ ),+ )+ assert excinfo.value.status_code == 409+ assert excinfo.value.detail["error"] == "gpu_busy"+ assert not event.is_set()+++def test_owner_idle_fence_stays_on_for_a_deactivated_accounts_work(deactivatable):+ """require_idle_other_accounts / foreign_work_active are ownership fences, not login mode."""+ event = threading.Event()+ with run_as(ALICE, active_generations.ActiveGeneration, event, model = "org/alice-private"):+ deactivatable["value"] = False+ assert run_as(OWNER, access.foreign_work_active) is True+ with pytest.raises(HTTPException) as excinfo:+ run_as(OWNER, access.require_idle_other_accounts)+ assert excinfo.value.status_code == 409+++async def test_owner_run_cannot_take_a_deactivated_accounts_supervisor_slot(+ deactivatable, monkeypatch+):+ """Item 3971721497: the supervisor keys tasks by bare run id, so an owner run reusing+ a live foreign id commits a queued row that supervisor.start() then silently drops."""+ event = threading.Event()+ with run_as(+ ALICE,+ active_generations.ActiveGeneration,+ event,+ model = "local",+ run_id = "run-1",+ thread_id = "thread-1",+ ):+ deactivatable["value"] = False+ started: list = []+ # A live task under the bare id: start() returns without scheduling anything.+ supervisor = SimpleNamespace(+ _tasks = {"run-1": object()},+ start = lambda run_id, **identity: started.append(run_id),+ )+ request = SimpleNamespace(+ app = SimpleNamespace(state = SimpleNamespace(chat_generation_supervisor = supervisor))+ )+ committed: list = []++ def create_run(**kwargs):+ committed.append(kwargs["run_id"])+ return (+ {+ "id": "run-1",+ "status": "queued",+ "threadId": "thread-1",+ "requestPayload": {"model": "local"},+ },+ True,+ )++ monkeypatch.setattr(run_routes.db, "create_run", create_run)+ payload = run_routes.CreateChatGenerationRun(+ runId = "run-1",+ threadId = "thread-1",+ userMessageId = "user-1",+ assistantMessageId = "assistant-1",+ requestPayload = {+ "model": "local",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ )+ with pytest.raises(HTTPException) as excinfo:+ await arun_as(+ OWNER,+ run_routes.create_chat_generation_run(payload, request, OWNER.username),+ )+ assert excinfo.value.status_code == 404+ assert committed == []+++def test_supervisor_run_id_fence_stays_on_after_deactivation(deactivatable):+ """The gate on its own, so the failure is readable without the route harness."""+ event = threading.Event()+ with run_as(+ ALICE,+ active_generations.ActiveGeneration,+ event,+ model = "local",+ run_id = "run-1",+ thread_id = "thread-1",+ ):+ deactivatable["value"] = False+ with pytest.raises(HTTPException) as excinfo:+ run_as(OWNER, run_routes._require_available_supervisor_run_id, "run-1")+ assert excinfo.value.status_code == 404diff --git a/studio/backend/tests/test_account_deactivation_fence.py b/studio/backend/tests/test_account_deactivation_fence.pynew file mode 100644index 00000000000..b15a07fa792--- /dev/null+++ b/studio/backend/tests/test_account_deactivation_fence.py@@ -0,0 +1,42 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A generation that registers after its account was disabled starts cancelled.++Deactivation cancels the generations registered at that instant. A request already past+authentication and waiting on a gate registers afterwards, so the fence set alongside the sweep+has to reach it too, and reactivation lifts it."""++import threading++from auth import storage+from state import active_generations+from studio.backend.tests.test_account_lifecycle import auth_env, headers, matrix # noqa: F401+from utils.account_context import run_as+++def _register(account):+ event = threading.Event()+ with run_as(account, active_generations.ActiveGeneration, event):+ return event.is_set()+++def test_late_registration_after_deactivation_is_cancelled(matrix):+ client, _, _ = matrix+ alice = storage.get_account("alice")+ assert _register(alice) is False+ url = f"/api/accounts/{alice.account_id}"+ assert client.patch(url, headers = headers(), json = {"is_active": False}).status_code == 200+ print(f"fenced after deactivation: {_register(alice)}")+ assert _register(alice) is True+ bob = storage.get_account("bob")+ assert _register(bob) is False+ assert client.patch(url, headers = headers(), json = {"is_active": True}).status_code == 200+ assert _register(alice) is False+++def test_retirement_fences_late_registration(matrix):+ client, _, _ = matrix+ alice = storage.get_account("alice")+ assert client.delete(f"/api/accounts/{alice.account_id}", headers = headers()).status_code == 204+ assert _register(alice) is Truediff --git a/studio/backend/tests/test_account_desktop_network.py b/studio/backend/tests/test_account_desktop_network.pynew file mode 100644index 00000000000..2473ba56809--- /dev/null+++ b/studio/backend/tests/test_account_desktop_network.py@@ -0,0 +1,418 @@+# 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 asyncio+import io+import secrets+import time+from types import SimpleNamespace++import pytest+from fastapi import Depends, FastAPI, HTTPException+from fastapi.testclient import TestClient+from starlette.requests import Request+from starlette.responses import StreamingResponse++from auth import authentication, policy, storage+from auth.bootstrap_timeout import enforce_bootstrap_password_deadline+from routes import auth as auth_routes+from utils import keyless_api_access as keyless+from utils.account_context import OWNER, arun_as, current_account, current_account_id, run_as++[email protected](autouse = True)+def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ keyless._reset_scope_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield+ policy.invalidate_account_cache()+ keyless._reset_scope_cache()+++def add_managed(*, must_change = False):+ storage.create_initial_user(+ "alice",+ "alice-password",+ secrets.token_urlsafe(32),+ must_change_password = must_change,+ )+ return storage.get_account("alice")+++def client():+ app = FastAPI()+ app.state.secure = True+ app.state.bind_host = "127.0.0.1"+ app.state.cloudflare_url = "https://shared.trycloudflare.com"+ app.include_router(auth_routes.router, prefix = "/api/auth")+ app.add_middleware(keyless.KeylessToolPolicyMiddleware)++ @app.get("/account")+ async def account(subject = Depends(authentication.get_current_subject)):+ return {"subject": subject, "account_id": current_account_id()}++ @app.get(+ "/owner",+ dependencies = [+ Depends(authentication.get_current_subject),+ Depends(policy.require_owner),+ ],+ )+ async def owner():+ return {"account_id": current_account_id()}++ @app.api_route("/events", methods = ["GET", "POST"])+ async def events(subject = Depends(authentication.get_current_subject)):+ async def stream():+ await asyncio.sleep(0)+ yield f"data: {subject}:{current_account_id()}\n\n"++ return StreamingResponse(stream(), media_type = "text/event-stream")++ return TestClient(app, client = ("127.0.0.1", 55000))+++def test_desktop_multi_validates_secret_and_never_mints_tokens(monkeypatch):+ raw = storage.create_desktop_secret()+ add_managed()++ def no_token(**kwargs):+ pytest.fail("Multi-account desktop auth must not mint a session")++ monkeypatch.setattr(auth_routes, "create_access_token", no_token)+ monkeypatch.setattr(auth_routes, "create_refresh_token", no_token)+ with client() as http:+ response = http.post("/api/auth/desktop-login", json = {"secret": raw})+ assert response.status_code == 200+ assert response.content == b'{"login_required":true,"login_mode":"multi"}'+ assert http.post("/api/auth/desktop-login", json = {"secret": raw + "x"}).status_code == 401+++def test_desktop_single_response_bytes_and_return_to_single(monkeypatch):+ raw = storage.create_desktop_secret()+ minted = []++ def access(**kwargs):+ minted.append(kwargs)+ return "access"++ monkeypatch.setattr(auth_routes, "create_access_token", access)+ monkeypatch.setattr(auth_routes, "create_refresh_token", lambda **kwargs: "refresh")+ expected = (+ b'{"access_token":"access","refresh_token":"refresh","token_type":"bearer",'+ b'"must_change_password":false,"account_id":"owner"}'+ )+ with client() as http:+ single = http.post("/api/auth/desktop-login", json = {"secret": raw})+ assert single.content == expected+ add_managed()+ assert http.post("/api/auth/desktop-login", json = {"secret": raw}).json()["login_required"]+ storage.delete_user("alice")+ assert http.post("/api/auth/desktop-login", json = {"secret": raw}).content == expected+ assert len(minted) == 2+ assert all(+ call == {"subject": "unsloth", "desktop": True, "secret": storage.get_jwt_secret("unsloth")}+ for call in minted+ )++[email protected]("desktop", [False, True])+def test_managed_account_cannot_set_desktop_initial_password(desktop):+ add_managed(must_change = True)+ before = storage.get_user_and_secret("alice")+ token = authentication.create_access_token(subject = "alice", desktop = desktop)+ with client() as http:+ response = http.post(+ "/api/auth/desktop-initial-password",+ headers = {"Authorization": f"Bearer {token}"},+ json = {"new_password": "changed-password"},+ )+ assert response.status_code == 403+ assert storage.get_user_and_secret("alice") == before+++def request(+ *,+ scope = "full",+ lan = False,+ headers = None,+):+ address = "192.168.1.2" if lan else "127.0.0.1"+ app = SimpleNamespace(+ state = SimpleNamespace(+ bind_host = address,+ secure = False,+ cloudflare_url = None,+ lan_access_launch_managed = lan,+ lan_access_launch_addresses = [address] if lan else [],+ lan_access_port = 8888,+ )+ )+ return Request(+ {+ "type": "http",+ "method": "GET",+ "path": "/v1/models" if scope == "inference" else "/account",+ "root_path": "",+ "query_string": b"",+ "scheme": "http",+ "server": (address, 8888),+ "client": ("192.168.1.3" if lan else "127.0.0.1", 55000),+ "headers": [(b"host", f"{address}:8888".encode()), *(headers or [])],+ "app": app,+ }+ )++[email protected]("scope,lan", [("full", False), ("inference", False), ("inference", True)])[email protected]("bearer", [None, "not-needed", "lm-studio", "ollama"])+def test_keyless_refused_for_every_multi_account_entry(scope, lan, bearer, monkeypatch):+ monkeypatch.setattr(keyless, "get_keyless_api_access_scope", lambda: scope)+ headers = [] if bearer is None else [(b"authorization", f"Bearer {bearer}".encode())]+ req = request(scope = scope, lan = lan, headers = headers)+ assert keyless.keyless_request_allowed(req)+ alice = add_managed()+ assert not keyless.keyless_request_allowed(req)+ assert not keyless.asgi_request_is_keyless(req.scope, (scope, True))++ async def resolve():+ return await authentication.get_current_subject(await authentication.security(req))++ with pytest.raises(HTTPException) as error:+ asyncio.run(arun_as(alice, resolve()))+ assert error.value.status_code == 401+ storage.delete_user("alice")+ assert keyless.keyless_request_allowed(req)++[email protected]("bearer", [None, "not-needed"])+def test_single_keyless_admission_explicitly_rebinds_owner(bearer, monkeypatch):+ alice = add_managed()+ storage.delete_user("alice")+ monkeypatch.setattr(keyless, "get_keyless_api_access_scope", lambda: "full")+ headers = [] if bearer is None else [(b"authorization", f"Bearer {bearer}".encode())]+ req = request(headers = headers)++ async def resolve():+ credentials = await authentication.security(req)+ subject = await authentication.get_current_subject(credentials)+ return subject, current_account()++ assert asyncio.run(arun_as(alice, resolve())) == ("unsloth", OWNER)+++def test_recorded_keyless_admission_is_refused_after_account_creation(monkeypatch):+ req = request()+ keyless.mark_keyless_admission(req, True)+ assert keyless.request_was_admitted_keyless(req) is True+ add_managed()+ assert keyless.request_was_admitted_keyless(req) is False+ with pytest.raises(HTTPException):+ asyncio.run(authentication.security(req))++[email protected]("subject", ["unsloth", "alice"])[email protected]("credential", ["jwt", "api_key"])[email protected]("transport", ["tunnel", "lan"])+def test_network_request_uses_account_credentials(subject, credential, transport, monkeypatch):+ alice = add_managed()+ monkeypatch.setattr(keyless, "_read_settings", lambda: ("full", True))+ token = (+ authentication.create_access_token(subject = subject)+ if credential == "jwt"+ else storage.create_api_key(subject, "network")[0]+ )+ headers = {"Authorization": f"Bearer {token}", "Host": "192.168.1.2:8888"}+ if transport == "tunnel":+ headers.update({"Host": "shared.trycloudflare.com", "cf-connecting-ip": "203.0.113.7"})+ expected = OWNER.account_id if subject == "unsloth" else alice.account_id+ with client() as http:+ response = http.get("/account", headers = headers)+ assert response.status_code == 200+ assert response.json() == {"subject": subject, "account_id": expected}+ assert http.get("/owner", headers = headers).status_code == (+ 200 if subject == "unsloth" else 403+ )+ for method in ("GET", "POST"):+ response = http.request(method, "/events", headers = headers)+ assert response.status_code == 200+ assert response.text == f"data: {subject}:{expected}\n\n"+ assert current_account() == OWNER++[email protected]("bearer", [None, "not-needed", "invalid-token"])+def test_tunnel_never_admits_keyless_even_with_one_account(bearer, monkeypatch):+ monkeypatch.setattr(keyless, "_read_settings", lambda: ("full", True))+ headers = {"Host": "shared.trycloudflare.com", "cf-connecting-ip": "203.0.113.7"}+ if bearer:+ headers["Authorization"] = f"Bearer {bearer}"+ with client() as http:+ assert http.get("/account", headers = headers).status_code == 401+++def test_bootstrap_html_single_bytes_and_multi_suppression(monkeypatch):+ import main+ import secrets as secrets_module++ monkeypatch.setattr(storage, "requires_password_change", lambda username: username == "unsloth")+ monkeypatch.setattr(secrets_module, "token_urlsafe", lambda size: "fixed-nonce")+ app = SimpleNamespace(state = SimpleNamespace(bootstrap_password = "owner-bootstrap"))+ html = b"<html><head></head><body>Studio</body></html>"+ expected = b'<html><head><script nonce="fixed-nonce">window.__UNSLOTH_BOOTSTRAP__={"username": "unsloth", "password": "owner-bootstrap"}</script></head><body>Studio</body></html>'+ assert main._inject_bootstrap(html, app) == (expected, "fixed-nonce")+ add_managed()+ assert main._inject_bootstrap(html, app) == (html, None)+ storage.delete_user("alice")+ assert main._inject_bootstrap(html, app) == (expected, "fixed-nonce")+++def test_bootstrap_html_stays_suppressed_while_a_deactivated_account_exists(monkeypatch):+ import main+ import secrets as secrets_module++ monkeypatch.setattr(storage, "requires_password_change", lambda username: username == "unsloth")+ monkeypatch.setattr(secrets_module, "token_urlsafe", lambda size: "fixed-nonce")+ app = SimpleNamespace(state = SimpleNamespace(bootstrap_password = "owner-bootstrap"))+ html = b"<html><head></head><body>Studio</body></html>"+ account = add_managed()+ storage.set_account_active(account.account_id, False)+ policy.invalidate_account_cache()+ assert policy.installation_is_multi_user() is False+ assert main._inject_bootstrap(html, app) == (html, None)+++def test_secure_banner_bytes_and_shared_url_survive_account_creation(monkeypatch, capsys):+ import run+ import startup_banner++ monkeypatch.setattr(run, "_cloudflare_url", "https://shared.trycloudflare.com")+ monkeypatch.setattr(run, "_public_reachable", None)+ monkeypatch.setattr(startup_banner, "stdout_supports_color", lambda: False)+ divider = "─" * 52+ expected = (+ "\n🦥 Unsloth Studio is running (secure)\n"+ f"{divider}\n"+ " Secure link access via Cloudflare: https://shared.trycloudflare.com\n"+ " On this machine only: http://127.0.0.1:8888/\n"+ f"{divider}\n"+ "Server-side tools are DISABLED (--disable-tools).\n"+ "\n To stop Unsloth Studio: press Ctrl+C (Control+C, not Command+C, on macOS).\n"+ f"{divider}\n\n"+ ).encode()+ run._emit_secure_startup_output(8888, enable_tools = False)+ assert capsys.readouterr().out.encode() == expected+ add_managed()+ run._emit_secure_startup_output(8888, enable_tools = False)+ assert capsys.readouterr().out.encode() == expected++[email protected]("owner_pending", [False, True])+def test_timeout_checks_only_owner_even_in_managed_context(owner_pending, monkeypatch, capsys):+ alice = add_managed(must_change = True)+ checked = []+ stopped = []++ def pending(username):+ checked.append(username)+ return owner_pending if username == "unsloth" else True++ monkeypatch.setattr(storage, "requires_password_change", pending)+ result = run_as(+ alice,+ enforce_bootstrap_password_deadline,+ storage,+ lambda: stopped.append(True),+ timeout_seconds = 1,+ )+ assert result is owner_pending+ assert checked == ["unsloth"]+ assert bool(stopped) is owner_pending+ assert "alice" not in capsys.readouterr().err+++def test_terminal_gate_ignores_managed_setup_and_changes_only_owner(monkeypatch):+ import run+ from auth import terminal_prompt++ alice = add_managed(must_change = True)+ output = io.StringIO()+ monkeypatch.setattr(run.sys, "stderr", output)+ monkeypatch.setattr(run, "_stream_isatty", lambda stream: True)+ kwargs = dict(+ tunnel_will_start = True, host = "127.0.0.1", secure = True, api_only = False, frontend_served = True+ )+ assert run_as(alice, run._terminal_password_gate, **kwargs) == (True, False)+ assert output.getvalue() == ""+ before = storage.get_user_and_secret("alice")+ with storage.get_connection() as connection:+ connection.execute(+ "UPDATE auth_user SET must_change_password = 1 WHERE username = 'unsloth'"+ )+ keys = iter("new-owner-password\nnew-owner-password\n")+ monkeypatch.setattr(terminal_prompt, "_getch", lambda: next(keys))+ assert run_as(alice, run._terminal_password_gate, **kwargs) == (True, True)+ assert "Password updated for 'unsloth'." in output.getvalue()+ assert "alice" not in output.getvalue()+ assert storage.get_user_and_secret("alice") == before+++def _request(path, headers):+ scope = {+ "type": "http",+ "method": "GET",+ "path": path,+ "query_string": b"",+ "headers": [(k.encode(), v.encode()) for k, v in headers.items()],+ "app": SimpleNamespace(state = SimpleNamespace()),+ }+ return Request(scope)+++def test_desktop_secret_authenticates_the_shell_health_probe(monkeypatch):+ """On a multi-account install desktop-login mints nothing, so the secret itself is the credential."""+ import main++ raw = storage.create_desktop_secret()+ add_managed()++ async def no_wait(budget):+ return None++ monkeypatch.setattr(main, "_await_hardware_detection", no_wait)+ health = main.health_check++ body = asyncio.run(health(_request("/api/health", {"x-desktop-secret": raw})))+ assert body.get("version")+ body = asyncio.run(health(_request("/api/health", {})))+ assert "version" not in body+ with pytest.raises(HTTPException) as refused:+ asyncio.run(health(_request("/api/health", {"x-desktop-secret": raw + "x"})))+ assert refused.value.status_code == 401+++def test_desktop_secret_stops_the_backend_it_owns(monkeypatch):+ import main++ raw = storage.create_desktop_secret()+ add_managed()+ app = FastAPI()+ fired = []+ app.state.trigger_shutdown = lambda: fired.append(True)+ app.add_api_route("/api/desktop/shutdown", main.desktop_shutdown_server, methods = ["POST"])+ with TestClient(app) as http:+ assert http.post("/api/desktop/shutdown").status_code == 401+ assert (+ http.post("/api/desktop/shutdown", headers = {"X-Desktop-Secret": raw + "x"}).status_code+ == 401+ )+ response = http.post("/api/desktop/shutdown", headers = {"X-Desktop-Secret": raw})+ assert response.status_code == 200+ assert response.json() == {"status": "shutting_down"}+ deadline = time.monotonic() + 5+ while not fired and time.monotonic() < deadline:+ time.sleep(0.05)+ assert fireddiff --git a/studio/backend/tests/test_account_downgrade_fence.py b/studio/backend/tests/test_account_downgrade_fence.pynew file mode 100644index 00000000000..a6f2df0a8f9--- /dev/null+++ b/studio/backend/tests/test_account_downgrade_fence.py@@ -0,0 +1,216 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A build without account support cannot authenticate a managed account: its credentials live in columns that build never reads, behind a hash prefix it never computes, while the owner's row is unchanged."""++import secrets+import sqlite3++import jwt+import pytest++from auth import policy, storage+from auth.hashing import verify_password+++def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield storage+ policy.invalidate_account_cache()+++def _legacy(username: str) -> sqlite3.Row:+ """The row exactly as a build without account support reads it."""+ conn = sqlite3.connect(storage.DB_PATH)+ conn.row_factory = sqlite3.Row+ try:+ return conn.execute(+ "SELECT password_salt, password_hash, jwt_secret, must_change_password "+ "FROM auth_user WHERE username = ?",+ (username,),+ ).fetchone()+ finally:+ conn.close()+++def _legacy_lookup(table: str, column: str, digest: str):+ conn = sqlite3.connect(storage.DB_PATH)+ try:+ return conn.execute(+ f"SELECT username FROM {table} WHERE {column} = ?", (digest,)+ ).fetchone()+ finally:+ conn.close()+++def _set_up_alice(password: str = "alice-password-1") -> dict:+ account = storage.issue_account_setup_code(username = "alice")+ record = storage.authenticate_account_login("alice", account["setup_code"])+ assert record is not None+ _salt, pwd_hash, secret, must_change = record+ assert must_change+ new_secret = storage.update_account_password(+ "alice", password, expect_password_hash = pwd_hash, expect_secret = secret+ )+ assert new_secret+ return account["account"]+++def test_owner_row_is_byte_for_byte_legacy(auth_db):+ legacy = _legacy("unsloth")+ assert verify_password("owner-password", legacy["password_salt"], legacy["password_hash"])+ assert storage.get_jwt_secret("unsloth") == legacy["jwt_secret"]+ raw, _row = storage.create_api_key("unsloth", name = "cli")+ assert _legacy_lookup("api_keys", "key_hash", storage._pbkdf2_api_key(raw)) is not None+ storage.save_refresh_token("tok", "unsloth", "2999-01-01T00:00:00+00:00")+ assert _legacy_lookup("refresh_tokens", "token_hash", storage._hash_token("tok")) is not None+++def test_managed_password_never_verifies_on_the_legacy_columns(auth_db):+ _set_up_alice()+ assert storage.authenticate_account_login("alice", "alice-password-1") is not None+ legacy = _legacy("alice")+ assert not verify_password("alice-password-1", legacy["password_salt"], legacy["password_hash"])+ assert legacy["password_hash"] == "managed-account"+++def test_managed_tokens_do_not_verify_with_the_legacy_secret(auth_db):+ _set_up_alice()+ real = storage.get_jwt_secret("alice")+ legacy = _legacy("alice")["jwt_secret"]+ assert real and legacy and real != legacy+ token = jwt.encode({"sub": "alice"}, real, algorithm = "HS256")+ assert jwt.decode(token, real, algorithms = ["HS256"])["sub"] == "alice"+ with pytest.raises(jwt.InvalidSignatureError):+ jwt.decode(token, legacy, algorithms = ["HS256"])+++def test_managed_api_keys_and_refresh_tokens_are_invisible_to_a_plain_lookup(auth_db):+ _set_up_alice()+ raw, _row = storage.create_api_key("alice", name = "cli")+ assert _legacy_lookup("api_keys", "key_hash", storage._pbkdf2_api_key(raw)) is None+ verified = storage.validate_api_key_account(raw)+ assert verified is not None and verified[0]["username"] == "alice"++ storage.save_refresh_token("alice-refresh", "alice", "2999-01-01T00:00:00+00:00")+ assert (+ _legacy_lookup("refresh_tokens", "token_hash", storage._hash_token("alice-refresh")) is None+ )+ assert storage.verify_refresh_token("alice-refresh") == ("alice", False)+ consumed = storage.consume_refresh_token("alice-refresh")+ assert consumed is not None and consumed[0] == "alice"+ assert consumed[2] == storage.get_jwt_secret("alice")+++def test_every_managed_credential_path_stays_fenced(auth_db):+ alice = _set_up_alice()+ storage.issue_account_setup_code(account_id = alice["account_id"])+ assert _legacy("alice")["password_hash"] == "managed-account"+ storage.set_account_active(alice["account_id"], False)+ storage.set_account_active(alice["account_id"], True)+ assert _legacy("alice")["jwt_secret"] != storage.get_jwt_secret("alice")+ storage.update_password("alice", "alice-password-2")+ assert _legacy("alice")["password_hash"] == "managed-account"+ assert storage.get_user_and_secret("alice") is not None+ salt, pwd_hash, _secret, _change = storage.get_user_and_secret("alice")+ assert verify_password("alice-password-2", salt, pwd_hash)+++def test_rows_written_before_the_fence_are_moved_behind_it(auth_db):+ conn = sqlite3.connect(storage.DB_PATH)+ try:+ conn.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret, must_change_password, "+ "account_id, role, is_active, created_at) VALUES ('bob', 's', 'h', 'legacy-secret', 0, 'bob-id', 'user', 1, 'now')"+ )+ conn.execute(+ "INSERT INTO api_keys (username, key_prefix, key_hash, name, created_at) VALUES ('bob', 'p', 'plainhash', 'k', 'now')"+ )+ conn.execute(+ "INSERT INTO refresh_tokens (token_hash, username, expires_at) VALUES ('plaintoken', 'bob', '2999-01-01T00:00:00+00:00')"+ )+ conn.commit()+ storage._fence_managed_credentials(conn)+ conn.commit()+ conn.row_factory = sqlite3.Row+ row = conn.execute("SELECT * FROM auth_user WHERE username = 'bob'").fetchone()+ assert row["account_jwt_secret"] == "legacy-secret" and row["jwt_secret"] != "legacy-secret"+ assert row["account_password_hash"] == "h" and row["password_hash"] == "managed-account"+ assert (+ conn.execute("SELECT key_hash FROM api_keys WHERE username = 'bob'").fetchone()[0]+ == "account:plainhash"+ )+ assert (+ conn.execute("SELECT token_hash FROM refresh_tokens WHERE username = 'bob'").fetchone()[+ 0+ ]+ == "account:plaintoken"+ )+ storage._fence_managed_credentials(conn)+ assert (+ conn.execute("SELECT key_hash FROM api_keys WHERE username = 'bob'").fetchone()[0]+ == "account:plainhash"+ )+ owner = conn.execute("SELECT * FROM auth_user WHERE username = 'unsloth'").fetchone()+ assert owner["account_jwt_secret"] is None+ finally:+ conn.close()+ assert storage.get_jwt_secret("bob") == "legacy-secret"+++def _owner_row(column: str):+ conn = sqlite3.connect(storage.DB_PATH)+ try:+ return conn.execute(+ f"SELECT {column} FROM auth_user WHERE username = ?",+ (storage.DEFAULT_ADMIN_USERNAME,),+ ).fetchone()[0]+ finally:+ conn.close()+++def test_an_owner_seeded_by_an_older_build_gets_its_account_id_back(tmp_path, monkeypatch):+ """Columns present, owner row unbacked: without a repair every request 500s."""+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ storage.get_connection().close()+ conn = sqlite3.connect(storage.DB_PATH)+ with conn:+ conn.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret) "+ "VALUES (?, 'salt', 'hash', 'secret')",+ (storage.DEFAULT_ADMIN_USERNAME,),+ )+ conn.close()+ assert _owner_row("account_id") is None+ assert _owner_row("role") == "user"++ restarted = tmp_path / "restarted.db"+ source, target = sqlite3.connect(storage.DB_PATH), sqlite3.connect(restarted)+ with target:+ source.backup(target)+ source.close()+ target.close()+ monkeypatch.setattr(storage, "DB_PATH", restarted)+ storage.get_connection().close()+ owner = storage.get_account(storage.DEFAULT_ADMIN_USERNAME)+ assert (owner.account_id, owner.role) == ("owner", "owner")+ assert _owner_row("created_at")++ statements = []+ connect = sqlite3.connect++ def traced(*args, **kwargs):+ conn = connect(*args, **kwargs)+ conn.set_trace_callback(statements.append)+ return conn++ monkeypatch.setattr(sqlite3, "connect", traced)+ storage.get_connection().close()+ assert statements and not [query for query in statements if "UPDATE auth_user" in query]diff --git a/studio/backend/tests/test_account_download_idle_status.py b/studio/backend/tests/test_account_download_idle_status.pynew file mode 100644index 00000000000..a78428c7136--- /dev/null+++ b/studio/backend/tests/test_account_download_idle_status.py@@ -0,0 +1,95 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account must be able to observe an idle download it does not own a job for."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from hub.services import download_lifecycle+from hub.services.models import account_access as access+from hub.services.models import downloads as model_downloads+from hub.utils import download_registry+from utils.account_context import AccountContext, arun_as, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_public_repos", {})+ monkeypatch.setattr(download_lifecycle, "_job_accounts", {})+ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: (_ for _ in ()).throw(OSError("offline"))+ ),+ )+++def test_status_for_a_repo_with_no_job_is_idle_for_a_managed_account():+ registry = download_registry.DownloadRegistry()+ key = "org/model::"+ state, error, generation = run_as(+ BOB,+ lambda: download_lifecycle.idle_status(+ registry, key, repo_type = "model", repo_id = "org/model", variant = None+ ),+ )+ assert (state, error, generation) == ("idle", None, 0)+++def test_hydrating_after_a_restart_settles_instead_of_404ing_forever():+ """The registry and the ownership map are in-memory, so a restart leaves the client's+ persisted active download with no entry at all; its status poll must settle."""+ before = download_registry.DownloadRegistry()+ key = "org/model::"+ before.claim(key, "http", repo_type = "model", repo_id = "org/model")+ run_as(ALICE, download_lifecycle.record_download_account, before, key)++ after_restart = download_registry.DownloadRegistry()+ state, _, _ = run_as(+ ALICE,+ lambda: download_lifecycle.idle_status(+ after_restart, key, repo_type = "model", repo_id = "org/model", variant = None+ ),+ )+ assert state == "idle"+++def test_status_route_reports_idle_for_a_managed_account(monkeypatch):+ registry = download_registry.DownloadRegistry()+ monkeypatch.setattr(model_downloads, "_registry", registry)+ monkeypatch.setattr(+ model_downloads, "resolve_cached_repo_id_case", lambda repo_id, **k: repo_id+ )+ status = asyncio.run(+ arun_as(BOB, model_downloads.get_download_status_response("org/model", ""))+ )+ assert status.state == "idle"+++def test_another_accounts_live_job_stays_hidden():+ registry = download_registry.DownloadRegistry()+ key = "org/secret::"+ registry.set_job(key, "running")+ download_lifecycle._job_accounts[(id(registry), key)] = ALICE.account_id+ with pytest.raises(HTTPException) as exc:+ run_as(+ BOB,+ lambda: download_lifecycle.idle_status(+ registry, key, repo_type = "model", repo_id = "org/secret", variant = None+ ),+ )+ assert exc.value.status_code == 404+ assert run_as(ALICE, download_lifecycle.download_belongs_to_account, registry, key)diff --git a/studio/backend/tests/test_account_download_retirement_race.py b/studio/backend/tests/test_account_download_retirement_race.pynew file mode 100644index 00000000000..e6fadd3978b--- /dev/null+++ b/studio/backend/tests/test_account_download_retirement_race.py@@ -0,0 +1,176 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A download request caught mid-flight by retirement must not reach spawn.++Retirement scans the download registries for jobs to cancel. A request that is still inside a+pre-claim await owns no registry entry yet, so the scan reports clean retirement and the request+then claims a key and launches a worker holding the deleted account's captured token."""++from __future__ import annotations++import asyncio+import subprocess+import threading++import pytest+from fastapi import HTTPException++from auth import policy+from core.training import account_jobs as jobs+from hub.schemas.downloads import DownloadDatasetRequest, DownloadModelRequest+from hub.services import download_lifecycle+from hub.services.datasets import downloads as dataset_downloads+from hub.services.models import account_access as access, downloads+from hub.utils import download_manifest, download_registry+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(download_lifecycle, "_job_accounts", {})+ monkeypatch.setattr(downloads, "_registry", download_registry.DownloadRegistry())+ monkeypatch.setattr(dataset_downloads, "_account_registries", {})+ monkeypatch.setattr(jobs, "_services", [])+ monkeypatch.setattr(jobs, "_retired", set())+ monkeypatch.setattr(+ download_lifecycle, "resolve_requested_use_xet", lambda mode, use_xet: (False, "HTTP")+ )+ from core import research_runs+ from core.rag import folder_sync, ingestion++ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+++def _retire_while_blocked(blocked, release, start_request):+ """Run *start_request* until it parks on *blocked*, retire ALICE, then let it finish."""+ result = {}++ def request_thread():+ try:+ result["value"] = run_as(ALICE, lambda: asyncio.run(start_request()))+ except HTTPException as exc:+ result["error"] = (exc.status_code, exc.detail)+ except Exception as exc: # noqa: BLE001+ result["error"] = (type(exc).__name__, str(exc))++ thread = threading.Thread(target = request_thread)+ thread.start()+ assert blocked.wait(timeout = 30), "the request never reached its pre-claim await"+ jobs.retire_account_jobs(ALICE)+ release.set()+ thread.join(timeout = 30)+ assert not thread.is_alive()+ return result+++def test_model_download_cannot_launch_after_retirement_reported_success(monkeypatch):+ blocked, release, spawned = threading.Event(), threading.Event(), []+ monkeypatch.setattr(dataset_downloads, "retire_account_downloads", lambda: None)++ def authorize(repo_id, repo_type, hf_token):+ blocked.set()+ release.wait(timeout = 30)++ monkeypatch.setattr(access, "authorize_download", authorize)+ monkeypatch.setattr(downloads, "resolve_cached_repo_id_case", lambda repo_id, **k: repo_id)+ monkeypatch.setattr(downloads, "_load_in_flight", lambda repo_id: False)++ def fake_spawn(repo_id, variant, hf_token, **kwargs):+ proc = subprocess.Popen(["sleep", "3"])+ spawned.append((proc, hf_token))+ return proc++ monkeypatch.setattr(downloads, "_spawn_download_worker", fake_spawn)++ result = _retire_while_blocked(+ blocked,+ release,+ lambda: downloads.download_model_response(+ DownloadModelRequest(repo_id = "org/private", use_xet = False),+ hf_token = "alice-secret-token",+ ),+ )+ for proc, _ in spawned:+ proc.kill()+ assert not spawned, f"a worker was launched for a retired account: {spawned}"+ assert result.get("error") == (403, "Account is retired"), result+++def test_dataset_download_cannot_launch_after_retirement_reported_success(monkeypatch):+ blocked, release, spawned = threading.Event(), threading.Event(), []+ monkeypatch.setattr(downloads, "retire_account_downloads", lambda: None)++ def blocking_case(repo_id, **kwargs):+ blocked.set()+ release.wait(timeout = 30)+ return repo_id++ monkeypatch.setattr(dataset_downloads, "resolve_cached_repo_id_case", blocking_case)+ monkeypatch.setattr(access, "authorize_download", lambda *a, **k: None)++ def fake_spawn(args, hf_token, **kwargs):+ proc = subprocess.Popen(["sleep", "3"])+ spawned.append((proc, hf_token))+ return proc++ monkeypatch.setattr(download_lifecycle, "spawn_worker", fake_spawn)+ monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)++ result = _retire_while_blocked(+ blocked,+ release,+ lambda: dataset_downloads.download_dataset_response(+ DownloadDatasetRequest(repo_id = "org/private-ds", use_xet = False),+ hf_token = "alice-secret-token",+ ),+ )+ for proc, _ in spawned:+ proc.kill()+ assert not spawned, f"a dataset worker was launched for a retired account: {spawned}"+ assert result.get("error") == (403, "Account is retired"), result+++def test_dataset_retirement_cancels_a_job_claimed_but_not_yet_launched(monkeypatch):+ """Ownership must be recorded with the claim: retirement scans the per-account registry, and an+ unattributed job makes its cancel raise "Download not found" and abort the whole deletion."""+ blocked, release, spawned = threading.Event(), threading.Event(), []+ monkeypatch.setattr(downloads, "retire_account_downloads", lambda: None)+ monkeypatch.setattr(dataset_downloads, "_registry", download_registry.DownloadRegistry())+ monkeypatch.setattr(dataset_downloads, "resolve_cached_repo_id_case", lambda r, **k: r)+ monkeypatch.setattr(access, "authorize_download", lambda *a, **k: None)++ def blocking_clear(*args, **kwargs):+ # Between the claim and launch_worker: the route clears the cancel marker here.+ blocked.set()+ release.wait(timeout = 30)++ monkeypatch.setattr(download_manifest, "clear_cancel_marker", blocking_clear)++ def fake_spawn(args, hf_token, **kwargs):+ proc = subprocess.Popen(["sleep", "3"])+ spawned.append((proc, hf_token))+ return proc++ monkeypatch.setattr(download_lifecycle, "spawn_worker", fake_spawn)+ monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)++ result = _retire_while_blocked(+ blocked,+ release,+ lambda: dataset_downloads.download_dataset_response(+ DownloadDatasetRequest(repo_id = "org/private-ds", use_xet = False),+ hf_token = "alice-secret-token",+ ),+ )+ for proc, _ in spawned:+ proc.kill()+ assert not spawned, f"a dataset worker was launched for a retired account: {spawned}"+ assert result.get("error") == (403, "Account is retired"), resultdiff --git a/studio/backend/tests/test_account_inference_isolation.py b/studio/backend/tests/test_account_inference_isolation.pynew file mode 100644index 00000000000..419fc55e7bc--- /dev/null+++ b/studio/backend/tests/test_account_inference_isolation.py@@ -0,0 +1,744 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import asyncio+import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from models.inference import LoadRequest, UnloadRequest+from routes import inference, models, video+from state import active_generations+from utils.account_context import (+ OWNER,+ AccountContext,+ arun_as,+ bind_account,+ reset_account,+ run_as,+)++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(inference, "_managed_catalogs", {})+ monkeypatch.setattr(inference, "_CATALOG_CACHE", {"at": 0.0, "models": []})+ monkeypatch.setattr(inference, "_ADVERTISED_CACHE", {"at": None, "paths": {}})+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: False)+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ monkeypatch.setattr(inference, "_CANCEL_REGISTRY", {})+ monkeypatch.setattr(inference, "_PENDING_CANCELS", {})+ active_generations.reset_for_tests()+ yield+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(inference.router, prefix = "/api/inference")+ app.include_router(inference.studio_router, prefix = "/api/inference")+ app.include_router(video.router, prefix = "/api/inference")+ app.include_router(models.router, prefix = "/api/models")+ return TestClient(app)+++ "modality,paths",+ [+ ("chat", ["status", "load-progress"]),+ ("diffusion", ["images/status", "images/load-progress", "images/generate-progress"]),+ ("video", ["video/status", "video/load-progress", "video/generate-progress"]),+ ],+)+def test_resident_identity_and_progress_are_hidden_from_other_accounts(+ monkeypatch, modality, paths+):+ monkeypatch.setattr(gpu_arbiter, "_owner", modality)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)+ with client_for(BOB) as client:+ for path in paths:+ response = client.get(f"/api/inference/{path}")+ assert response.status_code == 200+ body = response.json()+ assert body.get("yours") is False, body+ # The chat status shape lists resident models, so its hidden answer lists none.+ assert body["loaded"] == ([] if path == "status" and modality == "chat" else True)+ assert not run_as(ALICE, access.resident_hidden, modality)+ assert not run_as(OWNER, access.resident_hidden, modality)+++ "path,body",+ [+ ("images/load", {"model_path": "org/public"}),+ ("video/load", {"model_path": "org/public"}),+ ("unload", {"model_path": "org/public", "force_cancel_active": True}),+ ("images/unload", None),+ ("video/unload", None),+ ],+)+def test_foreign_generation_returns_retryable_409_without_cancelling_it(path, body):+ event = threading.Event()+ with run_as(BOB, active_generations.ActiveGeneration, event, model = "org/bob-private"):+ with client_for(ALICE) as client:+ response = client.post(f"/api/inference/{path}", json = body)+ assert response.status_code == 409+ body = response.json()+ assert body["error"] == "gpu_busy"+ assert body["retry_after"] == int(response.headers["retry-after"])+ assert not event.is_set()+++def test_chat_load_and_raw_arbiter_error_use_the_same_retry_response(monkeypatch):+ async def fail(*args, **kwargs):+ raise gpu_arbiter.GpuBusyForAnotherAccountError("video", 1)++ monkeypatch.setattr(inference, "load_model_gated", fail)+ with client_for(ALICE) as client:+ response = client.post("/api/inference/load", json = {"model_path": "org/public"})+ assert response.status_code == 409+ body = response.json()+ assert body["error"] == "gpu_busy"+ assert body["retry_after"] == int(response.headers["retry-after"])+++def test_forced_swap_cancels_only_callers_registrations():+ mine, theirs = threading.Event(), threading.Event()+ with (+ run_as(ALICE, active_generations.ActiveGeneration, mine),+ run_as(BOB, active_generations.ActiveGeneration, theirs),+ ):+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, inference._raise_or_cancel_active_generations, force = True, action = "Load")+ assert exc.value.detail["error"] == "gpu_busy"+ assert not theirs.is_set()+ with run_as(ALICE, active_generations.ActiveGeneration, mine):+ assert (+ run_as(ALICE, inference._raise_or_cancel_active_generations, force = True, action = "Load")+ == 1+ )+ assert mine.is_set()+++def test_forced_swap_checks_foreign_work_before_cancelling_the_caller():+ """A force refused for another account must leave the caller's chats running."""+ mine, theirs = threading.Event(), threading.Event()+ with (+ run_as(ALICE, active_generations.ActiveGeneration, mine),+ run_as(BOB, active_generations.ActiveGeneration, theirs),+ ):+ with pytest.raises(HTTPException) as exc:+ run_as(+ ALICE,+ inference._raise_or_cancel_active_generations,+ force = True,+ action = "Installing a new transformers version",+ )+ assert exc.value.detail["error"] == "gpu_busy"+ assert not mine.is_set() and not theirs.is_set()+++def test_active_generation_and_cancel_id_routes_are_scoped(monkeypatch):+ monkeypatch.setattr(inference, "_openai_llama_admission_capacity", lambda *a: 2)+ mine, theirs = threading.Event(), threading.Event()+ with (+ run_as(+ ALICE,+ inference._TrackedCancel,+ mine,+ "same-id",+ thread_id = "alice-thread",+ model = "alice/private",+ ),+ run_as(+ BOB,+ inference._TrackedCancel,+ theirs,+ "same-id",+ thread_id = "bob-thread",+ model = "bob/private",+ ),+ ):+ with client_for(ALICE) as client:+ response = client.get("/api/inference/active-generations").json()+ assert response["thread_ids"] == ["alice-thread"]+ assert response["count"] == 1+ assert "bob/private" not in str(response)+ assert client.post("/api/inference/cancel", json = {"cancel_id": "same-id"}).json() == {+ "cancelled": 1+ }+ assert mine.is_set() and not theirs.is_set()+++def test_pending_cancel_and_recreated_username_do_not_cross_accounts():+ run_as(ALICE, inference._cancel_by_cancel_id_or_stash, "pending")+ event = threading.Event()+ with run_as(BOB, inference._TrackedCancel, event, "pending"):+ assert not event.is_set()+ with run_as(AccountContext("c" * 32, "alice"), inference._TrackedCancel, event, "pending"):+ assert not event.is_set()+ with run_as(ALICE, inference._TrackedCancel, event, "pending"):+ assert event.is_set()+++def test_scoped_load_request_ids_use_immutable_accounts():+ request = LoadRequest(model_path = "org/private", load_request_id = "same-request")+ alice = run_as(ALICE, inference._begin_load_attempt, request, "alice")+ replacement = AccountContext("c" * 32, "alice")+ second = run_as(replacement, inference._begin_load_attempt, request, "alice")+ try:+ cancel = UnloadRequest(model_path = "org/private", cancel_load_request_id = "same-request")+ run_as(replacement, inference._cancel_scoped_load_attempt, cancel, "alice")+ assert second.cancel_event.is_set()+ assert not alice.cancel_event.is_set()+ finally:+ inference._finish_load_attempt(alice)+ inference._finish_load_attempt(second)++[email protected]("path", ["images/generate/cancel", "video/generate/cancel"])+def test_media_cancel_cannot_stop_foreign_resident(monkeypatch, path):+ monkeypatch.setattr(+ gpu_arbiter, "_owner", "diffusion" if path.startswith("images") else "video"+ )+ monkeypatch.setattr(gpu_arbiter, "_owner_account", BOB.account_id)+ with client_for(ALICE) as client:+ assert client.post(f"/api/inference/{path}").json() == {"cancelled": False}+++ "path",+ [+ "config/org/private",+ "check-vision/org/private",+ "check-embedding/org/private",+ "loras/org/private/base-model",+ "cached-model-path?repo_id=org/private",+ "gguf-variants?repo_id=org/private",+ "download-progress?repo_id=org/private",+ "gguf-download-progress?repo_id=org/private&variant=Q4_K_M",+ "kv-cache-estimate?repo_id=org/private&quant=Q4_K_M",+ ],+)+def test_private_model_object_routes_refuse_unguarded_cache_reads(path):+ with client_for(BOB) as client:+ response = client.get(f"/api/models/{path}")+ assert response.status_code == 404, response.text+++ "field", ["model_name", "model_local_path", "model_snapshot_path", "model_snapshot_repo_id"]+)+def test_transformers_preflight_refuses_foreign_targets(field):+ body = {"model_name": "org/public", field: "org/private"}+ with client_for(BOB) as client:+ response = client.post("/api/inference/transformers-upgrade-check", json = body)+ assert response.status_code == 404, response.text++[email protected]("base,expected", [("org/private", 404), ("org/public", None)])+def test_a_resolved_adapter_base_needs_its_own_grant(monkeypatch, base, expected):+ monkeypatch.setattr(+ access, "repo_is_public", lambda repo, repo_type = "model": repo == "org/public"+ )+ config = SimpleNamespace(base_model = base, identifier = "alice/adapter")+ if expected is None:+ run_as(BOB, inference._require_resolved_base_access, config)+ else:+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, inference._require_resolved_base_access, config)+ assert exc.value.status_code == expected+ inference._require_resolved_base_access(config)+++def test_preview_load_refuses_private_foreign_target_before_gpu_work():+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ arun_as(+ BOB,+ inference.load_model_for_preview(+ LoadRequest(model_path = "org/private"), SimpleNamespace(scope = {}), "bob"+ ),+ )+ )+ assert exc.value.status_code == 404+++def test_same_public_resident_is_available_without_loading_or_cancelling(monkeypatch):+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ from utils import openai_auto_switch_settings++ monkeypatch.setattr(+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False+ )+ monkeypatch.setattr(openai_auto_switch_settings, "idle_unload_is_configured", lambda: False)+ monkeypatch.setattr(inference, "_loaded_satisfies", lambda model: True)+ monkeypatch.setattr(inference, "_claim_slot_for_non_preview", lambda request: None)+ event = threading.Event()+ with run_as(BOB, active_generations.ActiveGeneration, event):+ asyncio.run(+ arun_as(+ ALICE,+ inference._maybe_auto_switch_model(+ "org/public", SimpleNamespace(scope = {}, state = SimpleNamespace()), "alice"+ ),+ )+ )+ assert not event.is_set()++[email protected]("path", ["validate", "estimate-memory", "audio/download-plan"])+def test_model_probe_posts_cannot_read_private_cache(path):+ with client_for(BOB) as client:+ response = client.post(f"/api/inference/{path}", json = {"model_path": "org/private"})+ assert response.status_code == 404, response.text+++def test_cpu_resident_provenance_does_not_depend_on_a_gpu_lease(monkeypatch):+ monkeypatch.setattr(access, "_resident_accounts", {})+ run_as(ALICE, access.note_resident_account, "chat", "org/private")+ assert run_as(BOB, access.resident_hidden, "chat", "org/private")+ assert not run_as(ALICE, access.resident_hidden, "chat", "org/private")+ assert not run_as(OWNER, access.resident_hidden, "chat", "org/private")+ assert not run_as(BOB, access.resident_hidden, "chat")+++def test_stt_private_status_and_download_state_are_filtered(monkeypatch):+ monkeypatch.setattr(inference, "_stt_download_accounts", {"transformers": ALICE.account_id})+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)+ run_as(ALICE, access.note_resident_account, "stt:transformers", "org/private")+ status = {"loaded_model": "org/private"}+ for engine in ["transformers", "gguf", "mtmd"]:+ status[engine] = {+ "loaded_model": "org/private",+ "downloaded_models": ["org/private"],+ "download": {"model": "org/private", "error": "private error"},+ }+ result = run_as(BOB, inference._account_stt_status, status)+ assert result["loaded_model"] is None+ assert "org/private" not in str(result)+ assert "private error" not in str(result)+++def test_stt_downloads_grant_only_the_initiator_and_cancel_is_scoped(monkeypatch):+ monkeypatch.setattr(inference, "_stt_download_accounts", {})+ monkeypatch.setattr(inference, "_stt_grant_pending", {})+ monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)+ monkeypatch.setattr(access, "authorize_download", lambda *a: None)+ calls = []+ module = SimpleNamespace(+ start_model_download = lambda *a: calls.append(a),+ download_status = lambda: {"downloading": False},+ is_model_downloaded = lambda model: True,+ cancel_model_download = lambda: calls.append("cancel") or True,+ )+ run_as(+ ALICE,+ inference._start_account_stt_download,+ module,+ "transformers",+ "org/private",+ "alice-token",+ )+ assert inference._stt_grant_pending["transformers"].wait(5)+ assert run_as(ALICE, access.repo_visible, "org/private")+ assert not run_as(BOB, access.repo_visible, "org/private")+ assert run_as(BOB, inference._cancel_account_stt_download, module, "transformers") == {+ "downloading": False,+ "cancelled": False,+ }+ assert "cancel" not in calls+ assert run_as(ALICE, inference._cancel_account_stt_download, module, "transformers")[+ "cancelled"+ ]+++def test_stt_download_cannot_adopt_another_accounts_job(monkeypatch):+ monkeypatch.setattr(inference, "_stt_download_accounts", {"transformers": ALICE.account_id})+ module = SimpleNamespace(download_status = lambda: {"downloading": True})+ with pytest.raises(HTTPException) as exc:+ run_as(+ BOB, inference._start_account_stt_download, module, "transformers", "org/private", False+ )+ assert exc.value.status_code == 409+++def test_openai_catalog_and_advertised_paths_are_account_scoped(monkeypatch):+ from utils.account_context import current_account_id++ monkeypatch.setattr(inference, "_classified_catalog", lambda rows: rows)+ monkeypatch.setattr(+ models,+ "collect_local_models",+ lambda path: [SimpleNamespace(model_id = "same/name", path = current_account_id())],+ )++ async def read(account):+ return await arun_as(account, inference._cached_local_catalog())++ for account in [ALICE, BOB, ALICE, OWNER]:+ rows = asyncio.run(read(account))+ assert rows[0].path == account.account_id+ assert run_as(account, inference._advertised_local_path, "same/name") == account.account_id+++def test_the_local_id_v1_models_publishes_is_usable_by_its_own_account(monkeypatch):+ from utils.paths.storage_roots import workspace_root++ def _row(account):+ path = str(run_as(account, workspace_root) / "models" / "my-model")+ return SimpleNamespace(model_id = None, id = path, path = path)++ rows = [_row(OWNER), _row(ALICE), _row(BOB)]+ monkeypatch.setattr(inference, "_classified_catalog", lambda listed: listed)+ monkeypatch.setattr(models, "collect_local_models", lambda path: rows)++ request = SimpleNamespace(+ scope = {},+ state = SimpleNamespace(),+ url = SimpleNamespace(path = "/v1/chat/completions"),+ )++ async def resolve(account):+ return await arun_as(+ account,+ inference._maybe_auto_switch_model("my-model", request, account.username),+ )++ for account in (ALICE, BOB):+ asyncio.run(resolve(account))+ assert (+ run_as(account, inference._own_local_model_for_alias, "my-model") == _row(account).path+ )+ assert run_as(account, inference._own_local_model_for_alias, "other-model") is None++ monkeypatch.setattr(inference, "_managed_catalogs", {})+ monkeypatch.setattr(models, "collect_local_models", lambda path: [_row(OWNER)])+ for account in (ALICE, BOB):+ with pytest.raises(HTTPException) as refused:+ asyncio.run(resolve(account))+ assert refused.value.status_code == 404+++def test_private_media_index_rows_cannot_bypass_filtered_openai_catalog(monkeypatch):+ picks = {+ "text-to-image": [+ ("org/private", SimpleNamespace(model_path = "org/private", gguf_filename = None), True)+ ]+ }+ monkeypatch.setattr(inference, "_validated_media_picks", lambda at: picks)+ monkeypatch.setattr(inference, "_resident_media_status", lambda task: None)+ run_as(ALICE, access.record_model_grant, "org/private")+ assert run_as(BOB, inference._media_model_objects, [], 1, 1) == []+ assert run_as(ALICE, inference._media_model_objects, [], 1, 1)[0]["id"] == "org/private"+++def test_custom_stt_models_are_filtered_before_openai_listing(monkeypatch):+ from core.inference import stt_mtmd_sidecar, stt_sidecar++ monkeypatch.setattr(stt_sidecar, "is_available", lambda: True)+ monkeypatch.setattr(stt_sidecar, "is_model_downloaded", lambda model: False)+ monkeypatch.setattr(+ stt_sidecar, "get_stt_sidecar", lambda: SimpleNamespace(loaded_model = "org/private")+ )+ monkeypatch.setattr(stt_mtmd_sidecar, "is_available", lambda: False)+ monkeypatch.setattr(inference, "_downloaded_custom_stt_ids", lambda at: ("org/private",))+ run_as(ALICE, access.record_model_grant, "org/private")+ run_as(ALICE, access.note_resident_account, "stt:transformers", "org/private")+ assert run_as(BOB, inference._stt_model_objects, 1, 1) == []+ assert run_as(ALICE, inference._stt_model_objects, 1, 1)[0]["loaded"]++[email protected]("kind", ["images", "video"])+def test_private_cpu_media_residents_hide_progress_and_refuse_generation_and_unload(+ monkeypatch, kind+):+ from core.inference import diffusion_engine_router, media_auto_switch+ from core.inference import video as video_engine++ _status = lambda: {"loaded": True, "repo_id": "org/private"}+ backend = SimpleNamespace(status = _status, generation_snapshot = lambda: (_status(), object()))+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ monkeypatch.setattr(video_engine, "get_video_backend", lambda: backend)++ async def no_switch(*a, **k):+ return None++ monkeypatch.setattr(media_auto_switch, "maybe_auto_switch_media_model", no_switch)+ run_as(+ ALICE,+ access.note_resident_account,+ "diffusion" if kind == "images" else "video",+ "org/private",+ )+ with client_for(BOB) as client:+ for path in ["load-progress", "generate-progress"]:+ response = client.get(f"/api/inference/{kind}/{path}")+ assert response.json() == {"loaded": True, "yours": False}+ response = client.post(f"/api/inference/{kind}/generate", json = {"prompt": "hello"})+ assert response.status_code == 404, response.text+ assert client.post(f"/api/inference/{kind}/unload").status_code == 404++[email protected]("path", ["images/generate/cancel", "video/generate/cancel"])+def test_model_loader_cannot_cancel_a_different_accounts_generation(path):+ event = threading.Event()+ with run_as(BOB, active_generations.ActiveGeneration, event):+ with client_for(OWNER) as client:+ assert client.post(f"/api/inference/{path}").json() == {"cancelled": False}+ assert not event.is_set()+++def test_authorized_private_download_progress_is_visible_before_grant_completion(monkeypatch):+ from hub.services import download_lifecycle, snapshot_progress+ from hub.services.models import downloads++ registry = SimpleNamespace(active_job_refs = lambda repo: [SimpleNamespace(key = "org/private::")])+ monkeypatch.setattr(downloads, "_registry", registry)+ monkeypatch.setattr(+ download_lifecycle, "_job_accounts", {(id(registry), "org/private::"): ALICE.account_id}+ )++ async def progress(**kwargs):+ return {"downloaded_bytes": 12}++ monkeypatch.setattr(snapshot_progress, "snapshot_progress_response", progress)+ with client_for(ALICE) as client:+ assert client.get("/api/models/download-progress?repo_id=org/private").json() == {+ "downloaded_bytes": 12+ }+ with client_for(BOB) as client:+ assert client.get("/api/models/download-progress?repo_id=org/private").status_code == 404++[email protected]("kind", ["loras", "controlnets"])+def test_media_adapter_catalogs_and_selection_do_not_reveal_owner_files(+ monkeypatch, tmp_path, kind+):+ from core.inference import diffusion_lora, diffusion_controlnet++ module = diffusion_lora if kind == "loras" else diffusion_controlnet+ entry = SimpleNamespace(+ id = "private-adapter", local_path = str(tmp_path / "private-weights"), repo_id = None+ )+ monkeypatch.setattr(module, "list_" + kind, lambda **kwargs: [entry])+ with client_for(BOB) as client:+ response = client.get("/api/models/diffusion-" + kind)+ assert response.status_code == 200, response.text+ assert response.json()[kind] == []+ assert BOB.account_id in response.json()[kind + "_dir"]+ request = SimpleNamespace(+ loras = [SimpleNamespace(id = entry.id)] if kind == "loras" else None,+ controlnet = SimpleNamespace(id = entry.id) if kind == "controlnets" else None,+ )+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, access.require_media_adapters, request)+ assert exc.value.status_code == 404+++def test_the_native_context_worker_runs_as_the_requesting_account(monkeypatch):+ from utils.account_context import current_account_id++ seen = []+ monkeypatch.setattr(+ models,+ "_read_native_context_length",+ lambda model, is_local: seen.append(current_account_id()) or 4096,+ )+ read = models._read_native_context_length_bounded("org/model", False)+ assert asyncio.run(arun_as(ALICE, read)) == 4096+ assert seen == [ALICE.account_id]+++def test_every_model_load_worker_is_pinned_to_its_account():+ import ast+ import inspect++ from core.inference import diffusion, sd_cpp_backend, video as video_backend++ for module in (diffusion, sd_cpp_backend, video_backend):+ tree = ast.parse(inspect.getsource(module))+ starters = [+ node.func+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and any(+ keyword.arg == "target"+ and isinstance(keyword.value, ast.Attribute)+ and keyword.value.attr == "_run_load"+ for keyword in node.keywords+ )+ ]+ assert starters, module.__name__+ assert all(+ isinstance(func, ast.Name) and func.id == "account_thread" for func in starters+ ), module.__name__+++def test_the_lora_and_controlnet_scanners_read_the_reported_directory(tmp_path, monkeypatch):+ from core.inference import diffusion_controlnet, diffusion_lora+ from utils.paths.storage_roots import workspace_root++ for account in (OWNER, ALICE):+ reported = {+ "loras": run_as(account, diffusion_lora.loras_dir),+ "controlnets": run_as(account, diffusion_controlnet.controlnets_dir),+ }+ root = run_as(account, workspace_root)+ assert reported["loras"] == root / "loras" / "diffusion"+ assert reported["controlnets"] == root / "controlnets" / "diffusion"++ owner_lora = run_as(OWNER, diffusion_lora.loras_dir) / "owner-private.safetensors"+ owner_lora.write_bytes(b"weights")+ assert [+ entry.id for entry in run_as(ALICE, diffusion_lora.list_loras) if entry.source == "local"+ ] == []+ assert any(entry.source == "local" for entry in run_as(OWNER, diffusion_lora.list_loras))+++def test_stt_load_does_not_claim_a_model_another_account_switched_to(monkeypatch):+ """A load landing between the sidecar lock release and the ownership record is not adopted."""+ import json++ sidecar = SimpleNamespace(loaded_model = None, device = None)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "require_model_access", lambda *a, **k: None)+ monkeypatch.setattr(inference, "_resolve_serving_stt_engine", lambda engine: "transformers")+ monkeypatch.setattr(inference, "_stt_sidecar_for", lambda engine: sidecar)+ monkeypatch.setattr(inference, "_prepare_runtime_fallback_checkpoint", lambda *a, **k: None)+ monkeypatch.setattr(+ inference, "_stt_lifecycle", lambda: (lambda *a, **k: None, lambda *a, **k: [])+ )++ async def _watcher(request, sidecar_, cancel_event):+ return None++ async def _stop(task):+ sidecar.loaded_model = "bob/private-stt"+ run_as(BOB, access.note_resident_account, "stt:transformers", "bob/private-stt")++ monkeypatch.setattr(inference, "_await_stt_disconnect_then_cancel", _watcher)+ monkeypatch.setattr(inference, "_stop_local_disconnect_cancel_watcher", _stop)++ payload = SimpleNamespace(model = "alice/model", engine = "transformers", device = None)+ response = asyncio.run(arun_as(ALICE, inference.stt_load(payload, SimpleNamespace(), "alice")))+ assert json.loads(response.body)["loaded_model"] != "bob/private-stt"+ assert access._resident_accounts["stt:transformers"][0] == BOB.account_id+++def test_implicit_transcribe_load_records_the_caller_as_resident(monkeypatch):+ sidecar = SimpleNamespace(loaded_model = None, device = None)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "require_model_access", lambda *a, **k: None)+ monkeypatch.setattr(inference, "_resolve_serving_stt_engine", lambda engine: "transformers")+ monkeypatch.setattr(inference, "_stt_sidecar_for", lambda engine: sidecar)+ monkeypatch.setattr(inference, "_stt_resolved_model_id", lambda model, engine: model)+ monkeypatch.setattr(inference, "_prepare_runtime_fallback_checkpoint", lambda *a, **k: None)++ def _load(+ model,+ engine,+ cancel_event,+ device = None,+ ):+ sidecar.loaded_model = model++ sidecar.transcribe = lambda *a, **k: {"text": "hi"}+ monkeypatch.setattr(inference, "_stt_lifecycle", lambda: (_load, lambda *a, **k: []))++ result = asyncio.run(+ arun_as(+ ALICE,+ inference._transcribe_audio_result(+ b"audio", "alice/model", None, False, "transformers"+ ),+ )+ )+ assert result == {"text": "hi"}+ assert access._resident_accounts["stt:transformers"][0] == ALICE.account_id+++def test_count_tokens_refuses_another_accounts_resident_model(monkeypatch):+ monkeypatch.setattr(gpu_arbiter, "_owner", "chat")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)+ with client_for(BOB) as client:+ response = client.post(+ "/api/inference/chat/count_tokens",+ json = {"model": "org/A-GGUF", "messages": [{"role": "user", "content": "hi"}]},+ )+ assert response.status_code == 404, response.text+++def test_legacy_generate_stream_refuses_another_accounts_resident_model(monkeypatch):+ monkeypatch.setattr(gpu_arbiter, "_owner", "chat")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)+ with client_for(BOB) as client:+ response = client.post(+ "/api/inference/generate/stream",+ json = {"messages": [{"role": "user", "content": "hi"}]},+ )+ assert response.status_code == 404, response.text+ assert "model_path" not in response.text++[email protected]("override,expected", [(None, 403), ("1", None)])+def test_managed_load_cannot_enable_remote_code_unless_the_owner_opted_in(+ monkeypatch, override, expected+):+ from utils.security import consent++ monkeypatch.delenv(consent.MANAGED_REMOTE_CODE_OVERRIDE, raising = False)+ if override is not None:+ monkeypatch.setenv(consent.MANAGED_REMOTE_CODE_OVERRIDE, override)+ assert run_as(BOB, consent.managed_remote_code_refused) is (expected is not None)+ assert consent.managed_remote_code_refused() is False+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ monkeypatch.setattr(consent, "_config_has_auto_map", lambda *a, **k: True)+ monkeypatch.setattr(+ consent, "repo_remote_code_files", lambda *a, **k: {"modeling.py": "import torch\n"}+ )+ decision = run_as(+ BOB,+ consent.evaluate_remote_code_consent_for_targets,+ ["org/public"],+ trust_remote_code = True,+ )+ assert decision.blocked is (expected is not None)+ assert decision.approvable is (expected is None)+++def test_the_chat_load_refuses_managed_remote_code_before_the_worker_starts():+ """The inference worker is spawned unbound, so the route must apply the policy."""+ import inspect++ src = inspect.getsource(inference._load_model_impl)+ check = src.index("managed_remote_code_refused()")+ assert check < src.index("backend.load_model,")+ assert "MANAGED_REMOTE_CODE_REFUSAL" in src[check : check + 200]diff --git a/studio/backend/tests/test_account_installation_mutations.py b/studio/backend/tests/test_account_installation_mutations.pynew file mode 100644index 00000000000..c6648faae85--- /dev/null+++ b/studio/backend/tests/test_account_installation_mutations.py@@ -0,0 +1,105 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import pytest+from fastapi import Depends, FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import get_current_subject+from utils.account_context import AccountContext, OWNER, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")++[email protected](autouse = True)+def multi_user(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ yield+++def _client(account, build):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ build(app)+ return TestClient(app)+++def _llama_app(app):+ from routes import llama+ app.include_router(llama.router, prefix = "/api/llama")+++def _shutdown_route():+ import main+ for route in main.app.routes:+ if getattr(route, "path", None) == "/api/shutdown" and "POST" in getattr(+ route, "methods", ()+ ):+ return route+ raise AssertionError("POST /api/shutdown is not registered")+++ "path,payload", [("/api/llama/update", None), ("/api/llama/backend", {"backend": "cpu"})]+)+def test_a_managed_account_cannot_replace_the_installation_executables(monkeypatch, path, payload):+ from utils import llama_cpp_update++ started = []+ monkeypatch.setattr(+ llama_cpp_update, "start_update", lambda: started.append("update") or {"started": True}+ )+ monkeypatch.setattr(+ llama_cpp_update,+ "start_backend_switch",+ lambda backend: started.append(backend) or {"started": True},+ )+ from routes import llama as llama_routes++ monkeypatch.setattr(llama_routes, "start_update", llama_cpp_update.start_update)+ monkeypatch.setattr(llama_routes, "start_backend_switch", llama_cpp_update.start_backend_switch)++ with _client(ALICE, _llama_app) as client:+ assert client.post(path, json = payload).status_code == 403+ assert started == []+ with _client(OWNER, _llama_app) as client:+ assert client.post(path, json = payload).status_code == 200+ assert started+++def test_a_managed_account_cannot_stop_the_shared_server():+ route = _shutdown_route()+ solved = [+ dependency.call+ for dependency in route.dependant.dependencies+ if dependency.call is not None+ ]+ assert policy.require_owner in solved+ assert solved.index(get_current_subject) < solved.index(policy.require_owner)+++def test_a_managed_account_cannot_replace_the_transformers_sidecar(monkeypatch):+ from routes import inference++ def _inference_app(app):+ app.include_router(inference.studio_router, prefix = "/api/inference")++ swaps = []+ monkeypatch.setattr(+ inference, "try_begin_sidecar_swap", lambda *a, **k: swaps.append(1), raising = False+ )+ with _client(ALICE, _inference_app) as client:+ response = client.post("/api/inference/install-latest-transformers", json = {})+ assert response.status_code == 403+ assert swaps == []diff --git a/studio/backend/tests/test_account_integration_wiring.py b/studio/backend/tests/test_account_integration_wiring.pynew file mode 100644index 00000000000..780ffe1d341--- /dev/null+++ b/studio/backend/tests/test_account_integration_wiring.py@@ -0,0 +1,268 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Seams that join the account domains: HTTP admission, the desktop marker, schema init, output roots and retirement draining."""++import asyncio+import inspect+import secrets++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from auth import authentication, policy, storage+from auth.authentication import get_current_subject+from hub.storage import scan_folders+from routes import inference+from utils import keyless_api_access as keyless+from utils.account_context import (+ OWNER,+ AccountContext,+ bind_account,+ current_account_id,+ reset_account,+ run_as,+)+from utils.models import model_config+from utils.paths import outputs_root++ALICE = AccountContext("a" * 32, "alice")+++def multi_user(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+++def _isolated_auth_db(+ tmp_path,+ monkeypatch,+ *,+ owner_must_change = False,+):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ keyless._reset_scope_cache()+ storage.create_initial_user(+ "unsloth",+ "owner-password",+ secrets.token_urlsafe(32),+ must_change_password = owner_must_change,+ )+++def auth_db(tmp_path, monkeypatch):+ _isolated_auth_db(tmp_path, monkeypatch)+ yield+ policy.invalidate_account_cache()+ keyless._reset_scope_cache()+++def _client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.router, prefix = "/v1")+ return TestClient(app)+++def _credentials(token):+ return authentication.HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)+++_FULL_ACCESS = "Full access is unavailable while more than one account exists."++_REQUESTS = {+ "/v1/chat/completions": {"model": "m", "messages": [{"role": "user", "content": "hi"}]},+ "/v1/responses": {"model": "m", "input": "hi"},+ "/v1/messages": {+ "model": "m",+ "max_tokens": 8,+ "messages": [{"role": "user", "content": "hi"}],+ },+}++[email protected]("path", sorted(_REQUESTS))+ "flags",+ [+ {"bypass_permissions": True},+ {"permission_mode": "full"},+ {"disable_sandbox": True},+ ],+)[email protected]("account", [OWNER, ALICE], ids = ["owner", "alice"])+def test_full_access_is_refused_at_the_door_in_multi_mode(+ multi_user, monkeypatch, path, flags, account+):+ def never(*_args, **_kwargs):+ raise AssertionError("the request reached the backend")++ monkeypatch.setattr(inference, "get_llama_cpp_backend", never)+ with _client_for(account) as client:+ response = client.post(path, json = {**_REQUESTS[path], **flags})+ assert response.status_code == 400, response.text+ assert response.json()["detail"] == _FULL_ACCESS++[email protected]("path", sorted(_REQUESTS))+def test_single_account_full_access_passes_the_door(monkeypatch, path):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)++ def backend():+ raise HTTPException(status_code = 503, detail = "no backend in this test")++ monkeypatch.setattr(inference, "get_llama_cpp_backend", backend)+ monkeypatch.setattr(inference, "produce_openai_chat_completions", lambda *a, **k: backend())+ with _client_for(OWNER) as client:+ response = client.post(path, json = {**_REQUESTS[path], "bypass_permissions": True})+ assert response.status_code != 400 or response.json().get("detail") != _FULL_ACCESS+++def test_admission_runs_after_the_docstring_and_reads_every_flag():+ for handler in (+ inference.openai_chat_completions,+ inference.openai_responses,+ inference.anthropic_messages,+ ):+ body = inspect.getsource(handler)+ assert "_admit_tool_access(payload)" in body, handler.__name__+ for handler in (inference.openai_responses, inference.anthropic_messages):+ assert handler.__doc__, handler.__name__+ source = inspect.getsource(inference._admit_tool_access)+ for flag in ("permission_mode", "bypass_permissions", "disable_sandbox"):+ assert flag in source+++def test_desktop_marker_only_authenticates_the_owner(auth_db):+ storage.create_initial_user("alice", "alice-password", secrets.token_urlsafe(32))+ owner_secret = storage.get_user_record("unsloth")["jwt_secret"]+ alice_secret = storage.get_user_record("alice")["jwt_secret"]+ owner_token = authentication.create_access_token(+ subject = "unsloth", desktop = True, secret = owner_secret+ )+ alice_token = authentication.create_access_token(+ subject = "alice", desktop = True, secret = alice_secret+ )+ assert authentication.is_desktop_access_token(owner_token)+ assert not authentication.is_desktop_access_token(alice_token)+++def test_desktop_marker_does_not_bypass_a_managed_password_change(auth_db):+ storage.create_initial_user(+ "alice",+ "alice-password",+ secrets.token_urlsafe(32),+ must_change_password = True,+ )+ alice_secret = storage.get_user_record("alice")["jwt_secret"]+ token = authentication.create_access_token(subject = "alice", desktop = True, secret = alice_secret)+ with pytest.raises(HTTPException) as refused:+ asyncio.run(authentication.get_current_subject(_credentials(token)))+ assert refused.value.status_code == 403+ assert refused.value.detail == "Password change required"+++def test_desktop_marker_still_bypasses_the_owner_password_change(tmp_path, monkeypatch):+ _isolated_auth_db(tmp_path, monkeypatch, owner_must_change = True)+ owner_secret = storage.get_user_record("unsloth")["jwt_secret"]+ token = authentication.create_access_token(subject = "unsloth", desktop = True, secret = owner_secret)+ assert asyncio.run(authentication.get_current_subject(_credentials(token))) == "unsloth"+ policy.invalidate_account_cache()+++def test_refresh_drops_the_desktop_marker_for_a_managed_account(auth_db):+ from routes import auth as auth_routes++ storage.create_initial_user(+ "alice",+ "alice-password",+ secrets.token_urlsafe(32),+ must_change_password = True,+ )+ alice_secret = storage.get_user_record("alice")["jwt_secret"]+ refresh = authentication.create_refresh_token(+ subject = "alice", desktop = True, secret = alice_secret+ )+ app = FastAPI()+ app.include_router(auth_routes.router, prefix = "/api/auth")+ with TestClient(app) as client:+ response = client.post("/api/auth/refresh", json = {"refresh_token": refresh})+ assert response.status_code == 200, response.text+ assert response.json()["must_change_password"] is True+ assert not authentication.is_desktop_access_token(response.json()["access_token"])+++def test_scan_folders_schema_is_initialised_for_each_account(tmp_path, monkeypatch, multi_user):+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ folder = tmp_path / "shared-folder"+ folder.mkdir()+ assert run_as(OWNER, scan_folders.list_scan_folders) == []+ run_as(OWNER, scan_folders.add_scan_folder, str(folder))+ assert run_as(ALICE, scan_folders.list_scan_folders) == []+ assert [row["path"] for row in run_as(OWNER, scan_folders.list_scan_folders)] == [+ str(folder.resolve())+ ]+ assert len(studio_db._schema_ready) == 2+++def test_output_scans_resolve_the_acting_account_root(tmp_path, monkeypatch, multi_user):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ for function in (model_config.scan_trained_models, model_config.scan_exported_models):+ parameter = next(iter(inspect.signature(function).parameters.values()))+ assert parameter.default is None, function.__name__+ seen = []+ monkeypatch.setattr(+ model_config, "resolve_output_dir", lambda value: seen.append(value) or tmp_path / "missing"+ )+ run_as(OWNER, model_config.scan_trained_models)+ run_as(ALICE, model_config.scan_trained_models)+ assert seen == [str(run_as(OWNER, outputs_root)), str(run_as(ALICE, outputs_root))]+ assert seen[0] != seen[1]+++def test_retirement_drains_jobs_and_sessions_under_the_account(tmp_path, monkeypatch, multi_user):+ from core.inference import mcp_client+ from core.training import account_jobs+ from routes import accounts++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ calls = []+ monkeypatch.setattr(+ account_jobs,+ "retire_account_jobs",+ lambda account: calls.append(("jobs", account.account_id)),+ )+ monkeypatch.setattr(+ mcp_client,+ "close_mcp_sessions",+ lambda *a, **k: calls.append(("mcp", current_account_id())),+ )+ monkeypatch.setattr(+ mcp_client,+ "invalidate_tool_cache",+ lambda *a, **k: calls.append(("tools", current_account_id())),+ )+ accounts.retire_account_roots(ALICE)+ assert calls == [+ ("jobs", ALICE.account_id),+ ("mcp", ALICE.account_id),+ ("tools", ALICE.account_id),+ ]+ with pytest.raises(ValueError):+ accounts.retire_account_roots(OWNER)diff --git a/studio/backend/tests/test_account_lifecycle.py b/studio/backend/tests/test_account_lifecycle.pynew file mode 100644index 00000000000..4060dc99438--- /dev/null+++ b/studio/backend/tests/test_account_lifecycle.py@@ -0,0 +1,889 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Real SQLite and HTTP coverage for owner-managed account lifecycle and setup."""++import importlib.util+import secrets+import threading+from concurrent.futures import ThreadPoolExecutor+from datetime import datetime, timedelta, timezone+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from typer.testing import CliRunner++from auth import authentication, hashing, policy, storage+from state import active_generations+from utils.account_context import OWNER, bind_account, reset_account, run_as+from utils.paths import storage_roots+from unsloth_cli.commands import studio as studio_cli+++def _load_route(name):+ path = Path(__file__).resolve().parents[1] / "routes" / f"{name}.py"+ spec = importlib.util.spec_from_file_location(f"_lifecycle_{name}", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def auth_env(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(storage_roots.tempfile, "gettempdir", lambda: str(tmp_path / "tmp"))+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "studio" / "auth" / "auth.db")+ monkeypatch.setattr(+ storage, "_BOOTSTRAP_PW_PATH", storage.DB_PATH.parent / ".bootstrap_password"+ )+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)+ storage._reset_api_key_hash_cache()+ token = bind_account(OWNER)+ policy.invalidate_account_cache()+ active_generations.reset_for_tests()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(64))+ auth = _load_route("auth")+ accounts = _load_route("accounts")+ app = FastAPI()+ app.include_router(auth.router, prefix = "/api/auth")+ app.include_router(accounts.router, prefix = "/api/accounts")+ app.state.bootstrap_password = "owner-bootstrap"+ with TestClient(app) as client:+ yield client, auth, accounts+ active_generations.reset_for_tests()+ reset_account(token)+ policy.invalidate_account_cache()+ storage._reset_api_key_hash_cache()+++def matrix(auth_env):+ for username in ("alice", "bob"):+ storage.create_initial_user(username, f"{username}-password", secrets.token_urlsafe(64))+ return auth_env+++def headers(username = "unsloth"):+ return {"Authorization": "Bearer " + authentication.create_access_token(username)}+++def login(client, username, password):+ return client.post("/api/auth/login", json = {"username": username, "password": password})+++def create(client, username = "carol"):+ return client.post("/api/accounts", headers = headers(), json = {"username": username})+++def db_rows(table):+ conn = storage.get_connection()+ try:+ return [dict(row) for row in conn.execute(f"SELECT * FROM {table} ORDER BY id")]+ finally:+ conn.close()++[email protected]("actor", ["unsloth", "alice", "bob"])+ "operation", ["list", "create", "setup-code", "deactivate", "reactivate", "delete"]+)[email protected]("target", ["unsloth", "alice", "bob"])+def test_owner_alice_bob_endpoint_matrix(matrix, actor, operation, target):+ client, _, _ = matrix+ account = storage.get_account(target)+ url = f"/api/accounts/{account.account_id}"+ before = db_rows("auth_user")+ if operation == "list":+ response = client.get("/api/accounts", headers = headers(actor))+ elif operation == "create":+ response = client.post("/api/accounts", headers = headers(actor), json = {"username": "carol"})+ elif operation == "setup-code":+ response = client.post(url + "/setup-code", headers = headers(actor))+ elif operation in ("deactivate", "reactivate"):+ response = client.patch(+ url, headers = headers(actor), json = {"is_active": operation == "reactivate"}+ )+ else:+ response = client.delete(url, headers = headers(actor))+ if actor != "unsloth":+ assert response.status_code == 403+ assert response.json() == {"detail": "Only the installation owner can do this"}+ assert db_rows("auth_user") == before+ elif target == "unsloth" and operation not in ("list", "create"):+ assert response.status_code == 400+ assert db_rows("auth_user") == before+ else:+ assert response.status_code == {"create": 201, "delete": 204}.get(operation, 200)+ if response.status_code == 200 and operation == "list":+ assert {r["username"] for r in response.json()["accounts"]} == {"unsloth", "alice", "bob"}+ assert all(+ set(row)+ == {"account_id", "username", "role", "is_active", "created_at", "setup_code_pending"}+ for row in response.json()["accounts"]+ )+++ "method,suffix,payload",+ [+ ("GET", "", None),+ ("POST", "", {"username": "carol"}),+ ("POST", "/missing/setup-code", None),+ ("PATCH", "/missing", {"is_active": False}),+ ("DELETE", "/missing", None),+ ],+)+def test_accounts_requires_authentication(auth_env, method, suffix, payload):+ response = auth_env[0].request(method, "/api/accounts" + suffix, json = payload)+ assert response.status_code in (401, 403)+ assert "unsloth" not in response.text and "alice" not in response.text+++ "username,valid,canonical",+ [+ ("abc", True, "abc"),+ ("A_L-I9", True, "a_l-i9"),+ ("a" * 32, True, "a" * 32),+ ("ab", False, None),+ ("a" * 33, False, None),+ ("", False, None),+ ("alice ", False, None),+ (" ali", False, None),+ ("a.b", False, None),+ ("a/b", False, None),+ ("a\\b", False, None),+ ("álice", False, None),+ ("a\nb", False, None),+ ("UNSLOTH", False, None),+ ("Owner", False, None),+ ("ADMIN", False, None),+ ("root", False, None),+ ("system", False, None),+ ],+)+def test_username_validation(auth_env, username, valid, canonical):+ response = create(auth_env[0], username)+ assert response.status_code == (201 if valid else 422)+ if valid:+ assert response.json()["account"]["username"] == canonical+ else:+ assert storage.count_active_accounts() == 1+++def test_create_code_hash_expiry_duplicate_and_public_fields(auth_env):+ client, _, _ = auth_env+ assert policy.login_mode() == "single"+ before = datetime.now(timezone.utc)+ response = create(client, "ALICE")+ assert response.status_code == 201+ body = response.json()+ after = datetime.now(timezone.utc)+ expiry = datetime.fromisoformat(body["setup_code_expires_at"])+ assert before + timedelta(minutes = 60) <= expiry <= after + timedelta(minutes = 60)+ assert policy.login_mode() == "multi"+ record = next(row for row in db_rows("auth_user") if row["username"] == "alice")+ assert record["setup_code_hash"] == storage._hash_setup_code(body["setup_code"])+ assert body["setup_code"] not in str(record)+ assert record["must_change_password"] == 1+ listing = client.get("/api/accounts", headers = headers())+ assert body["setup_code"] not in listing.text+ assert "hash" not in listing.text+ assert body["account"]["setup_code_pending"] is True+ assert create(client, "Alice").status_code == 409++[email protected]("username", ["alice", "bob"])+def test_setup_single_use_then_change_password_without_owner_side_effects(auth_env, username):+ client, _, _ = auth_env+ desktop = storage.create_desktop_secret()+ storage._BOOTSTRAP_PW_PATH.write_bytes(b"owner-bootstrap\n")+ owner_before = storage.get_user_record("unsloth")+ body = create(client, username).json()+ response = login(client, username.upper(), body["setup_code"])+ assert response.status_code == 200+ session = response.json()+ assert session["must_change_password"] is True+ assert login(client, username, body["setup_code"]).status_code == 401+ auth_header = {"Authorization": "Bearer " + session["access_token"]}+ assert client.get("/api/auth/api-keys", headers = auth_header).status_code == 403+ response = client.post(+ "/api/auth/change-password",+ headers = auth_header,+ json = {+ "current_password": body["setup_code"],+ "new_password": "permanent-password",+ },+ )+ assert response.status_code == 200+ assert response.json()["must_change_password"] is False+ assert login(client, username, "permanent-password").status_code == 200+ assert (+ client.post(+ "/api/auth/refresh", json = {"refresh_token": session["refresh_token"]}+ ).status_code+ == 401+ )+ assert storage.get_user_record("unsloth") == owner_before+ assert storage.validate_desktop_secret(desktop) == "unsloth"+ assert storage._BOOTSTRAP_PW_PATH.read_bytes() == b"owner-bootstrap\n"+ assert client.app.state.bootstrap_password == "owner-bootstrap"+++def test_expired_setup_code_is_the_same_generic_401_as_wrong_password(auth_env):+ client, _, _ = auth_env+ body = create(client, "alice").json()+ with storage.get_connection() as conn:+ conn.execute(+ "UPDATE auth_user SET setup_code_expires_at = ? WHERE account_id = ?",+ (+ (datetime.now(timezone.utc) - timedelta(seconds = 1)).isoformat(),+ body["account"]["account_id"],+ ),+ )+ responses = [+ login(client, "alice", body["setup_code"]),+ login(client, "alice", "wrong"),+ login(client, "nobody", "wrong"),+ ]+ assert all(r.status_code == 401 for r in responses)+ assert len({r.content for r in responses}) == 1+++def test_setup_consumption_is_atomic(auth_env):+ client, _, _ = auth_env+ body = create(client, "alice").json()+ barrier = threading.Barrier(8)++ def consume(_):+ barrier.wait()+ return storage.authenticate_account_login("alice", body["setup_code"])++ with ThreadPoolExecutor(max_workers = 8) as pool:+ results = list(pool.map(consume, range(8)))+ assert sum(result is not None for result in results) == 1+++def test_setup_login_uses_existing_casefolded_rate_limit_buckets(auth_env):+ client, auth, _ = auth_env+ alice = create(client, "alice").json()+ bob = create(client, "bob").json()+ for i in range(auth._LOGIN_MAX_FAILS):+ assert login(client, "ALICE" if i % 2 else "alice", "wrong").status_code == 401+ blocked = login(client, "alice", alice["setup_code"])+ assert blocked.status_code == 429 and "Retry-After" in blocked.headers+ assert login(client, "bob", bob["setup_code"]).status_code == 200+ assert login(client, "unsloth", "owner-password").status_code == 200+++def test_multi_login_requires_username(matrix):+ client, _, _ = matrix+ assert client.post("/api/auth/login", json = {"password": "owner-password"}).status_code == 422+ assert login(client, "", "owner-password").status_code == 401+ assert login(client, "UNSLOTH", "owner-password").status_code == 200+++def test_login_and_refresh_carry_the_immutable_account_id(auth_env):+ client, _, _ = auth_env+ first = create(client, "alice").json()+ first_id = first["account"]["account_id"]+ session = login(client, "alice", first["setup_code"])+ assert session.status_code == 200+ assert session.json()["account_id"] == first_id+ assert first_id != storage.get_account("unsloth").account_id+ refreshed = client.post(+ "/api/auth/refresh", json = {"refresh_token": session.json()["refresh_token"]}+ )+ assert refreshed.status_code == 200+ assert refreshed.json()["account_id"] == first_id++ assert client.delete(f"/api/accounts/{first_id}", headers = headers()).status_code == 204+ second = create(client, "alice").json()+ replacement = login(client, "alice", second["setup_code"])+ assert replacement.status_code == 200+ assert replacement.json()["account_id"] == second["account"]["account_id"]+ assert replacement.json()["account_id"] != first_id+ assert login(client, "unsloth", "owner-password").json()["account_id"] == "owner"++[email protected]("must_change", [False, True])+def test_single_owner_login_response_bytes_and_lookup_cost_are_unchanged(+ auth_env, monkeypatch, must_change+):+ client, auth, _ = auth_env+ with storage.get_connection() as conn:+ conn.execute("UPDATE auth_user SET must_change_password = ?", (int(must_change),))+ assert policy.login_mode() == "single"+ monkeypatch.setattr(policy, "active_account_count", lambda: 1)+ monkeypatch.setattr(auth, "create_access_token", lambda **kwargs: "access")+ monkeypatch.setattr(auth, "create_refresh_token", lambda **kwargs: "refresh")+ calls = []+ lookup = storage.get_user_and_secret++ def record_lookup(username):+ calls.append(username)+ return lookup(username)++ monkeypatch.setattr(storage, "get_user_and_secret", record_lookup)+ monkeypatch.setattr(+ storage, "authenticate_account_login", lambda *_: pytest.fail("owner entered managed login")+ )+ response = login(client, "unsloth", "owner-password")+ assert response.status_code == 200+ assert (+ response.content+ == b'{"access_token":"access","refresh_token":"refresh","token_type":"bearer","must_change_password":'+ + (b"true" if must_change else b"false")+ + b',"account_id":"owner"}'+ )+ assert calls == ["unsloth"]+ assert login(client, "UNSLOTH", "owner-password").status_code == 401+++def seed_credentials():+ return {+ name: (+ authentication.create_access_token(name),+ authentication.create_refresh_token(name),+ storage.create_api_key(name, "test")[0],+ )+ for name in ("unsloth", "alice", "bob")+ }++[email protected]("operation", ["setup-code", "deactivate", "delete"])[email protected]("target", ["alice", "bob"])+def test_credential_revocation_is_scoped(matrix, operation, target):+ client, _, _ = matrix+ credentials = seed_credentials()+ account = storage.get_account(target)+ url = f"/api/accounts/{account.account_id}"+ if operation == "setup-code":+ response = client.post(url + "/setup-code", headers = headers())+ elif operation == "deactivate":+ response = client.patch(url, headers = headers(), json = {"is_active": False})+ else:+ response = client.delete(url, headers = headers())+ assert response.status_code in (200, 204)+ for name, (access, refresh, key) in credentials.items():+ response = client.get("/api/auth/api-keys", headers = {"Authorization": "Bearer " + access})+ assert response.status_code == (401 if name == target else 200)+ assert (storage.verify_refresh_token(refresh) is None) == (name == target)+ assert (storage.validate_api_key(key) is None) == (name == target)+++def test_regeneration_invalidates_old_setup_and_its_session(auth_env):+ client, _, _ = auth_env+ first = create(client, "alice").json()+ session = login(client, "alice", first["setup_code"]).json()+ second = client.post(+ f"/api/accounts/{first['account']['account_id']}/setup-code", headers = headers()+ ).json()+ assert first["setup_code"] != second["setup_code"]+ assert login(client, "alice", first["setup_code"]).status_code == 401+ assert (+ client.post(+ "/api/auth/change-password",+ headers = {"Authorization": "Bearer " + session["access_token"]},+ json = {+ "current_password": first["setup_code"],+ "new_password": "new-password",+ },+ ).status_code+ == 401+ )+ assert login(client, "alice", second["setup_code"]).status_code == 200+++def test_activity_updates_policy_and_deactivated_login_stays_refused_in_single_mode(auth_env):+ client, _, _ = auth_env+ body = create(client, "alice").json()+ url = f"/api/accounts/{body['account']['account_id']}"+ assert policy.login_mode() == "multi"+ assert client.patch(url, headers = headers(), json = {"is_active": False}).status_code == 200+ assert policy.login_mode() == "single"+ assert login(client, "alice", body["setup_code"]).status_code == 401+ assert client.patch(url, headers = headers(), json = {"is_active": True}).status_code == 200+ assert policy.login_mode() == "multi"+ assert login(client, "alice", body["setup_code"]).status_code == 200+++def test_delete_retires_all_roots_and_recreated_username_inherits_nothing(matrix):+ client, _, _ = matrix+ alice = storage.get_account("alice")+ bob = storage.get_account("bob")+ roots = (+ storage_roots.workspace_root,+ storage_roots.project_workspaces_root,+ storage_roots.tmp_root,+ )+ old_paths = []+ untouched = []+ for account in (OWNER, alice, bob):+ for root in roots:+ path = run_as(account, root)+ path.mkdir(parents = True, exist_ok = True)+ (path / "private.txt").write_text(account.username)+ (old_paths if account == alice else untouched).append(path)+ events = {account.username: threading.Event() for account in (OWNER, alice, bob)}+ with (+ run_as(OWNER, active_generations.ActiveGeneration, events["unsloth"]),+ run_as(alice, active_generations.ActiveGeneration, events["alice"]),+ run_as(bob, active_generations.ActiveGeneration, events["bob"]),+ ):+ assert (+ client.delete(f"/api/accounts/{alice.account_id}", headers = headers()).status_code == 204+ )+ assert events["alice"].is_set()+ assert not events["bob"].is_set() and not events["unsloth"].is_set()+ for path in old_paths:+ assert not path.exists()+ retired = list(path.parent.glob(path.name + "-deleted-*"))+ assert len(retired) == 1+ assert (retired[0] / "private.txt").read_text() == "alice"+ for path in untouched:+ assert (path / "private.txt").exists()+ fresh = create(client, "alice").json()+ assert fresh["account"]["account_id"] != alice.account_id+ for root in roots:+ assert not run_as(storage.get_account("alice"), root).exists()+ assert client.delete(f"/api/accounts/{alice.account_id}", headers = headers()).status_code == 404+++def test_failed_retirement_leaves_disabled_retryable_account(matrix, monkeypatch):+ client, _, accounts = matrix+ account = storage.get_account("alice")++ def fail(_):+ raise PermissionError("private host path must not be exposed")++ retire = accounts.retire_account_roots+ monkeypatch.setattr(accounts, "retire_account_roots", fail)+ response = client.delete(f"/api/accounts/{account.account_id}", headers = headers())+ assert response.status_code == 409+ assert "private host path" not in response.text+ assert storage.get_user_record("alice")["is_active"] == 0+ monkeypatch.setattr(accounts, "retire_account_roots", retire)+ assert (+ client.delete(f"/api/accounts/{account.account_id}", headers = headers()).status_code == 204+ )+++def test_a_partly_failed_retirement_puts_the_moved_roots_back(matrix, monkeypatch):+ import os++ client, _, accounts = matrix+ account = storage.get_account("alice")+ roots = [+ run_as(account, root)+ for root in (+ storage_roots.workspace_root,+ storage_roots.project_workspaces_root,+ storage_roots.tmp_root,+ )+ ]+ for root in roots:+ root.mkdir(parents = True, exist_ok = True)+ (root / "private.txt").write_text("keep")+ calls = []++ class RenameFailsSecond(type(roots[0])):+ @staticmethod+ def rename(source, destination):+ calls.append(1)+ if len(calls) == 2:+ raise PermissionError("locked directory")+ os.rename(source, destination)++ monkeypatch.setattr(accounts, "Path", RenameFailsSecond)+ url = f"/api/accounts/{account.account_id}"+ assert client.delete(url, headers = headers()).status_code == 409+ for root in roots:+ assert (root / "private.txt").read_text() == "keep"+ assert not [p for p in root.parent.iterdir() if "-deleted-" in p.name]+++def test_an_unstoppable_worker_leaves_a_disabled_retryable_account(matrix, monkeypatch):+ """retire_account_jobs raises its own error, not OSError; the answer is the same 409."""+ from core.training.account_jobs import AccountRetirementError++ client, _, accounts = matrix+ account = storage.get_account("alice")++ def fail(_):+ raise AccountRetirementError("Retired account worker has not stopped")++ monkeypatch.setattr(accounts, "retire_account_roots", fail)+ response = client.delete(f"/api/accounts/{account.account_id}", headers = headers())+ assert response.status_code == 409+ assert storage.get_user_record("alice")["is_active"] == 0+++def test_reactivating_after_a_failed_delete_lifts_the_job_retirement(matrix, monkeypatch):+ client, _, accounts = matrix+ from core.training import account_jobs as jobs++ monkeypatch.setattr(jobs, "_retired", set())+ account = storage.get_account("alice")+ run_as(account, storage_roots.workspace_root).mkdir(parents = True, exist_ok = True)++ class FailingRename:+ @staticmethod+ def rename(root, destination):+ raise PermissionError("locked directory")++ monkeypatch.setattr(accounts, "Path", FailingRename)+ url = f"/api/accounts/{account.account_id}"+ assert client.delete(url, headers = headers()).status_code == 409+ assert run_as(account, jobs.account_is_retired) is True++ assert client.patch(url, headers = headers(), json = {"is_active": True}).status_code == 200+ assert run_as(account, jobs.account_is_retired) is False+++def test_managed_password_change_cannot_overwrite_a_rotated_credential(matrix):+ record = storage.get_user_record("alice")+ storage.set_account_active(record["account_id"], False)+ storage.set_account_active(record["account_id"], True)+ assert (+ storage.update_account_password(+ "alice",+ "replacement-password",+ expect_password_hash = record["password_hash"],+ expect_secret = record["jwt_secret"],+ )+ is None+ )+ current = storage.get_user_record("alice")+ assert hashing.verify_password(+ "alice-password", current["password_salt"], current["password_hash"]+ )+++def reset_cli(auth_env, monkeypatch):+ monkeypatch.setattr(studio_cli, "STUDIO_HOME", storage.DB_PATH.parent.parent)+ monkeypatch.setattr(studio_cli, "_generate_reset_password", lambda: "reset-password")+ return CliRunner()+++def test_cli_single_account_default_output_and_desktop_cleanup_unchanged(auth_env, reset_cli):+ client, _, _ = auth_env+ desktop = storage.create_desktop_secret()+ auth_dir = storage.DB_PATH.parent+ for filename in (studio_cli.BOOTSTRAP_PASSWORD_FILE, studio_cli.DESKTOP_SECRET_FILE):+ (auth_dir / filename).write_text("old-secret", encoding = "utf-8")+ token = authentication.create_refresh_token("unsloth")+ key = storage.create_api_key("unsloth", "test")[0]+ result = reset_cli.invoke(studio_cli.studio_app, ["reset-password"])+ assert result.exit_code == 0, result.output+ assert result.output == (+ "New password for 'unsloth': reset-password\n"+ "Sessions and API keys revoked. A running Unsloth takes it on the next request, "+ "though repeated failed logins can hold the rate limit shut for up to a minute.\n"+ )+ assert storage.validate_desktop_secret(desktop) is None+ assert storage.verify_refresh_token(token) is None+ assert storage.validate_api_key(key) is None+ assert login(client, "unsloth", "reset-password").status_code == 200+ for filename in (studio_cli.BOOTSTRAP_PASSWORD_FILE, studio_cli.DESKTOP_SECRET_FILE):+ assert not (auth_dir / filename).exists()+++def test_login_failure_hint_prints_a_command_that_runs_in_this_mode(auth_env, reset_cli):+ client, _, _ = auth_env+ detail = login(client, "unsloth", "wrong").json()["detail"]+ assert "--username" not in detail+ assert reset_cli.invoke(studio_cli.studio_app, ["reset-password"]).exit_code == 0+++def test_multi_account_login_failure_hint_names_the_account_flag(matrix, reset_cli):+ client, _, _ = matrix+ for username in ("alice", "nobody"):+ detail = login(client, username, "wrong").json()["detail"]+ assert "--username <name>" in detail+ assert username not in detail+ assert reset_cli.invoke(studio_cli.studio_app, ["reset-password"]).exit_code == 1+ assert (+ reset_cli.invoke(studio_cli.studio_app, ["reset-password", "--username", "alice"]).exit_code+ == 0+ )+++def test_cli_multi_requires_username_without_listing_or_changing_accounts(matrix, reset_cli):+ seed_credentials()+ before = {table: db_rows(table) for table in ("auth_user", "refresh_tokens", "api_keys")}+ result = reset_cli.invoke(studio_cli.studio_app, ["reset-password"])+ assert result.exit_code == 1+ assert "--username is required" in result.output+ assert all(name not in result.output for name in ("unsloth", "alice", "bob"))+ assert {table: db_rows(table) for table in before} == before++[email protected]("target", ["unsloth", "alice", "bob"])+def test_cli_reset_only_target_and_owner_only_desktop_rotation(matrix, reset_cli, target):+ client, _, _ = matrix+ credentials = seed_credentials()+ desktop = storage.create_desktop_secret()+ auth_dir = storage.DB_PATH.parent+ for filename in (studio_cli.BOOTSTRAP_PASSWORD_FILE, studio_cli.DESKTOP_SECRET_FILE):+ (auth_dir / filename).write_text("owner-only", encoding = "utf-8")+ before = {name: storage.get_user_record(name) for name in credentials}+ result = reset_cli.invoke(+ studio_cli.studio_app, ["reset-password", "--username", target.upper()]+ )+ assert result.exit_code == 0, result.output+ assert f"New password for '{target}'" in result.output+ for name, (_, refresh, key) in credentials.items():+ after = storage.get_user_record(name)+ if name == target:+ assert after["jwt_secret"] != before[name]["jwt_secret"]+ assert hashing.verify_password(+ "reset-password", after["password_salt"], after["password_hash"]+ )+ else:+ assert after == before[name]+ assert (storage.verify_refresh_token(refresh) is None) == (name == target)+ assert (storage.validate_api_key(key) is None) == (name == target)+ assert (storage.validate_desktop_secret(desktop) is None) == (target == "unsloth")+ for filename in (studio_cli.BOOTSTRAP_PASSWORD_FILE, studio_cli.DESKTOP_SECRET_FILE):+ assert (auth_dir / filename).exists() == (target != "unsloth")+ assert login(client, target, "reset-password").status_code == 200+++def test_cli_reset_clears_pending_setup_and_never_reactivates(auth_env, reset_cli):+ client, _, _ = auth_env+ body = create(client, "alice").json()+ storage.set_account_active(body["account"]["account_id"], False)+ result = reset_cli.invoke(studio_cli.studio_app, ["reset-password", "--username", "alice"])+ assert result.exit_code == 0+ row = next(row for row in db_rows("auth_user") if row["username"] == "alice")+ assert row["setup_code_hash"] is None and row["setup_code_expires_at"] is None+ assert row["is_active"] == 0 and row["must_change_password"] == 0+ assert login(client, "alice", body["setup_code"]).status_code == 401+ assert login(client, "alice", "reset-password").status_code == 401+ storage.set_account_active(body["account"]["account_id"], True)+ assert login(client, "alice", "reset-password").status_code == 200+++def test_cli_unknown_target_never_creates_account_or_changes_credentials(matrix, reset_cli):+ before = db_rows("auth_user")+ result = reset_cli.invoke(studio_cli.studio_app, ["reset-password", "--username", "missing"])+ assert result.exit_code == 1+ assert result.output == "Error: account not found.\n"+ assert db_rows("auth_user") == before++[email protected]("actor", ["unsloth", "alice", "bob"])+def test_logout_revokes_only_actor_and_only_owner_clears_bootstrap_state(matrix, actor):+ client, _, _ = matrix+ tokens = {+ name: authentication.create_refresh_token(name) for name in ("unsloth", "alice", "bob")+ }+ response = client.post("/api/auth/logout", headers = headers(actor))+ assert response.status_code == 204+ for name, token in tokens.items():+ assert (storage.verify_refresh_token(token) is None) == (name == actor)+ assert client.app.state.bootstrap_password == (+ None if actor == "unsloth" else "owner-bootstrap"+ )+++ "method,suffix,payload",+ [+ ("POST", "/setup-code", None),+ ("PATCH", "", {"is_active": False}),+ ("DELETE", "", None),+ ],+)+def test_unknown_account_id_returns_404(matrix, method, suffix, payload):+ response = matrix[0].request(+ method, "/api/accounts/missing" + suffix, headers = headers(), json = payload+ )+ assert response.status_code == 404+ assert response.json() == {"detail": "Account not found"}+++def test_retirement_preserves_symlink_target_and_collision(auth_env, monkeypatch):+ _, _, accounts = auth_env+ storage.create_initial_user("alice", "alice-password", secrets.token_urlsafe(64))+ account = storage.get_account("alice")+ root = run_as(account, storage_roots.workspace_root)+ owner_file = storage_roots.workspace_root() / "owner-data"+ owner_file.mkdir()+ (owner_file / "private").write_text("owner")+ root.parent.mkdir(parents = True, exist_ok = True)+ root.symlink_to(owner_file, target_is_directory = True)++ class FrozenDatetime:+ @staticmethod+ def now(tz):+ return datetime(2026, 1, 1, tzinfo = tz)++ monkeypatch.setattr(accounts, "datetime", FrozenDatetime)+ existing = root.with_name(root.name + "-deleted-20260101T000000000000Z")+ existing.mkdir()+ (existing / "preserved").write_text("old")+ accounts.retire_account_roots(account)+ assert (owner_file / "private").read_text() == "owner"+ assert (existing / "preserved").read_text() == "old"+ assert existing.with_name(existing.name + "-1").is_symlink()+ assert not root.is_symlink()+ with pytest.raises(ValueError):+ accounts.retire_account_roots(OWNER)+++def test_retirement_failure_stays_disabled_after_a_racing_reactivation(matrix, monkeypatch):+ account = storage.get_account("alice")+ set_active = storage.set_account_active+ first = True++ def reactivate_once(account_id, is_active):+ nonlocal first+ result = set_active(account_id, is_active)+ if first:+ first = False+ set_active(account_id, True)+ return result++ def fail(_):+ raise PermissionError("locked directory")++ monkeypatch.setattr(storage, "set_account_active", reactivate_once)+ with pytest.raises(PermissionError):+ storage.delete_account(account.account_id, fail)+ assert storage.get_user_record("alice")["is_active"] == 0+++def test_recreated_account_rejects_late_tokens_from_the_deleted_identity(matrix):+ client, _, _ = matrix+ old = storage.get_user_record("alice")+ old_access = authentication.create_access_token("alice")+ assert client.delete(f"/api/accounts/{old['account_id']}", headers = headers()).status_code == 204+ fresh = create(client, "alice").json()+ late_refresh = authentication.create_refresh_token("alice", secret = old["jwt_secret"])+ assert storage.verify_refresh_token(late_refresh) is None+ assert (+ client.get(+ "/api/auth/api-keys", headers = {"Authorization": "Bearer " + old_access}+ ).status_code+ == 401+ )+ assert login(client, "alice", "alice-password").status_code == 401+ assert login(client, "alice", fresh["setup_code"]).status_code == 200+++def test_logout_from_a_deleted_identity_spares_the_recreated_account(matrix):+ client, auth, _ = matrix+ old = storage.get_user_record("alice")+ old_access = authentication.create_access_token("alice", secret = old["jwt_secret"])+ replacement = {}++ def delete_and_recreate_alice() -> bool:+ storage.delete_account(old["account_id"], lambda account: None)+ storage.create_initial_user("alice", "second-password", secrets.token_urlsafe(64))+ fresh = storage.get_user_record("alice")+ replacement["account_id"] = fresh["account_id"]+ replacement["refresh"] = authentication.create_refresh_token(+ "alice", secret = fresh["jwt_secret"]+ )+ return False++ client.app.dependency_overrides[auth.authenticated_without_credential] = (+ delete_and_recreate_alice+ )+ try:+ response = client.post(+ "/api/auth/logout", headers = {"Authorization": "Bearer " + old_access}+ )+ finally:+ client.app.dependency_overrides.clear()++ assert response.status_code == 204+ assert replacement["account_id"] != old["account_id"]+ assert storage.verify_refresh_token(replacement["refresh"]) == ("alice", False)+++def test_auth_schema_setup_runs_once_per_database_file(auth_env, tmp_path):+ """Every auth connection re-ran the schema DDL; it is cached per file and schema version."""+ storage._auth_schema_ready.clear()+ storage.get_connection().close()+ storage.get_connection().close()+ assert len(storage._auth_schema_ready) == 1+ replaced = tmp_path / "studio" / "auth" / "auth.db"+ for suffix in ("", "-wal", "-shm"):+ Path(str(replaced) + suffix).unlink(missing_ok = True)+ conn = storage.get_connection()+ tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}+ conn.close()+ # The recreated file may reuse the inode and reach the same schema version, so the key can+ # collide with the first one; the schema running again is the observable requirement.+ assert "auth_user" in tables+++def test_a_database_failure_after_retirement_puts_the_roots_back(matrix, monkeypatch):+ """The auth transaction rolls back on a sqlite error, so the renamed roots must come back too."""+ import sqlite3++ from routes import accounts as accounts_module+ from utils.account_context import run_as+ from utils.paths import storage_roots++ client, _, _ = matrix+ account = storage.get_account("alice")+ roots = [+ run_as(account, root)+ for root in (+ storage_roots.workspace_root,+ storage_roots.project_workspaces_root,+ storage_roots.tmp_root,+ )+ ]+ for root in roots:+ root.mkdir(parents = True, exist_ok = True)+ (root / "private.txt").write_text("keep", encoding = "utf-8")+ real_get_connection = storage.get_connection++ class Proxy:+ def __init__(self, conn):+ self._conn = conn++ def execute(self, sql, *args, **kwargs):+ if "DELETE FROM auth_user" in sql:+ raise sqlite3.OperationalError("disk I/O error")+ return self._conn.execute(sql, *args, **kwargs)++ def __getattr__(self, name):+ return getattr(self._conn, name)++ def __enter__(self):+ return self._conn.__enter__()++ def __exit__(self, *args):+ return self._conn.__exit__(*args)++ armed = {"on": True}+ monkeypatch.setattr(+ storage,+ "get_connection",+ lambda: Proxy(real_get_connection()) if armed["on"] else real_get_connection(),+ )+ with pytest.raises(sqlite3.OperationalError):+ storage.delete_account(account.account_id, accounts_module.retire_account_roots)+ armed["on"] = False+ assert storage.get_user_record("alice") is not None+ for root in roots:+ assert (root / "private.txt").read_text(encoding = "utf-8") == "keep"+ assert not [p for p in root.parent.iterdir() if "-deleted-" in p.name]+ response = client.patch(+ f"/api/accounts/{account.account_id}", headers = headers(), json = {"is_active": True}+ )+ assert response.status_code == 200+ assert (+ client.delete(f"/api/accounts/{account.account_id}", headers = headers()).status_code == 204+ )diff --git a/studio/backend/tests/test_account_local_model_resolver.py b/studio/backend/tests/test_account_local_model_resolver.pynew file mode 100644index 00000000000..e5bc2d6038f--- /dev/null+++ b/studio/backend/tests/test_account_local_model_resolver.py@@ -0,0 +1,116 @@+# 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 auto-switch resolver index is one account's answer: its roots (that account's scan folders+and HF cache home) are private, so a process-global snapshot hands the next account the previous+one's checkpoint path and the load then refuses it as foreign."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++import routes.inference as inference+from auth import policy+from core.inference import local_model_resolver as resolver+from hub.services.models import account_access as access+from storage import studio_db+from utils import openai_auto_switch_settings as switch_settings+from utils.account_context import OWNER, AccountContext, arun_as, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def home(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(inference, "_managed_catalogs", {})+ monkeypatch.setattr(switch_settings, "get_openai_auto_switch_enabled", lambda: True)+ monkeypatch.setattr(switch_settings, "get_openai_auto_download_enabled", lambda: False)+ monkeypatch.setattr(switch_settings, "get_model_override", lambda *a, **k: None)+ resolver.invalidate_index()+ yield tmp_path+ resolver.invalidate_index()+++def _private_gguf(+ account,+ home,+ filename = "shared-model.gguf",+):+ """A checkpoint in a scan folder registered in *account*'s own database."""+ root = home / "accounts" / account.account_id / "private_models"+ root.mkdir(parents = True, exist_ok = True)+ model = root / filename+ model.write_bytes(b"GGUF" + b"\0" * 64)++ def _register():+ connection = studio_db.get_connection()+ with connection:+ connection.execute(+ "INSERT INTO scan_folders (path, created_at) VALUES (?, datetime('now'))",+ (str(root),),+ )+ connection.close()++ run_as(account, _register)+ return model+++def _request():+ return SimpleNamespace(+ scope = {},+ state = SimpleNamespace(),+ url = SimpleNamespace(path = "/v1/chat/completions"),+ headers = {},+ )+++def test_a_warm_resolver_index_does_not_answer_for_the_next_account(home):+ alice_model = _private_gguf(ALICE, home)+ bob_model = _private_gguf(BOB, home)++ assert run_as(ALICE, resolver.resolve_local_gguf, "shared-model")[0] == str(alice_model)+ assert run_as(BOB, resolver.resolve_local_gguf, "shared-model")[0] == str(bob_model)+ # And back again: neither account's snapshot is displaced by the other's.+ assert run_as(ALICE, resolver.resolve_local_gguf, "shared-model")[0] == str(alice_model)+++def test_an_alias_another_account_warmed_still_switches_to_the_callers_own_checkpoint(+ home, monkeypatch+):+ alice_model = _private_gguf(ALICE, home)+ bob_model = _private_gguf(BOB, home)+ loaded = []++ async def _load(request, *args, **kwargs):+ # The real impl refuses a path the caller cannot see, which is the 404 under test.+ access.require_model_access(request.model_path)+ loaded.append(request.model_path)+ return {}++ monkeypatch.setattr(inference, "_load_model_impl", _load)++ asyncio.run(+ arun_as(ALICE, inference._maybe_auto_switch_model("shared-model", _request(), "alice"))+ )+ assert loaded == [str(alice_model)]+ asyncio.run(arun_as(BOB, inference._maybe_auto_switch_model("shared-model", _request(), "bob")))+ assert loaded[-1] == str(bob_model)+++def test_the_owner_keeps_one_index_on_a_single_user_install(home, monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ owner_model = _private_gguf(OWNER, home, "owner-model.gguf")+ scans = []+ real = resolver._build_index+ monkeypatch.setattr(resolver, "_build_index", lambda: (scans.append(1), real())[1])++ for _ in range(3):+ assert resolver.resolve_local_gguf("owner-model")[0] == str(owner_model)+ assert len(scans) == 1diff --git a/studio/backend/tests/test_account_login_name_oracle.py b/studio/backend/tests/test_account_login_name_oracle.pynew file mode 100644index 00000000000..46f2aca05c9--- /dev/null+++ b/studio/backend/tests/test_account_login_name_oracle.py@@ -0,0 +1,24 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An unauthenticated client must not learn account existence from lockout scope."""++from studio.backend.tests.test_account_lifecycle import auth_env, login+from auth import storage+++def test_login_throttling_does_not_disclose_account_existence(auth_env):+ client, auth, _ = auth_env+ storage.issue_account_setup_code(username = "alice")+ observed = {}+ for candidate in ("alice", "not-an-account"):+ # Independent attacker sessions, each beginning with empty rate limits.+ auth._LOGIN_BUCKETS.clear()+ auth._LOGIN_IP_BUCKETS.clear()+ for _ in range(auth._LOGIN_MAX_FAILS):+ assert login(client, candidate, "wrong-password").status_code == 401+ # No correct password or privileged request is needed for the oracle.+ response = login(client, "unsloth", "also-wrong")+ observed[candidate] = response.status_code+ print(f"Unauthenticated probe statuses: {observed}")+ assert observed["alice"] == observed["not-an-account"], observeddiff --git a/studio/backend/tests/test_account_login_timing_oracle.py b/studio/backend/tests/test_account_login_timing_oracle.pynew file mode 100644index 00000000000..c33bd6354f6--- /dev/null+++ b/studio/backend/tests/test_account_login_timing_oracle.py@@ -0,0 +1,46 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A login miss spends the same password-hashing work as a wrong password, so an+unauthenticated client cannot time /api/auth/login to learn which names exist."""++import hashlib++import pytest++from auth import hashing, storage+from studio.backend.tests.test_account_lifecycle import auth_env, login, matrix # noqa: F401+++def pbkdf2_calls(monkeypatch):+ calls = []+ real = hashlib.pbkdf2_hmac++ def counting(*args, **kwargs):+ calls.append(args[0])+ return real(*args, **kwargs)++ monkeypatch.setattr(hashing.hashlib, "pbkdf2_hmac", counting)+ return calls+++def _rounds_for(client, pbkdf2_calls, username, password):+ del pbkdf2_calls[:]+ assert login(client, username, password).status_code == 401+ return len(pbkdf2_calls)+++def test_unknown_inactive_and_pending_names_cost_a_verification(matrix, pbkdf2_calls):+ client, _, _ = matrix+ baseline = _rounds_for(client, pbkdf2_calls, "alice", "wrong-password")+ assert baseline == 1++ assert _rounds_for(client, pbkdf2_calls, "not-an-account", "wrong-password") == baseline++ bob = storage.get_user_record("bob")+ storage.set_account_active(bob["account_id"], False)+ assert _rounds_for(client, pbkdf2_calls, "bob", "bob-password") == baseline++ storage.issue_account_setup_code(username = "carol")+ assert _rounds_for(client, pbkdf2_calls, "carol", "not-the-setup-code") == baselinediff --git a/studio/backend/tests/test_account_macos_profile_symlinks.py b/studio/backend/tests/test_account_macos_profile_symlinks.pynew file mode 100644index 00000000000..a60755149fb--- /dev/null+++ b/studio/backend/tests/test_account_macos_profile_symlinks.py@@ -0,0 +1,42 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Regression test for the macOS half of the managed-account link invariant.++Linux already withholds LANDLOCK_ACCESS_FS_MAKE_SYM from every writable root+(test_managed_child_cannot_plant_a_link_in_its_own_tree). The macOS profile+granted a plain file-write* on the same roots, and file-write* covers+symlink creation, so a managed tool could plant a link that the unconfined job+child later follows out of the account's roots.++"""++import sys+from pathlib import Path++import pytest++from core.inference import tool_confinement+from core.inference import tools+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("alice-id", "alice")++[email protected](autouse = True)+def _roots(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ return tmp_path+++def test_macos_profile_refuses_symlink_creation_in_the_writable_roots(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ run_as(ALICE, tools._get_workdir, "chat")+ profile = run_as(ALICE, tools._account_confinement).wrap(["true"])[2]++ deny = "(deny file-write-create (vnode-type SYMLINK))"+ assert deny in profile, "file-write* grants symlink creation unless it is subtracted back out"+ # Later rules win, so the deny has to sit after every writable grant.+ assert profile.rstrip().endswith(deny)+ assert profile.index(deny) > profile.rindex("(allow file-read* file-write* (subpath")diff --git a/studio/backend/tests/test_account_macos_profile_temp_root.py b/studio/backend/tests/test_account_macos_profile_temp_root.pynew file mode 100644index 00000000000..c46fc9efbc7--- /dev/null+++ b/studio/backend/tests/test_account_macos_profile_temp_root.py@@ -0,0 +1,78 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""Regression test for the macOS half of the managed-account temp invariant.++Linux grants a confined tool no read on the system temp tree at all+(``_SYSTEM_READ_ROOTS`` names no /tmp), only the account's own ``tmp_root()``+among the writable roots. The macOS profile granted ``file-read*`` on the whole+shared ``/private/tmp``, so a managed tool could read every same-UID temp file+the owner or any other application on the host had left there; the hidden-root+deny only covers ``<tempdir>/unsloth-studio``. The child's TMPDIR already points+inside its own sandbox dir, so the shared tree is not needed for startup.+"""++import re+import sys+from pathlib import Path++import pytest++from core.inference import tool_confinement+from core.inference import tools+from utils.account_context import AccountContext, run_as+from utils.paths.storage_roots import tmp_root++ALICE = AccountContext("alice-id", "alice")++_RULE = re.compile(+ r'^\((allow|deny) (file-[^ (]*(?: file-[^ (]*)*)((?: \(subpath "(?:[^"\\]|\\.)*"\))+)\)$'+)+_SUBPATH = re.compile(r'\(subpath "((?:[^"\\]|\\.)*)"\)')+++def _grants_read(profile: str, path: str) -> bool:+ """Later rules win in an SBPL profile, so the last matching rule decides."""+ granted = False+ for line in profile.splitlines():+ match = _RULE.match(line.strip())+ if not match or "file-read*" not in match.group(2).split():+ continue+ for raw in _SUBPATH.findall(match.group(3)):+ root = raw.replace('\\"', '"').replace("\\\\", "\\")+ if path == root or path.startswith(root.rstrip("/") + "/"):+ granted = match.group(1) == "allow"+ return granted++[email protected](autouse = True)+def _roots(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ return tmp_path+++def _profile(monkeypatch) -> str:+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ run_as(ALICE, tools._get_workdir, "chat")+ return run_as(ALICE, tools._account_confinement).wrap(["true"])[2]+++def test_macos_profile_grants_no_read_on_the_shared_temp_tree(monkeypatch):+ profile = _profile(monkeypatch)+ account_tmp = str(Path(run_as(ALICE, tmp_root)).resolve())+ # Every temp tree a macOS child can reach: the world-writable one, and the per-user+ # darwin tree launchd points TMPDIR at.+ for root in ("/private/tmp", "/tmp", "/private/var/tmp", "/private/var/folders/ab/cd/T"):+ assert not _grants_read(+ profile, root+ ), f"the profile grants a managed tool read on the shared temp tree {root}"+ outsider = str(Path(root) / "some-other-app.sock")+ assert not _grants_read(+ profile, outsider+ ), f"the profile grants a managed tool read on {outsider}"+ # The account keeps its own temp root, wherever tempfile puts it.+ assert _grants_read(profile, account_tmp)+ assert _grants_read(profile, account_tmp + "/scratch.txt")diff --git a/studio/backend/tests/test_account_media_generation_arbiter.py b/studio/backend/tests/test_account_media_generation_arbiter.pynew file mode 100644index 00000000000..3a45d7990c6--- /dev/null+++ b/studio/backend/tests/test_account_media_generation_arbiter.py@@ -0,0 +1,73 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import pytest++import core.inference.gpu_arbiter as arb+from auth import policy+from hub.services.models import account_access+from utils.account_context import AccountContext, bind_account, reset_account, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def calls(monkeypatch):+ recorded: list[str] = []+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(arb, "_owner", None)+ monkeypatch.setattr(arb, "_owner_account", None)+ monkeypatch.setattr(arb, "_prior_account", None)+ monkeypatch.setattr(account_access, "_generation_accounts", {})+ monkeypatch.setattr(account_access, "_generation_holders", {})+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: recorded.append("evict-chat"))+ monkeypatch.setitem(arb._EVICTORS, arb.DIFFUSION, lambda: recorded.append("evict-diffusion"))+ monkeypatch.setitem(arb._EVICTORS, arb.VIDEO, lambda: recorded.append("evict-video"))+ return recorded+++def test_image_generation_blocks_foreign_chat_load(calls):+ run_as(ALICE, arb.acquire_for, arb.DIFFUSION, lambda: None)+ token = bind_account(ALICE)+ try:+ with account_access.media_generation_slot("diffusion"):+ with pytest.raises(arb.GpuBusyForAnotherAccountError):+ run_as(BOB, arb.acquire_for, arb.CHAT, lambda: None)+ finally:+ reset_account(token)+ assert calls == []+++def test_video_generation_blocks_foreign_chat_load(calls, monkeypatch):+ from core.inference import video as video_module++ backend = video_module.get_video_backend()+ monkeypatch.setattr(backend, "_generate_job_active", True, raising = False)+ monkeypatch.setattr(backend, "_generate_job_account", ALICE.account_id, raising = False)+ run_as(ALICE, arb.acquire_for, arb.VIDEO, lambda: None)+ with pytest.raises(arb.GpuBusyForAnotherAccountError):+ run_as(BOB, arb.acquire_for, arb.CHAT, lambda: None)+ assert calls == []+++def test_own_image_generation_does_not_block_own_load(calls):+ run_as(ALICE, arb.acquire_for, arb.DIFFUSION, lambda: None)+ token = bind_account(ALICE)+ try:+ with account_access.media_generation_slot("diffusion"):+ run_as(ALICE, arb.acquire_for, arb.CHAT, lambda: None)+ finally:+ reset_account(token)+ assert calls == ["evict-diffusion"]+ assert arb.current_owner() == arb.CHAT+++def test_single_user_install_still_evicts_during_a_generation(calls, monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ arb.acquire_for(arb.DIFFUSION, lambda: None)+ with account_access.media_generation_slot("diffusion"):+ arb.acquire_for(arb.CHAT, lambda: None)+ assert calls == ["evict-diffusion"]diff --git a/studio/backend/tests/test_account_media_generation_deactivated.py b/studio/backend/tests/test_account_media_generation_deactivated.pynew file mode 100644index 00000000000..07fc422213c--- /dev/null+++ b/studio/backend/tests/test_account_media_generation_deactivated.py@@ -0,0 +1,142 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Deactivation does not cancel media generations, so the owner must stay scoped.++Deactivating the last managed account drops the ACTIVE count back to one, but its+in-flight image generation keeps running: ownership tracking has to follow+``account_scope()`` (any managed account exists), not the active-count login mode.+"""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from routes import inference+from state import active_generations+from utils.account_context import OWNER, AccountContext, bind_account, reset_account, run_as++ALICE = AccountContext("a" * 32, "alice")+++def deactivatable(monkeypatch, tmp_path):+ """A one-managed-account install whose account can be deactivated mid-generation."""+ multi = {"value": True}+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: multi["value"])+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_generation_accounts", {})+ monkeypatch.setattr(access, "_generation_holders", {})+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ active_generations.reset_for_tests()+ yield multi+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(inference.studio_router, prefix = "/api/inference")+ return TestClient(app)+++def alice_resident(monkeypatch):+ running = threading.Event()+ cancelled = threading.Event()++ def generate(**kwargs):+ running.set()+ cancelled.wait(20)+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG++ raise RuntimeError(DIFFUSION_CANCELLED_MSG)++ backend = SimpleNamespace(+ is_loaded = True,+ status = lambda: {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ },+ generate = generate,+ generate_progress = lambda: {"active": True, "step": 3, "total": 10},+ cancel_generate = lambda **kwargs: (cancelled.set(), True)[1],+ )+ from core.inference import diffusion_engine_router++ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ monkeypatch.setattr(gpu_arbiter, "_owner", "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)+ return SimpleNamespace(running = running, cancelled = cancelled)+++def _start_alice_generation(alice_resident):+ result = {}++ def run():+ with client_for(ALICE) as client:+ result["response"] = client.post(+ "/api/inference/images/generate", json = {"prompt": "a sloth"}+ )++ thread = threading.Thread(target = run)+ thread.start()+ assert alice_resident.running.wait(20)+ return thread, result+++def test_owner_cannot_cancel_a_deactivated_accounts_image_generation(deactivatable, alice_resident):+ thread, result = _start_alice_generation(alice_resident)+ try:+ # The owner deactivates alice mid-generation: the active count drops to one, but+ # set_account_active() only cancels chat generations, so this image job runs on.+ deactivatable["value"] = False+ assert run_as(OWNER, access.generation_is_foreign, "diffusion") is True+ assert run_as(OWNER, access.tracked_generation_account) == OWNER.account_id+ with client_for(OWNER) as client:+ assert client.post("/api/inference/images/generate/cancel").json() == {+ "cancelled": False+ }+ assert not alice_resident.cancelled.is_set()+ finally:+ alice_resident.cancelled.set()+ thread.join(20)+ assert result["response"].status_code == 409+++def test_a_deactivated_account_still_owns_its_own_generation(deactivatable):+ token = bind_account(ALICE)+ try:+ with access.media_generation_slot("diffusion"):+ deactivatable["value"] = False+ assert access.generation_is_mine("diffusion") is True+ assert access.generation_is_foreign("diffusion") is False+ assert access.tracked_generation_account() == ALICE.account_id+ finally:+ reset_account(token)diff --git a/studio/backend/tests/test_account_media_generation_owner.py b/studio/backend/tests/test_account_media_generation_owner.pynew file mode 100644index 00000000000..67cafe9d867--- /dev/null+++ b/studio/backend/tests/test_account_media_generation_owner.py@@ -0,0 +1,197 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An image generation belongs to the account that started it, not to the model's loader."""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from routes import inference+from state import active_generations+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_generation_accounts", {})+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ active_generations.reset_for_tests()+ yield+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(inference.studio_router, prefix = "/api/inference")+ app.include_router(inference.router, prefix = "/v1")+ return TestClient(app)+++def shared_resident(monkeypatch):+ from core.inference import diffusion_engine_router++ running = threading.Event()+ cancelled = threading.Event()++ def generate(**kwargs):+ running.set()+ cancelled.wait(20)+ from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG++ raise RuntimeError(DIFFUSION_CANCELLED_MSG)++ backend = SimpleNamespace(+ is_loaded = True,+ status = lambda: {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ },+ generate = generate,+ generate_progress = lambda: {"active": True, "step": 3, "total": 10},+ cancel_generate = lambda **kwargs: (cancelled.set(), True)[1],+ )+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ monkeypatch.setattr(gpu_arbiter, "_owner", "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", BOB.account_id)+ return SimpleNamespace(running = running, cancelled = cancelled)+++def _start_alice_generation(shared_resident):+ result = {}++ def run():+ with client_for(ALICE) as client:+ result["response"] = client.post(+ "/api/inference/images/generate", json = {"prompt": "a sloth"}+ )++ thread = threading.Thread(target = run)+ thread.start()+ assert shared_resident.running.wait(20)+ return thread, result+++def test_generation_progress_and_cancel_follow_the_account_that_started_it(shared_resident):+ thread, result = _start_alice_generation(shared_resident)+ try:+ with client_for(ALICE) as client:+ progress = client.get("/api/inference/images/generate-progress").json()+ assert progress["active"] is True and progress["step"] == 3+ assert client.post("/api/inference/images/generate/cancel").json() == {+ "cancelled": True+ }+ finally:+ shared_resident.cancelled.set()+ thread.join(20)+ assert result["response"].status_code == 409+++def test_the_model_loader_cannot_see_or_cancel_another_accounts_generation(shared_resident):+ thread, result = _start_alice_generation(shared_resident)+ try:+ with client_for(BOB) as client:+ assert client.get("/api/inference/images/generate-progress").json() == {+ "loaded": True,+ "yours": False,+ }+ assert client.post("/api/inference/images/generate/cancel").json() == {+ "cancelled": False+ }+ assert not shared_resident.cancelled.is_set()+ finally:+ shared_resident.cancelled.set()+ thread.join(20)+ assert result["response"].status_code == 409+++def test_residency_still_governs_progress_and_cancel_with_no_generation_in_flight(monkeypatch):+ from core.inference import diffusion_engine_router++ backend = SimpleNamespace(+ status = lambda: {"loaded": True, "repo_id": "org/public-model"},+ generate_progress = lambda: {"active": False},+ cancel_generate = lambda **kwargs: False,+ )+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ monkeypatch.setattr(gpu_arbiter, "_owner", "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", BOB.account_id)+ with client_for(ALICE) as client:+ assert client.get("/api/inference/images/generate-progress").json() == {+ "loaded": True,+ "yours": False,+ }+ assert client.post("/api/inference/images/generate/cancel").json() == {"cancelled": False}+ with client_for(BOB) as client:+ assert client.get("/api/inference/images/generate-progress").json()["active"] is False+++def _start_alice_openai_generation(shared_resident):+ result = {}++ def run():+ with client_for(ALICE) as client:+ result["response"] = client.post(+ "/v1/images/generations",+ json = {+ "prompt": "a sloth",+ "size": "256x256",+ "response_format": "b64_json",+ },+ )++ thread = threading.Thread(target = run)+ thread.start()+ assert shared_resident.running.wait(20)+ return thread, result+++def test_openai_image_generations_belong_to_the_account_that_started_them(shared_resident):+ thread, result = _start_alice_openai_generation(shared_resident)+ try:+ with client_for(ALICE) as client:+ progress = client.get("/api/inference/images/generate-progress").json()+ assert progress["active"] is True and progress["step"] == 3+ with client_for(BOB) as client:+ assert client.get("/api/inference/images/generate-progress").json() == {+ "loaded": True,+ "yours": False,+ }+ assert client.post("/api/inference/images/generate/cancel").json() == {+ "cancelled": False+ }+ assert not shared_resident.cancelled.is_set()+ finally:+ shared_resident.cancelled.set()+ thread.join(20)+ assert result["response"].status_code >= 400diff --git a/studio/backend/tests/test_account_media_generation_slot.py b/studio/backend/tests/test_account_media_generation_slot.pynew file mode 100644index 00000000000..7210fe0598e--- /dev/null+++ b/studio/backend/tests/test_account_media_generation_slot.py@@ -0,0 +1,160 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A queued image request is not an active generation: the slot holder owns progress and cancel."""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter+from core.inference.diffusion import DiffusionBackend+from core.inference.diffusion_families import DIFFUSION_CANCELLED_MSG+from hub.services.models import account_access as access+from routes import inference+from state import active_generations+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_generation_accounts", {})+ if hasattr(access, "_generation_holders"):+ monkeypatch.setattr(access, "_generation_holders", {})+ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: True)+ monkeypatch.setattr(gpu_arbiter, "_owner", "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ active_generations.reset_for_tests()+ yield+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(inference.studio_router, prefix = "/api/inference")+ return TestClient(app)+++class SharedEngine:+ is_loaded = True++ def __init__(self):+ self.slots = DiffusionBackend()+ self.entered = threading.Semaphore(0)+ self.running = threading.Event()+ self.stop_all = threading.Event()++ def status(self):+ return {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ }++ def generate(self, **kwargs):+ cancel = threading.Event()+ self.entered.release()+ with self.slots._generation_slot(cancel):+ self.running.set()+ while not cancel.is_set() and not self.stop_all.is_set():+ cancel.wait(0.02)+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)++ def generate_progress(self):+ return {"active": True, "step": 3, "total_steps": 10, "fraction": 0.3, "eta_seconds": 1.0}++ def cancel_generate(self, expected_account = None):+ return self.slots.cancel_generate()+++def engine(monkeypatch):+ from core.inference import diffusion_engine_router++ shared = SharedEngine()+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: shared)+ return shared+++def _post_generate(account, engine, results, key):+ def run():+ with client_for(account) as client:+ results[key] = client.post("/api/inference/images/generate", json = {"prompt": "a sloth"})++ thread = threading.Thread(target = run, daemon = True)+ thread.start()+ assert engine.entered.acquire(timeout = 20)+ return thread+++def test_a_queued_request_does_not_take_progress_and_cancel_from_the_active_generation(engine):+ results = {}+ alice = _post_generate(ALICE, engine, results, "alice")+ assert engine.running.wait(20)+ bob = _post_generate(BOB, engine, results, "bob")+ try:+ with client_for(BOB) as client:+ assert client.get("/api/inference/images/generate-progress").json() == {+ "loaded": True,+ "yours": False,+ }+ assert client.post("/api/inference/images/generate/cancel").json() == {+ "cancelled": False+ }+ with client_for(ALICE) as client:+ progress = client.get("/api/inference/images/generate-progress").json()+ assert progress["active"] is True and progress["step"] == 3+ assert client.post("/api/inference/images/generate/cancel").json() == {+ "cancelled": True+ }+ finally:+ engine.stop_all.set()+ alice.join(20)+ bob.join(20)+ assert results["alice"].status_code == 409++[email protected]("engine", ["diffusers", "sd_cpp"])+def test_cancel_rechecks_the_authorized_account_under_the_lock(engine):+ """The route authorizes on the loop and cancels on an executor; a generation that finished and a successor that took the slot in between must not receive the stale cancel."""+ if engine == "diffusers":+ from core.inference.diffusion import DiffusionBackend++ backend = object.__new__(DiffusionBackend)+ backend._generation_cancel_lock = threading.Lock()+ backend._generation_owns_slot = True+ else:+ from core.inference.sd_cpp_backend import SdCppDiffusionBackend+ backend = object.__new__(SdCppDiffusionBackend)+ backend._lock = threading.RLock()+ event = threading.Event()+ backend._active_generate_cancel = event+ backend._active_generate_account = BOB.account_id+ assert backend.cancel_generate(expected_account = ALICE.account_id) is False+ assert not event.is_set()+ assert backend.cancel_generate(expected_account = BOB.account_id) is True+ assert event.is_set()diff --git a/studio/backend/tests/test_account_media_generation_transition.py b/studio/backend/tests/test_account_media_generation_transition.pynew file mode 100644index 00000000000..5395b61b21f--- /dev/null+++ b/studio/backend/tests/test_account_media_generation_transition.py@@ -0,0 +1,73 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# 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 single-user to multi-user transition must not strand an in-flight media generation."""++from __future__ import annotations++import pytest++import core.inference.gpu_arbiter as arb+from auth import policy+from hub.services.models import account_access+from utils.account_context import OWNER, AccountContext, bind_account, reset_account, run_as++BOB = AccountContext("b" * 32, "bob")+++def calls(monkeypatch):+ recorded: list[str] = []+ multi = {"value": False}+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: multi["value"])+ monkeypatch.setattr(arb, "_owner", None)+ monkeypatch.setattr(arb, "_owner_account", None)+ monkeypatch.setattr(arb, "_prior_account", None)+ monkeypatch.setattr(account_access, "_generation_accounts", {})+ monkeypatch.setattr(account_access, "_generation_holders", {})+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: recorded.append("evict-chat"))+ monkeypatch.setitem(arb._EVICTORS, arb.DIFFUSION, lambda: recorded.append("evict-diffusion"))+ monkeypatch.setitem(arb._EVICTORS, arb.VIDEO, lambda: recorded.append("evict-video"))+ return recorded, multi+++def test_first_managed_account_cannot_evict_an_owner_generation_started_single_user(calls):+ recorded, multi = calls+ arb.acquire_for(arb.DIFFUSION, lambda: None)+ token = bind_account(OWNER)+ try:+ with account_access.media_generation("diffusion"):+ # The owner creates the first managed account mid-generation.+ multi["value"] = True+ with pytest.raises(arb.GpuBusyForAnotherAccountError):+ run_as(BOB, arb.acquire_for, arb.CHAT, lambda: None)+ finally:+ reset_account(token)+ assert recorded == []+ assert arb.current_owner() == arb.DIFFUSION+ assert account_access._generation_accounts == {}+++def test_slot_holder_survives_the_same_transition(calls):+ recorded, multi = calls+ arb.acquire_for(arb.DIFFUSION, lambda: None)+ token = bind_account(OWNER)+ try:+ with account_access.media_generation_slot("diffusion"):+ multi["value"] = True+ with pytest.raises(arb.GpuBusyForAnotherAccountError):+ run_as(BOB, arb.acquire_for, arb.CHAT, lambda: None)+ finally:+ reset_account(token)+ assert recorded == []+ assert account_access._generation_holders == {}+++def test_single_user_owner_still_evicts_its_own_generation(calls):+ recorded, _ = calls+ arb.acquire_for(arb.DIFFUSION, lambda: None)+ with account_access.media_generation("diffusion"):+ arb.acquire_for(arb.CHAT, lambda: None)+ assert recorded == ["evict-diffusion"]diff --git a/studio/backend/tests/test_account_media_isolation.py b/studio/backend/tests/test_account_media_isolation.pynew file mode 100644index 00000000000..5ffdcfa48ce--- /dev/null+++ b/studio/backend/tests/test_account_media_isolation.py@@ -0,0 +1,240 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Account boundaries exercised through the real media object routes and stores."""++from __future__ import annotations+++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from PIL import Image++from auth import policy, storage as auth_storage+from auth.authentication import get_current_subject+from core.inference import audio_gallery, image_gallery, search_images, video_gallery+from routes import inference, video+from utils.account_context import OWNER, AccountContext, bind_account, reset_account, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(search_images, "_account_states", {})+ monkeypatch.setattr(video, "_managed_jobs", {})+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ connection = auth_storage.get_connection()+ with connection:+ for account in (ALICE, BOB):+ connection.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret,"+ " account_id, role, is_active) VALUES (?, 'salt', 'hash', 'secret', ?, 'user', 1)",+ (account.username, account.account_id),+ )+ connection.close()+ yield+ policy.invalidate_account_cache()+++def _save(kind):+ meta = {+ "prompt": "private prompt",+ "model": "private/model",+ "created_at": 100.0,+ "width": 512,+ "height": 512,+ "steps": 5,+ "guidance": 1.0,+ "seed": 1,+ "num_frames": 49,+ "fps": 24,+ "duration_s": 2.0,+ }+ if kind == "images":+ return image_gallery.save(Image.new("RGB", (8, 8)), meta)+ if kind == "audio":+ meta.update(audio_type = "snac", sample_rate = 24000, created_at = "2026-08-06T00:00:00Z")+ return audio_gallery.save(b"RIFF\x24\x00\x00\x00WAVEfmt ", meta)+ meta["created_at"] = "2026-08-06T00:00:00Z"+ return video_gallery.save(b"\x00\x00\x00\x18ftypmp42", meta)+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.studio_router, prefix = "/api/inference")+ app.include_router(video.router, prefix = "/api/inference")+ app.include_router(video.openai_router, prefix = "/v1")+ return TestClient(app)++[email protected]("kind", ["images", "audio", "video"])[email protected]("account,other", [(ALICE, BOB), (BOB, ALICE)])+def test_gallery_object_routes_do_not_resolve_another_accounts_ids(kind, account, other):+ record = run_as(account, _save, kind)+ root = f"/api/inference/{kind}/gallery"+ with _client(other) as client:+ assert client.get(f"{root}/{record['id']}/file").status_code == 404+ assert client.patch(f"{root}/{record['id']}", json = {"starred": True}).status_code == 404+ assert client.delete(f"{root}/{record['id']}").status_code == 404+ assert record["id"] not in client.get(root).text+ if kind == "video":+ assert client.get(f"{root}/{record['id']}/signed-url").status_code == 404+ assert client.get(f"{root}/{record['id']}/export").status_code == 404+ with _client(account) as client:+ assert client.get(f"{root}/{record['id']}/file").status_code == 200+ assert record["id"] in client.get(root).text+++ "kind,module", [("images", image_gallery), ("audio", audio_gallery), ("video", video_gallery)]+)+def test_clear_and_paths_are_account_scoped(kind, module, tmp_path):+ a = run_as(ALICE, _save, kind)+ b = run_as(BOB, _save, kind)+ assert run_as(ALICE, module.clear) == 1+ path_fn = {+ "images": image_gallery.owned_image_path,+ "audio": audio_gallery.owned_audio_path,+ "video": video_gallery.owned_video_path,+ }[kind]+ assert run_as(ALICE, path_fn, a["id"]) is None+ assert run_as(BOB, path_fn, b["id"]).is_file()+ folder = "videos" if kind == "video" else kind+ assert run_as(OWNER, module.gallery_dir) == tmp_path / folder+ assert run_as(BOB, module.gallery_dir) == tmp_path / "accounts" / BOB.account_id / folder++[email protected]("kind,module", [("images", inference), ("video", video)])+def test_signed_links_authorize_only_the_original_account_and_media(kind, module):+ record = run_as(ALICE, _save, kind)+ sign = module._sign_image_id if kind == "images" else module._sign_video_id+ token = run_as(ALICE, sign, record["id"])+ root = f"/api/inference/{kind}/gallery"+ with _client(BOB) as client:+ assert (+ client.get(f"{root}/{record['id']}/file-signed", params = {"token": token}).status_code+ == 200+ )+ assert client.get(f"{root}/guessed/file-signed", params = {"token": token}).status_code == 401+ tampered = token.replace(ALICE.account_id, BOB.account_id)+ assert (+ client.get(f"{root}/{record['id']}/file-signed", params = {"token": tampered}).status_code+ == 401+ )+ verify = (+ module._verify_image_link_token if kind == "images" else module._verify_video_link_token+ )+ owner_token = run_as(OWNER, sign, record["id"])+ assert owner_token.split(".")[0] == record["id"]+ assert verify(owner_token) == record["id"]+++def test_search_ids_and_clear_fences_are_private(monkeypatch):+ raw = [{"thumbnail": "https://example.com/image.jpg", "url": "https://example.com/page"}]+ monkeypatch.setattr(search_images, "_fetch_thumbnail_bytes", lambda *args: b"thumbnail")+ image_id = run_as(ALICE, search_images.register_images, raw)[0]["id"]+ assert run_as(BOB, search_images.lookup_image, image_id) is None+ assert run_as(BOB, search_images.thumbnail_bytes, image_id) is None+ before = run_as(ALICE, search_images.cache_generation)+ run_as(BOB, search_images.snapshot_and_fence_registrations)+ run_as(BOB, search_images.clear_cache)+ assert run_as(ALICE, search_images.cache_generation) == before+ assert run_as(ALICE, search_images.thumbnail_bytes, image_id) == b"thumbnail"+ with _client(BOB) as client:+ assert client.get(f"/api/inference/search-images/{image_id}").status_code == 404+ run_as(ALICE, search_images.clear_cache)+ assert run_as(ALICE, search_images.thumbnail_bytes, image_id) is None+++def test_openai_video_jobs_are_private_in_memory_and_after_rehydration():+ job = video._VideoJob(+ id = "private-job",+ created_at = 100,+ prompt = "private",+ model = "private/model",+ size = "512x512",+ seconds = "2",+ status = "failed",+ )+ run_as(ALICE, video._remember_job, job)+ assert run_as(BOB, video._lookup_video, job.id) is None+ assert run_as(BOB, video._all_videos) == []+ assert run_as(ALICE, video._lookup_video, job.id).id == job.id+ video._managed_jobs.clear()+ assert run_as(BOB, video._lookup_video, job.id) is None+ assert run_as(ALICE, video._lookup_video, job.id).id == job.id+ with _client(BOB) as client:+ assert client.get(f"/v1/videos/{job.id}").status_code == 404+ assert client.get(f"/v1/videos/{job.id}/content").status_code == 404+ assert client.delete(f"/v1/videos/{job.id}").status_code == 404+++def test_clearing_a_managed_chat_history_reaps_only_its_own_thumbnails(monkeypatch):+ """The clear reaps every account's private thumbnails, not just the owner's."""+ from routes import chat_history++ monkeypatch.setattr(search_images, "_fetch_thumbnail_bytes", lambda *args: b"thumbnail")+ raw = [{"thumbnail": "https://example.com/i.jpg", "url": "https://example.com/p"}]+ ids = {+ account: run_as(account, search_images.register_images, raw)[0]["id"]+ for account in (ALICE, BOB)+ }+ snapshot = run_as(ALICE, chat_history._snapshot_chat_images)+ assert snapshot == {ids[ALICE]}+ run_as(ALICE, search_images.clear_cache, snapshot)+ assert run_as(ALICE, search_images.thumbnail_bytes, ids[ALICE]) is None+ assert run_as(BOB, search_images.thumbnail_bytes, ids[BOB]) == b"thumbnail"+++def test_a_failed_replacement_load_leaves_residency_with_the_resident_model(monkeypatch):+ import threading++ from core.inference import gpu_arbiter, video as video_module++ backend = video_module.get_video_backend()+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setattr(gpu_arbiter, "_owner_account", None)+ monkeypatch.setattr(gpu_arbiter, "_prior_account", None, raising = False)+ resident = {**backend.status(), "loaded": True, "repo_id": "alice/private-video"}+ monkeypatch.setattr(backend, "status", lambda: resident)+ monkeypatch.setattr(backend, "_state", object())+ unloaded: list[str] = []+ monkeypatch.setattr(backend, "unload", lambda: unloaded.append("unload") or resident)+ run_as(ALICE, gpu_arbiter.acquire_for, gpu_arbiter.VIDEO, lambda: None)+ run_as(BOB, gpu_arbiter.acquire_for, gpu_arbiter.VIDEO, lambda: None)+ monkeypatch.setattr(+ video_module,+ "_detect_load_family",+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("boom")),+ )+ run_as(+ BOB,+ backend._run_load,+ repo_id = "bob/model",+ _load_token = backend._load_token,+ _cancel_event = threading.Event(),+ )+ assert gpu_arbiter.owner_account() == ALICE.account_id+ with _client(BOB) as client:+ assert client.get("/api/inference/video/status").json() == {"loaded": True, "yours": False}+ assert client.post("/api/inference/video/unload").status_code == 404+ assert unloaded == []+ with _client(ALICE) as client:+ assert client.get("/api/inference/video/status").json()["repo_id"] == "alice/private-video"diff --git a/studio/backend/tests/test_account_media_load_retirement_race.py b/studio/backend/tests/test_account_media_load_retirement_race.pynew file mode 100644index 00000000000..38616e15832--- /dev/null+++ b/studio/backend/tests/test_account_media_load_retirement_race.py@@ -0,0 +1,149 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An image load caught by retirement must not run for the deleted account.++Retirement tombstones the account and scans for its media work. A /images/load still inside a+pre-admission await owns nothing the scan can see, so it used to start its load afterwards; and+a load admitted just before the tombstone kept running. Now admission and the scan share one+lock: the late request is refused, the early load is torn down."""++from __future__ import annotations++import asyncio+import threading+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from core.inference import diffusion, diffusion_device, diffusion_engine_router, video+from core.inference import diffusion_compat+from core.training import account_jobs as jobs+from hub.services.models import account_access as access+from models.inference import DiffusionLoadRequest+from routes import accounts, inference+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+++class FakeEngine:+ def __init__(self):+ self.started = []+ self.unloaded = 0+ self.loading = False++ def begin_load(self, repo_id, **kwargs):+ self.started.append(repo_id)+ self.loading = True+ return {"loaded": False, "repo_id": repo_id}++ def loading_repo_ids(self):+ return ("org/model",) if self.loading else ()++ def unload(self):+ self.unloaded += 1+ self.loading = False+ return {"loaded": False}++ def preflight_base_access(self, *args, **kwargs):+ return None+++def engine(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_retired", set())+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_resident_components", {})+ monkeypatch.setattr(access, "_uncommitted_resident", {})+ monkeypatch.setattr(access, "_uncommitted_components", {})+ fake = FakeEngine()+ backend = SimpleNamespace(+ validate_load_request = lambda *a, **k: None,+ assert_precision_available = lambda *a, **k: None,+ )+ monkeypatch.setattr(diffusion, "get_diffusion_backend", lambda: backend)+ monkeypatch.setattr(diffusion, "resolve_model_kind", lambda *a, **k: "pipeline")+ monkeypatch.setattr(diffusion, "resolve_local_single_file", lambda path: None)+ monkeypatch.setattr(diffusion, "_diffusion_backend", fake)+ monkeypatch.setattr(+ diffusion_device,+ "resolve_diffusion_device_target",+ lambda: SimpleNamespace(device = "cpu"),+ )+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: fake)+ monkeypatch.setattr(diffusion_engine_router, "select_and_activate_engine", lambda *a, **k: fake)+ monkeypatch.setattr(diffusion_engine_router, "predict_engine", lambda *a, **k: None)+ monkeypatch.setattr(diffusion_engine_router, "engine_for", lambda name: fake)+ monkeypatch.setattr(diffusion_engine_router, "annotate_status", lambda status: status)+ monkeypatch.setattr(diffusion_compat, "assert_pick_is_not_speech", lambda *a, **k: None)+ monkeypatch.setattr(inference, "_guard_diffusion_load_against_training", lambda: None)++ async def no_ordinal(gpu_ids):+ return None++ monkeypatch.setattr(inference, "_selected_gpu_ordinal", no_ordinal)+ monkeypatch.setattr(inference, "reset_media_load_progress", lambda kind: None)+ monkeypatch.setattr(access, "require_media_references", lambda request: None)+ monkeypatch.setattr(access, "require_idle_other_accounts", lambda *a, **k: None)+ monkeypatch.setattr(video, "_backend", None)+ return fake+++def _retire():+ jobs._retired.add(ALICE.account_id)+ diffusion_engine_router.retire_load_for_account(ALICE.account_id)+ video.retire_load_for_account(ALICE.account_id)+++def _load():+ request = DiffusionLoadRequest(model_path = "org/model")+ return asyncio.run(inference.load_diffusion_model_gated(request, "alice", user_initiated = True))+++def test_load_parked_before_admission_is_refused_after_retirement(monkeypatch, engine):+ blocked, release, result = threading.Event(), threading.Event(), {}++ def access_check(model_name):+ blocked.set()+ release.wait(timeout = 30)++ monkeypatch.setattr(access, "require_model_access", access_check)++ def request_thread():+ try:+ result["value"] = run_as(ALICE, _load)+ except HTTPException as exc:+ result["error"] = (exc.status_code, exc.detail)++ thread = threading.Thread(target = request_thread)+ thread.start()+ assert blocked.wait(timeout = 30)+ _retire()+ release.set()+ thread.join(timeout = 30)+ assert not thread.is_alive()+ print(f"late load: {result}, started={engine.started}")+ assert engine.started == []+ assert result["error"] == (403, "Account is retired")+++def test_load_admitted_before_retirement_is_torn_down(monkeypatch, engine):+ monkeypatch.setattr(access, "require_model_access", lambda model_name: None)+ status = run_as(ALICE, _load)+ assert status.loaded is False and engine.loading+ _retire()+ print(f"early load: unloaded={engine.unloaded}, loading={engine.loading}")+ assert engine.unloaded == 1 and not engine.loading+++def test_retirement_leaves_another_accounts_load_alone(monkeypatch, engine):+ monkeypatch.setattr(access, "require_model_access", lambda model_name: None)+ run_as(AccountContext("b" * 32, "bob"), _load)+ _retire()+ assert engine.unloaded == 0 and engine.loadingdiff --git a/studio/backend/tests/test_account_media_resident_authorization.py b/studio/backend/tests/test_account_media_resident_authorization.pynew file mode 100644index 00000000000..f0e3b6fd711--- /dev/null+++ b/studio/backend/tests/test_account_media_resident_authorization.py@@ -0,0 +1,456 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A generation must clear every component of the resident it runs on, and keep owning it."""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+from PIL import Image+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter, image_gallery+from core.inference.diffusion_families import DiffusionModelReplacedError, load_identity+from hub.services.models import account_access as access+from routes import inference, video+from state import active_generations+from utils.account_context import AccountContext, bind_account, reset_account, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++PUBLIC = {"org/public-model", "org/other-public", "org/public-video"}++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_resident_components", {}, raising = False)+ monkeypatch.setattr(access, "_generation_accounts", {})+ monkeypatch.setattr(access, "repo_is_public", lambda repo_id, *a, **k: repo_id in PUBLIC)+ monkeypatch.setattr(gpu_arbiter, "_owner", "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", BOB.account_id)+ active_generations.reset_for_tests()+ yield+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(inference.studio_router, prefix = "/api/inference")+ app.include_router(video.router, prefix = "/api/inference")+ return TestClient(app)+++def _result(repo_id):+ return {+ "images": [Image.new("RGB", (8, 8))],+ "seed": 1,+ "seeds": [1],+ "repo_id": repo_id,+ "workflow": "txt2img",+ }+++def _install_backend(monkeypatch, status, generate):+ from core.inference import diffusion_engine_router++ backend = SimpleNamespace(+ is_loaded = True,+ status = status,+ generate = generate,+ generate_progress = lambda: {+ "active": False,+ "step": 0,+ "total_steps": 0,+ "fraction": 0.0,+ "eta_seconds": None,+ },+ cancel_generate = lambda **kwargs: False,+ )+ monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda: backend)+ return backend+++def test_a_private_base_repo_of_a_shared_resident_is_reauthorized(monkeypatch):+ used = []+ status = {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": "bob/private-base",+ }+ _install_backend(+ monkeypatch,+ lambda: status,+ lambda **kwargs: (used.append("ran"), _result("org/public-model"))[1],+ )+ with client_for(ALICE) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 404+ )+ assert used == []+ run_as(BOB, access.record_model_grant, "bob/private-base")+ with client_for(BOB) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 200+ )+ assert used == ["ran"]+++def test_baked_private_adapters_of_a_shared_resident_are_reauthorized(monkeypatch):+ """The adapters baked in at load time are components too, and status() does not carry them."""+ used = []+ status = {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ }+ _install_backend(+ monkeypatch,+ lambda: status,+ lambda **kwargs: (used.append("ran"), _result("org/public-model"))[1],+ )+ run_as(+ BOB, access.note_resident_components, "diffusion", "org/public-model", "bob/private-lora"+ )+ with client_for(ALICE) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 404+ )+ assert used == []+ run_as(BOB, access.note_resident_components, "diffusion", "org/other-public")+ with client_for(ALICE) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 200+ )+++def test_video_generation_reauthorizes_a_private_base_repo(monkeypatch):+ from core.inference import video as video_module++ started = []+ _status = lambda: {+ "loaded": True,+ "repo_id": "org/public-video",+ "family": "wan",+ "base_repo": "bob/private-base",+ }+ backend = SimpleNamespace(+ status = _status,+ generation_snapshot = lambda: (_status(), object()),+ begin_generate = lambda **kwargs: started.append("ran"),+ )+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+ monkeypatch.setattr(gpu_arbiter, "_owner", "video")+ with client_for(ALICE) as client:+ response = client.post(+ "/api/inference/video/generate",+ json = {"prompt": "a sloth", "width": 320, "height": 320, "num_frames": 17},+ )+ assert response.status_code == 404+ assert started == []+++def test_a_video_resident_replaced_after_authorization_is_not_generated_on(monkeypatch):+ """Another account's load commits between the authorized snapshot and the reservation."""+ from core.inference import video as video_module+ from core.inference.video_families import VIDEO_MODEL_CHANGED_MSG++ resident = SimpleNamespace(repo_id = "org/public-video", family = "wan")+ replacement = SimpleNamespace(repo_id = "bob/private-video", family = "wan")+ box = {"state": resident, "reads": 0}+ reserved = []++ def _status_of(state):+ return {+ "loaded": True,+ "repo_id": state.repo_id,+ "family": state.family,+ "base_repo": None,+ "defaults": {+ "num_frames": 17,+ "fps": 16,+ "frame_step": 4,+ "frame_offset": 1,+ "resolution_presets": [[320, 320]],+ },+ }++ def generation_snapshot():+ state = box["state"]+ box["reads"] += 1+ if box["reads"] == 1:+ box["state"] = replacement+ return _status_of(state), state++ def begin_generate(**kwargs):+ expected = kwargs.get("expected_state")+ if expected is not None and expected is not box["state"]:+ raise RuntimeError(VIDEO_MODEL_CHANGED_MSG)+ reserved.append(box["state"].repo_id)+ return {"width": 320, "height": 320, "num_frames": 17, "fps": 16}++ backend = SimpleNamespace(+ status = lambda: _status_of(box["state"]),+ generation_snapshot = generation_snapshot,+ begin_generate = begin_generate,+ generate_progress = lambda: {"active": False},+ )+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+ monkeypatch.setattr(gpu_arbiter, "_owner", "video")+ with client_for(ALICE) as client:+ response = client.post(+ "/api/inference/video/generate",+ json = {"prompt": "a sloth", "width": 320, "height": 320, "num_frames": 17},+ )+ assert response.status_code == 404+ assert reserved == []+++def test_a_resident_replaced_after_authorization_is_not_generated_on(monkeypatch):+ """Another account's load commits between the status read and generate (#9448)."""+ used = []+ resident = {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ }+ replacement = {+ "loaded": True,+ "repo_id": "bob/private-model",+ "family": "z-image",+ "base_repo": None,+ }+ state = {"current": resident, "reads": 0}++ def status():+ current = state["current"]+ state["reads"] += 1+ if state["reads"] == 1:+ state["current"] = replacement+ return current++ def generate(**kwargs):+ current = state["current"]+ loaded = load_identity(current["repo_id"], current["base_repo"], current["family"])+ expected = kwargs.get("expected_load")+ if expected is not None and expected != loaded:+ raise DiffusionModelReplacedError(expected, loaded)+ used.append(current["repo_id"])+ return _result(current["repo_id"])++ _install_backend(monkeypatch, status, generate)+ with client_for(ALICE) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 404+ )+ assert used == []+++def test_a_public_replacement_is_regenerated_after_reauthorization(monkeypatch):+ used = []+ resident = {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ }+ replacement = {+ "loaded": True,+ "repo_id": "org/other-public",+ "family": "z-image",+ "base_repo": None,+ }+ state = {"current": resident, "reads": 0}++ def status():+ current = state["current"]+ state["reads"] += 1+ if state["reads"] == 1:+ state["current"] = replacement+ return current++ def generate(**kwargs):+ current = state["current"]+ loaded = load_identity(current["repo_id"], current["base_repo"], current["family"])+ expected = kwargs.get("expected_load")+ if expected is not None and expected != loaded:+ raise DiffusionModelReplacedError(expected, loaded)+ used.append(current["repo_id"])+ return _result(current["repo_id"])++ _install_backend(monkeypatch, status, generate)+ with client_for(ALICE) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 200+ )+ assert used == ["org/other-public"]+++def test_the_gallery_persist_window_still_belongs_to_the_generating_account(monkeypatch):+ status = {+ "loaded": True,+ "repo_id": "org/public-model",+ "family": "z-image",+ "base_repo": None,+ }+ _install_backend(monkeypatch, lambda: status, lambda **kwargs: _result("org/public-model"))+ persisting = threading.Event()+ release = threading.Event()+ real_save = image_gallery.save++ def blocking_save(image, meta):+ persisting.set()+ release.wait(20)+ return real_save(image, meta)++ monkeypatch.setattr(image_gallery, "save", blocking_save)+ result = {}++ def run():+ with client_for(ALICE) as client:+ result["response"] = client.post(+ "/api/inference/images/generate", json = {"prompt": "a sloth"}+ )++ thread = threading.Thread(target = run)+ thread.start()+ try:+ assert persisting.wait(20)+ with client_for(ALICE) as client:+ progress = client.get("/api/inference/images/generate-progress").json()+ assert progress["active"] is True+ with client_for(BOB) as client:+ assert client.get("/api/inference/images/generate-progress").json() == {+ "loaded": True,+ "yours": False,+ }+ finally:+ release.set()+ thread.join(20)+ assert result["response"].status_code == 200+++def test_a_failed_load_leaves_the_previous_resident_with_its_account(monkeypatch):+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_prior_resident_accounts", {})+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ run_as(ALICE, access.note_resident_account, "video", "a/model")+ run_as(BOB, access.note_resident_account, "video", "b/model")+ assert run_as(ALICE, access.resident_hidden, "video", "a/model") is False+ assert run_as(BOB, access.resident_hidden, "video", "a/model") is True+ assert run_as(BOB, access.resident_hidden, "video", "b/model") is False+ assert run_as(ALICE, access.resident_hidden, "video", "b/model") is True+++def test_every_generation_access_check_names_its_modality():+ """Baked adapters are recorded per modality, so a check without one skips them."""+ import re+ from pathlib import Path++ routes = Path(__file__).resolve().parents[1] / "routes"+ pattern = re.compile(r"require_media_generation_access,\s*[^,\n]+,\s*\"(video|diffusion)\"")+ for path in routes.glob("*.py"):+ text = path.read_text(encoding = "utf-8")+ calls = text.count("require_media_generation_access,")+ assert len(pattern.findall(text)) == calls, path.name+++def test_a_failed_load_does_not_authorize_the_requester_against_the_previous_resident(monkeypatch):+ """The records a load publishes are undone when that load fails with the old build resident.++ Alice loads a shared base with a private adapter baked in. Bob asks for the same base with his+ own adapter and the background load fails, so the engine keeps serving ALICE's pipeline. The+ ownership record names one reference (the model path), which is unchanged, so the prior-owner+ fallback never fires, and the component record was replaced with Bob's adapter set: without the+ rollback Bob clears his own list and generates on Alice's private build."""+ monkeypatch.setattr(access, "_prior_resident_accounts", {})+ monkeypatch.setattr(access, "_uncommitted_resident", {}, raising = False)+ monkeypatch.setattr(access, "_uncommitted_components", {}, raising = False)+ ran = []+ status = {"loaded": True, "repo_id": "org/public-model", "family": "z-image", "base_repo": None}+ _install_backend(+ monkeypatch,+ lambda: status,+ lambda **kwargs: (ran.append("ran"), _result("org/public-model"))[1],+ )+ run_as(ALICE, access.record_model_grant, "alice/private-lora")+ run_as(BOB, access.record_model_grant, "bob/private-lora")+ run_as(ALICE, access.note_resident_account, "diffusion", "org/public-model")+ run_as(+ ALICE,+ access.note_resident_components,+ "diffusion",+ "org/public-model",+ "alice/private-lora",+ )+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "_prior_account", None)++ # Bob's load route: the arbiter claim, then the two records published right after begin_load.+ run_as(BOB, gpu_arbiter.acquire_for, "diffusion", lambda: None)+ run_as(BOB, access.note_resident_account, "diffusion", "org/public-model")+ run_as(+ BOB,+ access.note_resident_components,+ "diffusion",+ "org/public-model",+ None,+ "bob/private-lora",+ )+ # ... and the background load fails with Alice's pipeline still resident.+ assert run_as(BOB, gpu_arbiter.restore_owner_account, "diffusion") is True+ assert run_as(BOB, access.restore_resident_metadata, "diffusion") is True++ assert access.resident_components(status, "diffusion") == [+ "org/public-model",+ "alice/private-lora",+ ]+ with client_for(BOB) as client:+ assert (+ client.post("/api/inference/images/generate", json = {"prompt": "a sloth"}).status_code+ == 404+ )+ assert ran == []+ assert run_as(ALICE, access.resident_hidden, "diffusion", "org/public-model") is False+++def test_restoring_residency_records_is_a_noop_once_another_load_took_them(monkeypatch):+ """Mirrors restore_owner_account: a rollback may never displace a newer account's claim."""+ monkeypatch.setattr(access, "_prior_resident_accounts", {})+ monkeypatch.setattr(access, "_uncommitted_resident", {}, raising = False)+ monkeypatch.setattr(access, "_uncommitted_components", {}, raising = False)+ run_as(ALICE, access.note_resident_account, "diffusion", "a/model")+ run_as(ALICE, access.note_resident_components, "diffusion", "a/model", "alice/private-lora")+ run_as(BOB, access.note_resident_account, "diffusion", "b/model")+ run_as(BOB, access.note_resident_components, "diffusion", "b/model", "bob/private-lora")+ assert run_as(ALICE, access.restore_resident_metadata, "diffusion") is False+ assert access._resident_accounts["diffusion"][0] == BOB.account_id+ assert access._resident_components["diffusion"] == ("b/model", frozenset({"bob/private-lora"}))diff --git a/studio/backend/tests/test_account_model_access.py b/studio/backend/tests/test_account_model_access.pynew file mode 100644index 00000000000..c16c9573ca6--- /dev/null+++ b/studio/backend/tests/test_account_model_access.py@@ -0,0 +1,600 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Private shared-cache content needs anonymous Hub proof or a durable account grant."""++from __future__ import annotations++import asyncio+import io+import json+import logging+import sqlite3+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from hub.services import download_lifecycle+from hub.services.models import account_access as access, cache_inventory, local_inventory+from hub.utils import download_registry+from utils.account_context import OWNER, AccountContext, arun_as, run_as+from utils.paths.storage_roots import studio_db_path++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_public_repos", {})+ monkeypatch.setattr(download_lifecycle, "_job_accounts", {})+ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: (_ for _ in ()).throw(OSError("offline"))+ ),+ )++[email protected]("repo_type", ["model", "dataset"])+ "answer,visible",+ [+ ("public", True),+ ("private", False),+ ("unreachable", False),+ ("unknown", False),+ ("gated", False),+ ],+)+def test_public_proof_is_anonymous_cached_and_fail_closed(monkeypatch, answer, visible, repo_type):+ calls = []++ def info(repo, **kwargs):+ calls.append((repo, kwargs))+ if answer == "unreachable":+ raise OSError("Hub unavailable")+ return SimpleNamespace(+ private = {"public": False, "private": True, "unknown": None, "gated": False}[answer],+ gated = answer == "gated",+ )++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = info))+ assert run_as(ALICE, access.repo_visible, "Org/Secret", repo_type) is visible+ assert run_as(BOB, access.repo_visible, "Org/Secret", repo_type) is visible+ assert calls == [("Org/Secret", {"repo_type": repo_type, "token": False, "timeout": 5.0})]+ assert run_as(OWNER, access.repo_visible, "Org/Secret", repo_type)+ assert len(calls) == 1++[email protected]("failure", ["unreachable", "forced_offline"])+def test_a_proven_public_repo_stays_visible_when_the_hub_cannot_be_asked(+ monkeypatch, tmp_path, failure+):+ answers = {"mode": "public"}++ def info(repo, **kwargs):+ if answers["mode"] == "public":+ return SimpleNamespace(private = False, gated = False)+ if answers["mode"] == "forced_offline":+ from huggingface_hub.errors import OfflineModeIsEnabled+ raise OfflineModeIsEnabled("HF_HUB_OFFLINE=1")+ if answers["mode"] == "private":+ raise type("RepositoryNotFoundError", (Exception,), {})(+ "private",+ )+ raise OSError("Hub unavailable")++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = info))+ assert run_as(ALICE, access.repo_visible, "Org/Public")+ assert json.loads(access._public_verdicts_path().read_text()).keys() == {"model:org/public"}+ assert access._public_verdicts_path().is_relative_to(tmp_path / "cache")++ access._public_repos.clear()+ answers["mode"] = failure+ assert run_as(BOB, access.repo_visible, "org/public"), "the proof on disk carries the answer"+ assert not run_as(BOB, access.repo_visible, "org/never-proven")++ access._public_repos.clear()+ answers["mode"] = "private"+ error = Exception("gone")+ error.response = SimpleNamespace(status_code = 404)++ def definitive(repo, **kwargs):+ raise error++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = definitive))+ assert not run_as(ALICE, access.repo_visible, "org/public")+ assert json.loads(access._public_verdicts_path().read_text()) == {}+++def test_grants_survive_restart_and_username_reuse_inherits_nothing():+ run_as(ALICE, access.record_model_grant, "Org/Secret")+ path = run_as(ALICE, studio_db_path)+ with sqlite3.connect(path) as conn:+ raw = conn.execute(+ "SELECT value_json FROM app_settings WHERE key = 'model_grants'"+ ).fetchone()[0]+ assert json.loads(raw) == ["model:org/secret"]+ access._public_repos.clear()+ assert run_as(ALICE, access.repo_visible, "org/secret")+ assert not run_as(BOB, access.repo_visible, "org/secret")+ assert not run_as(AccountContext("c" * 32, "alice"), access.repo_visible, "org/secret")+ assert not run_as(ALICE, access.repo_visible, "org/secret", "dataset")+ run_as(BOB, access.record_model_grant, "Org/Secret")+ assert run_as(BOB, access.repo_visible, "org/secret")+++def test_simultaneous_download_completions_preserve_all_grants():+ with ThreadPoolExecutor(max_workers = 4) as pool:+ futures = [+ pool.submit(run_as, ALICE, access.record_model_grant, f"org/model-{i}")+ for i in range(12)+ ]+ for future in futures:+ future.result()+ assert run_as(ALICE, access.model_grants) == {f"model:org/model-{i}" for i in range(12)}+++def test_snapshot_paths_and_symlinks_cannot_bypass_repo_grants(monkeypatch, tmp_path):+ from utils import hf_cache_settings++ cache = tmp_path / "cache"+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])+ snapshot = cache / "models--org--secret" / "snapshots" / "commit"+ snapshot.mkdir(parents = True)+ weights = snapshot / "model.gguf"+ weights.write_bytes(b"weights")+ assert not run_as(BOB, access.model_visible, str(weights))+ run_as(ALICE, access.record_model_grant, "org/secret")+ assert run_as(ALICE, access.model_visible, str(weights))+ assert not run_as(BOB, access.model_visible, str(weights))+ bob_root = tmp_path / "accounts" / BOB.account_id+ bob_root.mkdir(parents = True)+ link = bob_root / "stolen.gguf"+ link.symlink_to(weights)+ assert not run_as(BOB, access.model_visible, str(link))+ fake = tmp_path / "accounts" / ALICE.account_id / "models--org--public"+ fake.mkdir(parents = True)+ monkeypatch.setattr(access, "repo_is_public", lambda *a: True)+ assert not run_as(BOB, access.model_visible, str(fake))++[email protected]("kind", ["models", "gguf"])+def test_shared_catalog_is_filtered_after_each_account_reads_it(monkeypatch, kind):+ rows = [{"repo_id": "org/secret", "path": None}, {"repo_id": "org/public", "path": None}]+ run_as(ALICE, access.record_model_grant, "org/secret")+ monkeypatch.setattr(access, "repo_is_public", lambda repo, *a: repo == "org/public")++ async def scan(*args):+ return cache_inventory._CachedInventoryScan(rows, True)++ monkeypatch.setattr(cache_inventory, "_shared_cached_inventory_scan", scan)+ fn = (+ cache_inventory.list_cached_models_response+ if kind == "models"+ else cache_inventory.list_cached_gguf_response+ )+ assert len(asyncio.run(arun_as(ALICE, fn()))["cached"]) == 2+ assert asyncio.run(arun_as(BOB, fn()))["cached"] == [rows[1]]+ assert len(asyncio.run(arun_as(OWNER, fn()))["cached"]) == 2+ assert len(rows) == 2+++def test_concurrent_misses_ask_the_hub_once_per_repo(monkeypatch):+ calls = []+ barrier = threading.Barrier(8)++ def answer(repo_id, repo_type):+ calls.append(repo_id)+ barrier.wait(timeout = 30)+ time.sleep(0.02)+ return True++ monkeypatch.setattr(access, "_hub_public_answer", answer)+ rows = [{"repo_id": f"org/repo-{index}"} for index in range(8)]+ with ThreadPoolExecutor(max_workers = 8) as pool:+ listings = [+ pool.submit(run_as, ALICE, access.filter_model_rows, list(rows)) for _ in range(8)+ ]+ results = [listing.result(timeout = 60) for listing in listings]+ assert all(len(result) == 8 for result in results)+ assert sorted(calls) == sorted(row["repo_id"] for row in rows)+++def test_a_listing_probes_its_unknown_repos_together(monkeypatch):+ monkeypatch.setattr(access, "_hub_public_answer", lambda *a: time.sleep(0.1) or True)+ rows = [{"repo_id": f"org/slow-{index}"} for index in range(8)]+ start = time.perf_counter()+ assert len(run_as(ALICE, access.filter_model_rows, rows)) == 8+ assert time.perf_counter() - start < 0.4+++def test_a_warm_listing_asks_the_hub_nothing(monkeypatch):+ rows = [{"repo_id": f"org/warm-{index}"} for index in range(4)]+ monkeypatch.setattr(access, "_hub_public_answer", lambda *a: True)+ assert len(run_as(ALICE, access.filter_model_rows, rows)) == 4++ def unexpected(*args):+ raise AssertionError("a cached verdict must not be probed again")++ monkeypatch.setattr(access, "_hub_public_answer", unexpected)+ assert len(run_as(ALICE, access.filter_model_rows, rows)) == 4+++def test_shared_dataset_catalog_is_filtered_for_each_account(monkeypatch):+ from hub.services.datasets import cache_inventory as dataset_inventory++ rows = [{"repo_id": "org/secret"}, {"repo_id": "org/public"}]+ run_as(ALICE, access.record_model_grant, "org/secret", "dataset")+ monkeypatch.setattr(access, "repo_is_public", lambda repo, *a: repo == "org/public")+ monkeypatch.setattr(dataset_inventory, "_scan_hf_dataset_caches", lambda: rows)++ fn = dataset_inventory.list_cached_datasets_response+ assert len(asyncio.run(arun_as(ALICE, fn()))["cached"]) == 2+ assert asyncio.run(arun_as(BOB, fn()))["cached"] == [rows[1]]+ assert len(asyncio.run(arun_as(OWNER, fn()))["cached"]) == 2+ assert len(rows) == 2+++def test_a_blank_managed_token_is_anonymous_not_the_installations(monkeypatch):+ assert run_as(ALICE, access.account_hf_token, " ") is False+ assert run_as(ALICE, access.account_hf_token, "") is False+ assert run_as(ALICE, access.account_hf_token, None) is False+ assert run_as(ALICE, access.account_hf_token, " hf_real ") == " hf_real "+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ assert access.account_hf_token(" ") == " "+++def test_the_shared_chat_template_read_needs_model_access(monkeypatch):+ from picker.routes import templates++ monkeypatch.setattr(access, "repo_is_public", lambda *a, **k: False)+ monkeypatch.setattr(templates, "read_default_chat_template", lambda *a, **k: "{{ raw }}")+ run_as(ALICE, access.record_model_grant, "org/secret")++ async def read(account):+ return await arun_as(+ account,+ templates.get_default_chat_template_route(+ model_name = "org/secret",+ gguf_variant = None,+ hf_token = None,+ current_subject = account.username,+ ),+ )++ assert asyncio.run(read(OWNER)).chat_template == "{{ raw }}"+ assert asyncio.run(read(ALICE)).chat_template == "{{ raw }}"+ with pytest.raises(HTTPException) as refused:+ asyncio.run(read(BOB))+ assert refused.value.status_code == 404+++def test_local_inventory_does_not_mutate_shared_scan_objects():+ class Response:+ models = [SimpleNamespace(path = "org/secret", id = "same-id")]++ def model_copy(self, *, update):+ return SimpleNamespace(**update)++ response = Response()+ assert asyncio.run(arun_as(BOB, local_inventory._account_local_response(response))).models == []+ assert len(response.models) == 1++[email protected]("repo_type", ["model", "dataset"])+def test_only_successful_downloads_record_a_grant(monkeypatch, repo_type):+ from core.inference import local_model_resolver++ monkeypatch.setattr(local_model_resolver, "note_downloaded", lambda *a: None)+ monkeypatch.setattr(local_model_resolver, "invalidate_index", lambda **k: None)+ monkeypatch.setattr(local_model_resolver, "warm_index_soon", lambda: None)+ monkeypatch.setattr(+ download_lifecycle.download_manifest, "clear_cancel_marker", lambda *a, **k: None+ )+ registry = SimpleNamespace(+ cancel_requested = lambda key: False,+ drop_process = lambda *a: True,+ get_job_metadata = lambda key: None,+ set_job = lambda *a: None,+ update_job_transport = lambda *a: None,+ )+ for rc in [1, 0]:+ proc = SimpleNamespace(stderr = io.BytesIO(), wait = lambda: rc)+ state = run_as(+ ALICE,+ download_lifecycle.finalize_worker_exit,+ registry,+ "org/secret::",+ proc,+ hf_token = "alice-token",+ label = "org/secret",+ log_prefix = "Download",+ logger = logging.getLogger(__name__),+ repo_type = repo_type,+ repo_id = "org/secret",+ )+ assert state == ("complete" if rc == 0 else "error")+ assert run_as(ALICE, access.repo_visible, "org/secret", repo_type) is (rc == 0)+ assert not run_as(BOB, access.repo_visible, "org/secret", repo_type)+++def test_private_cache_hit_cannot_turn_into_a_download_grant_without_hub_authorization():+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, access.authorize_download, "org/secret", "model", None)+ assert exc.value.status_code == 404+ assert run_as(BOB, access.model_grants) == set()+++def test_download_cancel_and_status_are_owned_by_the_initiating_account():+ registry = download_registry.DownloadRegistry()+ key = "org/secret::"+ registry.set_job(key, "downloading")+ download_lifecycle._job_accounts[(id(registry), key)] = ALICE.account_id+ for fn in [+ lambda: download_lifecycle.cancel_worker(+ registry, key, generation = None, label = "secret", logger = logging.getLogger(__name__)+ ),+ lambda: download_lifecycle.idle_status(+ registry, key, repo_type = "model", repo_id = "org/secret", variant = None+ ),+ ]:+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, fn)+ assert exc.value.status_code == 404+ assert run_as(ALICE, download_lifecycle.download_belongs_to_account, registry, key)+++def test_download_ownership_replaces_the_previous_downloader_of_the_same_key():+ registry = download_registry.DownloadRegistry()+ key = "org/secret::"+ download_lifecycle._job_accounts[(id(registry), key)] = BOB.account_id+ run_as(ALICE, download_lifecycle.record_download_account, registry, key)+ assert run_as(ALICE, download_lifecycle.download_belongs_to_account, registry, key)+ assert not run_as(BOB, download_lifecycle.download_belongs_to_account, registry, key)+++def test_download_ownership_lands_before_the_hub_authorization(monkeypatch):+ registry = download_registry.DownloadRegistry()+ key = "org/secret::"+ download_lifecycle._job_accounts[(id(registry), key)] = BOB.account_id+ registry.claim(key, "http", repo_type = "model", repo_id = "org/secret")+ seen = {}++ def repo_info(*args, **kwargs):+ seen["bob"] = run_as(BOB, download_lifecycle.download_belongs_to_account, registry, key)+ seen["alice"] = run_as(ALICE, download_lifecycle.download_belongs_to_account, registry, key)+ return SimpleNamespace(gated = False)++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = repo_info))++ def spawn():+ raise OSError("no worker in this test")++ with pytest.raises(HTTPException):+ run_as(+ ALICE,+ lambda: download_lifecycle.launch_worker(+ registry,+ key,+ spawn = spawn,+ hf_token = "alice-token",+ label = "org/secret",+ log_prefix = "Download",+ logger = logging.getLogger(__name__),+ repo_type = "model",+ repo_id = "org/secret",+ transport = "http",+ watch_name = "watch",+ ),+ )+ assert seen == {"bob": False, "alice": True}+++def test_single_owner_does_no_hub_or_grant_io(monkeypatch, tmp_path):+ def unexpected(*args, **kwargs):+ raise AssertionError("owner must not probe private-model policy")++ monkeypatch.setattr(access, "HfApi", unexpected)+ monkeypatch.setattr(access, "model_grants", unexpected)+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ rows = [{"repo_id": "org/secret"}]+ assert access.filter_model_rows(rows) is rows+ assert access.model_visible("/any/legacy/path")+ access.record_model_grant("org/secret")+ assert not (tmp_path / "studio.db").exists()+ monkeypatch.setenv("HF_TOKEN", "owner-token")+ assert access.ambient_hf_token() == "owner-token"+++def test_managed_directory_scans_and_media_companions_are_private(tmp_path):+ from hub.services.models import folder_browser++ owner_output = str(tmp_path / "outputs")+ alice_output = str(tmp_path / "accounts" / ALICE.account_id / "outputs")+ assert run_as(ALICE, access.private_directory, owner_output, "outputs") == alice_output+ assert run_as(ALICE, folder_browser._build_browse_allowlist) == [+ tmp_path / "accounts" / ALICE.account_id+ ]+ with pytest.raises(HTTPException):+ run_as(BOB, access.private_directory, alice_output, "outputs")+ for reference in [alice_output + "/model.gguf", "../../private/model.gguf"]:+ with pytest.raises(HTTPException):+ run_as(BOB, access.require_media_references, SimpleNamespace(gguf_filename = reference))+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, access.require_installation_owner)+ assert exc.value.status_code == 403+++def test_managed_download_process_never_inherits_ambient_hf_tokens(monkeypatch):+ from utils import hf_cache_settings++ captured = []+ monkeypatch.setattr(+ hf_cache_settings,+ "get_hf_cache_paths",+ lambda: SimpleNamespace(+ child_env = lambda: {+ "HF_TOKEN": "owner-secret",+ "HUGGING_FACE_HUB_TOKEN": "legacy-owner-secret",+ }+ ),+ )+ monkeypatch.setattr(+ download_lifecycle.subprocess,+ "Popen",+ lambda *args, **kwargs: captured.append(kwargs["env"]) or SimpleNamespace(pid = 123),+ )+ run_as(+ ALICE, download_lifecycle.spawn_worker, ["--repo-id", "org/private"], None, use_xet = False+ )+ assert "HF_TOKEN" not in captured[0]+ assert "HUGGING_FACE_HUB_TOKEN" not in captured[0]+ assert captured[0]["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == "1"+ run_as(+ BOB,+ download_lifecycle.spawn_worker,+ ["--repo-id", "org/private"],+ "bob-token",+ use_xet = False,+ )+ assert captured[1]["HF_TOKEN"] == "bob-token"+ assert "HUGGING_FACE_HUB_TOKEN" not in captured[1]++[email protected]("authorized", [False, True])+def test_gated_metadata_alone_is_not_download_authorization(monkeypatch, authorized):+ calls = []++ def check(repo, **kwargs):+ calls.append((repo, kwargs))+ if not authorized:+ raise OSError("license not accepted")++ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: SimpleNamespace(gated = True), auth_check = check+ ),+ )+ if authorized:+ run_as(ALICE, access.authorize_download, "org/gated", "model", "alice-token")+ else:+ with pytest.raises(HTTPException):+ run_as(ALICE, access.authorize_download, "org/gated", "model", "alice-token")+ assert calls == [("org/gated", {"repo_type": "model", "token": "alice-token"})]+ assert run_as(ALICE, access.model_grants) == set()+++def test_a_persisted_public_proof_expires_rather_than_outliving_a_privacy_change(monkeypatch):+ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: SimpleNamespace(private = False, gated = False)+ ),+ )+ assert run_as(ALICE, access.repo_visible, "Org/Public")+ path = access._public_verdicts_path()+ assert json.loads(path.read_text()).keys() == {"model:org/public"}++ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: (_ for _ in ()).throw(OSError("Hub unavailable"))+ ),+ )+ access._public_repos.clear()+ path.write_text(json.dumps({"model:org/public": time.time() - 3600}))+ assert run_as(BOB, access.repo_visible, "org/public"), "a proof inside the bound still carries"++ access._public_repos.clear()+ path.write_text(json.dumps({"model:org/public": time.time() - 30 * 24 * 3600}))+ assert not run_as(BOB, access.repo_visible, "org/public")+ assert not run_as(ALICE, access.repo_visible, "org/public")+++def test_a_checkpoint_in_the_accounts_projects_tree_is_loadable_by_that_account(+ monkeypatch, tmp_path+):+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ from core.training.account_jobs import validate_job_paths+ from utils.paths.storage_roots import project_workspaces_root++ checkpoint = run_as(ALICE, project_workspaces_root) / "demo" / "outputs" / "checkpoint-10"+ checkpoint.mkdir(parents = True)+ run_as(ALICE, validate_job_paths, {"output_dir": str(checkpoint)})+ assert run_as(ALICE, access.model_visible, str(checkpoint))+ assert run_as(ALICE, access.require_model_access, str(checkpoint)) is None+ assert not run_as(BOB, access.model_visible, str(checkpoint))+ with pytest.raises(HTTPException) as refused:+ run_as(BOB, access.require_model_access, str(checkpoint))+ assert refused.value.status_code == 404+ assert run_as(OWNER, project_workspaces_root) != run_as(ALICE, project_workspaces_root)++[email protected]("repo_id,folder", [("gpt2", "models--gpt2"), ("org/m", "models--org--m")])+def test_one_segment_hub_ids_follow_their_grant(monkeypatch, tmp_path, repo_id, folder):+ """The download validator accepts ``repo_name`` alone, so visibility must too."""+ from utils import hf_cache_settings++ cache = tmp_path / "cache"+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])+ monkeypatch.setattr(access, "repo_is_public", lambda *a: False)+ weights = cache / folder / "snapshots" / "commit" / "model.safetensors"+ weights.parent.mkdir(parents = True)+ weights.write_bytes(b"weights")+ assert not run_as(BOB, access.model_visible, repo_id)+ assert not run_as(BOB, access.model_visible, str(weights))+ run_as(ALICE, access.record_model_grant, repo_id)+ assert run_as(ALICE, access.model_visible, repo_id)+ assert run_as(ALICE, access.model_visible, str(weights))+ assert not run_as(BOB, access.model_visible, repo_id)+ assert not run_as(BOB, access.model_visible, str(weights))+++def test_cache_path_rows_join_the_concurrent_hub_warmup():+ """Inventory rows carry snapshot paths; skipping them serialised one Hub call per repo."""+ path = "/cache/models--org--m/snapshots/abc/model.gguf"+ assert access._hub_probe_targets([path], "model", set()) == {"org/m"}+ assert (+ access._hub_probe_targets([path], "model", {access._grant_key("org/m", "model")}) == set()+ )+ assert access._hub_probe_targets([path], "dataset", set()) == set()+++def test_a_grant_racing_retirement_does_not_recreate_the_workspace(monkeypatch, tmp_path):+ from core.training import account_jobs+ from utils.paths import storage_roots++ root = run_as(ALICE, storage_roots.workspace_root)+ root.mkdir(parents = True)+ real = account_jobs.account_is_retired+ fired = []++ def retire_after_check():+ # The retirement lands between the tombstone check and the directory creation.+ if not fired:+ fired.append(True)+ account_jobs._retired.add(ALICE.account_id)+ root.rename(root.with_name(root.name + "-deleted-1"))+ return False+ return real()++ monkeypatch.setattr(account_jobs, "account_is_retired", retire_after_check)+ try:+ run_as(ALICE, access.record_model_grant, "org/secret")+ finally:+ account_jobs._retired.discard(ALICE.account_id)+ assert not root.exists()diff --git a/studio/backend/tests/test_account_model_config_caller_token.py b/studio/backend/tests/test_account_model_config_caller_token.pynew file mode 100644index 00000000000..179c924b39a--- /dev/null+++ b/studio/backend/tests/test_account_model_config_caller_token.py@@ -0,0 +1,135 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed user's valid HF token must work before their first model download."""++from contextlib import nullcontext+from types import SimpleNamespace++import pytest++from studio.backend.tests.test_account_lifecycle import auth_env, headers+from auth import storage+from hub.services.models import account_access as access+from utils.account_context import run_as++REPO = "org/private-model"+TOKEN = "hf_alice_private_access"+++def config_env(auth_env, monkeypatch):+ from routes import models+ from core.inference import llama_cpp+ from utils.models import model_config++ client, _, _ = auth_env+ storage.create_initial_user(+ "alice", "alice-password", "alice-jwt-secret-for-test-at-least-32-bytes"+ )+ storage.create_initial_user("bob", "bob-password", "bob-jwt-secret-for-test-at-least-32-bytes")+ client.app.include_router(models.router, prefix = "/api/models")+ monkeypatch.setattr(access, "_public_repos", {})+ calls = []++ def repo_info(+ repo_id,+ *,+ token = None,+ **kwargs,+ ):+ calls.append(token)+ if token != TOKEN:+ exc = Exception("Repository not found")+ exc.response = SimpleNamespace(status_code = 404)+ raise exc+ return SimpleNamespace(private = True, gated = False)++ # Stand in only for Hub metadata and model introspection; real HTTP auth,+ # account policy, grants, and authorization checks remain in use.+ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = repo_info))+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable_for", lambda _: nullcontext())+ monkeypatch.setattr(models, "resolve_cached_repo_id_case", lambda name: name)+ monkeypatch.setattr(models, "load_model_defaults", lambda _: {})+ monkeypatch.setattr(models, "is_vision_model", lambda *a, **k: False)+ monkeypatch.setattr(models, "is_embedding_model", lambda *a, **k: False)+ monkeypatch.setattr(model_config, "detect_audio_type_checked", lambda *a, **k: (None, True))+ monkeypatch.setattr(+ models.ModelConfig, "from_identifier", lambda *a, **k: SimpleNamespace(is_lora = False)+ )+ monkeypatch.setattr(models, "_get_max_position_embeddings", lambda _: 4096)+ monkeypatch.setattr(models, "_get_model_size_bytes", lambda *a, **k: 123)+ return client, calls+++def test_first_private_model_config_accepts_callers_valid_token(config_env):+ client, calls = config_env+ alice = storage.get_account("alice")+ assert run_as(alice, access.model_grants) == set()+ response = client.get(+ f"/api/models/config/{REPO}",+ headers = {+ **headers("alice"),+ "X-Unsloth-HF-Token": TOKEN,+ },+ )+ print(+ f"Valid caller token: HTTP {response.status_code}, body={response.json()}, Hub tokens={calls}"+ )+ assert response.status_code == 200, response.text+ assert response.json()["max_position_embeddings"] == 4096+ assert TOKEN in calls+ assert (+ run_as(alice, access.model_grants) == set()+ ), "metadata preflight must not grant cached content"++[email protected]("token", [None, "hf_wrong"])+def test_missing_or_wrong_token_remains_hidden(config_env, token):+ client, _ = config_env+ request_headers = headers("bob")+ if token:+ request_headers["X-Unsloth-HF-Token"] = token+ assert client.get(f"/api/models/config/{REPO}", headers = request_headers).status_code == 404+++def test_caller_token_does_not_authorize_foreign_local_path(config_env, tmp_path):+ client, _ = config_env+ foreign = tmp_path / "foreign-model"+ foreign.mkdir()+ response = client.get(+ f"/api/models/config/{REPO}",+ params = {"local_path": str(foreign)},+ headers = {+ **headers("alice"),+ "X-Unsloth-HF-Token": TOKEN,+ },+ )+ assert response.status_code == 404+++def test_owner_and_managed_account_with_grant_can_read_config(config_env):+ client, _ = config_env+ run_as(storage.get_account("alice"), access.record_model_grant, REPO)+ for username in ("unsloth", "alice"):+ response = client.get(+ f"/api/models/config/{REPO}",+ headers = {+ **headers(username),+ "X-Unsloth-HF-Token": TOKEN,+ },+ )+ assert response.status_code == 200, response.text+++def test_cache_only_selection_still_needs_account_grant(config_env):+ client, _ = config_env+ response = client.get(+ f"/api/models/config/{REPO}",+ params = {"prefer_local_cache": "true"},+ headers = {+ **headers("alice"),+ "X-Unsloth-HF-Token": TOKEN,+ },+ )+ assert response.status_code == 404diff --git a/studio/backend/tests/test_account_native_diffusion_load_rollback.py b/studio/backend/tests/test_account_native_diffusion_load_rollback.pynew file mode 100644index 00000000000..e81d6447dc0--- /dev/null+++ b/studio/backend/tests/test_account_native_diffusion_load_rollback.py@@ -0,0 +1,101 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A failed NATIVE (sd.cpp) replacement load must hand GPU residency back to the displaced account.++sd.cpp can be selected on a GPU host (UNSLOTH_DIFFUSION_ENGINE=sd_cpp), where /images/load takes+the arbiter with ``acquire_for_request(DIFFUSION, _begin_load)`` before the background load runs.+That claim moves ``gpu_arbiter._owner_account`` to the requester, so when the load then fails with+the previous account's pipeline still resident, the failure path has to undo it -- the diffusers+and video backends both call ``restore_owner_account`` there.+"""++from __future__ import annotations++import types++import pytest++from auth import policy+from core.inference import gpu_arbiter+from core.inference.sd_cpp_backend import SdCppDiffusionBackend, _SdLoading+from hub.services.models import account_access as access+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_resident_components", {}, raising = False)+ monkeypatch.setattr(access, "_prior_resident_accounts", {})+ monkeypatch.setattr(access, "_uncommitted_resident", {}, raising = False)+ monkeypatch.setattr(access, "_uncommitted_components", {}, raising = False)+ monkeypatch.setattr(gpu_arbiter, "_owner", "diffusion")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", ALICE.account_id)+ monkeypatch.setattr(gpu_arbiter, "_prior_account", None)+ yield+++def _failing_backend(monkeypatch):+ backend = SdCppDiffusionBackend(engine = None)+ monkeypatch.setattr(+ SdCppDiffusionBackend,+ "_resolve_backend",+ lambda self: (_ for _ in ()).throw(+ RuntimeError("sd-cli binary is present but not runnable.")+ ),+ )+ # Alice's native pipeline is what stays resident through the failure.+ backend._state = types.SimpleNamespace(repo_id = "org/alice-model")+ backend._loading = _SdLoading(repo_id = "org/bob-model", base_repo = "")+ return backend+++def test_failed_native_load_returns_gpu_residency_to_the_displaced_account(monkeypatch):+ backend = _failing_backend(monkeypatch)+ # /images/load on a GPU host: the arbiter claim runs under Bob, displacing Alice.+ run_as(BOB, gpu_arbiter.acquire_for, "diffusion", lambda: None)+ run_as(BOB, access.note_resident_account, "diffusion", "org/bob-model")+ assert gpu_arbiter.owner_account() == BOB.account_id++ run_as(+ BOB,+ lambda: backend._run_load(+ repo_id = "org/bob-model",+ gguf_filename = "flux1-dev-Q4_K_M.gguf",+ base = "",+ fam = None,+ hf_token = None,+ _load_token = backend._load_token,+ ),+ )++ assert backend._loading.error # the load really failed+ assert backend._state is not None # Alice's pipeline is still resident+ assert gpu_arbiter.owner_account() == ALICE.account_id+ assert run_as(ALICE, access.resident_hidden, "diffusion", "org/alice-model") is False+ assert run_as(BOB, access.resident_hidden, "diffusion", "org/alice-model") is True+++def test_failed_native_cpu_load_leaves_a_released_arbiter_alone(monkeypatch):+ """Single-user / CPU parity: the CPU path releases DIFFUSION, so the restore must no-op."""+ backend = _failing_backend(monkeypatch)+ gpu_arbiter.release("diffusion")+ run_as(+ BOB,+ lambda: backend._run_load(+ repo_id = "org/bob-model",+ gguf_filename = "flux1-dev-Q4_K_M.gguf",+ base = "",+ fam = None,+ hf_token = None,+ _load_token = backend._load_token,+ ),+ )+ assert gpu_arbiter.current_owner() is None+ assert gpu_arbiter.owner_account() is Nonediff --git a/studio/backend/tests/test_account_native_model_lease.py b/studio/backend/tests/test_account_native_model_lease.pynew file mode 100644index 00000000000..31a16bda5f7--- /dev/null+++ b/studio/backend/tests/test_account_native_model_lease.py@@ -0,0 +1,118 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A native GGUF selection is authorized on the lease's canonical path, not its display label.++The desktop shell mints the signed lease; on a multi-account install the account signed in+inside that shell is a managed one, and its ``model_path`` is the file's display label.+"""++from __future__ import annotations++import asyncio+import base64+import hashlib+import hmac+import json+import os+import time+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++import utils.native_path_leases as leases+from auth import policy+from hub.services.models import account_access as access+from models.inference import LoadRequest, ValidateModelRequest+from routes import inference as inference_routes+from utils.account_context import AccountContext, arun_as, run_as+from utils.paths.storage_roots import workspace_root++ALICE = AccountContext("a" * 32, "alice")+SECRET = base64.urlsafe_b64encode(b"native-lease-secret-for-tests-32").decode()++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv(leases.LEASE_SECRET_ENV, SECRET)+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None)+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_public_repos", {})+ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: (_ for _ in ()).throw(OSError("offline"))+ ),+ )+++def _mint(path, operation: str, label: str) -> str:+ st = os.lstat(path)+ payload = {+ "version": 1,+ "operation": operation,+ "canonical_path": str(path),+ "path_kind": "model",+ "path_type": "file",+ "source_kind": "drop",+ "token_id_hash": "token-hash",+ "display_label": label,+ "issued_at_ms": int(time.time() * 1000) - 1000,+ "expires_at_ms": int(time.time() * 1000) + 600_000,+ "nonce": base64.urlsafe_b64encode(os.urandom(12)).decode(),+ "size_bytes": st.st_size,+ "modified_ms": int(st.st_mtime_ns // 1_000_000),+ "device_id": format(st.st_dev, "x"),+ "file_id": format(st.st_ino, "x"),+ }+ body = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")+ signature = hmac.new(+ base64.urlsafe_b64decode(SECRET), body.encode("ascii"), hashlib.sha256+ ).digest()+ return f"{body}.{base64.urlsafe_b64encode(signature).decode().rstrip('=')}"+++def _gguf(directory, name = "private-model.gguf"):+ directory.mkdir(parents = True, exist_ok = True)+ path = directory / name+ path.write_bytes(b"GGUF" + b"\0" * 64)+ return path+++def _validate(request):+ return asyncio.run(arun_as(ALICE, inference_routes.validate_model(request, None, "alice")))+++def test_validate_accepts_a_native_gguf_inside_the_accounts_own_workspace():+ gguf = _gguf(run_as(ALICE, workspace_root) / "models")+ request = ValidateModelRequest(+ model_path = gguf.name,+ native_path_lease = _mint(gguf, "validate-model", gguf.name),+ )+ response = _validate(request)+ assert response.valid is True+++def test_validate_refuses_a_native_gguf_outside_the_accounts_roots(tmp_path):+ gguf = _gguf(tmp_path / "elsewhere")+ request = ValidateModelRequest(+ model_path = gguf.name,+ native_path_lease = _mint(gguf, "validate-model", gguf.name),+ )+ with pytest.raises(HTTPException) as excinfo:+ _validate(request)+ assert excinfo.value.status_code == 404+++def test_load_refuses_a_native_gguf_outside_the_accounts_roots(tmp_path):+ gguf = _gguf(tmp_path / "elsewhere")+ request = LoadRequest(+ model_path = gguf.name,+ native_path_lease = _mint(gguf, "load-model", gguf.name),+ )+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(arun_as(ALICE, inference_routes._load_model_impl(request, None, "alice")))+ assert excinfo.value.status_code == 404diff --git a/studio/backend/tests/test_account_offline_dataset_fallback.py b/studio/backend/tests/test_account_offline_dataset_fallback.pynew file mode 100644index 00000000000..93a9308d25e--- /dev/null+++ b/studio/backend/tests/test_account_offline_dataset_fallback.py@@ -0,0 +1,76 @@+# 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 offline dataset fallback must not hand another account's cached private dataset away."""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import HTTPException++from auth import policy+from hub.services.models import account_access+from hub.utils import dataset_cache+from models.training import TrainingStartRequest+from routes import training+from utils import hf_cache_settings+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+++def shared_cache(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ cache = tmp_path / "hub-cache"+ for repo in ("public--set", "private--set"):+ (cache / f"datasets--{repo}" / "snapshots" / "rev").mkdir(parents = True)+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(cache))+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])+ monkeypatch.setattr(account_access, "model_grants", lambda: set())+ monkeypatch.setattr(+ account_access,+ "repo_is_public",+ lambda repo_id, repo_type = "model": not repo_id.startswith("private/"),+ )+ # Bob already downloaded both; the cache lookup finds them for anyone.+ monkeypatch.setattr(+ dataset_cache,+ "training_dataset_cache_pin",+ lambda repo_id, local_path = None: (+ cache / f"datasets--{repo_id.replace('/', '--')}" / "snapshots" / "rev",+ "rev",+ ),+ )+ # No Hub: only the offline fallback can answer.+ monkeypatch.setattr(training, "hf_env_offline", lambda: True)+ monkeypatch.setattr(training, "_hub_unreachable", lambda: True)+ return cache+++def _request(dataset: str) -> TrainingStartRequest:+ return TrainingStartRequest(+ model_name = "public/model",+ hf_dataset = dataset,+ hf_token = "not-a-real-token",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ )+++def test_the_offline_cache_fallback_refuses_an_invisible_dataset(shared_cache):+ """No cached claim is advertised, so nothing else in the start path checks the grant."""+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, training._preflight_hf_dataset_request, _request("private/set"))+ assert exc.value.status_code == 404+++def test_the_offline_cache_fallback_still_accepts_a_visible_dataset(shared_cache):+ assert run_as(ALICE, training._preflight_hf_dataset_request, _request("public/set")) is None+++def test_the_owner_offline_cache_fallback_is_unchanged(shared_cache):+ assert training._preflight_hf_dataset_request(_request("private/set")) is Nonediff --git a/studio/backend/tests/test_account_openai_video_pin.py b/studio/backend/tests/test_account_openai_video_pin.pynew file mode 100644index 00000000000..7c0ebea4945--- /dev/null+++ b/studio/backend/tests/test_account_openai_video_pin.py@@ -0,0 +1,125 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import allow_ambient_hf_token, get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access as access+from routes import video+from state import active_generations+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+PUBLIC = {"org/public-video"}++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_resident_accounts", {})+ monkeypatch.setattr(access, "_resident_components", {}, raising = False)+ monkeypatch.setattr(access, "_generation_accounts", {})+ monkeypatch.setattr(access, "repo_is_public", lambda repo_id, *a, **k: repo_id in PUBLIC)+ monkeypatch.setattr(gpu_arbiter, "_owner", "video")+ monkeypatch.setattr(gpu_arbiter, "_owner_account", BOB.account_id)+ active_generations.reset_for_tests()+ yield+ active_generations.reset_for_tests()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[allow_ambient_hf_token] = lambda: False+ app.include_router(video.openai_router, prefix = "/v1")+ return TestClient(app)+++def _multipart(fields):+ boundary = "----unsloth-test-boundary"+ parts = []+ for name, value in fields.items():+ parts.append(+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()+ )+ parts.append(f"--{boundary}--\r\n".encode())+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"+++def test_openai_video_resident_replaced_after_authorization(monkeypatch):+ from core.inference import video as video_module+ from core.inference.video_families import VIDEO_MODEL_CHANGED_MSG++ resident = SimpleNamespace(repo_id = "org/public-video", family = "wan")+ replacement = SimpleNamespace(repo_id = "bob/private-video", family = "wan")+ box = {"state": resident, "reads": 0}+ reserved = []++ def _status_of(state):+ return {+ "loaded": True,+ "repo_id": state.repo_id,+ "family": state.family,+ "base_repo": None,+ "defaults": {+ "num_frames": 17,+ "fps": 16,+ "frame_step": 4,+ "frame_offset": 1,+ "resolution_presets": [[320, 320]],+ },+ }++ def _advance():+ state = box["state"]+ box["reads"] += 1+ if box["reads"] == 1:+ box["state"] = replacement+ return state++ def status():+ return _status_of(_advance())++ def generation_snapshot():+ state = _advance()+ return _status_of(state), state++ def begin_generate(**kwargs):+ expected = kwargs.get("expected_state")+ if expected is not None and expected is not box["state"]:+ raise RuntimeError(VIDEO_MODEL_CHANGED_MSG)+ reserved.append(box["state"].repo_id)+ return {"width": 320, "height": 320, "num_frames": 17, "fps": 16}++ backend = SimpleNamespace(+ status = status,+ generation_snapshot = generation_snapshot,+ begin_generate = begin_generate,+ generate_progress = lambda: {"active": False},+ )+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+ body, content_type = _multipart({"prompt": "a sloth", "size": "320x320"})+ with client_for(ALICE) as client:+ response = client.post("/v1/videos", content = body, headers = {"Content-Type": content_type})+ print("STATUS", response.status_code, response.json())+ print("RESERVED", reserved)+ assert response.status_code == 404, response.json()+ assert reserved == []diff --git a/studio/backend/tests/test_account_path_hardening.py b/studio/backend/tests/test_account_path_hardening.pynew file mode 100644index 00000000000..c959d801cc7--- /dev/null+++ b/studio/backend/tests/test_account_path_hardening.py@@ -0,0 +1,375 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's paths resolve inside its own roots, and monitor rows are visible only to the owner and the loading account."""++import json+import os+import sys++import pytest+from fastapi import HTTPException++from auth import policy+from core.inference import api_monitor+from hub.storage import scan_folders+from utils.account_context import OWNER, AccountContext, run_as+from utils.models import checkpoints, model_config+from utils.paths import storage_roots++ALICE = AccountContext("alice-id", "alice")+BOB = AccountContext("bob-id", "bob")++[email protected](autouse = True)+def studio(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ return tmp_path / "studio"+++def _adapter_run(root, name, base):+ run = root / name+ run.mkdir(parents = True, exist_ok = True)+ (run / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": base}))+ return run++[email protected](sys.platform == "win32", reason = "symlinks need privileges on Windows")+def test_managed_dataset_path_does_not_follow_a_link_out_of_the_account():+ secret = run_as(ALICE, storage_roots.dataset_uploads_root) / "private.jsonl"+ secret.parent.mkdir(parents = True)+ secret.write_text('{"text": "ALICE-SECRET"}')+ bob_uploads = run_as(BOB, storage_roots.dataset_uploads_root)+ bob_uploads.mkdir(parents = True)+ (bob_uploads / "linked.jsonl").symlink_to(secret)+ for spelling in ("uploads/linked.jsonl", "linked.jsonl", str(bob_uploads / "linked.jsonl")):+ with pytest.raises(ValueError, match = "escapes the account workspace|under a dataset root"):+ run_as(BOB, storage_roots.resolve_dataset_path, spelling)+ own = bob_uploads / "mine.jsonl"+ own.write_text("{}")+ assert run_as(BOB, storage_roots.resolve_dataset_path, "uploads/mine.jsonl") == own++[email protected](sys.platform == "win32", reason = "symlinks need privileges on Windows")+def test_owner_keeps_following_links_in_its_own_install(tmp_path):+ elsewhere = tmp_path / "other-drive" / "data.jsonl"+ elsewhere.parent.mkdir(parents = True)+ elsewhere.write_text("{}")+ uploads = run_as(OWNER, storage_roots.dataset_uploads_root)+ uploads.mkdir(parents = True)+ (uploads / "linked.jsonl").symlink_to(elsewhere)+ assert (+ run_as(OWNER, storage_roots.resolve_dataset_path, "uploads/linked.jsonl")+ == uploads / "linked.jsonl"+ )++[email protected](sys.platform == "win32", reason = "symlinks need privileges on Windows")+def test_scanners_skip_a_linked_run_that_belongs_to_another_account():+ alice_run = _adapter_run(+ run_as(ALICE, storage_roots.outputs_root), "alice-run", "ALICE-PRIVATE-BASE"+ )+ alice_export = run_as(ALICE, storage_roots.exports_root) / "alice-export" / "checkpoint-1"+ _adapter_run(alice_export.parent, "checkpoint-1", "ALICE-PRIVATE-BASE")+ bob_outputs = run_as(BOB, storage_roots.outputs_root)+ bob_outputs.mkdir(parents = True)+ _adapter_run(bob_outputs, "bob-run", "BOB-BASE")+ (bob_outputs / "linked-run").symlink_to(alice_run, target_is_directory = True)+ bob_exports = run_as(BOB, storage_roots.exports_root)+ bob_exports.mkdir(parents = True)+ (bob_exports / "linked-export").symlink_to(alice_export.parent, target_is_directory = True)++ names = [name for name, _cps, _meta in run_as(BOB, checkpoints.scan_checkpoints)]+ assert names == ["bob-run"]+ trained = [name for name, _path, _kind in run_as(BOB, model_config.scan_trained_models)]+ assert trained == ["bob-run"]+ exported = run_as(BOB, model_config.scan_exported_models)+ assert all("ALICE" not in json.dumps(row) for row in exported)+ owner_outputs = run_as(OWNER, storage_roots.outputs_root)+ owner_outputs.mkdir(parents = True, exist_ok = True)+ (owner_outputs / "linked-run").symlink_to(alice_run, target_is_directory = True)+ assert "linked-run" in [name for name, _c, _m in run_as(OWNER, checkpoints.scan_checkpoints)]+++def test_managed_export_write_dir_stays_inside_its_roots():+ foreign = run_as(ALICE, storage_roots.exports_root) / "victim"+ foreign.mkdir(parents = True)+ with pytest.raises(ValueError, match = "escapes the account workspace"):+ run_as(BOB, storage_roots.resolve_export_write_dir, str(foreign))+ own = run_as(BOB, storage_roots.exports_root) / "mine"+ assert run_as(BOB, storage_roots.resolve_export_write_dir, str(own)) == own+ assert run_as(OWNER, storage_roots.resolve_export_write_dir, str(foreign)) == foreign++[email protected]("module_name", ["hub.storage.scan_folders", "storage.studio_db"])+def test_scan_folder_storage_refuses_a_foreign_directory(monkeypatch, module_name):+ import importlib++ module = importlib.import_module(module_name)+ foreign = run_as(ALICE, storage_roots.outputs_root)+ foreign.mkdir(parents = True, exist_ok = True)+ own = run_as(BOB, storage_roots.outputs_root)+ own.mkdir(parents = True, exist_ok = True)+ assert run_as(OWNER, module.add_scan_folder_with_status, str(foreign))[1]+ assert run_as(BOB, module.add_scan_folder_with_status, str(own))[1]+ monkeypatch.setattr(+ module,+ "get_connection",+ lambda: (_ for _ in ()).throw(AssertionError("opened the database")),+ )+ with pytest.raises(ValueError, match = "outside this account's workspace"):+ run_as(BOB, module.add_scan_folder_with_status, str(foreign))+++def test_image_training_dataset_name_resolves_before_the_account_check():+ from routes import training++ for account in (OWNER, ALICE):+ root = run_as(account, storage_roots.datasets_root)+ (root / "my-images").mkdir(parents = True, exist_ok = True)+ assert run_as(account, training._resolve_diffusion_data_dir, "my-images") == (+ root / "my-images"+ )+ foreign = run_as(ALICE, storage_roots.datasets_root) / "my-images"+ with pytest.raises((HTTPException, ValueError)):+ run_as(BOB, training._resolve_diffusion_data_dir, str(foreign))+++def test_monitor_hides_a_foreign_load_row_from_managed_accounts():+ monitor = (+ api_monitor.ApiMonitor() if hasattr(api_monitor, "ApiMonitor") else api_monitor.api_monitor+ )+ entry = run_as(+ ALICE,+ api_monitor.ApiMonitorEntry,+ id = "load-1",+ endpoint = "",+ method = "",+ model = "/private/alice/outputs/SECRET.gguf",+ prompt = "",+ status = "completed",+ started_at = 0.0,+ updated_at = 0.0,+ started_monotonic = 0.0,+ finished_at = 0.0,+ finished_monotonic = 0.0,+ kind = "lifecycle",+ event = "load",+ reason = "",+ shared = True,+ subject = "alice",+ )+ assert run_as(ALICE, monitor._visible, entry, "alice")+ assert run_as(OWNER, monitor._visible, entry, "unsloth")+ assert not run_as(BOB, monitor._visible, entry, "bob")+ monkeypatch_single = policy.installation_is_multi_user+ policy.installation_is_multi_user = lambda: False+ try:+ assert run_as(OWNER, monitor._visible, entry, "unsloth")+ assert not run_as(BOB, monitor._visible, entry, "bob")+ finally:+ policy.installation_is_multi_user = monkeypatch_single+++def test_a_recreated_username_cannot_read_the_previous_accounts_monitor_rows():+ old_alice = AccountContext("alice-first-id", "alice")+ new_alice = AccountContext("alice-second-id", "alice")+ monitor = api_monitor.ApiMonitor()++ request_id = run_as(+ old_alice,+ lambda: monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "org/Repo",+ prompt = "ALICE-PRIVATE-PROMPT",+ subject = "alice",+ ),+ )+ run_as(+ old_alice,+ monitor.record_lifecycle,+ event = "load",+ model = "/alice/secret.gguf",+ subject = "alice",+ )++ assert run_as(new_alice, monitor.get, request_id, subject = "alice") is None+ assert run_as(new_alice, monitor.snapshot, subject = "alice") == []+ assert run_as(new_alice, monitor.active_count, subject = "alice") == 0+ run_as(new_alice, monitor.clear, subject = "alice")+ assert len(monitor._entries) == 2++ assert run_as(old_alice, monitor.get, request_id, subject = "alice") is not None+ assert run_as(old_alice, monitor.active_count, subject = "alice") == 1+ assert len(run_as(old_alice, monitor.snapshot, subject = "alice")) == 2+ run_as(old_alice, monitor.clear, subject = "alice")+ assert run_as(old_alice, monitor.get, request_id, subject = "alice") is not None+++def test_unload_rows_without_a_subject_stay_inside_the_account_that_recorded_them():+ monitor = api_monitor.ApiMonitor()+ run_as(ALICE, monitor.record_lifecycle, event = "unload", model = "acme/private", reason = "manual")+ run_as(ALICE, monitor.record_lifecycle, event = "unload", model = "alice-run-merged", reason = "idle")+ assert run_as(BOB, monitor.snapshot, subject = "bob") == []+ assert len(run_as(ALICE, monitor.snapshot, subject = "alice")) == 2+ assert len(run_as(OWNER, monitor.snapshot, subject = "unsloth")) == 2+++def test_one_account_installs_keep_every_monitor_row(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monitor = api_monitor.ApiMonitor()+ request_id = monitor.start(+ endpoint = "/v1/chat/completions",+ method = "POST",+ model = "org/Repo",+ prompt = "hello",+ subject = "unsloth",+ )+ monitor.finish(request_id)+ assert monitor.get(request_id, subject = "unsloth") is not None+ assert len(monitor.snapshot(subject = "unsloth")) == 1+ monitor.clear(subject = "unsloth")+ assert monitor.snapshot(subject = "unsloth") == []++[email protected](sys.platform == "win32", reason = "symlinks need privileges on Windows")+def test_a_managed_account_directory_replaced_by_a_link_is_refused(tmp_path):+ from core.inference import audio_gallery, image_gallery, video_gallery++ alice_images = run_as(ALICE, image_gallery.gallery_dir)+ (alice_images / "secret.png").write_bytes(b"ALICE-PNG")+ bob_root = run_as(BOB, storage_roots.workspace_root)+ bob_root.mkdir(parents = True, exist_ok = True)+ (bob_root / "images").symlink_to(alice_images, target_is_directory = True)+ (bob_root / "outputs").symlink_to(+ run_as(ALICE, storage_roots.outputs_root), target_is_directory = True+ )+ (bob_root / "studio.db").symlink_to(run_as(ALICE, storage_roots.studio_db_path))+ with pytest.raises(ValueError, match = "escapes the account workspace"):+ run_as(BOB, image_gallery.gallery_dir)+ with pytest.raises(ValueError, match = "escapes the account workspace"):+ run_as(BOB, image_gallery.list_images)+ with pytest.raises(ValueError, match = "escapes the account workspace"):+ run_as(BOB, storage_roots.outputs_root)+ with pytest.raises(ValueError, match = "escapes the account workspace"):+ run_as(BOB, storage_roots.studio_db_path)+ assert run_as(BOB, audio_gallery.gallery_dir) == bob_root / "audio"+ assert run_as(BOB, video_gallery.gallery_dir) == bob_root / "videos"+ assert run_as(BOB, storage_roots.exports_root) == bob_root / "exports"+ owner_root = run_as(OWNER, storage_roots.workspace_root)+ owner_root.mkdir(parents = True, exist_ok = True)+ (owner_root / "images").symlink_to(tmp_path / "other-drive-images", target_is_directory = True)+ (tmp_path / "other-drive-images").mkdir()+ assert run_as(OWNER, image_gallery.gallery_dir) == owner_root / "images"+++def test_tool_stream_worker_runs_as_the_calling_account():+ from core.inference.tool_stream_exec import stream_tool_execution+ from utils.account_context import current_account++ def consume(fn):+ gen = stream_tool_execution(lambda callback: fn(), tool_name = "python")+ try:+ while True:+ next(gen)+ except StopIteration as stop:+ return stop.value++ assert run_as(BOB, consume, lambda: current_account().account_id) == "bob-id"+ assert run_as(BOB, consume, lambda: str(storage_roots.studio_db_path())) == str(+ run_as(BOB, storage_roots.studio_db_path)+ )+ assert run_as(OWNER, consume, lambda: current_account().account_id) == OWNER.account_id+++def test_download_watcher_is_pinned_to_the_requesting_account(monkeypatch):+ from hub.services import download_lifecycle+ from utils import account_context++ captured = {}++ class _Thread:+ def __init__(+ self,+ *,+ target,+ args = (),+ kwargs = None,+ **_kw,+ ):+ captured["target"], captured["args"] = target, args++ def start(self):+ pass++ monkeypatch.setattr(account_context.threading, "Thread", _Thread)+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ run_as(BOB, download_lifecycle.account_thread, target = lambda: None, name = "watch", daemon = True)+ assert captured["target"] is account_context.run_as+ assert captured["args"][0] == BOB+++def test_external_provider_cancel_keys_are_scoped_like_every_lookup():+ import inspect++ import routes.inference as inference++ source = inspect.getsource(inference._proxy_to_external_provider)+ registration = source.index("cancel_keys = tuple(")+ assert "_account_cancel_key(key)" in source[registration : registration + 200]+ assert "_PENDING_CANCELS.pop(_account_cancel_key(payload.cancel_id), None)" in source+++def test_export_size_cache_is_keyed_per_managed_account(monkeypatch):+ import routes.models as models+ from hub.services.models import account_access++ monkeypatch.setattr(models, "_EXPORT_SIZE_CACHE", {})+ monkeypatch.setattr(account_access, "managed_account", lambda: True)+ monkeypatch.setattr(models, "is_local_path", lambda model: False)+ import utils.hardware.hardware as hardware++ monkeypatch.setattr(+ hardware,+ "estimate_fp16_model_size_bytes",+ lambda model, hf_token = None: (1000, "ALICE-SOURCE"),+ )+ assert run_as(ALICE, models._export_size_cached, "my-finetune", None) == (+ 1000,+ 500,+ "ALICE-SOURCE",+ )+ monkeypatch.setattr(+ hardware,+ "estimate_fp16_model_size_bytes",+ lambda model, hf_token = None: (2000, "BOB-SOURCE"),+ )+ assert run_as(BOB, models._export_size_cached, "my-finetune", None) == (+ 2000,+ 1000,+ "BOB-SOURCE",+ )+ assert run_as(ALICE, models._export_size_cached, "my-finetune", None) == (+ 1000,+ 500,+ "ALICE-SOURCE",+ )+++def test_a_managed_account_may_export_into_its_own_project_workspace(tmp_path, monkeypatch):+ from core.training import account_jobs++ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "documents"))+ own = run_as(BOB, storage_roots.project_workspaces_root) / "demo" / "exports"+ own.mkdir(parents = True)+ run_as(BOB, account_jobs.validate_job_paths, {"save_directory": str(own)})+ assert run_as(BOB, storage_roots.resolve_export_write_dir, str(own)) == own+ assert run_as(BOB, scan_folders.add_scan_folder_with_status, str(own))[1]+ foreign = run_as(ALICE, storage_roots.project_workspaces_root) / "alice-demo"+ foreign.mkdir(parents = True)+ with pytest.raises(ValueError, match = "escapes the account workspace"):+ run_as(BOB, storage_roots.resolve_export_write_dir, str(foreign))+ with pytest.raises(ValueError, match = "outside this account"):+ run_as(BOB, scan_folders.add_scan_folder_with_status, str(foreign))diff --git a/studio/backend/tests/test_account_path_imports.py b/studio/backend/tests/test_account_path_imports.pynew file mode 100644index 00000000000..286a22c3d76--- /dev/null+++ b/studio/backend/tests/test_account_path_imports.py@@ -0,0 +1,97 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Account roots must be resolved when work runs, never while importing it."""++import ast+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parents[1]+_PATH_MODULES = ("utils.paths", "hub.utils.paths")+# Shared by every account, so a value captured at import cannot leak between them.+_INSTALL_WIDE = ("studio_root", "auth_db_path", "bin_root", "cache_root", "logs_root")+++def import_time_path_calls(source: str, module: str = "") -> list[tuple[int, str]]:+ tree = ast.parse(source)+ names = {}+ for node in tree.body:+ if isinstance(node, ast.ImportFrom):+ origin = node.module or ""+ if node.level:+ origin = ".".join(module.split(".")[: -node.level] + [origin])+ for alias in node.names:+ names[alias.asname or alias.name] = f"{origin}.{alias.name}"+ elif isinstance(node, ast.Import):+ for alias in node.names:+ names[alias.asname or alias.name.split(".")[0]] = (+ alias.name if alias.asname else alias.name.split(".")[0]+ )++ def target(node):+ if isinstance(node, ast.Name):+ return names.get(node.id, "")+ if isinstance(node, ast.Attribute):+ return f"{target(node.value)}.{node.attr}"+ return ""++ found = []++ class AtImport(ast.NodeVisitor):+ def visit_Call(self, node):+ name = target(node.func)+ if (+ name.startswith(tuple(f"{prefix}." for prefix in _PATH_MODULES))+ and name.endswith(("_root", "_path"))+ and name.rsplit(".", 1)[-1] not in _INSTALL_WIDE+ ):+ found.append((node.lineno, name))+ self.generic_visit(node)++ def visit_FunctionDef(self, node):+ for value in [*node.decorator_list, *node.args.defaults, *node.args.kw_defaults]:+ if value is not None:+ self.visit(value)++ visit_AsyncFunctionDef = visit_FunctionDef++ def visit_Lambda(self, node):+ for value in [*node.args.defaults, *node.args.kw_defaults]:+ if value is not None:+ self.visit(value)++ AtImport().visit(tree)+ return found+++ "source",+ [+ "from utils.paths import outputs_root\nROOT = outputs_root()",+ "from utils.paths import outputs_root as root\ndef f(p = str(root())): pass",+ "import utils.paths as p\nclass C: root = p.outputs_root()",+ "from utils import paths as p\nf = lambda root = p.outputs_root(): root",+ "from hub.utils.paths import datasets_root\nROOT = datasets_root()",+ ],+)+def test_guard_detects_captured_roots(source):+ assert import_time_path_calls(source)+++def test_guard_allows_call_time_accessors():+ source = "from utils.paths import outputs_root\ndef f(): return outputs_root()\nROOT = lambda: outputs_root()"+ assert import_time_path_calls(source) == []+++def test_backend_does_not_capture_account_paths_at_import():+ failures = []+ for path in sorted(_BACKEND.rglob("*.py")):+ relative = path.relative_to(_BACKEND)+ if "tests" in relative.parts:+ continue+ module = ".".join(relative.with_suffix("").parts)+ for line, target in import_time_path_calls(path.read_text(encoding = "utf-8"), module):+ failures.append(f"{relative}:{line}: {target}")+ assert failures == [], "Resolve paths at call time:\n" + "\n".join(failures)diff --git a/studio/backend/tests/test_account_policy_cache_window.py b/studio/backend/tests/test_account_policy_cache_window.pynew file mode 100644index 00000000000..ea53679458f--- /dev/null+++ b/studio/backend/tests/test_account_policy_cache_window.py@@ -0,0 +1,125 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""No policy read may answer from the pre-write state once an account mutation has committed.++The observation point is the account write's own ``conn.close()``: the INSERT/UPDATE is durable by+then, and it sits inside the window that a concurrent request would land in.+"""++import importlib.util+import secrets+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage+++def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user(+ storage.DEFAULT_ADMIN_USERNAME, "owner-password", secrets.token_urlsafe(32)+ )+ yield storage+ policy.invalidate_account_cache()+++def _auth_client():+ route_path = Path(storage.__file__).resolve().parents[1] / "routes" / "auth.py"+ spec = importlib.util.spec_from_file_location("_policy_window_auth_route", route_path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ app = FastAPI()+ app.include_router(module.router, prefix = "/api/auth")+ return TestClient(app)+++class _ObservingConnection:+ """Delegates to a real connection and runs ``observe`` once, as the write closes it."""++ def __init__(self, conn, seen, observe):+ self._conn, self._seen, self._observe = conn, seen, observe++ def __getattr__(self, name):+ return getattr(self._conn, name)++ def __enter__(self):+ self._conn.__enter__()+ return self++ def __exit__(self, *exc):+ return self._conn.__exit__(*exc)++ def close(self):+ if self._observe is not None:+ observe, self._observe = self._observe, None+ self._seen["counts"] = storage.account_counts()+ self._seen["observed"] = observe()+ self._conn.close()+++def _observe_when_the_write_commits(monkeypatch, observe):+ seen = {}+ real = storage.get_connection+ armed = [True]++ def get_connection():+ conn = real()+ if not armed[0]:+ return conn+ armed[0] = False+ return _ObservingConnection(conn, seen, observe)++ monkeypatch.setattr(storage, "get_connection", get_connection)+ return seen+++def test_desktop_login_while_the_first_account_is_created_is_not_granted(auth_db, monkeypatch):+ raw = storage.create_desktop_secret()+ client = _auth_client()++ # A single-user install answers desktop-login from the cached owner-only count.+ granted = client.post("/api/auth/desktop-login", json = {"secret": raw})+ assert granted.status_code == 200 and granted.json().get("access_token")++ seen = _observe_when_the_write_commits(+ monkeypatch,+ lambda: client.post("/api/auth/desktop-login", json = {"secret": raw}).json(),+ )+ storage.issue_account_setup_code(username = "alice")++ assert seen["counts"] == (2, 1), "the managed account must already be durable"+ assert seen["observed"] == {"login_required": True, "login_mode": "multi"}+++def test_the_policy_verdict_follows_the_committed_row_while_creating(auth_db, monkeypatch):+ assert policy.installation_is_multi_user() is False++ seen = _observe_when_the_write_commits(monkeypatch, policy.installation_is_multi_user)+ storage.issue_account_setup_code(username = "alice")++ assert seen["counts"] == (2, 1)+ assert seen["observed"] is True+ assert policy.installation_is_multi_user() is True+++def test_the_policy_verdict_follows_the_committed_row_while_reactivating(auth_db, monkeypatch):+ account = storage.issue_account_setup_code(username = "alice")["account"]+ storage.set_account_active(account["account_id"], False)+ assert policy.installation_is_multi_user() is False++ seen = _observe_when_the_write_commits(monkeypatch, policy.installation_is_multi_user)+ storage.set_account_active(account["account_id"], True)++ assert seen["counts"] == (2, 1)+ assert seen["observed"] is True+ assert policy.installation_is_multi_user() is Truediff --git a/studio/backend/tests/test_account_policy_states.py b/studio/backend/tests/test_account_policy_states.pynew file mode 100644index 00000000000..64da75f6afb--- /dev/null+++ b/studio/backend/tests/test_account_policy_states.py@@ -0,0 +1,131 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""``login_mode`` / ``installation_is_multi_user`` follow the ACTIVE count; ``installation_has_managed_accounts`` and the full-access gate follow whether any managed account exists at all."""++import secrets++import pytest++from auth import policy, storage+++def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield storage+ policy.invalidate_account_cache()+++def _state() -> tuple[str, bool, bool, bool]:+ policy.invalidate_account_cache()+ return (+ policy.login_mode(),+ policy.installation_is_multi_user(),+ policy.installation_has_managed_accounts(),+ policy.full_access_permitted(),+ )+++def test_owner_only(auth_db):+ assert _state() == ("single", False, False, True)+++def test_owner_plus_one_active_managed_account(auth_db):+ storage.issue_account_setup_code(username = "alice")+ assert _state() == ("multi", True, True, False)+++def test_owner_plus_one_deactivated_managed_account(auth_db):+ account = storage.issue_account_setup_code(username = "alice")["account"]+ storage.set_account_active(account["account_id"], False)+ assert _state() == ("single", False, True, False)+++def test_an_unreadable_auth_database(auth_db, monkeypatch):+ def boom():+ raise OSError("auth.db unreadable")++ monkeypatch.setattr(storage, "account_counts", boom)+ assert _state() == ("single", False, True, False)+++def test_a_count_read_failure_keeps_a_bound_managed_account_isolated(auth_db, monkeypatch):+ from utils.account_context import AccountContext, run_as++ def boom():+ raise OSError("auth.db unreadable")++ monkeypatch.setattr(storage, "account_counts", boom)+ policy.invalidate_account_cache()+ assert run_as(AccountContext("a" * 32, "alice"), policy.installation_is_multi_user) is True+++def test_deactivating_the_last_managed_account_keeps_a_bound_request_isolated(+ auth_db, monkeypatch, tmp_path+):+ from fastapi import HTTPException+ from hub.services.models import account_access as access+ from utils.account_context import AccountContext, run_as++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("HF_TOKEN", "installation-token")+ account = storage.issue_account_setup_code(username = "alice")["account"]+ alice = AccountContext(account["account_id"], "alice")+ assert run_as(alice, access.managed_account) is True++ storage.set_account_active(account["account_id"], False)+ assert policy.installation_is_multi_user() is False+ assert run_as(alice, access.managed_account) is True+ assert run_as(alice, access.ambient_hf_token) is False+ with pytest.raises(HTTPException) as raised:+ run_as(alice, access.require_model_access, "/owner/private/checkpoint.gguf")+ assert raised.value.status_code == 404+++def test_deactivating_the_last_account_does_not_hand_its_download_to_the_owner(+ auth_db, monkeypatch, tmp_path+):+ """Deactivation does not cancel downloads, so the owner must stay scoped."""+ import logging++ from fastapi import HTTPException+ from hub.services import download_lifecycle+ from hub.services.models import account_access as access+ from hub.utils import download_registry+ from utils.account_context import OWNER, AccountContext, run_as++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(download_lifecycle, "_job_accounts", {})+ assert access.account_scope() is None+ record = storage.issue_account_setup_code(username = "alice")["account"]+ alice = AccountContext(record["account_id"], "alice")+ registry = download_registry.DownloadRegistry()+ key = "alice-org/private-secret::"+ registry.claim(key, "http", repo_type = "model", repo_id = "alice-org/private-secret")+ run_as(alice, download_lifecycle.record_download_account, registry, key)+ storage.set_account_active(record["account_id"], False)+ assert policy.installation_is_multi_user() is False+ assert run_as(OWNER, download_lifecycle.download_belongs_to_account, registry, key) is False+ assert (+ run_as(+ OWNER,+ lambda: download_lifecycle.active_download_refs(registry, None, with_variant = True),+ )+ == []+ )+ with pytest.raises(HTTPException) as exc:+ run_as(+ OWNER,+ lambda: download_lifecycle.cancel_worker(+ registry, key, generation = None, label = "model", logger = logging.getLogger(__name__)+ ),+ )+ assert exc.value.status_code == 404 and registry.get_job(key).state == "running"+ legacy = "legacy-org/model::"+ registry.claim(legacy, "http", repo_type = "model", repo_id = "legacy-org/model")+ assert run_as(OWNER, download_lifecycle.download_belongs_to_account, registry, legacy) is Truediff --git a/studio/backend/tests/test_account_private_directory_project_root.py b/studio/backend/tests/test_account_private_directory_project_root.pynew file mode 100644index 00000000000..696692a82ae--- /dev/null+++ b/studio/backend/tests/test_account_private_directory_project_root.py@@ -0,0 +1,62 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's own project workspace is inside its directory boundary."""++from __future__ import annotations++from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from hub.services.models import account_access as access+from utils.account_context import AccountContext, run_as+from utils.paths.storage_roots import project_workspaces_root++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_public_repos", {})+ monkeypatch.setattr(+ access,+ "HfApi",+ lambda: SimpleNamespace(+ repo_info = lambda *a, **k: (_ for _ in ()).throw(OSError("offline"))+ ),+ )+++def _alice_project(tmp_path):+ project = run_as(ALICE, project_workspaces_root) / "demo-1234"+ project.mkdir(parents = True, exist_ok = True)+ return project+++def test_private_directory_admits_the_accounts_own_project_workspace(tmp_path):+ project = _alice_project(tmp_path)+ # The same path the account boundary and model visibility already accept.+ assert run_as(ALICE, access.model_visible, str(project))+ assert run_as(ALICE, access.private_directory, str(project), "") == str(project)+++def test_private_directory_still_refuses_another_accounts_project_workspace(tmp_path):+ project = _alice_project(tmp_path)+ with pytest.raises(HTTPException):+ run_as(BOB, access.private_directory, str(project), "")+++def test_private_directory_owner_and_workspace_paths_unchanged(tmp_path):+ from utils.paths.storage_roots import workspace_root++ alice_outputs = str(run_as(ALICE, workspace_root) / "outputs")+ assert run_as(ALICE, access.private_directory, alice_outputs, "outputs") == alice_outputs+ with pytest.raises(HTTPException):+ run_as(ALICE, access.private_directory, str(tmp_path / "elsewhere"), "outputs")diff --git a/studio/backend/tests/test_account_provider_isolation.py b/studio/backend/tests/test_account_provider_isolation.pynew file mode 100644index 00000000000..9da0d17b45e--- /dev/null+++ b/studio/backend/tests/test_account_provider_isolation.py@@ -0,0 +1,191 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Provider, MCP and remote-code trust boundaries use the authenticated account DB."""++from __future__ import annotations++import asyncio+from contextlib import nullcontext++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import (+ authenticated_via_api_key,+ get_current_credential,+ get_current_subject,+)+from hub.services.models import account_access as access+from routes import mcp_servers, provider_credentials, providers+from storage import credential_secrets, mcp_servers_db, providers_db+from utils.account_context import (+ OWNER,+ AccountContext,+ arun_as,+ bind_account,+ reset_account,+ run_as,+)+from utils.security import remote_code_approvals as approvals++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ for module in (credential_secrets, mcp_servers_db, providers_db):+ monkeypatch.setattr(module, "_schema_ready", set())+ monkeypatch.setattr(+ credential_secrets, "get_or_create_credential_encryption_key", lambda: b"k" * 32+ )+ monkeypatch.setattr(providers, "current_credential_write", lambda credential: nullcontext())+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[get_current_credential] = lambda: (account.username, None)+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(providers.router, prefix = "/providers")+ app.include_router(mcp_servers.router, prefix = "/mcp")+ return TestClient(app)++[email protected]("account,other", [(ALICE, BOB), (BOB, ALICE)])+def test_provider_object_routes_and_saved_keys_are_private(account, other):+ with client_for(account) as client:+ created = client.post(+ "/providers/", json = {"provider_type": "openai", "display_name": "Private provider"}+ )+ assert created.status_code == 201, created.text+ provider_id = created.json()["id"]+ run_as(account, credential_secrets.save_provider_api_key, provider_id, "private-api-key")+ with client_for(other) as client:+ assert client.get("/providers/").json() == []+ assert (+ client.put(f"/providers/{provider_id}", json = {"display_name": "stolen"}).status_code+ == 404+ )+ assert client.delete(f"/providers/{provider_id}").status_code == 404+ assert (+ client.put(+ f"/providers/{provider_id}/api-key/migrate", json = {"encrypted_api_key": "ignored"}+ ).status_code+ == 404+ )+ for path in ["/providers/test", "/providers/models"]:+ response = client.post(+ path, json = {"provider_type": "openai", "provider_id": provider_id}+ )+ assert response.status_code == 404, response.text+ assert run_as(other, credential_secrets.get_provider_api_key, provider_id) is None+ assert (+ run_as(account, credential_secrets.get_provider_api_key, provider_id) == "private-api-key"+ )+ with client_for(account) as client:+ assert client.get("/providers/").json()[0]["id"] == provider_id++[email protected]("account,other", [(ALICE, BOB), (BOB, ALICE)])+def test_mcp_server_ids_are_scoped_before_session_or_tool_access(account, other, monkeypatch):+ with client_for(account) as client:+ created = client.post(+ "/mcp/",+ json = {+ "display_name": "Private MCP",+ "url": "https://8.8.8.8/mcp",+ "headers": {"Authorization": "Bearer private"},+ },+ )+ assert created.status_code == 201, created.text+ server_id = created.json()["id"]+ calls = []+ monkeypatch.setattr(mcp_servers, "list_tools_async", lambda **kwargs: calls.append(kwargs))+ with client_for(other) as client:+ assert client.get("/mcp/").json() == []+ assert client.put(f"/mcp/{server_id}", json = {"display_name": "stolen"}).status_code == 404+ assert client.delete(f"/mcp/{server_id}").status_code == 404+ assert client.post(f"/mcp/{server_id}/refresh").status_code == 404+ assert calls == []+ with client_for(account) as client:+ assert client.get("/mcp/").json()[0]["id"] == server_id+++def test_same_provider_id_can_hold_different_account_credentials():+ for account, secret in [(ALICE, "alice-secret"), (BOB, "bob-secret")]:+ run_as(account, credential_secrets.save_provider_api_key, "same-provider-id", secret)+ run_as(account, credential_secrets.save_hf_token, secret)+ assert (+ run_as(+ ALICE, provider_credentials.resolve_provider_api_key_or_400, "same-provider-id", None+ )+ == "alice-secret"+ )+ assert (+ run_as(BOB, provider_credentials.resolve_provider_api_key_or_400, "same-provider-id", None)+ == "bob-secret"+ )+ assert run_as(ALICE, credential_secrets.get_hf_token) == "alice-secret"+ assert run_as(BOB, credential_secrets.get_hf_token) == "bob-secret"+++def test_provider_config_locks_do_not_serialize_unrelated_account_ids():+ async def check():+ a = await arun_as(ALICE, _get_lock())+ b = await arun_as(BOB, _get_lock())+ assert a is not b+ assert a is await arun_as(ALICE, _get_lock())++ async def _get_lock():+ return provider_credentials.provider_config_guard("same-id")++ asyncio.run(check())+++def test_remote_code_approvals_are_account_owned_and_survive_renames(tmp_path):+ run_as(+ ALICE,+ approvals.record,+ "alice",+ "org/private",+ commit_sha = "abc",+ fingerprint = "safe",+ max_severity = None,+ )+ assert run_as(ALICE, approvals.lookup, "alice", "org/private") is not None+ assert run_as(BOB, approvals.lookup, "alice", "org/private") is None+ renamed = AccountContext(ALICE.account_id, "new-alice")+ assert run_as(renamed, approvals.lookup, "new-alice", "org/private") is not None+ replacement = AccountContext("c" * 32, "alice")+ assert run_as(replacement, approvals.lookup, "alice", "org/private") is None+ run_as(BOB, approvals.forget, "alice", "org/private")+ assert run_as(ALICE, approvals.lookup, "alice", "org/private") is not None+ assert (+ run_as(OWNER, approvals._store_path) == tmp_path / "security" / "remote_code_approvals.json"+ )+ assert (+ run_as(ALICE, approvals._store_path)+ == tmp_path / "accounts" / ALICE.account_id / "security" / "remote_code_approvals.json"+ )+++def test_ambient_hf_credentials_are_never_lent_to_managed_accounts(monkeypatch):+ monkeypatch.setenv("HF_TOKEN", "owner-token")+ assert run_as(OWNER, access.ambient_hf_token) == "owner-token"+ assert run_as(ALICE, access.ambient_hf_token) is False+ assert run_as(BOB, access.account_hf_token, None) is False+ assert run_as(ALICE, access.account_hf_token, "alice-token") == "alice-token"diff --git a/studio/backend/tests/test_account_provider_network_scope.py b/studio/backend/tests/test_account_provider_network_scope.pynew file mode 100644index 00000000000..9f0a41b20fc--- /dev/null+++ b/studio/backend/tests/test_account_provider_network_scope.py@@ -0,0 +1,130 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account must not reach owner-local or LAN provider endpoints.++Managed MCP servers are already restricted to public destinations; provider base+URLs are the same caller-controlled server-side egress, so they get the same rule.+"""++import http.server+import threading+from contextlib import nullcontext++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import (+ authenticated_via_api_key,+ get_current_credential,+ get_current_subject,+)+from routes import providers+from storage import credential_secrets, providers_db+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")++# What an owner-local llama-server would expose and a tenant must never see.+OWNER_LOCAL_MODEL = "owner-local-secret-model"++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.delenv("UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS", raising = False)+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ for module in (credential_secrets, providers_db):+ monkeypatch.setattr(module, "_schema_ready", set())+ monkeypatch.setattr(+ credential_secrets, "get_or_create_credential_encryption_key", lambda: b"k" * 32+ )+ monkeypatch.setattr(providers, "current_credential_write", lambda credential: nullcontext())+++def local_provider():+ """A loopback OpenAI-compatible server standing in for the owner's llama-server."""++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ body = ('{"data": [{"id": "%s"}]}' % OWNER_LOCAL_MODEL).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target = server.serve_forever, daemon = True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}/v1"+ finally:+ server.shutdown()+ server.server_close()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[get_current_credential] = lambda: (account.username, None)+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(providers.router, prefix = "/providers")+ return TestClient(app)+++def test_managed_account_cannot_list_models_from_a_loopback_provider(local_provider):+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert response.status_code == 400, response.text+ assert OWNER_LOCAL_MODEL not in response.text+++def test_managed_account_cannot_save_a_private_provider_base_url(local_provider):+ with client_for(ALICE) as client:+ for base_url in (local_provider, "http://10.0.0.7:8080/v1", "http://169.254.1.1/v1"):+ created = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "LAN",+ "base_url": base_url,+ },+ )+ assert created.status_code == 400, f"{base_url}: {created.text}"+++def test_owner_keeps_local_providers(local_provider):+ with client_for(OWNER) as client:+ created = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "Local llama-server",+ "base_url": local_provider,+ },+ )+ assert created.status_code == 201, created.text+ listed = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert listed.status_code == 200, listed.text+ assert [m["id"] for m in listed.json()] == [OWNER_LOCAL_MODEL]diff --git a/studio/backend/tests/test_account_provider_rebind_pin.py b/studio/backend/tests/test_account_provider_rebind_pin.pynew file mode 100644index 00000000000..06a234e3255--- /dev/null+++ b/studio/backend/tests/test_account_provider_rebind_pin.py@@ -0,0 +1,91 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's provider hostname is re-resolved and pinned per connection, so a+name that validated as public cannot rebind to loopback before the request is sent."""++import asyncio+import http.server+import socket+import threading++import pytest++from core.inference import external_provider, providers+from core.inference.external_provider import ExternalProviderClient+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+REBINDING_HOST = "rebind.example"+PUBLIC_ADDRESS = "93.184.216.34"+++def owner_local():+ """A loopback server counting the requests that reached it."""+ hits = []++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ hits.append(self.path)+ body = b'{"data": [{"id": "owner-local-model"}]}'+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target = server.serve_forever, daemon = True).start()+ try:+ yield server.server_address[1], hits+ finally:+ server.shutdown()+ server.server_close()+++def rebinding_dns(monkeypatch, owner_local):+ """The first lookup of the name answers a public address; every later one answers loopback."""+ port, _ = owner_local+ real = socket.getaddrinfo+ answers = []++ def fake(host, *args, **kwargs):+ if host != REBINDING_HOST:+ return real(host, *args, **kwargs)+ address = PUBLIC_ADDRESS if not answers else "127.0.0.1"+ answers.append(address)+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port))]++ monkeypatch.setattr(socket, "getaddrinfo", fake)+ monkeypatch.setattr(providers, "_dns_cache", {})+ monkeypatch.setattr(external_provider, "_managed_http_client", None, raising = False)+ return answers+++def _list_models_as(account, base_url):+ token = bind_account(account)+ try:+ client = ExternalProviderClient("custom", base_url, "key")+ return asyncio.run(client.list_models())+ finally:+ reset_account(token)+++def test_managed_account_request_does_not_follow_a_rebound_name(owner_local, rebinding_dns):+ port, hits = owner_local+ with pytest.raises(Exception):+ _list_models_as(ALICE, f"http://{REBINDING_HOST}:{port}/v1")+ assert hits == [], hits+ assert rebinding_dns[0] == PUBLIC_ADDRESS and "127.0.0.1" in rebinding_dns[1:]+++def test_owner_request_still_reaches_a_local_provider(owner_local):+ port, hits = owner_local+ models = _list_models_as(OWNER, f"http://127.0.0.1:{port}/v1")+ assert [m["id"] for m in models] == ["owner-local-model"]+ assert hits == ["/v1/models"]diff --git a/studio/backend/tests/test_account_recipe_env_secrets.py b/studio/backend/tests/test_account_recipe_env_secrets.pynew file mode 100644index 00000000000..19db5c236fb--- /dev/null+++ b/studio/backend/tests/test_account_recipe_env_secrets.py@@ -0,0 +1,119 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed recipe must not be able to name a host environment secret.++Data Designer 0.5.4 resolves ModelProvider.api_key through+CompositeResolver([EnvironmentResolver(), PlaintextResolver()]), so a bare env var+name in api_key is replaced by that variable's value before it goes out as a bearer+token to the provider endpoint the same recipe supplies.+"""++from __future__ import annotations++import multiprocessing+import os++import pytest+from fastapi import HTTPException++from auth import policy+from core.training import account_jobs as jobs+from utils.account_context import AccountContext, OWNER, run_as++ALICE = AccountContext("alice-secret-account", "alice")++[email protected](autouse = True)+def multi(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(jobs, "_retired", set())+++ "recipe",+ [+ {+ "model_providers": [+ {+ "name": "exfil",+ "endpoint": "http://attacker.example/v1",+ "provider_type": "openai",+ "api_key": "OPENAI_API_KEY",+ }+ ]+ },+ {+ "mcp_providers": [+ {+ "name": "exfil",+ "endpoint": "http://attacker.example/mcp",+ "provider_type": "streamable_http",+ "api_key": "OPENAI_API_KEY",+ }+ ]+ },+ {"seed_config": {"source": {"seed_type": "hf", "token": "OPENAI_API_KEY"}}},+ ],+)+def test_managed_recipe_cannot_name_a_host_environment_secret(monkeypatch, recipe):+ monkeypatch.setenv("OPENAI_API_KEY", "sk-owner-host-secret")+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.validate_recipe_access, recipe)+ assert exc.value.status_code == 403+ run_as(OWNER, jobs.validate_recipe_access, recipe)+++def test_managed_recipe_keeps_accepting_plaintext_credentials(monkeypatch):+ monkeypatch.setenv("OPENAI_API_KEY", "sk-owner-host-secret")+ recipe = {+ "model_providers": [+ {+ "name": "mine",+ "endpoint": "https://api.openai.com/v1",+ "provider_type": "openai",+ "api_key": "sk-alice-own-key",+ }+ ]+ }+ run_as(ALICE, jobs.validate_recipe_access, recipe)+++def _provider_secret_probe(result_queue):+ result_queue.put({name: os.environ.get(name) for name in _PROVIDER_SECRETS})+++_PROVIDER_SECRETS = (+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "NVIDIA_API_KEY",+ "OPENROUTER_API_KEY",+)+++def test_child_scrubs_model_provider_secrets(monkeypatch):+ for name in _PROVIDER_SECRETS:+ monkeypatch.setenv(name, f"owner-{name}")+ ctx = multiprocessing.get_context("spawn")+ result_queue = ctx.Queue()+ process = ctx.Process(+ target = jobs.run_account_child,+ kwargs = {+ "account": ALICE,+ "job_module": __name__,+ "job_target": "_provider_secret_probe",+ "result_queue": result_queue,+ },+ )+ process.start()+ try:+ result = result_queue.get(timeout = 60)+ process.join(timeout = 10)+ assert process.exitcode == 0+ finally:+ if process.is_alive():+ process.terminate()+ process.join(timeout = 5)+ result_queue.close()+ assert all(value is None for value in result.values()), result+ assert os.environ["OPENAI_API_KEY"] == "owner-OPENAI_API_KEY"diff --git a/studio/backend/tests/test_account_recipe_mcp.py b/studio/backend/tests/test_account_recipe_mcp.pynew file mode 100644index 00000000000..e7eb14e0823--- /dev/null+++ b/studio/backend/tests/test_account_recipe_mcp.py@@ -0,0 +1,170 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's recipe MCP providers obey the chat MCP network boundary: no loopback, no LAN."""++from __future__ import annotations++import sys+import types++import pytest+from fastapi import HTTPException++from auth import policy+from core.inference import mcp_client+from utils.account_context import OWNER, AccountContext, run_as++ALICE = AccountContext("alice-id", "alice")++_PRIVATE_ENDPOINTS = (+ "http://127.0.0.1:9111/mcp",+ "http://localhost:9111/sse",+ "http://10.0.0.5:8000/mcp",+)++[email protected](autouse = True)+def data_designer_stub(monkeypatch, tmp_path):+ """Stand in for the recipe engine's provider classes, which are an Unsloth-only plugin absent on CI."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)++ class _Provider:+ def __init__(self, **fields):+ self.__dict__.update(fields)++ package = types.ModuleType("data_designer")+ config = types.ModuleType("data_designer.config")+ mcp = types.ModuleType("data_designer.config.mcp")+ mcp.MCPProvider = type("MCPProvider", (_Provider,), {})+ mcp.LocalStdioMCPProvider = type("LocalStdioMCPProvider", (_Provider,), {})+ models = types.ModuleType("data_designer.config.models")+ models.ModelProvider = type("ModelProvider", (_Provider,), {})+ config.mcp = mcp+ config.models = models+ package.config = config+ for name, module in (+ ("data_designer", package),+ ("data_designer.config", config),+ ("data_designer.config.mcp", mcp),+ ("data_designer.config.models", models),+ ):+ monkeypatch.setitem(sys.modules, name, module)+++def _recipe(endpoint: str) -> dict:+ return {+ "mcp_providers": [+ {"provider_type": "streamable_http", "name": "local", "endpoint": endpoint}+ ]+ }++[email protected]("endpoint", _PRIVATE_ENDPOINTS)+def test_managed_recipe_mcp_is_refused_where_chat_mcp_refuses(endpoint):+ from core.data_recipe.service import build_mcp_providers++ with pytest.raises(HTTPException) as chat:+ run_as(ALICE, mcp_client.validate_mcp_address, endpoint)+ assert chat.value.status_code == 400+ with pytest.raises(HTTPException) as recipe:+ run_as(ALICE, build_mcp_providers, _recipe(endpoint))+ assert recipe.value.status_code == 403+++def test_owner_recipe_mcp_is_unchanged():+ from core.data_recipe.service import build_mcp_providers+ built = run_as(OWNER, build_mcp_providers, _recipe(_PRIVATE_ENDPOINTS[0]))+ assert [provider.endpoint for provider in built] == [_PRIVATE_ENDPOINTS[0]]+++def test_single_account_installs_keep_recipe_mcp(monkeypatch):+ from core.data_recipe.service import build_mcp_providers++ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ built = run_as(OWNER, build_mcp_providers, _recipe(_PRIVATE_ENDPOINTS[0]))+ assert [provider.endpoint for provider in built] == [_PRIVATE_ENDPOINTS[0]]+ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, build_mcp_providers, _recipe(_PRIVATE_ENDPOINTS[0]))+ assert refused.value.status_code == 403+++def test_managed_recipe_stdio_provider_is_still_dropped(monkeypatch):+ """The network refusal must not turn the host gate's silent drop of a local command into an error."""+ from core.data_recipe.service import build_mcp_providers++ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")+ recipe = {+ "mcp_providers": [+ {"provider_type": "stdio", "name": "fs", "command": "npx", "args": [], "env": {}}+ ]+ }+ assert run_as(ALICE, build_mcp_providers, recipe) == []+++def _provider_recipe(endpoint: str) -> dict:+ return {"model_providers": [{"name": "llm", "endpoint": endpoint, "api_key": "k"}]}+++ "endpoint",+ (+ *(e.replace("http://", "https://") for e in _PRIVATE_ENDPOINTS),+ "https://169.254.169.254/latest",+ "https://[::1]:11434/v1",+ ),+)+def test_managed_recipe_model_provider_must_be_public(endpoint):+ """The engine dials providers itself, so a managed recipe cannot point one at loopback or the LAN."""+ from core.data_recipe.service import build_model_providers++ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, build_model_providers, _provider_recipe(endpoint))+ assert refused.value.status_code == 403+ assert "public" in refused.value.detail+++def test_managed_recipe_model_provider_on_a_public_https_address_is_kept():+ from core.data_recipe.service import build_model_providers+ built = run_as(ALICE, build_model_providers, _provider_recipe("https://8.8.8.8/v1"))+ assert [provider.endpoint for provider in built] == ["https://8.8.8.8/v1"]+++def test_managed_recipe_model_provider_over_plain_http_is_refused():+ """The engine re-resolves the name when it connects, so only TLS pins the peer; plain HTTP is refused."""+ from core.data_recipe.service import build_model_providers++ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, build_model_providers, _provider_recipe("http://8.8.8.8/v1"))+ assert refused.value.status_code == 403+ assert "HTTPS" in refused.value.detail+++def test_owner_recipe_model_provider_endpoints_are_unchanged():+ from core.data_recipe.service import build_model_providers+ built = run_as(OWNER, build_model_providers, _provider_recipe(_PRIVATE_ENDPOINTS[0]))+ assert [provider.endpoint for provider in built] == [_PRIVATE_ENDPOINTS[0]]+++def test_managed_recipe_worker_refuses_names_that_resolve_privately(monkeypatch):+ """The endpoint check resolves once; the worker's resolver refuses a later private answer."""+ import socket++ from core.data_recipe.service import install_public_egress_guard++ answers = {"public.example": "8.8.8.8", "rebind.example": "127.0.0.1"}++ def fake(host, port, *args, **kwargs):+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (answers[host], port or 0))]++ monkeypatch.setattr(socket, "getaddrinfo", fake)+ monkeypatch.setattr(socket, "gethostbyname", socket.gethostbyname)+ run_as(OWNER, install_public_egress_guard)+ assert socket.getaddrinfo is fake+ run_as(ALICE, install_public_egress_guard)+ assert socket.getaddrinfo("public.example", 443)[0][4][0] == "8.8.8.8"+ with pytest.raises(socket.gaierror):+ socket.getaddrinfo("rebind.example", 443)+ with pytest.raises(socket.gaierror):+ socket.gethostbyname("rebind.example")diff --git a/studio/backend/tests/test_account_retired_workspace_recreated.py b/studio/backend/tests/test_account_retired_workspace_recreated.pynew file mode 100644index 00000000000..9e373a0a1d9--- /dev/null+++ b/studio/backend/tests/test_account_retired_workspace_recreated.py@@ -0,0 +1,59 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A raw mkdir that outlives deletion must not un-fence the retired account."""++import pytest++from storage import studio_db+from utils.account_context import OWNER, AccountContext, run_as+from utils.paths import storage_roots as roots++ALICE = AccountContext("11111111111111111111111111111111", "alice")++[email protected](autouse = True)+def fresh_retirement_tombstones(monkeypatch):+ from core.training import account_jobs+ monkeypatch.setattr(account_jobs, "_retired", set())+++def account_home(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "Documents"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ studio_db.close_wal_keeper()+ studio_db.reset_schema_state_for_tests()+ yield+ studio_db.close_wal_keeper()+ studio_db.reset_schema_state_for_tests()+++def test_a_raw_mkdir_after_deletion_does_not_unfence_the_account(account_home, monkeypatch):+ """``import-example``'s failure recovery calls ``folder.mkdir(parents = True)`` directly, so a+ request that outlives DELETE puts the workspace back. Every later guarded creation must still+ refuse: the tombstone, not the directory's existence, says the account is gone."""+ from routes.accounts import retire_account_roots++ monkeypatch.setattr("core.inference.mcp_client.close_mcp_sessions", lambda: None)+ monkeypatch.setattr("core.inference.mcp_client.invalidate_tool_cache", lambda: None)+ root = run_as(ALICE, roots.workspace_root)+ run_as(ALICE, studio_db.get_connection).close()+ retire_account_roots(ALICE)+ assert not root.exists()++ # routes/training.py restore_folded(), verbatim, on a folder under the retired workspace.+ folder = run_as(ALICE, lambda: roots.datasets_root() / "tuxemon")+ folder.mkdir(parents = True, exist_ok = True)+ assert root.exists()++ studio_db.reset_schema_state_for_tests()+ with pytest.raises(roots.RetiredAccountError):+ run_as(ALICE, lambda: roots.ensure_dir(roots.outputs_root()))+ with pytest.raises(roots.RetiredAccountError):+ run_as(ALICE, studio_db.get_connection).close()+ assert not (root / "studio.db").exists()++ # Single-user / owner installs are untouched: the owner is never retired.+ assert run_as(OWNER, lambda: roots.ensure_dir(roots.outputs_root())).is_dir()diff --git a/studio/backend/tests/test_account_retirement_restore_report.py b/studio/backend/tests/test_account_retirement_restore_report.pynew file mode 100644index 00000000000..37e09320e69--- /dev/null+++ b/studio/backend/tests/test_account_retirement_restore_report.py@@ -0,0 +1,47 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A retirement rollback that cannot rename a root back says so and keeps the root listed,+instead of reporting a clean rollback with the data stranded under its deleted name."""++import os++from auth import storage+from studio.backend.tests.test_account_lifecycle import auth_env, headers, matrix # noqa: F401+from utils.account_context import run_as+from utils.paths import storage_roots+++def test_a_failed_restore_is_reported_with_the_stranded_path(matrix, monkeypatch):+ client, _, accounts = matrix+ account = storage.get_account("alice")+ roots = [+ run_as(account, root)+ for root in (+ storage_roots.workspace_root,+ storage_roots.project_workspaces_root,+ storage_roots.tmp_root,+ )+ ]+ for root in roots:+ root.mkdir(parents = True, exist_ok = True)+ (root / "private.txt").write_text("keep")+ calls = []++ class RenameFailsLateAndOnce(type(roots[0])):+ @staticmethod+ def rename(source, destination):+ calls.append((str(source), str(destination)))+ # The last move aside fails, then the first rename back fails as well.+ if len(calls) in (3, 4):+ raise PermissionError("locked directory")+ os.rename(source, destination)++ monkeypatch.setattr(accounts, "Path", RenameFailsLateAndOnce)+ response = client.delete(f"/api/accounts/{account.account_id}", headers = headers())+ print(f"delete: {response.status_code} {response.text}")+ assert response.status_code == 409+ stranded = [p for root in roots for p in root.parent.iterdir() if "-deleted-" in p.name]+ assert len(stranded) == 1, stranded+ assert str(stranded[0]) in response.text+ assert storage.get_user_record("alice")["is_active"] == 0diff --git a/studio/backend/tests/test_account_sandbox_retirement.py b/studio/backend/tests/test_account_sandbox_retirement.pynew file mode 100644index 00000000000..29694973ec2--- /dev/null+++ b/studio/backend/tests/test_account_sandbox_retirement.py@@ -0,0 +1,66 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An overridden sandbox home is a private root: retirement renames it aside too."""++from pathlib import Path++import pytest++from auth import storage+from utils.account_context import run_as+from utils.paths import storage_roots++from .test_account_lifecycle import auth_env, matrix # noqa: F401+++def sandbox_home(tmp_path, monkeypatch, matrix): # noqa: F811+ """UNSLOTH_STUDIO_SANDBOX_HOME puts the account sandbox outside workspace_root()."""+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sandboxes"))+ return matrix+++def _make_private_roots(account):+ for root in (+ storage_roots.workspace_root,+ storage_roots.project_workspaces_root,+ storage_roots.tmp_root,+ ):+ run_as(account, root).mkdir(parents = True, exist_ok = True)+++def test_delete_retires_an_overridden_sandbox_root(sandbox_home):+ _, _, accounts = sandbox_home+ from core.inference import tools++ alice = storage.get_account("alice")+ sandbox = Path(run_as(alice, tools.sandbox_root))+ assert sandbox not in run_as(alice, storage_roots.workspace_root).parents+ sandbox.mkdir(parents = True, exist_ok = True)+ (sandbox / "tool-output.txt").write_text("alice")+ _make_private_roots(alice)++ storage.delete_account(alice.account_id, accounts.retire_account_roots)++ assert not sandbox.exists()+ retired = list(sandbox.parent.glob(sandbox.name + "-deleted-*"))+ assert len(retired) == 1+ assert (retired[0] / "tool-output.txt").read_text() == "alice"+++def test_the_retirement_fence_covers_an_overridden_sandbox_root(sandbox_home):+ """A finalizer outliving the delete must not recreate the sandbox either."""+ _, _, accounts = sandbox_home+ from core.inference import tools++ alice = storage.get_account("alice")+ sandbox = Path(run_as(alice, tools.sandbox_root))+ sandbox.mkdir(parents = True, exist_ok = True)+ _make_private_roots(alice)+ storage.delete_account(alice.account_id, accounts.retire_account_roots)++ assert run_as(alice, storage_roots._under_managed_workspace, sandbox) is True+ with pytest.raises(storage_roots.RetiredAccountError):+ run_as(alice, storage_roots.ensure_dir, sandbox / "late")+ assert not sandbox.exists()diff --git a/studio/backend/tests/test_account_shared_load_settings.py b/studio/backend/tests/test_account_shared_load_settings.pynew file mode 100644index 00000000000..01523d39617--- /dev/null+++ b/studio/backend/tests/test_account_shared_load_settings.py@@ -0,0 +1,85 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Install-wide load policy is the owner's, so a managed account's load obeys it too; an account-keyed read would silently fall back to defaults."""++from __future__ import annotations++import pytest++from auth import policy+from utils import (+ hf_cache_settings,+ llama_cpp_path_settings,+ model_memory_settings,+ openai_auto_switch_settings,+ preview_sharing_settings,+ upload_limits,+ vram_budget_settings,+)+from utils.account_context import OWNER, AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")++[email protected](autouse = True)+def studio_home(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {})+ for module in (model_memory_settings, vram_budget_settings, openai_auto_switch_settings):+ monkeypatch.setattr(module, "_cache", {})+ if hasattr(module, "_generation"):+ monkeypatch.setattr(module, "_generation", {})+ yield+++def test_a_managed_load_reads_the_owners_model_memory_policy():+ run_as(OWNER, model_memory_settings.set_model_memory_settings, True, False)+ assert run_as(ALICE, model_memory_settings.get_model_memory_settings) == (True, False)+ assert run_as(ALICE, model_memory_settings.should_mlock) is True+++def test_a_managed_load_reads_the_owners_vram_budget():+ run_as(OWNER, vram_budget_settings.set_vram_budget_fraction, 0.85)+ assert run_as(ALICE, vram_budget_settings.get_vram_budget_fraction) == pytest.approx(0.85)+++def test_a_managed_request_reads_the_owners_auto_switch_policy():+ run_as(OWNER, openai_auto_switch_settings.set_openai_auto_switch, True, None)+ assert run_as(ALICE, openai_auto_switch_settings.get_openai_auto_switch_enabled) is True+++def test_a_managed_upload_reads_the_owners_upload_limit():+ run_as(OWNER, upload_limits.set_upload_limit_mb, 2048)+ assert run_as(ALICE, upload_limits.get_upload_limit_mb) == 2048+ assert run_as(ALICE, upload_limits.get_upload_limit_bytes) == 2048 * 1024 * 1024+++def test_a_managed_request_reads_the_owners_preview_sharing_switch():+ run_as(OWNER, preview_sharing_settings.set_preview_sharing_enabled, False)+ assert run_as(ALICE, preview_sharing_settings.get_preview_sharing_enabled) is False+++def test_a_managed_load_reads_the_owners_llama_cpp_path(tmp_path, monkeypatch):+ binary = tmp_path / "llama" / llama_cpp_path_settings.llama_server_binary_name()+ binary.parent.mkdir(parents = True, exist_ok = True)+ binary.write_text("")+ binary.chmod(0o755)+ monkeypatch.delenv("LLAMA_SERVER_PATH", raising = False)+ monkeypatch.delenv("UNSLOTH_LLAMA_CPP_PATH", raising = False)+ run_as(OWNER, llama_cpp_path_settings.set_custom_llama_cpp_path, str(binary.parent))+ assert run_as(ALICE, llama_cpp_path_settings.get_stored_custom_llama_cpp_path) is not None+ assert run_as(ALICE, llama_cpp_path_settings.custom_llama_cpp_path_source) == "studio"+++def test_a_managed_scan_keys_on_the_owners_cache_home(tmp_path):+ custom = tmp_path / "external" / "huggingface"+ custom.parent.mkdir(parents = True, exist_ok = True)+ run_as(OWNER, hf_cache_settings.set_hf_cache_home, str(custom))+ # The key separates in-flight scans per cache volume, so it must name the home actually scanned.+ assert run_as(ALICE, hf_cache_settings.get_hf_cache_paths).cache_home == custom+ assert run_as(ALICE, hf_cache_settings.configured_cache_key) == run_as(+ OWNER, hf_cache_settings.configured_cache_key+ )+ assert run_as(ALICE, hf_cache_settings.configured_cache_key) == "studio:" + str(custom)diff --git a/studio/backend/tests/test_account_signed_links.py b/studio/backend/tests/test_account_signed_links.pynew file mode 100644index 00000000000..bb1fbac47ad--- /dev/null+++ b/studio/backend/tests/test_account_signed_links.py@@ -0,0 +1,106 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Signed links carry their own account, and die with it: with no auth dependency to bind one, each route resolves the account from the signed target and re-checks that it still exists."""++import secrets+from pathlib import Path++import pytest+from fastapi import HTTPException+from PIL import Image++from auth import policy, storage+from core.inference import image_gallery, video_gallery+from core.rag import store+from hub.services.models import account_access as access+from routes import rag as rag_routes+from storage import rag_db+from utils.account_context import OWNER, run_as+from utils.paths import ensure_dir, rag_uploads_root++ALICE_NAME = "alice"+++def accounts(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ rag_db.reset_schema_state_for_tests()+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ alice = storage.issue_account_setup_code(username = ALICE_NAME)["account"]+ yield storage.get_account(ALICE_NAME), alice["account_id"]+ policy.invalidate_account_cache()+++def _seed_document(account, document_id: str, text: bytes) -> None:+ def write():+ path = ensure_dir(rag_uploads_root()) / f"{document_id}.txt"+ path.write_bytes(text)+ conn = rag_db.get_connection()+ try:+ store.create_document(+ conn,+ scope = "kb:none",+ filename = f"{document_id}.txt",+ sha256 = document_id,+ status = "ready",+ stored_path = str(path),+ document_id = document_id,+ )+ finally:+ conn.close()++ run_as(account, write)+++def test_a_signed_rag_link_serves_its_own_accounts_document(accounts):+ alice, _account_id = accounts+ _seed_document(OWNER, "shared-id", b"owner secret")+ _seed_document(alice, "shared-id", b"alice secret")++ token = run_as(alice, rag_routes._sign_document, "shared-id")+ response = rag_routes.document_file_signed("shared-id", token = token)+ assert Path(response.path).read_bytes() == b"alice secret"++ owner_token = rag_routes._sign_document("shared-id")+ owner_response = rag_routes.document_file_signed("shared-id", token = owner_token)+ assert Path(owner_response.path).read_bytes() == b"owner secret"+++def test_a_signed_rag_link_dies_with_its_account(accounts):+ alice, account_id = accounts+ _seed_document(alice, "doc-1", b"alice secret")+ token = run_as(alice, rag_routes._sign_document, "doc-1")+ served = rag_routes.document_file_signed("doc-1", token = token)+ assert Path(served.path).read_bytes() == b"alice secret"++ storage.set_account_active(account_id, False)+ with pytest.raises(HTTPException) as refused:+ rag_routes.document_file_signed("doc-1", token = token)+ assert refused.value.status_code == 401+++def test_a_signed_media_link_dies_with_its_account(accounts):+ alice, account_id = accounts+ meta = {"prompt": "p", "model": "m", "created_at": 100.0, "width": 8, "height": 8}+ image_id = run_as(alice, image_gallery.save, Image.new("RGB", (8, 8)), meta)["id"]+ video_id = run_as(+ alice,+ video_gallery.save,+ b"\x00\x00\x00\x18ftypmp42",+ {**meta, "num_frames": 1, "fps": 1, "duration_s": 1.0},+ )["id"]++ for media_id in (image_id, video_id):+ target = run_as(alice, access.media_link_target, media_id)+ assert access.media_link_account(target, media_id).account_id == account_id++ storage.set_account_active(account_id, False)+ for media_id in (image_id, video_id):+ target = f"{account_id}:{media_id}"+ assert access.media_link_account(target, media_id) is None+ assert access.media_link_account(image_id, image_id) is OWNERdiff --git a/studio/backend/tests/test_account_storage.py b/studio/backend/tests/test_account_storage.pynew file mode 100644index 00000000000..aecd8412a34--- /dev/null+++ b/studio/backend/tests/test_account_storage.py@@ -0,0 +1,563 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise owner and managed storage in the same interpreter."""++import importlib+import os+import sqlite3+import threading+from pathlib import Path++import pytest++from storage import api_usage_db, profile_stats_db, studio_db+from utils.account_context import OWNER, AccountContext, account_thread, current_account_id, run_as+from utils.paths import storage_roots as roots+from utils.paths.lazy import LazyPath++ALICE = AccountContext("11111111111111111111111111111111", "alice")+BOB = AccountContext("22222222222222222222222222222222", "bob")+ACCOUNTS = (OWNER, ALICE, BOB)++[email protected](autouse = True)+def fresh_retirement_tombstones(monkeypatch):+ # Tombstones are process-global; one test retiring ALICE would fence the later ones.+ from core.training import account_jobs+ monkeypatch.setattr(account_jobs, "_retired", set())+++def account_home(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "Documents"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ studio_db.close_wal_keeper()+ profile_stats_db._cache.clear()+ memos = []+ for name in (+ "model_memory_settings",+ "vram_budget_settings",+ "openai_auto_switch_settings",+ "embedding_model_settings",+ ):+ module = importlib.import_module(f"utils.{name}")+ for attribute in ("_cache", "_cached", "_generation", "_resolved_gguf_memo"):+ memo = getattr(module, attribute, None)+ if isinstance(memo, dict):+ memo.clear()+ memos.append(memo)+ yield tmp_path+ for memo in memos:+ memo.clear()+ studio_db.close_wal_keeper()+ profile_stats_db._cache.clear()+++ "module_name,table",+ [+ ("studio_db", "app_settings"),+ ("rag_db", "documents"),+ ("providers_db", "llm_providers"),+ ("mcp_servers_db", "mcp_servers"),+ ("credential_secrets", "credential_secrets"),+ ("chat_generation_runs_db", "chat_generation_runs"),+ ],+)+def test_each_database_gets_its_schema(account_home, module_name, table):+ module = importlib.import_module(f"storage.{module_name}")+ module.reset_schema_state_for_tests()+ connect = module._connect if module_name == "chat_generation_runs_db" else module.get_connection+ for account in ACCOUNTS:+ conn = run_as(account, connect)+ try:+ assert conn.execute(f"SELECT count(*) FROM {table}").fetchone()[0] == 0+ if module_name == "chat_generation_runs_db":+ conn.execute("SELECT progress_at, progress_tokens FROM chat_generation_runs")+ conn.execute("CREATE TABLE account_probe (account_id TEXT)")+ conn.execute("INSERT INTO account_probe VALUES (?)", (account.account_id,))+ conn.commit()+ finally:+ conn.close()+ for account in ACCOUNTS:+ conn = run_as(account, connect)+ try:+ assert (+ conn.execute("SELECT account_id FROM account_probe").fetchall()[0][0]+ == account.account_id+ )+ finally:+ conn.close()+ assert len(module._schema_ready) == 3+ assert all(path.is_absolute() for path in module._schema_ready)+ module.reset_schema_state_for_tests()+ assert module._schema_ready == set()+++def test_wal_keepers_can_close_one_account(account_home):+ for account in ACCOUNTS:+ assert run_as(account, studio_db.open_wal_keeper)+ paths = {account: run_as(account, roots.studio_db_path) for account in ACCOUNTS}+ alice = studio_db._wal_keepers[paths[ALICE]]+ studio_db.close_wal_keeper_for(paths[ALICE])+ with pytest.raises(sqlite3.ProgrammingError, match = "closed"):+ alice.execute("SELECT 1")+ for account in (OWNER, BOB):+ assert studio_db._wal_keepers[paths[account]].execute("SELECT 1").fetchone()[0] == 1+ studio_db.close_wal_keeper()+ assert studio_db._wal_keepers == {}+++def test_a_managed_database_keeps_its_wal_across_a_connection_close(account_home):+ studio_db.reset_schema_state_for_tests()+ alice_db = run_as(ALICE, roots.studio_db_path)+ owner_db = run_as(OWNER, roots.studio_db_path)+ for account, db_path in ((OWNER, owner_db), (ALICE, alice_db)):+ conn = run_as(account, studio_db.get_connection)+ try:+ conn.execute(+ "INSERT OR REPLACE INTO app_settings (key, value_json, updated_at)"+ " VALUES ('probe', '1', 'now')"+ )+ conn.commit()+ finally:+ conn.close()+ # The owner's keeper is a lifespan concern (main.py); only the managed one opens on demand.+ assert owner_db not in studio_db._wal_keepers+ assert not owner_db.with_name("studio.db-wal").exists()+ assert alice_db in studio_db._wal_keepers+ assert alice_db.with_name("studio.db-wal").exists()+++def test_retiring_an_account_releases_its_wal_keeper(account_home):+ from routes.accounts import retire_account_roots++ studio_db.reset_schema_state_for_tests()+ alice_db = run_as(ALICE, roots.studio_db_path)+ run_as(ALICE, studio_db.get_connection).close()+ keeper = studio_db._wal_keepers[alice_db]+ retire_account_roots(ALICE)+ assert alice_db not in studio_db._wal_keepers+ with pytest.raises(sqlite3.ProgrammingError, match = "closed"):+ keeper.execute("SELECT 1")+++def _receipt() -> api_usage_db.ApiUsageReceipt:+ return api_usage_db.ApiUsageReceipt(+ id = "same-receipt",+ subject = "same-subject",+ endpoint = "/v1/chat/completions",+ model = "model",+ status = "completed",+ prompt_tokens = 2,+ completion_tokens = 3,+ total_tokens = 5,+ created_at = 1,+ )+++def test_usage_writer_retains_account_through_retries(account_home, monkeypatch):+ seen = []+ retried = False++ def sink(receipt):+ nonlocal retried+ seen.append(current_account_id())+ if current_account_id() == ALICE.account_id and not retried:+ retried = True+ raise sqlite3.OperationalError("database is locked")+ return api_usage_db.record_api_usage(receipt)++ monkeypatch.setattr(api_usage_db, "_sleep_after_busy", lambda delay: None)+ writer = api_usage_db.ApiUsageWriter(sink = sink)+ try:+ for account in ACCOUNTS:+ assert run_as(account, writer.submit, _receipt())+ finally:+ assert writer.stop(timeout = 10)+ assert seen == [OWNER.account_id, ALICE.account_id, ALICE.account_id, BOB.account_id]+ for account in ACCOUNTS:+ conn = run_as(account, studio_db.get_connection)+ try:+ assert conn.execute("SELECT sum(total_tokens) FROM api_usage_events").fetchone()[0] == 5+ finally:+ conn.close()+++def test_a_durable_run_poll_resolves_the_account_root_once(account_home, monkeypatch):+ from storage import chat_generation_runs_db as runs_db++ runs_db.reset_schema_state_for_tests()+ run_as(ALICE, runs_db._connect).close()+ resolutions = []+ monkeypatch.setattr(+ runs_db, "studio_db_path", lambda: resolutions.append(1) or roots.studio_db_path()+ )+ run_as(ALICE, runs_db._connect).close()+ assert resolutions == []+++def test_profile_cache_and_invalidation_are_private(account_home):+ # Empty databases have identical fingerprints; one account's cached object must not be served to another.+ values = {+ account: run_as(account, profile_stats_db.compute_profile_stats) for account in ACCOUNTS+ }+ assert values[OWNER] is not values[ALICE]+ assert values[ALICE] is not values[BOB]+ for account in ACCOUNTS:+ assert run_as(account, profile_stats_db.compute_profile_stats) is values[account]+ run_as(ALICE, profile_stats_db.invalidate_profile_stats_cache)+ assert run_as(OWNER, profile_stats_db.compute_profile_stats) is values[OWNER]+ assert run_as(BOB, profile_stats_db.compute_profile_stats) is values[BOB]+ assert run_as(ALICE, profile_stats_db.compute_profile_stats) is not values[ALICE]+++ "module_name,setter,getter,first,second",+ [+ (+ "embedding_model_settings",+ "set_rag_embedding_model",+ "get_stored_embedding_model",+ ("org/one",),+ ("org/two",),+ ),+ ],+)+def test_settings_memos_follow_accounts(+ account_home, monkeypatch, module_name, setter, getter, first, second+):+ module = importlib.import_module(f"utils.{module_name}")+ monkeypatch.setattr(module, "_CACHE_TTL_S", 3600)+ for account, args in ((OWNER, first), (ALICE, second), (BOB, first)):+ run_as(account, getattr(module, setter), *args)+ assert run_as(account, getattr(module, getter)) == args[0]+ for account, expected in ((OWNER, first[0]), (ALICE, second[0]), (BOB, first[0])):+ assert run_as(account, getattr(module, getter)) == expected+ run_as(ALICE, getattr(module, setter), *first)+ assert run_as(OWNER, getattr(module, getter)) == first[0]+++def test_embedding_resolution_memo_is_private(account_home):+ from utils import embedding_model_settings as settings++ settings._resolved_gguf_memo.clear()+ for account, repo in ((OWNER, "org/owner-GGUF"), (ALICE, "org/alice-GGUF")):+ run_as(account, settings.set_rag_embedding_model, "org/embed", gguf_repo = repo)+ assert run_as(account, settings.get_stored_gguf_repo, "org/embed") == repo+ run_as(account, settings.set_rag_embedding_model, "org/other")+ assert run_as(OWNER, settings.remembered_gguf_repo, "org/embed") == "org/owner-GGUF"+ assert run_as(ALICE, settings.remembered_gguf_repo, "org/embed") == "org/alice-GGUF"+ assert run_as(BOB, settings.remembered_gguf_repo, "org/embed") is None+ settings._resolved_gguf_memo.clear()+++def test_hf_validation_cache_and_budget_are_private(monkeypatch):+ from utils import hf_token_validation as validation++ validation.reset_hf_token_validation_state()+ calls = []+ monkeypatch.setattr(+ validation,+ "_check_remote",+ lambda token: (+ calls.append(current_account_id()) or validation.TokenValidationResult(status = "valid")+ ),+ )+ monkeypatch.setattr(validation, "_MAX_ATTEMPTS", 1)+ try:+ for account in ACCOUNTS:+ assert (+ run_as(+ account, validation.validate_hf_token, "same-token", rate_key = "same-client"+ ).status+ == "valid"+ )+ assert (+ run_as(+ account, validation.validate_hf_token, "same-token", rate_key = "same-client"+ ).status+ == "valid"+ )+ assert (+ run_as(+ account, validation.validate_hf_token, "another-token", rate_key = "same-client"+ ).status+ == "rate_limited"+ )+ assert calls == [account.account_id for account in ACCOUNTS]+ finally:+ validation.reset_hf_token_validation_state()+++def test_hub_reexports_the_canonical_owner_and_account_roots(account_home):+ from hub.utils import paths as hub+ expected = {+ "studio_root": account_home,+ "cache_root": account_home / "cache",+ "assets_root": account_home / "assets",+ "datasets_root": account_home / "assets/datasets",+ "dataset_uploads_root": account_home / "assets/datasets/uploads",+ "recipe_datasets_root": account_home / "assets/datasets/recipes",+ "outputs_root": account_home / "outputs",+ "exports_root": account_home / "exports",+ "tmp_root": roots.tmp_root(),+ }+ for name, owner_path in expected.items():+ assert getattr(hub, name) is getattr(roots, name)+ assert getattr(hub, name)() == owner_path+ assert run_as(ALICE, getattr(hub, name)) == run_as(ALICE, getattr(roots, name))+++def test_lazy_paths_keep_imported_references_live(account_home):+ path = LazyPath(roots.outputs_root)+ for account in ACCOUNTS:+ expected = run_as(account, roots.outputs_root)+ assert run_as(account, path) == expected+ assert run_as(account, os.fspath, path) == str(expected)+ assert run_as(account, str, path) == str(expected)+ assert run_as(account, lambda: path / "child") == expected / "child"+ assert run_as(account, lambda: path == expected)+ assert run_as(account, lambda: path.parent) == expected.parent+ assert not (account_home / "outputs").exists()+++ "filename,names",+ [+ (+ "hub/services/datasets/local.py",+ {+ "LOCAL_DATASETS_ROOT": roots.recipe_datasets_root,+ "DATASET_UPLOAD_DIR": roots.dataset_uploads_root,+ },+ ),+ ("core/data_recipe/jobs/worker.py", {"_ARTIFACT_ROOT": roots.recipe_datasets_root}),+ (+ "routes/data_recipe/seed.py",+ {+ "SEED_UPLOAD_DIR": roots.seed_uploads_root,+ "UNSTRUCTURED_UPLOAD_ROOT": roots.unstructured_uploads_root,+ },+ ),+ (+ "plugins/data-designer-unstructured-seed/src/data_designer_unstructured_seed/chunking.py",+ {"_CACHE_DIR": roots.unstructured_seed_cache_root},+ ),+ ],+)+def test_legacy_root_names_resolve_at_use(account_home, filename, names):+ import ast++ source = Path(__file__).resolve().parents[1] / filename+ tree = ast.parse(source.read_text(encoding = "utf-8"))+ assignments = [+ node+ for node in tree.body+ if isinstance(node, ast.Assign)+ and any(isinstance(target, ast.Name) and target.id in names for target in node.targets)+ ]+ namespace = {"LazyPath": LazyPath, **{fn.__name__: fn for fn in names.values()}}+ exec(compile(ast.Module(body = assignments, type_ignores = []), str(source), "exec"), namespace)+ for name, root in names.items():+ accessor = namespace[name]+ for account in ACCOUNTS:+ assert run_as(account, Path, accessor) == run_as(account, root)+++def test_checkpoint_defaults_resolve_in_the_calling_account(account_home, monkeypatch):+ from utils.models import checkpoints++ seen = []+ monkeypatch.setattr(checkpoints, "scan_checkpoints", lambda path: seen.append(path) or [])+ for account in ACCOUNTS:+ assert run_as(account, checkpoints.list_preview_targets) == []+ assert seen == [str(run_as(account, roots.outputs_root)) for account in ACCOUNTS]+++def test_owner_setting_cache_hits_do_not_query_storage(account_home, monkeypatch):+ from utils import (+ embedding_model_settings,+ model_memory_settings,+ openai_auto_switch_settings,+ vram_budget_settings,+ )++ getters = (+ model_memory_settings.get_keep_resident,+ vram_budget_settings.get_vram_budget_fraction,+ openai_auto_switch_settings.get_openai_auto_switch_enabled,+ embedding_model_settings.get_stored_embedding_model,+ )+ expected = [get() for get in getters]++ def unexpected(*args, **kwargs):+ pytest.fail("A hot owner setting lookup queried storage")++ monkeypatch.setattr(studio_db, "get_app_setting", unexpected)+ monkeypatch.setattr(studio_db, "get_app_settings", unexpected)+ for _ in range(10):+ assert [get() for get in getters] == expected+++def test_hf_inflight_checks_do_not_join_another_account(monkeypatch):+ from utils import hf_token_validation as validation++ validation.reset_hf_token_validation_state()+ entered = threading.Barrier(2)+ results = []++ def remote(token):+ entered.wait(timeout = 5)+ return validation.TokenValidationResult(status = "valid")++ monkeypatch.setattr(validation, "_check_remote", remote)+ monkeypatch.setattr(validation, "_INFLIGHT_WAIT_SECONDS", 0.1)++ def check():+ results.append(validation.validate_hf_token("same-token", rate_key = "same-client").status)++ threads = [account_thread(account = account, target = check) for account in (ALICE, BOB)]+ try:+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout = 6)+ assert results == ["valid", "valid"]+ finally:+ validation.reset_hf_token_validation_state()+++def test_local_dataset_list_uses_the_acting_accounts_uploads(account_home):+ from hub.services.datasets import local+ for account in ACCOUNTS:+ directory = run_as(account, roots.dataset_uploads_root)+ directory.mkdir(parents = True)+ (directory / f"{account.username}.csv").write_text("value\n1\n")+ for account in ACCOUNTS:+ items = run_as(account, local._build_uploaded_dataset_items)+ assert [item.label for item in items] == [f"{account.username}.csv"]+++def test_scan_checkpoints_default_uses_the_acting_account(account_home, monkeypatch):+ from utils.models import checkpoints++ seen = []++ def resolve(path):+ seen.append(path)+ return Path(path)++ monkeypatch.setattr(checkpoints, "resolve_output_dir", resolve)+ for account in ACCOUNTS:+ assert run_as(account, checkpoints.scan_checkpoints) == []+ assert seen == [str(run_as(account, roots.outputs_root)) for account in ACCOUNTS]+++ "module_name",+ [+ "studio_db",+ "rag_db",+ "providers_db",+ "mcp_servers_db",+ "credential_secrets",+ "chat_generation_runs_db",+ ],+)+def test_warm_owner_connections_do_not_resolve_database_again(+ account_home, monkeypatch, module_name+):+ module = importlib.import_module(f"storage.{module_name}")+ connect = module._connect if module_name == "chat_generation_runs_db" else module.get_connection+ path_name = "rag_db_path" if module_name == "rag_db" else "studio_db_path"+ path = getattr(module, path_name)()+ monkeypatch.setattr(module, path_name, lambda: path)+ connect().close()+ original = Path.resolve++ def resolve(candidate, *args, **kwargs):+ assert (+ candidate != path+ ), "Warm owner connections must not repeat database realpath resolution"+ return original(candidate, *args, **kwargs)++ monkeypatch.setattr(Path, "resolve", resolve)+ connect().close()+++def test_a_symlinked_database_resolves_its_path_once(account_home, tmp_path):+ """A relocated studio.db behind a symlink must not re-resolve on every connection."""+ studio_db.reset_schema_state_for_tests()+ db_path = roots.studio_db_path()+ target = tmp_path / "elsewhere" / "studio.db"+ target.parent.mkdir(parents = True)+ db_path.parent.mkdir(parents = True, exist_ok = True)+ db_path.symlink_to(target)+ studio_db.get_connection().close()+ assert db_path in studio_db._schema_ready+ resolves = []+ original = Path.resolve++ def counting(self, *args, **kwargs):+ resolves.append(self)+ return original(self, *args, **kwargs)++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(Path, "resolve", counting)+ studio_db.get_connection().close()+ assert db_path not in resolves+ studio_db.reset_schema_state_for_tests()+++ "module_name,connect_name",+ [+ ("mcp_servers_db", "get_connection"),+ ("providers_db", "get_connection"),+ ("credential_secrets", "get_connection"),+ ("rag_db", "get_metadata_connection"),+ ],+)+def test_no_account_database_recreates_a_retired_workspace(+ account_home, monkeypatch, module_name, connect_name+):+ """A create or update that was in flight when the owner deleted the account must not+ put the renamed-aside workspace back: the row, and the private headers in it, would+ live in a directory no identity owns any more."""+ from routes.accounts import retire_account_roots++ monkeypatch.setattr("core.inference.mcp_client.close_mcp_sessions", lambda: None)+ monkeypatch.setattr("core.inference.mcp_client.invalidate_tool_cache", lambda: None)+ module = importlib.import_module(f"storage.{module_name}")+ module.reset_schema_state_for_tests()+ studio_db.reset_schema_state_for_tests()+ root = run_as(ALICE, roots.workspace_root)+ run_as(ALICE, studio_db.get_connection).close()+ assert root.exists()+ retire_account_roots(ALICE)+ assert not root.exists()++ with pytest.raises(roots.RetiredAccountError):+ run_as(ALICE, getattr(module, connect_name)).close()+ assert not root.exists(), f"storage.{module_name} recreated the retired workspace"+++def test_an_upload_directory_cannot_recreate_a_retired_workspace(account_home, monkeypatch):+ """Same for the plain directory roots: uploads and outputs are created on demand too."""+ from routes.accounts import retire_account_roots++ monkeypatch.setattr("core.inference.mcp_client.close_mcp_sessions", lambda: None)+ monkeypatch.setattr("core.inference.mcp_client.invalidate_tool_cache", lambda: None)+ studio_db.reset_schema_state_for_tests()+ root = run_as(ALICE, roots.workspace_root)+ run_as(ALICE, studio_db.get_connection).close()+ retire_account_roots(ALICE)+ for root_fn in (roots.rag_uploads_root, roots.dataset_uploads_root, roots.outputs_root):+ with pytest.raises(roots.RetiredAccountError):+ run_as(ALICE, lambda: roots.ensure_dir(root_fn()))+ assert not root.exists()+ # The owner's own tree is not account-scoped and keeps creating directories as before.+ assert run_as(OWNER, lambda: roots.ensure_dir(roots.outputs_root())).is_dir()diff --git a/studio/backend/tests/test_account_tool_confinement.py b/studio/backend/tests/test_account_tool_confinement.pynew file mode 100644index 00000000000..1ab1b31045e--- /dev/null+++ b/studio/backend/tests/test_account_tool_confinement.py@@ -0,0 +1,836 @@+# 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 os+import subprocess+import sys+from pathlib import Path++import pytest++from auth import policy, storage+from core.inference import tool_confinement, tools+from utils.account_context import OWNER, AccountContext, run_as+from utils.paths import storage_roots++from .test_account_lifecycle import auth_env, matrix # noqa: F401++ALICE = AccountContext("alice-id", "alice")+BOB = AccountContext("bob-id", "bob")++LANDLOCK = (+ sys.platform == "linux"+ and tool_confinement.landlock_abi() >= tool_confinement._MIN_LANDLOCK_ABI+)++[email protected](autouse = True)+def isolated(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)+ monkeypatch.delenv("UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS", raising = False)+ # The sandbox caps the child at 10000 processes per user; a busy CI host is often already above that.+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_NPROC", "4000000")+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(tools, "_workdirs", {})+ monkeypatch.setattr(tools, "_active_sessions", {})+ monkeypatch.setattr(tools, "_pending_removals", {})+ monkeypatch.setattr(tools, "_removing_sessions", set())+ monkeypatch.setattr(tools, "_legacy_sandbox_migrated", True)+ monkeypatch.setattr(tools, "_start_detached_sweep", lambda: None)+ monkeypatch.setattr(tools, "_legacy_sandbox_root", lambda: str(tmp_path / "legacy"))+++def _seed(tmp_path: Path) -> dict[str, Path]:+ files = {}+ for account in (OWNER, ALICE, BOB):+ workdir = Path(run_as(account, tools._get_workdir, "chat"))+ secret = workdir / f"{account.username}-secret.txt"+ secret.write_text(f"{account.username.upper()}_PRIVATE")+ files[account.username] = secret+ auth_dir = tmp_path / "studio" / "auth"+ auth_dir.mkdir(parents = True, exist_ok = True)+ files["auth"] = auth_dir / "auth.db"+ files["auth"].write_text("OWNER_AUTH_DB")+ return files+++def test_owner_spawns_exactly_as_before():+ assert run_as(OWNER, tools._account_confinement) is None+ kwargs = {"preexec_fn": tools._sandbox_preexec}+ argv = ["bash", "-c", "true"]+ assert tools._apply_confinement(None, kwargs, argv) is argv+ assert kwargs["preexec_fn"] is tools._sandbox_preexec++[email protected](sys.platform == "linux" and LANDLOCK, reason = "host confines with Landlock")[email protected](sys.platform == "darwin", reason = "host confines with sandbox-exec")+def test_managed_account_is_refused_without_a_mechanism(monkeypatch):+ monkeypatch.setattr(tool_confinement, "landlock_abi", lambda: 0)+ with pytest.raises(tool_confinement.ToolConfinementUnavailable):+ run_as(ALICE, tools._account_confinement)+ out = run_as(ALICE, tools._bash_exec, "echo hi", session_id = "chat")+ assert out.startswith("Execution error: Code execution is unavailable for this account")+++def test_owner_opt_out_runs_unconfined_when_no_mechanism(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ with pytest.raises(tool_confinement.ToolConfinementUnavailable):+ run_as(ALICE, tools._account_confinement)+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS", "1")+ confinement = run_as(ALICE, tools._account_confinement)+ assert confinement.mechanism == "unconfined-by-owner"+ assert confinement.preexec is None and confinement.wrap(["x"]) == ["x"]+++def test_macos_profile_hides_install_root_then_allows_own_roots(tmp_path, monkeypatch):+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ run_as(ALICE, tools._get_workdir, "chat")+ confinement = run_as(ALICE, tools._account_confinement)+ assert confinement.mechanism == "sandbox-exec"+ argv = confinement.wrap(["bash", "-c", "true"])+ assert argv[:2] == ["/usr/bin/sandbox-exec", "-p"]+ profile = argv[2]+ studio = str((tmp_path / "studio").resolve())+ alice_root = str((tmp_path / "studio" / "accounts" / "alice-id").resolve())+ assert profile.startswith("(version 1)\n(deny default)")+ deny = profile.index(f'(deny file-read* file-write* (subpath "{studio}"))')+ allow = profile.index(f'(allow file-read* (subpath "{alice_root}"))')+ writable = profile.index(f'(allow file-read* file-write* (subpath "{alice_root}/sandbox"))')+ assert (+ deny < allow < writable+ ), "the account roots must be allowed after the install root is denied"+ assert argv[3:] == ["bash", "-c", "true"]+++def test_macos_profile_keeps_the_interpreter_readable_under_a_hidden_root(tmp_path, monkeypatch):+ """Later rules win: an interpreter prefix inside the install root must be allowed again."""+ venv = tmp_path / "studio" / "unsloth_studio"+ (venv / "lib").mkdir(parents = True)+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ monkeypatch.setattr(tool_confinement, "_interpreter_roots", lambda: [str(venv)])+ run_as(ALICE, tools._get_workdir, "chat")+ profile = run_as(ALICE, tools._account_confinement).wrap(["bash"])[2]++ studio = str((tmp_path / "studio").resolve())+ deny = profile.rindex(f'(deny file-read* file-write* (subpath "{studio}"))')+ allow = profile.rindex(f'(allow file-read* (subpath "{venv}"))')+ assert deny < allow, "the interpreter must be readable after the install root is denied"+ assert f'(allow file-read* (subpath "{studio}"))' not in profile+++def test_macos_profile_hides_other_accounts_temporary_roots(tmp_path, monkeypatch):+ import tempfile as _tempfile++ from utils.paths import storage_roots++ shared_tmp = tmp_path / "tmp"+ shared_tmp.mkdir()+ monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(shared_tmp))+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ run_as(BOB, storage_roots.tmp_root).mkdir(parents = True, exist_ok = True)+ (run_as(BOB, storage_roots.tmp_root) / "dataset.jsonl").write_text("BOB_PRIVATE")++ profile = run_as(ALICE, tools._account_confinement).wrap(["bash"])[2]+ base = str((shared_tmp / "unsloth-studio").resolve())+ alice_tmp = str(run_as(ALICE, storage_roots.tmp_root).resolve())+ bob_tmp = str(run_as(BOB, storage_roots.tmp_root).resolve())++ deny = profile.index(f'(deny file-read* file-write* (subpath "{base}"))')+ allow = profile.index(f'(allow file-read* file-write* (subpath "{alice_tmp}"))')+ # The server's own bare tempfile output sits beside the Studio subtree, outside every account root.+ assert '(allow file-read* (subpath "/var/folders"))' not in profile+ assert '(subpath "/private/var/folders") (subpath "/var/folders"))' in profile+ folders = profile.index('(deny file-read* file-write* (subpath "/private/var/folders")')+ assert folders < allow+ assert deny < allow, "the account's own temporary root must be allowed after the deny"+ assert f'(subpath "{bob_tmp}")' not in profile++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")[email protected]("tool", ["terminal", "python"])+def test_managed_child_cannot_read_or_write_other_accounts(tool, tmp_path):+ files = _seed(tmp_path)+ bob_dir = Path(run_as(BOB, tools._get_workdir, "chat"))+ foreign = {+ "owner": files["unsloth"] if "unsloth" in files else files[OWNER.username],+ "alice": files["alice"],+ "auth": files["auth"],+ }++ def run(command_or_code: str) -> str:+ if tool == "terminal":+ return run_as(BOB, tools._bash_exec, command_or_code, session_id = "chat")+ return run_as(BOB, tools._python_exec, command_or_code, session_id = "chat")++ if tool == "terminal":+ assert "BOB_PRIVATE" in run("cat bob-secret.txt")+ assert "written" in run("echo written > note.txt && cat note.txt")+ else:+ assert "BOB_PRIVATE" in run("print(open('bob-secret.txt').read())")+ assert "written" in run(+ "open('note.txt','w').write('written'); print(open('note.txt').read())"+ )+ assert (bob_dir / "note.txt").read_text().strip() == "written"++ for name, path in foreign.items():+ rel = os.path.relpath(path, bob_dir)+ for target in (rel, str(path)):+ if tool == "terminal":+ out = run(f"cat {target}; echo rc=$?")+ else:+ out = run(+ "try:\n"+ f" print(open({target!r}).read())\n"+ "except OSError as e:\n"+ " print('DENIED', e.__class__.__name__)\n"+ )+ assert "PRIVATE" not in out and "AUTH_DB" not in out, (name, target, out)+ assert "rc=0" not in out+ if tool == "terminal":+ out = run(f"echo BOB_OVERWROTE > {target}; echo rc=$?")+ else:+ out = run(+ "try:\n"+ f" open({target!r}, 'w').write('BOB_OVERWROTE')\n"+ "except OSError as e:\n"+ " print('DENIED', e.__class__.__name__)\n"+ )+ assert "rc=0" not in out+ assert path.read_text() != "BOB_OVERWROTE", (name, path)++ studio = tmp_path / "studio"+ if tool == "terminal":+ out = run(f"ls {studio}; echo rc=$?; ls {studio / 'accounts' / 'alice-id'}; echo rc=$?")+ else:+ out = run(+ "import os\n"+ f"for p in [{str(studio)!r}, {str(studio / 'accounts' / 'alice-id')!r}]:\n"+ " try:\n"+ " print(os.listdir(p))\n"+ " except OSError as e:\n"+ " print('DENIED', e.__class__.__name__)\n"+ )+ assert "rc=0" not in out+ assert "auth" not in out.replace("DENIED", "") or "PermissionError" in out++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_confinement_survives_nested_processes(tmp_path):+ files = _seed(tmp_path)+ alice = files["alice"]+ out = run_as(+ BOB,+ tools._bash_exec,+ f"python -c \"import subprocess; print(subprocess.run(['cat', {str(alice)!r}], "+ 'capture_output=True, text=True).stderr)"',+ session_id = "chat",+ )+ assert "PRIVATE" not in out+ assert "Permission denied" in out or "denied" in out.lower()++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_confined_child_keeps_interpreter_and_system_tools(tmp_path):+ _seed(tmp_path)+ out = run_as(+ BOB,+ tools._python_exec,+ "import json, sqlite3, tempfile, os\n"+ "with tempfile.NamedTemporaryFile('w', delete=False) as f:\n"+ " f.write('x')\n"+ "print(json.dumps({'tmp': os.path.exists(f.name), 'sqlite': sqlite3.sqlite_version != ''}))\n",+ session_id = "chat",+ )+ assert '"tmp": true' in out and '"sqlite": true' in out+ out = run_as(+ BOB, tools._bash_exec, "ls /usr/bin | head -1; python --version", session_id = "chat"+ )+ assert "Python" in out++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_owner_child_remains_unconfined(tmp_path):+ files = _seed(tmp_path)+ out = run_as(OWNER, tools._bash_exec, f"cat {files['alice']}", session_id = "chat")+ assert "ALICE_PRIVATE" in out+++def test_landlock_rules_cover_own_roots_only(tmp_path):+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ run_as(ALICE, tools._get_workdir, "chat")+ rules = run_as(ALICE, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ handled = tool_confinement._handled_mask(3)+ writable = [p for p, access in rules if access == handled & ~tool_confinement._FS_MAKE_SYM]+ alice_root = str((tmp_path / "studio" / "accounts" / "alice-id").resolve())+ assert alice_root not in writable+ assert f"{alice_root}/sandbox" in writable+ assert str((tmp_path / "projects" / "Accounts" / "alice-id" / "Projects").resolve()) in writable+ assert alice_root in [+ p for p, access in rules if access != handled & ~tool_confinement._FS_MAKE_SYM+ ]+ assert str((tmp_path / "studio").resolve()) not in [p for p, _ in rules]+ assert all(+ not p.startswith(str((tmp_path / "studio").resolve()) + os.sep) or p.startswith(alice_root)+ for p, _ in rules+ )+ read_only = [+ p+ for p, access in rules+ if access not in (handled, handled & ~tool_confinement._FS_MAKE_SYM)+ ]+ assert any(+ p.startswith(os.path.realpath(sys.prefix)) or os.path.realpath(sys.prefix).startswith(p)+ for p in read_only+ )++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_managed_child_cannot_plant_a_link_in_its_own_tree(tmp_path):+ """The server follows links for the owner, so a managed child gets no way to make one."""+ files = _seed(tmp_path)+ bob_dir = Path(run_as(BOB, tools._get_workdir, "chat"))+ out = run_as(+ BOB,+ tools._bash_exec,+ f"ln -s {files['alice'].parent} linked; echo rc=$?; mkdir made && echo made > made/f && cat made/f",+ session_id = "chat",+ )+ assert "rc=0" not in out+ assert not (bob_dir / "linked").is_symlink()+ assert "made" in out++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_managed_child_cannot_signal_another_accounts_process(tmp_path):+ """Two accounts' tools run as one Unix user; signals stay inside the child's own domain."""+ _seed(tmp_path)+ alice_job = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])+ try:+ out = run_as(+ BOB,+ tools._python_exec,+ "import os, signal, subprocess\n"+ f"pid = {alice_job.pid}\n"+ "try:\n"+ " os.kill(pid, signal.SIGTERM); print('SIGNALLED')\n"+ "except OSError as e:\n"+ " print('signal denied', e.__class__.__name__)\n"+ "child = subprocess.Popen(['sleep', '30'])\n"+ "child.terminate(); print('own child rc', child.wait())\n",+ session_id = "chat",+ )+ assert "SIGNALLED" not in out and "signal denied" in out, out+ assert "own child rc -15" in out, out+ assert alice_job.poll() is None+ finally:+ alice_job.kill()++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_managed_child_writes_only_its_sandbox_and_projects(tmp_path):+ files = _seed(tmp_path)+ bob_root = Path(run_as(BOB, storage_roots_workspace))+ (bob_root / "studio.db").write_text("BOB-DB")+ (bob_root / "assets").mkdir(exist_ok = True)+ (bob_root / "assets" / "data.jsonl").write_text('{"text": "BOB-DATA"}')+ out = run_as(+ BOB,+ tools._bash_exec,+ f"cat {bob_root}/assets/data.jsonl; echo rc=$?; "+ f"echo TAMPERED > {bob_root}/studio.db; echo write_rc=$?; "+ f"echo x > {bob_root}/assets/new.txt; echo assets_rc=$?; "+ "echo mine > own.txt; echo sandbox_rc=$?",+ session_id = "chat",+ )+ assert "BOB-DATA" in out and "rc=0" in out, out+ assert "write_rc=0" not in out and "assets_rc=0" not in out, out+ assert "sandbox_rc=0" in out, out+ assert (bob_root / "studio.db").read_text() == "BOB-DB"+ assert files["unsloth"].read_text() == "UNSLOTH_PRIVATE"+++def storage_roots_workspace():+ from utils.paths.storage_roots import workspace_root+ return workspace_root()++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_install_under_a_granted_root_stays_hidden(tmp_path, monkeypatch):+ home = Path(sys.prefix) / f"mu-confinement-home-{os.getpid()}"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ try:+ files = _seed(home.parent)+ auth = home / "auth" / "auth.db"+ auth.parent.mkdir(parents = True, exist_ok = True)+ auth.write_text("OWNER_AUTH_DB", encoding = "utf-8")+ out = run_as(+ BOB,+ tools._bash_exec,+ f"cat {auth}; echo rc=$?; ls {home}; echo ls_rc=$?; python -c 'import sys; print(sys.prefix)'",+ session_id = "chat",+ )+ assert "OWNER_AUTH_DB" not in out and "rc=0" not in out and "ls_rc=0" not in out, out+ assert sys.prefix in out, out+ rules = run_as(BOB, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ assert all(not tool_confinement._contains(p, str(home.resolve())) for p, _ in rules)+ finally:+ import shutil+ shutil.rmtree(home, ignore_errors = True)+++def test_sandbox_home_override_is_writable(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "custom-sandboxes"))+ roots = run_as(BOB, tool_confinement._writable_roots)+ assert str((tmp_path / "custom-sandboxes" / "accounts" / "bob-id").resolve()) in roots+++def test_landlock_below_abi_3_is_refused(monkeypatch):+ monkeypatch.setattr(tool_confinement, "landlock_abi", lambda: 2)+ assert tool_confinement._linux_confinement(tools._SANDBOX_SITE_DIR) is None++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_sandbox_home_under_a_granted_root_hides_other_accounts(tmp_path, monkeypatch):+ base = Path(sys.prefix) / f"mu-shared-sandboxes-{os.getpid()}"+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(base))+ try:+ alice_dir = Path(run_as(ALICE, tools._get_workdir, "chat"))+ (alice_dir / "alice-secret.txt").write_text("ALICE_PRIVATE")+ out = run_as(+ BOB,+ tools._bash_exec,+ f"cat {alice_dir}/alice-secret.txt; echo rc=$?; "+ "echo mine > own.txt; cat own.txt; echo own_rc=$?",+ session_id = "chat",+ )+ assert "ALICE_PRIVATE" not in out and "rc=0" not in out.replace("own_rc=0", ""), out+ assert "own_rc=0" in out and "mine" in out, out+ rules = run_as(BOB, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ assert all(not tool_confinement._contains(p, str(alice_dir)) for p, _ in rules)+ finally:+ import shutil+ shutil.rmtree(base, ignore_errors = True)++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_projects_home_under_a_granted_root_hides_other_accounts(tmp_path, monkeypatch):+ from utils.paths.storage_roots import project_workspaces_root++ base = Path(sys.prefix) / f"mu-shared-projects-{os.getpid()}"+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(base))+ try:+ alice_projects = run_as(ALICE, project_workspaces_root)+ alice_projects.mkdir(parents = True, exist_ok = True)+ (alice_projects / "plan.md").write_text("ALICE_PRIVATE")+ bob_projects = run_as(BOB, project_workspaces_root)+ out = run_as(+ BOB,+ tools._bash_exec,+ f"cat {alice_projects}/plan.md; echo rc=$?; "+ f"echo mine > {bob_projects}/own.md; echo own_rc=$?",+ session_id = "chat",+ )+ assert "ALICE_PRIVATE" not in out and "rc=0" not in out.replace("own_rc=0", ""), out+ assert "own_rc=0" in out, out+ assert (bob_projects / "own.md").read_text().strip() == "mine"+ finally:+ import shutil+ shutil.rmtree(base, ignore_errors = True)+++def test_macos_profile_hides_shared_sandbox_and_project_bases(tmp_path, monkeypatch):+ prefix = tmp_path / "prefix"+ sandboxes = prefix / "sandboxes"+ projects = prefix / "projects"+ sandboxes.mkdir(parents = True)+ projects.mkdir(parents = True)+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(sandboxes))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(projects))+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ monkeypatch.setattr(tool_confinement, "_interpreter_roots", lambda: [str(prefix)])+ run_as(ALICE, tools._get_workdir, "chat")++ profile = run_as(BOB, tools._account_confinement).wrap(["bash"])[2]+ bob_sandbox = str(Path(run_as(BOB, tools.sandbox_root)).resolve())+ alice_sandbox = str(Path(run_as(ALICE, tools.sandbox_root)).resolve())+ for base in (sandboxes, projects):+ deny = profile.index(f'(deny file-read* file-write* (subpath "{base.resolve()}"))')+ assert profile.index(f'(allow file-read* (subpath "{prefix.resolve()}"))') < deny+ allow_own = profile.index(f'(allow file-read* file-write* (subpath "{bob_sandbox}"))')+ assert (+ profile.rindex(f'(deny file-read* file-write* (subpath "{sandboxes.resolve()}"))')+ < allow_own+ )+ assert f'(subpath "{alice_sandbox}")' not in profile++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_hf_cache_under_a_granted_root_is_hidden(monkeypatch):+ from utils import hf_cache_settings++ cache = Path(sys.prefix) / f"mu-shared-hf-{os.getpid()}"+ secret = cache / "models--acme--private" / "snapshots" / "x" / "config.json"+ secret.parent.mkdir(parents = True)+ secret.write_text("ACME_PRIVATE", encoding = "utf-8")+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {"HF_HUB_CACHE": str(cache)})+ try:+ run_as(BOB, tools._get_workdir, "chat")+ rules = run_as(BOB, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ assert all(not tool_confinement._contains(p, str(secret)) for p, _ in rules)+ out = run_as(BOB, tools._bash_exec, f"cat {secret}; echo rc=$?", session_id = "chat")+ assert "ACME_PRIVATE" not in out and "rc=0" not in out, out+ finally:+ import shutil+ shutil.rmtree(cache, ignore_errors = True)+++def test_macos_profile_hides_the_hf_cache(tmp_path, monkeypatch):+ from utils import hf_cache_settings++ prefix = tmp_path / "prefix"+ cache = prefix / "hf" / "hub"+ cache.mkdir(parents = True)+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {"HF_HUB_CACHE": str(cache)})+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ monkeypatch.setattr(tool_confinement, "_interpreter_roots", lambda: [str(prefix)])++ profile = run_as(BOB, tools._account_confinement).wrap(["bash"])[2]+ deny = profile.index(f'(deny file-read* file-write* (subpath "{cache.resolve()}"))')+ assert profile.index(f'(allow file-read* (subpath "{prefix.resolve()}"))') < deny+++def test_bases_outside_a_granted_root_leave_the_landlock_rules_unchanged(tmp_path):+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ from utils.paths.storage_roots import studio_root++ run_as(ALICE, tools._get_workdir, "chat")+ rules = run_as(ALICE, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ install_only = tool_confinement._existing((run_as(ALICE, studio_root),))+ original = tool_confinement._protected_roots+ tool_confinement._protected_roots = lambda: install_only+ try:+ baseline = run_as(ALICE, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ finally:+ tool_confinement._protected_roots = original+ assert rules == baseline+++def test_default_layout_denies_exactly_the_previous_macos_roots(tmp_path, monkeypatch):+ import tempfile as _tempfile++ home = tmp_path / "home"+ (home / "Documents").mkdir(parents = True)+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(home / "Documents" / "Unsloth Studio"))+ shared_tmp = tmp_path / "tmp"+ shared_tmp.mkdir()+ monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(shared_tmp))+ from utils import hf_cache_settings++ monkeypatch.delenv("XDG_CACHE_HOME", raising = False)+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {})+ monkeypatch.setattr(hf_cache_settings, "_stored_cache_home", lambda: None)+ monkeypatch.setattr(hf_cache_settings, "_stored_history", lambda: [])+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ profile = run_as(ALICE, tools._account_confinement).wrap(["bash"])[2]+ denied = {+ line.split('"')[1] for line in profile.splitlines() if line.startswith("(deny file-read*")+ }+ assert denied == {+ "/private/var/folders",+ str((tmp_path / "studio").resolve()),+ str((shared_tmp / "unsloth-studio").resolve()),+ str(home.resolve()),+ }++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_link_to_an_ancestor_of_the_install_root_stays_hidden(tmp_path, monkeypatch):+ """A symlink inside a read root pointing at an ancestor of the install root is opened as that ancestor, so it must not become a rule of its own."""+ prefix = Path(os.path.realpath(sys.prefix))+ parent = prefix / f"mu-ancestor-{os.getpid()}"+ home = parent / "unsloth-studio"+ link = prefix / f"mu-root-link-{os.getpid()}"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ try:+ auth = home / "auth" / "auth.db"+ auth.parent.mkdir(parents = True, exist_ok = True)+ auth.write_text("OWNER_AUTH_DB", encoding = "utf-8")+ link.symlink_to(parent, target_is_directory = True)+ out = run_as(+ BOB,+ tools._bash_exec,+ f"cat {link}/unsloth-studio/auth/auth.db; echo rc=$?; "+ "echo mine > own.txt; cat own.txt; echo own_rc=$?",+ session_id = "chat",+ )+ assert "OWNER_AUTH_DB" not in out and "rc=0" not in out.replace("own_rc=0", ""), out+ assert "own_rc=0" in out and "mine" in out, out+ rules = run_as(BOB, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ assert all(not tool_confinement._contains(p, str(link)) for p, _ in rules), rules+ finally:+ import shutil+ link.unlink(missing_ok = True)+ shutil.rmtree(parent, ignore_errors = True)++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_shared_temporary_base_under_a_granted_root_hides_other_accounts(tmp_path, monkeypatch):+ import tempfile as _tempfile++ from utils.paths import storage_roots++ base = Path(os.path.realpath(sys.prefix)) / f"mu-shared-tmp-{os.getpid()}"+ base.mkdir(parents = True, exist_ok = True)+ monkeypatch.setattr(_tempfile, "gettempdir", lambda: str(base))+ try:+ alice_tmp = run_as(ALICE, storage_roots.tmp_root)+ alice_tmp.mkdir(parents = True, exist_ok = True)+ (alice_tmp / "dataset.jsonl").write_text("ALICE_PRIVATE", encoding = "utf-8")+ bob_tmp = run_as(BOB, storage_roots.tmp_root)+ out = run_as(+ BOB,+ tools._bash_exec,+ f"cat {alice_tmp}/dataset.jsonl; echo rc=$?; "+ f"echo mine > {bob_tmp}/own.txt; echo own_rc=$?",+ session_id = "chat",+ )+ assert "ALICE_PRIVATE" not in out and "rc=0" not in out.replace("own_rc=0", ""), out+ assert "own_rc=0" in out, out+ assert (bob_tmp / "own.txt").read_text().strip() == "mine"+ finally:+ import shutil+ shutil.rmtree(base, ignore_errors = True)+++def test_macos_profile_keeps_the_user_cache_dir_readable(tmp_path, monkeypatch):+ """dyld reads its closure cache under the per-user cache dir, so that one subtree is allowed back after the /var/folders deny."""+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(tool_confinement.shutil, "which", lambda name: "/usr/bin/sandbox-exec")+ cache = "/var/folders/ab/cd/C"+ monkeypatch.setattr(+ tool_confinement, "_darwin_user_cache_dirs", lambda: (cache, "/private" + cache)+ )+ profile = run_as(ALICE, tools._account_confinement).wrap(["bash"])[2]+ deny = profile.index('(deny file-read* file-write* (subpath "/private/var/folders")')+ assert deny < profile.index(f'(allow file-read* (subpath "{cache}"))')+ assert deny < profile.index(f'(allow file-read* (subpath "/private{cache}"))')++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_another_accounts_command_text_is_not_on_the_process_list(tmp_path):+ """Landlock cannot deny /proc/<pid>/cmdline, so a confined command runs from a file."""+ import threading++ _seed(tmp_path)+ marker = "ALICE_PROMPT_9f3a"+ alice = {}++ def run_alice():+ alice["out"] = run_as(+ ALICE, tools._bash_exec, f"echo begin; sleep 4; echo {marker}", session_id = "chat"+ )++ thread = threading.Thread(target = run_alice)+ thread.start()+ try:+ snoop = (+ "import os, time\n"+ "hits = []\n"+ "for _ in range(20):\n"+ " for pid in os.listdir('/proc'):\n"+ " if not pid.isdigit():\n"+ " continue\n"+ " try:\n"+ " text = open(os.path.join('/proc', pid, 'cmdline'), 'rb').read()\n"+ " except OSError:\n"+ " continue\n"+ f" if b'{marker}' in text and b'python' not in text:\n"+ " hits.append(text)\n"+ " time.sleep(0.1)\n"+ "print('HITS', len(hits))\n"+ )+ out = run_as(BOB, tools._python_exec, snoop, session_id = "chat")+ finally:+ thread.join()+ assert "HITS 0" in out, out+ assert marker in alice["out"]+ assert not list(Path(run_as(ALICE, tools._get_workdir, "chat")).glob(".studio_cmd_*"))+++def _make_private_roots(account):+ for root in (+ storage_roots.workspace_root,+ storage_roots.project_workspaces_root,+ storage_roots.tmp_root,+ ):+ run_as(account, root).mkdir(parents = True, exist_ok = True)+++def test_a_tool_launch_after_deletion_refuses_instead_of_recreating_the_roots(matrix): # noqa: F811+ """A chat authenticated before the delete must not rematerialize the private roots.++ ``_ensure_dirs`` used to create the workspace, sandbox, temporary and project roots+ with a raw ``Path.mkdir``, so a tool process launched after ``delete_account`` returned+ rebuilt an orphaned account tree and ran in it.+ """+ _, _, accounts = matrix+ alice = storage.get_account("alice")+ _make_private_roots(alice)+ Path(run_as(alice, tools.sandbox_root)).mkdir(parents = True, exist_ok = True)++ storage.delete_account(alice.account_id, accounts.retire_account_roots)++ workspace = run_as(alice, storage_roots.workspace_root)+ tmp = run_as(alice, storage_roots.tmp_root)+ projects = run_as(alice, storage_roots.project_workspaces_root)+ sandbox = Path(run_as(alice, tools.sandbox_root))+ assert not any(root.exists() for root in (workspace, tmp, projects, sandbox))++ for helper in (+ tool_confinement._readable_account_roots,+ tool_confinement._writable_roots,+ ):+ with pytest.raises(storage_roots.RetiredAccountError):+ run_as(alice, helper)++ # The public entry a tool call uses refuses too, as a returned error rather than a raise.+ with pytest.raises(storage_roots.RetiredAccountError):+ run_as(alice, tools._get_workdir, "chat")+ result = run_as(alice, tools._bash_exec, "echo hi", "chat")+ assert "account has been deleted" in result++ assert not any(root.exists() for root in (workspace, tmp, projects, sandbox))+++def test_runtime_secret_mounts_are_excluded_from_the_system_grant(tmp_path, monkeypatch):+ """A managed tool must not read /run/secrets or /run/credentials; the rest of /run stays readable."""+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ run = tmp_path / "run"+ for name in ("user/1000", "secrets", "credentials", "lock"):+ (run / name).mkdir(parents = True)+ (run / "secrets" / "db_password").write_text("hunter2")+ (run / "credentials" / "svc" / "token").parent.mkdir()+ (run / "credentials" / "svc" / "token").write_text("token")+ monkeypatch.setattr(tool_confinement, "_SYSTEM_READ_ROOTS", (str(run),))+ # The shipped list, relocated under the fake /run, so the test reads the real constant.+ monkeypatch.setattr(+ tool_confinement,+ "_PRIVATE_RUNTIME_ROOTS",+ tuple(+ str(run / os.path.relpath(p, "/run")) for p in tool_confinement._PRIVATE_RUNTIME_ROOTS+ ),+ )+ run_as(ALICE, tools._get_workdir, "chat")+ rules = run_as(ALICE, tool_confinement._landlock_rules, 6, tools._SANDBOX_SITE_DIR)+ granted = [p for p, _ in rules]+ resolved = str(run.resolve())+ print(f"granted under {resolved}: {[p for p in granted if p.startswith(resolved)]}")+ assert f"{resolved}/lock" in granted+ assert resolved not in granted+ for private in ("secrets", "credentials", "user"):+ assert not any(+ p == f"{resolved}/{private}" or p.startswith(f"{resolved}/{private}/") for p in granted+ ), private+++def test_privileged_etc_secrets_are_excluded_from_the_system_grant(tmp_path, monkeypatch):+ """A root-run Studio must not hand a managed tool /etc/shadow, sudoers, host keys or private TLS keys."""+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ etc = tmp_path / "etc"+ for name in ("ssl/private", "ssl/certs", "ssh", "sudoers.d", "security"):+ (etc / name).mkdir(parents = True)+ for name in (+ "shadow",+ "sudoers",+ "sudoers.d/admins",+ "security/opasswd",+ "ssl/private/server.key",+ "ssh/ssh_host_ed25519_key",+ "hosts",+ "ssh/ssh_config",+ "ssh/ssh_host_ed25519_key.pub",+ "ssl/certs/ca.pem",+ ):+ (etc / name).write_text(name)+ monkeypatch.setattr(tool_confinement, "_SYSTEM_READ_ROOTS", (str(etc),))+ monkeypatch.setattr(+ tool_confinement,+ "_PRIVATE_SYSTEM_PATHS",+ tuple(+ str(etc / os.path.relpath(p, "/etc")) for p in tool_confinement._PRIVATE_SYSTEM_PATHS+ ),+ )+ run_as(ALICE, tools._get_workdir, "chat")+ rules = run_as(ALICE, tool_confinement._landlock_rules, 6, tools._SANDBOX_SITE_DIR)+ granted = [p for p, _ in rules]+ resolved = str(etc.resolve())+ assert resolved not in granted+ for public in ("hosts", "ssh/ssh_config", "ssh/ssh_host_ed25519_key.pub", "ssl/certs"):+ assert f"{resolved}/{public}" in granted, public+ for private in (+ "shadow",+ "sudoers",+ "sudoers.d",+ "security/opasswd",+ "ssl/private",+ "ssh/ssh_host_ed25519_key",+ ):+ assert not any(+ p == f"{resolved}/{private}" or p.startswith(f"{resolved}/{private}/") for p in granted+ ), private+++def test_landlock_grants_device_nodes_not_the_device_tree(tmp_path):+ """Same-UID ptys, shm objects and a root deployment's disks live under /dev; tools get the pseudo-devices."""+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ run_as(ALICE, tools._get_workdir, "chat")+ rules = dict(run_as(ALICE, tool_confinement._landlock_rules, 5, tools._SANDBOX_SITE_DIR))+ granted = [p for p in rules if p == "/dev" or p.startswith("/dev/")]+ assert "/dev" not in granted+ assert {"/dev/null", "/dev/urandom"} <= set(granted)+ assert not any(p.startswith(("/dev/shm", "/dev/pts")) for p in granted)+ device = (+ tool_confinement._FS_READ_FILE+ | tool_confinement._FS_WRITE_FILE+ | tool_confinement._FS_IOCTL_DEV+ )+ assert rules["/dev/null"] == device++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_managed_child_reaches_pseudo_devices_but_not_shared_memory(tmp_path):+ _seed(tmp_path)+ out = run_as(+ BOB,+ tools._python_exec,+ "import os\n"+ "print('urandom', len(open('/dev/urandom', 'rb').read(4)))\n"+ "open('/dev/null', 'w').write('x'); print('null ok')\n"+ "try:\n"+ " os.listdir('/dev/shm'); print('SHM LISTED')\n"+ "except OSError as e:\n"+ " print('shm denied', e.__class__.__name__)\n",+ session_id = "chat",+ )+ assert "urandom 4" in out and "null ok" in out, out+ assert "SHM LISTED" not in out and "shm denied" in out, out+++def test_macos_profile_grants_pseudo_devices_only():+ profile = tool_confinement.macos_profile(read_roots = [], hidden_roots = [], writable_roots = [])+ assert '(subpath "/dev")' not in profile+ assert '(literal "/dev/null")' in profile and '(literal "/dev/urandom")' in profilediff --git a/studio/backend/tests/test_account_tool_confinement_runtime_dir.py b/studio/backend/tests/test_account_tool_confinement_runtime_dir.pynew file mode 100644index 00000000000..f1c58d43da1--- /dev/null+++ b/studio/backend/tests/test_account_tool_confinement_runtime_dir.py@@ -0,0 +1,45 @@+# 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 os+import sys++import pytest++from core.inference import tool_confinement, tools+from utils.account_context import run_as++from .test_account_tool_confinement import BOB, LANDLOCK, auth_env, isolated, matrix # noqa: F401+++def _runtime_dir() -> str:+ return f"/run/user/{os.getuid()}"+++def test_landlock_rules_exclude_the_per_user_runtime_dir(tmp_path):+ """/run is granted wholesale, but XDG_RUNTIME_DIR is 0700 for the Studio Unix user:+ without an exclusion every managed account reads the owner's runtime secrets."""+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ runtime = _runtime_dir()+ if not os.path.isdir(runtime):+ pytest.skip("no per-user runtime dir on this host")+ run_as(BOB, tools._get_workdir, "chat")+ rules = run_as(BOB, tool_confinement._landlock_rules, 3, tools._SANDBOX_SITE_DIR)+ assert all(not tool_confinement._contains(p, runtime) for p, _ in rules), [+ p for p, _ in rules if tool_confinement._contains(p, runtime)+ ]+ # The rest of /run stays readable: /etc/resolv.conf usually points into it.+ resolv = os.path.realpath("/etc/resolv.conf")+ if resolv.startswith("/run/") and os.path.exists(resolv):+ assert any(tool_confinement._contains(p, resolv) for p, _ in rules)++[email protected](not LANDLOCK, reason = "Landlock not available on this kernel")+def test_managed_child_cannot_read_the_per_user_runtime_dir(tmp_path):+ runtime = _runtime_dir()+ if not os.path.isdir(runtime):+ pytest.skip("no per-user runtime dir on this host")+ run_as(BOB, tools._get_workdir, "chat")+ out = run_as(BOB, tools._bash_exec, f"ls -a {runtime}; echo rc=$?", session_id = "chat")+ assert "rc=0" not in out, outdiff --git a/studio/backend/tests/test_account_tool_confinement_signal_abi.py b/studio/backend/tests/test_account_tool_confinement_signal_abi.pynew file mode 100644index 00000000000..cca22adb629--- /dev/null+++ b/studio/backend/tests/test_account_tool_confinement_signal_abi.py@@ -0,0 +1,81 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression: a Landlock confinement offered to a managed account must scope signals.++Drop in as studio/backend/tests/test_account_tool_confinement_signal_abi.py.+"""++import subprocess+import sys+import time++import pytest++from auth import policy+from core.inference import tool_confinement, tools+from utils.account_context import AccountContext, run_as++from .test_account_lifecycle import auth_env, matrix # noqa: F401++BOB = AccountContext("bob-id", "bob")++[email protected](autouse = True)+def isolated(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)+ monkeypatch.delenv("UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS", raising = False)+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_NPROC", "4000000")+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(tools, "_workdirs", {})+ monkeypatch.setattr(tools, "_active_sessions", {})+ monkeypatch.setattr(tools, "_pending_removals", {})+ monkeypatch.setattr(tools, "_removing_sessions", set())+ monkeypatch.setattr(tools, "_legacy_sandbox_migrated", True)+ monkeypatch.setattr(tools, "_start_detached_sweep", lambda: None)+ monkeypatch.setattr(tools, "_legacy_sandbox_root", lambda: str(tmp_path / "legacy"))+++ sys.platform != "linux" or tool_confinement.landlock_abi() < 6,+ reason = "needs a kernel able to apply the ABI 6 signal scope",+)[email protected]("abi", (3, 4, 5))+def test_pre_scope_landlock_abi_never_confines_a_managed_account(abi, monkeypatch):+ """Below ABI 6 signals are unscoped, so the fs sandbox alone must not count as confinement."""+ monkeypatch.setattr(tool_confinement, "landlock_abi", lambda: abi)+ assert tool_confinement._linux_confinement(tools._SANDBOX_SITE_DIR) is None+ with pytest.raises(tool_confinement.ToolConfinementUnavailable):+ run_as(BOB, tools._account_confinement)+++ sys.platform != "linux" or tool_confinement.landlock_abi() < 6,+ reason = "needs a kernel able to apply the ABI 6 signal scope",+)+def test_a_confined_managed_child_cannot_kill_a_foreign_process_on_a_pre_scope_abi(monkeypatch):+ """Same behaviour, observed: an ABI 5 host must not hand a managed tool a signal-capable box."""+ monkeypatch.setattr(tool_confinement, "landlock_abi", lambda: 5)+ victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])+ try:+ try:+ run_as(BOB, tools._account_confinement)+ except tool_confinement.ToolConfinementUnavailable:+ return # refused: the gap cannot be reached+ out = run_as(+ BOB,+ tools._python_exec,+ "import os, signal\n"+ f"try:\n"+ f" os.kill({victim.pid}, signal.SIGKILL); print('KILLED_FOREIGN')\n"+ "except OSError as e:\n"+ " print('signal denied', e.errno)\n",+ session_id = "chat",+ )+ time.sleep(1)+ assert "KILLED_FOREIGN" not in out, out+ assert victim.poll() is None, "a managed tool killed a foreign same-UID process"+ finally:+ victim.kill()diff --git a/studio/backend/tests/test_account_tool_isolation.py b/studio/backend/tests/test_account_tool_isolation.pynew file mode 100644index 00000000000..da1a4772e2e--- /dev/null+++ b/studio/backend/tests/test_account_tool_isolation.py@@ -0,0 +1,711 @@+# 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 asyncio+import json+import os+import socket+import sys+import threading+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from core.inference import mcp_client, tools+from state import tool_policy+from storage import mcp_servers_db+from utils.account_context import OWNER, AccountContext, arun_as, current_account_id, run_as++ALICE = AccountContext("alice-id", "alice")+BOB = AccountContext("bob-id", "bob")+ACCOUNTS = (OWNER, ALICE, BOB)++[email protected](autouse = True)+def isolated(tmp_path, monkeypatch):+ sweep = tools._start_detached_sweep+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(tools, "_workdirs", {})+ monkeypatch.setattr(tools, "_active_sessions", {})+ monkeypatch.setattr(tools, "_pending_removals", {})+ monkeypatch.setattr(tools, "_removing_sessions", set())+ monkeypatch.setattr(tools, "_legacy_sandbox_migrated", True)+ monkeypatch.setattr(tools, "_start_detached_sweep", lambda: None)+ monkeypatch.setattr(tools, "_legacy_sandbox_root", lambda: str(tmp_path / "legacy"))+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())+ if hasattr(mcp_servers_db, "_account_schema_ready"):+ monkeypatch.setattr(mcp_servers_db, "_account_schema_ready", set())+ monkeypatch.setattr(mcp_client, "_tool_cache", {})+ monkeypatch.setattr(mcp_client, "_probe_cooloff_until", {})+ monkeypatch.setattr(mcp_client, "_oauth_token_store", None)+ if hasattr(mcp_client, "_account_oauth_token_stores"):+ monkeypatch.setattr(mcp_client, "_account_oauth_token_stores", {})+ return sweep++[email protected]("session", [None, "same-chat", "../invalid", "project-same"])+def test_workdirs_and_memos_are_account_scoped(session, tmp_path):+ paths = [run_as(account, tools._get_workdir, session) for account in ACCOUNTS]+ assert len(set(paths)) == 3+ for account, path in zip(ACCOUNTS, paths):+ root = tmp_path / "studio"+ if account != OWNER:+ root = root / "accounts" / account.account_id+ assert Path(path).parent == root / "sandbox"+ assert run_as(account, tools.resolve_sandbox_workdir, session) == path+ assert tools._workdirs[(account.account_id, session or tools._ANON_KEY)] == path+++def test_override_preserves_owner_and_namespaces_managed_accounts(tmp_path, monkeypatch):+ override = tmp_path / "custom-sandbox"+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(override))+ assert tools.sandbox_root() == str(override)+ for account in (ALICE, BOB):+ assert run_as(account, tools.sandbox_root) == str(+ override / "accounts" / account.account_id+ )+++ "resolver,name",+ [+ (tools._orphan_records_dir, "orphaned-projects"),+ (tools._spill_records_dir, "tool-output-records"),+ ],+)+def test_records_are_account_scoped(resolver, name, tmp_path):+ assert resolver() == str(tmp_path / "studio" / name)+ for account in (ALICE, BOB):+ assert run_as(account, resolver) == str(+ tmp_path / "studio" / "accounts" / account.account_id / name+ )+++def test_managed_account_never_reads_or_migrates_owner_legacy_sandbox(tmp_path, monkeypatch):+ legacy = tmp_path / "legacy" / "same-chat"+ legacy.mkdir(parents = True)+ (legacy / "secret").write_text("owner", encoding = "utf-8")+ monkeypatch.setattr(tools, "_legacy_sandbox_migrated", False)+ assert run_as(ALICE, tools._legacy_session_dir, "same-chat") is None+ path = Path(run_as(ALICE, tools._get_workdir, "same-chat"))+ assert not (path / "secret").exists()+ assert (legacy / "secret").read_text(encoding = "utf-8") == "owner"+ assert not tools._legacy_sandbox_migrated+++def test_managed_project_does_not_resolve_host_workspace(monkeypatch):+ from storage import studio_db+ monkeypatch.setattr(+ studio_db,+ "ensure_chat_project_workspace",+ lambda *_: pytest.fail("host workspace consulted"),+ )+ assert run_as(ALICE, tools._get_project_workdir, "project-demo") is None+++def test_session_lifecycle_does_not_block_another_account():+ def alice_call():+ with tools._session_in_flight("same-chat"):+ assert tools.wait_for_sessions_idle(["same-chat"], timeout = 0) is False+ assert run_as(BOB, tools.wait_for_sessions_idle, ["same-chat"], timeout = 0) is True+ assert run_as(OWNER, tools.wait_for_sessions_idle, ["same-chat"], timeout = 0) is True++ run_as(ALICE, alice_call)+++def test_removing_alices_sandbox_keeps_bobs(tmp_path):+ alice = Path(run_as(ALICE, tools._get_workdir, "same-chat"))+ bob = Path(run_as(BOB, tools._get_workdir, "same-chat"))+ assert run_as(ALICE, tools.remove_session_sandbox, "same-chat") is True+ assert not alice.exists()+ assert bob.is_dir()+ assert (BOB.account_id, "same-chat") in tools._workdirs+ assert (ALICE.account_id, "same-chat") not in tools._workdirs++[email protected]("other", [OWNER, BOB])[email protected]("kind", ["absolute", "parent", "symlink"])+def test_edit_file_cannot_read_or_write_foreign_sandbox(other, kind):+ alice = Path(run_as(ALICE, tools._get_workdir, "same-chat"))+ foreign = Path(run_as(other, tools._get_workdir, "same-chat")) / "secret.txt"+ foreign.write_text("private", encoding = "utf-8")+ if kind == "absolute":+ raw = str(foreign)+ elif kind == "parent":+ raw = os.path.relpath(foreign, alice)+ else:+ (alice / "link").symlink_to(foreign)+ raw = "link"+ result = run_as(+ ALICE,+ tools.execute_tool,+ "edit_file",+ {+ "path": raw,+ "edits": [{"old_string": "private", "new_string": "changed"}],+ },+ session_id = "same-chat",+ )+ assert "outside" in result+ assert foreign.read_text(encoding = "utf-8") == "private"++[email protected]("account", ACCOUNTS)+ "flags", [{"permission_mode": "full"}, {"bypass_permissions": True}, {"disable_sandbox": True}]+)+def test_full_access_admission_refuses_every_account_in_multi_mode(account, flags):+ with pytest.raises(HTTPException) as exc:+ run_as(account, tool_policy.require_tool_access, **flags)+ assert exc.value.status_code == 400+ assert "full access" in exc.value.detail.lower()+ assert "more than one account exists" in exc.value.detail+++ "mode,bypass,want",+ [+ (None, False, ("auto", False)),+ ("unknown", False, ("ask", False)),+ ("off", False, ("off", False)),+ ("full", False, ("full", True)),+ ("ask", True, ("full", True)),+ ],+)+def test_single_account_permissions_keep_historical_normalization(mode, bypass, want, monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ assert tool_policy.normalize_tool_permissions(mode, bypass) == want+++def test_sandboxed_admission_never_queries_installation_policy(monkeypatch):+ monkeypatch.setattr(+ policy, "full_access_permitted", lambda: pytest.fail("unexpected policy lookup")+ )+ tool_policy.require_tool_access("auto")+ tool_policy.require_tool_access("ask")+ tool_policy.require_tool_access("off")+++def test_direct_tool_bypass_is_rejected_before_dispatch(monkeypatch):+ monkeypatch.setattr(tools, "_bash_exec", lambda *a, **kw: pytest.fail("tool ran"))+ with pytest.raises(HTTPException) as exc:+ tools.execute_tool("terminal", {"command": "pwd"}, disable_sandbox = True)+ assert exc.value.status_code == 400++[email protected]("account", ACCOUNTS)+ "name",+ [+ "HF_TOKEN",+ "WANDB_API_KEY",+ "AWS_PROFILE",+ "AWS_ACCESS_KEY_ID",+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "GH_TOKEN",+ "CUSTOM_TOKEN",+ "CUSTOM_KEY",+ "CUSTOM_SECRET",+ "custom_key",+ ],+)+def test_safe_environment_excludes_host_credentials(account, name, monkeypatch):+ monkeypatch.setenv(name, "private-value")+ workdir = run_as(account, tools._get_workdir, "env")+ env = run_as(account, tools._build_safe_env, workdir)+ assert name not in env+ assert env["HOME"] == workdir+ assert Path(env["TMPDIR"]).parent == Path(workdir)+++def test_owner_environment_remains_identical_for_managed_context(monkeypatch):+ workdir = tools._get_workdir("env")+ monkeypatch.setenv("HF_TOKEN", "owner-token")+ monkeypatch.setenv("LANG", "en_US.UTF-8")+ assert run_as(ALICE, tools._build_safe_env, workdir) == tools._build_safe_env(workdir)+++def test_tool_stream_carries_account_into_worker_thread():+ from core.inference.tool_stream_exec import stream_tool_execution++ seen = []+ stream = run_as(ALICE, tool_policy.account_tool_stream, stream_tool_execution)+ list(stream(lambda output: seen.append(current_account_id()) or "done", tool_name = "test"))+ assert seen == [ALICE.account_id]+ assert tool_policy.account_tool_stream(stream_tool_execution) is stream_tool_execution+++ "model_name", ["ChatCompletionRequest", "ChatCountTokensRequest", "AnthropicMessagesRequest"]+)+def test_full_access_validators_remain_policy_free(model_name, monkeypatch):+ from models import inference++ monkeypatch.setattr(+ policy, "full_access_permitted", lambda: pytest.fail("model consulted policy")+ )+ model = getattr(inference, model_name)+ kwargs = {+ "model": "test",+ "permission_mode": "full",+ "messages": [{"role": "user", "content": "hi"}],+ "max_tokens": 10,+ }+ payload = model(**kwargs)+ assert payload.bypass_permissions is True+++def test_mcp_configs_are_private_and_schema_is_initialized_per_database(monkeypatch):+ monkeypatch.setattr(+ socket,+ "getaddrinfo",+ lambda *a, **kw: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))],+ )+ for account in ACCOUNTS:+ run_as(+ account,+ mcp_servers_db.create_server,+ id = "same",+ display_name = account.username,+ url = "https://public.example/mcp",+ )+ for account in ACCOUNTS:+ assert (+ run_as(account, mcp_servers_db.get_server, "same")["display_name"] == account.username+ )+ run_as(ALICE, mcp_servers_db.delete_server, "same")+ assert run_as(ALICE, mcp_servers_db.list_servers) == []+ assert run_as(BOB, mcp_servers_db.get_server, "same") is not None+ assert mcp_servers_db.get_server("same") is not None+++ "url",+ [+ "python server.py",+ "http://127.0.0.1/mcp",+ "http://10.0.0.1/mcp",+ "http://169.254.169.254/mcp",+ "http://[::1]/mcp",+ "http://[::ffff:127.0.0.1]/mcp",+ ],+)+def test_managed_mcp_registration_refuses_local_servers(url):+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, mcp_servers_db.create_server, id = "unsafe", display_name = "Unsafe", url = url)+ assert exc.value.status_code == 400+ assert run_as(ALICE, mcp_servers_db.get_server, "unsafe") is None+++def test_mcp_update_cannot_introduce_local_endpoint(monkeypatch):+ monkeypatch.setattr(+ socket,+ "getaddrinfo",+ lambda *a, **kw: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))],+ )+ run_as(+ ALICE,+ mcp_servers_db.create_server,+ id = "server",+ display_name = "Public",+ url = "https://public.example/mcp",+ )+ with pytest.raises(HTTPException):+ run_as(ALICE, mcp_servers_db.update_server, "server", {"url": "python local.py"})+ assert run_as(ALICE, mcp_servers_db.get_server, "server")["url"] == "https://public.example/mcp"+++def test_mcp_owner_keeps_local_registration_without_dns_cost(monkeypatch):+ monkeypatch.setattr(socket, "getaddrinfo", lambda *a, **kw: pytest.fail("owner DNS validation"))+ for index, url in enumerate(("python server.py", "http://127.0.0.1/mcp")):+ mcp_servers_db.create_server(id = str(index), display_name = "Owner", url = url)+ assert mcp_servers_db.get_server(str(index))["url"] == url+++def test_stdio_gate_refuses_alice_even_when_installation_enables_it(monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")+ assert not run_as(ALICE, mcp_client.stdio_mcp_enabled)+ assert "owner" in run_as(ALICE, mcp_client.stdio_mcp_disabled_reason)+++def test_mcp_dns_rejects_mixed_public_and_private_answers(monkeypatch):+ monkeypatch.setattr(+ socket,+ "getaddrinfo",+ lambda *a, **kw: [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 443)) for ip in ("8.8.8.8", "10.0.0.1")+ ],+ )+ with pytest.raises(HTTPException):+ run_as(ALICE, mcp_client.validate_mcp_address, "https://mixed.example/mcp")+++def test_mcp_cache_and_failure_cooloffs_are_private():+ for account in ACCOUNTS:+ run_as(account, mcp_client.cache_tools, "same", [{"name": account.username}])+ run_as(ALICE, mcp_client.record_probe_failure, "same")+ assert run_as(ALICE, mcp_client.in_failure_cooloff, "same")+ assert not run_as(BOB, mcp_client.in_failure_cooloff, "same")+ run_as(ALICE, mcp_client.invalidate_tool_cache)+ assert run_as(ALICE, mcp_client.get_cached_tools, "same") is None+ assert run_as(BOB, mcp_client.get_cached_tools, "same") == [{"name": "bob"}]+ assert mcp_client.get_cached_tools("same") == [{"name": "unsloth"}]+++def test_oauth_stores_and_files_are_private(tmp_path):+ stores = [run_as(account, mcp_client._oauth_store) for account in ACCOUNTS]+ assert len({id(store) for store in stores}) == 3+ assert str(stores[0]._data_directory) == str(tmp_path / "studio" / "mcp-oauth-tokens")+ for account, store in zip(ACCOUNTS, stores):+ assert run_as(account, mcp_client._oauth_store) is store+ for account, store in zip((ALICE, BOB), stores[1:]):+ assert str(store._data_directory) == str(+ tmp_path / "studio" / "accounts" / account.account_id / "mcp-oauth-tokens"+ )+++def test_closing_mcp_sessions_only_closes_acting_account(monkeypatch):+ sessions = {}+ closed = []+ for account in ACCOUNTS:+ key = run_as(+ account, mcp_client._session_key, "https://public.example/mcp", None, "same-chat"+ )+ sessions[key] = account.account_id+ assert len(sessions) == 3+ monkeypatch.setattr(mcp_client, "_mcp_sessions", sessions)+ monkeypatch.setattr(mcp_client, "_close_all", lambda values: closed.extend(values))+ monkeypatch.setattr(mcp_client, "_drain_cleanup_queue", lambda: ([], None))+ before = {+ account.account_id: run_as(+ account, mcp_client._mcp_close_generation, "https://public.example/mcp", None+ )+ for account in ACCOUNTS+ }+ run_as(ALICE, mcp_client.close_mcp_sessions)+ assert closed == [ALICE.account_id]+ for account in (OWNER, BOB):+ assert (+ run_as(account, mcp_client._mcp_close_generation, "https://public.example/mcp", None)+ == before[account.account_id]+ )+ assert (+ run_as(ALICE, mcp_client._mcp_close_generation, "https://public.example/mcp", None)+ != before[ALICE.account_id]+ )++[email protected]("account", ACCOUNTS)[email protected]("loop_name", ["gguf", "safetensors", "studio", "codex"])+def test_every_tool_loop_refuses_full_access_before_model_or_tool_dispatch(account, loop_name):+ def check():+ if loop_name == "gguf":+ from core.inference.llama_cpp import LlamaCppBackend+ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ list(+ backend.generate_chat_completion_with_tools(+ messages = [], tools = [], permission_mode = "full"+ )+ )+ elif loop_name == "safetensors":+ from core.inference.safetensors_agentic import run_safetensors_tool_loop+ list(+ run_safetensors_tool_loop(+ single_turn = lambda *_: pytest.fail("model ran"),+ messages = [],+ tools = [],+ execute_tool = lambda *a, **kw: pytest.fail("tool ran"),+ permission_mode = "full",+ )+ )+ else:+ from core.inference.studio_tool_loop import (+ ToolLoopPolicy,+ ToolLoopRun,+ stream_with_studio_tools,+ )++ transport = SimpleNamespace(heals_text_tool_calls = False)+ run = ToolLoopRun(model = "test", messages = [])+ loop_policy = ToolLoopPolicy(+ tools = [],+ max_calls = 1,+ timeout = 1,+ rag_scope = None,+ permission_mode = "full",+ confirm_calls = False,+ bypass_permissions = False,+ )+ if loop_name == "studio":+ stream = stream_with_studio_tools(+ transport, run = run, policy = loop_policy, cancel_event = threading.Event()+ )+ else:+ from core.inference.openai_codex_tool_loop import (+ CodexRunContext,+ CodexToolPolicy,+ stream_codex_with_studio_tools,+ )+ stream = stream_codex_with_studio_tools(+ client = None,+ cancel_event = threading.Event(),+ run = CodexRunContext(+ model = "test",+ messages = [],+ provider_id = "test",+ thread_id = None,+ session_id = None,+ reasoning_effort = None,+ ),+ policy = CodexToolPolicy(+ tools = [],+ max_calls = 1,+ timeout = 1,+ rag_scope = None,+ permission_mode = "full",+ confirm_calls = False,+ bypass_permissions = False,+ ),+ )++ async def consume():+ return [event async for event in stream]++ asyncio.run(consume())++ with pytest.raises(HTTPException) as exc:+ run_as(account, check)+ assert exc.value.status_code == 400+++def test_mcp_lru_never_evicts_another_accounts_session(monkeypatch):+ key = run_as(BOB, mcp_client._session_key, "https://public.example/mcp", None, "chat")+ session = SimpleNamespace(last_used = 0, in_flight = 0)+ monkeypatch.setattr(mcp_client, "_mcp_sessions", {key: session})+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 1)+ assert run_as(ALICE, mcp_client._evict_lru_locked) == []+ assert mcp_client._mcp_sessions[key] is session+++def test_mcp_release_overshoot_never_evicts_another_accounts_session(monkeypatch):+ bob_key = run_as(BOB, mcp_client._session_key, "https://public.example/mcp", None, "chat")+ bob = SimpleNamespace(last_used = 0, in_flight = 0)+ alice_old_key = run_as(ALICE, mcp_client._session_key, "https://a.example/mcp", None, "chat")+ alice_old = SimpleNamespace(last_used = 1, in_flight = 0, defunct = False)+ alice_new_key = run_as(ALICE, mcp_client._session_key, "https://b.example/mcp", None, "chat")+ alice_new = SimpleNamespace(+ last_used = 2, in_flight = 1, defunct = False, account_id = ALICE.account_id+ )+ sessions = {bob_key: bob, alice_old_key: alice_old, alice_new_key: alice_new}+ monkeypatch.setattr(mcp_client, "_mcp_sessions", sessions)+ monkeypatch.setattr(mcp_client, "_MAX_SESSIONS", 1)+ monkeypatch.setattr(mcp_client, "_close_detached", lambda victims: None)+ run_as(ALICE, mcp_client._release_session, alice_new, True)+ assert sessions[bob_key] is bob+ assert alice_old_key not in sessions+++def test_mcp_public_transport_pins_dns_and_checks_redirects(monkeypatch):+ seen = []++ async def check():+ client = mcp_client._public_http_client_factory()+ http = sys.modules[type(client).__module__.split(".")[0]]++ async def send(transport, request):+ seen.append(+ (str(request.url), request.headers["host"], request.extensions["sni_hostname"])+ )+ return http.Response(302, headers = {"location": "http://127.0.0.1/private"})++ monkeypatch.setattr(http.AsyncHTTPTransport, "handle_async_request", send)++ def resolve(host, port, **kwargs):+ ip = "8.8.8.8" if host == "public.example" else host+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port))]++ monkeypatch.setattr(socket, "getaddrinfo", resolve)+ async with client:+ with pytest.raises(HTTPException):+ await client.get("https://public.example/mcp")++ asyncio.run(check())+ assert seen == [("https://8.8.8.8/mcp", "public.example", "public.example")]+++def test_managed_transport_and_oauth_use_public_http_factory(monkeypatch):+ import fastmcp+ import fastmcp.client.transports as transports++ monkeypatch.setattr(+ socket,+ "getaddrinfo",+ lambda *a, **kw: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", 443))],+ )+ monkeypatch.setattr(fastmcp, "Client", lambda transport: transport)+ monkeypatch.setattr(transports, "StreamableHttpTransport", lambda **kwargs: kwargs)+ oauth = SimpleNamespace(httpx_client_factory = None)+ monkeypatch.setattr(mcp_client, "_oauth", lambda url: oauth)+ result = run_as(ALICE, mcp_client._client, "https://public.example/mcp", None, True)+ assert result["httpx_client_factory"] is mcp_client._public_http_client_factory+ assert oauth.httpx_client_factory is mcp_client._public_http_client_factory+ owner = mcp_client._client("http://127.0.0.1/mcp", None)+ assert "httpx_client_factory" not in owner+++def test_workspace_cleanup_thread_retains_account(monkeypatch):+ seen = []+ monkeypatch.setattr(tools, "wait_for_sessions_idle", lambda *a, **kw: True)+ monkeypatch.setattr(+ tools, "collect_orphaned_project_workspaces", lambda: seen.append(current_account_id())+ )+ worker = run_as(ALICE, tools.finish_workspace_delete_when_idle, "project")+ worker.join(5)+ assert not worker.is_alive()+ assert seen == [ALICE.account_id]++[email protected]("loop_name", ["gguf", "safetensors", "studio"])+def test_tool_loops_keep_account_in_real_worker_thread(loop_name, monkeypatch):+ monkeypatch.syspath_prepend(str(Path(__file__).parent))+ from core.inference import studio_tool_loop++ seen = []++ def execute(name, arguments, **kwargs):+ seen.append(current_account_id())+ return "completed"++ monkeypatch.setattr(tools, "execute_tool", execute)+ monkeypatch.setattr(studio_tool_loop, "execute_tool", execute)+ monkeypatch.setattr(tools, "build_rag_autoinject", lambda *a, **kw: None)+ monkeypatch.setattr(studio_tool_loop, "build_rag_autoinject", lambda *a, **kw: None)+ schema = [+ {"type": "function", "function": {"name": "python", "parameters": {"type": "object"}}}+ ]+ if loop_name == "gguf":+ from test_llama_cpp_tool_loop import _make_backend, _sse, _done, _structured_tool_call+ backend = _make_backend(+ monkeypatch,+ [+ _structured_tool_call("python", {"code": "print(1)"}, "call1"),+ [_sse({"content": "done"}), _done()],+ ],+ [],+ )++ def run():+ return list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "run"}],+ tools = schema,+ permission_mode = "off",+ max_tool_iterations = 1,+ )+ )+ elif loop_name == "safetensors":+ from core.inference.safetensors_agentic import run_safetensors_tool_loop+ turns = iter(+ ['<tool_call>{"name":"python","arguments":{"code":"print(1)"}}</tool_call>', "done"]+ )++ def run():+ return list(+ run_safetensors_tool_loop(+ single_turn = lambda *_: iter([next(turns)]),+ messages = [{"role": "user", "content": "run"}],+ tools = schema,+ execute_tool = execute,+ permission_mode = "off",+ max_tool_iterations = 1,+ )+ )+ else:+ from test_studio_tool_loop import FakeTransport, _run, _sse, _DONE+ transport = FakeTransport(+ [+ [+ _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call1",+ "function": {+ "name": "python",+ "arguments": '{"code":"print(1)"}',+ },+ }+ ]+ }+ ),+ _sse(finish = "tool_calls"),+ _DONE,+ ],+ [_sse({"content": "done"}), _sse(finish = "stop"), _DONE],+ ]+ )++ def run():+ return _run(transport, tools = schema)++ run_as(ALICE, run)+ assert seen == [ALICE.account_id]+++def test_retrieval_worker_retains_account():+ result = run_as(+ ALICE,+ tools._search_knowledge_base_with_budget,+ {},+ None,+ 5,+ None,+ search_fn = lambda *args: current_account_id(),+ )+ assert result == ALICE.account_id+++def test_managed_sandbox_does_not_fall_back_to_owner_on_root_error(monkeypatch):+ from utils.paths import storage_roots++ def unavailable():+ raise RuntimeError("root unavailable")++ monkeypatch.setattr(storage_roots, "workspace_root", unavailable)+ with pytest.raises(RuntimeError, match = "root unavailable"):+ run_as(ALICE, tools.sandbox_root)+ assert tools.sandbox_root() == tools._legacy_sandbox_root()+++def test_transport_refuses_managed_stdio_before_constructing_client(monkeypatch):+ import fastmcp++ monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")+ monkeypatch.setattr(fastmcp, "Client", lambda *a, **kw: pytest.fail("local client constructed"))+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, mcp_client._client, "python server.py", None)+ assert exc.value.status_code == 400+++def test_sandbox_recovery_runs_once_for_each_account(isolated, monkeypatch):+ seen = []+ monkeypatch.setattr(tools, "_swept_detached", True)+ monkeypatch.setattr(tools, "_swept_detached_accounts", set(), raising = False)+ monkeypatch.setattr(+ tools, "sweep_detached_sandboxes", lambda: seen.append(current_account_id())+ )+ monkeypatch.setattr(tools, "collect_orphaned_project_workspaces", lambda: None)+ for account in (ALICE, BOB):+ worker = run_as(account, isolated)+ assert worker is not None+ worker.join(5)+ assert not worker.is_alive()+ assert run_as(account, isolated) is None+ assert seen == [ALICE.account_id, BOB.account_id]diff --git a/studio/backend/tests/test_account_variant_preflight_token.py b/studio/backend/tests/test_account_variant_preflight_token.pynew file mode 100644index 00000000000..1cb88483094--- /dev/null+++ b/studio/backend/tests/test_account_variant_preflight_token.py@@ -0,0 +1,123 @@+# 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 GGUF variant preflight must accept a caller token that proves Hub access.++A managed account picking a quantization for a private or gated repo it has never+downloaded holds no grant yet -- the grant is only recorded once a download finishes --+so the grant/public check alone turns the whole select-then-download flow into a 404.+The cache-only direction (no token) still needs the grant.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from hub.services.models import account_access as access+from hub.services.models import gguf_variants+from hub.utils import hf_tokens+from utils.account_context import AccountContext, arun_as++ALICE = AccountContext("a" * 32, "alice")++TOKEN = "hf_alice_token"+REPO = "Org/PrivateGGUF"++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(access, "_public_repos", {})+ hf_tokens.reset_repo_access_cache()+ monkeypatch.setattr(hf_tokens, "_hub_offline", lambda: False)+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: True)+ # No cached copy anywhere: the answer has to come from the Hub listing below.+ monkeypatch.setattr(gguf_variants, "select_gguf_cache_snapshot", lambda *_a, **_k: None)+ monkeypatch.setattr(gguf_variants, "_quants_from_state", lambda *_a, **_k: None)+ monkeypatch.setattr(+ gguf_variants,+ "list_gguf_variants",+ lambda *_a, **_k: (+ [+ SimpleNamespace(+ filename = "model-Q4_K_M.gguf",+ quant = "Q4_K_M",+ display_label = "Q4_K_M",+ size_bytes = 1234,+ shard_count = 0,+ )+ ],+ False,+ [],+ ),+ )+ yield+ hf_tokens.reset_repo_access_cache()+++def _hub(monkeypatch, calls: list) -> None:+ """A private repo: anonymous asks are refused, the caller's token is accepted."""++ def repo_info(repo, **kwargs):+ calls.append(kwargs.get("token"))+ if not isinstance(kwargs.get("token"), str):+ error = Exception("private repo")+ error.response = SimpleNamespace(status_code = 404)+ raise error+ return SimpleNamespace(private = True, gated = False)++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = repo_info))+++def _variants(hf_token):+ return asyncio.run(+ arun_as(ALICE, gguf_variants.get_gguf_variants_answer(REPO, hf_token = hf_token))+ )+++def test_a_caller_token_authorizes_the_variant_preflight_before_any_download(monkeypatch):+ calls: list = []+ _hub(monkeypatch, calls)++ answer = _variants(TOKEN)++ assert [v.quant for v in answer.response.variants] == ["Q4_K_M"]+ assert TOKEN in calls, "the supplied token was never offered to the Hub"+++def test_a_cache_only_request_without_a_token_still_needs_the_grant(monkeypatch):+ calls: list = []+ _hub(monkeypatch, calls)++ with pytest.raises(HTTPException) as excinfo:+ _variants(None)++ assert excinfo.value.status_code == 404+++def test_a_recorded_grant_still_answers_without_asking_the_hub(monkeypatch):+ calls: list = []+ _hub(monkeypatch, calls)++ asyncio.run(arun_as(ALICE, asyncio.to_thread(access.record_model_grant, REPO)))+ answer = _variants(None)++ assert [v.quant for v in answer.response.variants] == ["Q4_K_M"]+++def test_an_unreachable_hub_does_not_turn_a_token_into_access(monkeypatch):+ def repo_info(repo, **kwargs):+ raise OSError("Hub unavailable")++ monkeypatch.setattr(access, "HfApi", lambda: SimpleNamespace(repo_info = repo_info))++ with pytest.raises(HTTPException) as excinfo:+ _variants(TOKEN)++ assert excinfo.value.status_code == 404diff --git a/studio/backend/tests/test_account_video_cancel_handoff.py b/studio/backend/tests/test_account_video_cancel_handoff.pynew file mode 100644index 00000000000..888295802f7--- /dev/null+++ b/studio/backend/tests/test_account_video_cancel_handoff.py@@ -0,0 +1,127 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A cancel authorized against one account's job must not cancel the successor's render.++The cancel route reads the backend's reservation several times (the visibility check, the+foreign-work check, and the expected_account it hands back). ``begin_generate`` runs in a worker+thread (asyncio.to_thread), so another account can take the reservation between two of those reads+with no await in between. The backend then rechecks against the account it was GIVEN, so a stale+read makes the recheck a no-op and the requester cancels a render it never owned.+"""++from __future__ import annotations++import threading++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage as auth_storage+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access+from routes import video+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++class HandoffVideoBackend:+ """ALICE's job is current when the route authorizes; BOB reserves right after that read.++ The handoff fires once, immediately after the FIRST read of the reservation, which is the+ earliest interleaving a worker-thread begin_generate can produce: ALICE's clip finished and+ BOB's reservation committed while the cancel request was still on the loop.++ ``cancel_generate`` is the real backend's recheck (core/inference/video.py): it compares+ ``expected_account`` with the reservation it holds NOW and sets the cancel event on a match.+ """++ def __init__(self, hand_off: bool = True):+ self._hand_off = hand_off+ self.job_account = ALICE.account_id+ self.cancel_event = threading.Event()++ def status(self):+ return {"loaded": True, "repo_id": "public/video-model"}++ def generate_job_account(self):+ current = self.job_account+ if self._hand_off:+ self._hand_off = False+ self.job_account = BOB.account_id+ return current++ def cancel_generate(+ self,+ expected_video_id = None,+ expected_account = None,+ ):+ if expected_account is not None and self.job_account != expected_account:+ return False+ self.cancel_event.set()+ return True++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ monkeypatch.setattr(video, "_generation_account", None, raising = False)+ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)+ yield+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(video.router, prefix = "/api/inference")+ return TestClient(app)+++def _install(monkeypatch, backend):+ import core.inference.video as video_module+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+++def test_cancel_does_not_follow_a_reservation_that_changed_hands(monkeypatch):+ """BOB reserves after ALICE's cancel passed authorization; BOB's render must survive."""+ backend = HandoffVideoBackend(hand_off = True)+ _install(monkeypatch, backend)++ with _client(ALICE) as client:+ body = client.post("/api/inference/video/generate/cancel").json()++ assert backend.job_account == BOB.account_id+ assert not backend.cancel_event.is_set(), "alice cancelled bob's render"+ assert body == {"cancelled": False}+++def test_cancel_still_stops_the_requesting_accounts_own_job(monkeypatch):+ """No handoff: the ordinary cancel keeps working."""+ backend = HandoffVideoBackend(hand_off = False)+ _install(monkeypatch, backend)++ with _client(ALICE) as client:+ body = client.post("/api/inference/video/generate/cancel").json()++ assert body == {"cancelled": True}+ assert backend.cancel_event.is_set()diff --git a/studio/backend/tests/test_account_video_generation_owner.py b/studio/backend/tests/test_account_video_generation_owner.pynew file mode 100644index 00000000000..988f3d53570--- /dev/null+++ b/studio/backend/tests/test_account_video_generation_owner.py@@ -0,0 +1,176 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A background clip belongs to the account that started it, not to the model's loader."""++from __future__ import annotations++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage as auth_storage+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access+from routes import video+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++CLIP = {+ "id": "clip-1",+ "url": "/api/inference/video/gallery/clip-1/file",+ "prompt": "bob's private prompt",+ "width": 512,+ "height": 512,+ "num_frames": 49,+ "fps": 24,+ "duration_s": 2.0,+ "steps": 5,+ "guidance": 1.0,+ "seed": 1,+ "created_at": "2026-08-06T00:00:00Z",+}+++class FakeVideoBackend:+ def __init__(self):+ self.started: list[str] = []+ self.cancelled: list[str] = []++ def status(self):+ return {+ "loaded": True,+ "repo_id": "public/video-model",+ "defaults": {"fps": 24, "num_frames": 49, "frame_step": 4, "frame_offset": 1},+ }++ def generation_snapshot(self):+ return self.status(), self++ def begin_generate(self, **kwargs):+ from utils.account_context import current_account+ self.started.append(current_account().username)+ return {"queued": 1, "width": 512, "height": 512, "num_frames": 49, "fps": 24}++ def generate_progress(self):+ return {"active": False, "phase": "completed", "step": 5, "total": 5, "video": CLIP}++ def cancel_generate(self, *args, **kwargs):+ from utils.account_context import current_account+ self.cancelled.append(current_account().username)+ return True++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ monkeypatch.setattr(video, "_generation_account", None, raising = False)+ policy.invalidate_account_cache()+ connection = auth_storage.get_connection()+ with connection:+ for account in (ALICE, BOB):+ connection.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret,"+ " account_id, role, is_active) VALUES (?, 'salt', 'hash', 'secret', ?, 'user', 1)",+ (account.username, account.account_id),+ )+ connection.close()+ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)+ yield+ policy.invalidate_account_cache()+++def backend(monkeypatch):+ import core.inference.video as video_module++ fake = FakeVideoBackend()+ monkeypatch.setattr(video_module, "get_video_backend", lambda: fake)+ return fake+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(video.router, prefix = "/api/inference")+ app.include_router(video.openai_router, prefix = "/v1")+ return TestClient(app)+++def test_the_starting_account_owns_its_clip_and_the_models_loader_does_not(backend):+ generate = "/api/inference/video/generate"+ progress = "/api/inference/video/generate-progress"+ cancel = "/api/inference/video/generate/cancel"++ with _client(BOB) as client:+ assert client.post(generate, json = {"prompt": "p", "steps": 5}).status_code == 200+ assert backend.started == ["bob"]+ assert client.get(progress).json()["video"]["prompt"] == CLIP["prompt"]++ with _client(ALICE) as client:+ assert client.get(progress).json() == {"loaded": True, "yours": False}+ assert client.post(cancel).json() == {"cancelled": False}+ assert backend.cancelled == []++ with _client(BOB) as client:+ assert client.post(cancel).json() == {"cancelled": True}+ assert backend.cancelled == ["bob"]+++def test_a_clip_started_on_the_openai_route_belongs_to_that_account_too(backend):+ progress = "/api/inference/video/generate-progress"+ cancel = "/api/inference/video/generate/cancel"++ with _client(BOB) as client:+ created = client.post(+ "/v1/videos",+ json = {+ "prompt": "p",+ "model": "public/video-model",+ "seconds": "2",+ "size": "512x512",+ },+ )+ assert created.status_code == 200, created.text+ assert backend.started == ["bob"]+ assert client.get(progress).json()["video"]["prompt"] == CLIP["prompt"]++ with _client(ALICE) as client:+ assert client.get(progress).json() == {"loaded": True, "yours": False}+ assert client.post(cancel).json() == {"cancelled": False}+ assert backend.cancelled == []+++def test_the_installation_owner_does_not_see_a_managed_accounts_clip(backend):+ """The owner administers the machine, which does not extend to another account's prompt."""+ from utils.account_context import OWNER++ generate = "/api/inference/video/generate"+ progress = "/api/inference/video/generate-progress"+ cancel = "/api/inference/video/generate/cancel"++ with _client(BOB) as client:+ assert client.post(generate, json = {"prompt": "p", "steps": 5}).status_code == 200+ assert client.get(progress).json()["video"]["prompt"] == CLIP["prompt"]++ with _client(OWNER) as client:+ assert client.get(progress).json() == {"loaded": True, "yours": False}+ assert client.post(cancel).json() == {"cancelled": False}+ assert backend.cancelled == []diff --git a/studio/backend/tests/test_account_video_generation_reservation.py b/studio/backend/tests/test_account_video_generation_reservation.pynew file mode 100644index 00000000000..2bc61f7277e--- /dev/null+++ b/studio/backend/tests/test_account_video_generation_reservation.py@@ -0,0 +1,201 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A clip belongs to the account that reserved the job, from the moment the reservation is taken."""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage as auth_storage+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access+from routes import video+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++CLIP = {+ "id": "clip-1",+ "url": "/api/inference/video/gallery/clip-1/file",+ "prompt": "bob's private prompt",+ "width": 512,+ "height": 512,+ "num_frames": 49,+ "fps": 24,+ "duration_s": 2.0,+ "steps": 5,+ "guidance": 1.0,+ "seed": 1,+ "created_at": "2026-08-06T00:00:00Z",+}+++class ReservingVideoBackend:+ """Reserves the job under its own lock, then resolves inputs, as the real backend does."""++ def __init__(self):+ self.cancelled: list[str] = []+ self.reserved = threading.Event()+ self.release = threading.Event()+ self.release.set()+ self._job_account: str | None = None++ def status(self):+ return {+ "loaded": True,+ "repo_id": "public/video-model",+ "defaults": {"fps": 24, "num_frames": 49, "frame_step": 4, "frame_offset": 1},+ }++ def generate_job_account(self):+ return self._job_account++ def generation_snapshot(self):+ return self.status(), self++ def begin_generate(self, **kwargs):+ from utils.account_context import current_account_id++ self._job_account = current_account_id()+ self.reserved.set()+ assert self.release.wait(20)+ return {"queued": 1, "width": 512, "height": 512, "num_frames": 49, "fps": 24}++ def generate_progress(self):+ return {"active": True, "phase": "denoising", "step": 2, "total": 5, "video": CLIP}++ def cancel_generate(self, *args, **kwargs):+ from utils.account_context import current_account+ self.cancelled.append(current_account().username)+ return True++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ monkeypatch.setattr(video, "_generation_account", None, raising = False)+ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)+ yield+++def backend(monkeypatch):+ import core.inference.video as video_module++ fake = ReservingVideoBackend()+ monkeypatch.setattr(video_module, "get_video_backend", lambda: fake)+ return fake+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(video.router, prefix = "/api/inference")+ return TestClient(app)+++def test_ownership_holds_from_the_reservation_not_from_the_end_of_begin_generate(backend):+ generate = "/api/inference/video/generate"+ progress = "/api/inference/video/generate-progress"+ cancel = "/api/inference/video/generate/cancel"++ with _client(ALICE) as client:+ assert client.post(generate, json = {"prompt": "p", "steps": 5}).status_code == 200++ backend.reserved.clear()+ backend.release.clear()+ started = {}++ def run():+ with _client(BOB) as client:+ started["response"] = client.post(generate, json = {"prompt": "p", "steps": 5})++ thread = threading.Thread(target = run, daemon = True)+ thread.start()+ try:+ assert backend.reserved.wait(20)+ with _client(ALICE) as client:+ assert client.post(cancel).json() == {"cancelled": False}+ assert client.get(progress).json() == {"loaded": True, "yours": False}+ assert backend.cancelled == []+ with _client(BOB) as client:+ assert client.get(progress).json()["video"]["prompt"] == CLIP["prompt"]+ finally:+ backend.release.set()+ thread.join(20)+ assert started["response"].status_code == 200+++def test_the_real_backend_records_the_account_inside_the_locked_reservation():+ import functools++ from core.inference.video import VideoBackend, _VideoResolvedInputs++ backend = VideoBackend()+ family = SimpleNamespace(+ name = "fam",+ default_fps = 24,+ default_num_frames = 49,+ frame_step = 4,+ frame_offset = 1,+ )+ state = SimpleNamespace(family = family, h3_task = None, engine = "diffusers", repo_id = "r")+ backend._state = state+ backend._resolve_keyframes = lambda *a, **k: (None, None, 512, 512, "t2v")+ backend._resolve_references = lambda *a, **k: None+ backend._resolve_flow_shifts = lambda *a, **k: (None, None)+ seen = {}++ def worker(**kwargs):+ seen["at_start"] = backend.generate_job_account()++ backend._run_generate = worker+ import core.inference.video as video_module++ original = video_module.validate_video_request_shape+ video_module.validate_video_request_shape = lambda *a, **k: None+ try:+ from utils.account_context import run_as+ run_as(BOB, functools.partial(backend.begin_generate, prompt = "p", steps = 5))+ finally:+ video_module.validate_video_request_shape = original+ assert seen["at_start"] == BOB.account_id+ assert backend.generate_job_account() == BOB.account_id+++def test_cancel_rechecks_the_authorized_reservation_under_the_lock():+ """The route authorizes on the loop and cancels in a thread; a successor that reserved in between must not receive the stale cancel."""+ import threading++ from core.inference.video import VideoBackend++ backend = VideoBackend()+ event = threading.Event()+ backend._active_generate_cancel = event+ backend._generate_job_account = BOB.account_id+ assert backend.cancel_generate(expected_account = ALICE.account_id) is False+ assert not event.is_set()+ assert backend.cancel_generate(expected_account = BOB.account_id) is True+ assert event.is_set()diff --git a/studio/backend/tests/test_account_video_idle_cancel.py b/studio/backend/tests/test_account_video_idle_cancel.pynew file mode 100644index 00000000000..8d2123dd653--- /dev/null+++ b/studio/backend/tests/test_account_video_idle_cancel.py@@ -0,0 +1,130 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An idle cancel must not stop a render another account starts in the gap.++Before the first generation of the process the backend holds no reservation+(``generate_job_account()`` is None, and it is never cleared afterwards), so the+cancel route takes its no-reservation branch and calls ``cancel_generate()`` with+no expectation at all. ``begin_generate`` runs on a worker thread, so another+account can reserve between the route's read and the executor call, and an+unexpecting cancel sets whatever cancel event is current -- the foreign render's.+"""++from __future__ import annotations++import threading++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage as auth_storage+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from core.inference.video import VideoBackend+from hub.services.models import account_access+from routes import video+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def _arm(backend: VideoBackend, account: AccountContext) -> threading.Event:+ """What begin_generate commits under the lock: the account plus the cancel handle."""+ event = threading.Event()+ backend._generate_job_account = account.account_id+ backend._active_generate_cancel = event+ return event+++def _reserve_after_first_read(backend: VideoBackend, account: AccountContext) -> threading.Event:+ """Return the real reservation now (None), then let ``account`` reserve."""+ event = threading.Event()+ original = backend.generate_job_account+ fired = {"done": False}++ def reading():+ current = original()+ if not fired["done"]:+ fired["done"] = True+ backend._generate_job_account = account.account_id+ backend._active_generate_cancel = event+ return current++ backend.generate_job_account = reading+ return event++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ monkeypatch.setattr(video, "_generation_account", None, raising = False)+ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)+ yield+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(video.router, prefix = "/api/inference")+ return TestClient(app)+++def _install(monkeypatch, backend):+ import core.inference.video as video_module+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+++def test_idle_cancel_does_not_stop_a_render_another_account_starts_in_the_gap(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ backend = VideoBackend()+ _install(monkeypatch, backend)+ bob_event = _reserve_after_first_read(backend, BOB)++ with _client(ALICE) as client:+ body = client.post("/api/inference/video/generate/cancel").json()++ assert backend._generate_job_account == BOB.account_id+ assert not bob_event.is_set(), "alice's idle cancel stopped bob's render"+ assert body == {"cancelled": False}+++def test_idle_cancel_still_stops_the_callers_own_render_started_in_the_gap(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ backend = VideoBackend()+ _install(monkeypatch, backend)+ alice_event = _reserve_after_first_read(backend, ALICE)++ with _client(ALICE) as client:+ body = client.post("/api/inference/video/generate/cancel").json()++ assert body == {"cancelled": True}+ assert alice_event.is_set()+++def test_single_user_cancel_still_works_and_is_a_no_op_when_idle(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: OWNER.account_id)+ backend = VideoBackend()+ _install(monkeypatch, backend)++ with _client(OWNER) as client:+ assert client.post("/api/inference/video/generate/cancel").json() == {"cancelled": False}+ event = _arm(backend, OWNER)+ assert client.post("/api/inference/video/generate/cancel").json() == {"cancelled": True}+ assert event.is_set()diff --git a/studio/backend/tests/test_account_video_progress_handoff.py b/studio/backend/tests/test_account_video_progress_handoff.pynew file mode 100644index 00000000000..fc300118f25--- /dev/null+++ b/studio/backend/tests/test_account_video_progress_handoff.py@@ -0,0 +1,188 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Video generate-progress must not hand one account the successor's job.++The route reads the reservation for its visibility check and then reads the progress.+``begin_generate`` runs in a worker thread (asyncio.to_thread), so another account can take the+reservation between those two reads with no await in between: ALICE's clip finished, BOB reserved,+and ALICE's poll then returns BOB's fresh progress instead of ALICE's terminal record. The Video+page merges that terminal record to show the saved clip, so the handoff both leaks BOB's job and+makes ALICE's completed clip vanish until the gallery is refreshed.+"""++from __future__ import annotations++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage as auth_storage+from auth.authentication import get_current_subject+from core.inference import gpu_arbiter+from hub.services.models import account_access+from routes import video+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++ALICE_CLIP = {+ "id": "alice-clip",+ "url": "/api/inference/video/gallery/alice-clip/file",+ "prompt": "alice's private prompt",+ "width": 512,+ "height": 512,+ "num_frames": 49,+ "fps": 24,+ "duration_s": 2.0,+ "steps": 5,+ "guidance": 1.0,+ "seed": 1,+ "created_at": "2026-08-06T00:00:00Z",+}++ALICE_TERMINAL = {+ "active": False,+ "phase": "completed",+ "step": 5,+ "total": 5,+ "video": ALICE_CLIP,+}+BOB_FRESH = {+ "active": True,+ "phase": "queued",+ "step": 0,+ "total": 0,+ "eta_seconds": None,+ "video_id": "bob-clip",+}+++class HandoffVideoBackend:+ """ALICE owns the reservation when the route authorizes; BOB reserves right after that read.++ The handoff fires once, immediately after the FIRST read of the reservation, which is the+ earliest interleaving a worker-thread ``begin_generate`` can produce. ``generate_progress``+ mirrors the real backend: the reservation and the progress come out of ONE lock, so an+ ``expected_account`` the caller authorized is rechecked against the owner held right now.+ """++ def __init__(self, hand_off: bool = True):+ self._hand_off = hand_off+ self.job_account = ALICE.account_id+ self.progress = dict(ALICE_TERMINAL)++ def status(self):+ return {"loaded": True, "repo_id": "public/video-model"}++ def generate_job_account(self):+ current = self.job_account+ if self._hand_off:+ self._hand_off = False+ self.job_account = BOB.account_id+ self.progress = dict(BOB_FRESH)+ return current++ def generate_progress(self, expected_account = None):+ if expected_account is not None and self.job_account != expected_account:+ return None+ return dict(self.progress)+++class SoloVideoBackend:+ """A single-user backend with no reservation at all: the old path must be untouched."""++ def __init__(self):+ self.progress = dict(ALICE_TERMINAL)++ def status(self):+ return {"loaded": True, "repo_id": "public/video-model"}++ def generate_progress(self):+ return dict(self.progress)++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ monkeypatch.setattr(video, "_generation_account", None, raising = False)+ monkeypatch.setattr(gpu_arbiter, "current_owner", lambda: gpu_arbiter.VIDEO)+ monkeypatch.setattr(gpu_arbiter, "owner_account", lambda: ALICE.account_id)+ monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: True)+ yield+++def _client(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(video.router, prefix = "/api/inference")+ return TestClient(app)+++def _install(monkeypatch, backend):+ import core.inference.video as video_module+ monkeypatch.setattr(video_module, "get_video_backend", lambda: backend)+++PROGRESS = "/api/inference/video/generate-progress"+++def test_progress_does_not_follow_a_reservation_that_changed_hands(monkeypatch):+ """BOB reserves after ALICE's poll passed authorization; ALICE must not get BOB's job."""+ backend = HandoffVideoBackend(hand_off = True)+ _install(monkeypatch, backend)++ with _client(ALICE) as client:+ body = client.get(PROGRESS).json()++ assert backend.job_account == BOB.account_id+ assert body.get("video_id") != "bob-clip", "alice received bob's job progress"+ assert body == {"loaded": True, "yours": False}+++def test_progress_still_returns_the_owners_own_terminal_record(monkeypatch):+ """No handoff: ALICE keeps seeing the completed clip the Video page merges."""+ backend = HandoffVideoBackend(hand_off = False)+ _install(monkeypatch, backend)++ with _client(ALICE) as client:+ body = client.get(PROGRESS).json()++ assert body["phase"] == "completed"+ assert body["video"]["id"] == ALICE_CLIP["id"]+++def test_single_user_backend_without_a_reservation_is_unchanged(monkeypatch):+ backend = SoloVideoBackend()+ _install(monkeypatch, backend)++ with _client(ALICE) as client:+ body = client.get(PROGRESS).json()++ assert body["phase"] == "completed"+ assert body["video"]["id"] == ALICE_CLIP["id"]+++def test_real_backend_returns_none_when_the_reservation_moved():+ """The recheck lives under the same lock as the progress read."""+ from core.inference.video import VideoBackend++ backend = VideoBackend()+ backend._gen = dict(ALICE_TERMINAL)+ backend._generate_job_account = BOB.account_id+ assert backend.generate_progress(expected_account = ALICE.account_id) is None+ assert backend.generate_progress(expected_account = BOB.account_id)["phase"] == "completed"+ assert backend.generate_progress()["phase"] == "completed"diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.pyindex 5e4180f8fd2..ba124b0581e 100644--- a/studio/backend/tests/test_active_generations.py+++ b/studio/backend/tests/test_active_generations.py@@ -71,7 +71,9 @@ def test_snapshot_is_json_safe_and_ordered_by_start():assert [e["thread_id"] for e in snap] == ["first", "second"]# The threading.Event must not leak into an HTTP response body.assert all("event" not in e for e in snap)- assert {"handle", "thread_id", "run_id", "model", "kind", "started_at"} == set(snap[0])+ assert {"handle", "thread_id", "run_id", "model", "kind", "account_id", "started_at"} == set(+ snap[0]+ )def test_thread_ids_are_deduped_and_skip_unnamed_runs():diff --git a/studio/backend/tests/test_api_key_account_scope.py b/studio/backend/tests/test_api_key_account_scope.pynew file mode 100644index 00000000000..e193421c1e4--- /dev/null+++ b/studio/backend/tests/test_api_key_account_scope.py@@ -0,0 +1,143 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account's API keys are addressed by its immutable id, so a namesake recreated under a freed username cannot reach them."""++import secrets+import sqlite3++import pytest++from auth import policy, storage+++def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield storage+ policy.invalidate_account_cache()+++def _alice() -> str:+ return storage.issue_account_setup_code(username = "alice")["account"]["account_id"]+++def test_namesake_keys_stay_apart(auth_db):+ old_id = _alice()+ _raw, old_row = storage.create_api_key("alice", name = "old", account_id = old_id)+ assert old_row["account_id"] == old_id+ storage.delete_account(old_id, lambda account: None)+ new_id = _alice()+ assert new_id != old_id+ _raw, new_row = storage.create_api_key("alice", name = "NEW-PRIVATE", account_id = new_id)++ assert storage.list_api_keys("alice", account_id = old_id) == []+ assert not storage.revoke_api_key("alice", new_row["id"], account_id = old_id)+ assert [row["name"] for row in storage.list_api_keys("alice", account_id = new_id)] == [+ "NEW-PRIVATE"+ ]+ assert storage.revoke_api_key("alice", new_row["id"], account_id = new_id)+++def test_owner_keys_keep_the_username_query(auth_db):+ _raw, row = storage.create_api_key("unsloth", name = "cli")+ assert row["account_id"] is None+ assert [r["name"] for r in storage.list_api_keys("unsloth")] == ["cli"]+ assert storage.revoke_api_key("unsloth", row["id"])+++def test_existing_managed_rows_are_pinned_on_upgrade(auth_db):+ alice = _alice()+ conn = sqlite3.connect(storage.DB_PATH)+ try:+ conn.execute(+ "INSERT INTO api_keys (username, key_prefix, key_hash, name, created_at) VALUES ('alice', 'p', 'h1', 'k', 'now')"+ )+ conn.execute(+ "INSERT INTO api_keys (username, key_prefix, key_hash, name, created_at) VALUES ('unsloth', 'p', 'h2', 'k', 'now')"+ )+ conn.commit()+ storage._ensure_account_api_keys(conn, set())+ rows = dict(conn.execute("SELECT key_hash, account_id FROM api_keys").fetchall())+ finally:+ conn.close()+ assert rows["h1"] == alice and rows["h2"] is None+++def test_managed_keys_survive_an_older_builds_bulk_delete(auth_db):+ alice = _alice()+ raw, row = storage.create_api_key("alice", name = "cli", account_id = alice)+ owner_raw, _owner_row = storage.create_api_key("unsloth", name = "owner-cli")+ assert storage.validate_api_key_account(raw) is not None+ conn = sqlite3.connect(storage.DB_PATH)+ try:+ conn.execute("DELETE FROM api_keys")+ conn.commit()+ assert conn.execute("SELECT COUNT(*) FROM account_api_keys").fetchone()[0] == 1+ conn.row_factory = sqlite3.Row+ storage._account_keys_synced.clear()+ storage._ensure_account_api_keys(conn, {"account_id"})+ finally:+ conn.close()+ verified = storage.validate_api_key_account(raw)+ assert verified is not None and verified[0]["account_id"] == alice+ assert storage.validate_api_key_account(owner_raw) is None+ assert [r["name"] for r in storage.list_api_keys("alice", account_id = alice)] == ["cli"]+ restored_id = storage.list_api_keys("alice", account_id = alice)[0]["id"]+ assert storage.revoke_api_key("alice", restored_id, account_id = alice)+ conn = sqlite3.connect(storage.DB_PATH)+ conn.row_factory = sqlite3.Row+ try:+ conn.execute("DELETE FROM api_keys")+ conn.commit()+ storage._account_keys_synced.clear()+ storage._ensure_account_api_keys(conn, {"account_id"})+ finally:+ conn.close()+ assert storage.validate_api_key_account(raw) is None+++def test_deleting_an_account_removes_its_key_copy(auth_db):+ alice = _alice()+ storage.create_api_key("alice", name = "cli", account_id = alice)+ storage.delete_account(alice, lambda account: None)+ conn = sqlite3.connect(storage.DB_PATH)+ try:+ assert conn.execute("SELECT COUNT(*) FROM account_api_keys").fetchone()[0] == 0+ finally:+ conn.close()+++def test_a_managed_key_minted_without_an_explicit_scope_is_still_pinned(auth_db):+ alice = _alice()+ _raw, row = storage.create_api_key("alice", name = "data-recipe workflow", internal = True)+ assert row["account_id"] == alice+++def test_a_key_row_that_outlived_its_account_is_not_resolved_by_a_namesake(auth_db):+ old_id = _alice()+ raw, _row = storage.create_api_key("alice", name = "old", account_id = old_id)+ assert storage.validate_api_key_account(raw)[0]["account_id"] == old_id++ conn = sqlite3.connect(storage.DB_PATH)+ with conn:+ conn.execute("UPDATE auth_user SET account_id = ? WHERE username = 'alice'", ("f" * 32,))+ conn.close()+ assert storage.validate_api_key_account(raw) is None+++def test_a_managed_key_with_no_id_does_not_validate(auth_db):+ """Only the owner's key rows may carry no account id."""+ alice = _alice()+ raw, _row = storage.create_api_key("alice", name = "old-build", account_id = alice)+ conn = sqlite3.connect(storage.DB_PATH)+ with conn:+ conn.execute("UPDATE api_keys SET account_id = NULL WHERE username = 'alice'")+ conn.close()+ assert storage.validate_api_key_account(raw) is None+ owner_raw, _owner_row = storage.create_api_key("unsloth", name = "cli")+ assert storage.validate_api_key_account(owner_raw)[0]["account_id"] == "owner"diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.pyindex af70e25d50a..7bc6c34ac29 100644--- a/studio/backend/tests/test_api_monitor.py+++ b/studio/backend/tests/test_api_monitor.py@@ -612,10 +612,13 @@ def test_hidden_shared_ids_do_not_outlive_their_entries():monitor = ApiMonitor(max_entries = 2)monitor.record_lifecycle(event = "unload", model = "org/A")monitor.clear(subject = "alice")- assert monitor._hidden_shared.get("alice")+ from utils.account_context import current_account_id++ key = (current_account_id(), "alice")+ assert monitor._hidden_shared.get(key)for i in range(5):monitor.record_lifecycle(event = "unload", model = f"org/M{i}")- assert not monitor._hidden_shared.get("alice")+ assert not monitor._hidden_shared.get(key)def test_an_api_triggered_lifecycle_row_carries_the_attribution():diff --git a/studio/backend/tests/test_auth_lookup_off_event_loop.py b/studio/backend/tests/test_auth_lookup_off_event_loop.pyindex 19caaedcfc0..b6c04b522ba 100644--- a/studio/backend/tests/test_auth_lookup_off_event_loop.py+++ b/studio/backend/tests/test_auth_lookup_off_event_loop.py@@ -34,11 +34,24 @@ def _record_thread(threads: list[int], result):return _stub+def _record(secret: str) -> dict:+ return {+ "username": SUBJECT,+ "password_salt": "salt",+ "password_hash": "hash",+ "jwt_secret": secret,+ "must_change_password": 0,+ "account_id": "acct-test",+ "role": "user",+ "is_active": 1,+ }++def _jwt_case(monkeypatch, threads):monkeypatch.setattr(authentication,- "get_user_and_secret",- _record_thread(threads, ("salt", "hash", SECRET, False)),+ "get_user_record",+ _record_thread(threads, _record(SECRET)),)token = jwt.encode({"sub": SUBJECT}, SECRET, algorithm = authentication.ALGORITHM)return authentication.get_current_subject(_credentials(token))@@ -47,8 +60,8 @@ def _jwt_case(monkeypatch, threads):def _api_key_case(monkeypatch, threads):monkeypatch.setattr(authentication,- "validate_api_key_with_credential",- _record_thread(threads, (SUBJECT, SECRET)),+ "validate_api_key_account",+ _record_thread(threads, (_record(SECRET), SECRET)),)return authentication.get_current_subject(_credentials(f"{API_KEY_PREFIX}key"))diff --git a/studio/backend/tests/test_auth_schema_concurrency.py b/studio/backend/tests/test_auth_schema_concurrency.pynew file mode 100644index 00000000000..ae1d3c1917b--- /dev/null+++ b/studio/backend/tests/test_auth_schema_concurrency.py@@ -0,0 +1,59 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Concurrent first opens of auth.db add the account columns exactly once, and a loser never raises."""++from concurrent.futures import ThreadPoolExecutor++import pytest++from auth import policy, storage+++def fresh_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth" / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ yield+ policy.invalidate_account_cache()+++def _open_and_close():+ conn = storage.get_connection()+ try:+ return {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}+ finally:+ conn.close()++[email protected]("round_", range(6))+def test_concurrent_first_opens_never_raise(fresh_db, round_):+ with ThreadPoolExecutor(max_workers = 8) as pool:+ columns = list(pool.map(lambda _i: _open_and_close(), range(8)))+ expected = {name for name, _decl in storage._ACCOUNT_COLUMNS}+ for seen in columns:+ assert expected <= seen+++def test_legacy_table_is_migrated_once_under_contention(fresh_db):+ import sqlite3++ storage.DB_PATH.parent.mkdir(parents = True)+ conn = sqlite3.connect(storage.DB_PATH)+ conn.execute(+ "CREATE TABLE auth_user (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, "+ "password_salt TEXT NOT NULL, password_hash TEXT NOT NULL, jwt_secret TEXT NOT NULL, "+ "must_change_password INTEGER NOT NULL DEFAULT 0)"+ )+ conn.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret) VALUES ('unsloth', 's', 'h', 'j')"+ )+ conn.commit()+ conn.close()+ with ThreadPoolExecutor(max_workers = 8) as pool:+ list(pool.map(lambda _i: _open_and_close(), range(16)))+ record = storage.get_user_record("unsloth")+ assert record["account_id"] == "owner" and record["role"] == "owner"+ assert record["jwt_secret"] == "j"diff --git a/studio/backend/tests/test_chat_attachments.py b/studio/backend/tests/test_chat_attachments.pyindex 459587ca9e9..482ece1b6ef 100644--- a/studio/backend/tests/test_chat_attachments.py+++ b/studio/backend/tests/test_chat_attachments.py@@ -26,7 +26,7 @@ PNG_DATA_URL = "data:image/png;base64," + base64.b64encode(PNG_BYTES).decode("asdef _reset_studio_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())def _thread(diff --git a/studio/backend/tests/test_chat_generation_lease_compat.py b/studio/backend/tests/test_chat_generation_lease_compat.pyindex 3aeb4638dae..0fe6df3a16a 100644--- a/studio/backend/tests/test_chat_generation_lease_compat.py+++ b/studio/backend/tests/test_chat_generation_lease_compat.py@@ -98,7 +98,7 @@ def _drop_lease_columns():for column in ("progress_at", "progress_tokens"):conn.execute(f"ALTER TABLE chat_generation_runs DROP COLUMN {column}")conn.commit()- runs_db._schema_ready = False+ runs_db._schema_ready = set()# --------------------------------------------------------------------------- upgrade@@ -112,7 +112,7 @@ def test_migration_adds_both_columns(clock):def test_migration_is_idempotent(clock):_seed()for _ in range(5):- runs_db._schema_ready = False+ runs_db._schema_ready = set()runs_db._connect()assert {"progress_at", "progress_tokens"} <= _columns()@@ -122,7 +122,7 @@ def test_upgrade_over_an_existing_database_preserves_rows(clock):token = _seed("run-old")_drop_lease_columns()assert "progress_at" not in _columns() or True # DROP may be unsupported; see below- runs_db._schema_ready = False+ runs_db._schema_ready = set()runs_db._connect()assert {"progress_at", "progress_tokens"} <= _columns()run = runs_db.get_run("run-old")@@ -148,17 +148,17 @@ def test_pre_upgrade_rows_have_a_usable_lease_fallback(clock):def test_missing_table_does_not_raise(monkeypatch, clock):# A database whose schema has not been created yet must not turn a history read# into a crash.- runs_db._schema_ready = False+ runs_db._schema_ready = set()conn = runs_db._connect()conn.execute("DROP TABLE IF EXISTS chat_generation_runs")conn.commit()- runs_db._schema_ready = False+ runs_db._schema_ready = set()runs_db._connect() # must not raisedef test_concurrent_migration_from_many_threads(clock):_seed()- runs_db._schema_ready = False+ runs_db._schema_ready = set()errors: list[BaseException] = []barrier = threading.Barrier(8)@@ -182,7 +182,7 @@ def test_duplicate_column_error_is_swallowed(clock, monkeypatch):# Another process migrated between our PRAGMA and our ALTER._seed()_drop_lease_columns() # otherwise the ALTER is skipped and the race cannot fire- runs_db._schema_ready = False+ runs_db._schema_ready = set()real_get = runs_db.get_connectionstate = {"fired": False}@@ -370,7 +370,7 @@ def _migration_blocked(monkeypatch):columns. This is the window the degradations below have to survive."""_drop_lease_columns()- runs_db._schema_ready = False+ runs_db._schema_ready = set()real_get = runs_db.get_connectionclass _Locked:@@ -390,7 +390,7 @@ def _migration_blocked(monkeypatch):yieldfinally:monkeypatch.setattr(runs_db, "get_connection", real_get)- runs_db._schema_ready = False+ runs_db._schema_ready = set()def test_streaming_survives_a_migration_still_blocked_by_a_writer(clock, monkeypatch):diff --git a/studio/backend/tests/test_chat_generation_run_account_sweep.py b/studio/backend/tests/test_chat_generation_run_account_sweep.pynew file mode 100644index 00000000000..cc98810edcd--- /dev/null+++ b/studio/backend/tests/test_chat_generation_run_account_sweep.py@@ -0,0 +1,169 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Regression: the lease sweep must not cancel a different account's live run.++Run ids are client chosen and the run rows live in per-account databases, so two accounts+can legitimately hold the same id. The supervisor keys its tasks, cancel events and+reservations by bare run id, so flattening every account's reconciled ids into one list and+calling supervisor.cancel(run_id) lets one account's aged row stop another account's live+generation.+"""++from __future__ import annotations++import asyncio+import secrets+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import chat_generation_runs as runs_mod # noqa: E402+from core.inference.chat_generation_runs import ( # noqa: E402+ ChatGenerationLeaseSweeper,+ ChatGenerationSupervisor,+)+from storage import chat_generation_runs_db as runs_db # noqa: E402+from storage import studio_db # noqa: E402++_MINUTE_MS = 60_000+++class _Clock:+ def __init__(self, start = 1_700_000_000_000):+ self.now = int(start)++ def __call__(self):+ return self.now++ def advance_ms(self, ms):+ self.now += int(ms)+++def clock(monkeypatch):+ fake = _Clock()+ monkeypatch.setattr(runs_db, "now_ms", fake)+ return fake+++def _running_run(+ owner,+ run_id = "run-1",+ thread_id = "thread-1",+):+ studio_db.upsert_chat_thread(+ {+ "id": thread_id,+ "title": "Chat",+ "modelType": "base",+ "modelId": "local.gguf",+ "createdAt": 1,+ }+ )+ studio_db.upsert_chat_message(+ {+ "id": f"user-{run_id}",+ "threadId": thread_id,+ "role": "user",+ "content": [{"type": "text", "text": "Hello"}],+ "createdAt": 2,+ }+ )+ runs_db.create_run(+ run_id = run_id,+ owner_subject = owner,+ thread_id = thread_id,+ user_message_id = f"user-{run_id}",+ assistant_message_id = f"assistant-{run_id}",+ request_payload = {+ "model": "local.gguf",+ "messages": [{"role": "user", "content": "Hello"}],+ "stream": True,+ },+ )+ token = runs_db.get_worker_token(run_id)+ assert runs_db.mark_running(run_id, token)+ return token+++async def test_sweep_does_not_cancel_another_accounts_run_with_the_same_id(+ clock, tmp_path, monkeypatch+):+ from auth import policy, storage+ from state import active_generations+ from utils.account_context import AccountContext, run_as++ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth" / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / "auth" / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ try:+ alice = AccountContext(+ storage.issue_account_setup_code(username = "alice")["account"]["account_id"], "alice"+ )+ bob = AccountContext(+ storage.issue_account_setup_code(username = "bob")["account"]["account_id"], "bob"+ )+ policy.invalidate_account_cache()++ # Alice's row committed but her producer was never registered (supervisor.start+ # never ran, or the process restarted), so nothing live holds the id.+ run_as(alice, lambda: _running_run("alice"))+ clock.advance_ms(11 * _MINUTE_MS)++ app = SimpleNamespace(state = SimpleNamespace())+ supervisor = ChatGenerationSupervisor(app)+ app.state.chat_generation_supervisor = supervisor+ started = asyncio.Event()++ async def _produce(+ run_id,+ cancel_event = None,+ activity = None,+ ):+ started.set()+ await asyncio.sleep(3600)++ monkeypatch.setattr(supervisor, "_produce", _produce)++ # Bob may reuse the client-chosen id: the route only refuses ids held by a LIVE+ # registration, and Alice's stale row has none.+ assert [e for e in active_generations.snapshot() if e["run_id"] == "run-1"] == []++ def _start_bob():+ _running_run("bob")+ supervisor.start("run-1", thread_id = "thread-1", model = "local.gguf")++ run_as(bob, _start_bob)+ for _ in range(100):+ if started.is_set():+ break+ await asyncio.sleep(0.01)+ assert started.is_set(), "Bob's producer never started"+ bob_event = supervisor._cancel_events["run-1"]+ bob_task = supervisor._tasks["run-1"]+ bob_registration = [e for e in active_generations.snapshot() if e["run_id"] == "run-1"]+ assert [e["account_id"] for e in bob_registration] == [bob.account_id]++ sweeper = ChatGenerationLeaseSweeper(app, interval_s = 60.0, timeout_s = 600.0)+ settled = await sweeper.sweep_once()+ assert settled == ["run-1"]+ assert run_as(alice, lambda: runs_db.get_run("run-1", "alice"))["status"] == "failed"++ assert (+ not bob_event.is_set()+ ), "the sweep cancelled another account's live run that happens to share the id"+ assert not bob_task.done()+ assert run_as(bob, lambda: runs_db.get_run("run-1", "bob"))["status"] == "running"+ bob_task.cancel()+ finally:+ policy.invalidate_account_cache()diff --git a/studio/backend/tests/test_chat_generation_run_lease.py b/studio/backend/tests/test_chat_generation_run_lease.pyindex 7b958276def..c1eacb610d4 100644--- a/studio/backend/tests/test_chat_generation_run_lease.py+++ b/studio/backend/tests/test_chat_generation_run_lease.py@@ -543,3 +543,38 @@ async def test_stopping_the_sweeper_does_not_spend_the_desktop_exit_budget(monkeawait sweeper.stop()elapsed = _time.monotonic() - startedassert elapsed < 2.0, f"sweeper.stop() took {elapsed:.2f}s of the graceful-exit budget"+++def test_sweep_still_reaps_a_deactivated_accounts_stalled_run(clock, tmp_path, monkeypatch):+ """Deactivation only sets the cancel event; a wedged producer keeps its GPU reservation."""+ import secrets++ from auth import policy, storage+ from utils.account_context import AccountContext, run_as++ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth" / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / "auth" / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ try:+ record = storage.issue_account_setup_code(username = "alice")["account"]+ alice = AccountContext(record["account_id"], "alice")+ run_as(alice, _running_run)+ clock.advance_ms(11 * _MINUTE_MS)+ storage.set_account_active(record["account_id"], False)+ policy.invalidate_account_cache()+ assert policy.installation_is_multi_user() is False+ cancelled = []+ app = SimpleNamespace(+ state = SimpleNamespace(+ chat_generation_supervisor = SimpleNamespace(cancel = cancelled.append)+ )+ )+ assert asyncio.run(_sweeper(app, timeout_s = 600.0).sweep_once()) == ["run-1"]+ assert cancelled == ["run-1"]+ assert run_as(alice, lambda: runs_db.get_run("run-1", "alice"))["finishReason"] == (+ "interrupted"+ )+ finally:+ policy.invalidate_account_cache()diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex af8fdb74e25..d07b337b1c4 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -897,7 +897,7 @@ def test_a_clear_does_not_reap_an_image_registered_while_it_was_running(tmp_pathmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())monkeypatch.setattr(search_images, "_registry", {})monkeypatch.setattr(search_images, "_cleared_unservable", set())monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")@@ -978,7 +978,7 @@ def test_replayed_clear_keeps_the_thumbnails_of_a_chat_it_did_not_delete(tmp_patmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())reaped: list[str] = []monkeypatch.setattr(search_images, "clear_cache", lambda only_ids = None: reaped.append("reaped"))@@ -1034,7 +1034,7 @@ def test_the_replay_bit_comes_from_the_clear_transaction(monkeypatch, tmp_path):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())reaps: list[str] = []reap_lock = threading.Lock()@@ -1127,7 +1127,7 @@ def test_a_chat_created_in_the_gap_after_the_clear_keeps_its_images(monkeypatch,monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())monkeypatch.setattr(search_images, "_registry", {})monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)@@ -1193,12 +1193,15 @@ def test_the_clear_and_its_image_snapshot_share_one_threadpool_hop():source = inspect.getsource(chat_history.clear_history)assert source.count("run_in_threadpool(_clear_rows)") == 1assert (- "run_in_threadpool(snapshot_and_fence_registrations)" not in source+ "run_in_threadpool(_snapshot_chat_images)" not in source), "a second hop for the snapshot reopens the gap the first one closed"body = source.split("def _clear_rows(", 1)[1].split("\n # The clear reports", 1)[0]assert (- "snapshot_and_fence_registrations()" in body+ "_snapshot_chat_images()" in body), "the snapshot belongs inside the clear's hop, and it carries the registration fence"+ assert "snapshot_and_fence_registrations()" in inspect.getsource(+ chat_history._snapshot_chat_images+ )def test_a_replay_finishes_a_reap_the_original_clear_died_before_running(monkeypatch, tmp_path):@@ -1219,7 +1222,7 @@ def test_a_replay_finishes_a_reap_the_original_clear_died_before_running(monkeypmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())monkeypatch.setattr(search_images, "_registry", {})monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)@@ -1297,7 +1300,7 @@ def test_a_plain_replay_with_nothing_outstanding_still_reaps_nothing(monkeypatchmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())monkeypatch.setattr(search_images, "_registry", {})monkeypatch.setattr(search_images, "_cache_dir", lambda: tmp_path / "thumbs")(tmp_path / "thumbs").mkdir(parents = True, exist_ok = True)diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex f1180062c83..8a9db2e763f 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -25,7 +25,7 @@ def _reset_studio_db("UNSLOTH_STUDIO_PROJECTS_HOME",str(projects_home if projects_home is not None else tmp_path / "Projects"),)- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())@pytest.fixturediff --git a/studio/backend/tests/test_chat_thread_settings.py b/studio/backend/tests/test_chat_thread_settings.pyindex e544469d96d..ba678ca129f 100644--- a/studio/backend/tests/test_chat_thread_settings.py+++ b/studio/backend/tests/test_chat_thread_settings.py@@ -50,7 +50,7 @@ SETTINGS = {def _reset_studio_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())def _thread(thread_id: str = "thread-1", **extra) -> dict:@@ -475,7 +475,7 @@ def test_the_watermark_column_is_added_to_an_existing_database(tmp_path, monkeypconn.commit()finally:conn.close()- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.write_chat_thread_settings("thread-1", replace = {"toolsEnabled": True}, seq = 1, writer = "tab-a"diff --git a/studio/backend/tests/test_consent_gate.py b/studio/backend/tests/test_consent_gate.pyindex 00b58fb7156..58dbf13c757 100644--- a/studio/backend/tests/test_consent_gate.py+++ b/studio/backend/tests/test_consent_gate.py@@ -427,6 +427,28 @@ class TestConsentGate:assert d.blocked is Trueassert d.approvable is False+ def test_managed_account_is_refused_before_the_scan(self, monkeypatch):+ from utils.account_context import AccountContext, run_as++ monkeypatch.delenv(consent.MANAGED_REMOTE_CODE_OVERRIDE, raising = False)+ with (+ patch.object(consent, "_config_has_auto_map", return_value = True),+ patch.object(+ consent, "repo_remote_code_files", return_value = {"m.py": "import torch\n"}+ ),+ patch.object(consent, "scan_remote_code_files") as scan,+ ):+ d = run_as(+ AccountContext("b" * 32, "bob"),+ evaluate_remote_code_consent_for_targets,+ ["org/model"],+ trust_remote_code = True,+ approved_fingerprint = "anything",+ )+ assert d.blocked is True and d.approvable is False+ assert d.reason == consent.MANAGED_REMOTE_CODE_REFUSAL+ scan.assert_not_called()+def test_medium_severity_blocks_pending_approval(self):# A MEDIUM finding is approvable but blocks until pinned, so trust_remote_code=True alone# cannot run flagged code. MEDIUM is rarely emitted, so the scan result is mocked.diff --git a/studio/backend/tests/test_cpu_media_load_foreign_fence.py b/studio/backend/tests/test_cpu_media_load_foreign_fence.pynew file mode 100644index 00000000000..e9ed453a26d--- /dev/null+++ b/studio/backend/tests/test_cpu_media_load_foreign_fence.py@@ -0,0 +1,134 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A CPU-only media load must re-check for foreign generations before it touches the backend.++The GPU path re-asks ``require_no_foreign_generations`` right before engine activation, and the+arbiter re-asks it again under its lock. The CPU path takes neither, so a generation another+account starts while this load is still validating (a multi-second window of Hub / header reads)+is cancelled or replaced by ``begin_load``, which signals the active generation with no regard+for who owns it.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from core.inference import gpu_arbiter as arb+from hub.services.models import account_access+from state import active_generations as generations+from utils.account_context import AccountContext, arun_as, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(arb, "_owner", None)+ monkeypatch.setattr(arb, "_owner_account", None)+ monkeypatch.setattr(arb, "_owner_epoch", 0)+ monkeypatch.setattr(account_access, "_generation_accounts", {})+ monkeypatch.setattr(account_access, "_generation_holders", {})+ generations.reset_for_tests()+ yield+ generations.reset_for_tests()+++def foreign_generation():+ """Start ALICE's image/video generation on demand, mid-load."""+ state = {}++ def start(modality):+ token = bind_account(ALICE)+ try:+ ctx = account_access.media_generation_slot(modality)+ ctx.__enter__()+ finally:+ reset_account(token)+ state["ctx"] = ctx++ yield start+ ctx = state.pop("ctx", None)+ if ctx is not None:+ ctx.__exit__(None, None, None)++[email protected]("modality", ["image", "video"])+def test_cpu_media_load_refuses_a_generation_started_mid_load(+ monkeypatch, foreign_generation, modality+):+ from core.inference import (+ diffusion,+ diffusion_compat,+ diffusion_device,+ diffusion_engine_router,+ video,+ )+ from models.inference import DiffusionLoadRequest, VideoLoadRequest+ from routes import inference as route+ from routes import video as video_route++ touched = []+ backend = SimpleNamespace(+ validate_load_request = lambda *_a, **_k: SimpleNamespace(name = "ltx-2", base_repo = None),+ preflight_base_access = lambda *_a, **_k: None,+ assert_precision_available = lambda *_a, **_k: None,+ begin_load = lambda *_a, **_k: touched.append("load") or {},+ )++ async def ordinal(*_args):+ return None++ def start_foreign(*_a, **_k):+ # The window: another account's generation registers while this load is still validating.+ foreign_generation("diffusion" if modality == "image" else "video")++ monkeypatch.setattr(diffusion, "get_diffusion_backend", lambda: backend)+ monkeypatch.setattr(diffusion, "resolve_local_single_file", lambda *_a, **_k: None)+ monkeypatch.setattr(video, "get_video_backend", lambda: backend)+ monkeypatch.setattr(video, "assert_video_precision_available", lambda *_a, **_k: None)+ monkeypatch.setattr(+ diffusion_device, "resolve_diffusion_device_target", lambda: SimpleNamespace(device = "cpu")+ )+ monkeypatch.setattr(diffusion_engine_router, "predict_engine", lambda *_a, **_k: "sd_cpp")+ monkeypatch.setattr(diffusion_engine_router, "engine_for", lambda *_a: backend)+ monkeypatch.setattr(diffusion_engine_router, "active_engine_name", lambda: "sd_cpp")+ monkeypatch.setattr(+ diffusion_engine_router,+ "select_and_activate_engine",+ lambda *_a, **_k: touched.append("activate") or backend,+ )+ monkeypatch.setattr(diffusion_engine_router, "begin_load_on", lambda _e, start: start())+ monkeypatch.setattr(diffusion_compat, "assert_pick_is_not_speech", start_foreign)+ monkeypatch.setattr(route, "_guard_diffusion_load_against_training", lambda: None)+ monkeypatch.setattr(route, "_selected_gpu_ordinal", ordinal)+ monkeypatch.setattr(route, "_assert_native_precision_unset", lambda **_k: None)+ monkeypatch.setattr(video_route, "_guard_video_load_against_training", lambda: None)+ monkeypatch.setattr(video_route, "_selected_gpu_ordinal", ordinal)+ monkeypatch.setattr(account_access, "require_media_references", lambda *_a, **_k: None)+ monkeypatch.setattr(account_access, "require_model_access", lambda *_a, **_k: None)+ monkeypatch.setattr(account_access, "account_hf_token", lambda token = None: token)+ monkeypatch.setattr(account_access, "note_resident_account", lambda *_a, **_k: None)+ monkeypatch.setattr(account_access, "note_resident_components", lambda *_a, **_k: None)++ if modality == "image":+ request = DiffusionLoadRequest(model_path = "org/image", gguf_filename = "model.gguf")+ load = route.load_diffusion_model_gated+ else:+ request = VideoLoadRequest(model_path = "org/video", gguf_filename = "model.gguf")+ load = video_route.load_video_model_gated++ with pytest.raises(HTTPException) as refused:+ asyncio.run(arun_as(BOB, load(request, BOB.username)))+ assert refused.value.status_code == 409+ assert refused.value.detail["error"] == "gpu_busy"+ # Nothing was activated and nothing was loaded: ALICE's generation still owns the backend.+ assert touched == []diff --git a/studio/backend/tests/test_credential_routes.py b/studio/backend/tests/test_credential_routes.pyindex bc409d855d4..e9eda146bca 100644--- a/studio/backend/tests/test_credential_routes.py+++ b/studio/backend/tests/test_credential_routes.py@@ -83,11 +83,11 @@ def isolated_databases(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):"get_or_create_credential_encryption_key",auth_storage.get_or_create_credential_encryption_key,)- providers_db._schema_ready = False- credential_secrets._schema_ready = False+ providers_db._schema_ready = set()+ credential_secrets._schema_ready = set()yield- providers_db._schema_ready = False- credential_secrets._schema_ready = False+ providers_db._schema_ready = set()+ credential_secrets._schema_ready = set()auth_storage._credential_encryption_key_cache = None@@ -605,7 +605,7 @@ def test_provider_model_and_connection_routes_use_saved_key(monkeypatch):credential_secrets.save_hf_token("hf-after-restart")auth_storage._credential_encryption_key_cache = None- credential_secrets._schema_ready = False+ credential_secrets._schema_ready = set()assert (settings_route.get_hugging_face_token("alice", via_api_key = False).token== "hf-after-restart"diff --git a/studio/backend/tests/test_credential_secrets.py b/studio/backend/tests/test_credential_secrets.pyindex 8b5eea78ddb..7b5bb56b026 100644--- a/studio/backend/tests/test_credential_secrets.py+++ b/studio/backend/tests/test_credential_secrets.py@@ -39,9 +39,9 @@ def isolated_databases(tmp_path, monkeypatch):"get_or_create_credential_encryption_key",auth_storage.get_or_create_credential_encryption_key,)- credential_secrets._schema_ready = False+ credential_secrets._schema_ready = set()yield studio_db- credential_secrets._schema_ready = False+ credential_secrets._schema_ready = set()auth_storage._credential_encryption_key_cache = None@@ -101,7 +101,7 @@ def test_tampering_and_key_loss_fail_closed(isolated_databases):def test_repeated_schema_initialization_and_concurrent_upserts():credential_secrets.get_connection().close()- credential_secrets._schema_ready = False+ credential_secrets._schema_ready = set()credential_secrets.get_connection().close()with ThreadPoolExecutor(max_workers = 4) as pool:diff --git a/studio/backend/tests/test_deep_research_handoff_simulation.py b/studio/backend/tests/test_deep_research_handoff_simulation.pyindex 6ec858b0097..b407efe7794 100644--- a/studio/backend/tests/test_deep_research_handoff_simulation.py+++ b/studio/backend/tests/test_deep_research_handoff_simulation.py@@ -42,7 +42,7 @@ REFINED = "Which small dog breeds suit a flat with no garden?"@pytest.fixturedef research_home(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "thread-1",diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex 2c23e6204cc..e6f232f66fa 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -709,7 +709,7 @@ def test_reset_password_removes_desktop_secret_files(tmp_path, monkeypatch):"get_or_create_credential_encryption_key",auth_storage.get_or_create_credential_encryption_key,)- credential_secrets._schema_ready = False+ credential_secrets._schema_ready = set()secret = studio_cli._create_desktop_secret_in_cli()studio_cli._write_auth_secret(auth_dir / studio_cli.DESKTOP_SECRET_FILE, secret)@@ -745,7 +745,7 @@ def test_reset_password_removes_desktop_secret_files(tmp_path, monkeypatch):assert credential_key is not Noneauth_storage._credential_encryption_key_cache = Noneassert credential_secrets.get_hf_token() == "hf_survives_reset"- credential_secrets._schema_ready = False+ credential_secrets._schema_ready = set()auth_storage._credential_encryption_key_cache = None@@ -816,6 +816,8 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):whisper_module.router = APIRouter()profile_stats_module = ModuleType("routes.profile_stats")profile_stats_module.router = APIRouter()+ accounts_module = ModuleType("routes.accounts")+ accounts_module.router = APIRouter()# Derived from main.py's import block, not hand-listed: the old hardcoded dict went stale# twice (#8511's openai_codex_auth_router, #8648's youtube_router), each time killing every@@ -838,6 +840,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes.preview", preview_module)monkeypatch.setitem(sys.modules, "routes.whisper", whisper_module)monkeypatch.setitem(sys.modules, "routes.profile_stats", profile_stats_module)+ monkeypatch.setitem(sys.modules, "routes.accounts", accounts_module)import studio.backend.main as backend_maindiff --git a/studio/backend/tests/test_diffusion_compat_preflight.py b/studio/backend/tests/test_diffusion_compat_preflight.pyindex 4793d8b5391..aaaa1b1454c 100644--- a/studio/backend/tests/test_diffusion_compat_preflight.py+++ b/studio/backend/tests/test_diffusion_compat_preflight.py@@ -1411,10 +1411,14 @@ def test_both_media_routes_refuse_a_speech_pick_before_taking_the_gpu():# The CALL, not the import line at the top of each route, which names acquire_for far earlier.for source, acquire, label in (- (inspect.getsource(video_route.load_video_model_gated), "acquire_for(VIDEO", "video"),+ (+ inspect.getsource(video_route.load_video_model_gated),+ "acquire_for_request(VIDEO",+ "video",+ ),(inspect.getsource(inference_route.load_diffusion_model_gated),- "acquire_for(DIFFUSION",+ "acquire_for_request(DIFFUSION","images",),):diff --git a/studio/backend/tests/test_embedding_model_security_gate.py b/studio/backend/tests/test_embedding_model_security_gate.pyindex c0b057b724b..45b4e99a499 100644--- a/studio/backend/tests/test_embedding_model_security_gate.py+++ b/studio/backend/tests/test_embedding_model_security_gate.py@@ -388,6 +388,9 @@ def test_active_backend_is_llama_reflects_cache_and_resolver(monkeypatch):def test_settings_scan_scopes_module_subdirs(monkeypatch):# The settings scan must pass the ST module dirs (0_Transformer/) as load roots so a# pickle directly under one blocks; assert those subdirs reach evaluate_file_security.+ from utils import utils as studio_utils++ monkeypatch.setattr(studio_utils, "hf_env_offline", lambda: False)saved: dict = {}monkeypatch.setattr(settings, "default_embedding_model", lambda: "unsloth/default-embed")monkeypatch.setattr(settings, "validate_embedding_model", lambda v: v)@@ -643,6 +646,9 @@ def test_the_resolved_repo_is_what_gets_verified_and_scanned(client, monkeypatchis_embedding_model and the malware scan against the literal name: a repo thatusually does not exist (fail-open, or a forceable 409) or, worse, a differenttop-level repo that does."""+ from utils import utils as studio_utils++ monkeypatch.setattr(studio_utils, "hf_env_offline", lambda: False)c, saved = clientseen = {}diff --git a/studio/backend/tests/test_embedding_model_settings.py b/studio/backend/tests/test_embedding_model_settings.pyindex 47eea251ce1..ecb25cfac10 100644--- a/studio/backend/tests/test_embedding_model_settings.py+++ b/studio/backend/tests/test_embedding_model_settings.py@@ -155,7 +155,10 @@ def test_a_concurrent_save_is_not_reverted_by_a_late_pending_clear(settings_storstale = ems._get_stored_state() # A's loader has read itassert stale[1] == "org/a" and stale[4] is Trueems.set_rag_embedding_model("org/b", gguf_repo = "org/b-GGUF", backend = "sentence-transformers")- ems._cached = (0.0, stale) # its 2s snapshot still says A+ ems._cached[("owner", ems.EMBEDDING_RESOLUTION_SETTING_KEY)] = (+ 0.0,+ stale,+ ) # its 2s snapshot still says Aassert ems.clear_stored_download_pending("org/a") is Falseems._invalidate_cache()@@ -399,3 +402,18 @@ def test_pinning_a_model_memoizes_what_was_resolved_for_it(settings_store, monke"mirror/off-convention-GGUF")assert ems.get_stored_backend("org/embedder-a") == "llama-server"+++def test_the_per_identity_cache_is_bounded(settings_store, monkeypatch):+ ems._cached.clear()+ ems._generation.clear()+ for index in range(ems._CACHE_MAX * 2):+ monkeypatch.setattr(ems, "current_account_id", lambda index = index: f"account-{index}")+ ems._get_stored_state()+ assert len(ems._cached) <= ems._CACHE_MAX+ assert (+ f"account-{ems._CACHE_MAX * 2 - 1}",+ ems.EMBEDDING_RESOLUTION_SETTING_KEY,+ ) in ems._cached+ ems._cached.clear()+ ems._generation.clear()diff --git a/studio/backend/tests/test_external_tool_truncated_and_budget.py b/studio/backend/tests/test_external_tool_truncated_and_budget.pyindex 9f3b9d49342..ef9d78e68ad 100644--- a/studio/backend/tests/test_external_tool_truncated_and_budget.py+++ b/studio/backend/tests/test_external_tool_truncated_and_budget.py@@ -373,7 +373,7 @@ def test_truncated_mcp_call_card_carries_server_display_name(tmp_path, monkeypatfrom storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())mcp_servers_db.create_server(id = "srv1", display_name = "GitHub", url = "https://a/m")turn = [@@ -404,7 +404,7 @@ def test_budget_exhausted_mcp_card_carries_server_display_name(tmp_path, monkeypfrom storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())mcp_servers_db.create_server(id = "srv1", display_name = "GitHub", url = "https://a/m")turns = [diff --git a/studio/backend/tests/test_folder_sync_account_rotation.py b/studio/backend/tests/test_folder_sync_account_rotation.pynew file mode 100644index 00000000000..ad5e05f63e7--- /dev/null+++ b/studio/backend/tests/test_folder_sync_account_rotation.py@@ -0,0 +1,56 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Linked-folder scheduling must rotate between accounts instead of restarting at the first one."""++from __future__ import annotations++import pytest++from utils.account_context import AccountContext, current_account++ALICE = AccountContext("alice-job-account", "alice")+BOB = AccountContext("bob-job-account", "bob")+++def folder_sync(monkeypatch):+ from core.rag import folder_sync as module++ monkeypatch.setattr(module, "job_accounts", lambda: [ALICE, BOB])+ monkeypatch.setattr(module, "_last_job_account", None, raising = False)+ return lambda next_job: monkeypatch.setattr(module, "_next_job", next_job) or module+++def test_folder_sync_claim_rotates_across_accounts(folder_sync):+ """A busy account must not starve the next one; the worker reconciles one folder at a time."""+ queued = {+ ALICE.account_id: ["alice-1", "alice-2", "alice-3"],+ BOB.account_id: ["bob-1"],+ }++ def next_job():+ pending = queued[current_account().account_id]+ job = pending.pop(0) if pending else None+ return (job, f"folder-{job}") if job else None++ module = folder_sync(next_job)+ claimed = [module._next_account_job() for _ in range(3)]+ assert [account for account, _, _ in claimed] == [ALICE, BOB, ALICE]+ assert [job for _, job, _ in claimed] == ["alice-1", "bob-1", "alice-2"]+++def test_a_continuous_backlog_does_not_starve_the_next_accounts_pending_sync(folder_sync):+ """Alice keeps queueing successor syncs; Bob's pending job must still be reached."""+ counter = {"n": 0}+ bob_pending = ["bob-1"]++ def next_job():+ if current_account() == ALICE:+ counter["n"] += 1+ return (f"alice-{counter['n']}", "folder-alice")+ return (bob_pending.pop(0), "folder-bob") if bob_pending else None++ module = folder_sync(next_job)+ selected = [module._next_account_job()[0] for _ in range(20)]+ assert BOB in selected, "an account with a continuous backlog starved every other account"diff --git a/studio/backend/tests/test_gpu_arbiter.py b/studio/backend/tests/test_gpu_arbiter.pyindex c2b06e44a65..7fc7515c723 100644--- a/studio/backend/tests/test_gpu_arbiter.py+++ b/studio/backend/tests/test_gpu_arbiter.py@@ -349,3 +349,34 @@ def test_the_safetensors_load_yields_a_gpu_it_lost_while_loading():guard = tail.index("if chat_load_needs_gpu and current_owner() != CHAT:")assert "await asyncio.to_thread(backend.unload_model, config.identifier)" in tail[guard:]assert tail.index("status_code = 409", guard) > guard+++def test_restore_owner_account_returns_residency_to_the_displaced_account(calls, monkeypatch):+ from utils.account_context import AccountContext, run_as++ alice, bob = AccountContext("a" * 32, "alice"), AccountContext("b" * 32, "bob")+ monkeypatch.setattr(arb, "_owner_account", None)+ monkeypatch.setattr(arb, "_prior_account", None)+ run_as(alice, arb.acquire_for, arb.VIDEO, lambda: None)+ run_as(bob, arb.acquire_for, arb.VIDEO, lambda: None)+ assert arb.owner_account() == bob.account_id+ assert run_as(bob, arb.restore_owner_account, arb.VIDEO) is True+ assert arb.owner_account() == alice.account_id+ assert run_as(alice, arb.restore_owner_account, arb.VIDEO) is False+++def test_restore_owner_account_is_a_noop_once_someone_else_holds_residency(calls, monkeypatch):+ from utils.account_context import AccountContext, run_as++ alice, bob, carol = (+ AccountContext("a" * 32, "alice"),+ AccountContext("b" * 32, "bob"),+ AccountContext("c" * 32, "carol"),+ )+ monkeypatch.setattr(arb, "_owner_account", None)+ monkeypatch.setattr(arb, "_prior_account", None)+ run_as(alice, arb.acquire_for, arb.VIDEO, lambda: None)+ run_as(bob, arb.acquire_for, arb.VIDEO, lambda: None)+ run_as(carol, arb.acquire_for, arb.VIDEO, lambda: None)+ assert run_as(bob, arb.restore_owner_account, arb.VIDEO) is False+ assert arb.owner_account() == carol.account_iddiff --git a/studio/backend/tests/test_gpu_arbitration_sim.py b/studio/backend/tests/test_gpu_arbitration_sim.pynew file mode 100644index 00000000000..13ea2e482ae--- /dev/null+++ b/studio/backend/tests/test_gpu_arbitration_sim.py@@ -0,0 +1,818 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Deterministic account/GPU simulations without a GPU: backends are recorders, the arbiter and route guards are real."""++from __future__ import annotations++import asyncio+import itertools+import sqlite3+import threading+import time+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from core.inference import gpu_arbiter as arb+from core.inference import llama_admission as admission+from core.inference import llama_keepwarm as keepwarm+from core.inference import media_auto_switch as media+from core.inference import media_keepwarm+from core.inference import media_switch_backends as media_backends+from core.inference import local_model_resolver as resolver+from core.inference.media_model_index import MediaModelPick+from state import active_generations as generations+from utils import openai_auto_switch_settings as settings+from utils.account_context import OWNER, AccountContext, arun_as, current_account_id, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+CAROL = AccountContext("c" * 32, "carol")+ACCOUNTS = (ALICE, BOB, CAROL)+BACKENDS = (arb.CHAT, arb.DIFFUSION, arb.VIDEO)++[email protected](autouse = True)+def isolated(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(arb, "_owner", None)+ monkeypatch.setattr(arb, "_owner_account", None)+ monkeypatch.setattr(arb, "_owner_epoch", 0)+ monkeypatch.setattr(keepwarm, "_inflight", 0)+ monkeypatch.setattr(keepwarm, "_pending", 0)+ monkeypatch.setattr(keepwarm, "_admitted_inference", 0)+ generations.reset_for_tests()+ admission.reset_llama_admission_queues()+ yield+ generations.reset_for_tests()+ admission.reset_llama_admission_queues()+++def route():+ from routes import inference+ return inference+++class Simulator:+ def __init__(self, monkeypatch):+ self.resident = None+ self.evictions = []+ self.runs = {}+ for owner in BACKENDS:+ monkeypatch.setitem(arb._EVICTORS, owner, self.evict)++ def evict(self):+ self.evictions.append(self.resident)+ self.resident = None++ def load(self, account, owner, model):+ if self.resident == (owner, model):+ run_as(account, arb.acquire_for_request, owner)+ return "reused"++ def register():+ if self.resident is not None:+ self.evict()+ self.resident = (owner, model)++ run_as(account, arb.acquire_for_request, owner, register)+ return "loaded"++ def start(self, account, name):+ event = threading.Event()+ tracker = run_as(+ account,+ generations.ActiveGeneration,+ event,+ thread_id = "same-client-id",+ run_id = name,+ model = self.resident[1],+ )+ tracker.__enter__()+ self.runs[name] = (tracker, event)+ return event++ def finish(self, name):+ tracker, _event = self.runs.pop(name)+ tracker.__exit__(None, None, None)++ def delete(self, account):+ return generations.cancel_all(account.account_id)++ def training(self, account):+ def reserve():+ # Must run BEFORE the training route's destructive cleanup, under its admission gate.+ arb.raise_if_other_accounts_active()+ arb.release(arb.DIFFUSION)+ arb.release(arb.VIDEO)+ self.evict()+ arb.release(arb.CHAT)++ run_as(account, reserve)+++def sim(monkeypatch):+ return Simulator(monkeypatch)+++def test_a_failed_registration_does_not_take_residency(monkeypatch):+ """``_owner_account`` says who LOADED the resident model, so a registration that raised may not take it."""+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: None)+ run_as(ALICE, arb.acquire_for, arb.CHAT, lambda: None)+ assert arb.owner_account() == ALICE.account_id+ with pytest.raises(RuntimeError, match = "out of memory"):+ run_as(+ BOB,+ arb.acquire_for,+ arb.CHAT,+ lambda: (_ for _ in ()).throw(RuntimeError("out of memory")),+ )+ assert arb.owner_account() == ALICE.account_id+++def test_a_lone_owner_acquires_without_reading_policy_or_a_database(monkeypatch):+ def unexpected(*args, **kwargs):+ raise AssertionError("the arbiter must not read account policy under its lock")++ monkeypatch.setattr(policy, "installation_is_multi_user", unexpected)+ monkeypatch.setattr(policy, "_account_counts", unexpected)+ monkeypatch.setattr(sqlite3, "connect", unexpected)+ monkeypatch.setitem(arb._EVICTORS, arb.CHAT, lambda: None)+ assert run_as(OWNER, arb.acquire_for, arb.CHAT, lambda: "loaded") == "loaded"+ run_as(OWNER, arb.raise_if_other_accounts_active)+ assert arb.owner_account() == OWNER.account_id++[email protected]("first,second", tuple(itertools.permutations(ACCOUNTS, 2)))[email protected]("outgoing,incoming", tuple(itertools.product(BACKENDS, repeat = 2)))+def test_sim_different_models_busy_then_idle_swap(sim, first, second, outgoing, incoming):+ assert sim.load(first, outgoing, "one") == "loaded"+ event = sim.start(first, "stream")+ before = arb.owner_snapshot()+ with pytest.raises(HTTPException) as refused:+ sim.load(second, incoming, "two")+ assert refused.value.status_code == 409+ assert refused.value.detail["error"] == "gpu_busy"+ assert int(refused.value.headers["Retry-After"]) >= 1+ assert arb.owner_snapshot() == before+ assert arb.owner_account() == first.account_id+ assert sim.evictions == [] and not event.is_set()+ sim.finish("stream")+ assert sim.load(second, incoming, "two") == "loaded"+ assert sim.evictions == [(outgoing, "one")]+ assert sim.resident == (incoming, "two")+++def test_sim_third_account_must_wait_for_both_streams(sim):+ sim.load(ALICE, arb.CHAT, "shared")+ a = sim.start(ALICE, "a")+ assert sim.load(BOB, arb.CHAT, "shared") == "reused"+ b = sim.start(BOB, "b")+ for finished in (None, "a"):+ if finished:+ sim.finish(finished)+ with pytest.raises(HTTPException):+ sim.load(CAROL, arb.CHAT, "different")+ assert not a.is_set() and not b.is_set()+ assert not sim.evictions+ sim.finish("b")+ assert sim.load(CAROL, arb.CHAT, "different") == "loaded"++[email protected]("deleting", [False, True])+def test_sim_stop_and_delete_cancel_only_the_target(sim, route, deleting):+ sim.load(ALICE, arb.CHAT, "shared")+ a = sim.start(ALICE, "a")+ b = sim.start(BOB, "b")+ if deleting:+ assert sim.delete(ALICE) == 1+ else:+ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, route._raise_or_cancel_active_generations, force = True, action = "Load")+ assert refused.value.detail["error"] == "gpu_busy"+ # Delete cancels Alice's own run; a refused force leaves it running.+ assert a.is_set() == deleting and not b.is_set()+ assert generations.foreign_count(BOB.account_id) == 1 # cancellation is not completion+ sim.finish("a")+ assert generations.count(BOB.account_id) == 1+ assert sim.load(CAROL, arb.CHAT, "shared") == "reused"+ sim.finish("b")+++def test_sim_training_preflight_and_release_do_not_terminate_foreign_chat(sim):+ sim.load(ALICE, arb.CHAT, "shared")+ event = sim.start(ALICE, "a")+ run_as(BOB, arb.release, arb.DIFFUSION)+ run_as(BOB, arb.release, arb.VIDEO)+ assert arb.current_owner() == arb.CHAT+ with pytest.raises(arb.GpuBusyForAnotherAccountError):+ sim.training(BOB)+ assert not event.is_set() and sim.evictions == []+ sim.finish("a")+ sim.training(BOB)+ assert sim.evictions == [(arb.CHAT, "shared")]+ assert arb.current_owner() is None++[email protected]("force,cancel", tuple(itertools.product([False, True], repeat = 2)))+def test_route_preflight_and_force_respect_accounts(route, sim, force, cancel):+ sim.load(ALICE, arb.CHAT, "shared")+ mine = sim.start(ALICE, "a")+ theirs = sim.start(BOB, "b")+ with pytest.raises(HTTPException) as refused:+ run_as(+ ALICE,+ route._raise_or_cancel_active_generations,+ force = force,+ cancel = cancel,+ action = "Replacing the model",+ )+ assert refused.value.status_code == 409+ assert refused.value.detail["error"] == "gpu_busy"+ # Refused for a foreign generation, so the caller's chats are never cancelled.+ assert not mine.is_set()+ assert not theirs.is_set()+ body = str(refused.value.detail)+ for private in (BOB.account_id, "same-client-id", "shared"):+ assert private not in body+ sim.finish("a")+ sim.finish("b")+++def test_route_own_stream_keeps_existing_conflict_and_force_shape(route, sim):+ sim.load(ALICE, arb.CHAT, "shared")+ event = sim.start(ALICE, "a")+ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, route._raise_or_cancel_active_generations, force = False, action = "Load")+ assert refused.value.detail["error"] == "active_generations"+ assert refused.value.detail["thread_ids"] == ["same-client-id"]+ assert run_as(ALICE, route._raise_or_cancel_active_generations, force = True, action = "Load") == 1+ assert event.is_set()+ sim.finish("a")++[email protected]("cancel_pending", [False, True])+def test_wait_refuses_foreign_even_when_counters_miss_it_or_deadline_expires(+ route, sim, cancel_pending+):+ sim.load(ALICE, arb.CHAT, "shared")+ event = sim.start(ALICE, "a")+ with pytest.raises(HTTPException) as refused:+ asyncio.run(+ arun_as(+ BOB,+ route._wait_for_model_switch_idle(+ current_request_counted = True,+ cancel_pending = cancel_pending,+ timeout_s = 0,+ ),+ )+ )+ assert refused.value.detail["error"] == "gpu_busy"+ assert not event.is_set()+ sim.finish("a")+ asyncio.run(arun_as(BOB, route._wait_for_model_switch_idle(current_request_counted = True)))+++def test_wait_discounts_only_own_cancellable_work(route, sim, monkeypatch):+ sim.load(ALICE, arb.CHAT, "shared")+ event = sim.start(ALICE, "a")+ monkeypatch.setattr(keepwarm, "_inflight", 1)+ asyncio.run(+ arun_as(+ ALICE,+ route._wait_for_model_switch_idle(+ current_request_counted = False,+ cancel_pending = True,+ ),+ )+ )+ assert not event.is_set()+ sim.finish("a")+++ "previous,target,active", tuple(itertools.product((None, *BACKENDS), BACKENDS, [False, True]))+)+def test_single_account_arbiter_matches_legacy_decisions(+ sim, monkeypatch, previous, target, active+):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ if previous:+ sim.load(OWNER, previous, "one")+ if active:+ tracker = generations.ActiveGeneration(threading.Event())+ tracker.__enter__()+ try:++ def forbidden_retry():+ pytest.fail("Single-account load must not compute a busy hint")++ monkeypatch.setattr(admission, "estimate_gpu_retry_after", forbidden_retry)+ sim.load(OWNER, target, "two")+ assert sim.evictions == ([(previous, "one")] if previous else [])+ assert arb.current_owner() == target+ finally:+ if active:+ tracker.__exit__(None, None, None)++[email protected]("active,force,cancel", tuple(itertools.product([False, True], repeat = 3)))+def test_single_account_cancel_matches_legacy_decisions(route, monkeypatch, active, force, cancel):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ event = threading.Event()+ tracker = generations.ActiveGeneration(event, thread_id = "owner-chat")+ if active:+ tracker.__enter__()+ try:+ if active and not force:+ with pytest.raises(HTTPException) as refused:+ route._raise_or_cancel_active_generations(force = force, cancel = cancel, action = "Load")+ assert refused.value.detail["error"] == "active_generations"+ assert refused.value.headers is None+ else:+ assert route._raise_or_cancel_active_generations(+ force = force,+ cancel = cancel,+ action = "Load",+ ) == int(active and force and cancel)+ assert event.is_set() == (active and force and cancel)+ finally:+ if active:+ tracker.__exit__(None, None, None)+++def test_single_account_wait_keeps_post_cancel_timeout(route, monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(keepwarm, "_inflight", 1)+ monkeypatch.setattr(+ generations, "foreign_count", lambda _account: pytest.fail("foreign scan on owner drain")+ )+ asyncio.run(route._wait_for_model_switch_idle(current_request_counted = False, timeout_s = 0))+++def test_borrowing_a_durable_registration_requires_the_same_account():+ event = threading.Event()+ with run_as(ALICE, generations.ActiveGeneration, event, run_id = "same"):+ with run_as(BOB, generations.ActiveGeneration, event, run_id = "same"):+ assert generations.count(ALICE.account_id) == 1+ assert generations.count(BOB.account_id) == 1+ assert generations.count(ALICE.account_id) == 1+ with run_as(ALICE, generations.ActiveGeneration, event, run_id = "same"):+ assert generations.count() == 1+ assert generations.count() == 0++[email protected]("cancel_queued", [False, True])+def test_real_admission_runs_accounts_concurrently_and_scopes_cancellation(cancel_queued):+ async def scenario():+ queue = admission.get_llama_admission_queue("one-llama-server")+ config = admission.llama_admission_config_from_env()+ entered = {name: asyncio.Event() for name in ("a", "b", "queued")}+ ready = {name: asyncio.Event() for name in entered}+ advance = {name: asyncio.Event() for name in entered}+ events = {name: threading.Event() for name in entered}+ streaming = {}+ reservations = {}++ async def stream(account, name):+ with generations.ActiveGeneration(events[name], run_id = name):+ assert current_account_id() == account.account_id+ reservation = queue.reserve(capacity = 2, config = config, tokens = 32, budget = 128)+ reservations[name] = reservation+ ready[name].set()+ try:+ lease = reservation.lease_nowait()+ if lease is None:+ await advance[name].wait()+ if events[name].is_set():+ return+ lease = await reservation.wait(1)+ streaming[name] = lease.slot+ entered[name].set()+ await advance[name].wait()+ assert current_account_id() == account.account_id+ finally:+ streaming.pop(name, None)+ reservation.cancel()++ tasks = []+ try:+ for account, name in ((ALICE, "a"), (BOB, "b"), (CAROL, "queued")):+ tasks.append(asyncio.create_task(arun_as(account, stream(account, name))))+ await ready[name].wait()+ assert entered["a"].is_set() and entered["b"].is_set()+ assert len(set(streaming.values())) == 2+ assert not entered["queued"].is_set()+ assert queue.snapshot().queued == 1+ if cancel_queued:+ assert generations.cancel_all(CAROL.account_id) == 1+ advance["queued"].set()+ await tasks[2]+ assert set(streaming) == {"a", "b"}+ assert queue.snapshot().queued == 0+ assert run_as(ALICE, generations.cancel_all, ALICE.account_id) == 1+ advance["a"].set()+ await tasks[0]+ assert not events["b"].is_set() and not tasks[1].done()+ if not cancel_queued:+ advance["queued"].set()+ await tasks[2]+ assert entered["queued"].is_set()+ advance["b"].set()+ await tasks[1]+ assert queue.is_idle() and generations.count() == 0+ finally:+ for event in advance.values():+ event.set()+ await asyncio.gather(*tasks, return_exceptions = True)++ asyncio.run(scenario())+++ "capacity,count,expected", [(2, 0, 15), (2, 2, 15), (2, 3, 30), (2, 7, 60), (1, 20, 120)]+)+def test_retry_hint_tracks_queue_waves_without_creating_queues(capacity, count, expected):+ async def scenario():+ assert admission.estimate_gpu_retry_after() == 15+ assert not admission._QUEUES+ queue = admission.get_llama_admission_queue("shared-server")+ config = admission.llama_admission_config_from_env()+ reservations = [queue.reserve(capacity = capacity, config = config) for _ in range(count)]+ try:+ assert admission.estimate_gpu_retry_after() == expected+ exc = arb.GpuBusyForAnotherAccountError(arb.CHAT, 1).as_http_exception()+ assert exc.detail["retry_after"] == expected+ assert exc.headers["Retry-After"] == str(expected)+ finally:+ for reservation in reservations:+ reservation.cancel()++ asyncio.run(scenario())++[email protected]("kind", [arb.CHAT, arb.DIFFUSION, arb.VIDEO])[email protected]("multi", [False, True])+def test_global_idle_clock_follows_last_account_activity(monkeypatch, kind, multi):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: multi)+ clock = [0.0]+ if kind == arb.CHAT:+ monkeypatch.setattr(keepwarm, "time", SimpleNamespace(monotonic = lambda: clock[0]))+ monkeypatch.setattr(keepwarm, "_last_active", 0.0)+ start, end, idle = keepwarm._note_start, keepwarm._note_end, keepwarm._is_idle+ else:+ monkeypatch.setattr(media_keepwarm, "time", SimpleNamespace(monotonic = lambda: clock[0]))+ tracker = media_keepwarm._Tracker(kind)+ start, end, idle = tracker.note_start, tracker.note_end, tracker.is_idle+ accounts = (ALICE, BOB) if multi else (OWNER, OWNER)+ run_as(accounts[0], start)+ clock[0] = 10.0+ run_as(accounts[1], start)+ clock[0] = 20.0+ run_as(accounts[0], end)+ assert not idle(5)+ clock[0] = 100.0+ assert not idle(5)+ run_as(accounts[1], end)+ clock[0] = 104.0+ assert not idle(5)+ clock[0] = 105.0+ assert idle(5)+++def chat_switch(route, monkeypatch):+ backend = SimpleNamespace(+ is_loaded = True,+ model_identifier = "org/one-GGUF",+ hf_variant = None,+ _openai_advertised_id = None,+ )+ loads = []+ monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: True)+ monkeypatch.setattr(resolver, "warm_index_soon", lambda: None)+ monkeypatch.setattr(+ resolver, "resolve_trusted_cached_local_gguf", lambda name, **_kw: (name, None, name)+ )+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_args: True)+ monkeypatch.setattr(route, "get_llama_cpp_backend", lambda: backend)+ monkeypatch.setattr(route, "_auto_switch_waiters", {})+ monkeypatch.setattr(+ route, "_loaded_identity_satisfies", lambda name: backend.model_identifier == name+ )+ monkeypatch.setattr(route, "_claim_slot_for_non_preview", lambda *_args: None)+ monkeypatch.setattr(+ route.account_access, "require_model_access", lambda *_args, **_kwargs: None+ )++ async def load(request, *_args, **_kwargs):+ loads.append(request.model_path)+ backend.model_identifier = request.model_path++ monkeypatch.setattr(route, "_load_model_impl", load)++ async def reject(*_args):+ pass++ monkeypatch.setattr(route, "_reject_unservable_model", reject)+ return backend, loads++[email protected]("path", ["/v1/chat/completions", "/v1/messages"])+def test_chat_auto_switch_keeps_resident_parallel_and_refuses_foreign_swap(+ route, sim, chat_switch, path+):+ backend, loads = chat_switch+ sim.load(ALICE, arb.CHAT, "org/one-GGUF")+ event = sim.start(ALICE, "a")+ request = SimpleNamespace(scope = {}, url = SimpleNamespace(path = path))+ asyncio.run(arun_as(BOB, route._maybe_auto_switch_model("org/one-GGUF", request, BOB.username)))+ assert loads == []+ with pytest.raises(HTTPException) as refused:+ asyncio.run(+ arun_as(BOB, route._maybe_auto_switch_model("org/two-GGUF", request, BOB.username))+ )+ assert refused.value.status_code == 409+ assert refused.value.detail["error"]["type"] == "conflict_error"+ if path.endswith("completions"):+ assert refused.value.detail["error"]["code"] == "gpu_busy"+ assert refused.value.headers["Retry-After"] == "15"+ assert loads == [] and not event.is_set()+ assert backend.model_identifier == "org/one-GGUF"+ sim.finish("a")+ asyncio.run(arun_as(BOB, route._maybe_auto_switch_model("org/two-GGUF", request, BOB.username)))+ assert loads == ["org/two-GGUF"]+++def test_chat_auto_switch_rechecks_under_lifecycle_gate(route, sim, chat_switch, monkeypatch):+ _backend, loads = chat_switch+ sim.load(ALICE, arb.CHAT, "org/one-GGUF")+ acquire = route._acquire_swap_gate++ async def register_during_prepare():+ await acquire()+ sim.start(ALICE, "late")++ monkeypatch.setattr(route, "_acquire_swap_gate", register_during_prepare)+ request = SimpleNamespace(scope = {}, url = SimpleNamespace(path = "/v1/chat/completions"))+ with pytest.raises(HTTPException) as refused:+ asyncio.run(+ arun_as(BOB, route._maybe_auto_switch_model("org/two-GGUF", request, BOB.username))+ )+ assert refused.value.detail["error"]["code"] == "gpu_busy"+ assert loads == []+ assert not route._auto_switch_waiters+ assert not route._auto_switch_process_lock.locked()+ sim.finish("late")+++def media_switch(monkeypatch):+ resident = {"loaded": False}+ backend = SimpleNamespace(+ status = lambda: dict(resident),+ loading_repo_ids = lambda: [],+ generate_progress = lambda: {"active": False},+ load_progress = lambda: {"phase": "ready"},+ )+ pick = MediaModelPick("org/image", "org/image", model_kind = "diffusers")+ loads = []+ monkeypatch.setattr(settings, "get_media_auto_switch_enabled", lambda: True)+ monkeypatch.setattr(media, "backend_for", lambda _owner: backend)+ monkeypatch.setattr(media, "resolve_local_media_model", lambda *_args, **_kwargs: pick)+ monkeypatch.setattr(media, "is_edit_only", lambda _pick: False)+ monkeypatch.setattr(media, "load_takes_the_gpu", lambda: True)+ monkeypatch.setattr(media_backends, "load_takes_the_gpu", lambda: True)+ monkeypatch.setattr(media_backends, "other_backend_busy", lambda _owner: False)+ monkeypatch.setattr(media_backends, "chat_busy", lambda *_args: False)+ monkeypatch.setattr(+ media_keepwarm,+ "_TRACKERS",+ {owner: media_keepwarm._Tracker(owner) for owner in (arb.DIFFUSION, arb.VIDEO)},+ )++ async def require_local(*_args, **_kwargs):+ pass++ monkeypatch.setattr(media, "_require_local", require_local)++ async def load(owner, pick, *_args):+ arb.acquire_for_request(owner, replacing = True)+ loads.append(pick.model_id)+ resident.update(loaded = True, repo_id = pick.model_id, model_kind = "diffusers")++ monkeypatch.setattr(media, "_start_load", load)+ return backend, pick, resident, loads++[email protected]("owner", [arb.DIFFUSION, arb.VIDEO])[email protected]("openai_errors", [False, True])+def test_media_auto_switch_refuses_foreign_work_with_existing_error_shape(+ sim, media_switch, owner, openai_errors+):+ _backend, _pick, _resident, loads = media_switch+ sim.load(ALICE, arb.CHAT, "shared")+ event = sim.start(ALICE, "a")++ def switch():+ return asyncio.run(+ arun_as(+ BOB,+ media.maybe_auto_switch_media_model(+ "org/image",+ owner = owner,+ current_subject = BOB.username,+ openai_errors = openai_errors,+ ),+ )+ )++ with pytest.raises(HTTPException) as refused:+ switch()+ assert refused.value.status_code == 409+ if openai_errors:+ assert refused.value.detail["error"]["code"] == "model_busy"+ else:+ assert isinstance(refused.value.detail, str)+ assert refused.value.headers == {"Retry-After": "15"}+ assert loads == [] and sim.evictions == [] and not event.is_set()+ sim.finish("a")+ switch()+ assert loads == ["org/image"]+++def test_media_already_resident_never_checks_account_or_drains(sim, media_switch, monkeypatch):+ _backend, _pick, resident, loads = media_switch+ resident.update(loaded = True, repo_id = "org/image", model_kind = "diffusers")+ sim.load(ALICE, arb.DIFFUSION, "org/image")+ sim.start(ALICE, "a")+ monkeypatch.setattr(+ policy, "installation_is_multi_user", lambda: pytest.fail("resident hot path")+ )+ asyncio.run(+ arun_as(+ BOB,+ media.maybe_auto_switch_media_model(+ "org/image",+ owner = arb.DIFFUSION,+ current_subject = BOB.username,+ openai_errors = True,+ ),+ )+ )+ assert loads == []+ sim.finish("a")+++def test_media_final_arbiter_refusal_is_converted_after_drain(sim, media_switch, monkeypatch):+ _backend, _pick, _resident, loads = media_switch+ sim.load(ALICE, arb.CHAT, "shared")+ original = media._start_load++ async def late_start(*args):+ sim.start(ALICE, "late")+ return await original(*args)++ monkeypatch.setattr(media, "_start_load", late_start)+ with pytest.raises(HTTPException) as refused:+ asyncio.run(+ arun_as(+ BOB,+ media.maybe_auto_switch_media_model(+ "org/image",+ owner = arb.DIFFUSION,+ current_subject = BOB.username,+ openai_errors = True,+ ),+ )+ )+ assert refused.value.detail["error"]["code"] == "model_busy"+ assert refused.value.headers["Retry-After"] == "15"+ assert loads == [] and sim.evictions == []+ sim.finish("late")+++def test_cpu_media_drain_does_not_refuse_unrelated_gpu_work(sim, media_switch, monkeypatch):+ backend, _pick, _resident, _loads = media_switch+ sim.load(ALICE, arb.CHAT, "shared")+ sim.start(ALICE, "a")+ monkeypatch.setattr(media_backends, "load_takes_the_gpu", lambda: False)+ assert asyncio.run(+ arun_as(+ BOB,+ media_backends.drain(+ arb.DIFFUSION,+ backend,+ time.monotonic() + 1,+ ),+ )+ )+ sim.finish("a")++[email protected]("owner", [arb.DIFFUSION, arb.VIDEO])[email protected]("resident_owner", [arb.CHAT, arb.DIFFUSION, arb.VIDEO])+def test_actual_media_load_routes_refuse_before_engine_activation_or_load(+ route, sim, monkeypatch, owner, resident_owner+):+ from core.inference import (+ diffusion,+ diffusion_device,+ diffusion_engine_router,+ diffusion_compat,+ video,+ )+ from models.inference import DiffusionLoadRequest, VideoLoadRequest+ from routes import video as video_route++ touched = []+ backend = SimpleNamespace(+ validate_load_request = lambda *_a, **_k: SimpleNamespace(name = "ltx-2", base_repo = None),+ preflight_base_access = lambda *_a, **_k: None,+ assert_precision_available = lambda *_a, **_k: None,+ begin_load = lambda *_a, **_k: touched.append("load"),+ )++ async def ordinal(*_args):+ return None++ monkeypatch.setattr(diffusion, "get_diffusion_backend", lambda: backend)+ monkeypatch.setattr(video, "get_video_backend", lambda: backend)+ monkeypatch.setattr(video, "assert_video_precision_available", lambda *_a, **_k: None)+ monkeypatch.setattr(+ diffusion_device, "resolve_diffusion_device_target", lambda: SimpleNamespace(device = "cuda")+ )+ monkeypatch.setattr(diffusion_engine_router, "predict_engine", lambda *_a, **_k: "diffusers")+ monkeypatch.setattr(diffusion_engine_router, "engine_for", lambda *_a: backend)+ monkeypatch.setattr(diffusion_engine_router, "active_engine_name", lambda: "diffusers")+ monkeypatch.setattr(+ diffusion_engine_router,+ "select_and_activate_engine",+ lambda *_a, **_k: touched.append("activate") or backend,+ )+ monkeypatch.setattr(diffusion_compat, "assert_pick_is_not_speech", lambda *_a: None)+ monkeypatch.setattr(route, "_guard_diffusion_load_against_training", lambda: None)+ monkeypatch.setattr(route, "_selected_gpu_ordinal", ordinal)+ monkeypatch.setattr(video_route, "_guard_video_load_against_training", lambda: None)+ monkeypatch.setattr(video_route, "_selected_gpu_ordinal", ordinal)+ sim.load(ALICE, resident_owner, "resident")+ event = sim.start(ALICE, "a")+ if owner == arb.DIFFUSION:+ request = DiffusionLoadRequest(model_path = "org/image", gguf_filename = "model.gguf")+ load = route.load_diffusion_model_gated+ else:+ request = VideoLoadRequest(model_path = "org/video", gguf_filename = "model.gguf")+ load = video_route.load_video_model_gated+ with pytest.raises(HTTPException) as refused:+ asyncio.run(arun_as(BOB, load(request, BOB.username)))+ assert refused.value.status_code == 409+ assert refused.value.detail["error"] == "gpu_busy"+ assert refused.value.headers["Retry-After"] == "15"+ assert touched == [] and sim.evictions == [] and not event.is_set()+ sim.finish("a")++[email protected]("path", ["/v1/chat/completions", "/v1/messages", "/api/inference/chat"])+def test_chat_final_arbiter_refusal_keeps_endpoint_error_shape(+ route, sim, chat_switch, monkeypatch, path+):+ _backend, loads = chat_switch+ sim.load(ALICE, arb.CHAT, "org/one-GGUF")++ async def late_load(*_args, **_kwargs):+ sim.start(ALICE, "late")+ arb.acquire_for_request(arb.CHAT, replacing = True)++ monkeypatch.setattr(route, "_load_model_impl", late_load)+ request = SimpleNamespace(scope = {}, url = SimpleNamespace(path = path))+ with pytest.raises(HTTPException) as refused:+ asyncio.run(+ arun_as(BOB, route._maybe_auto_switch_model("org/two-GGUF", request, BOB.username))+ )+ assert refused.value.status_code == 409+ if path.startswith("/v1/"):+ assert refused.value.detail["error"]["type"] == "conflict_error"+ else:+ assert refused.value.detail["error"] == "gpu_busy"+ assert refused.value.headers["Retry-After"] == "15"+ assert loads == [] and sim.evictions == []+ sim.finish("late")+++def test_chat_resident_fast_path_adds_no_account_policy_work(route, chat_switch, monkeypatch):+ monkeypatch.setattr(+ policy, "installation_is_multi_user", lambda: pytest.fail("resident policy read")+ )+ monkeypatch.setattr(+ generations, "foreign_count", lambda _account: pytest.fail("resident foreign scan")+ )+ request = SimpleNamespace(scope = {}, url = SimpleNamespace(path = "/v1/chat/completions"))+ asyncio.run(+ arun_as(OWNER, route._maybe_auto_switch_model("org/one-GGUF", request, OWNER.username))+ )diff --git a/studio/backend/tests/test_hub_download_ambient_token.py b/studio/backend/tests/test_hub_download_ambient_token.pyindex 63fcddc894a..5ab93a455e4 100644--- a/studio/backend/tests/test_hub_download_ambient_token.py+++ b/studio/backend/tests/test_hub_download_ambient_token.py@@ -57,11 +57,22 @@ class _Proc:class _ImmediateThread:- def __init__(self, *, target, **_kwargs):+ """Runs the watcher inline; it is pinned to an account, so the positional arguments (account, target) must reach it."""++ def __init__(+ self,+ *,+ target,+ args = (),+ kwargs = None,+ **_kwargs,+ ):self.target = target+ self.args = args+ self.kwargs = kwargs or {}def start(self):- self.target()+ self.target(*self.args, **self.kwargs)def _client(via_api_key: bool) -> TestClient:diff --git a/studio/backend/tests/test_job_accounts.py b/studio/backend/tests/test_job_accounts.pynew file mode 100644index 00000000000..135a224c460--- /dev/null+++ b/studio/backend/tests/test_job_accounts.py@@ -0,0 +1,1883 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Account isolation at job admission, observation, and execution boundaries."""++from __future__ import annotations++import asyncio+import json+import multiprocessing+import os+import queue+import importlib+import threading+import weakref+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from auth import policy+from core.training import account_jobs as jobs+from core.training.training import TrainingBackend, TrainingProgress+from utils.account_context import AccountContext, OWNER, arun_as, current_account, run_as+from utils.paths import (+ exports_root,+ outputs_root,+ rag_root,+ studio_db_path,+ tensorboard_root,+ workspace_root,+)++ALICE = AccountContext("alice-job-account", "alice")+BOB = AccountContext("bob-job-account", "bob")++[email protected](autouse = True)+def multi(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(jobs, "_retired", set())+++class FakeProcess:+ pid = None+ exitcode = 0++ def __init__(self):+ self.running = False+ self.terminated = False++ def start(self):+ self.running = True++ def is_alive(self):+ return self.running++ def terminate(self):+ self.terminated = True+ self.running = False++ def join(self, timeout = None):+ pass++ kill = terminate+++class FakeThread:+ def start(self):+ pass++ def is_alive(self):+ return False++ def join(self, timeout = None):+ pass+++def training(monkeypatch):+ from core.training import training as module+ from utils import transformers_version+ from storage import studio_db++ backend = TrainingBackend()+ monkeypatch.setattr(studio_db, "mark_run_cancel_requested", lambda run_id: True)+ process = FakeProcess()+ captures = []+ monkeypatch.setattr(module, "prepare_gpu_selection", lambda *a, **k: ([], {}))+ monkeypatch.setattr(module, "_apply_cache_pins", lambda config: None)+ monkeypatch.setattr(transformers_version, "sidecar_swap_in_progress", lambda: False)+ monkeypatch.setattr(module._CTX, "Queue", queue.Queue)+ monkeypatch.setattr(module._CTX, "Process", lambda **kwargs: captures.append(kwargs) or process)+ monkeypatch.setattr(module, "account_thread", lambda **kwargs: FakeThread())+ monkeypatch.setattr(backend, "_ensure_db_run_created", lambda: None)+ monkeypatch.setattr(backend, "_start_stop_watchdog", lambda *a, **k: None)+ return backend, process, captures+++def start_training(backend, account = ALICE):+ return run_as(+ account, backend.start_training, "job-a", model_name = "org/model", hf_token = "account-token"+ )+++def test_training_admission_status_metrics_and_cancel_are_private(training, monkeypatch):+ from routes import training as route++ backend, proc, captures = training+ assert start_training(backend)+ assert backend.job_account == ALICE+ assert captures[0]["kwargs"]["account"] == ALICE+ assert captures[0]["kwargs"]["config"]["model_name"] == "org/model"+ backend._progress = TrainingProgress(is_training = True, status_message = "Secret model", loss = 9.5)+ backend.loss_history = [9.5]+ backend.step_history = [1]+ backend._output_dir = "/private/alice"+ monkeypatch.setattr(route, "get_training_backend", lambda: backend)+ status = asyncio.run(arun_as(BOB, route.get_training_status("bob")))+ assert status.message == "Busy"+ assert status.job_id == "" and status.details is None and status.metric_history is None+ metrics = asyncio.run(arun_as(BOB, route.get_training_metrics(current_subject = "bob")))+ assert metrics.loss_history == [] and metrics.current_loss is None+ assert run_as(BOB, backend.trainer.get_training_progress).loss != 9.5+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, backend.stop_training, expected_job_id = "job-a")+ assert exc.value.status_code == 404+ assert proc.is_alive()+ with pytest.raises(HTTPException) as exc:+ start_training(backend, BOB)+ assert exc.value.status_code == 409+ assert backend.job_account == ALICE+ assert run_as(ALICE, backend.stop_training, save = False, expected_job_id = "job-a")+++def test_pending_start_is_owned_and_failed_validation_releases_slot(training):+ backend, _, _ = training+ run_as(ALICE, backend.reserve_start_request, "alice-request", "a")+ assert backend.job_account == ALICE+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, backend.reserve_start_request, "bob-request", "b")+ assert exc.value.status_code == 409+ run_as(+ ALICE, backend.resolve_start_request, "alice-request", state = "rejected", message = "Failed"+ )+ jobs.refresh_job_owner(backend)+ assert backend.job_account is None+ run_as(BOB, backend.reserve_start_request, "bob-request", "b")+ assert backend.job_account == BOB+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, backend.get_start_request, "alice-request")+ assert exc.value.status_code == 404+++def test_finished_training_results_remain_private_and_successor_clears_them(training):+ backend, proc, _ = training+ assert start_training(backend)+ proc.running = False+ backend._progress = TrainingProgress(is_completed = True, status_message = "Alice done", loss = 4.0)+ backend.loss_history.append(4.0)+ jobs.refresh_job_owner(backend)+ assert backend.job_account is None+ assert run_as(BOB, backend.get_training_status)[1].loss != 4.0+ run_as(BOB, backend.reserve_start_request, "bob", "b")+ assert backend.loss_history == []+ assert backend._progress.status_message != "Alice done"+++def export(monkeypatch):+ from core.export.orchestrator import ExportOrchestrator++ backend = ExportOrchestrator()+ proc = FakeProcess()++ def spawn(config):+ proc.start()+ backend._proc = proc++ monkeypatch.setattr(backend, "_spawn_subprocess", spawn)+ monkeypatch.setattr(backend, "_send_cmd", lambda command: None)+ monkeypatch.setattr(+ backend,+ "_wait_response",+ lambda *a, **k: {+ "success": True,+ "message": "done",+ "is_peft": True,+ "checkpoint": "/arbitrary/checkpoint",+ },+ )+ monkeypatch.setattr(backend, "_shutdown_subprocess", lambda **kwargs: proc.terminate() or True)+ yield backend, proc+ proc.running = False+++def test_export_finished_checkpoint_and_logs_are_private(export):+ backend, proc = export+ checkpoint = str(run_as(ALICE, outputs_root) / "checkpoint")+ assert run_as(ALICE, backend.load_checkpoint, checkpoint)[0]+ backend._append_log({"line": "alice secret metric", "ts": 1})+ assert backend.job_account is None+ assert run_as(BOB, backend.get_logs_since, 0) == ([], 0)+ assert run_as(BOB, backend.get_last_op) is None+ for operation in (backend.cancel_export, backend.cleanup_memory):+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, operation)+ assert exc.value.status_code == 404+ with pytest.raises(HTTPException):+ run_as(BOB, backend.export_lora_adapter, str(run_as(BOB, exports_root)))+ assert proc.is_alive()+++def test_export_busy_status_hides_checkpoint(export, monkeypatch):+ from routes import export as route++ backend, _ = export+ backend._result_account = ALICE+ backend.current_checkpoint = "alice-private-model"+ backend._export_active = True+ monkeypatch.setattr(route, "get_export_backend", lambda: backend)+ result = asyncio.run(arun_as(BOB, route.get_export_status("bob")))+ assert result.active_op_kind == "busy"+ assert result.current_checkpoint is None and result.is_peft is False+++def test_export_owner_single_mode_preserves_operation_and_status_bytes(export, monkeypatch):+ from routes import export as route++ backend, _ = export+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(route, "get_export_backend", lambda: backend)+ assert run_as(OWNER, backend.load_checkpoint, "/arbitrary/checkpoint") == (True, "done")+ result = asyncio.run(route.get_export_status("unsloth"))+ expected = {+ "current_checkpoint": "/arbitrary/checkpoint",+ "is_vision": False,+ "is_peft": True,+ "is_export_active": False,+ "active_op_kind": None,+ "last_op_seq": 1,+ "last_op_kind": "load_checkpoint",+ "last_op_status": "success",+ "last_op_output_path": None,+ "last_op_error": None,+ }+ assert result.model_dump_json() == json.dumps(expected, separators = (",", ":"))+ exported = backend.export_lora_adapter("/arbitrary/export")+ assert json.dumps(exported, separators = (",", ":")) == '[true,"done",null]'+ assert backend.cancel_export() is True+++def test_recipe_job_status_dataset_events_and_cancel_are_private(monkeypatch):+ from core.data_recipe.jobs import manager as module++ manager = module.JobManager()+ process = FakeProcess()+ monkeypatch.setattr(module._CTX, "Queue", queue.Queue)+ monkeypatch.setattr(module._CTX, "Process", lambda **kwargs: process)+ monkeypatch.setattr(module, "account_thread", lambda **kwargs: FakeThread())+ job_id = run_as(ALICE, manager.start, recipe = {}, run = {})+ assert manager.job_account == ALICE+ assert run_as(BOB, manager.get_current_status) == {"status": "busy"}+ assert run_as(BOB, manager.get_status, job_id) is None+ assert run_as(BOB, manager.get_dataset, job_id, limit = 10) is None+ assert run_as(BOB, manager.subscribe, job_id) is None+ with pytest.raises(HTTPException):+ run_as(BOB, manager.cancel, job_id)+ assert process.is_alive()+ process.running = False+ jobs.refresh_job_owner(manager)+ assert manager.job_account is None+ assert run_as(BOB, manager.start, recipe = {}, run = {}) != job_id+++class _OwnedJobService:+ def __init__(self):+ self._account_job_lock = threading.RLock()+ self._account_inflight = 0+ self._result_account = None+ self.job_account = None+ self._account_clear = None+ self.live = False++ def _account_active(self):+ return self.live++ @jobs.owned_job()+ def start(self):+ self.live = True+ return "started"+++def test_owner_start_while_the_last_managed_account_is_deactivated_keeps_its_own_attribution(+ monkeypatch,+):+ mode = {"multi": True}+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: mode["multi"])+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)++ service = _OwnedJobService()+ run_as(ALICE, service.start)+ service.live = False+ jobs.refresh_job_owner(service)+ assert service._result_account == ALICE++ mode["multi"] = False+ run_as(OWNER, service.start)+ assert service._result_account == OWNER and service.job_account == OWNER++ mode["multi"] = True+ assert not run_as(OWNER, jobs.job_is_foreign, service)+ assert run_as(ALICE, jobs.job_is_foreign, service)+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.require_job_owner, service)+ assert exc.value.status_code == 404+++def test_deactivating_the_last_managed_account_keeps_its_job_private(training, monkeypatch):+ from routes import training as route++ backend, proc, _ = training+ assert start_training(backend)+ backend._progress = TrainingProgress(is_training = True, status_message = "Secret model", loss = 9.5)+ backend.loss_history = [9.5]+ backend.step_history = [1]+ backend._output_dir = "/private/alice"+ monkeypatch.setattr(route, "get_training_backend", lambda: backend)+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)++ status = asyncio.run(arun_as(OWNER, route.get_training_status("unsloth")))+ assert status.message == "Busy"+ assert status.job_id == "" and status.details is None and status.metric_history is None+ metrics = asyncio.run(arun_as(OWNER, route.get_training_metrics(current_subject = "unsloth")))+ assert metrics.loss_history == [] and metrics.current_loss is None+ with pytest.raises(HTTPException) as exc:+ run_as(OWNER, backend.stop_training, expected_job_id = "job-a")+ assert exc.value.status_code == 404+ assert proc.is_alive()+++def test_deactivating_the_last_managed_account_keeps_an_in_flight_start_contained(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)++ assert run_as(ALICE, jobs.managed_account) is True+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.validate_job_paths, {"output_dir": "/owner/private/outputs"})+ assert exc.value.status_code == 403+ assert run_as(ALICE, jobs.account_hf_token, "") is False++ args, kwargs = run_as(+ ALICE,+ jobs.account_process_spec,+ "core.training.worker",+ "run_training_process",+ {},+ {"config": {"model_name": "org/model"}},+ )+ assert args[0:2] == ("core.training.account_jobs", "run_account_child")+ assert kwargs["account"] == ALICE+ assert kwargs["job_module"] == "core.training.worker"+ assert kwargs["job_target"] == "run_training_process"+++def test_an_owner_request_keeps_the_legacy_spawn_and_paths(monkeypatch):+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)++ assert jobs.managed_account() is False+ run_as(OWNER, jobs.validate_job_paths, {"output_dir": "/arbitrary/outputs"})+ args, kwargs = run_as(+ OWNER, jobs.account_process_spec, "core.training.worker", "run_training_process", {}, {}+ )+ assert args[0:2] == ("core.training.worker", "run_training_process")+ assert "account" not in kwargs+++def test_reactivation_clears_the_retirement_left_by_a_failed_delete(monkeypatch):+ from core import research_runs+ from core.export.orchestrator import ExportOrchestrator+ from core.rag import folder_sync, ingestion+ from hub.services.datasets import downloads++ def fail():+ raise RuntimeError("a worker is still alive")++ broken = ExportOrchestrator()+ broken._result_account = ALICE+ monkeypatch.setattr(broken, "_account_cancel", fail)+ monkeypatch.setattr(jobs, "_services", [broken])+ monkeypatch.setattr(downloads, "retire_account_downloads", lambda: None)+ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ with pytest.raises(RuntimeError):+ jobs.retire_account_jobs(ALICE)++ service = _OwnedJobService()+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, service.start)+ assert exc.value.status_code == 403++ jobs.restore_account_jobs(ALICE.account_id)+ assert run_as(ALICE, jobs.account_is_retired) is False+ assert run_as(ALICE, service.start) == "started"+++def test_an_install_that_never_had_a_managed_account_does_no_job_bookkeeping(monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: False)++ service = _OwnedJobService()+ service._account_job_lock = None # any reservation would raise here+ assert run_as(OWNER, service.start) == "started"+ assert service._result_account is None and service.job_account is None+++def test_diffusion_status_and_stop_are_private():+ from core.training.diffusion_training_service import DiffusionTrainingService++ service = DiffusionTrainingService()+ service._result_account = service.job_account = ALICE+ service._proc = FakeProcess()+ service._proc.start()+ service._state.update(base_model = "secret", loss = 123.0, output_dir = "/alice")+ status = run_as(BOB, service.status)+ assert status["status"] == "busy"+ assert status["base_model"] is None and status["loss"] is None and status["output_dir"] is None+ with pytest.raises(HTTPException):+ run_as(BOB, service.stop)+ assert service._proc.is_alive()+++def test_diffusion_history_resolves_per_account():+ from core.training.diffusion_training_service import _runs_dir+ assert run_as(ALICE, _runs_dir) == run_as(ALICE, tensorboard_root) / "diffusion"+ assert run_as(BOB, _runs_dir) != run_as(ALICE, _runs_dir)+++ "field",+ [+ "model_local_path",+ "checkpoint_path",+ "dataset_local_path",+ "local_datasets",+ "output_dir",+ "save_directory",+ "imatrix_path",+ "tensorboard_dir",+ "resume_from_checkpoint",+ ],+)+def test_managed_request_paths_cannot_cross_account_roots(field):+ private = str(run_as(BOB, workspace_root) / "secret")+ value = [private] if field == "local_datasets" else private+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.validate_job_paths, {field: value})+ assert exc.value.status_code == 403+ run_as(OWNER, jobs.validate_job_paths, {field: value})+++def test_managed_relative_export_destinations_resolve_under_the_account_exports_root():+ for name in ("llama-3-merged", "my-run/checkpoint-100", "model-GGUF"):+ run_as(ALICE, jobs.validate_job_paths, {"save_directory": name})+ for bad in (str(run_as(BOB, exports_root) / "stolen"), "../../escape"):+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.validate_job_paths, {"save_directory": bad})+ assert exc.value.status_code == 403+ own = str(run_as(ALICE, exports_root) / "mine")+ run_as(ALICE, jobs.validate_job_paths, {"save_directory": own})+ run_as(OWNER, jobs.validate_job_paths, {"save_directory": "llama-3-merged"})+++def test_managed_paths_resolve_symlinks_and_accept_private_outputs(tmp_path):+ own = run_as(ALICE, workspace_root)+ own.mkdir(parents = True)+ link = own / "link"+ link.symlink_to(tmp_path, target_is_directory = True)+ with pytest.raises(HTTPException):+ run_as(ALICE, jobs.account_path, link / "new-file")+ path = own / "outputs" / "new-run"+ assert run_as(ALICE, jobs.account_path, path) == path+ assert (+ run_as(ALICE, jobs.account_path, "org/public-model", reference = True) == "org/public-model"+ )+++ "config",+ [+ {"enable_wandb": True},+ {"s3_dataset": {"use_iam_role": True}},+ {"s3_dataset": {"region": "us-east-1"}},+ ],+)+def test_managed_jobs_require_explicit_credentials(config):+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.require_explicit_credentials, config)+ assert exc.value.status_code == 403+ run_as(OWNER, jobs.require_explicit_credentials, config)+++def test_hf_ambient_fallback_is_disabled_only_for_managed_accounts(monkeypatch):+ monkeypatch.setenv("HF_TOKEN", "owner-secret")+ assert run_as(ALICE, jobs.account_hf_token, None) is False+ assert run_as(ALICE, jobs.account_hf_token, "alice-secret") == "alice-secret"+ assert run_as(OWNER, jobs.account_hf_token, None) is None+++ "recipe",+ [+ {"seed_config": {"source": {"path": "/outside/private"}}},+ {"model_providers": [{"api_key_env": "OWNER_SECRET"}]},+ ],+)+def test_recipe_cannot_read_foreign_paths_or_environment_secrets(recipe):+ with pytest.raises(HTTPException):+ run_as(ALICE, jobs.validate_recipe_access, recipe)+ run_as(OWNER, jobs.validate_recipe_access, recipe)+++def _child_probe(result_queue):+ from utils.paths import tmp_root++ path = outputs_root() / "worker-account.txt"+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_text(current_account().account_id)+ result_queue.put(+ {+ "account": current_account().account_id,+ "output": str(path),+ "exports": str(exports_root()),+ "rag": str(rag_root()),+ "tensorboard": str(tensorboard_root()),+ "hf": os.environ.get("HF_TOKEN"),+ "wandb": os.environ.get("WANDB_API_KEY"),+ "aws": os.environ.get("AWS_ACCESS_KEY_ID"),+ "implicit": os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"),+ "tmp": str(tmp_root()),+ }+ )+++def test_spawned_worker_binds_account_before_import_and_scrubs_ambient_credentials(monkeypatch):+ monkeypatch.setenv("HF_TOKEN", "owner-hf")+ monkeypatch.setenv("WANDB_API_KEY", "owner-wandb")+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "owner-aws")+ ctx = multiprocessing.get_context("spawn")+ result_queue = ctx.Queue()+ process = ctx.Process(+ target = jobs.run_account_child,+ kwargs = {+ "account": ALICE,+ "job_module": __name__,+ "job_target": "_child_probe",+ "result_queue": result_queue,+ },+ )+ process.start()+ try:+ result = result_queue.get(timeout = 30)+ process.join(timeout = 10)+ assert process.exitcode == 0+ finally:+ if process.is_alive():+ process.terminate()+ process.join(timeout = 5)+ result_queue.close()+ assert result["account"] == ALICE.account_id+ assert Path(result["output"]).read_text() == ALICE.account_id+ assert Path(result["output"]).parent == run_as(ALICE, outputs_root)+ for name, root in (+ ("exports", exports_root),+ ("rag", rag_root),+ ("tensorboard", tensorboard_root),+ ):+ assert result[name] == str(run_as(ALICE, root))+ assert result["hf"] is result["wandb"] is result["aws"] is None+ assert result["implicit"] == "1"+ assert os.environ["HF_TOKEN"] == "owner-hf"+++def test_rag_in_memory_event_queues_are_account_scoped(monkeypatch):+ from core.rag import ingestion++ monkeypatch.setattr(+ ingestion,+ "_jobs",+ {+ run_as(ALICE, jobs.account_key, "same-id"): queue.Queue(),+ run_as(BOB, jobs.account_key, "same-id"): queue.Queue(),+ },+ )+ run_as(ALICE, ingestion._emit, "same-id", {"secret": "alice"})+ assert ingestion._jobs[run_as(ALICE, jobs.account_key, "same-id")].get_nowait() == {+ "secret": "alice"+ }+ assert ingestion._jobs[run_as(BOB, jobs.account_key, "same-id")].empty()+++def test_research_cancel_uses_account_keys():+ from core.research_runs import ResearchSupervisor++ supervisor = ResearchSupervisor(SimpleNamespace(state = SimpleNamespace()))+ alice = run_as(ALICE, supervisor._cancel_event, "same-id")+ bob = run_as(BOB, supervisor._cancel_event, "same-id")+ run_as(ALICE, supervisor.cancel, "same-id")+ assert alice.is_set() and not bob.is_set()+++def test_retirement_cancels_only_target_accounts_jobs(training, monkeypatch):+ from core.rag import ingestion, folder_sync+ from core import research_runs++ backend, proc, _ = training+ assert start_training(backend)+ cancelled = []+ monkeypatch.setattr(backend, "_account_cancel", lambda: cancelled.append(current_account()))+ monkeypatch.setattr(jobs, "_services", {backend})+ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+ jobs.retire_account_jobs(BOB)+ assert cancelled == [] and proc.is_alive()+ jobs.retire_account_jobs(ALICE)+ assert cancelled == [ALICE]+ with pytest.raises(HTTPException) as exc:+ start_training(backend)+ assert exc.value.status_code == 403+++def test_existing_event_stream_stops_before_successor_account_frame():+ service = SimpleNamespace(_result_account = ALICE)++ async def events():+ yield "alice frame"+ service._result_account = BOB+ yield "bob secret"++ async def consume():+ return [item async for item in jobs.account_event_stream(service, events())]++ result = asyncio.run(arun_as(ALICE, consume()))+ assert result == ["alice frame", 'event: busy\ndata: {"status":"busy"}\n\n']+++def test_remote_training_cannot_borrow_the_owner_hf_token(monkeypatch):+ monkeypatch.setenv("HF_TOKEN", "owner-secret")+ with pytest.raises(HTTPException) as exc:+ run_as(ALICE, jobs.validate_job_paths, {"model_name": "org/model"})+ assert exc.value.status_code == 403+ run_as(ALICE, jobs.validate_job_paths, {"model_name": "org/model", "hf_token": "alice-secret"})+++def test_actual_training_s3_config_key_refuses_ambient_role():+ with pytest.raises(HTTPException):+ run_as(ALICE, jobs.validate_job_paths, {"s3_config": {"use_iam_role": True}})+++def test_dataset_download_registries_do_not_share_jobs(monkeypatch):+ from hub.services.datasets import downloads++ monkeypatch.setattr(downloads, "_account_registries", {})+ alice = run_as(ALICE, downloads._account_registry)+ bob = run_as(BOB, downloads._account_registry)+ alice.claim("org/dataset", "http", repo_type = "dataset", repo_id = "org/dataset")+ assert len(alice.active_job_refs()) == 1+ assert bob.active_job_refs() == []+ assert downloads._registry.active_job_refs("org/dataset") == []+ assert run_as(OWNER, downloads._account_registry) is downloads._registry+++def test_managed_account_cannot_delete_shared_dataset_cache():+ from hub.services.datasets.cache_inventory import delete_cached_dataset_response+ with pytest.raises(HTTPException) as exc:+ asyncio.run(arun_as(ALICE, delete_cached_dataset_response("org/dataset")))+ assert exc.value.status_code == 403+++def test_research_claim_uses_the_database_of_each_account(monkeypatch):+ from core import research_runs++ seen = []+ monkeypatch.setattr(research_runs, "job_accounts", lambda: [OWNER, ALICE, BOB])++ def claim(worker_id):+ seen.append(current_account())+ return {"id": "alice-run"} if current_account() == ALICE else None++ monkeypatch.setattr(research_runs.db, "claim_next", claim)+ supervisor = research_runs.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace()))+ account, run = supervisor._claim_account_run()+ assert seen == [OWNER, ALICE]+ assert account == ALICE and run == {"id": "alice-run"}+ assert current_account() == OWNER+++def test_research_claim_skips_an_account_whose_database_fails(monkeypatch):+ import sqlite3++ from core import research_runs++ monkeypatch.setattr(research_runs, "job_accounts", lambda: [ALICE, BOB])++ def claim(worker_id):+ if current_account() == ALICE:+ raise sqlite3.DatabaseError("file is not a database")+ return {"id": "bob-run"}++ monkeypatch.setattr(research_runs.db, "claim_next", claim)+ supervisor = research_runs.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace()))+ assert supervisor._claim_account_run() == (BOB, {"id": "bob-run"})+++def test_research_claim_rotates_across_accounts(monkeypatch):+ """A busy account must not starve the next one; the supervisor runs one run at a time."""+ from core import research_runs++ monkeypatch.setattr(research_runs, "job_accounts", lambda: [ALICE, BOB])+ queued = {ALICE.account_id: ["alice-1", "alice-2", "alice-3"], BOB.account_id: ["bob-1"]}++ def claim(worker_id):+ pending = queued[current_account().account_id]+ return {"id": pending.pop(0)} if pending else None++ monkeypatch.setattr(research_runs.db, "claim_next", claim)+ supervisor = research_runs.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace()))+ claimed = [supervisor._claim_account_run() for _ in range(3)]+ assert [account for account, _ in claimed] == [ALICE, BOB, ALICE]+ assert [run["id"] for _, run in claimed] == ["alice-1", "bob-1", "alice-2"]+++def test_folder_sync_claim_carries_account_data(monkeypatch):+ from core.rag import folder_sync++ monkeypatch.setattr(folder_sync, "job_accounts", lambda: [ALICE, BOB])+ monkeypatch.setattr(+ folder_sync,+ "_next_job",+ lambda: ("job-b", "folder-b") if current_account() == BOB else None,+ )+ assert folder_sync._next_account_job() == (BOB, "job-b", "folder-b")+++def test_rag_lease_keys_include_the_account(monkeypatch):+ from core.rag import job_leases++ monkeypatch.setattr(job_leases, "_active", set())+ monkeypatch.setattr(job_leases, "_thread", SimpleNamespace(is_alive = lambda: True))+ run_as(ALICE, job_leases.activate, "ingestion", "same-id")+ run_as(BOB, job_leases.activate, "ingestion", "same-id")+ assert job_leases._active == {(ALICE, "ingestion", "same-id"), (BOB, "ingestion", "same-id")}+++def test_owner_training_start_status_cancel_bytes_are_unchanged(training, monkeypatch):+ from routes import training as route++ backend, _, captured = training+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ monkeypatch.setattr(route, "get_training_backend", lambda: backend)+ assert start_training(backend, OWNER) is True+ assert captured[0]["args"][0:2] == ("core.training.worker", "run_training_process")+ assert "account" not in captured[0]["kwargs"]+ status = asyncio.run(route.get_training_status("unsloth"))+ expected = {+ "job_id": "job-a",+ "start_request_id": None,+ "start_request_state": None,+ "phase": "configuring",+ "is_training_running": True,+ "eval_enabled": False,+ "message": "Initializing training...",+ "error": None,+ "warnings": [],+ "details": {+ "epoch": 0,+ "step": 0,+ "total_steps": 0,+ "loss": None,+ "learning_rate": None,+ "output_dir": None,+ },+ "metric_history": None,+ }+ assert status.model_dump_json() == json.dumps(expected, separators = (",", ":"))+ assert backend.stop_training(save = False, expected_job_id = "job-a") is True+++def test_retired_background_jobs_do_not_recreate_storage(monkeypatch):+ from core.rag import account_db+ from storage import research_runs_db++ monkeypatch.setattr(jobs, "_retired", {ALICE.account_id})+ opened = []+ monkeypatch.setattr(+ account_db._db, "get_connection", lambda: opened.append(current_account()) or "rag"+ )+ monkeypatch.setattr(+ research_runs_db,+ "_studio_connection",+ lambda: opened.append(current_account()) or "research",+ )+ for getter in (account_db.get_connection, research_runs_db.get_connection):+ with pytest.raises(RuntimeError, match = "retired"):+ run_as(ALICE, getter)+ assert opened == []+ assert run_as(BOB, account_db.get_connection) == "rag"+ assert run_as(OWNER, research_runs_db.get_connection) == "research"+++def test_retirement_stops_the_captured_worker_process(training, monkeypatch):+ from core.rag import folder_sync, ingestion+ from core import research_runs+ from hub.services.datasets import downloads++ backend, process, _ = training+ assert start_training(backend)+ monkeypatch.setattr(jobs, "_services", {backend})+ monkeypatch.setattr(backend, "_account_cancel", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+ monkeypatch.setattr(downloads, "retire_account_downloads", lambda: None)+ jobs.retire_account_jobs(ALICE)+ assert process.terminated and not process.is_alive()+++def test_renaming_an_account_does_not_change_job_ownership(training):+ backend, _, _ = training+ assert start_training(backend)+ renamed = AccountContext(ALICE.account_id, "alice-renamed")+ assert run_as(renamed, jobs.job_is_foreign, backend) is False+ assert run_as(BOB, jobs.job_is_foreign, backend) is True+++def test_rag_embedder_never_reads_the_owner_hf_login(monkeypatch):+ from core.rag import embeddings+ import huggingface_hub++ monkeypatch.setattr(huggingface_hub, "get_token", lambda: "owner-secret")+ assert run_as(ALICE, embeddings._ambient_hf_token) is False+ assert run_as(OWNER, embeddings._ambient_hf_token) == "owner-secret"+++def test_foreign_completed_job_reports_idle(export, monkeypatch):+ from routes import export as route++ backend, _ = export+ backend._result_account = ALICE+ backend.current_checkpoint = "alice-private"+ monkeypatch.setattr(route, "get_export_backend", lambda: backend)+ result = asyncio.run(arun_as(BOB, route.get_export_status("bob")))+ assert result.current_checkpoint is None and result.active_op_kind is None+ assert result.is_export_active is False+++def test_status_pump_restart_keeps_the_original_owner_after_multi_mode_begins(+ training, monkeypatch+):+ from core.training import training as module++ backend, process, _ = training+ backend._proc = process+ backend._pump_running = True+ backend._event_queue = queue.Queue()+ process.start()+ spawned = []+ monkeypatch.setattr(+ module, "account_thread", lambda **kwargs: spawned.append(kwargs) or FakeThread()+ )+ run_as(ALICE, backend._ensure_pump_alive)+ assert spawned[0]["account"] == OWNER+++def test_new_account_waits_for_previous_jobs_finalizer(training):+ backend, process, _ = training+ assert start_training(backend)+ process.running = False+ backend._progress = TrainingProgress(is_completed = True)+ backend._pump_thread = SimpleNamespace(is_alive = lambda: True)+ with pytest.raises(HTTPException) as exc:+ run_as(BOB, backend.reserve_start_request, "bob", "b")+ assert exc.value.status_code == 409+ assert backend._result_account == ALICE+++def test_only_server_resolved_resource_pins_can_use_shared_hub_cache(monkeypatch):+ from utils import hf_cache_settings++ shared = run_as(OWNER, workspace_root) / "shared-model-cache"+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: shared)+ config = {"model_snapshot_path": str(shared / "model/snapshots/revision")}+ with pytest.raises(HTTPException):+ run_as(ALICE, jobs.validate_job_paths, config)+ run_as(ALICE, jobs.validate_job_paths, config, cached_resources = True)+ with pytest.raises(HTTPException):+ run_as(+ ALICE,+ jobs.validate_job_paths,+ {"model_snapshot_path": str(run_as(BOB, outputs_root))},+ cached_resources = True,+ )+++def test_s3_download_temporary_files_belong_to_the_account(monkeypatch):+ from core.training import s3_dataset+ from utils.paths import tmp_root++ monkeypatch.setattr(s3_dataset, "boto3_available", lambda: True)+ monkeypatch.setattr(s3_dataset, "_list_dataset_keys", lambda *args: ["data.jsonl"])+ client = SimpleNamespace(download_file = lambda bucket, key, path: Path(path).write_text("{}\n"))+ monkeypatch.setattr(s3_dataset, "_build_s3_client", lambda config: client)+ download = run_as(ALICE, s3_dataset.prepare_s3_dataset_download, {"bucket": "bucket"})+ try:+ assert Path(download.temp_dir).parent == run_as(ALICE, tmp_root)+ assert Path(download.files[0]).read_text() == "{}\n"+ finally:+ download.cleanup()+++def test_retirement_keeps_checkpoint_files_for_directory_renaming(monkeypatch):+ from core.training.training import _cleanup_cancelled_checkpoints++ root = run_as(ALICE, outputs_root) / "run" / "checkpoint-1"+ root.mkdir(parents = True)+ checkpoint = root / "adapter.safetensors"+ checkpoint.write_text("preserve")+ monkeypatch.setattr(jobs, "_retired", {ALICE.account_id})+ run_as(ALICE, _cleanup_cancelled_checkpoints, root.parent)+ assert checkpoint.read_text() == "preserve"+++def test_retirement_attempts_every_service_when_one_cancel_fails(monkeypatch):+ from core.rag import folder_sync, ingestion+ from core import research_runs+ from hub.services.datasets import downloads+ from core.export.orchestrator import ExportOrchestrator++ broken = ExportOrchestrator()+ healthy = ExportOrchestrator()+ broken._result_account = healthy._result_account = ALICE+ cancelled = []++ def fail():+ raise RuntimeError("cancel failed")++ monkeypatch.setattr(broken, "_account_cancel", fail)+ monkeypatch.setattr(healthy, "_account_cancel", lambda: cancelled.append("healthy"))+ monkeypatch.setattr(jobs, "_services", [broken, healthy])+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: cancelled.append("folders"))+ monkeypatch.setattr(+ ingestion, "retire_account_ingestions", lambda: cancelled.append("ingestion")+ )+ monkeypatch.setattr(+ research_runs, "retire_account_research", lambda account: cancelled.append("research")+ )+ monkeypatch.setattr(+ downloads, "retire_account_downloads", lambda: cancelled.append("downloads")+ )+ with pytest.raises(RuntimeError, match = "keep its directories"):+ jobs.retire_account_jobs(ALICE)+ assert cancelled == ["healthy", "downloads", "ingestion", "folders", "research"]+++def test_unstructured_recipe_path_lists_are_contained():+ with pytest.raises(HTTPException):+ run_as(+ ALICE,+ jobs.validate_recipe_access,+ {+ "seed_config": {+ "source": {+ "seed_type": "unstructured",+ "paths": [str(run_as(BOB, workspace_root) / "notes.txt")],+ }+ }+ },+ )+++def test_hugging_face_recipe_seeds_use_explicit_account_credentials():+ source = {+ "seed_type": "hf",+ "path": "datasets/org/dataset/**/*.parquet",+ "token": "alice-token",+ }+ run_as(ALICE, jobs.validate_recipe_access, {"source": source})+ with pytest.raises(HTTPException):+ run_as(ALICE, jobs.validate_recipe_access, {"source": {**source, "path": "/owner/private"}})+ with pytest.raises(HTTPException):+ run_as(ALICE, jobs.validate_recipe_access, {"source": {**source, "token": ""}})++[email protected]("account", [OWNER, ALICE])+def test_recipe_workflow_key_belongs_to_the_starting_account(account, monkeypatch):+ from routes.data_recipe import jobs as route+ from auth import storage++ captured = []+ monkeypatch.setattr(+ route, "_resolve_local_v1_endpoint", lambda request: "http://127.0.0.1:8888/v1"+ )+ monkeypatch.setattr(+ route, "_ensure_selected_local_model_loaded", lambda recipe, local_names: None+ )+ monkeypatch.setattr(+ storage,+ "create_api_key",+ lambda **kwargs: captured.append(kwargs) or ("sk-private", {"id": 42}),+ )+ recipe = {+ "model_providers": [{"name": "local", "is_local": True}],+ "model_configs": [{"provider": "local", "alias": "model"}],+ "columns": [{"column_type": "llm-text", "model_alias": "model"}],+ }+ assert (+ run_as(account, route._inject_local_providers, recipe, SimpleNamespace(), "generation")+ == 42+ )+ assert captured[0]["username"] == account.username+ assert captured[0]["expect_gen"] == "generation"+ assert recipe["model_providers"][0]["api_key"] == "sk-private"+++def test_diffusion_status_releases_ownership_after_child_teardown():+ from core.training.diffusion_training_service import DiffusionTrainingService++ service = DiffusionTrainingService()+ service._result_account = service.job_account = ALICE+ service._proc = FakeProcess()+ service._state.update(status = "completed", base_model = "alice-private")+ state = run_as(BOB, service.status)+ assert service.job_account is None+ assert state["status"] == "idle" and state["base_model"] is None+++def test_startup_reconciliation_visits_every_account_database(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(jobs, "job_accounts", lambda: [OWNER, ALICE, BOB])+ alice_db = run_as(ALICE, studio_db_path)+ alice_db.parent.mkdir(parents = True, exist_ok = True)+ alice_db.write_bytes(b"")+ # BOB has never used Studio: reconciling would create a database for him.+ assert jobs.startup_reconciliation_accounts() == [OWNER, ALICE]+ assert not run_as(BOB, studio_db_path).exists()+++def test_startup_settles_the_runs_of_every_account():+ import ast++ source = (Path(jobs.__file__).resolve().parents[2] / "main.py").read_text(encoding = "utf-8")+ direct = [+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id in {"cleanup_orphaned_runs", "reconcile_orphaned_runs"}+ ]+ assert direct == []+ assert "startup_reconciliation_accounts" in source+++def test_a_managed_download_blocks_the_shared_dataset_delete(monkeypatch):+ from hub.services.datasets import downloads+ from hub.services.datasets.cache_inventory import delete_cached_dataset_response++ from hub.services.datasets import cache_inventory++ monkeypatch.setattr(downloads, "_account_registries", {})+ monkeypatch.setattr(downloads, "_deleting", set(), raising = False)+ deleted = []+ monkeypatch.setattr(+ cache_inventory,+ "_delete_cached_dataset_blocking",+ lambda *args, **kwargs: deleted.append(args) or {"deleted": True},+ )+ alice = run_as(ALICE, downloads._account_registry)+ alice.claim("org/dataset", "http", repo_type = "dataset", repo_id = "org/dataset")+ with pytest.raises(HTTPException) as exc:+ asyncio.run(delete_cached_dataset_response("org/dataset"))+ assert exc.value.status_code == 400+ assert "Cancel the active download" in exc.value.detail+ assert deleted == []+++def test_an_account_registry_opened_during_a_delete_cannot_claim(monkeypatch):+ from hub.services.datasets import downloads++ monkeypatch.setattr(downloads, "_account_registries", {})+ monkeypatch.setattr(downloads, "_deleting", set(), raising = False)+ assert downloads.begin_delete("org/dataset")+ bob = run_as(BOB, downloads._account_registry)+ claimed, state = bob.claim("org/dataset", "http", repo_type = "dataset", repo_id = "org/dataset")+ assert not claimed and state == "deleting"+ downloads.end_delete("org/dataset")+ assert run_as(BOB, downloads._account_registry).claim(+ "org/dataset", "http", repo_type = "dataset", repo_id = "org/dataset"+ )[0]+++def test_dataset_download_progress_refuses_another_accounts_private_repo(monkeypatch):+ from hub.services.datasets import downloads+ from hub.services.models import account_access++ monkeypatch.setattr(downloads, "_account_registries", {})+ monkeypatch.setattr(account_access, "repo_is_public", lambda *a, **k: False)+ monkeypatch.setattr(+ account_access,+ "model_grants",+ lambda: {"dataset:org/private-set"} if current_account() == ALICE else set(),+ )+ scanned = []++ async def progress(**kwargs):+ scanned.append(kwargs["repo_id"])+ return {"downloaded_bytes": 41, "cache_path": "/shared/hub/datasets--org--private-set"}++ monkeypatch.setattr(downloads.snapshot_progress, "snapshot_progress_response", progress)+ read = downloads.get_dataset_download_progress_response("org/private-set")+ assert asyncio.run(arun_as(ALICE, read))["downloaded_bytes"] == 41+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ arun_as(BOB, downloads.get_dataset_download_progress_response("org/private-set"))+ )+ assert exc.value.status_code == 404+ assert scanned == ["org/private-set"]+++def test_a_second_account_cannot_start_the_same_dataset_download(monkeypatch):+ from hub.services.datasets import downloads++ monkeypatch.setattr(downloads, "_account_registries", {})+ monkeypatch.setattr(downloads, "_deleting", set(), raising = False)+ monkeypatch.setattr(downloads, "resolve_cached_repo_id_case", lambda repo_id, **_k: repo_id)+ monkeypatch.setattr(+ downloads.download_registry, "download_transport_unavailable_reason", lambda _t: None+ )+ monkeypatch.setattr(downloads.download_manifest, "clear_cancel_marker", lambda *a, **k: None)+ monkeypatch.setattr(downloads.account_access, "authorize_download", lambda *a, **k: None)+ launched = []+ monkeypatch.setattr(+ downloads.download_lifecycle,+ "launch_worker",+ lambda registry, key, **kwargs: launched.append(key) or "running",+ )++ def start(account):+ request = SimpleNamespace(repo_id = "Org/Data", use_xet = False, transport_mode = "http")+ return asyncio.run(arun_as(account, downloads.download_dataset_response(request)))++ assert start(ALICE)["accepted"]+ bob = start(BOB)+ assert not bob["accepted"] and not bob["attached"]+ assert launched == ["org/data"]+++def test_dataset_download_request_authorizes_before_reporting_a_foreign_job(monkeypatch):+ from hub.services.datasets import downloads+ from hub.services.models import account_access++ monkeypatch.setattr(downloads, "_account_registries", {})+ monkeypatch.setattr(downloads, "_deleting", set(), raising = False)+ monkeypatch.setattr(downloads, "resolve_cached_repo_id_case", lambda repo_id, **_k: repo_id)+ monkeypatch.setattr(+ downloads.download_registry, "download_transport_unavailable_reason", lambda _t: None+ )+ monkeypatch.setattr(downloads.download_manifest, "clear_cancel_marker", lambda *a, **k: None)+ monkeypatch.setattr(+ downloads.download_lifecycle, "launch_worker", lambda registry, key, **kwargs: "running"+ )++ def authorize(repo_id, repo_type, hf_token):+ if current_account() == BOB:+ raise HTTPException(status_code = 404, detail = "Repository not found")++ monkeypatch.setattr(account_access, "authorize_download", authorize)++ def start(account):+ request = SimpleNamespace(repo_id = "org/private", use_xet = False, transport_mode = "http")+ return asyncio.run(arun_as(account, downloads.download_dataset_response(request)))++ assert start(ALICE)["accepted"]+ with pytest.raises(HTTPException) as exc:+ start(BOB)+ assert exc.value.status_code == 404+++def test_dataset_transport_status_refuses_another_accounts_private_repo(monkeypatch):+ from hub.services.datasets import downloads+ from hub.services.models import account_access++ monkeypatch.setattr(downloads, "_account_registries", {})+ monkeypatch.setattr(account_access, "repo_is_public", lambda *a, **k: False)+ monkeypatch.setattr(+ account_access,+ "model_grants",+ lambda: {"dataset:org/private-set"} if current_account() == ALICE else set(),+ )+ monkeypatch.setattr(downloads, "has_active_incomplete_blobs", lambda *a: True)+ monkeypatch.setattr(+ downloads.download_registry, "read_active_transport_marker", lambda *a: "http"+ )+ monkeypatch.setattr(downloads.download_registry, "is_resumable_partial", lambda *a: True)+ read = downloads.get_dataset_transport_status_response("org/private-set")+ assert asyncio.run(arun_as(ALICE, read))["has_partial"]+ with pytest.raises(HTTPException) as exc:+ asyncio.run(+ arun_as(BOB, downloads.get_dataset_transport_status_response("org/private-set"))+ )+ assert exc.value.status_code == 404+++def test_startup_reconciliation_settles_a_deactivated_accounts_interrupted_runs(+ tmp_path, monkeypatch+):+ from auth import storage+ from storage import studio_db++ home = tmp_path / "install"+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ monkeypatch.setattr(storage, "DB_PATH", home / "auth" / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", home / "auth" / ".bootstrap_password")+ monkeypatch.setattr(storage, "_credential_encryption_key_cache", None)+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ policy.invalidate_account_cache()+ try:+ storage.create_initial_user("unsloth", "account-password", "unsloth-jwt-secret")+ storage.create_initial_user("alice", "account-password", "alice-jwt-secret")+ alice = storage.get_account("alice")+ run_as(+ alice,+ studio_db.create_run,+ id = "interrupted",+ model_name = "m",+ dataset_name = "d",+ config_json = "{}",+ started_at = "2026-01-01T00:00:00Z",+ total_steps = 10,+ )+ assert run_as(alice, studio_db.get_run, "interrupted")["status"] == "running"++ storage.set_account_active(alice.account_id, False)+ policy.invalidate_account_cache()++ reconciled = jobs.startup_reconciliation_accounts()+ assert alice.account_id in {account.account_id for account in reconciled}+ for account in reconciled:+ run_as(account, studio_db.cleanup_orphaned_runs)+ assert run_as(alice, studio_db.get_run, "interrupted")["status"] == "error"+ finally:+ policy.invalidate_account_cache()+++def test_retirement_cancels_model_downloads_and_no_late_grant_recreates_the_workspace(+ tmp_path, monkeypatch+):+ """A model download of a deleted account is killed, and a worker that still completes cannot+ rebuild the workspace retirement just renamed aside."""+ import subprocess+ import sys++ from hub.services import download_lifecycle+ from hub.services.models import account_access, downloads as model_downloads+ from hub.utils import download_registry+ from routes.accounts import retire_account_roots+ from core.rag import folder_sync, ingestion+ from core import research_runs+ from hub.services.datasets import downloads as dataset_downloads+ from utils.paths import storage_roots as roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "Documents"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(jobs, "_services", [])+ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+ monkeypatch.setattr(dataset_downloads, "retire_account_downloads", lambda: None)++ repo_id = "acme/retired-model"+ registry = model_downloads._registry+ key = model_downloads._download_job_key(repo_id, None)+ claimed, state = registry.claim(+ key, download_registry.TRANSPORT_HTTP, repo_type = "model", repo_id = repo_id+ )+ assert claimed, state+ run_as(ALICE, download_lifecycle.record_download_account, registry, key)+ proc = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(120)"], stderr = subprocess.PIPE+ )+ assert registry.register_process(key, proc)+ workspace = run_as(ALICE, roots.workspace_root)+ workspace.mkdir(parents = True, exist_ok = True)++ try:+ retire_account_roots(ALICE)+ assert proc.poll() is not None, "the retired account's model worker is still running"+ assert not workspace.exists()++ # A worker of the same account that still reaches a clean exit must not write the account back.+ registry.drop_process(key, proc)+ finished = subprocess.Popen([sys.executable, "-c", "pass"], stderr = subprocess.PIPE)+ registry.register_process(key, finished)+ run_as(+ ALICE,+ lambda: download_lifecycle.finalize_worker_exit(+ registry,+ key,+ finished,+ hf_token = None,+ label = repo_id,+ log_prefix = "test",+ logger = download_lifecycle.logger,+ repo_type = "model",+ repo_id = repo_id,+ ),+ )+ assert not workspace.exists(), "a late completion recreated a deleted workspace"+ assert run_as(ALICE, account_access.model_grants) == set()+ finally:+ for handle in (proc, finished if "finished" in dir() else None):+ if handle is not None and handle.poll() is None:+ handle.kill()+ registry.set_job(key, "idle")+++def test_retirement_is_refused_while_a_start_is_in_flight(training, monkeypatch):+ """Retiring under an admitted start deadlocked on the lifecycle lock or spawned a child afterwards."""+ backend, _, _ = training+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet([backend]))+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)+ paused, resume = threading.Event(), threading.Event()++ def persist():+ paused.set()+ assert resume.wait(10)++ monkeypatch.setattr(backend, "_ensure_db_run_created", persist)+ run_as(ALICE, backend.reserve_start_request, "request", "job")+ starter = threading.Thread(+ target = lambda: run_as(+ ALICE,+ backend.start_training,+ "job",+ start_request_id = "request",+ model_name = "org/model",+ hf_token = "account-token",+ ),+ daemon = True,+ )+ starter.start()+ assert paused.wait(10)+ outcome = []+ retiring = threading.Thread(+ target = lambda: outcome.append(+ _catch(jobs.AccountRetirementError, jobs.retire_account_jobs, ALICE)+ ),+ daemon = True,+ )+ retiring.start()+ retiring.join(5)+ resume.set()+ starter.join(10)+ assert not retiring.is_alive() and not starter.is_alive()+ assert isinstance(outcome[0], jobs.AccountRetirementError)+++def _catch(error, fn, *args):+ try:+ return fn(*args)+ except error as exc:+ return exc+++def test_deleting_an_account_cancels_its_video_render_and_keeps_its_roots(monkeypatch, tmp_path):+ from core.inference import video+ from routes.accounts import retire_account_roots+ from utils.paths import storage_roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)+ backend = video.VideoBackend()+ monkeypatch.setattr(video, "_backend", backend)+ backend._state = SimpleNamespace(+ family = SimpleNamespace(+ name = "fam", default_fps = 24, default_num_frames = 49, frame_step = 4, frame_offset = 1+ ),+ h3_task = None,+ engine = "diffusers",+ repo_id = "r",+ )+ backend._resolve_keyframes = lambda *a, **k: (None, None, 512, 512, "t2v")+ backend._resolve_references = lambda *a, **k: None+ backend._resolve_flow_shifts = lambda *a, **k: (None, None)+ monkeypatch.setattr(video, "validate_video_request_shape", lambda *a, **k: None)+ entered, release, done = threading.Event(), threading.Event(), threading.Event()+ cancels = []++ def render(**kwargs):+ cancels.append(kwargs["cancel_event"])+ entered.set()+ try:+ assert release.wait(10)+ finally:+ with backend._lock:+ backend._generate_job_active = False+ backend._active_generate_cancel = None+ done.set()++ monkeypatch.setattr(backend, "_run_generate", render)+ root = run_as(ALICE, storage_roots.workspace_root)+ root.mkdir(parents = True)+ run_as(ALICE, backend.begin_generate, prompt = "review", steps = 5)+ try:+ assert entered.wait(10)+ with pytest.raises(jobs.AccountRetirementError):+ retire_account_roots(ALICE)+ assert root.exists() and cancels[0].is_set()+ finally:+ release.set()+ assert done.wait(10)+++def test_retirement_reaps_dataset_downloads_and_refuses_when_one_survives(tmp_path, monkeypatch):+ """A dataset worker of a deleted account must be reaped, and a failed kill must block deletion."""+ import subprocess+ import sys++ from hub.services import download_lifecycle+ from hub.services.datasets import downloads as dataset_downloads+ from hub.services.models import downloads as model_downloads+ from hub.utils import download_registry+ from core.rag import folder_sync, ingestion+ from core import research_runs++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(jobs, "_services", [])+ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+ monkeypatch.setattr(model_downloads, "retire_account_downloads", lambda: None)++ repo_id = "acme/retired-dataset"+ registry = run_as(ALICE, dataset_downloads._account_registry)+ key = dataset_downloads._download_job_key(repo_id)++ def start_worker():+ claimed, state = registry.claim(+ key, download_registry.TRANSPORT_HTTP, repo_type = "dataset", repo_id = repo_id+ )+ assert claimed, state+ run_as(ALICE, download_lifecycle.record_download_account, registry, key)+ worker = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(120)"], stderr = subprocess.PIPE+ )+ assert registry.register_process(key, worker)+ return worker++ proc = start_worker()+ try:+ jobs.retire_account_jobs(ALICE)+ assert proc.poll() is not None, "the retired account's dataset worker is still running"+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+ registry.drop_process(key, proc)+ registry.set_job(key, "idle")++ # A worker that cannot be killed must fail retirement instead of leaving the token in flight.+ jobs.restore_account_jobs(ALICE.account_id)+ survivor = start_worker()+ monkeypatch.setattr(+ survivor, "kill", lambda: (_ for _ in ()).throw(PermissionError("kill denied"))+ )+ try:+ with pytest.raises(jobs.AccountRetirementError):+ jobs.retire_account_jobs(ALICE)+ assert survivor.poll() is None+ finally:+ monkeypatch.undo()+ survivor.kill()+ survivor.wait()+ registry.drop_process(key, survivor)+ registry.set_job(key, "idle")+++def test_a_late_finalizer_cannot_recreate_a_deleted_accounts_workspace(monkeypatch, tmp_path):+ """cancel_all() only signals, so a finalizer still running after the rename must not mkdir the account back."""+ from core.inference import image_gallery+ from routes.accounts import retire_account_roots+ from state import active_generations+ from storage import studio_db+ from utils.paths import storage_roots+ from utils.paths.storage_roots import RetiredAccountError++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)+ active_generations.reset_for_tests()+ root = run_as(ALICE, storage_roots.workspace_root)+ root.mkdir(parents = True)++ cancel_event = threading.Event()+ started, gate, finished = threading.Event(), threading.Event(), threading.Event()+ refused = []++ def producer():+ with active_generations.ActiveGeneration(+ cancel_event, run_id = "run-1", thread_id = "t-1", account_id = ALICE.account_id+ ):+ started.set()+ assert cancel_event.wait(10)+ # The finalizers that run after the cancel is observed: db.finish_run, then the gallery write.+ assert gate.wait(10)+ for call in (studio_db.get_connection, image_gallery.gallery_dir):+ with pytest.raises(RetiredAccountError):+ run_as(ALICE, call)+ refused.append(call)+ finished.set()++ worker = threading.Thread(target = producer, daemon = True)+ worker.start()+ try:+ assert started.wait(10)+ retire_account_roots(ALICE)+ assert not root.exists()+ finally:+ gate.set()+ assert finished.wait(10)+ worker.join(10)+ assert len(refused) == 2+ assert not root.exists()+++def test_retirement_reaps_stt_downloads_and_fences_a_parked_start(tmp_path, monkeypatch):+ """A dictation download of a deleted account is cancelled, its engine is freed for other+ accounts, and a start parked on remote validation cannot spawn a worker afterwards."""+ import subprocess+ import sys++ from core import research_runs+ from core.rag import folder_sync, ingestion+ from hub.services.datasets import downloads as dataset_downloads+ from hub.services.models import account_access as access, downloads as model_downloads+ from routes import inference++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(jobs, "_services", [])+ monkeypatch.setattr(ingestion, "retire_account_ingestions", lambda: None)+ monkeypatch.setattr(folder_sync, "retire_account_sync", lambda: None)+ monkeypatch.setattr(research_runs, "retire_account_research", lambda account: None)+ monkeypatch.setattr(dataset_downloads, "retire_account_downloads", lambda: None)+ monkeypatch.setattr(model_downloads, "retire_account_downloads", lambda: None)+ monkeypatch.setattr(inference, "_stt_download_accounts", {})+ monkeypatch.setattr(inference, "_stt_grant_pending", {})+ monkeypatch.setattr(inference, "_stt_repo_reference", lambda model, engine: model)+ monkeypatch.setattr(access, "authorize_download", lambda *a: None)+ monkeypatch.setattr(access, "account_hf_token", lambda token: "alice-token")++ # A sidecar-shaped module whose transfer is a real child process.+ handles = {"proc": None, "tokens": []}++ def start_model_download(+ model,+ hf_token = None,+ revision = None,+ ):+ handles["tokens"].append(hf_token)+ handles["proc"] = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(120)"], stderr = subprocess.PIPE+ )++ def cancel_model_download():+ proc = handles["proc"]+ if proc is None or proc.poll() is not None:+ return False+ proc.terminate()+ proc.wait(timeout = 10)+ return True++ module = SimpleNamespace(+ start_model_download = start_model_download,+ download_status = lambda: {+ "downloading": handles["proc"] is not None and handles["proc"].poll() is None+ },+ cancel_model_download = cancel_model_download,+ is_model_downloaded = lambda model: False,+ )+ monkeypatch.setattr(inference, "_stt_download_module", lambda engine: module)+ monkeypatch.setattr(inference, "_resolve_serving_stt_engine", lambda engine: "transformers")++ try:+ run_as(+ ALICE,+ inference._start_account_stt_download,+ module,+ "transformers",+ "org/private",+ "alice-token",+ )+ worker = handles["proc"]+ assert worker.poll() is None+ jobs.retire_account_jobs(ALICE)+ assert worker.poll() is not None, "the retired account's dictation worker is still running"+ assert inference._stt_download_accounts == {}+ # The engine must not stay claimed by an account that no longer exists.+ run_as(+ BOB,+ inference._start_account_stt_download,+ module,+ "transformers",+ "org/other",+ "bob-token",+ )+ handles["proc"].kill()++ # A start parked on remote validation when retirement lands must not reach the worker.+ jobs.restore_account_jobs(ALICE.account_id)+ handles["proc"], handles["tokens"] = None, []+ parked, release = threading.Event(), threading.Event()++ def validate_remote_model(model, token = None):+ parked.set()+ assert release.wait(20)+ return {"revision": "0" * 40}++ from core.inference import stt_sidecar+ from models.inference import SttLoadRequest++ monkeypatch.setattr(stt_sidecar, "validate_remote_model", validate_remote_model)+ outcome = []+ request = SttLoadRequest(model = "org/private", engine = "transformers")+ thread = threading.Thread(+ target = lambda: outcome.append(+ _catch(+ HTTPException,+ lambda: asyncio.run(+ arun_as(+ ALICE,+ inference.stt_download(request, current_subject = "alice", hf_token = None),+ )+ ),+ )+ ),+ daemon = True,+ )+ thread.start()+ assert parked.wait(20)+ jobs.retire_account_jobs(ALICE)+ release.set()+ thread.join(30)+ assert not thread.is_alive()+ assert isinstance(outcome[0], HTTPException) and outcome[0].status_code == 403+ assert handles["proc"] is None, "a download spawned for an account retired mid-validation"+ assert handles["tokens"] == []+ finally:+ for handle in (handles["proc"],):+ if handle is not None and handle.poll() is None:+ handle.kill()+++def test_a_creation_in_flight_cannot_outlive_the_rename_that_retires_the_roots(+ monkeypatch, tmp_path+):+ """The tombstone is only consulted once the roots are gone, so the check and the mkdir must+ share the retirement lock: otherwise a finalizer that passed the check recreates the account."""+ from routes.accounts import retire_account_roots+ from state import active_generations+ from utils.paths import storage_roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)+ monkeypatch.setattr("core.inference.mcp_client.close_mcp_sessions", lambda: None)+ monkeypatch.setattr("core.inference.mcp_client.invalidate_tool_cache", lambda: None)+ active_generations.reset_for_tests()+ root = run_as(ALICE, storage_roots.workspace_root)+ root.mkdir(parents = True)++ checked, release = threading.Event(), threading.Event()+ real_ensure_dir = storage_roots._mkdir++ def slow_ensure_dir(path):+ # Past the existence gate of ensure_account_dir; hand the CPU to the deleting thread.+ checked.set()+ assert release.wait(10)+ return real_ensure_dir(path)++ monkeypatch.setattr(storage_roots, "_mkdir", slow_ensure_dir)+ outcome, retirement = {}, {}++ def finalizer():+ try:+ outcome["path"] = run_as(+ ALICE,+ lambda: storage_roots.ensure_account_dir(storage_roots.account_path("images")),+ )+ except BaseException as exc: # noqa: BLE001+ outcome["error"] = exc++ def deleter():+ try:+ retire_account_roots(ALICE)+ except BaseException as exc: # noqa: BLE001+ retirement["error"] = exc++ worker = threading.Thread(target = finalizer, daemon = True)+ worker.start()+ try:+ assert checked.wait(10)+ remover = threading.Thread(target = deleter, daemon = True)+ remover.start()+ remover.join(2)+ assert remover.is_alive(), "the rename ran while a directory creation was mid-flight"+ finally:+ release.set()+ worker.join(10)+ remover.join(10)+ assert not retirement, retirement+ assert not root.exists(), f"the deleted private root was recreated: {outcome}"+ aside = [p for p in (tmp_path / "home" / "accounts").iterdir() if p.name != ALICE.account_id]+ assert aside and (aside[0] / "images").exists(), "the in-flight creation was not renamed aside"++[email protected]("engine", ["diffusers", "sd_cpp"])+def test_deleting_an_account_cancels_its_image_generation_and_keeps_its_roots(+ monkeypatch, tmp_path, engine+):+ """An image render holds the GPU and the account's uploads, and its gallery write would hit the+ retired root as a 500; retirement must stop it and refuse until it has drained, like video."""+ from core.inference import diffusion, sd_cpp_backend+ from hub.services.models import account_access as access+ from routes.accounts import retire_account_roots+ from utils.account_context import current_account_id+ from utils.paths import storage_roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ monkeypatch.setattr(access, "_generation_holders", {})+ monkeypatch.setattr(access, "_generation_accounts", {})+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)++ entered, release, done = threading.Event(), threading.Event(), threading.Event()+ cancel = threading.Event()++ if engine == "diffusers":+ backend = diffusion.DiffusionBackend()+ monkeypatch.setattr(diffusion, "_diffusion_backend", backend)++ def denoise():+ # The real slot: it binds the cancel event and the acting account under the lock.+ with backend._generation_slot(cancel):+ entered.set()+ release.wait(10)+ done.set()+ else:+ backend = sd_cpp_backend.SdCppDiffusionBackend()+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_backend", backend)++ def denoise():+ with backend._generate_lock, access.media_generation_slot("diffusion"):+ with backend._lock:+ backend._active_generate_cancel = cancel+ backend._active_generate_account = current_account_id()+ entered.set()+ release.wait(10)+ with backend._lock:+ backend._active_generate_cancel = None+ backend._active_generate_account = None+ done.set()++ root = run_as(ALICE, storage_roots.workspace_root)+ root.mkdir(parents = True)+ thread = threading.Thread(target = lambda: run_as(ALICE, denoise))+ thread.start()+ try:+ assert entered.wait(10)+ with pytest.raises(jobs.AccountRetirementError):+ retire_account_roots(ALICE)+ assert root.exists(), "roots were retired under a live image generation"+ assert cancel.is_set(), "the account's image generation was never cancelled"+ finally:+ release.set()+ cancel.set()+ assert done.wait(10)+ thread.join(10)+++def test_retirement_leaves_another_accounts_image_generation_alone(monkeypatch, tmp_path):+ """The cancel is account-scoped: BOB's render survives ALICE's deletion."""+ from core.inference import diffusion+ from hub.services.models import account_access as access+ from routes.accounts import retire_account_roots+ from utils.paths import storage_roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ monkeypatch.setattr(access, "_generation_holders", {})+ monkeypatch.setattr(access, "_generation_accounts", {})+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)++ backend = diffusion.DiffusionBackend()+ monkeypatch.setattr(diffusion, "_diffusion_backend", backend)+ entered, release, done = threading.Event(), threading.Event(), threading.Event()+ cancel = threading.Event()++ def denoise():+ with backend._generation_slot(cancel):+ entered.set()+ release.wait(10)+ done.set()++ run_as(ALICE, storage_roots.workspace_root).mkdir(parents = True)+ thread = threading.Thread(target = lambda: run_as(BOB, denoise))+ thread.start()+ try:+ assert entered.wait(10)+ retire_account_roots(ALICE)+ assert not cancel.is_set(), "another account's image generation was cancelled"+ finally:+ release.set()+ cancel.set()+ assert done.wait(10)+ thread.join(10)diff --git a/studio/backend/tests/test_linux_external_media_paths.py b/studio/backend/tests/test_linux_external_media_paths.pyindex 9fb482cf408..5fec6e1118a 100644--- a/studio/backend/tests/test_linux_external_media_paths.py+++ b/studio/backend/tests/test_linux_external_media_paths.py@@ -62,7 +62,6 @@ def _stub_linux_path_checks(monkeypatch, module):def _stub_hub_scan_folder_db(monkeypatch):- monkeypatch.setattr(scan_folders, "_ensure_schema", lambda _conn: None)monkeypatch.setattr(scan_folders, "get_connection", _ExistingScanFolderConn)diff --git a/studio/backend/tests/test_llama_compat_routes.py b/studio/backend/tests/test_llama_compat_routes.pyindex 94550876224..e76ee8c6af0 100644--- a/studio/backend/tests/test_llama_compat_routes.py+++ b/studio/backend/tests/test_llama_compat_routes.py@@ -834,3 +834,30 @@ def test_the_version_lookup_leaves_the_event_loop():src = inspect.getsource(_load().studio_version)assert "to_thread" in src, "the version handler must resolve off the event loop"+++def test_props_hides_a_resident_that_belongs_to_another_account(monkeypatch):+ from hub.services.models import account_access++ upstream = {"model_path": "/media/models/alice-private.gguf", "chat_template": "ALICE_TEMPLATE"}+ mod = _load(backend = _Backend(props = upstream))+ monkeypatch.setattr(account_access, "managed_account", lambda: True)+ monkeypatch.setattr(account_access, "resident_hidden", lambda modality, reference = None: True)+ with _client(mod) as c:+ for path in ("/props", "/props/", "/v1/props", "/v1/props/"):+ raw = c.get(path)+ assert raw.status_code == 200+ assert raw.json() == {"loaded": True, "yours": False}+ assert "ALICE_TEMPLATE" not in raw.text and "Qwen" not in raw.text++ monkeypatch.setattr(account_access, "resident_hidden", lambda modality, reference = None: False)+ with _client(mod) as c:+ assert c.get("/props").json()["chat_template"] == "ALICE_TEMPLATE"+ monkeypatch.setattr(account_access, "managed_account", lambda: False)+ monkeypatch.setattr(+ account_access,+ "resident_hidden",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("owner path consulted policy")),+ )+ with _client(mod) as c:+ assert c.get("/props").json()["model_path"] == "unsloth/Qwen3.8-27B-GGUF"diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex 6f81aaf3b26..bdc55a0850d 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -5218,7 +5218,7 @@ def test_provisional_mcp_card_carries_server_display_name(tmp_path, monkeypatch)from storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())mcp_servers_db.create_server(id = "a3f9c1d2e4b6f807", display_name = "GitHub", url = "https://a/m")tool_name = "mcp__a3f9c1d2e4b6f807__create_issue"@@ -5248,7 +5248,7 @@ def test_provisional_non_mcp_card_omits_mcp_server(tmp_path, monkeypatch):from storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())big_code = "total = 0\n" + "\n".join(f"total += {i}" for i in range(120))first_stream = _streamed_structured_tool_call("python", {"code": big_code}, "call_py")diff --git a/studio/backend/tests/test_local_options_account_access.py b/studio/backend/tests/test_local_options_account_access.pynew file mode 100644index 00000000000..85defed4afd--- /dev/null+++ b/studio/backend/tests/test_local_options_account_access.py@@ -0,0 +1,80 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++from pathlib import Path++import pytest++from auth import policy+from hub.services.models import account_access+from utils import hf_cache_settings+from utils.account_context import AccountContext, OWNER, run_as++ALICE = AccountContext("a" * 32, "alice")++_CARD = """---+configs:+- config_name: secret_config+ data_files:+ - split: secret_split+ path: data.csv+---+"""+++def shared_cache(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ cache = tmp_path / "hub-cache"+ for repo in ("public--set", "private--set"):+ snapshot = cache / f"datasets--{repo}" / "snapshots" / "rev"+ snapshot.mkdir(parents = True)+ (snapshot / "README.md").write_text(_CARD, encoding = "utf-8")+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(cache))+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])+ monkeypatch.setattr(account_access, "model_grants", lambda: set())+ monkeypatch.setattr(+ account_access,+ "repo_is_public",+ lambda repo_id, repo_type = "model": not repo_id.startswith("private/"),+ )+ return cache+++def _options(dataset_name: str, local_path: str | None = None):+ from hub.schemas.datasets import LocalDatasetOptionsRequest+ from hub.services.datasets import local_options+ return local_options.local_dataset_options(+ LocalDatasetOptionsRequest(dataset_name = dataset_name, local_path = local_path)+ )+++def test_a_repo_only_request_cannot_read_another_accounts_private_cached_dataset(shared_cache):+ """Omitting local_path skipped every check and resolved the installation-wide cache."""+ response = run_as(ALICE, _options, "private/set")+ assert response.cache_available is False+ assert response.splits == []+++def test_a_repo_only_request_still_reads_a_visible_cached_dataset(shared_cache):+ response = run_as(ALICE, _options, "public/set")+ assert response.cache_available is True+ assert [(item.config, item.split) for item in response.splits] == [+ ("secret_config", "secret_split")+ ]+++def test_the_owner_still_reads_any_cached_dataset(shared_cache):+ response = run_as(OWNER, _options, "private/set")+ assert response.cache_available is True+ assert response.splits+++def test_a_single_user_install_still_reads_any_cached_dataset(shared_cache, monkeypatch):+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: False)+ response = _options("private/set")+ assert response.cache_available is True+ assert response.splitsdiff --git a/studio/backend/tests/test_logger_follows_current_stdout.py b/studio/backend/tests/test_logger_follows_current_stdout.pynew file mode 100644index 00000000000..78b2eddcbaa--- /dev/null+++ b/studio/backend/tests/test_logger_follows_current_stdout.py@@ -0,0 +1,47 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""cache_logger_on_first_use freezes the logger, so the stream must be resolved per record and keep following stdout."""++import io+import sys++import structlog++from loggers.config import LogConfig, _CurrentStdoutLogger+++def test_a_cached_logger_writes_to_the_stdout_of_the_moment(monkeypatch):+ LogConfig.setup_logging(env = "production", quiet_progress_bars = False)+ logger = structlog.get_logger("tests.follows_stdout")++ first, second = io.StringIO(), io.StringIO()+ monkeypatch.setattr(sys, "stdout", first)+ logger.info("first-line") # first use: the bound logger is cached from here on+ monkeypatch.setattr(sys, "stdout", second)+ logger.info("second-line")++ assert "first-line" in first.getvalue() and "second-line" not in first.getvalue()+ assert "second-line" in second.getvalue()+++def test_the_factory_hands_out_the_current_stdout_logger():+ LogConfig.setup_logging(env = "production", quiet_progress_bars = False)+ factory = structlog.get_config()["logger_factory"]+ assert isinstance(factory("any", "args"), _CurrentStdoutLogger)+++def test_a_missing_stdout_drops_the_record_instead_of_raising(monkeypatch):+ monkeypatch.setattr(sys, "stdout", None)+ _CurrentStdoutLogger().info("nowhere")+++def test_a_closed_stdout_still_raises_like_a_print_logger(monkeypatch):+ stream = io.StringIO()+ stream.close()+ monkeypatch.setattr(sys, "stdout", stream)+ try:+ _CurrentStdoutLogger().info("closed")+ except ValueError:+ return+ raise AssertionError("a closed stream must surface, as PrintLogger does")diff --git a/studio/backend/tests/test_managed_named_model_serving.py b/studio/backend/tests/test_managed_named_model_serving.pynew file mode 100644index 00000000000..70a3fa0140d--- /dev/null+++ b/studio/backend/tests/test_managed_named_model_serving.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A managed account that names a model is never served by another account's resident model under that name."""++import asyncio++import pytest+from fastapi import HTTPException++import routes.inference as inference+from hub.services.models import account_access+++class _Request:+ def __init__(self):+ self.scope = {}+ self.state = type("State", (), {})()+++def no_switch(monkeypatch):+ import utils.openai_auto_switch_settings as settings++ monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: False)+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: False)+ monkeypatch.setattr(account_access, "require_model_access", lambda requested: None)+ monkeypatch.setattr(inference, "_loaded_slot_ident", lambda: "/alice/private.gguf")+ monkeypatch.setattr(inference, "_claim_slot_for_non_preview", lambda request: None)+++def _run(requested, *, managed, hidden, satisfies, monkeypatch):+ monkeypatch.setattr(account_access, "managed_account", lambda: managed)+ monkeypatch.setattr(account_access, "resident_hidden", lambda modality, reference = None: hidden)+ monkeypatch.setattr(inference, "_loaded_identity_satisfies", lambda requested: satisfies)+ return asyncio.run(inference._maybe_auto_switch_model(requested, _Request(), "bob"))+++def test_managed_caller_naming_another_model_is_refused_when_the_resident_is_foreign(+ no_switch, monkeypatch+):+ with pytest.raises(HTTPException) as info:+ _run(+ "review/public-model",+ managed = True,+ hidden = True,+ satisfies = False,+ monkeypatch = monkeypatch,+ )+ assert info.value.status_code == 404+ assert info.value.detail == "Model not found"+++def test_managed_caller_is_served_when_the_resident_answers_to_the_name(no_switch, monkeypatch):+ assert (+ _run(+ "review/public-model",+ managed = True,+ hidden = True,+ satisfies = True,+ monkeypatch = monkeypatch,+ )+ is None+ )+++def test_managed_caller_is_served_by_its_own_resident(no_switch, monkeypatch):+ assert (+ _run("anything", managed = True, hidden = False, satisfies = False, monkeypatch = monkeypatch)+ is None+ )+++def test_owner_keeps_the_fall_through(no_switch, monkeypatch):+ assert (+ _run(+ "review/public-model",+ managed = False,+ hidden = True,+ satisfies = False,+ monkeypatch = monkeypatch,+ )+ is None+ )+++def test_omitted_model_against_a_foreign_resident_is_refused_as_before(no_switch, monkeypatch):+ with pytest.raises(HTTPException) as info:+ _run(None, managed = True, hidden = True, satisfies = False, monkeypatch = monkeypatch)+ assert info.value.status_code == 404+++def test_a_raw_body_request_without_a_model_is_served_by_the_accounts_own_resident(+ no_switch, monkeypatch+):+ assert (+ _run(+ inference._RELOAD_ONLY_MODEL,+ managed = True,+ hidden = False,+ satisfies = False,+ monkeypatch = monkeypatch,+ )+ is None+ )+ with pytest.raises(HTTPException) as info:+ _run(+ inference._RELOAD_ONLY_MODEL,+ managed = True,+ hidden = True,+ satisfies = False,+ monkeypatch = monkeypatch,+ )+ assert info.value.status_code == 404diff --git a/studio/backend/tests/test_mcp_config_import.py b/studio/backend/tests/test_mcp_config_import.pyindex 30365d3025d..ea4718513ec 100644--- a/studio/backend/tests/test_mcp_config_import.py+++ b/studio/backend/tests/test_mcp_config_import.py@@ -19,7 +19,7 @@ from storage import mcp_servers_dbdef _reset_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())def _enable(monkeypatch):diff --git a/studio/backend/tests/test_mcp_servers.py b/studio/backend/tests/test_mcp_servers.pyindex 7df8a2c0208..aa676d69998 100644--- a/studio/backend/tests/test_mcp_servers.py+++ b/studio/backend/tests/test_mcp_servers.py@@ -12,7 +12,7 @@ from storage import mcp_servers_dbdef _reset_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())# ── storage: mcp_servers_db ─────────────────────────────────────────diff --git a/studio/backend/tests/test_mcp_stdio_api_key_gate.py b/studio/backend/tests/test_mcp_stdio_api_key_gate.pyindex 65b6a85e415..a08952fba5d 100644--- a/studio/backend/tests/test_mcp_stdio_api_key_gate.py+++ b/studio/backend/tests/test_mcp_stdio_api_key_gate.py@@ -21,7 +21,7 @@ from utils import host_policydef _reset_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())mcp_client.invalidate_tool_cache()diff --git a/studio/backend/tests/test_mcp_stdio_improvements.py b/studio/backend/tests/test_mcp_stdio_improvements.pyindex 06f3c8fc861..6d87a869a3f 100644--- a/studio/backend/tests/test_mcp_stdio_improvements.py+++ b/studio/backend/tests/test_mcp_stdio_improvements.py@@ -18,7 +18,7 @@ from storage import mcp_servers_dbdef _reset_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())def _enable(monkeypatch):diff --git a/studio/backend/tests/test_mcp_stdio_pr5863.py b/studio/backend/tests/test_mcp_stdio_pr5863.pyindex cda68c9c4fa..439e7145dbe 100644--- a/studio/backend/tests/test_mcp_stdio_pr5863.py+++ b/studio/backend/tests/test_mcp_stdio_pr5863.py@@ -20,7 +20,7 @@ from utils import host_policydef _reset_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())# The discovered-tool cache is process-global and keyed by server id; tests# reuse "stdio1", so clear it (and the failure cool-off) for isolation —# otherwise a prior test's warm cache makes discovery skip its probe.diff --git a/studio/backend/tests/test_mcp_stdio_real_server.py b/studio/backend/tests/test_mcp_stdio_real_server.pyindex 2c253be26fb..43a811ef1ef 100644--- a/studio/backend/tests/test_mcp_stdio_real_server.py+++ b/studio/backend/tests/test_mcp_stdio_real_server.py@@ -28,7 +28,7 @@ FIXTURE = Path(__file__).parent / "fixtures" / "mcp_argument_echo_server.py"def _reset_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_ALLOW_STDIO_MCP", "1")- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())def _encode(arguments: list[str]) -> str:diff --git a/studio/backend/tests/test_mcp_stdio_sessions.py b/studio/backend/tests/test_mcp_stdio_sessions.pyindex 391568749c3..8a96a46206d 100644--- a/studio/backend/tests/test_mcp_stdio_sessions.py+++ b/studio/backend/tests/test_mcp_stdio_sessions.py@@ -763,7 +763,7 @@ def test_execute_tool_mcp_scope_is_per_thread(tmp_path, monkeypatch):from storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())monkeypatch.setattr(tools_mod, "stdio_mcp_enabled", lambda: True)mcp_servers_db.create_server(id = "s1", display_name = "S", url = STDIO_URL, is_enabled = True)@@ -796,7 +796,7 @@ def test_execute_tool_config_check_tracks_row(tmp_path, monkeypatch):from storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())monkeypatch.setattr(tools_mod, "stdio_mcp_enabled", lambda: True)mcp_servers_db.create_server(id = "s1", display_name = "S", url = STDIO_URL, is_enabled = True)diff --git a/studio/backend/tests/test_media_model_index_accounts.py b/studio/backend/tests/test_media_model_index_accounts.pynew file mode 100644index 00000000000..9b63d60fa98--- /dev/null+++ b/studio/backend/tests/test_media_model_index_accounts.py@@ -0,0 +1,84 @@+# 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 media resolver index is one account's answer, not whoever warmed it first: a cache keyed only by task hands the next account the previous one's picks for the whole TTL."""++from __future__ import annotations++import pytest++import core.inference.media_auto_switch as mas+import core.inference.media_model_index as index+import routes.models as models_route+from auth import policy+from storage import studio_db+from utils.account_context import OWNER, AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+++def home(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(models_route, "_local_model_task", lambda info: mas.IMAGE_TASK)+ mas.invalidate_index()+ yield tmp_path+ mas.invalidate_index()+++def _private_pipeline(account, home, name):+ root = home / "accounts" / account.account_id / "private_models"+ pipeline = root / name+ pipeline.mkdir(parents = True)+ (pipeline / "model_index.json").write_text("{}")++ def _register():+ connection = studio_db.get_connection()+ with connection:+ connection.execute(+ "INSERT INTO scan_folders (path, created_at) VALUES (?, datetime('now'))",+ (str(root),),+ )+ connection.close()++ run_as(account, _register)+ return pipeline+++def test_a_warm_index_does_not_answer_for_the_next_account(home):+ alice_model = _private_pipeline(ALICE, home, "alice-secret-flux")+ bob_model = _private_pipeline(BOB, home, "bob-own-flux")++ assert run_as(ALICE, mas.available_media_model_ids, mas.IMAGE_TASK) == ["alice-secret-flux"]+ assert run_as(BOB, mas.available_media_model_ids, mas.IMAGE_TASK) == ["bob-own-flux"]++ bob_pick = run_as(+ BOB, lambda: mas.resolve_local_media_model("bob-own-flux", task = mas.IMAGE_TASK)+ )+ assert bob_pick is not None and bob_pick.model_path == str(bob_model)+ assert (+ run_as(BOB, lambda: mas.resolve_local_media_model("alice-secret-flux", task = mas.IMAGE_TASK))+ is None+ )+ alice_pick = run_as(+ ALICE, lambda: mas.resolve_local_media_model("alice-secret-flux", task = mas.IMAGE_TASK)+ )+ assert alice_pick is not None and alice_pick.model_path == str(alice_model)+++def test_the_owner_still_gets_one_cached_scan(home, monkeypatch):+ _private_pipeline(OWNER, home, "owner-flux")+ scans = []+ real = models_route.collect_local_models+ monkeypatch.setattr(+ models_route,+ "collect_local_models",+ lambda root: (scans.append(root), real(root))[1],+ )++ assert mas.available_media_model_ids(mas.IMAGE_TASK) == ["owner-flux"]+ assert mas.available_media_model_ids(mas.IMAGE_TASK) == ["owner-flux"]+ assert len(scans) == 1+ assert list(index._index) == [(OWNER.account_id, mas.IMAGE_TASK)]diff --git a/studio/backend/tests/test_model_memory_settings.py b/studio/backend/tests/test_model_memory_settings.pyindex aaa915664d3..f193efd6c5c 100644--- a/studio/backend/tests/test_model_memory_settings.py+++ b/studio/backend/tests/test_model_memory_settings.py@@ -1852,8 +1852,8 @@ class TestPairedWritesAreInvalidatedTogether:mm._generation.clear()mm._invalidate(mm.KEEP_RESIDENT_SETTING_KEY, mm.NO_RAM_RESERVE_SETTING_KEY)- assert mm._generation[mm.KEEP_RESIDENT_SETTING_KEY] == 1- assert mm._generation[mm.NO_RAM_RESERVE_SETTING_KEY] == 1+ assert mm._generation[("owner", mm.KEEP_RESIDENT_SETTING_KEY)] == 1+ assert mm._generation[("owner", mm.NO_RAM_RESERVE_SETTING_KEY)] == 1def test_one_acquisition_covers_every_key(self):import astdiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 79d1b0adfd0..76a33f0ed08 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -4966,7 +4966,7 @@ def _enabled_mcp_server(from storage import mcp_servers_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())monkeypatch.setattr(tools_mod, "stdio_mcp_enabled", lambda: True)monkeypatch.setattr(mcp_client, "_tool_cache", {})monkeypatch.setattr(mcp_client, "_probe_cooloff_until", {})@@ -7855,7 +7855,6 @@ def test_scan_folder_removal_revokes_additions_only_cache_trust(monkeypatch):def test_scan_folder_storage_removals_report_if_a_row_changed(monkeypatch):from hub.storage import scan_folders-class _Connection:def __init__(self, rowcount):self.rowcount = rowcount@@ -7871,7 +7870,6 @@ def test_scan_folder_storage_removals_report_if_a_row_changed(monkeypatch):def close(self):self.closed = True- monkeypatch.setattr(scan_folders, "_ensure_schema", lambda _conn: None)for storage in (studio_db, scan_folders):for rowcount, expected in ((1, True), (0, False)):connection = _Connection(rowcount)@@ -8157,7 +8155,7 @@ def test_map_entry_fill_reads_and_writes_in_one_transaction(tmp_path, monkeypatc"""The real store, not the in-memory stand-in: the read has to share the write'stransaction, or a concurrent writer still slips between them."""monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(db, "_schema_ready", False)+ monkeypatch.setattr(db, "_schema_ready", set())key = "test_map_entry_create"assert db.upsert_app_setting_map_entry(key, "a", {"v": 1}) == {"a": {"v": 1}}@@ -8197,7 +8195,7 @@ def test_a_fill_never_relabels_a_stored_gpu_pin_with_this_browser_s_index_space(then name devices in a space it was never written in."""monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(db, "_schema_ready", False)+ monkeypatch.setattr(db, "_schema_ready", set())key = "test_map_entry_coupled"coupled = (("gpu_ids", "gpu_index_kind"),)diff --git a/studio/backend/tests/test_openai_models_servable_cache.py b/studio/backend/tests/test_openai_models_servable_cache.pyindex 629def7f91c..5e5aea511c5 100644--- a/studio/backend/tests/test_openai_models_servable_cache.py+++ b/studio/backend/tests/test_openai_models_servable_cache.py@@ -98,3 +98,27 @@ def test_unservable_entries_are_dropped(monkeypatch):)monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)assert inf._servable_catalog_rows(_catalog(3), 111.0) == []+++def test_a_managed_account_scans_the_shared_catalog_object(monkeypatch):+ """Filtering first handed a fresh list to the scan, so every managed poll rescanned."""+ import asyncio++ from hub.services.models import account_access++ catalog = _catalog(3)+ seen = []++ async def cached():+ return catalog++ monkeypatch.setattr(inf, "_cached_local_catalog", cached)+ monkeypatch.setattr(inf, "_account_catalog_cache", lambda: {"at": 1.0})+ monkeypatch.setattr(inf, "_openai_model_objects", lambda: [])+ monkeypatch.setattr(inf, "_peek_inference_backend", lambda: None)+ monkeypatch.setattr(account_access, "managed_account", lambda: True)+ monkeypatch.setattr(account_access, "filter_model_rows", lambda rows: list(rows[:1]))+ monkeypatch.setattr(account_access, "resident_hidden", lambda *a, **k: False)+ monkeypatch.setattr(inf, "_servable_catalog_rows", lambda rows, at: seen.append(rows) or [])+ asyncio.run(inf._openai_catalog_objects())+ assert seen[0] is catalogdiff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.pyindex 40aaf8569e2..be511315723 100644--- a/studio/backend/tests/test_orchestrator_unload_cancel.py+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py@@ -2911,6 +2911,7 @@ def test_the_impl_cancel_check_refuses_a_load_once_shutdown_has_latched():import astimport textwrapimport threading+ from types import SimpleNamespacefrom fastapi import HTTPException@@ -2925,6 +2926,7 @@ def test_the_impl_cancel_check_refuses_a_load_once_shutdown_has_latched():"_scoped_load_attempts_lock": threading.Lock(),"_loads_shutting_down": False,"load_cancel_event": None,+ "account_access": SimpleNamespace(require_live_account = lambda: None),}exec(textwrap.dedent(ast.get_source_segment(src, helper) or ""), ns)check = ns["_raise_if_scoped_load_cancelled"]diff --git a/studio/backend/tests/test_preview_account_binding.py b/studio/backend/tests/test_preview_account_binding.pynew file mode 100644index 00000000000..99b71951aac--- /dev/null+++ b/studio/backend/tests/test_preview_account_binding.py@@ -0,0 +1,148 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A public preview link opens the outputs of the account that minted it; the owner's tokens keep their shape so links handed out before this change still work."""++import json+import secrets+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.preview as preview+import utils.preview_token as preview_token+from auth import policy, storage+from utils.account_context import OWNER, AccountContext, run_as+from utils.paths import outputs_root++_SECRET = b"unit-test-preview-secret-0123456789"+++def studio(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "studio" / "auth" / "auth.db")+ (tmp_path / "studio" / "auth").mkdir(parents = True)+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ monkeypatch.setattr(preview_token, "get_or_create_preview_link_secret", lambda: _SECRET)+ monkeypatch.setattr(preview, "get_preview_sharing_enabled", lambda: True)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield tmp_path+ policy.invalidate_account_cache()+++def _managed(username: str) -> AccountContext:+ account = storage.issue_account_setup_code(username = username)["account"]+ return AccountContext(account["account_id"], account["username"], "user")+++def _make_run(account: AccountContext, name: str, marker: str) -> Path:+ run = Path(run_as(account, outputs_root)) / name+ run.mkdir(parents = True)+ (run / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": marker}))+ return run+++def _client() -> TestClient:+ app = FastAPI()+ app.include_router(preview.router, prefix = "/p")+ return TestClient(app)+++def test_owner_tokens_keep_their_shape_and_open_the_owner_root(studio):+ token = run_as(OWNER, preview_token.sign_preview_ref, "demorun")+ assert "." not in token+ assert preview_token.preview_token_account("demorun", token) == OWNER+ assert preview_token.verify_preview_ref("demorun", token)+ assert not preview_token.verify_preview_ref("otherrun", token)+++def test_managed_token_names_its_account_and_only_that_account(studio):+ alice = _managed("alice")+ bob = _managed("bob")+ token = run_as(alice, preview_token.sign_preview_ref, "demorun")+ account_id, _, signature = token.partition(".")+ assert account_id == alice.account_id and signature+ assert preview_token.preview_token_account("demorun", token) == alice+ assert run_as(bob, preview_token.sign_preview_ref, "demorun") != token+ assert run_as(OWNER, preview_token.sign_preview_ref, "demorun") != token+ forged = f"{bob.account_id}.{signature}"+ assert preview_token.preview_token_account("demorun", forged) is None+ owner_mac = run_as(OWNER, preview_token.sign_preview_ref, "demorun")+ assert preview_token.preview_token_account("demorun", f"{alice.account_id}.{owner_mac}") is None+ assert preview_token.preview_token_account("demorun", owner_mac) == OWNER+++def test_deactivated_or_deleted_account_links_stop_working(studio):+ alice = _managed("alice")+ token = run_as(alice, preview_token.sign_preview_ref, "demorun")+ storage.set_account_active(alice.account_id, False)+ assert preview_token.preview_token_account("demorun", token) is None+ storage.set_account_active(alice.account_id, True)+ assert preview_token.preview_token_account("demorun", token) == alice+ storage.delete_account(alice.account_id, lambda account: None)+ assert preview_token.preview_token_account("demorun", token) is None+++def test_public_request_is_served_in_the_minting_accounts_outputs(studio):+ alice = _managed("alice")+ owner_run = _make_run(OWNER, "victim-run", "OWNER_ADAPTER")+ alice_run = _make_run(alice, "victim-run", "ALICE_ADAPTER")+ assert owner_run != alice_run+ alice_token = run_as(alice, preview_token.sign_preview_ref, "victim-run")+ owner_token = run_as(OWNER, preview_token.sign_preview_ref, "victim-run")+ client = _client()++ owner_models = client.get("/p/victim-run/v1/models", params = {"k": owner_token})+ alice_models = client.get("/p/victim-run/v1/models", params = {"k": alice_token})+ assert owner_models.status_code == 200 and alice_models.status_code == 200+ assert client.get("/p/victim-run", params = {"k": alice_token}).status_code == 200++ (alice_run / "adapter_config.json").unlink()+ alice_run.rmdir()+ assert owner_run.is_dir()+ assert client.get("/p/victim-run/v1/models", params = {"k": alice_token}).status_code == 404+ assert client.get("/p/victim-run", params = {"k": alice_token}).status_code == 404+ assert client.get("/p/victim-run/v1/models", params = {"k": owner_token}).status_code == 200++ alice_run.mkdir()+ (alice_run / "adapter_config.json").write_text("{}")+ owner_run.joinpath("adapter_config.json").unlink()+ owner_run.rmdir()+ assert client.get("/p/victim-run/v1/models", params = {"k": owner_token}).status_code == 404+ assert client.get("/p/victim-run/v1/models", params = {"k": alice_token}).status_code == 200+++def test_chat_route_binds_the_minting_account_for_the_whole_request(studio, monkeypatch):+ alice = _managed("alice")+ _make_run(alice, "demorun", "ALICE_ADAPTER")+ token = run_as(alice, preview_token.sign_preview_ref, "demorun")+ seen = {}++ async def fake_load(load_request, request, subject):+ from utils.account_context import current_account+ seen["load_account"] = current_account().account_id+ seen["path"] = load_request.model_path++ async def fake_chat(payload, request, subject):+ from utils.account_context import current_account+ seen["chat_account"] = current_account().account_id+ return {"choices": [{"message": {"role": "assistant", "content": "hi"}}]}++ monkeypatch.setattr(preview, "load_model_for_preview", fake_load)+ monkeypatch.setattr(preview, "openai_chat_completions", fake_chat)+ monkeypatch.setattr(preview, "check_rate_limit", lambda ip: None)+ client = _client()+ response = client.post(+ "/p/demorun/v1/chat/completions",+ params = {"k": token},+ json = {"model": "demorun", "messages": [{"role": "user", "content": "hi"}]},+ )+ assert response.status_code == 200, response.text+ assert seen["load_account"] == alice.account_id+ assert seen["chat_account"] == alice.account_id+ assert str(Path(run_as(alice, outputs_root)) / "demorun") in seen["path"]diff --git a/studio/backend/tests/test_profile_stats.py b/studio/backend/tests/test_profile_stats.pyindex b4aac9cff2a..3b862f3a130 100644--- a/studio/backend/tests/test_profile_stats.py+++ b/studio/backend/tests/test_profile_stats.py@@ -44,7 +44,7 @@ def _shared_setup_1(conn):def stats_db(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())invalidate_profile_stats_cache()yieldinvalidate_profile_stats_cache()@@ -249,7 +249,7 @@ def test_api_only_usage_is_durable_idempotent_and_invalidates_cache(stats_db):assert after_insert["streak"]["current"] == 1# A fresh process/schema initialization still reads the same receipt.- studio_db._schema_ready = False+ studio_db._schema_ready = set()invalidate_profile_stats_cache()after_restart = compute_profile_stats(days = 7, tz_name = "UTC", subject = "external-client")assert after_restart["totals"]["apiTokens"] == 50@@ -633,7 +633,7 @@ def test_existing_database_gets_additive_api_usage_schema(stats_db):finally:legacy.close()- studio_db._schema_ready = False+ studio_db._schema_ready = set()conn = studio_db.get_connection()try:assert conn.execute("SELECT value FROM legacy_marker").fetchone()[0] == "kept"diff --git a/studio/backend/tests/test_provider_max_output_tokens_contract.py b/studio/backend/tests/test_provider_max_output_tokens_contract.pyindex fe43bb9190a..38fa8421831 100644--- a/studio/backend/tests/test_provider_max_output_tokens_contract.py+++ b/studio/backend/tests/test_provider_max_output_tokens_contract.py@@ -92,9 +92,9 @@ def isolated_providers_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Padb_path = tmp_path / "studio.db"monkeypatch.setattr(providers_db, "studio_db_path", lambda: db_path)monkeypatch.setattr(providers_db, "ensure_dir", lambda _path: None)- providers_db._schema_ready = False+ providers_db._schema_ready = set()yield db_path- providers_db._schema_ready = False+ providers_db._schema_ready = set()@pytest.fixture()@@ -112,11 +112,11 @@ def provider_routes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:"get_or_create_credential_encryption_key",auth_storage.get_or_create_credential_encryption_key,)- providers_db._schema_ready = False- credential_secrets._schema_ready = False+ providers_db._schema_ready = set()+ credential_secrets._schema_ready = set()yield studio_db- providers_db._schema_ready = False- credential_secrets._schema_ready = False+ providers_db._schema_ready = set()+ credential_secrets._schema_ready = set()auth_storage._credential_encryption_key_cache = None@@ -194,7 +194,7 @@ def test_the_migration_is_idempotent(isolated_providers_db: Path):"""ALTER TABLE has no IF NOT EXISTS, so a second run must not raise."""_write_pre_pr_database(isolated_providers_db)for _ in range(3):- providers_db._schema_ready = False+ providers_db._schema_ready = set()assert providers_db.get_provider("old-custom")["max_output_tokens"] is Noneassert _columns(isolated_providers_db).count("max_output_tokens") == 1diff --git a/studio/backend/tests/test_providers_db_models.py b/studio/backend/tests/test_providers_db_models.pyindex 2d99591c3ef..a5bae89ac35 100644--- a/studio/backend/tests/test_providers_db_models.py+++ b/studio/backend/tests/test_providers_db_models.py@@ -18,9 +18,9 @@ def isolated_providers_db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):db_path = tmp_path / "studio.db"monkeypatch.setattr(providers_db, "studio_db_path", lambda: db_path)monkeypatch.setattr(providers_db, "ensure_dir", lambda _path: None)- providers_db._schema_ready = False+ providers_db._schema_ready = set()yield db_path- providers_db._schema_ready = False+ providers_db._schema_ready = set()def test_create_and_list_provider_models(isolated_providers_db: Path):diff --git a/studio/backend/tests/test_rag_folder_sync_retirement.py b/studio/backend/tests/test_rag_folder_sync_retirement.pynew file mode 100644index 00000000000..42ab85f5c92--- /dev/null+++ b/studio/backend/tests/test_rag_folder_sync_retirement.py@@ -0,0 +1,164 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Deleting an account must not kill the one linked-folder worker that serves every account."""++from __future__ import annotations++import importlib+import threading+import time+import weakref++import pytest++from auth import policy+from core.rag import folder_sync+from core.training import account_jobs as jobs+from storage import rag_db+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++requires_sqlite_vec = pytest.mark.skipif(+ not rag_db.RAG_AVAILABLE, reason = "sqlite-vec is not installed"+)+++def two_accounts(tmp_path, monkeypatch, stub_embeddings):+ from utils.paths import storage_roots as roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "docs"))+ monkeypatch.setattr(rag_db, "_schema_ready", set())+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ monkeypatch.setattr(jobs, "_retired", set())+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.ingestion", "retire_account_ingestions"),+ ("routes.inference", "retire_stt_downloads"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)+ monkeypatch.setattr(+ folder_sync,+ "job_accounts",+ lambda: [a for a in (ALICE, BOB) if a.account_id not in jobs._retired],+ )+ homes = {}+ for account in (ALICE, BOB):+ workspace = run_as(account, roots.workspace_root)+ workspace.mkdir(parents = True, exist_ok = True)+ homes[account.account_id] = workspace+ return homes+++def _link(account, workspace, name: str):+ source = workspace / f"linked-{name}"+ source.mkdir(parents = True, exist_ok = True)+ (source / "notes.txt").write_text(f"{name} text", encoding = "utf-8")++ def create():+ folder = folder_sync.create_folder(+ scope_type = "knowledge_base", scope_id = f"kb-{name}", path = str(source), name = name+ )+ return folder, folder_sync.request_sync(folder["id"])++ return run_as(account, create)+++@requires_sqlite_vec+def test_retiring_an_account_mid_sync_keeps_the_shared_folder_worker_alive(+ two_accounts, monkeypatch+):+ from routes.accounts import retire_account_roots++ blocked, release = threading.Event(), threading.Event()+ real_snapshot = folder_sync._snapshot++ def slow_snapshot(root, metadata):+ blocked.set()+ assert release.wait(60)+ return real_snapshot(root, metadata)++ monkeypatch.setattr(folder_sync, "_snapshot", slow_snapshot)+ _link(ALICE, two_accounts[ALICE.account_id], "alice")++ stop = threading.Event()+ worker = threading.Thread(target = folder_sync._worker, args = (stop,), daemon = True)+ worker.start()+ try:+ assert blocked.wait(30), "the worker never reached the snapshot"+ retire_account_roots(ALICE)+ release.set()++ _, bob_job = _link(BOB, two_accounts[BOB.account_id], "bob")+ folder_sync._wake.set()+ deadline = time.time() + 30+ status = None+ while time.time() < deadline:+ status = run_as(BOB, folder_sync.get_job, bob_job)["status"]+ if status in ("completed", "failed"):+ break+ time.sleep(0.2)+ assert worker.is_alive(), "retiring one account killed the shared linked-folder worker"+ assert not two_accounts[+ ALICE.account_id+ ].exists(), "a late linked-folder snapshot recreated the deleted workspace"+ assert status == "completed", f"the surviving account never synced: {status}"+ finally:+ stop.set()+ release.set()+ folder_sync._wake.set()+ worker.join(30)+++def _corrupt_rag_db(account) -> None:+ """Replace the account's rag.db with bytes SQLite refuses to open."""+ from utils.paths import storage_roots as roots++ path = run_as(account, roots.rag_db_path)+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(b"not a sqlite database" * 64)+++@requires_sqlite_vec+def test_a_corrupt_account_database_does_not_hide_the_next_accounts_jobs(two_accounts):+ _link(BOB, two_accounts[BOB.account_id], "bob")+ _corrupt_rag_db(ALICE)++ selected = folder_sync._next_account_job()++ assert selected is not None, "a corrupt account database hid every job behind it"+ assert selected[0].account_id == BOB.account_id+++@requires_sqlite_vec+def test_the_shared_worker_still_syncs_accounts_behind_a_corrupt_database(two_accounts):+ _, bob_job = _link(BOB, two_accounts[BOB.account_id], "bob")+ _corrupt_rag_db(ALICE)++ stop = threading.Event()+ worker = threading.Thread(target = folder_sync._worker, args = (stop,), daemon = True)+ worker.start()+ try:+ deadline = time.time() + 60+ status = None+ while time.time() < deadline:+ status = run_as(BOB, folder_sync.get_job, bob_job)["status"]+ if status in ("completed", "failed"):+ break+ folder_sync._wake.set()+ time.sleep(0.2)+ assert worker.is_alive(), "a corrupt account database killed the shared worker"+ assert status == "completed", f"the healthy account never synced: {status}"+ finally:+ stop.set()+ folder_sync._wake.set()+ worker.join(30)diff --git a/studio/backend/tests/test_rag_ingestion_retirement.py b/studio/backend/tests/test_rag_ingestion_retirement.pynew file mode 100644index 00000000000..2e28485d005--- /dev/null+++ b/studio/backend/tests/test_rag_ingestion_retirement.py@@ -0,0 +1,97 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Deleting an account must reap its RAG ingestion workers, not just drop their leases.++A worker parked in a long parse notices retirement only at its next progress checkpoint, so+without a join the delete renames the roots, returns 204, and the thread then lands its+cleanup writes in the renamed-aside database."""++from __future__ import annotations++import importlib+import sqlite3+import threading+import weakref++import pytest++from auth import policy+from core.rag import ingestion, parsers, store+from core.training import account_jobs as jobs+from utils.account_context import AccountContext, run_as++ALICE = AccountContext("a" * 32, "alice")+++def alice_home(tmp_path, monkeypatch, stub_embeddings):+ from storage import rag_db+ from utils.paths import storage_roots as roots++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setenv("UNSLOTH_STUDIO_DOCUMENTS_HOME", str(tmp_path / "docs"))+ monkeypatch.setattr(rag_db, "_schema_ready", set())+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True)+ monkeypatch.setattr(jobs, "_services", weakref.WeakSet())+ monkeypatch.setattr(jobs, "_retired", set())+ for module, name in (+ ("hub.services.datasets.downloads", "retire_account_downloads"),+ ("hub.services.models.downloads", "retire_account_downloads"),+ ("core.rag.folder_sync", "retire_account_sync"),+ ):+ monkeypatch.setattr(importlib.import_module(module), name, lambda: None)+ monkeypatch.setattr("core.research_runs.retire_account_research", lambda account: None)+ workspace = run_as(ALICE, roots.workspace_root)+ workspace.mkdir(parents = True, exist_ok = True)+ return workspace+++def test_deleting_an_account_reaps_its_blocked_ingestion_worker(alice_home, monkeypatch):+ from routes.accounts import retire_account_roots++ monkeypatch.setattr(ingestion, "_RETIRE_JOIN_SECONDS", 1.0, raising = False)+ path = alice_home / "doc.txt"+ path.write_text("alpha bravo charlie " * 200, encoding = "utf-8")++ blocked, release = threading.Event(), threading.Event()+ real_parse = parsers.parse++ def slow_parse(stored_path, *args, **kwargs):+ blocked.set()+ assert release.wait(60)+ return real_parse(stored_path, *args, **kwargs)++ monkeypatch.setattr(parsers, "parse", slow_parse)++ scope = store.kb_scope("K1")+ _doc_id, job_id = run_as(+ ALICE, ingestion.start_ingestion, scope, "K1", None, "doc.txt", str(path)+ )+ worker = ingestion._workers[(ALICE.account_id, job_id)]+ assert blocked.wait(30), "the worker never reached parse"++ try:+ with pytest.raises(jobs.AccountRetirementError):+ retire_account_roots(ALICE)+ assert alice_home.exists(), "the roots moved out from under a live ingestion worker"+ assert not [p for p in alice_home.parent.iterdir() if "-deleted-" in p.name]+ finally:+ release.set()+ worker.join(60)+ assert not worker.is_alive()++ # With the worker gone, retirement completes and the roots move with nothing left writing.+ retire_account_roots(ALICE)+ tombstones = [p for p in alice_home.parent.iterdir() if "-deleted-" in p.name]+ assert tombstones and not alice_home.exists()+ db = tombstones[0] / "rag" / "rag.db"+ before = db.stat().st_mtime_ns+ conn = sqlite3.connect(str(db))+ try:+ assert conn.execute("SELECT 1 FROM ingestion_jobs WHERE id=?", (job_id,)).fetchone()+ finally:+ conn.close()+ assert db.stat().st_mtime_ns == beforediff --git a/studio/backend/tests/test_rag_nudge_roster_compat.py b/studio/backend/tests/test_rag_nudge_roster_compat.pyindex a4bda4e4f9b..71329f38956 100644--- a/studio/backend/tests/test_rag_nudge_roster_compat.py+++ b/studio/backend/tests/test_rag_nudge_roster_compat.py@@ -49,7 +49,7 @@ def fresh_process(monkeypatch):from storage import rag_dbmonkeypatch.setattr(rag_db, "_extension_loaded", False)- monkeypatch.setattr(rag_db, "_schema_ready", False)+ monkeypatch.setattr(rag_db, "_schema_ready", set())def _doc(@@ -206,7 +206,9 @@ def test_roster_degrades_rather_than_raising_when_the_gate_lies(rag_home, monkeyfrom routes import inferencemonkeypatch.setattr(rag_db, "_extension_loaded", True)- monkeypatch.setattr(rag_db, "_schema_ready", True) # so nothing migrates it+ monkeypatch.setattr(+ rag_db, "_schema_ready", {rag_db.rag_db_path().resolve()}+ ) # so nothing migrates itout = _nudge({"project_id": "p1"})assert inference._RAG_GROUNDING_NUDGE in outassert _roster(out) == "" or "legacy.pdf" in _roster(out)diff --git a/studio/backend/tests/test_rag_preview.py b/studio/backend/tests/test_rag_preview.pyindex 89710f3ecec..348907486f8 100644--- a/studio/backend/tests/test_rag_preview.py+++ b/studio/backend/tests/test_rag_preview.py@@ -191,8 +191,10 @@ def test_locator_anchors_through_markdown_table_pipes():def test_sign_verify_roundtrip(rag_home):from routes import rag as rag_routes+ from utils.account_context import OWNERtok = rag_routes._sign_document("doc-123")- assert rag_routes._verify_document_token(tok) == "doc-123"- assert rag_routes._verify_document_token("doc-123.0.deadbeef") is None # expired/bad- assert rag_routes._verify_document_token("garbage") is None+ assert rag_routes._verify_document_token("doc-123", tok) == OWNER+ assert rag_routes._verify_document_token("doc-456", tok) is None+ assert rag_routes._verify_document_token("doc-123", "0..deadbeef") is None+ assert rag_routes._verify_document_token("doc-123", "garbage") is Nonediff --git a/studio/backend/tests/test_research_no_evidence.py b/studio/backend/tests/test_research_no_evidence.pyindex f7163fec6ed..c7b3069ce2f 100644--- a/studio/backend/tests/test_research_no_evidence.py+++ b/studio/backend/tests/test_research_no_evidence.py@@ -25,7 +25,7 @@ FOUND = (@pytest.fixturedef research_home(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "thread-1",diff --git a/studio/backend/tests/test_research_progress_events.py b/studio/backend/tests/test_research_progress_events.pyindex 3fdd2c3bb2b..434f65a7421 100644--- a/studio/backend/tests/test_research_progress_events.py+++ b/studio/backend/tests/test_research_progress_events.py@@ -21,7 +21,7 @@ from storage import studio_db@pytest.fixturedef research_home(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "thread-1", "title": "R", "modelType": "base", "modelId": "m", "createdAt": 1})diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.pyindex ee022a6453d..13087e948b7 100644--- a/studio/backend/tests/test_research_runs_storage.py+++ b/studio/backend/tests/test_research_runs_storage.py@@ -69,7 +69,7 @@ def _shared_setup_6():@pytest.fixturedef research_home(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "thread-1",@@ -549,7 +549,7 @@ def test_schema_and_state_transitions(research_home):def test_owner_scoped_claim_schema_migrates_to_global(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "shared-thread",@@ -594,7 +594,7 @@ def test_owner_scoped_claim_schema_migrates_to_global(tmp_path, monkeypatch):finally:conn.close()- studio_db._schema_ready = False+ studio_db._schema_ready = set()conn = studio_db.get_connection()try:primary_key = [@@ -619,7 +619,7 @@ def test_owner_scoped_claim_schema_migrates_to_global(tmp_path, monkeypatch):def test_owner_scoped_claim_migration_rolls_back_on_interruption(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "shared-thread",@@ -661,14 +661,14 @@ def test_owner_scoped_claim_migration_rolls_back_on_interruption(tmp_path, monkereturn real_connect(path, *args, **kwargs)monkeypatch.setattr(studio_db.sqlite3, "connect", _failing_connect)- studio_db._schema_ready = False+ studio_db._schema_ready = set()with pytest.raises(RuntimeError, match = "simulated crash"):studio_db.get_connection()# Recover: the interrupted migration left nothing half-applied, so a clean boot# completes the migration and preserves the original claim exactly once.monkeypatch.setattr(studio_db.sqlite3, "connect", real_connect)- studio_db._schema_ready = False+ studio_db._schema_ready = set()conn = studio_db.get_connection()try:primary_key = [diff --git a/studio/backend/tests/test_research_synthesis_recovery.py b/studio/backend/tests/test_research_synthesis_recovery.pyindex 57a06cc9b20..26729a721f5 100644--- a/studio/backend/tests/test_research_synthesis_recovery.py+++ b/studio/backend/tests/test_research_synthesis_recovery.py@@ -27,7 +27,7 @@ SEARCH_RESULT = (@pytest.fixturedef research_home(tmp_path, monkeypatch):monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.upsert_chat_thread({"id": "thread-1",diff --git a/studio/backend/tests/test_research_workflow_key_account.py b/studio/backend/tests/test_research_workflow_key_account.pynew file mode 100644index 00000000000..04e0c4f76ce--- /dev/null+++ b/studio/backend/tests/test_research_workflow_key_account.py@@ -0,0 +1,85 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A research run's workflow key must be pinned to the account that claimed it, not to its username."""++from __future__ import annotations++import asyncio+import secrets+import sqlite3+from types import SimpleNamespace++import pytest++from auth import policy+from auth import storage as auth_storage+from core.research_runs import ResearchSupervisor+from utils.account_context import AccountContext, arun_as+++def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ monkeypatch.setattr(auth_storage, "_api_key_pbkdf2_salt_cache", None)+ auth_storage._reset_api_key_hash_cache()+ policy.invalidate_account_cache()+ auth_storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield auth_storage+ auth_storage._reset_api_key_hash_cache()+ policy.invalidate_account_cache()+++def _alice() -> str:+ return auth_storage.issue_account_setup_code(username = "alice")["account"]["account_id"]+++def _workflow_key_rows():+ conn = sqlite3.connect(auth_storage.DB_PATH)+ conn.row_factory = sqlite3.Row+ try:+ return [+ dict(row)+ for row in conn.execute(+ "SELECT username, account_id FROM api_keys WHERE name = ?",+ (auth_storage.DEEP_RESEARCH_WORKFLOW_KEY_NAME,),+ ).fetchall()+ ]+ finally:+ conn.close()+++def test_workflow_key_is_pinned_to_the_claimed_account(auth_db, monkeypatch):+ old_id = _alice()+ old_account = AccountContext(old_id, "alice")+ auth_storage.delete_account(old_id, lambda account: None)+ new_id = _alice()+ assert new_id != old_id++ supervisor = ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))++ async def stop_after_mint(*args, **kwargs):+ raise RuntimeError("stop after the key is minted")++ monkeypatch.setattr(supervisor, "_note_phase", stop_after_mint)+ run = {+ "id": "run-1",+ "ownerSubject": "alice",+ "config": {"model": "local", "budgets": {"modelTimeoutSeconds": 5}},+ }++ async def drive():+ with pytest.raises(RuntimeError):+ await arun_as(old_account, supervisor._stream_completion(run, [], phase = "plan"))++ asyncio.run(drive())++ rows = _workflow_key_rows()+ assert rows, "the workflow key was never minted"+ assert [row["account_id"] for row in rows] == [+ old_id+ ], f"workflow key bound to {rows} instead of the claiming account {old_id}"diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.pyindex 9bff1cd1519..322b7b9692b 100644--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py@@ -4060,7 +4060,7 @@ def test_the_supervisor_is_told_even_with_no_row_left():from routes import chat_historysource = inspect.getsource(chat_history._cancel_research_runs)- assert source.index("supervisor.cancel(run_id)") < source.index(+ assert source.index("cancel_account_run(request, run_id,") < source.index("research_runs_db.request_cancel(run_id)")diff --git a/studio/backend/tests/test_studio_db_write_lock_contention.py b/studio/backend/tests/test_studio_db_write_lock_contention.pyindex fc9430a5ca4..a39bca92991 100644--- a/studio/backend/tests/test_studio_db_write_lock_contention.py+++ b/studio/backend/tests/test_studio_db_write_lock_contention.py@@ -40,7 +40,7 @@ FULL, NORMAL = 2, 1def db(tmp_path, monkeypatch):"""A studio.db in a temp dir, with the per-process schema latch reset."""monkeypatch.setattr(studio_db, "studio_db_path", lambda: tmp_path / "studio.db")- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())conn = studio_db.get_connection()conn.close()yield tmp_path / "studio.db"@@ -123,7 +123,7 @@ def test_non_wal_journal_keeps_full(db, monkeypatch, mode):setup.close()assert _journal_mode(db) != "wal"- monkeypatch.setattr(studio_db, "_schema_ready", True)+ monkeypatch.setattr(studio_db, "_schema_ready", {db.resolve()})conn = studio_db.get_connection()try:assert _synchronous(conn) == FULL, f"{mode} must not lose its commit fsync"@@ -250,7 +250,7 @@ def test_upgrade_replaces_the_unscoped_trigger(tmp_path, monkeypatch):"""path = tmp_path / "studio.db"monkeypatch.setattr(studio_db, "studio_db_path", lambda: path)- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())conn = studio_db.get_connection()try:@@ -277,7 +277,7 @@ def test_upgrade_replaces_the_unscoped_trigger(tmp_path, monkeypatch):finally:conn.close()- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())conn = studio_db.get_connection()try:assert (@@ -782,24 +782,23 @@ def test_wal_keeper_keeps_short_lived_writers_out_of_the_main_database(db):assert _digest(db) != unkept-def test_a_second_open_replaces_the_keeper_instead_of_inheriting_it(db, tmp_path, monkeypatch):- """Inheriting a keeper left by an earlier lifespan holds a database this process has- stopped using, reporting success while keeping nothing for the current one."""+def test_a_second_database_gets_its_own_keeper(db, tmp_path, monkeypatch):assert studio_db.open_wal_keeper() is True- stale = studio_db._wal_keeper+ stale = studio_db._wal_keepers[studio_db.studio_db_path().resolve()]second = tmp_path / "second" / "studio.db"second.parent.mkdir()monkeypatch.setattr(studio_db, "studio_db_path", lambda: second)- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())assert studio_db.open_wal_keeper() is True- assert studio_db._wal_keeper is not stale+ assert studio_db._wal_keepers[studio_db.studio_db_path().resolve()] is not stale+ assert stale.execute("SELECT 1").fetchone()[0] == 1_short_lived_write(second, "kept")assert Path(f"{second}-wal").is_file()studio_db.close_wal_keeper()- assert studio_db._wal_keeper is None+ assert not studio_db._wal_keepersassert not Path(f"{second}-wal").exists()studio_db.close_wal_keeper()@@ -807,7 +806,7 @@ def test_a_second_open_replaces_the_keeper_instead_of_inheriting_it(db, tmp_pathdef test_the_replaced_keeper_is_not_left_open(db):"""Replacing must release the old connection, not merely drop the reference."""assert studio_db.open_wal_keeper() is True- stale = studio_db._wal_keeper+ stale = studio_db._wal_keepers[studio_db.studio_db_path().resolve()]assert studio_db.open_wal_keeper() is Truewith pytest.raises(sqlite3.ProgrammingError, match = "closed database"):@@ -820,11 +819,11 @@ def test_a_keeper_left_by_a_dead_thread_is_replaced(db):opened = threading.Thread(target = studio_db.open_wal_keeper)opened.start()opened.join()- stale = studio_db._wal_keeper+ stale = studio_db._wal_keepers[studio_db.studio_db_path().resolve()]assert stale is not Noneassert studio_db.open_wal_keeper() is True- assert studio_db._wal_keeper is not stale+ assert studio_db._wal_keepers[studio_db.studio_db_path().resolve()] is not stale_short_lived_write(db, "kept")assert Path(f"{db}-wal").is_file()@@ -841,7 +840,7 @@ def test_wal_keeper_declines_when_the_filesystem_refused_wal(db, caplog):with caplog.at_level(logging.INFO, logger = studio_db.logger.name):assert studio_db.open_wal_keeper() is False- assert studio_db._wal_keeper is None+ assert not studio_db._wal_keepersassert "not WAL" in caplog.text@@ -855,7 +854,7 @@ def test_the_lifespan_holds_the_keeper_across_every_writer():source = inspect.getsource(main.lifespan)served = source.index("yield")- assert source.index("open_wal_keeper()") < source.index("cleanup_orphaned_runs()") < served+ assert source.index("open_wal_keeper()") < source.index("cleanup_orphaned_runs)") < servedassert (served < source.index("await run_lifespan_shutdown(") < source.index("close_wal_keeper()"))diff --git a/studio/backend/tests/test_tool_sandbox_per_thread.py b/studio/backend/tests/test_tool_sandbox_per_thread.pyindex 1fa7f7bfb18..41e7da998b6 100644--- a/studio/backend/tests/test_tool_sandbox_per_thread.py+++ b/studio/backend/tests/test_tool_sandbox_per_thread.py@@ -65,11 +65,13 @@ def test_a_directory_is_private_to_its_conversation(workdir):assert os.listdir(b) == [tools._SANDBOX_MARKER]-def test_project_chats_deliberately_share_one_workspace(workdir, monkeypatch):+def test_project_chats_deliberately_share_one_workspace(workdir, monkeypatch, tmp_path):# Chats in a project are meant to see each other's files.from core.inference import tools- monkeypatch.setattr(tools, "_get_project_workdir", lambda sid: "/tmp/project-ws")- assert tools._get_workdir("project-abc") == "/tmp/project-ws"++ project_workspace = str(tmp_path / "project-ws")+ monkeypatch.setattr(tools, "_get_project_workdir", lambda sid: project_workspace)+ assert tools._get_workdir("project-abc") == project_workspace@pytest.mark.parametrize(diff --git a/studio/backend/tests/test_training_history_delete.py b/studio/backend/tests/test_training_history_delete.pyindex bc36ac0c60c..8f3e09352de 100644--- a/studio/backend/tests/test_training_history_delete.py+++ b/studio/backend/tests/test_training_history_delete.py@@ -582,7 +582,7 @@ def test_list_other_run_output_dirs_ignores_unstamped_running_rows(monkeypatch,from storage import studio_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())shared = "/tmp/outputs/shared-run"studio_db.create_run(diff --git a/studio/backend/tests/test_training_provenance.py b/studio/backend/tests/test_training_provenance.pyindex 0993e8dd67d..82a27438630 100644--- a/studio/backend/tests/test_training_provenance.py+++ b/studio/backend/tests/test_training_provenance.py@@ -1323,7 +1323,7 @@ def test_db_config_update_only_mutates_running_run(monkeypatch, tmp_path):from storage import studio_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio-home"))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.create_run(id = "run-db",model_name = "org/model",diff --git a/studio/backend/tests/test_training_resume.py b/studio/backend/tests/test_training_resume.pyindex 37e60167ea5..e6a308bf02e 100644--- a/studio/backend/tests/test_training_resume.py+++ b/studio/backend/tests/test_training_resume.py@@ -15,7 +15,7 @@ def _shared_setup_1(monkeypatch, tmp_path):from storage import studio_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())studio_db.create_run(id = "r",@@ -33,7 +33,7 @@ def _shared_setup_2(monkeypatch, tmp_path):from storage import studio_dbmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))- monkeypatch.setattr(studio_db, "_schema_ready", False)+ monkeypatch.setattr(studio_db, "_schema_ready", set())return studio_dbdiff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 3ec400c59da..ea0b80f4eef 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -6897,8 +6897,16 @@ def test_h3_begin_generate_reuses_preflight_resolved_references(monkeypatch):return expectedclass _DeferredThread:- def __init__(self, *, target, kwargs, daemon):- captured.update(target = target, kwargs = kwargs, daemon = daemon)+ def __init__(+ self,+ *,+ target,+ args = (),+ kwargs,+ daemon,+ ):+ # The worker is pinned to its account: the thread target is run_as, the real target rides last in args.+ captured.update(target = args[-1] if args else target, kwargs = kwargs, daemon = daemon)def start(self):return None@@ -6938,8 +6946,15 @@ def test_a_v1_videos_job_id_stays_out_of_the_replayable_worker_kwargs(monkeypatccaptured = {}class _DeferredThread:- def __init__(self, *, target, kwargs, daemon):- captured.update(target = target, kwargs = kwargs, daemon = daemon)+ def __init__(+ self,+ *,+ target,+ args = (),+ kwargs,+ daemon,+ ):+ captured.update(target = args[-1] if args else target, kwargs = kwargs, daemon = daemon)def start(self):return Nonediff --git a/studio/backend/tests/test_web_rank.py b/studio/backend/tests/test_web_rank.pyindex 07a1b6566e4..cdb09ab5182 100644--- a/studio/backend/tests/test_web_rank.py+++ b/studio/backend/tests/test_web_rank.py@@ -21,7 +21,7 @@ def rag_home(tmp_path, monkeypatch):db_file = tmp_path / "rag.db"monkeypatch.setattr(rag_db, "rag_db_path", lambda: db_file)- monkeypatch.setattr(rag_db, "_schema_ready", False, raising = False)+ monkeypatch.setattr(rag_db, "_schema_ready", set(), raising = False)return db_filediff --git a/studio/backend/utils/account_context.py b/studio/backend/utils/account_context.pynew file mode 100644index 00000000000..4f1c946a99d--- /dev/null+++ b/studio/backend/utils/account_context.py@@ -0,0 +1,98 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which account a request, job or thread acts for: one ContextVar carried by asyncio tasks but NOT by new threads (they rebind via ``run_as``), keyed by immutable ``account_id``."""++from __future__ import annotations++import threading+from contextvars import ContextVar, Token+from dataclasses import dataclass+from typing import Any, Awaitable, Callable, TypeVar++OWNER_ACCOUNT_ID = "owner"+OWNER_USERNAME = "unsloth"+ROLE_OWNER = "owner"+ROLE_USER = "user"++T = TypeVar("T")+++@dataclass(frozen = True, slots = True)+class AccountContext:+ """The acting account. ``account_id`` is the storage key; ``username`` is not."""++ account_id: str+ username: str+ role: str = ROLE_USER++ @property+ def is_owner(self) -> bool:+ return self.role == ROLE_OWNER+++OWNER = AccountContext(OWNER_ACCOUNT_ID, OWNER_USERNAME, ROLE_OWNER)++_current: ContextVar[AccountContext] = ContextVar("unsloth_account", default = OWNER)+++def current_account() -> AccountContext:+ return _current.get()+++def current_account_id() -> str:+ return _current.get().account_id+++def is_owner_context() -> bool:+ return _current.get().is_owner+++def bind_account(account: AccountContext) -> Token[AccountContext]:+ if not isinstance(account, AccountContext) or not account.account_id:+ raise ValueError("bind_account needs an AccountContext with an account_id")+ return _current.set(account)+++def reset_account(token: Token[AccountContext]) -> None:+ _current.reset(token)+++def run_as(account: AccountContext, target: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:+ """Call ``target`` bound to ``account``; synchronous only, a returned coroutine would run after the reset (use ``arun_as``)."""+ token = bind_account(account)+ try:+ result = target(*args, **kwargs)+ finally:+ reset_account(token)+ if hasattr(result, "__await__"):+ raise TypeError(+ "run_as was given an awaitable; use arun_as so the binding outlives the await"+ )+ return result+++async def arun_as(account: AccountContext, awaitable: Awaitable[T]) -> T:+ token = bind_account(account)+ try:+ return await awaitable+ finally:+ reset_account(token)+++def account_thread(+ *,+ target: Callable[..., Any],+ account: AccountContext | None = None,+ args: tuple[Any, ...] = (),+ kwargs: dict[str, Any] | None = None,+ **thread_kwargs: Any,+) -> threading.Thread:+ """A thread pinned to one account, captured at creation rather than at start."""+ bound = account or current_account()+ return threading.Thread(+ target = run_as,+ args = (bound, target, *args),+ kwargs = kwargs or {},+ **thread_kwargs,+ )diff --git a/studio/backend/utils/embedding_model_settings.py b/studio/backend/utils/embedding_model_settings.pyindex de4a63a5270..97c90bf1b31 100644--- a/studio/backend/utils/embedding_model_settings.py+++ b/studio/backend/utils/embedding_model_settings.py@@ -9,6 +9,8 @@ import threadingimport timefrom typing import Any, Optional+from utils.account_context import current_account_id+EMBEDDING_MODEL_SETTING_KEY = "rag_embedding_model"# The GGUF repo the picker resolved for that model, stored so the loader opens what was actually downloaded instead of re-deriving a name that may not exist.EMBEDDING_GGUF_SETTING_KEY = "rag_embedding_gguf_repo"@@ -24,20 +26,39 @@ _CACHE_TTL_S = 2.0_StoredState = tuple[Optional[str], Optional[str], Optional[str], Optional[str], bool, Optional[dict]]-# (override model, resolved model, GGUF repo, backend, download pending, raw record). The raw record is carried so a conditional write compares against exactly what is stored: a reconstruction never matches a record written by a build with one field fewer.-_cached: tuple[float, _StoredState] | None = None-# Bumped on every write/invalidate. A reader captures it before the DB read and only fills the cache if it is unchanged afterward, so a read that overlapped a save cannot repopulate the cache with the pre-save value for the whole TTL.-_generation = 0+# (override model, resolved model, GGUF repo, backend, download pending, raw record).+# The raw record is carried so a conditional write compares against exactly what is stored: a reconstruction never+# matches a record written by a build with one field fewer.+_cached: dict[tuple[str, str], tuple[float, _StoredState]] = {}+_CACHE_MAX = 256+# Bumped on every write/invalidate. A reader captures it before the DB read and+# only fills the cache if it is unchanged afterward, so a read that overlapped a+# save cannot repopulate the cache with the pre-save value for the whole TTL.+_generation: dict[tuple[str, str], int] = {}_lock = threading.Lock()-# Per-model, process-local: the last (gguf_repo, backend, download_pending, files) seen for each model. The one stored record belongs to whichever model was saved last; see remembered_gguf_repo.-_resolved_gguf_memo: dict[str, tuple[Optional[str], Optional[str], bool, Optional[list]]] = {}+# Per-model, process-local: the last (gguf_repo, backend, download_pending, files)+# seen for each model. The one stored record belongs to whichever model was saved+# last; see remembered_gguf_repo.+_resolved_gguf_memo: dict[+ tuple[str, str], tuple[Optional[str], Optional[str], bool, Optional[list]]+] = {}+++def _store_cached(key: tuple[str, str], value: _StoredState) -> None:+ now = time.monotonic()+ if key not in _cached and len(_cached) >= _CACHE_MAX:+ for stale in [k for k, (at, _v) in _cached.items() if now - at >= _CACHE_TTL_S]:+ del _cached[stale]+ while len(_cached) >= _CACHE_MAX:+ _cached.pop(next(iter(_cached)))+ _cached[key] = (now, value)def _invalidate_cache() -> None:- global _cached, _generation+ key = (current_account_id(), EMBEDDING_RESOLUTION_SETTING_KEY)with _lock:- _cached = None- _generation += 1+ _cached.pop(key, None)+ _generation[key] = _generation.get(key, 0) + 1def default_embedding_model() -> str:@@ -89,12 +110,17 @@ def get_stored_gguf_repo(model: str) -> str | None:def _remember_resolution(model: str, stored: _StoredState) -> None:"""Keep this process's last resolved repo/backend/pending/files for ``model``."""with _lock:- _resolved_gguf_memo[model] = (stored[2], stored[3], stored[4], _files_of(stored[5]))+ _resolved_gguf_memo[(current_account_id(), model)] = (+ stored[2],+ stored[3],+ stored[4],+ _files_of(stored[5]),+ )def _remembered(model: str) -> tuple[str | None, str | None, bool, list | None] | None:with _lock:- return _resolved_gguf_memo.get(model)+ return _resolved_gguf_memo.get((current_account_id(), model))def _files_of(resolution: Optional[dict]) -> Optional[list]:@@ -172,14 +198,19 @@ def get_stored_embedding_model() -> str | None:def _get_stored_state() -> _StoredState:- """Read the override and its resolved artifact association as one snapshot. The resolution is one JSON value so its model/repo/backend can never be torn; the legacy individual fields are read in the same SQL statement for compatibility with builds from before the atomic record existed."""- global _cached+ """Read the override and its resolved artifact association as one snapshot.++ The resolution is one JSON value so its model/repo/backend can never be+ torn. The legacy individual fields are read in the same SQL statement for+ compatibility with builds from before the atomic record existed.+ """+ key = (current_account_id(), EMBEDDING_RESOLUTION_SETTING_KEY)now = time.monotonic()with _lock:- cached = _cached+ cached = _cached.get(key)if cached is not None and now - cached[0] < _CACHE_TTL_S:return cached[1]- gen = _generation+ gen = _generation.get(key, 0)try:from storage.studio_db import get_app_settingssettings = get_app_settings(@@ -193,9 +224,10 @@ def _get_stored_state() -> _StoredState:except Exception:# Transient store failure: keep the last known value instead of silently reverting the embed/search hot path to the default model, which would mix vector spaces mid-ingestion.with _lock:- if _cached is not None:- _cached = (time.monotonic(), _cached[1])- return _cached[1]+ cached = _cached.get(key)+ if cached is not None:+ _cached[key] = (time.monotonic(), cached[1])+ return cached[1]return (None, None, None, None, False, None)override = _coerce_embedding_model(settings.get(EMBEDDING_MODEL_SETTING_KEY))resolution = settings.get(EMBEDDING_RESOLUTION_SETTING_KEY)@@ -214,9 +246,10 @@ def _get_stored_state() -> _StoredState:raw = resolution if isinstance(resolution, dict) else Nonevalue: _StoredState = (override, resolved_model, repo, backend, download_pending, raw)with _lock:- # Only cache when no save landed while reading: a pre-save value would mask the new one for the whole TTL.- if _generation == gen:- _cached = (time.monotonic(), value)+ # Only cache when no save landed while reading: a pre-save value would mask the new one for the+ # whole TTL.+ if _generation.get(key, 0) == gen:+ _store_cached(key, value)return valuediff --git a/studio/backend/utils/hf_cache_settings.py b/studio/backend/utils/hf_cache_settings.pyindex 4c817e67ea8..62effd8e311 100644--- a/studio/backend/utils/hf_cache_settings.py+++ b/studio/backend/utils/hf_cache_settings.py@@ -111,7 +111,8 @@ def _environment_paths() -> Optional[HuggingFaceCachePaths]:def _stored_cache_home() -> Optional[Path]:try:from storage.studio_db import get_app_setting- value = get_app_setting(CACHE_HOME_SETTING_KEY, None)+ from utils.account_context import OWNER, run_as+ value = run_as(OWNER, get_app_setting, CACHE_HOME_SETTING_KEY, None)except Exception: # noqa: BLE001 - the shim is optional; a spawn must never depend on itreturn Noneif not isinstance(value, str) or not value.strip():@@ -137,7 +138,8 @@ def configured_cache_key() -> str:return "env:" + explicittry:from storage.studio_db import get_app_setting- value = get_app_setting(CACHE_HOME_SETTING_KEY, None)+ from utils.account_context import OWNER, run_as+ value = run_as(OWNER, get_app_setting, CACHE_HOME_SETTING_KEY, None)except Exception:return "default"if isinstance(value, str) and value.strip():@@ -285,7 +287,8 @@ def _validate_cache_home(raw_path: str) -> Path:def _stored_history() -> list[Path]:try:from storage.studio_db import get_app_setting- raw = get_app_setting(CACHE_HISTORY_SETTING_KEY, [])+ from utils.account_context import OWNER, run_as+ raw = run_as(OWNER, get_app_setting, CACHE_HISTORY_SETTING_KEY, [])except Exception:raw = []if not isinstance(raw, list):diff --git a/studio/backend/utils/hf_token_validation.py b/studio/backend/utils/hf_token_validation.pyindex 7247c6e7566..894c3d95096 100644--- a/studio/backend/utils/hf_token_validation.py+++ b/studio/backend/utils/hf_token_validation.py@@ -12,6 +12,8 @@ from collections import dequefrom dataclasses import dataclassfrom typing import Literal+from utils.account_context import current_account_id+from huggingface_hub import HfApifrom huggingface_hub.utils import build_hf_headers, get_session@@ -34,9 +36,9 @@ _MAX_CACHE_ENTRIES = 4096_INFLIGHT_WAIT_SECONDS = 30.0_REMOTE_TIMEOUT_SECONDS = 10.0-_attempts: dict[str, deque[float]] = {}-_cache: dict[str, tuple[float, TokenValidationResult]] = {}-_inflight: dict[str, threading.Event] = {}+_attempts: dict[tuple[str, str], deque[float]] = {}+_cache: dict[tuple[str, str], tuple[float, TokenValidationResult]] = {}+_inflight: dict[tuple[str, str], threading.Event] = {}_lock = threading.Lock()@@ -60,7 +62,7 @@ def _prune_locked(now: float) -> None:del _cache[key]-def _cached_locked(fingerprint: str, now: float) -> TokenValidationResult | None:+def _cached_locked(fingerprint: tuple[str, str], now: float) -> TokenValidationResult | None:cached = _cache.get(fingerprint)if cached is None:return None@@ -75,7 +77,7 @@ def _retry_after(bucket: deque[float], now: float) -> int:return max(1, int(_WINDOW_SECONDS - (now - bucket[0])) + 1)-def _reserve_attempt_locked(rate_key: str, now: float) -> TokenValidationResult | None:+def _reserve_attempt_locked(rate_key: tuple[str, str], now: float) -> TokenValidationResult | None:bucket = _attempts.get(rate_key)if bucket is None:if len(_attempts) >= _MAX_BUCKETS:@@ -146,16 +148,13 @@ def _check_remote(token: str) -> TokenValidationResult:def validate_hf_token(token: str, *, rate_key: str) -> TokenValidationResult:- """Validate ``token`` without retaining it, sharing results across callers.-- Cached checks do not consume the caller's three-per-hour network budget. A- single-flight event also prevents simultaneously mounted UI surfaces from- sending duplicate ``whoami`` requests for the same token.- """+ """Validate ``token`` without retaining it; cached checks skip the three-per-hour network budget."""normalized = token.strip()if not normalized:return TokenValidationResult(status = "invalid")- token_fingerprint = _fingerprint(normalized)+ account_id = current_account_id()+ token_fingerprint = (account_id, _fingerprint(normalized))+ account_rate_key = (account_id, rate_key)owner_event: threading.Event | None = Nonetry:@@ -167,7 +166,7 @@ def validate_hf_token(token: str, *, rate_key: str) -> TokenValidationResult:return cachedwaiting = _inflight.get(token_fingerprint)if waiting is None:- limited = _reserve_attempt_locked(rate_key, now)+ limited = _reserve_attempt_locked(account_rate_key, now)if limited is not None:return limitedowner_event = threading.Event()diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.pyindex b8391a952f3..11879fb636b 100644--- a/studio/backend/utils/keyless_api_access.py+++ b/studio/backend/utils/keyless_api_access.py@@ -11,6 +11,8 @@ import timeimport weakreffrom typing import Any, Optional+from utils.account_context import OWNER, is_owner_context, run_as+KEYLESS_API_ACCESS_SETTING_KEY = "keyless_api_access_scope"KEYLESS_API_TOOLS_SETTING_KEY = "keyless_api_access_tools"DEFAULT_KEYLESS_API_TOOLS_ENABLED = False@@ -45,9 +47,7 @@ _INFERENCE_ROUTES = frozenset(def is_empty_bearer(header: str) -> bool:- """Whether ``header`` is a bearer with no token: what a harness sends with no key set."""from fastapi.security.utils import get_authorization_scheme_param-scheme, token = get_authorization_scheme_param(header)return scheme.lower() == "bearer" and not token@@ -93,7 +93,9 @@ def _reset_scope_cache() -> None:def _read_settings_from_db() -> tuple[str, bool]:from storage.studio_db import get_app_settings- values = get_app_settings([KEYLESS_API_ACCESS_SETTING_KEY, KEYLESS_API_TOOLS_SETTING_KEY])+ keys = [KEYLESS_API_ACCESS_SETTING_KEY, KEYLESS_API_TOOLS_SETTING_KEY]+ # The cache is installation-wide, so a managed account's private settings must never be published as the authentication policy.+ values = get_app_settings(keys) if is_owner_context() else run_as(OWNER, get_app_settings, keys)scope = _coerce_scope(values.get(KEYLESS_API_ACCESS_SETTING_KEY))tools = _coerce_bool(values.get(KEYLESS_API_TOOLS_SETTING_KEY))return (@@ -209,6 +211,8 @@ def get_keyless_api_tools_enabled() -> bool:def set_keyless_api_access(value: Any, *, tools: Any = None) -> tuple[str, bool]:"""Persist which routes are served without a key, and whether tools come with them."""global _cached_settings, _settings_generation, _settings_write_inflight+ if not is_owner_context():+ raise ValueError("Only the installation owner can change keyless API access.")scope = _coerce_scope(value)if scope is None:raise ValueError(f"Keyless API access scope must be one of: {', '.join(KEYLESS_SCOPES)}.")@@ -502,6 +506,10 @@ def keyless_request_allowed(request: Any) -> bool:def _keyless_request_allowed_for_scope(request: Any, scope: str) -> bool:if scope == KEYLESS_SCOPE_OFF:return False+ from auth.policy import installation_has_managed_accounts++ if installation_has_managed_accounts():+ return Falseasgi_scope = getattr(request, "scope", {})method = asgi_scope.get("method", "")path = asgi_scope.get("path", "")@@ -525,6 +533,10 @@ def request_was_admitted_keyless(request: Any) -> Optional[bool]:value = getattr(request.state, KEYLESS_ADMISSION_STATE_KEY)except Exception:return None+ if value is True:+ from auth.policy import installation_has_managed_accounts+ if installation_has_managed_accounts():+ return Falsereturn value if isinstance(value, bool) else Nonediff --git a/studio/backend/utils/llama_cpp_path_settings.py b/studio/backend/utils/llama_cpp_path_settings.pyindex c8706da8cac..361d65d2cb6 100644--- a/studio/backend/utils/llama_cpp_path_settings.py+++ b/studio/backend/utils/llama_cpp_path_settings.py@@ -95,7 +95,8 @@ def get_stored_custom_llama_cpp_path() -> Optional[Path]:"""The Unsloth-selected directory, or ``None`` when automatic discovery is active."""try:from storage.studio_db import get_app_setting- value = get_app_setting(CUSTOM_LLAMA_CPP_PATH_SETTING_KEY, None)+ from utils.account_context import OWNER, run_as+ value = run_as(OWNER, get_app_setting, CUSTOM_LLAMA_CPP_PATH_SETTING_KEY, None)except Exception:# A settings DB problem must not take the bundled runtime down with it.return Nonediff --git a/studio/backend/utils/model_memory_settings.py b/studio/backend/utils/model_memory_settings.pyindex 2706c08508b..20ede1c4ea2 100644--- a/studio/backend/utils/model_memory_settings.py+++ b/studio/backend/utils/model_memory_settings.py@@ -19,6 +19,8 @@ import threadingimport timefrom typing import Any, Optional+from utils.account_context import OWNER, run_as+KEEP_RESIDENT_SETTING_KEY = "model_memory_keep_resident"NO_RAM_RESERVE_SETTING_KEY = "model_memory_no_ram_reserve"@@ -29,10 +31,10 @@ DEFAULT_NO_RAM_RESERVE = False# Matches openai_auto_switch_settings._CACHE_TTL_S = 2.0_cache_lock = threading.Lock()-_cache: dict[str, tuple[float, Any]] = {}+_cache: dict[tuple[str, str], tuple[float, Any]] = {}# Bumped on every write. A read that began before a write must not fill the cache with the value it already fetched, or# the new setting would appear to revert for the rest of the TTL and a load could launch contradicting it.-_generation: dict[str, int] = {}+_generation: dict[tuple[str, str], int] = {}def _coerce_bool(value: Any) -> Optional[bool]:@@ -53,21 +55,22 @@ _MAX_REREADS = 3def _cached_setting(key: str) -> Any:+ cache_key = (OWNER.account_id, key)for _attempt in range(_MAX_REREADS):with _cache_lock:- hit = _cache.get(key)+ hit = _cache.get(cache_key)if hit is not None and time.monotonic() - hit[0] < _CACHE_TTL_S:return hit[1]- generation = _generation.get(key, 0)+ generation = _generation.get(cache_key, 0)try:from storage.studio_db import get_app_setting- stored = get_app_setting(key, None)+ stored = run_as(OWNER, get_app_setting, key, None)except Exception:# An unreadable DB must not fail a load; fall back to the default.return Nonewith _cache_lock:- if _generation.get(key, 0) == generation:- _cache[key] = (time.monotonic(), stored)+ if _generation.get(cache_key, 0) == generation:+ _cache[cache_key] = (time.monotonic(), stored)return stored# A write committed while this read was in flight, so `stored` predates# it. Returning it would let a load launch with flags contradicting the@@ -80,10 +83,12 @@ def _invalidate(*keys: str) -> None:transaction, so invalidating them separately would let a load in between reada new keep_resident against a cached old no_ram_reserve and emit --mlock fora combination that was never stored."""+ account_id = OWNER.account_idwith _cache_lock:for key in keys:- _cache.pop(key, None)- _generation[key] = _generation.get(key, 0) + 1+ cache_key = (account_id, key)+ _cache.pop(cache_key, None)+ _generation[cache_key] = _generation.get(cache_key, 0) + 1def get_keep_resident() -> bool:@@ -111,8 +116,8 @@ def should_mlock() -> bool:def _pair_generations() -> tuple[int, int]:with _cache_lock:return (- _generation.get(KEEP_RESIDENT_SETTING_KEY, 0),- _generation.get(NO_RAM_RESERVE_SETTING_KEY, 0),+ _generation.get((OWNER.account_id, KEEP_RESIDENT_SETTING_KEY), 0),+ _generation.get((OWNER.account_id, NO_RAM_RESERVE_SETTING_KEY), 0),)diff --git a/studio/backend/utils/models/checkpoints.py b/studio/backend/utils/models/checkpoints.pyindex eaf75140fc2..d38c570ae43 100644--- a/studio/backend/utils/models/checkpoints.py+++ b/studio/backend/utils/models/checkpoints.py@@ -3,6 +3,8 @@"""Checkpoint scanning utilities for discovering training runs and checkpoints."""+from __future__ import annotations+import jsonimport reimport structlog@@ -16,6 +18,7 @@ from utils.training_runs import (model_segment_from_default_output_dir_name,)from utils.paths import outputs_root, resolve_output_dir+from utils.paths.storage_roots import own_entry, within_accountlogger = get_logger(__name__)@@ -126,7 +129,7 @@ def _infer_base_model_from_history(checkpoint_dir: Path) -> Optional[str]:def _read_checkpoint_loss(checkpoint_path: Path) -> Optional[float]:"""Read loss from the last log_history entry of trainer_state.json, or None."""trainer_state = checkpoint_path / "trainer_state.json"- if not trainer_state.exists():+ if not own_entry(trainer_state):return Nonetry:with open(trainer_state, encoding = "utf-8-sig") as f:@@ -140,7 +143,7 @@ def _read_checkpoint_loss(checkpoint_path: Path) -> Optional[float]:def scan_checkpoints(- outputs_dir: str = str(outputs_root()),+ outputs_dir: str | None = None,) -> List[Tuple[str, List[Tuple[str, str, Optional[float]]], dict]]:"""Scan outputs folder for training runs and their checkpoints.@@ -152,6 +155,8 @@ def scan_checkpoints(by numeric step descending; non-numbered checkpoint-* dirs keep theprevious lexicographic directory order."""+ if outputs_dir is None:+ outputs_dir = str(outputs_root())models = []outputs_path = resolve_output_dir(outputs_dir)@@ -163,27 +168,29 @@ def scan_checkpoints(for item in outputs_path.iterdir():if not item.is_dir():continue+ if not within_account(item):+ continueconfig_file = item / "config.json"adapter_config = item / "adapter_config.json"- if not (config_file.exists() or adapter_config.exists()):+ if not (own_entry(config_file) or own_entry(adapter_config)):continue# Training metadata from adapter_config.json / config.jsonmetadata: dict = {}try:- if adapter_config.exists():+ if own_entry(adapter_config):cfg = json.loads(adapter_config.read_text(encoding = "utf-8-sig"))metadata["base_model"] = cfg.get("base_model_name_or_path")metadata["peft_type"] = cfg.get("peft_type")metadata["lora_rank"] = cfg.get("r")- elif config_file.exists():+ elif own_entry(config_file):cfg = json.loads(config_file.read_text(encoding = "utf-8-sig"))metadata["base_model"] = cfg.get("_name_or_path")# Detect BNB quantization from config.json- if config_file.exists():+ if own_entry(config_file):if "cfg" not in dir():cfg = json.loads(config_file.read_text(encoding = "utf-8-sig"))quant_cfg = cfg.get("quantization_config")@@ -221,9 +228,11 @@ def scan_checkpoints(for sub in item.iterdir():if not sub.is_dir() or not sub.name.startswith("checkpoint-"):continue+ if not within_account(sub):+ continuesub_config = sub / "config.json"sub_adapter = sub / "adapter_config.json"- if sub_config.exists() or sub_adapter.exists():+ if own_entry(sub_config) or own_entry(sub_adapter):valid_checkpoints.append(sub)intermediate_checkpoints = []@@ -298,7 +307,9 @@ def resolve_preview_checkpoint(run: str, checkpoint: Optional[str] = None) -> Pareturn path-def list_preview_targets(outputs_dir: str = str(outputs_root())) -> List[dict]:+def list_preview_targets(outputs_dir: str | None = None) -> List[dict]:+ if outputs_dir is None:+ outputs_dir = str(outputs_root())targets: List[dict] = []for run_name, checkpoints, metadata in scan_checkpoints(outputs_dir):for display_name, path, loss in checkpoints:diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.pyindex 3f86e74f82d..52d82067e99 100644--- a/studio/backend/utils/models/gguf_metadata.py+++ b/studio/backend/utils/models/gguf_metadata.py@@ -2,8 +2,7 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0"""``general.*`` reader for GGUF headers, used by ``detect_mmproj_file`` to-pair weights and projectors via ``general.base_model.0.repo_url``. ~30 ms-per file, cached by resolved path and platform file identity."""+pair weights and projectors via ``general.base_model.0.repo_url``."""from __future__ import annotationsdiff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 9c178c38b28..447614f2a21 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -5,6 +5,7 @@from dataclasses import dataclassfrom typing import Optional, Dict, Any+from utils.paths.storage_roots import own_entry, within_accountfrom utils.paths import (normalize_path,is_local_path,@@ -1423,7 +1424,7 @@ def _local_audio_metadata_fingerprint(model_name: str) -> tuple:identities.append((relative, identity))return tuple(identities)except Exception:- # Keep cache-key construction from turning an unreadable path into a request failure.+ # An unreadable path must not turn cache-key construction into a request failure.return (("unreadable", None),)@@ -3523,13 +3524,15 @@ def _looks_like_lora_adapter(model_dir: Path) -> bool:)-def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[str, str, str]]:+def scan_trained_models(outputs_dir: Optional[str] = None) -> List[Tuple[str, str, str]]:"""Scan outputs folder for trained Unsloth models.Returns:List of (display_name, model_path, model_type), where model_type is"lora" for adapter runs or "merged" for full finetunes."""+ if outputs_dir is None:+ outputs_dir = str(outputs_root())trained_models = []outputs_path = resolve_output_dir(outputs_dir)@@ -3539,7 +3542,7 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[sttry:for item in outputs_path.iterdir():- if item.is_dir():+ if item.is_dir() and within_account(item):model_type = _detect_training_output_type(item)if model_type is None:continue@@ -3564,7 +3567,7 @@ def scan_trained_models(outputs_dir: str = str(outputs_root())) -> List[Tuple[stdef scan_exported_models(- exports_dir: str = str(exports_root()),+ exports_dir: Optional[str] = None,) -> List[Tuple[str, str, str, Optional[str]]]:"""Scan exports folder for exported models (merged, LoRA, GGUF).@@ -3575,6 +3578,8 @@ def scan_exported_models(List of (display_name, model_path, export_type, base_model), whereexport_type is "lora" | "merged" | "gguf"."""+ if exports_dir is None:+ exports_dir = str(exports_root())results = []exports_path = resolve_export_dir(exports_dir)@@ -3584,7 +3589,7 @@ def scan_exported_models(try:for run_dir in exports_path.iterdir():- if not run_dir.is_dir():+ if not run_dir.is_dir() or not within_account(run_dir):continue# Flat GGUF export (exports/...-gguf/); neither mmproj files nor the imatrix an@@ -3612,7 +3617,7 @@ def scan_exported_models(# Two-level: {run}/{checkpoint}/for checkpoint_dir in run_dir.iterdir():- if not checkpoint_dir.is_dir():+ if not checkpoint_dir.is_dir() or not within_account(checkpoint_dir):continueadapter_config = checkpoint_dir / "adapter_config.json"@@ -3626,18 +3631,18 @@ def scan_exported_models(base_model = Noneexport_type = None- if adapter_config.exists():+ if own_entry(adapter_config):export_type = "lora"try:cfg = json.loads(adapter_config.read_text(encoding = "utf-8-sig"))base_model = cfg.get("base_model_name_or_path")except Exception:pass- elif config_file.exists() and has_weights:+ elif own_entry(config_file) and has_weights:export_type = "merged"export_meta = checkpoint_dir / "export_metadata.json"try:- if export_meta.exists():+ if own_entry(export_meta):meta = json.loads(export_meta.read_text(encoding = "utf-8-sig"))base_model = meta.get("base_model")except Exception:@@ -3649,7 +3654,7 @@ def scan_exported_models(for meta_dir in (checkpoint_dir, run_dir):export_meta = meta_dir / "export_metadata.json"try:- if export_meta.exists():+ if own_entry(export_meta):meta = json.loads(export_meta.read_text(encoding = "utf-8-sig"))base_model = meta.get("base_model")if base_model:@@ -3669,7 +3674,7 @@ def scan_exported_models(if not base_model:outputs_adapter_cfg = resolve_output_dir(run_dir.name) / "adapter_config.json"try:- if outputs_adapter_cfg.exists():+ if own_entry(outputs_adapter_cfg):cfg = json.loads(outputs_adapter_cfg.read_text(encoding = "utf-8-sig"))base_model = cfg.get("base_model_name_or_path")except Exception:@@ -4201,7 +4206,6 @@ class ModelConfig:None,)- # Separate speculative-decoding companions, mirroring mmproj.mtp_file = _find_drafter(detect_mtp_file, "mtp")if mtp_file:logger.info(f"Detected MTP drafter: {mtp_file}")diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex f4bf24345ee..cf09d0973b4 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -11,6 +11,8 @@ import threadingimport timefrom typing import Any, Mapping, Optional+from utils.account_context import OWNER, run_as+OPENAI_AUTO_SWITCH_SETTING_KEY = "openai_api_auto_switch_model"OPENAI_AUTO_DOWNLOAD_SETTING_KEY = "openai_api_auto_download_model"AUTO_UNLOAD_IDLE_SETTING_KEY = "openai_api_auto_unload_idle_seconds"@@ -33,7 +35,7 @@ MIN_AUTO_UNLOAD_IDLE_SECONDS = 60_CACHE_TTL_S = 2.0_cache_lock = threading.Lock()-_cache: dict[str, tuple[float, Any]] = {}+_cache: dict[tuple[str, str], tuple[float, Any]] = {}def _coerce_bool(value: Any) -> bool | None:@@ -61,25 +63,27 @@ def _apply_idle_floor(seconds: int) -> int:def _cached_setting(key: str, default: Any) -> Any:"""Read an app setting, memoized for _CACHE_TTL_S to spare the hot path."""+ cache_key = (OWNER.account_id, key)now = time.monotonic()with _cache_lock:- hit = _cache.get(key)+ hit = _cache.get(cache_key)if hit is not None and now - hit[0] < _CACHE_TTL_S:return hit[1]try:from storage.studio_db import get_app_setting- stored = get_app_setting(key, None)+ stored = run_as(OWNER, get_app_setting, key, None)except Exception:stored = Nonevalue = default if stored is None else storedwith _cache_lock:- _cache[key] = (now, value)+ _cache[cache_key] = (now, value)return valuedef _invalidate(key: str) -> None:+ cache_key = (OWNER.account_id, key)with _cache_lock:- _cache.pop(key, None)+ _cache.pop(cache_key, None)def get_openai_auto_switch_enabled() -> bool:diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.pyindex 594488a18aa..1295d82c5ba 100644--- a/studio/backend/utils/paths/__init__.py+++ b/studio/backend/utils/paths/__init__.py@@ -15,6 +15,8 @@ from .path_utils import ()from .storage_roots import (studio_root,+ account_path,+ workspace_root,assets_root,dataset_files_in_dir,datasets_root,@@ -42,6 +44,7 @@ from .storage_roots import (ollama_model_dirs,hermes_model_dirs,well_known_model_dirs,+ ensure_account_dir,ensure_dir,ensure_studio_directories,resolve_under_root,@@ -67,6 +70,8 @@ __all__ = ["reset_cache_case_resolution_state","reveal_in_file_manager","studio_root",+ "account_path",+ "workspace_root","assets_root","dataset_files_in_dir","datasets_root",@@ -94,6 +99,7 @@ __all__ = ["ollama_model_dirs","hermes_model_dirs","well_known_model_dirs",+ "ensure_account_dir","ensure_dir","ensure_studio_directories","resolve_under_root",diff --git a/studio/backend/utils/paths/lazy.py b/studio/backend/utils/paths/lazy.pynew file mode 100644index 00000000000..4f0d9f000ae--- /dev/null+++ b/studio/backend/utils/paths/lazy.py@@ -0,0 +1,42 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Compatibility accessors for formerly import-time path constants."""++from __future__ import annotations++import os+from pathlib import Path+from typing import Callable+++class LazyPath(os.PathLike[str]):+ """Resolve a root in the acting account at use time; do not retain the accessor as a job's account identity, bind the account instead."""++ def __init__(self, resolve: Callable[[], Path]):+ self._resolve = resolve++ def __call__(self) -> Path:+ return self._resolve()++ def __fspath__(self) -> str:+ return os.fspath(self._resolve())++ def __str__(self) -> str:+ return str(self._resolve())++ def __truediv__(self, other: str | os.PathLike[str]) -> Path:+ return self._resolve() / other++ def __rtruediv__(self, other: str | os.PathLike[str]) -> Path:+ return other / self._resolve()++ def __getattr__(self, name: str):+ return getattr(self._resolve(), name)++ def __eq__(self, other: object) -> bool:+ if isinstance(other, LazyPath):+ other = other()+ return self._resolve() == other++ __hash__ = Nonediff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.pyindex 87002f22a29..9dcf984bcca 100644--- a/studio/backend/utils/paths/storage_roots.py+++ b/studio/backend/utils/paths/storage_roots.py@@ -8,11 +8,13 @@ import ntpathimport osimport reimport sys+import threadingfrom pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Iterableimport tempfilefrom loggers import get_logger+from utils.account_context import current_account, is_owner_contextfrom utils.paths.path_utils import drop_appledouble_metadata, host_normalize_pathlogger = get_logger(__name__)@@ -63,8 +65,17 @@ def studio_root() -> Path:return Path.home() / ".unsloth" / "studio"+def workspace_root() -> Path:+ """Private persistent root of the acting account: owner keeps the historical install-root+ layout, others get ``accounts/<account_id>/``, keyed by id so a reused name inherits nothing."""+ root = studio_root()+ if is_owner_context():+ return root+ return root / "accounts" / current_account().account_id++def cache_root() -> Path:- """Central cache dir for all studio downloads (models, datasets, etc.)."""+ """Central cache dir for all studio downloads (models, datasets, etc.). Shared."""return studio_root() / "cache"@@ -78,28 +89,37 @@ def studio_bin_root() -> Path:return studio_root() / "bin"+def account_path(relative: str) -> Path:+ """``workspace_root() / relative``, checked to really live inside the account's workspace: a+ directory swapped for a link into another account's tree would carry all its readers there."""+ path = workspace_root() / relative+ if not is_owner_context() and not within_account(path):+ raise ValueError(f"path escapes the account workspace: {path!s}")+ return path++def assets_root() -> Path:- return studio_root() / "assets"+ return account_path("assets")def datasets_root() -> Path:- return assets_root() / "datasets"+ return account_path("assets/datasets")def dataset_uploads_root() -> Path:- return datasets_root() / "uploads"+ return account_path("assets/datasets/uploads")def recipe_datasets_root() -> Path:- return datasets_root() / "recipes"+ return account_path("assets/datasets/recipes")def outputs_root() -> Path:- return studio_root() / "outputs"+ return account_path("outputs")def exports_root() -> Path:- return studio_root() / "exports"+ return account_path("exports")def auth_root() -> Path:@@ -111,12 +131,12 @@ def auth_db_path() -> Path:def studio_db_path() -> Path:- return studio_root() / "studio.db"+ return account_path("studio.db")def rag_root() -> Path:"""Root directory for retrieval-augmented-generation state (db + uploads)."""- return studio_root() / "rag"+ return account_path("rag")def rag_db_path() -> Path:@@ -192,19 +212,33 @@ def documents_root() -> Path:)+def shared_project_workspaces_root() -> Path:+ """Base every account's ``project_workspaces_root`` lives under; confinement hides it first."""+ override = (os.environ.get("UNSLOTH_STUDIO_PROJECTS_HOME") or "").strip()+ return Path(override).expanduser() if override else documents_root() / "Unsloth Studio"++def project_workspaces_root() -> Path:override = (os.environ.get("UNSLOTH_STUDIO_PROJECTS_HOME") or "").strip()- if override:- return Path(override).expanduser()- return documents_root() / "Unsloth Studio" / "Projects"+ base = shared_project_workspaces_root()+ if is_owner_context():+ return base if override else base / "Projects"+ return base / "Accounts" / current_account().account_id / "Projects"-def tmp_root() -> Path:+def shared_tmp_root() -> Path:return Path(tempfile.gettempdir()) / "unsloth-studio"+def tmp_root() -> Path:+ root = shared_tmp_root()+ if is_owner_context():+ return root+ return root / "accounts" / current_account().account_id++def seed_uploads_root() -> Path:- return datasets_root() / "seed-uploads"+ return account_path("assets/datasets/seed-uploads")def unstructured_seed_cache_root() -> Path:@@ -212,7 +246,7 @@ def unstructured_seed_cache_root() -> Path:def unstructured_uploads_root() -> Path:- return datasets_root() / "unstructured-uploads"+ return account_path("assets/datasets/unstructured-uploads")def oxc_validator_tmp_root() -> Path:@@ -220,14 +254,83 @@ def oxc_validator_tmp_root() -> Path:def tensorboard_root() -> Path:- return studio_root() / "runs"+ return account_path("runs")-def ensure_dir(path: Path) -> Path:+def _mkdir(path: Path) -> Path:path.mkdir(parents = True, exist_ok = True)return path+class RetiredAccountError(RuntimeError):+ """A write arrived for an account whose private roots have already been retired."""+++# Held across the rename-aside and every guarded directory creation.+root_retirement_lock = threading.RLock()+++def external_account_sandbox_root() -> Path | None:+ """The managed account's tool sandbox when ``UNSLOTH_STUDIO_SANDBOX_HOME`` moves it out of the+ workspace. A private root like the others, so retirement and ``ensure_dir`` cover it."""+ override = (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip()+ if is_owner_context() or not override:+ return None+ return (+ Path(os.path.abspath(os.path.expanduser(override)))+ / "accounts"+ / current_account().account_id+ )+++def managed_account_roots() -> tuple[Path, ...]:+ """Every private root retirement renames aside for the acting managed account."""+ roots = [workspace_root(), project_workspaces_root(), tmp_root()]+ sandbox = external_account_sandbox_root()+ if sandbox is not None:+ roots.append(sandbox)+ return tuple(roots)+++def _under_managed_workspace(path: Path) -> bool:+ """Lexically, whether *path* is inside one of the roots retirement renames aside."""+ if is_owner_context():+ return False+ try:+ absolute = Path(os.path.abspath(path))+ for root in managed_account_roots():+ try:+ absolute.relative_to(os.path.abspath(root))+ return True+ except ValueError:+ continue+ except (OSError, ValueError):+ return False+ return False+++def ensure_dir(path: Path) -> Path:+ """Create *path*; inside a managed workspace this is retirement-aware for every caller."""+ if _under_managed_workspace(path):+ return ensure_account_dir(path)+ return _mkdir(path)+++def ensure_account_dir(path: Path) -> Path:+ """``ensure_dir`` inside the acting account's workspace: refuse once the tombstone is set, or a+ finalizer outliving deletion recreates the renamed-aside roots. Locked against the rename."""+ with root_retirement_lock:+ if not is_owner_context():+ from core.training.account_jobs import account_is_retired++ # Existence is not proof of life: a late request can mkdir the workspace back.+ if account_is_retired():+ raise RetiredAccountError(+ f"account has been deleted; refusing to recreate {path!s}"+ )+ return _mkdir(path)++def legacy_hf_cache_dir() -> Path:"""Old Unsloth-specific HF hub cache, kept for backward-compat scans."""return cache_root() / "huggingface" / "hub"@@ -511,6 +614,32 @@ def _assert_contained(resolved: Path, root: Path) -> None:) from exc+def within_account(path: Path) -> bool:+ if is_owner_context():+ return True+ try:+ real = Path(os.path.realpath(path))+ except OSError:+ return False+ for root in (workspace_root(), project_workspaces_root(), tmp_root()):+ try:+ real.relative_to(Path(os.path.realpath(root)))+ return True+ except ValueError:+ continue+ return False+++def own_entry(path: Path) -> bool:+ return path.exists() and within_account(path)+++def require_within_account(path: Path) -> Path:+ if not within_account(path):+ raise ValueError(f"path escapes the account workspace: {path!s}")+ return path++def resolve_under_root(path_value: str | None,*,@@ -597,7 +726,7 @@ def resolve_export_write_dir(path_value: str | None = None) -> Path:if _has_parent_segment(raw, path):raise ValueError(f"path may not contain '..' segments: {raw!r}")if _is_absolute_user_path(path):- return path+ return require_within_account(path)return resolve_under_root(path_value,root = exports_root(),@@ -641,7 +770,7 @@ def resolve_dataset_path(path_value: str) -> Path:for root_fn in (datasets_root, dataset_uploads_root, recipe_datasets_root):try:_assert_contained(path, root_fn())- return path+ return require_within_account(path)except ValueError:continueraise ValueError(f"dataset path must be relative or under a dataset root: {raw!r}")@@ -651,10 +780,10 @@ def resolve_dataset_path(path_value: str) -> Path:parts = parts[2:]if parts and parts[0] == "uploads":cleaned = Path(*parts[1:]) if len(parts) > 1 else Path()- return dataset_uploads_root() / cleaned+ return require_within_account(dataset_uploads_root() / cleaned)if parts and parts[0] == "recipes":cleaned = Path(*parts[1:]) if len(parts) > 1 else Path()- return recipe_datasets_root() / cleaned+ return require_within_account(recipe_datasets_root() / cleaned)cleaned = Path(*parts) if parts else Path()candidates = [@@ -666,5 +795,5 @@ def resolve_dataset_path(path_value: str) -> Path:]for candidate in candidates:if candidate.exists():- return candidate+ return require_within_account(candidate)return candidates[0]diff --git a/studio/backend/utils/preview_sharing_settings.py b/studio/backend/utils/preview_sharing_settings.pyindex 047c4be3b41..2056f0a8e62 100644--- a/studio/backend/utils/preview_sharing_settings.py+++ b/studio/backend/utils/preview_sharing_settings.py@@ -36,7 +36,8 @@ def get_preview_sharing_enabled() -> bool:"""try:from storage.studio_db import get_app_setting- stored = get_app_setting(PREVIEW_SHARING_SETTING_KEY, None)+ from utils.account_context import OWNER, run_as+ stored = run_as(OWNER, get_app_setting, PREVIEW_SHARING_SETTING_KEY, None)except Exception:return Falseparsed = _coerce_bool(stored)diff --git a/studio/backend/utils/preview_token.py b/studio/backend/utils/preview_token.pyindex 558a484d0f7..129019a2b45 100644--- a/studio/backend/utils/preview_token.py+++ b/studio/backend/utils/preview_token.py@@ -1,14 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""HMAC capability tokens for public ``/p`` preview share links.--The preview ref (``run`` or ``run/checkpoint``) is a deterministic, guessable-outputs-root path, so it can't gate access on its own. We sign the canonical ref-with a dedicated server-side secret and require the resulting token on every-public preview request: guessing a ref no longer grants access, and rotating the-secret (``auth.storage.rotate_preview_link_secret``) revokes every link at once.-"""+"""HMAC capability tokens for public ``/p`` preview share links; owner tokens keep the original shape, and a managed token carries its account id ahead of a signature covering it, so identically named runs in two accounts never open each other's."""from __future__ import annotations@@ -18,35 +11,64 @@ import hmacfrom typing import Optionalfrom auth.storage import get_or_create_preview_link_secret+from utils.account_context import OWNER, AccountContext, current_account# Versioned so the token format can evolve without silently honoring old shapes._PREVIEW_TOKEN_VERSION = "v1"+_ACCOUNT_TOKEN_VERSION = "v2"+_ACCOUNT_SEPARATOR = "."-def _canonical_payload(ref: str) -> bytes:+def _canonical_payload(ref: str, account_id: Optional[str] = None) -> bytes:# Sign the canonical ref only, never host/path, so links stay portable across localhost / LAN IP# / tunnel host changes.- return f"preview:{_PREVIEW_TOKEN_VERSION}:{ref}".encode("utf-8")+ if account_id is None:+ return f"preview:{_PREVIEW_TOKEN_VERSION}:{ref}".encode("utf-8")+ return f"preview:{_ACCOUNT_TOKEN_VERSION}:{account_id}:{ref}".encode("utf-8")-def sign_preview_ref(ref: str) -> str:- """Return the URL-safe HMAC capability token for a canonical preview ref."""- mac = hmac.new(+def _mac(ref: str, account_id: Optional[str]) -> str:+ digest = hmac.new(get_or_create_preview_link_secret(),- _canonical_payload(ref),+ _canonical_payload(ref, account_id),hashlib.sha256,).digest()- return base64.urlsafe_b64encode(mac).rstrip(b"=").decode("ascii")+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")-def verify_preview_ref(ref: str, token: Optional[str]) -> bool:- """Constant-time check that ``token`` is a valid capability for ``ref``."""+def sign_preview_ref(ref: str, account: Optional[AccountContext] = None) -> str:+ account = account or current_account()+ if account.is_owner:+ return _mac(ref, None)+ return f"{account.account_id}{_ACCOUNT_SEPARATOR}{_mac(ref, account.account_id)}"+++def preview_token_account(ref: str, token: Optional[str]) -> Optional[AccountContext]:+ """The account whose outputs ``token`` opens for ``ref``, or None; constant-time on the signature."""if not token:- return False+ return None# Compare as bytes: a non-ASCII token (e.g. a %-encoded query value) would make# hmac.compare_digest on two str raise TypeError -> treat it as simply invalid.try:provided = token.encode("ascii")except UnicodeEncodeError:- return False- return hmac.compare_digest(sign_preview_ref(ref).encode("ascii"), provided)+ return None+ account_id, separator, signature = token.partition(_ACCOUNT_SEPARATOR)+ if not separator:+ if hmac.compare_digest(_mac(ref, None).encode("ascii"), provided):+ return OWNER+ return None+ if not account_id or not signature or _ACCOUNT_SEPARATOR in signature:+ return None+ if not hmac.compare_digest(_mac(ref, account_id).encode("ascii"), signature.encode("ascii")):+ return None+ from auth.storage import get_account_by_id++ account = get_account_by_id(account_id)+ if account is None or account.is_owner:+ return None+ return account+++def verify_preview_ref(ref: str, token: Optional[str]) -> bool:+ return preview_token_account(ref, token) is not Nonediff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.pyindex c71eba75e40..7aaf9071125 100644--- a/studio/backend/utils/process_lifetime.py+++ b/studio/backend/utils/process_lifetime.py@@ -28,6 +28,8 @@ from __future__ import annotationsimport osimport signalimport sys+import contextvars+import functoolsimport threadingimport timefrom typing import Callable, Optional@@ -450,7 +452,8 @@ class _Spawner:def run(self, spawn: Callable[[], object]) -> object:box: list = []done = threading.Event()- self._jobs.put((spawn, box, done))+ # The spawner thread has no context of its own; run the spawn in the caller's.+ self._jobs.put((functools.partial(contextvars.copy_context().run, spawn), box, done))done.wait()ok, value = box[0]if not ok:diff --git a/studio/backend/utils/security/consent.py b/studio/backend/utils/security/consent.pyindex 16cd3d29400..b866c4d26da 100644--- a/studio/backend/utils/security/consent.py+++ b/studio/backend/utils/security/consent.py@@ -8,11 +8,13 @@ The LOAD-path counterpart to the capability probes (which read raw config and neHardening plus consent, not a sandbox: static patterns are evadable, so subprocess / venv isolation remains the containment layer."""+import osfrom dataclasses import dataclass, fieldfrom typing import Optionalfrom loggers import get_logger+from utils.account_context import is_owner_contextfrom utils.security.remote_code_scan import (CRITICAL,HIGH,@@ -26,6 +28,20 @@ from utils.security.remote_code_scan import (logger = get_logger(__name__)+MANAGED_REMOTE_CODE_OVERRIDE = "UNSLOTH_STUDIO_ALLOW_MANAGED_REMOTE_CODE"+MANAGED_REMOTE_CODE_REFUSAL = (+ "Remote code is off for managed accounts; the installation owner can enable it with "+ f"{MANAGED_REMOTE_CODE_OVERRIDE}=1"+)+++def managed_remote_code_refused() -> bool:+ """Remote code runs unconfined as the Studio user, so a managed account may not+ enable it unless the owner opted in for the whole installation."""+ if is_owner_context():+ return False+ return os.environ.get(MANAGED_REMOTE_CODE_OVERRIDE, "").lower() not in ("1", "true", "yes")+@dataclassclass RemoteCodeDecision:@@ -266,6 +282,11 @@ def evaluate_remote_code_consent_for_targets("auto_map declared but no executable code present; trust_remote_code is a no-op",)+ if managed_remote_code_refused():+ return RemoteCodeDecision(+ primary, True, True, None, None, "", MANAGED_REMOTE_CODE_REFUSAL, approvable = False+ )+result = scan_remote_code_files(combined)fingerprint = remote_code_fingerprint(combined)sev = result.max_severitydiff --git a/studio/backend/utils/security/remote_code_approvals.py b/studio/backend/utils/security/remote_code_approvals.pyindex 44fdc712952..fdd666bedcd 100644--- a/studio/backend/utils/security/remote_code_approvals.py+++ b/studio/backend/utils/security/remote_code_approvals.py@@ -23,6 +23,8 @@ from typing import Optionalfrom loggers import get_loggerfrom utils.paths import storage_roots+from hub.services.models import account_access+from utils.account_context import current_account_id, is_owner_contextfrom utils.security.remote_code_scan import CRITICAL, SCAN_RULES_VERSIONlogger = get_logger(__name__)@@ -48,7 +50,9 @@ def cache_disabled() -> bool:def _store_path():- return storage_roots.studio_root() / "security" / "remote_code_approvals.json"+ if is_owner_context():+ return storage_roots.studio_root() / "security" / "remote_code_approvals.json"+ return storage_roots.account_path("security/remote_code_approvals.json")def _env_offline() -> bool:@@ -148,6 +152,8 @@ def _file_lock():def lookup(subject: str, target_key: str) -> Optional[StoredApproval]:"""The stored approval for (subject, target_key), or None. A CRITICAL entry (e.g. ahand-edited store) is refused so it can never seed an approval."""+ if account_access.managed_account():+ subject = current_account_id()if not subject or cache_disabled():return Nonewith _lock:@@ -176,6 +182,8 @@ def record(scanner_version: int = SCANNER_VERSION,) -> None:"""Persist a user's explicit approval. CRITICAL is never stored."""+ if account_access.managed_account():+ subject = current_account_id()if not subject or not fingerprint or cache_disabled() or max_severity == CRITICAL:returnwith _lock, _file_lock():@@ -196,6 +204,8 @@ def record(def forget(subject: str, target_key: str) -> None:"""Drop an approval (e.g. the user declined / discarded the download)."""+ if account_access.managed_account():+ subject = current_account_id()if not subject:returnwith _lock, _file_lock():@@ -219,7 +229,9 @@ def resolve_commit_sha(target: str, hf_token: Optional[str] = None) -> Optional[fresh every call: the default branch is mutable, so a cached SHA could mask a moved repoand reuse stale consent. None falls back to the authoritative fingerprint (never fail-open)."""+ hf_token = account_access.account_hf_token(hf_token)from utils.paths import is_local_path+try:if is_local_path(target) or _env_offline():return Nonediff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.pyindex 932a802146d..5344ac398b0 100644--- a/studio/backend/utils/upload_limits.py+++ b/studio/backend/utils/upload_limits.py@@ -58,7 +58,8 @@ def validate_upload_limit_mb(value: Any) -> int:def get_upload_limit_mb() -> int:try:from storage.studio_db import get_app_setting- stored = get_app_setting(UPLOAD_LIMIT_SETTING_KEY, None)+ from utils.account_context import OWNER, run_as+ stored = run_as(OWNER, get_app_setting, UPLOAD_LIMIT_SETTING_KEY, None)except Exception:stored = Nonereturn _coerce_upload_limit_mb(stored) or default_upload_limit_mb()diff --git a/studio/backend/utils/vram_budget_settings.py b/studio/backend/utils/vram_budget_settings.pyindex 0b2fe9cc791..b4f5ce1a674 100644--- a/studio/backend/utils/vram_budget_settings.py+++ b/studio/backend/utils/vram_budget_settings.py@@ -17,6 +17,8 @@ import threadingimport timefrom typing import Any, Optional+from utils.account_context import OWNER, run_as+VRAM_BUDGET_SETTING_KEY = "vram_budget_fraction"VRAM_FRACTION_ENV_VAR = "UNSLOTH_VRAM_FRACTION"@@ -32,39 +34,42 @@ VRAM_FRACTION_DECIMALS = 3# Read on the load path, so memo briefly to spare SQLite, as model_memory_settings._CACHE_TTL_S = 2.0_cache_lock = threading.Lock()-_cache: dict[str, tuple[float, Any]] = {}-# Bumped on every write: a read that began before it must not cache its stale value, or the new budget appears to revert for the rest of the TTL.-_generation: dict[str, int] = {}+_cache: dict[tuple[str, str], tuple[float, Any]] = {}+# Bumped on every write: a read that began before it must not cache its stale value, or the new+# budget appears to revert for the rest of the TTL.+_generation: dict[tuple[str, str], int] = {}# Retries converge; the bound only stops a write storm spinning here forever._MAX_REREADS = 3def _cached_setting(key: str) -> Any:+ cache_key = (OWNER.account_id, key)for _attempt in range(_MAX_REREADS):with _cache_lock:- hit = _cache.get(key)+ hit = _cache.get(cache_key)if hit is not None and time.monotonic() - hit[0] < _CACHE_TTL_S:return hit[1]- generation = _generation.get(key, 0)+ generation = _generation.get(cache_key, 0)try:from storage.studio_db import get_app_setting- stored = get_app_setting(key, None)+ stored = run_as(OWNER, get_app_setting, key, None)except Exception:# An unreadable DB must not fail a load; fall back to the default.return Nonewith _cache_lock:- if _generation.get(key, 0) == generation:- _cache[key] = (time.monotonic(), stored)+ if _generation.get(cache_key, 0) == generation:+ _cache[cache_key] = (time.monotonic(), stored)return stored# A write landed mid-read, so `stored` predates it and must not be cached.return storeddef _invalidate(key: str) -> None:+ cache_key = (OWNER.account_id, key)with _cache_lock:- _cache.pop(key, None)- _generation[key] = _generation.get(key, 0) + 1+ _cache.pop(cache_key, None)+ _generation[cache_key] = _generation.get(cache_key, 0) + 1def coerce_fraction(value: Any) -> Optional[float]:diff --git a/studio/frontend/public/reload-snapshot.js b/studio/frontend/public/reload-snapshot.jsindex 06f66967ec9..1e5549182e5 100644--- a/studio/frontend/public/reload-snapshot.js+++ b/studio/frontend/public/reload-snapshot.js@@ -18,6 +18,15 @@var overlay = null;var retainedSnapshot = null;var removalTimer = null;+ var accountStorageKey = "unsloth.browser-account.v1";+ function readAccountMarker() {+ try {+ return localStorage.getItem(accountStorageKey);+ } catch (error) {+ return null;+ }+ }+ var initialAccountMarker = readAccountMarker();// Appearance is inline custom properties on <html> plus these gate attributes, written by// theme-boot.js (mode and palette) and applyCustomizationToDocument in// src/features/settings/stores/appearance-custom-store.ts (the rest). Uncarried, the copy paints@@ -658,6 +667,7 @@function saveSnapshot() {if (+ readAccountMarker() !== initialAccountMarker ||document.documentElement.hasAttribute("data-reload-snapshot-private")) {clearStoredSnapshot();diff --git a/studio/frontend/smoke-settings-main.tsx b/studio/frontend/smoke-settings-main.tsxindex a58e641d2a6..3aad0367d90 100644--- a/studio/frontend/smoke-settings-main.tsx+++ b/studio/frontend/smoke-settings-main.tsx@@ -25,6 +25,16 @@ import {import { Component, type ReactNode, StrictMode } from "react";import { createRoot } from "react-dom/client";import "./src/index.css";+import { AUTH_TOKEN_KEY } from "@/features/auth/session";++// The Accounts tab is owner-only and the owner is read from the token's claims, so the harness carries an unsigned owner token.+if (!localStorage.getItem(AUTH_TOKEN_KEY)) {+ const claims = btoa(JSON.stringify({ sub: "unsloth", role: "owner" }))+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+ localStorage.setItem(AUTH_TOKEN_KEY, `smoke.${claims}.smoke`);+}declare global {interface Window {diff --git a/studio/frontend/src/app/auth-guards.ts b/studio/frontend/src/app/auth-guards.tsindex a3523ac580f..d35f7020f9c 100644--- a/studio/frontend/src/app/auth-guards.ts+++ b/studio/frontend/src/app/auth-guards.ts@@ -3,6 +3,8 @@import { redirect } from "@tanstack/react-router";import { apiUrl, isTauri } from "@/lib/api-base";+import { isTauriLoginRequired } from "@/features/auth/tauri-auto-auth";+import { setLoginMode } from "@/features/auth/login-client";import {getPostAuthRoute,hasAuthToken,@@ -21,6 +23,8 @@ async function hasActiveSession(): Promise<boolean> {interface AuthStatus {initialized: boolean;requires_password_change: boolean;+ login_mode?: "single" | "multi";+ full_access?: boolean;}const AUTH_STATUS_TTL_MS = 30_000;@@ -48,6 +52,10 @@ async function fetchAuthStatus(): Promise<AuthStatus> {}const status = (await res.json()) as AuthStatus;authStatusCheckedAt = Date.now();+ setLoginMode(status.login_mode ?? "single", status.full_access);+ if (status.login_mode === "multi") {+ return { ...status, requires_password_change: mustChangePassword() };+ }// Server truth wins; keep localStorage in sync both ways.if (status.requires_password_change !== mustChangePassword()) {setMustChangePassword(status.requires_password_change);@@ -71,7 +79,7 @@ function authRedirect(to: "/login" | "/change-password"): never {}export async function requireAuth(): Promise<void> {- if (isTauri) {+ if (isTauri && !isTauriLoginRequired()) {// AppProvider owns backend startup + desktop auth; route guards run before it mounts.return;}@@ -96,7 +104,7 @@ export async function requireAuth(): Promise<void> {}export async function requireGuest(): Promise<void> {- if (isTauri) {+ if (isTauri && !isTauriLoginRequired()) {throw redirect({ to: "/chat" });}if (!(await hasActiveSession())) return;@@ -106,7 +114,7 @@ export async function requireGuest(): Promise<void> {}export async function requirePasswordChangeFlow(): Promise<void> {- if (isTauri) {+ if (isTauri && !isTauriLoginRequired()) {throw redirect({ to: "/chat" });}diff --git a/studio/frontend/src/features/auth/account-session.ts b/studio/frontend/src/features/auth/account-session.tsnew file mode 100644index 00000000000..b1ec732cee3--- /dev/null+++ b/studio/frontend/src/features/auth/account-session.ts@@ -0,0 +1,74 @@+// 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 { useEffect, useSyncExternalStore } from "react";+import {+ ensureLoginMode,+ getFullAccessAllowed,+ getLoginMode,+ subscribeLoginMode,+} from "./login-client";+import {+ AUTH_SESSION_CLEARED_EVENT,+ AUTH_SESSION_STORED_EVENT,+ getAuthToken,+} from "./session";++/** Display policy only; the server validates the token and enforces owner access. */+export function sessionAccount(+ token: string | null,+): { username: string; isOwner: boolean } | null {+ if (!token) return null;+ try {+ const payload = JSON.parse(+ atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")),+ );+ if (typeof payload.sub !== "string") return null;+ return {+ username: payload.sub,+ isOwner: payload.role+ ? payload.role === "owner"+ : payload.sub === "unsloth",+ };+ } catch {+ return null;+ }+}++function subscribeSession(listener: () => void): () => void {+ const events = [+ AUTH_SESSION_STORED_EVENT,+ AUTH_SESSION_CLEARED_EVENT,+ "storage",+ ];+ for (const event of events) window.addEventListener(event, listener);+ return () => {+ for (const event of events) window.removeEventListener(event, listener);+ };+}+export function useIsAccountOwner(): boolean {+ return useSyncExternalStore(+ subscribeSession,+ () => sessionAccount(getAuthToken())?.isOwner ?? false,+ () => false,+ );+}+export function useLoginMode() {+ const mode = useSyncExternalStore(+ subscribeLoginMode,+ getLoginMode,+ () => "single" as const,+ );+ useEffect(ensureLoginMode, []);+ return mode;+}+/** Whether Full access may be offered; false whenever another account exists, active or not. */+export function useFullAccessAllowed(): boolean {+ const allowed = useSyncExternalStore(+ subscribeLoginMode,+ getFullAccessAllowed,+ () => true,+ );+ useEffect(ensureLoginMode, []);+ return allowed;+}diff --git a/studio/frontend/src/features/auth/api.ts b/studio/frontend/src/features/auth/api.tsindex cc7a40a8c51..c654d7941af 100644--- a/studio/frontend/src/features/auth/api.ts+++ b/studio/frontend/src/features/auth/api.ts@@ -1,6 +1,7 @@// 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 { accountTransitionPending } from "@/lib/account-transition";import { apiUrl, isTauri } from "@/lib/api-base";import {clearAuthTokens,@@ -91,7 +92,7 @@ async function isPasswordChangeRequiredResponse(}}-async function redirectToAuth(): Promise<void> {+async function redirectToAuth(passwordChangeRequired = false): Promise<void> {if (isRedirecting) return;isRedirecting = true;@@ -99,12 +100,18 @@ async function redirectToAuth(): Promise<void> {try {const res = await fetch(apiUrl("/api/auth/status"));if (res.ok) {- const data = (await res.json()) as { requires_password_change: boolean };- // Server truth wins; keep localStorage in sync both ways.- if (data.requires_password_change !== mustChangePassword()) {- setMustChangePassword(data.requires_password_change);+ const data = (await res.json()) as {+ requires_password_change: boolean;+ login_mode?: "single" | "multi";+ };+ // Public status describes the owner. A managed session carries its own requirement.+ const requiresChange = data.login_mode === "multi"+ ? passwordChangeRequired || mustChangePassword()+ : data.requires_password_change;+ if (requiresChange !== mustChangePassword()) {+ setMustChangePassword(requiresChange);}- if (data.requires_password_change) target = "/change-password";+ if (requiresChange) target = "/change-password";}} catch {// Fall through to /login on error@@ -226,6 +233,10 @@ export async function authFetch(init?: RequestInit,options?: AuthFetchOptions,): Promise<Response> {+ // Another tab is mid-switch: its new tokens are published before this tab reloads, so a+ // request now would carry this tab's account content under the next account's credentials.+ if (accountTransitionPending())+ throw new Error("Another tab is switching accounts; this tab will reload.");const resolvedInput = typeof input === "string" ? apiUrl(input) : input;const headers = new Headers(init?.headers);addBrowserTimezoneHeaders(headers);@@ -260,7 +271,7 @@ export async function authFetch()) ?? response);}- void redirectToAuth();+ void redirectToAuth(true);return response;}if (response.status !== 401) return response;diff --git a/studio/frontend/src/features/auth/components/auth-form.tsx b/studio/frontend/src/features/auth/components/auth-form.tsxindex f4829680249..7eab3272fd2 100644--- a/studio/frontend/src/features/auth/components/auth-form.tsx+++ b/studio/frontend/src/features/auth/components/auth-form.tsx@@ -3,6 +3,9 @@import { useAppShellReadySignal } from "@/components/app-readiness";import { apiUrl } from "@/lib/api-base";+import { normalizeAccountUsername, transitionBrowserAccount } from "@/lib/account-transition";+import { sessionAccount, useLoginMode } from "../account-session";+import { fetchAuthStatus, loginFromForm, loginWithPassword, setLoginMode, type TokenResponse } from "../login-client";import { Button } from "@/components/ui/button";import { MascotImg } from "@/components/mascot-img";import { Input } from "@/components/ui/input";@@ -40,41 +43,6 @@ import {type AuthMode = "login" | "change-password";-type AuthStatusResponse = {- initialized: boolean;- requires_password_change: boolean;- bootstrap_deadline_seconds?: number | null;-};--type TokenResponse = {- access_token: string;- refresh_token: string;- must_change_password: boolean;-};--async function loginWithPassword(- username: string,- password: string,-): Promise<TokenResponse> {- const response = await fetch(apiUrl("/api/auth/login"), {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- username: username.trim(),- password,- }),- });-- if (!response.ok) {- const errorPayload = (await response.json().catch(() => null)) as { detail?: string } | null;- throw new Error(errorPayload?.detail ?? "Login failed.");- }-- return (await response.json()) as TokenResponse;-}-type AuthFormProps = {mode: AuthMode;};@@ -87,7 +55,9 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {const isLoginMode = mode === "login";const [showPassword, setShowPassword] = useState(false);const [showNewPassword, setShowNewPassword] = useState(false);- const username = HIDDEN_LOGIN_USERNAME;+ const loginMode = useLoginMode();+ const [enteredUsername, setEnteredUsername] = useState("");+ const username = loginMode === "multi" ? enteredUsername : HIDDEN_LOGIN_USERNAME;const [password, setPassword] = useState("");const [newPassword, setNewPassword] = useState("");const [confirmPassword, setConfirmPassword] = useState("");@@ -99,6 +69,12 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {const [deadlineAt, setDeadlineAt] = useState<number | null>(null);const [nowMs, setNowMs] = useState<number>(() => Date.now());const reloadReadySent = useRef(false);+ // Keep the issued session so retrying a blocked cleanup does not consume the one-use setup code twice.+ const pendingLogin = useRef<{+ username: string;+ password: string;+ token: TokenResponse;+ } | null>(null);useEffect(() => {if (deadlineAt === null) {@@ -115,12 +91,13 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {// Always check the server first; localStorage flags can be stale (e.g. tokens from a previous// install). /api/auth/status is the source of truth for requires_password_change.try {- const response = await fetch(apiUrl("/api/auth/status"));- if (!response.ok) throw new Error("Failed to load auth status.");- const result = (await response.json()) as AuthStatusResponse;+ const result = await fetchAuthStatus();+ const requiresChange = result.login_mode === "multi"+ ? hasAuthToken() && mustChangePassword()+ : result.requires_password_change;if (!canceled) {setInitialized(result.initialized);- setRequiresPasswordChange(result.requires_password_change);+ setRequiresPasswordChange(requiresChange);// One clock sample for both: nowMs is otherwise still the mount time// until the first tick, which adds the request duration to the figure// and renders a 0 from the server as "shuts down in 0 seconds".@@ -131,22 +108,22 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {);// Server truth wins; keep localStorage in sync both ways.- if (result.requires_password_change !== mustChangePassword()) {- setMustChangePassword(result.requires_password_change);+ if (requiresChange !== mustChangePassword()) {+ setMustChangePassword(requiresChange);}// Redirect between login / change-password per server state- if (mode === "login" && result.requires_password_change) {+ if (mode === "login" && requiresChange) {navigate({ to: "/change-password" });return;}- if (mode === "change-password" && !result.requires_password_change) {+ if (mode === "change-password" && !requiresChange) {navigate({ to: "/login" });return;}// On login, skip to the app if a valid session exists and no password change is required.- if (isLoginMode && !result.requires_password_change) {+ if (isLoginMode && !requiresChange) {if (hasRefreshToken()) {const refreshed = await refreshSession();if (refreshed) {@@ -222,6 +199,8 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {// reuse that password; the Current password input is only rendered for the// admin-forced must_change_password path where no bootstrap is available.const hasBootstrapPassword = Boolean(window.__UNSLOTH_BOOTSTRAP__?.password);+ const changingFromSetupCode =+ !isLoginMode && sessionAccount(getAuthToken())?.isOwner === false;const invalidChangePasswordForm =!isLoginMode &&(currentPassword.length < 8 ||@@ -273,7 +252,17 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {let token: TokenResponse;if (isLoginMode) {- token = await loginWithPassword(username, password);+ const normalizedUsername = normalizeAccountUsername(username);+ const pending = pendingLogin.current;+ const result = pending?.username === normalizedUsername && pending.password === password+ ? pending.token+ : await loginFromForm(loginMode, username, password);+ if (!result) {+ setPassword("");+ return;+ }+ pendingLogin.current = { username: normalizedUsername, password, token: result };+ token = result;} else {let accessToken = getAuthToken();@@ -288,11 +277,15 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {if (!accessToken) {const bootstrapToken = await loginWithPassword(username, currentPassword);- storeAuthTokens(- bootstrapToken.access_token,- bootstrapToken.refresh_token,+ const replaced = await transitionBrowserAccount(+ { username, accountId: bootstrapToken.account_id },+ "/change-password",+ () => {+ storeAuthTokens(bootstrapToken.access_token, bootstrapToken.refresh_token);+ setMustChangePassword(bootstrapToken.must_change_password);+ },);- setMustChangePassword(bootstrapToken.must_change_password);+ if (replaced) return;accessToken = bootstrapToken.access_token;}@@ -320,13 +313,22 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {token = (await response.json()) as TokenResponse;}- if (!isLoginMode) {- setRequiresPasswordChange(false);- setMustChangePassword(false);- } else {- setMustChangePassword(token.must_change_password);- }- storeAuthTokens(token.access_token, token.refresh_token);+ const finishSession = () => {+ setLoginMode(loginMode);+ if (!isLoginMode) setRequiresPasswordChange(false);+ setMustChangePassword(isLoginMode && token.must_change_password);+ storeAuthTokens(token.access_token, token.refresh_token);+ };+ // The transition keys on the immutable account id: a recreated username must not inherit the old browser data.+ const signedInUsername = sessionAccount(token.access_token)?.username ?? username;+ const route = isLoginMode && token.must_change_password ? "/change-password" : "/chat";+ const replaced = await transitionBrowserAccount(+ { username: signedInUsername, accountId: token.account_id },+ route,+ finishSession,+ );+ pendingLogin.current = null;+ if (replaced) return;navigate({ to: getPostAuthRoute() });} catch (err: unknown) {// The backend returns the correct PATH-based command ("unsloth studio@@ -373,12 +375,31 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {</p>)}<form className="space-y-5" onSubmit={handleSubmit}>+ {isLoginMode && loginMode === "multi" && (+ <div className="space-y-2">+ <Label htmlFor="username">Username</Label>+ <Input+ id="username"+ name="username"+ autoComplete="username"+ autoCapitalize="none"+ spellCheck={false}+ value={enteredUsername}+ onChange={(event) => setEnteredUsername(event.target.value)}+ required+ />+ <p id="setup-code-hint" className="text-sm text-muted-foreground">+ First sign in? Paste the setup code your administrator gave you as the password.+ </p>+ </div>+ )}{isLoginMode && (<div className="space-y-2"><Label htmlFor="password">Password</Label><div className="relative"><Inputid="password"+ aria-describedby={loginMode === "multi" ? "setup-code-hint" : undefined}type={showPassword ? "text" : "password"}className="pr-10"autoComplete="current-password"@@ -412,6 +433,9 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {<div className="relative"><Inputid="current-password"+ aria-describedby={+ changingFromSetupCode ? "current-setup-code-hint" : undefined+ }type={showPassword ? "text" : "password"}className="pr-10"autoComplete="current-password"@@ -434,6 +458,14 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {)}</Button></div>+ {changingFromSetupCode && (+ <p+ id="current-setup-code-hint"+ className="text-sm text-muted-foreground"+ >+ Paste the setup code you just signed in with as the current password.+ </p>+ )}</div>)}<div className="space-y-2">@@ -509,7 +541,7 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {loading ||statusLoading ||blockedByState ||- (isLoginMode && password.length < 8) ||+ (isLoginMode && (password.length < 8 || (loginMode === "multi" && !username.trim()))) ||invalidChangePasswordForm}>diff --git a/studio/frontend/src/features/auth/index.ts b/studio/frontend/src/features/auth/index.tsindex 0c566cc715a..c5bcf16fe47 100644--- a/studio/frontend/src/features/auth/index.ts+++ b/studio/frontend/src/features/auth/index.ts@@ -24,3 +24,4 @@ export {getTauriAuthFailure,tauriAutoAuth,} from "./tauri-auto-auth";+export { sessionAccount, useIsAccountOwner, useLoginMode } from "./account-session";diff --git a/studio/frontend/src/features/auth/login-client.ts b/studio/frontend/src/features/auth/login-client.tsnew file mode 100644index 00000000000..c58729de59b--- /dev/null+++ b/studio/frontend/src/features/auth/login-client.ts@@ -0,0 +1,158 @@+// 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 { apiUrl } from "@/lib/api-base";+import {+ normalizeAccountUsername,+ resetFullAccessForMultiUser,+} from "@/lib/account-transition";++export type LoginMode = "single" | "multi";+export type AuthStatusResponse = {+ initialized: boolean;+ requires_password_change: boolean;+ bootstrap_deadline_seconds?: number | null;+ login_mode?: LoginMode;+ full_access?: boolean;+};+export type TokenResponse = {+ access_token: string;+ refresh_token: string;+ must_change_password: boolean;+ account_id?: string | null;+};++export const LOGIN_MODE_HINT_KEY = "unsloth.auth-login-mode.v1";+function authHint(): string | null {+ try {+ return typeof window !== "undefined"+ ? window.localStorage.getItem(LOGIN_MODE_HINT_KEY)+ : null;+ } catch {+ return null;+ }+}+function initialLoginMode(): LoginMode {+ return authHint() === "multi" ? "multi" : "single";+}+let loginMode: LoginMode = initialLoginMode();+let statusKnown = false;+let inflight: Promise<AuthStatusResponse> | null = null;+const listeners = new Set<() => void>();+export const getLoginMode = (): LoginMode => loginMode;+export const subscribeLoginMode = (listener: () => void): (() => void) => {+ if (listeners.size === 0 && typeof window !== "undefined") {+ window.addEventListener("storage", onLoginModeStorage);+ }+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0 && typeof window !== "undefined") {+ window.removeEventListener("storage", onLoginModeStorage);+ }+ };+};+function onLoginModeStorage(event: StorageEvent): void {+ // A removed hint can be account cleanup, so relaxing policy waits for a fresh server status.+ if (+ event.key !== LOGIN_MODE_HINT_KEY ||+ (event.storageArea && event.storageArea !== window.localStorage)+ )+ return;+ if (event.newValue === "multi") setLoginMode("multi");+ else if (event.newValue === "restricted") setLoginMode(loginMode, false);+}+let fullAccessAllowed: boolean = authHint() === null;+export const getFullAccessAllowed = (): boolean => fullAccessAllowed;+export function setLoginMode(mode: LoginMode, fullAccess?: boolean): void {+ statusKnown = true;+ const allowed = fullAccess ?? (mode === "multi" ? false : fullAccessAllowed);+ if (typeof window !== "undefined") {+ if (mode === "multi" || !allowed) {+ resetFullAccessForMultiUser(window.localStorage);+ }+ const hint = mode === "multi" ? "multi" : allowed ? null : "restricted";+ const stored = window.localStorage.getItem(LOGIN_MODE_HINT_KEY);+ if (hint === null) {+ if (stored !== null) window.localStorage.removeItem(LOGIN_MODE_HINT_KEY);+ } else if (stored !== hint) {+ window.localStorage.setItem(LOGIN_MODE_HINT_KEY, hint);+ }+ }+ const changed = loginMode !== mode || fullAccessAllowed !== allowed;+ loginMode = mode;+ fullAccessAllowed = allowed;+ if (changed) listeners.forEach((listener) => listener());+}+export async function fetchAuthStatus(): Promise<AuthStatusResponse> {+ if (inflight) return inflight;+ inflight = (async () => {+ const response = await fetch(apiUrl("/api/auth/status"));+ if (!response.ok) throw new Error("Failed to load auth status.");+ const result = (await response.json()) as AuthStatusResponse;+ setLoginMode(result.login_mode ?? "single", result.full_access);+ return result;+ })();+ try {+ return await inflight;+ } finally {+ inflight = null;+ }+}+export function ensureLoginMode(): void {+ if (!statusKnown && (loginMode === "multi" || !fullAccessAllowed))+ void fetchAuthStatus().catch(() => undefined);+}++export class LoginError extends Error {+ status: number;+ constructor(message: string, status: number) {+ super(message);+ this.status = status;+ }+}++export async function loginWithPassword(+ username: string,+ password: string,+): Promise<TokenResponse> {+ const response = await fetch(apiUrl("/api/auth/login"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ username: normalizeAccountUsername(username),+ password,+ }),+ });+ if (!response.ok) {+ const payload = (await response.json().catch(() => null)) as {+ detail?: string;+ } | null;+ throw new LoginError(payload?.detail ?? "Login failed.", response.status);+ }+ return response.json();+}++/** Only a rejected single-mode submit probes for an account created since page load. */+export async function loginFromForm(+ mode: LoginMode,+ username: string,+ password: string,+): Promise<TokenResponse | null> {+ try {+ return await loginWithPassword(+ mode === "single" ? "unsloth" : username,+ password,+ );+ } catch (error) {+ if (+ mode === "single" &&+ error instanceof LoginError &&+ error.status === 401+ ) {+ const status = await fetchAuthStatus().catch(() => null);+ if (status?.login_mode === "multi") return null;+ }+ throw error;+ }+}diff --git a/studio/frontend/src/features/auth/session.ts b/studio/frontend/src/features/auth/session.tsindex 0f820ff2994..34c96c61a5e 100644--- a/studio/frontend/src/features/auth/session.ts+++ b/studio/frontend/src/features/auth/session.ts@@ -2,6 +2,8 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { isTauri } from "@/lib/api-base";+import { installAccountTransitionListener } from "@/lib/account-transition";+import { getLoginMode } from "./login-client";import {AUTH_SESSION_CLEARED_EVENT,@@ -22,6 +24,10 @@ export const AUTH_MUST_CHANGE_PASSWORD_KEY = "unsloth_auth_must_change_password"export const AUTH_SESSION_MARK_KEY = "unsloth_auth_session_mark";+if (typeof window !== "undefined" && typeof window.addEventListener === "function") {+ installAccountTransitionListener();+}+let authSessionEpoch = 0;/** Stable across access-token refreshes; changes when an auth session starts or clears. */@@ -115,7 +121,7 @@ export function setMustChangePassword(required: boolean): void {export function getPostAuthRoute(): PostAuthRoute {- if (isTauri) return "/chat";+ if (isTauri && getLoginMode() === "single") return "/chat";if (mustChangePassword()) return "/change-password";return "/chat";}diff --git a/studio/frontend/src/features/auth/tauri-auto-auth.ts b/studio/frontend/src/features/auth/tauri-auto-auth.tsindex e825d5de317..da0518c81cf 100644--- a/studio/frontend/src/features/auth/tauri-auto-auth.ts+++ b/studio/frontend/src/features/auth/tauri-auto-auth.ts@@ -3,6 +3,7 @@import { isTauri } from "@/lib/api-base";import {+ clearAuthTokens,hasAuthToken,hasRefreshToken,mustChangePassword,@@ -10,11 +11,15 @@ import {storeAuthTokens,} from "./session";import { refreshSession } from "./api";+import { setLoginMode } from "./login-client";+import {+ OWNER_BROWSER_ACCOUNT,+ transitionBrowserAccount,+} from "@/lib/account-transition";-type DesktopAuthResponse = {- access_token: string;- refresh_token: string;-};+type DesktopAuthResponse =+ | { access_token: string; refresh_token: string }+ | { login_required: true; login_mode: "multi" };type TauriAutoAuthOptions = {force?: boolean;@@ -24,6 +29,11 @@ type TauriAutoAuthOptions = {// without this the first-launch password-change could race with itself.let pending: { promise: Promise<boolean>; force: boolean } | null = null;let lastTauriAuthFailure: string | null = null;+let tauriLoginRequired = false;++export function isTauriLoginRequired(): boolean {+ return tauriLoginRequired;+}const TAURI_AUTH_FAILURE_FALLBACK ="Desktop authentication failed. Update or repair the managed Unsloth install, then restart Unsloth.";@@ -73,8 +83,31 @@ async function doTauriAutoAuth(options: TauriAutoAuthOptions): Promise<boolean>try {const { invoke } = await import("@tauri-apps/api/core");const tokens = await invoke<DesktopAuthResponse>("desktop_auth");- storeAuthTokens(tokens.access_token, tokens.refresh_token);- setMustChangePassword(false);+ if ("login_required" in tokens) {+ tauriLoginRequired = true;+ // A managed account signs in in the document; do not discard the session it holds.+ if (hasRefreshToken() && (await refreshSession()) && hasAuthToken()) {+ clearTauriAuthFailure();+ if (mustChangePassword()) {+ const { router } = await import("@/app/router");+ await router.navigate({ to: "/change-password", replace: true });+ }+ return true;+ }+ clearAuthTokens();+ clearTauriAuthFailure();+ // The forced startup probe must release the startup screen so the login form can mount; ordinary API recovery still returns false.+ const { router } = await import("@/app/router");+ await router.navigate({ to: "/login", replace: true });+ return options.force === true;+ }+ tauriLoginRequired = false;+ // Owner tokens after the last managed account is deleted must not inherit its browser data.+ await transitionBrowserAccount(OWNER_BROWSER_ACCOUNT, "/chat", () => {+ storeAuthTokens(tokens.access_token, tokens.refresh_token);+ setMustChangePassword(false);+ setLoginMode("single");+ });clearTauriAuthFailure();return true;} catch (error) {@@ -84,14 +117,7 @@ async function doTauriAutoAuth(options: TauriAutoAuthOptions): Promise<boolean>}}-/**- * Silently authenticate in Tauri desktop mode.- *- * Delegates bootstrap/password handling to Rust and only stores returned tokens.- *- * Returns true if authentication succeeded.- * Concurrent calls are coalesced into a single in-flight attempt.- */+/** Silently authenticate in Tauri desktop mode; also true when only a forced startup probe verified the shell. */export function tauriAutoAuth(options: TauriAutoAuthOptions = {},): Promise<boolean> {@@ -104,5 +130,11 @@ export function tauriAutoAuth(});pending = { promise, force };}+ if (!force && pending.force) {+ // An API retry may share the forced probe, but shell readiness alone must not authorize it.+ return pending.promise.then(+ (ready) => ready && (!tauriLoginRequired || hasAuthToken()),+ );+ }return pending.promise;}diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.tsindex e2d0691df78..f4f08d4331f 100644--- a/studio/frontend/src/features/chat/api/providers-api.ts+++ b/studio/frontend/src/features/chat/api/providers-api.ts@@ -125,7 +125,6 @@ async function importProviderPublicKey(}const ENVELOPE_VERSION = "v1";-/** Pins an envelope to this protocol and version; the backend checks the same bytes. */const ENVELOPE_AAD = "unsloth-studio-provider-key-v1";const AES_KEY_BYTES = 32;const NONCE_BYTES = 12;@@ -136,10 +135,7 @@ function randomBinaryString(byteLength: number): string {return String.fromCharCode(...bytes);}-/**- * Produce `v1.<wrapped AES key>.<nonce>.<ciphertext||tag>`, each part base64. RSA-OAEP wraps- * only the 32-byte content key: encrypting the API key itself would cap it at 190 bytes.- */+/** RSA-OAEP wraps only the 32-byte content key: wrapping the API key itself caps it at 190 bytes. */export async function encryptProviderApiKey(plaintextApiKey: string,forceRefresh = false,@@ -150,8 +146,7 @@ export async function encryptProviderApiKey(const cipher = forge.cipher.createCipher("AES-GCM", aesKey);cipher.start({ iv: nonce, additionalData: ENVELOPE_AAD, tagLength: 128 });- // forge ciphers take bytes, so a non-ASCII key would otherwise lose all but the low byte- // of each UTF-16 code unit.+ // forge ciphers take bytes: without encodeUtf8 a non-ASCII key loses all but each low byte.cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(plaintextApiKey)));if (!cipher.finish()) {throw new Error("Failed to encrypt API key.");diff --git a/studio/frontend/src/features/chat/permission-mode-select.tsx b/studio/frontend/src/features/chat/permission-mode-select.tsxindex bdcb262dbe1..353f512dfaf 100644--- a/studio/frontend/src/features/chat/permission-mode-select.tsx+++ b/studio/frontend/src/features/chat/permission-mode-select.tsx@@ -3,7 +3,8 @@import { ChevronDown, CircleAlert, Hand, ShieldCheck } from "lucide-react";import type { ComponentType } from "react";-import { useState } from "react";+import { useEffect, useState } from "react";+import { useFullAccessAllowed } from "@/features/auth/account-session";import {AlertDialog,@@ -84,17 +85,30 @@ export function permissionModeOption(mode: PermissionMode) {/** The option rows shared by every permission dropdown or submenu. Non-full levels apply* directly; picking Full access must go through the caller's danger confirmation. */+function useAccountPermissionMode() {+ const fullAccessAllowed = useFullAccessAllowed();+ const permissionMode = useChatRuntimeStore((s) => s.permissionMode);+ const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);+ useEffect(() => {+ if (!fullAccessAllowed && permissionMode === "full") setPermissionMode("auto");+ }, [fullAccessAllowed, permissionMode, setPermissionMode]);+ return {+ permissionMode: !fullAccessAllowed && permissionMode === "full" ? "auto" : permissionMode,+ fullAccessAllowed,+ };+}+export function PermissionModeMenuItems({onRequestFullAccess,}: {onRequestFullAccess: () => void;}) {- const permissionMode = useChatRuntimeStore((s) => s.permissionMode);+ const { permissionMode, fullAccessAllowed } = useAccountPermissionMode();const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);return (<>- {PERMISSION_MODE_OPTIONS.map((option) => (+ {PERMISSION_MODE_OPTIONS.filter((option) => fullAccessAllowed || option.value !== "full").map((option) => (<DropdownMenuItemkey={option.value}onSelect={() => {@@ -145,6 +159,8 @@ export function FullAccessConfirmDialog({onOpenChange: (open: boolean) => void;}) {const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);+ const { fullAccessAllowed } = useAccountPermissionMode();+ if (!fullAccessAllowed) return null;return (<AlertDialog open={open} onOpenChange={onOpenChange}>@@ -184,7 +200,7 @@ export function PermissionModeDropdown({align?: "start" | "end";triggerClassName?: string;} = {}) {- const permissionMode = useChatRuntimeStore((s) => s.permissionMode);+ const { permissionMode, fullAccessAllowed } = useAccountPermissionMode();const [confirmOpen, setConfirmOpen] = useState(false);const active = permissionModeOption(permissionMode);const ActiveIcon = active.icon;@@ -247,7 +263,7 @@ export function PermissionModeComposerPill({}: {side?: "top" | "bottom";} = {}) {- const permissionMode = useChatRuntimeStore((s) => s.permissionMode);+ const { permissionMode, fullAccessAllowed } = useAccountPermissionMode();const setBypassConfirmOpen = useChatRuntimeStore((s) => s.setBypassConfirmOpen,);diff --git a/studio/frontend/src/features/data-recipes/data/recipes-db.ts b/studio/frontend/src/features/data-recipes/data/recipes-db.tsindex 3ffe09c2d2b..3709fbaf194 100644--- a/studio/frontend/src/features/data-recipes/data/recipes-db.ts+++ b/studio/frontend/src/features/data-recipes/data/recipes-db.ts@@ -2,12 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { createEmptyRecipePayload } from "@/features/recipe-studio";+import { accountDatabaseName } from "@/lib/account-transition";import { normalizeNonEmptyName } from "@/utils";import Dexie, { type EntityTable, liveQuery } from "dexie";import { useEffect, useState } from "react";import type { RecipeRecord, SaveRecipeInput } from "../types";-const db = new Dexie("unsloth-data-recipes") as Dexie & {+const db = new Dexie(accountDatabaseName("unsloth-data-recipes")) as Dexie & {recipes: EntityTable<RecipeRecord, "id">;};diff --git a/studio/frontend/src/features/recipe-studio/data/executions-db.ts b/studio/frontend/src/features/recipe-studio/data/executions-db.tsindex 6af436ded56..137c1122b9d 100644--- a/studio/frontend/src/features/recipe-studio/data/executions-db.ts+++ b/studio/frontend/src/features/recipe-studio/data/executions-db.ts@@ -1,10 +1,13 @@// 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 { accountDatabaseName } from "@/lib/account-transition";import Dexie, { type EntityTable } from "dexie";import type { RecipeExecutionRecord } from "../execution-types";-const db = new Dexie("unsloth-data-recipe-executions") as Dexie & {+const db = new Dexie(+ accountDatabaseName("unsloth-data-recipe-executions"),+) as Dexie & {executions: EntityTable<RecipeExecutionRecord, "id">;};@@ -19,7 +22,10 @@ db.version(2).stores({export async function listRecipeExecutions(recipeId: string,): Promise<RecipeExecutionRecord[]> {- const executions = await db.executions.where("recipeId").equals(recipeId).toArray();+ const executions = await db.executions+ .where("recipeId")+ .equals(recipeId)+ .toArray();return executions.sort((a, b) => b.createdAt - a.createdAt);}diff --git a/studio/frontend/src/features/settings/api/accounts.ts b/studio/frontend/src/features/settings/api/accounts.tsnew file mode 100644index 00000000000..1a18b8394d1--- /dev/null+++ b/studio/frontend/src/features/settings/api/accounts.ts@@ -0,0 +1,91 @@+// 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 { readFastApiError } from "@/lib/format-fastapi-error";+import { authFetch } from "@/features/auth";+import { fetchAuthStatus } from "@/features/auth/login-client";+import { normalizeAccountUsername } from "@/lib/account-transition";++export interface StudioAccount {+ account_id: string;+ username: string;+ role: "owner" | "user";+ is_active: boolean;+ created_at: string;+}+export interface AccountSetupCode {+ account_id: string;+ username: string;+ setup_code: string;+ expires_at: string;+}+interface AccountSetupResponse {+ account: StudioAccount;+ setup_code: string;+ setup_code_expires_at: string;+}+function toSetupCode(payload: AccountSetupResponse): AccountSetupCode {+ return {+ account_id: payload.account.account_id,+ username: payload.account.username,+ setup_code: payload.setup_code,+ expires_at: payload.setup_code_expires_at,+ };+}++async function accountsRequest(+ path = "",+ init?: RequestInit,+): Promise<Response> {+ const response = await authFetch(`/api/accounts${path}`, init);+ if (!response.ok) {+ throw new Error(await readFastApiError(response, "Account request failed"));+ }+ return response;+}+const accountPath = (accountId: string) => `/${encodeURIComponent(accountId)}`;+// Recheck installation policy after mutations; a failed status read must not lose a one-time code.+async function refreshAccountPolicy(): Promise<void> {+ await fetchAuthStatus().catch(() => undefined);+}+export async function fetchAccounts(): Promise<StudioAccount[]> {+ const response = await accountsRequest();+ const data = (await response.json()) as { accounts: StudioAccount[] };+ return data.accounts;+}+export async function createAccount(+ username: string,+): Promise<AccountSetupCode> {+ const response = await accountsRequest("", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ username: normalizeAccountUsername(username) }),+ });+ const result = toSetupCode((await response.json()) as AccountSetupResponse);+ await refreshAccountPolicy();+ return result;+}+export async function regenerateSetupCode(+ accountId: string,+): Promise<AccountSetupCode> {+ const response = await accountsRequest(+ `${accountPath(accountId)}/setup-code`,+ { method: "POST" },+ );+ return toSetupCode((await response.json()) as AccountSetupResponse);+}+export async function setAccountActive(+ accountId: string,+ active: boolean,+): Promise<void> {+ await accountsRequest(accountPath(accountId), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ is_active: active }),+ });+ await refreshAccountPolicy();+}+export async function deleteAccount(accountId: string): Promise<void> {+ await accountsRequest(accountPath(accountId), { method: "DELETE" });+ await refreshAccountPolicy();+}diff --git a/studio/frontend/src/features/settings/components/remote-access-section.tsx b/studio/frontend/src/features/settings/components/remote-access-section.tsxindex 6cf82b11cb9..360e6cfe8df 100644--- a/studio/frontend/src/features/settings/components/remote-access-section.tsx+++ b/studio/frontend/src/features/settings/components/remote-access-section.tsx@@ -1,6 +1,7 @@// 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 { useLoginMode } from "@/features/auth/account-session";import { Button } from "@/components/ui/button";import {Dialog,@@ -194,8 +195,7 @@ function RemoteUrlPanel({ url }: { url: string | null }) {);}-// Desktop signs in with a local secret, so the account password exists only for-// remote browsers and is managed here rather than in the General tab.+// The desktop owner signs in with a local secret, so this password is for remote browsers only.function RemotePasswordRow({status,onDone,@@ -203,13 +203,18 @@ function RemotePasswordRow({status: RemoteAccessStatus | null;onDone: () => void;}) {+ const multi = useLoginMode() === "multi";if (!(isTauri && status)) {return null;}return (<SettingsRowlabel="Remote password"- description="Remote browsers sign in as unsloth. The Unsloth Desktop App keeps signing in automatically."+ description={+ multi+ ? "This changes the installation owner's password. Every other account signs in with its own."+ : "Remote browsers sign in as unsloth. The Unsloth Desktop App keeps signing in automatically."+ }><ChangePasswordDialog initial={status.passwordPending} onDone={onDone} /></SettingsRow>diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsxindex 3bf2f717e0d..474a6e97446 100644--- a/studio/frontend/src/features/settings/settings-dialog.tsx+++ b/studio/frontend/src/features/settings/settings-dialog.tsx@@ -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 { useIsAccountOwner } from "@/features/auth";+import { resolveSettingsTab, settingsTabVisible } from "./settings-tab-visibility";import { getClientPlatform } from "@/components/tauri/window-titlebar";import { Button } from "@/components/ui/button";import {@@ -57,6 +59,8 @@ import {// Statically imported, every panel ran before first paint even though the dialog// starts closed. Load each on first view instead; this map also drives the prefetch.const TAB_LOADERS = {+ accounts: () =>+ import("./tabs/accounts-tab").then((m) => ({ default: m.AccountsTab })),general: () =>import("./tabs/general-tab").then((m) => ({ default: m.GeneralTab })),profile: () =>@@ -171,6 +175,7 @@ interface TabDef {}const TABS: TabDef[] = [+ { id: "accounts", labelKey: "settings.tabs.accounts", icon: UserIcon },{ id: "general", labelKey: "settings.tabs.general", icon: Settings02Icon },{id: "profile",@@ -254,8 +259,11 @@ function renderTab(tab: SettingsTab) {export function SettingsDialog() {const t = useT();+ const isOwner = useIsAccountOwner();+ const visibleTabs = useMemo(() => TABS.filter((tab) => settingsTabVisible(tab.id, isOwner)), [isOwner]);const open = useSettingsDialogStore((s) => s.open);- const activeTab = useSettingsDialogStore((s) => s.activeTab);+ const requestedTab = useSettingsDialogStore((s) => s.activeTab);+ const activeTab = resolveSettingsTab(requestedTab, isOwner);const setActiveTab = useSettingsDialogStore((s) => s.setActiveTab);const closeDialog = useSettingsDialogStore((s) => s.closeDialog);const opener = useSettingsDialogStore((s) => s.opener);@@ -263,7 +271,8 @@ export function SettingsDialog() {const reduced = useReducedMotion();// Mounting a heavy tab panel (System, Connections) in the same commit as the nav highlight makes// the highlight lag the click. Render the panel from a deferred value so the nav updates first.- const panelTab = useDeferredValue(activeTab);+ const deferredTab = useDeferredValue(activeTab);+ const panelTab = resolveSettingsTab(deferredTab, isOwner);const [query, setQuery] = useState("");// Once opened, pull the other panels in on idle so a tab click never waits on the@@ -286,7 +295,7 @@ export function SettingsDialog() {if (!q) {return null;}- return TABS.map((tab) => {+ return visibleTabs.map((tab) => {const tabLabel = t(tab.labelKey);const entries = SETTINGS_SEARCH_INDEX[tab.id].filter((key) => {@@ -305,7 +314,7 @@ export function SettingsDialog() {tabMatches: tabLabel.toLowerCase().includes(q),};}).filter((r) => r.tabMatches || r.entries.length > 0);- }, [query, t]);+ }, [query, t, visibleTabs]);const [pendingScroll, setPendingScroll] = useState<{tab: SettingsTab;@@ -380,6 +389,7 @@ export function SettingsDialog() {return () => window.cancelAnimationFrame(frame);}, [open]);const tabButtonRefs = useRef<Record<SettingsTab, HTMLButtonElement | null>>({+ accounts: null,general: null,profile: null,appearance: null,@@ -541,7 +551,7 @@ export function SettingsDialog() {results !== null && "max-sm:flex hidden",)}>- {TABS.map((tab) => {+ {visibleTabs.map((tab) => {const active = activeTab === tab.id;return (<buttondiff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 411c13d63d6..f4a70c43e64 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -10,6 +10,7 @@ import type { SettingsTab } from "./stores/settings-dialog-store";* (profile, connections) are still reachable from search.*/export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {+ accounts: ["settings.accounts.title", "settings.accounts.create"],general: ["settings.general.account","settings.general.password",diff --git a/studio/frontend/src/features/settings/settings-tab-visibility.ts b/studio/frontend/src/features/settings/settings-tab-visibility.tsnew file mode 100644index 00000000000..ce70062ea5b--- /dev/null+++ b/studio/frontend/src/features/settings/settings-tab-visibility.ts@@ -0,0 +1,23 @@+// 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 { SettingsTab } from "./stores/settings-dialog-store";++// Tabs whose every backing route is owner-only (installation-wide settings), so a managed account+// would only see controls that fail with 403.+export const OWNER_ONLY_SETTINGS_TABS: ReadonlySet<SettingsTab> = new Set<SettingsTab>([+ "accounts",+ "resources",+ "remote-lan",+ "agents",+ "debugging",+]);++export function settingsTabVisible(tab: SettingsTab, isOwner: boolean): boolean {+ return isOwner || !OWNER_ONLY_SETTINGS_TABS.has(tab);+}++// A deep link or a stale stored tab that the account cannot open lands on General.+export function resolveSettingsTab(requested: SettingsTab, isOwner: boolean): SettingsTab {+ return settingsTabVisible(requested, isOwner) ? requested : "general";+}diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.tsindex 62f098524b0..250e29aff4e 100644--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts@@ -10,6 +10,7 @@ import { create } from "zustand";export const SETTINGS_TABS = ["general","profile",+ "accounts","appearance","resources","chat",diff --git a/studio/frontend/src/features/settings/tabs/accounts-tab.tsx b/studio/frontend/src/features/settings/tabs/accounts-tab.tsxnew file mode 100644index 00000000000..a0da99134a9--- /dev/null+++ b/studio/frontend/src/features/settings/tabs/accounts-tab.tsx@@ -0,0 +1,322 @@+// 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 { useEffect, useState, type SyntheticEvent } from "react";+import { useIsAccountOwner } from "@/features/auth";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { useT } from "@/i18n";+import {+ createAccount,+ deleteAccount,+ fetchAccounts,+ regenerateSetupCode,+ setAccountActive,+ type AccountSetupCode,+ type StudioAccount,+} from "../api/accounts";++export function AccountsTab() {+ const owner = useIsAccountOwner();+ // No requests or managed-account content even if a persisted tab directly names Accounts.+ return owner ? <OwnerAccountsTab /> : null;+}++function OwnerAccountsTab() {+ const t = useT();+ const [accounts, setAccounts] = useState<StudioAccount[]>([]);+ const [username, setUsername] = useState("");+ const [setup, setSetup] = useState<AccountSetupCode | null>(null);+ const [copied, setCopied] = useState(false);+ const [resetting, setResetting] = useState<StudioAccount | null>(null);+ const [retiring, setRetiring] = useState<StudioAccount | null>(null);+ const [busy, setBusy] = useState(false);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let canceled = false;+ void fetchAccounts()+ .then((result) => {+ if (!canceled) setAccounts(result);+ })+ .catch((reason: unknown) => {+ if (!canceled)+ setError(+ reason instanceof Error+ ? reason.message+ : t("settings.accounts.failed"),+ );+ })+ .finally(() => {+ if (!canceled) setLoading(false);+ });+ return () => {+ canceled = true;+ };+ }, [t]);++ async function perform(action: () => Promise<void>) {+ setError(null);+ setBusy(true);+ try {+ await action();+ setAccounts(await fetchAccounts());+ } catch (reason) {+ setError(+ reason instanceof Error+ ? reason.message+ : t("settings.accounts.failed"),+ );+ } finally {+ setBusy(false);+ }+ }++ function showSetup(result: AccountSetupCode) {+ setSetup(result);+ setCopied(false);+ }++ function create(event: SyntheticEvent<HTMLFormElement>) {+ event.preventDefault();+ if (busy || !username.trim()) return;+ void perform(async () => {+ showSetup(await createAccount(username));+ setUsername("");+ });+ }++ const confirming = resetting ?? retiring;++ return (+ <div className="space-y-6">+ <div>+ <h2+ className="text-lg font-semibold"+ data-settings-label={t("settings.accounts.title")}+ >+ {t("settings.accounts.title")}+ </h2>+ <p className="text-sm text-muted-foreground">+ {t("settings.accounts.description")}+ </p>+ </div>+ <form className="space-y-2" onSubmit={create}>+ <Label+ htmlFor="new-account-username"+ data-settings-label={t("settings.accounts.create")}+ >+ {t("settings.accounts.create")}+ </Label>+ <div className="flex gap-2">+ <Input+ id="new-account-username"+ aria-label={t("settings.accounts.username")}+ value={username}+ onChange={(event) => setUsername(event.target.value)}+ autoComplete="off"+ autoCapitalize="none"+ spellCheck={false}+ required+ />+ <Button type="submit" disabled={busy || !username.trim()}>+ {t("settings.accounts.create")}+ </Button>+ </div>+ </form>+ {setup && (+ <section+ className="space-y-3 rounded-xl border p-4"+ aria-label={t("settings.accounts.setupCode")}+ >+ <h3 className="font-medium">+ {t("settings.accounts.setupFor", { username: setup.username })}+ </h3>+ <p className="text-sm text-muted-foreground">+ {t("settings.accounts.shownOnce")}+ </p>+ <code+ className="block break-all select-all"+ data-testid="account-setup-code"+ >+ {setup.setup_code}+ </code>+ <p className="text-sm">+ {t("settings.accounts.expires", {+ expiry: new Date(setup.expires_at).toLocaleString(),+ })}+ </p>+ <div className="flex gap-2">+ <Button+ variant="outline"+ onClick={() => {+ void copyToClipboard(setup.setup_code).then((ok) => {+ setCopied(ok);+ if (!ok) setError(t("settings.accounts.copyFailed"));+ });+ }}+ >+ {copied+ ? t("settings.accounts.copied")+ : t("settings.accounts.copy")}+ </Button>+ <Button variant="ghost" onClick={() => setSetup(null)}>+ {t("settings.accounts.dismiss")}+ </Button>+ </div>+ </section>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}+ {loading ? (+ <p>{t("common.loading")}</p>+ ) : (+ <ul className="divide-y">+ {accounts.map((account) => (+ <li+ key={account.account_id}+ className="flex flex-wrap items-center gap-3 py-3"+ data-testid={`account-${account.username}`}+ >+ <div className="min-w-0 flex-1">+ <p className="break-all font-medium">{account.username}</p>+ <p className="text-sm text-muted-foreground">+ {account.role === "owner"+ ? t("settings.accounts.owner")+ : account.is_active+ ? t("settings.accounts.active")+ : t("settings.accounts.inactive")}+ </p>+ </div>+ {account.role !== "owner" && (+ <div className="flex flex-wrap gap-2">+ <Button+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={() => setResetting(account)}+ >+ {t("settings.accounts.regenerate")}+ </Button>+ <Button+ variant="outline"+ size="sm"+ disabled={busy}+ onClick={() =>+ void perform(async () => {+ await setAccountActive(+ account.account_id,+ !account.is_active,+ );+ if (setup?.account_id === account.account_id)+ setSetup(null);+ })+ }+ >+ {account.is_active+ ? t("settings.accounts.deactivate")+ : t("settings.accounts.reactivate")}+ </Button>+ <Button+ variant="destructive"+ size="sm"+ disabled={busy}+ onClick={() => setRetiring(account)}+ >+ {t("settings.accounts.delete")}+ </Button>+ </div>+ )}+ </li>+ ))}+ </ul>+ )}+ {error && (+ <Button+ variant="outline"+ disabled={busy}+ onClick={() => void perform(async () => {})}+ >+ {t("settings.accounts.retry")}+ </Button>+ )}+ <AlertDialog+ open={confirming !== null}+ onOpenChange={(open) => {+ if (open || busy) return;+ setRetiring(null);+ setResetting(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(+ resetting+ ? "settings.accounts.resetTitle"+ : "settings.accounts.deleteTitle",+ { username: confirming?.username ?? "" },+ )}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ resetting+ ? "settings.accounts.resetDescription"+ : "settings.accounts.deleteDescription",+ { username: confirming?.username ?? "" },+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={busy}>+ {t("settings.accounts.cancel")}+ </AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={busy}+ onClick={(event) => {+ event.preventDefault();+ if (busy) return;+ if (resetting) {+ void perform(async () => {+ showSetup(await regenerateSetupCode(resetting.account_id));+ setResetting(null);+ });+ return;+ }+ if (!retiring) return;+ void perform(async () => {+ await deleteAccount(retiring.account_id);+ if (setup?.account_id === retiring.account_id) setSetup(null);+ setRetiring(null);+ });+ }}+ >+ {t(+ resetting+ ? "settings.accounts.regenerate"+ : "settings.accounts.delete",+ )}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsxindex cb5f042fca7..a2ee4aad922 100644--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx@@ -1,6 +1,7 @@// 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 { useIsAccountOwner } from "@/features/auth";import { Button } from "@/components/ui/button";import {Dialog,@@ -30,6 +31,7 @@ import { UsageExamples } from "../components/usage-examples";export function ApiKeysTab() {const t = useT();+ const isOwner = useIsAccountOwner();const [keys, setKeys] = useState<ApiKey[]>([]);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);@@ -181,14 +183,19 @@ export function ApiKeysTab() {<MonitorLink />- <KeylessApiAccessSection onSettingsChange={setKeyless} />+ {/* Installation-wide controls: owner-only routes. */}+ {isOwner ? (+ <>+ <KeylessApiAccessSection onSettingsChange={setKeyless} />- {/* Also on the Remote & LAN tab. One panel mounts at a time, so only one polls. */}- <RemoteAccessSection />+ {/* Also on the Remote & LAN tab. One panel mounts at a time, so only one polls. */}+ <RemoteAccessSection />- <LanAccessSection />+ <LanAccessSection />- <ModelAutoSwitchSection />+ <ModelAutoSwitchSection />+ </>+ ) : null}<UsageExamplesapiKey={revealed}diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex ec1fe77fc68..a99536e33d9 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -1,6 +1,7 @@// 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 { useIsAccountOwner } from "@/features/auth";import { Button } from "@/components/ui/button";import {Dialog,@@ -100,6 +101,7 @@ const SUBPAGE_FOR_SHELF = {export function DataTab() {const t = useT();+ const isOwner = useIsAccountOwner();const navigate = useNavigate();const archivedRequested = useSettingsDialogStore((s) => s.archivedRequested);const consumeArchivedChatsRequest = useSettingsDialogStore(@@ -977,7 +979,8 @@ export function DataTab() {) : null}</SettingsSection>- <DocumentsRagSection />+ {/* Embedding model settings are installation-wide (owner-only routes). */}+ {isOwner ? <DocumentsRagSection /> : null}<Dialog open={archiveConfirmOpen} onOpenChange={setArchiveConfirmOpen}><DialogContent className="max-w-md">diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 217af8bbacd..f5aaf7b5008 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -58,6 +58,7 @@ import {} from "../api/upload-limit";import { loadCloseToTray, updateCloseToTray } from "../api/close-to-tray";import { loadLaunchAtLogin, updateLaunchAtLogin } from "../api/launch-at-login";+import { useIsAccountOwner } from "@/features/auth";import { ChangePasswordDialog } from "../components/change-password-dialog";import { DesktopRepairControl } from "../components/desktop-repair-control";import {@@ -175,6 +176,7 @@ function resetAllPrefs() {}export function GeneralTab() {+ const isOwner = useIsAccountOwner();const t = useT();const hfToken = useChatRuntimeStore((s) => s.hfToken);const setHfToken = useChatRuntimeStore((s) => s.setHfToken);@@ -262,6 +264,7 @@ export function GeneralTab() {const tokenValidated = tokenIsCurrent && tokenValidation.isValid === true;useEffect(() => {+ if (!isOwner) return;let cancelled = false;void loadUploadLimitSettings().then((settings) => {@@ -280,9 +283,10 @@ export function GeneralTab() {return () => {cancelled = true;};- }, []);+ }, [isOwner]);useEffect(() => {+ if (!isOwner) return;let cancelled = false;void loadHelperPrecacheSettings().then((settings) => {@@ -301,9 +305,10 @@ export function GeneralTab() {return () => {cancelled = true;};- }, [t]);+ }, [t, isOwner]);useEffect(() => {+ if (!isOwner) return;let cancelled = false;void loadPreviewSharing().then((settings) => {@@ -322,7 +327,7 @@ export function GeneralTab() {return () => {cancelled = true;};- }, [t]);+ }, [t, isOwner]);const saveHelperPrecache = async (enabled: boolean) => {@@ -504,10 +509,10 @@ export function GeneralTab() {) : null}</div></SettingsRow>- {/* The desktop app authenticates via desktop auto-auth with a generated- secret, so this password only governs remote browsers and is managed- in Remote access instead. Web only. */}- {isTauri ? null : (+ {/* The desktop owner authenticates via desktop auto-auth with a generated+ secret, so the owner password only governs remote browsers and is+ managed in Remote access instead. Managed accounts sign in here. */}+ {isTauri && isOwner ? null : (<SettingsRowlabel={t("settings.general.password")}description={t("settings.general.passwordDescription")}@@ -606,6 +611,9 @@ export function GeneralTab() {</SettingsRow></SettingsSection>+ {/* Installation-wide settings: owner-only routes, so a managed account gets no dead controls. */}+ {isOwner ? (+ <><SettingsSectiontitle={t("settings.general.previewSharing.sectionTitle")}>@@ -722,6 +730,8 @@ export function GeneralTab() {</div></SettingsRow></SettingsSection>+ </>+ ) : null}<SettingsSectiontitle={t("settings.general.resetPreferences.sectionTitle")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 73640d675e4..ad0638a32f4 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -182,6 +182,34 @@ export const ar = {},},settings: {+ accounts: {+ title: "الحسابات",+ description: "أنشئ حسابات Studio خاصة. يسجّل المستخدمون الجدد الدخول برمز إعداد يُستخدم مرة واحدة ثم يختارون كلمة مرور.",+ username: "اسم المستخدم",+ create: "إنشاء حساب",+ setupCode: "رمز الإعداد",+ setupFor: "رمز الإعداد لـ {username}",+ shownOnce: "انسخ هذا الرمز الآن وشاركه مع صاحب الحساب. يظهر هنا فقط ويمكن استخدامه مرة واحدة خلال 60 دقيقة.",+ expires: "ينتهي {expiry}",+ copy: "نسخ رمز الإعداد",+ copied: "تم النسخ",+ copyFailed: "تعذّر النسخ. حدّد رمز الإعداد أعلاه وانسخه.",+ dismiss: "تم",+ owner: "مالك التثبيت",+ active: "نشط",+ inactive: "غير نشط",+ regenerate: "إعادة إنشاء رمز الإعداد",+ resetTitle: "إعادة تعيين كلمة مرور {username}؟",+ resetDescription: "إعادة إنشاء رمز الإعداد تستبدل كلمة مرور {username} وتُنهي جلساته وتُلغي مفاتيح API الخاصة به. أعطه الرمز الجديد ليختار كلمة مرور من جديد.",+ deactivate: "تعطيل",+ reactivate: "إعادة التفعيل",+ delete: "حذف الحساب",+ deleteTitle: "حذف {username}؟",+ deleteDescription: "سيؤدي هذا إلى إلغاء جلسات {username} وإيقاف أعماله الجارية. تُسحب محادثاته وإعداداته وبيانات اعتماده وملفاته المرفوعة ومجموعات بياناته وعمليات التدريب والمخرجات والتصديرات والمعارض وبيئات العزل والمشاريع والملفات المؤقتة. يُعاد تسمية المجلدات وتُنحّى جانبًا ولا تُحذف أبدًا. إنشاء اسم المستخدم هذا مرة أخرى يبدأ حسابًا جديدًا دون أيٍّ من هذه البيانات.",+ cancel: "إلغاء",+ retry: "تحديث الحسابات",+ failed: "فشل طلب الحساب.",+ },title: "الإعدادات",dialog: {title: "الإعدادات",@@ -193,6 +221,7 @@ export const ar = {panelReload: "إعادة التحميل",},tabs: {+ accounts: "الحسابات",general: "عام",profile: "الملف الشخصي",appearance: "المظهر",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 1f10d06b50b..4d1e437a175 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -186,6 +186,34 @@ export const de = {},},settings: {+ accounts: {+ title: "Konten",+ description: "Private Studio-Konten anlegen. Neue Nutzer melden sich mit einem einmaligen Einrichtungscode an und wählen ein Passwort.",+ username: "Benutzername",+ create: "Konto anlegen",+ setupCode: "Einrichtungscode",+ setupFor: "Einrichtungscode für {username}",+ shownOnce: "Kopieren Sie diesen Code jetzt und geben Sie ihn an den Kontoinhaber weiter. Er wird nur hier angezeigt und kann innerhalb von 60 Minuten einmal verwendet werden.",+ expires: "Läuft ab: {expiry}",+ copy: "Einrichtungscode kopieren",+ copied: "Kopiert",+ copyFailed: "Kopieren nicht möglich. Markieren und kopieren Sie den Einrichtungscode oben.",+ dismiss: "Fertig",+ owner: "Installationsinhaber",+ active: "Aktiv",+ inactive: "Inaktiv",+ regenerate: "Einrichtungscode neu erstellen",+ resetTitle: "Passwort von {username} zurücksetzen?",+ resetDescription: "Ein neu erstellter Einrichtungscode ersetzt das Passwort von {username}, meldet die Person ab und widerruft ihre API-Schlüssel. Geben Sie ihr den neuen Code, damit sie wieder ein Passwort wählen kann.",+ deactivate: "Deaktivieren",+ reactivate: "Reaktivieren",+ delete: "Konto löschen",+ deleteTitle: "{username} löschen?",+ deleteDescription: "Dadurch werden die Sitzungen von {username} widerrufen und laufende Arbeiten abgebrochen. Chats, Einstellungen, Zugangsdaten, Uploads, Datensätze, Trainingsläufe, Ausgaben, Exporte, Galerien, Sandboxes, Projekte und temporäre Dateien werden stillgelegt. Verzeichnisse werden beiseite umbenannt, nie gelöscht. Wird dieser Benutzername erneut angelegt, beginnt ein neues Konto ohne diese Daten.",+ cancel: "Abbrechen",+ retry: "Konten aktualisieren",+ failed: "Kontoanfrage fehlgeschlagen.",+ },title: "Einstellungen",dialog: {title: "Einstellungen",@@ -197,6 +225,7 @@ export const de = {panelReload: "Neu laden",},tabs: {+ accounts: "Konten",general: "Allgemein",profile: "Profil",appearance: "Darstellung",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex ae5ab703f31..52744d4cd1d 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -182,6 +182,34 @@ export const en = {},},settings: {+ accounts: {+ title: "Accounts",+ description: "Create private Studio accounts. New users sign in with a one-time setup code and choose a password.",+ username: "Username",+ create: "Create account",+ setupCode: "Setup code",+ setupFor: "Setup code for {username}",+ shownOnce: "Copy this code now and share it with the account holder. It is shown only here and can be used once within 60 minutes.",+ expires: "Expires {expiry}",+ copy: "Copy setup code",+ copied: "Copied",+ copyFailed: "Could not copy. Select and copy the setup code above.",+ dismiss: "Done",+ owner: "Installation owner",+ active: "Active",+ inactive: "Inactive",+ regenerate: "Regenerate setup code",+ resetTitle: "Reset {username}'s password?",+ resetDescription: "Regenerating the setup code replaces {username}'s password, signs them out and revokes their API keys. Give them the new code so they can choose a password again.",+ deactivate: "Deactivate",+ reactivate: "Reactivate",+ delete: "Delete account",+ deleteTitle: "Delete {username}?",+ deleteDescription: "This revokes {username}'s sessions and cancels their work. Their chats, settings, credentials, uploads, datasets, training runs, outputs, exports, galleries, sandboxes, projects and temporary files are retired. Directories are renamed aside, never deleted. Creating this username again starts a fresh account with none of this data.",+ cancel: "Cancel",+ retry: "Refresh accounts",+ failed: "Account request failed.",+ },title: "Settings",dialog: {title: "Settings",@@ -193,6 +221,7 @@ export const en = {panelReload: "Reload",},tabs: {+ accounts: "Accounts",general: "General",profile: "Profile",appearance: "Appearance",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 7672a69b8fb..066cff222d1 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -185,6 +185,34 @@ export const es = {},},settings: {+ accounts: {+ title: "Cuentas",+ description: "Crea cuentas privadas de Studio. Los nuevos usuarios inician sesión con un código de configuración de un solo uso y eligen una contraseña.",+ username: "Nombre de usuario",+ create: "Crear cuenta",+ setupCode: "Código de configuración",+ setupFor: "Código de configuración para {username}",+ shownOnce: "Copia este código ahora y compártelo con el titular de la cuenta. Solo se muestra aquí y puede usarse una vez en un plazo de 60 minutos.",+ expires: "Caduca {expiry}",+ copy: "Copiar código de configuración",+ copied: "Copiado",+ copyFailed: "No se pudo copiar. Selecciona y copia el código de configuración de arriba.",+ dismiss: "Listo",+ owner: "Propietario de la instalación",+ active: "Activa",+ inactive: "Inactiva",+ regenerate: "Regenerar código de configuración",+ resetTitle: "¿Restablecer la contraseña de {username}?",+ resetDescription: "Regenerar el código de configuración sustituye la contraseña de {username}, cierra sus sesiones y revoca sus claves de API. Dale el código nuevo para que elija otra contraseña.",+ deactivate: "Desactivar",+ reactivate: "Reactivar",+ delete: "Eliminar cuenta",+ deleteTitle: "¿Eliminar {username}?",+ deleteDescription: "Esto revoca las sesiones de {username} y cancela su trabajo. Sus chats, ajustes, credenciales, subidas, conjuntos de datos, entrenamientos, resultados, exportaciones, galerías, entornos aislados, proyectos y archivos temporales se retiran. Los directorios se renombran aparte, nunca se eliminan. Crear de nuevo este nombre de usuario inicia una cuenta nueva sin estos datos.",+ cancel: "Cancelar",+ retry: "Actualizar cuentas",+ failed: "La solicitud de cuenta falló.",+ },title: "Configuración",dialog: {title: "Configuración",@@ -196,6 +224,7 @@ export const es = {panelReload: "Recargar",},tabs: {+ accounts: "Cuentas",general: "General",profile: "Perfil",appearance: "Apariencia",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex f680a10308b..45f14458ce3 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -186,6 +186,34 @@ export const fr = {},},settings: {+ accounts: {+ title: "Comptes",+ description: "Créez des comptes Studio privés. Les nouveaux utilisateurs se connectent avec un code de configuration à usage unique et choisissent un mot de passe.",+ username: "Nom d'utilisateur",+ create: "Créer un compte",+ setupCode: "Code de configuration",+ setupFor: "Code de configuration pour {username}",+ shownOnce: "Copiez ce code maintenant et transmettez-le au titulaire du compte. Il n'est affiché qu'ici et ne peut être utilisé qu'une seule fois dans les 60 minutes.",+ expires: "Expire {expiry}",+ copy: "Copier le code de configuration",+ copied: "Copié",+ copyFailed: "Impossible de copier. Sélectionnez et copiez le code de configuration ci-dessus.",+ dismiss: "Terminé",+ owner: "Propriétaire de l'installation",+ active: "Actif",+ inactive: "Inactif",+ regenerate: "Régénérer le code de configuration",+ resetTitle: "Réinitialiser le mot de passe de {username} ?",+ resetDescription: "Régénérer le code de configuration remplace le mot de passe de {username}, ferme ses sessions et révoque ses clés API. Donnez-lui le nouveau code pour qu'il choisisse à nouveau un mot de passe.",+ deactivate: "Désactiver",+ reactivate: "Réactiver",+ delete: "Supprimer le compte",+ deleteTitle: "Supprimer {username} ?",+ deleteDescription: "Cette action révoque les sessions de {username} et annule ses travaux en cours. Ses conversations, réglages, identifiants, envois, jeux de données, entraînements, sorties, exports, galeries, bacs à sable, projets et fichiers temporaires sont retirés. Les répertoires sont renommés à part, jamais supprimés. Recréer ce nom d'utilisateur démarre un nouveau compte sans aucune de ces données.",+ cancel: "Annuler",+ retry: "Actualiser les comptes",+ failed: "La requête de compte a échoué.",+ },title: "Paramètres",dialog: {title: "Paramètres",@@ -197,6 +225,7 @@ export const fr = {panelReload: "Recharger",},tabs: {+ accounts: "Comptes",general: "Général",profile: "Profil",appearance: "Apparence",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 3992b18561f..fc88f4b6663 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -185,6 +185,34 @@ export const hi = {},},settings: {+ accounts: {+ title: "खाते",+ description: "निजी Studio खाते बनाएँ। नए उपयोगकर्ता एक बार इस्तेमाल होने वाले सेटअप कोड से साइन इन करते हैं और पासवर्ड चुनते हैं।",+ username: "उपयोगकर्ता नाम",+ create: "खाता बनाएँ",+ setupCode: "सेटअप कोड",+ setupFor: "{username} के लिए सेटअप कोड",+ shownOnce: "यह कोड अभी कॉपी करें और खाता धारक को दें। यह केवल यहीं दिखता है और 60 मिनट के भीतर एक बार इस्तेमाल किया जा सकता है।",+ expires: "समाप्ति: {expiry}",+ copy: "सेटअप कोड कॉपी करें",+ copied: "कॉपी हो गया",+ copyFailed: "कॉपी नहीं हो सका। ऊपर दिए सेटअप कोड को चुनकर कॉपी करें।",+ dismiss: "हो गया",+ owner: "इंस्टॉलेशन स्वामी",+ active: "सक्रिय",+ inactive: "निष्क्रिय",+ regenerate: "सेटअप कोड फिर से बनाएँ",+ resetTitle: "{username} का पासवर्ड रीसेट करें?",+ resetDescription: "सेटअप कोड फिर से बनाने पर {username} का पासवर्ड बदल जाता है, उनके सत्र समाप्त हो जाते हैं और उनकी API कुंजियाँ रद्द हो जाती हैं। उन्हें नया कोड दें ताकि वे फिर से पासवर्ड चुन सकें।",+ deactivate: "निष्क्रिय करें",+ reactivate: "फिर से सक्रिय करें",+ delete: "खाता हटाएँ",+ deleteTitle: "{username} को हटाएँ?",+ deleteDescription: "इससे {username} के सत्र रद्द हो जाएँगे और उनका चल रहा काम बंद हो जाएगा। उनकी चैट, सेटिंग्स, क्रेडेंशियल, अपलोड, डेटासेट, ट्रेनिंग रन, आउटपुट, एक्सपोर्ट, गैलरी, सैंडबॉक्स, प्रोजेक्ट और अस्थायी फ़ाइलें अलग रख दी जाती हैं। डायरेक्टरी का नाम बदलकर उन्हें किनारे कर दिया जाता है, हटाया कभी नहीं जाता। यही उपयोगकर्ता नाम फिर से बनाने पर इस डेटा के बिना एक नया खाता शुरू होता है।",+ cancel: "रद्द करें",+ retry: "खाते ताज़ा करें",+ failed: "खाता अनुरोध विफल रहा।",+ },title: "सेटिंग्स",dialog: {title: "सेटिंग्स",@@ -196,6 +224,7 @@ export const hi = {panelReload: "फिर से लोड करें",},tabs: {+ accounts: "खाते",general: "सामान्य",profile: "प्रोफ़ाइल",appearance: "रूप-रंग",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex ba861d22e3d..56020bd0b27 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -150,6 +150,34 @@ export const it = {},},settings: {+ accounts: {+ title: "Account",+ description: "Crea account Studio privati. I nuovi utenti accedono con un codice di configurazione monouso e scelgono una password.",+ username: "Nome utente",+ create: "Crea account",+ setupCode: "Codice di configurazione",+ setupFor: "Codice di configurazione per {username}",+ shownOnce: "Copia subito questo codice e condividilo con il titolare dell'account. Viene mostrato solo qui e può essere usato una sola volta entro 60 minuti.",+ expires: "Scade {expiry}",+ copy: "Copia codice di configurazione",+ copied: "Copiato",+ copyFailed: "Impossibile copiare. Seleziona e copia il codice di configurazione qui sopra.",+ dismiss: "Fatto",+ owner: "Proprietario dell'installazione",+ active: "Attivo",+ inactive: "Inattivo",+ regenerate: "Rigenera codice di configurazione",+ resetTitle: "Reimpostare la password di {username}?",+ resetDescription: "Rigenerare il codice di configurazione sostituisce la password di {username}, chiude le sue sessioni e revoca le sue chiavi API. Consegnagli il nuovo codice per scegliere di nuovo una password.",+ deactivate: "Disattiva",+ reactivate: "Riattiva",+ delete: "Elimina account",+ deleteTitle: "Eliminare {username}?",+ deleteDescription: "Questa operazione revoca le sessioni di {username} e annulla il suo lavoro. Chat, impostazioni, credenziali, caricamenti, dataset, addestramenti, output, esportazioni, gallerie, sandbox, progetti e file temporanei vengono ritirati. Le directory vengono rinominate e messe da parte, mai eliminate. Creare di nuovo questo nome utente avvia un account nuovo senza questi dati.",+ cancel: "Annulla",+ retry: "Aggiorna account",+ failed: "Richiesta account non riuscita.",+ },title: "Impostazioni",dialog: {title: "Impostazioni",@@ -161,6 +189,7 @@ export const it = {panelReload: "Ricarica",},tabs: {+ accounts: "Account",general: "Generali",profile: "Profilo",appearance: "Aspetto",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 5d0b481ea2d..2290638faaa 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -184,6 +184,34 @@ export const ja = {},},settings: {+ accounts: {+ title: "アカウント",+ description: "個別の Studio アカウントを作成します。新しいユーザーは一度きりのセットアップコードでサインインし、パスワードを設定します。",+ username: "ユーザー名",+ create: "アカウントを作成",+ setupCode: "セットアップコード",+ setupFor: "{username} のセットアップコード",+ shownOnce: "このコードを今すぐコピーしてアカウントの持ち主に渡してください。ここにしか表示されず、60 分以内に一度だけ使えます。",+ expires: "有効期限: {expiry}",+ copy: "セットアップコードをコピー",+ copied: "コピーしました",+ copyFailed: "コピーできませんでした。上のセットアップコードを選択してコピーしてください。",+ dismiss: "完了",+ owner: "インストールの所有者",+ active: "有効",+ inactive: "無効",+ regenerate: "セットアップコードを再発行",+ resetTitle: "{username} のパスワードをリセットしますか?",+ resetDescription: "セットアップコードを再発行すると {username} のパスワードが置き換えられ、セッションは終了し、API キーは失効します。新しいコードを渡して、もう一度パスワードを選んでもらってください。",+ deactivate: "無効化",+ reactivate: "再有効化",+ delete: "アカウントを削除",+ deleteTitle: "{username} を削除しますか?",+ deleteDescription: "{username} のセッションを取り消し、実行中の作業をキャンセルします。チャット、設定、認証情報、アップロード、データセット、学習の実行、出力、エクスポート、ギャラリー、サンドボックス、プロジェクト、一時ファイルは退避されます。ディレクトリは名前を変えて脇に置かれ、削除はされません。同じユーザー名を再び作成すると、これらのデータを持たない新しいアカウントになります。",+ cancel: "キャンセル",+ retry: "アカウントを再読み込み",+ failed: "アカウントの要求に失敗しました。",+ },title: "設定",dialog: {title: "設定",@@ -195,6 +223,7 @@ export const ja = {panelReload: "再読み込み",},tabs: {+ accounts: "アカウント",general: "一般",profile: "プロフィール",appearance: "外観",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 734c68e6fd5..6f377c898e5 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -182,6 +182,34 @@ export const ko = {},},settings: {+ accounts: {+ title: "계정",+ description: "개별 Studio 계정을 만듭니다. 새 사용자는 일회용 설정 코드로 로그인한 뒤 비밀번호를 정합니다.",+ username: "사용자 이름",+ create: "계정 만들기",+ setupCode: "설정 코드",+ setupFor: "{username}의 설정 코드",+ shownOnce: "지금 이 코드를 복사해 계정 소유자에게 전달하세요. 여기에서만 표시되며 60분 안에 한 번만 사용할 수 있습니다.",+ expires: "만료: {expiry}",+ copy: "설정 코드 복사",+ copied: "복사됨",+ copyFailed: "복사할 수 없습니다. 위의 설정 코드를 선택해 복사하세요.",+ dismiss: "완료",+ owner: "설치 소유자",+ active: "활성",+ inactive: "비활성",+ regenerate: "설정 코드 다시 생성",+ resetTitle: "{username}의 비밀번호를 재설정할까요?",+ resetDescription: "설정 코드를 다시 생성하면 {username}의 비밀번호가 바뀌고 세션이 종료되며 API 키가 취소됩니다. 새 코드를 전달해 비밀번호를 다시 정하도록 하세요.",+ deactivate: "비활성화",+ reactivate: "다시 활성화",+ delete: "계정 삭제",+ deleteTitle: "{username}을(를) 삭제할까요?",+ deleteDescription: "{username}의 세션을 취소하고 진행 중인 작업을 중단합니다. 채팅, 설정, 자격 증명, 업로드, 데이터셋, 학습 실행, 출력, 내보내기, 갤러리, 샌드박스, 프로젝트, 임시 파일이 퇴역 처리됩니다. 디렉터리는 이름을 바꿔 옆으로 옮길 뿐 삭제되지 않습니다. 같은 사용자 이름을 다시 만들면 이 데이터가 없는 새 계정이 시작됩니다.",+ cancel: "취소",+ retry: "계정 새로 고침",+ failed: "계정 요청에 실패했습니다.",+ },title: "설정",dialog: {title: "설정",@@ -193,6 +221,7 @@ export const ko = {panelReload: "새로고침",},tabs: {+ accounts: "계정",general: "일반",profile: "프로필",appearance: "모양",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 30861513404..288bba50ecf 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -184,6 +184,34 @@ export const ptBR = {},},settings: {+ accounts: {+ title: "Contas",+ description: "Crie contas privadas do Studio. Novos usuários entram com um código de configuração de uso único e escolhem uma senha.",+ username: "Nome de usuário",+ create: "Criar conta",+ setupCode: "Código de configuração",+ setupFor: "Código de configuração para {username}",+ shownOnce: "Copie este código agora e compartilhe com o titular da conta. Ele é mostrado apenas aqui e pode ser usado uma vez em até 60 minutos.",+ expires: "Expira {expiry}",+ copy: "Copiar código de configuração",+ copied: "Copiado",+ copyFailed: "Não foi possível copiar. Selecione e copie o código de configuração acima.",+ dismiss: "Concluído",+ owner: "Proprietário da instalação",+ active: "Ativa",+ inactive: "Inativa",+ regenerate: "Gerar novo código de configuração",+ resetTitle: "Redefinir a senha de {username}?",+ resetDescription: "Gerar um novo código de configuração substitui a senha de {username}, encerra as sessões dela e revoga suas chaves de API. Entregue o novo código para que ela escolha outra senha.",+ deactivate: "Desativar",+ reactivate: "Reativar",+ delete: "Excluir conta",+ deleteTitle: "Excluir {username}?",+ deleteDescription: "Isso revoga as sessões de {username} e cancela o trabalho em andamento. Chats, configurações, credenciais, uploads, conjuntos de dados, treinamentos, saídas, exportações, galerias, sandboxes, projetos e arquivos temporários são retirados. Os diretórios são renomeados à parte, nunca excluídos. Criar este nome de usuário novamente inicia uma conta nova sem nenhum desses dados.",+ cancel: "Cancelar",+ retry: "Atualizar contas",+ failed: "A solicitação da conta falhou.",+ },title: "Configurações",dialog: {title: "Configurações",@@ -195,6 +223,7 @@ export const ptBR = {panelReload: "Recarregar",},tabs: {+ accounts: "Contas",general: "Geral",profile: "Perfil",appearance: "Aparência",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 8a28bb807fd..5996d98f4d0 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -184,6 +184,34 @@ export const ru = {},},settings: {+ accounts: {+ title: "Учётные записи",+ description: "Создавайте отдельные учётные записи Studio. Новые пользователи входят по одноразовому коду настройки и задают пароль.",+ username: "Имя пользователя",+ create: "Создать учётную запись",+ setupCode: "Код настройки",+ setupFor: "Код настройки для {username}",+ shownOnce: "Скопируйте этот код сейчас и передайте владельцу учётной записи. Он показывается только здесь и действует один раз в течение 60 минут.",+ expires: "Истекает {expiry}",+ copy: "Скопировать код настройки",+ copied: "Скопировано",+ copyFailed: "Не удалось скопировать. Выделите и скопируйте код настройки выше.",+ dismiss: "Готово",+ owner: "Владелец установки",+ active: "Активна",+ inactive: "Неактивна",+ regenerate: "Создать новый код настройки",+ resetTitle: "Сбросить пароль {username}?",+ resetDescription: "Создание нового кода настройки заменяет пароль {username}, завершает его сеансы и отзывает его ключи API. Передайте ему новый код, чтобы он снова выбрал пароль.",+ deactivate: "Деактивировать",+ reactivate: "Активировать снова",+ delete: "Удалить учётную запись",+ deleteTitle: "Удалить {username}?",+ deleteDescription: "Это отзывает сеансы {username} и отменяет текущую работу. Чаты, настройки, учётные данные, загрузки, наборы данных, обучения, результаты, экспорты, галереи, песочницы, проекты и временные файлы выводятся из использования. Каталоги переименовываются и откладываются, но не удаляются. Повторное создание этого имени пользователя начнёт новую учётную запись без этих данных.",+ cancel: "Отмена",+ retry: "Обновить список",+ failed: "Запрос к учётной записи не выполнен.",+ },title: "Настройки",dialog: {title: "Настройки",@@ -195,6 +223,7 @@ export const ru = {panelReload: "Перезагрузить",},tabs: {+ accounts: "Учётные записи",general: "Общие",profile: "Профиль",appearance: "Оформление",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 2e4e99b0cb5..d56e29474e5 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -180,6 +180,34 @@ export const zhCN = {},},settings: {+ accounts: {+ title: "账户",+ description: "创建独立的 Studio 账户。新用户使用一次性设置码登录并设置密码。",+ username: "用户名",+ create: "创建账户",+ setupCode: "设置码",+ setupFor: "{username} 的设置码",+ shownOnce: "请立即复制此设置码并交给账户持有人。它只在此处显示一次,60 分钟内可使用一次。",+ expires: "过期时间:{expiry}",+ copy: "复制设置码",+ copied: "已复制",+ copyFailed: "无法复制。请选中并复制上方的设置码。",+ dismiss: "完成",+ owner: "安装所有者",+ active: "已启用",+ inactive: "已停用",+ regenerate: "重新生成设置码",+ resetTitle: "重置 {username} 的密码?",+ resetDescription: "重新生成设置码会替换 {username} 的密码、结束其会话并吊销其 API 密钥。请把新的设置码交给对方,让其重新设置密码。",+ deactivate: "停用",+ reactivate: "重新启用",+ delete: "删除账户",+ deleteTitle: "删除 {username}?",+ deleteDescription: "这将撤销 {username} 的会话并取消其进行中的工作。其聊天、设置、凭据、上传、数据集、训练运行、输出、导出、图库、沙箱、项目和临时文件都会被退役。目录只会重命名移开,绝不删除。再次创建该用户名将开始一个不包含这些数据的新账户。",+ cancel: "取消",+ retry: "刷新账户",+ failed: "账户请求失败。",+ },title: "设置",dialog: {title: "设置",@@ -191,6 +219,7 @@ export const zhCN = {panelReload: "重新加载",},tabs: {+ accounts: "账户",general: "通用",profile: "个人资料",appearance: "外观",diff --git a/studio/frontend/src/lib/account-transition.ts b/studio/frontend/src/lib/account-transition.tsnew file mode 100644index 00000000000..c38205a05f5--- /dev/null+++ b/studio/frontend/src/lib/account-transition.ts@@ -0,0 +1,270 @@+// 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 { USER_STOPPED_KEY } from "../hooks/server-stop-intent.ts";++export const BROWSER_ACCOUNT_KEY = "unsloth.browser-account.v1";+/** Written before a switch publishes new tokens, so peer tabs stop sending requests until the+ * marker lands and they reload. */+export const BROWSER_ACCOUNT_FENCE_KEY = "unsloth.browser-account.fence.v1";+/** A peer tab holds the marker for at most this long before reloading on its own. */+export const ACCOUNT_FENCE_TIMEOUT_MS = 10_000;++let transitionPending = false;+/** True in a peer tab between another tab's fence and its marker: requests must not go out. */+export function accountTransitionPending(): boolean {+ return transitionPending;+}+export const OWNER_BROWSER_ACCOUNT = "unsloth";++export const APPEARANCE_KEY = "unsloth_appearance_customization";++/** Browser chrome only. Never add credentials, content, model choices or profile data. */+export const ACCOUNT_CHROME_KEYS = new Set([+ "theme",+ "palette",+ APPEARANCE_KEY,+ "unsloth_locale",+ "sidebar_pinned",+ "sidebar_width",+ "chat_settings_width",+ "unsloth_sidebar_navigate_open",+ "unsloth_settings_active_tab",+ "unsloth_loaded_models_collapsed",+ "unsloth_loaded_models_dismissed",+ "unsloth-rag-preview-width",+]);+export const ACCOUNT_CHROME_PREFIXES = [+ "unsloth_web_update_dismissed:",+] as const;+/** Per-tab flags about the browser session, not the account. Never add content. */+export const ACCOUNT_SESSION_CHROME_KEYS = new Set([USER_STOPPED_KEY]);+/** Purged on an account change. Durable stores are named per account (`accountDatabaseName`). */+export const ACCOUNT_DATABASES = [+ // Legacy store: its one-shot import would push these threads into the next account.+ "unsloth-chat",+] as const;++export type AccountTransitionBrowser = Pick<+ Window,+ "localStorage" | "sessionStorage" | "indexedDB" | "location"+>;++export type BrowserAccount = { username: string; accountId?: string | null };++const ACCOUNT_ID_MARKER_PREFIX = "account:";++/** Must match what `auth/storage.py` stores: casefolded `[a-z0-9_-]{3,32}`. */+export function normalizeAccountUsername(username: string): string {+ return username.trim().toLowerCase();+}++export function browserAccountMarker(account: BrowserAccount | string): string {+ const identity: BrowserAccount =+ typeof account === "string" ? { username: account } : account;+ const username = normalizeAccountUsername(identity.username);+ if (!username) throw new Error("Missing account username.");+ return identity.accountId+ ? `${ACCOUNT_ID_MARKER_PREFIX}${identity.accountId}:${username}`+ : username;+}++/** The owner keeps the historical name; a managed account gets its own store. */+export function accountDatabaseName(+ name: string,+ storage: Pick<Storage, "getItem"> | null = typeof window === "undefined"+ ? null+ : window.localStorage,+): string {+ const account = parseAccountMarker(+ storage?.getItem(BROWSER_ACCOUNT_KEY) ?? OWNER_BROWSER_ACCOUNT,+ );+ const owner =+ account.accountId === "owner" ||+ (!account.accountId && account.username === OWNER_BROWSER_ACCOUNT);+ return owner ? name : `${name}:${account.accountId ?? account.username}`;+}++type MarkedAccount = { accountId: string | null; username: string };+function parseAccountMarker(marker: string): MarkedAccount {+ const legacy = {+ accountId: null,+ username: normalizeAccountUsername(marker),+ };+ if (!marker.startsWith(ACCOUNT_ID_MARKER_PREFIX)) return legacy;+ const qualified = marker.slice(ACCOUNT_ID_MARKER_PREFIX.length);+ const separator = qualified.indexOf(":");+ if (separator <= 0 || separator === qualified.length - 1) return legacy;+ return {+ accountId: qualified.slice(0, separator),+ username: normalizeAccountUsername(qualified.slice(separator + 1)),+ };+}++/** May the browser data carry over? The username fallback cannot tell a recreated account apart. */+function isSameAccount(previous: MarkedAccount, next: MarkedAccount): boolean {+ if (previous.accountId && next.accountId)+ return previous.accountId === next.accountId;+ return previous.username === next.username;+}++export function resetFullAccessForMultiUser(storage: Storage): void {+ if (storage.getItem("unsloth_chat_permission_mode") === "full") {+ storage.setItem("unsloth_chat_permission_mode", "auto");+ }+}++const IMPORTED_FONT_SELECTIONS = [+ "uiFont",+ "headingFont",+ "chatFont",+ "codeFont",+] as const;++/** An imported font is uploaded file bytes, not chrome: strip it and any selection naming it. */+function purgeImportedFonts(storage: Storage): void {+ const raw = storage.getItem(APPEARANCE_KEY);+ if (!raw?.includes("importedFonts")) return;+ let parsed: {+ state?: { customization?: Record<string, unknown> };+ customization?: Record<string, unknown>;+ };+ try {+ parsed = JSON.parse(raw);+ } catch {+ // Unreadable, so worthless to the store, and it still holds font bytes.+ storage.removeItem(APPEARANCE_KEY);+ return;+ }+ const customization = parsed?.state?.customization ?? parsed?.customization;+ const fonts = customization?.importedFonts;+ if (!customization || !Array.isArray(fonts) || fonts.length === 0) return;+ const names = new Set(+ fonts.map((font) => (font as { name?: unknown } | null)?.name),+ );+ customization.importedFonts = [];+ for (const field of IMPORTED_FONT_SELECTIONS) {+ if (names.has(customization[field])) customization[field] = null;+ }+ storage.setItem(APPEARANCE_KEY, JSON.stringify(parsed));+}++function clearAccountSessionStorage(browser: AccountTransitionBrowser): void {+ try {+ const storage = browser.sessionStorage;+ const keys = Array.from({ length: storage.length }, (_, index) =>+ storage.key(index),+ );+ for (const key of keys) {+ if (!key || ACCOUNT_SESSION_CHROME_KEYS.has(key)) continue;+ storage.removeItem(key);+ }+ } catch {+ // Unreadable session storage never fails a sign-in.+ }+}++function deleteAccountDatabase(+ indexedDB: IDBFactory,+ name: string,+): Promise<void> {+ return new Promise((resolve, reject) => {+ const request = indexedDB.deleteDatabase(name);+ request.onsuccess = () => resolve();+ request.onerror = () =>+ reject(request.error ?? new Error("Could not clear account data."));+ request.onblocked = () =>+ reject(+ new Error(+ "Close other Unsloth tabs and retry signing in to clear the previous account's data.",+ ),+ );+ });+}++/** Run before publishing new tokens; the marker is published last so other tabs reload only+ * once the new session is ready. */+export async function transitionBrowserAccount(+ account: BrowserAccount | string,+ postAuthRoute: string,+ commitSession: () => void,+ browser: AccountTransitionBrowser = window,+): Promise<boolean> {+ const marker = browserAccountMarker(account);+ const storage = browser.localStorage;+ const changed = !isSameAccount(+ parseAccountMarker(+ storage.getItem(BROWSER_ACCOUNT_KEY) ?? OWNER_BROWSER_ACCOUNT,+ ),+ parseAccountMarker(marker),+ );+ if (changed) {+ const keys = Array.from({ length: storage.length }, (_, index) =>+ storage.key(index),+ );+ for (const key of keys) {+ if (+ !key ||+ key === BROWSER_ACCOUNT_KEY ||+ ACCOUNT_CHROME_KEYS.has(key) ||+ ACCOUNT_CHROME_PREFIXES.some((prefix) => key.startsWith(prefix))+ )+ continue;+ if (key.startsWith("unsloth") || key.startsWith("chat-draft"))+ storage.removeItem(key);+ }+ purgeImportedFonts(storage);+ clearAccountSessionStorage(browser);+ await Promise.all(+ ACCOUNT_DATABASES.map((name) =>+ deleteAccountDatabase(browser.indexedDB, name),+ ),+ );+ }+ // Fence first: peers see it before the tokens, so nothing of the previous account goes out+ // under the new credentials while their reload is pending.+ if (changed) storage.setItem(BROWSER_ACCOUNT_FENCE_KEY, marker);+ commitSession();+ if (storage.getItem(BROWSER_ACCOUNT_KEY) !== marker)+ storage.setItem(BROWSER_ACCOUNT_KEY, marker);+ if (changed) storage.removeItem(BROWSER_ACCOUNT_FENCE_KEY);+ if (changed) browser.location.replace(postAuthRoute);+ return changed;+}++const watchedBrowsers = new WeakSet<Window>();+export function installAccountTransitionListener(+ browser: Window = window,+): void {+ if (watchedBrowsers.has(browser)) return;+ watchedBrowsers.add(browser);+ let reloading = false;+ let fenceTimer: ReturnType<typeof setTimeout> | null = null;+ const reload = () => {+ if (reloading) return;+ reloading = true;+ if (fenceTimer !== null) clearTimeout(fenceTimer);+ clearAccountSessionStorage(browser);+ browser.location.reload();+ };+ browser.addEventListener("storage", (event) => {+ if (reloading || event.newValue === null) return;+ if (event.storageArea && event.storageArea !== browser.localStorage) return;+ if (event.key === BROWSER_ACCOUNT_FENCE_KEY) {+ const current = parseAccountMarker(+ browser.localStorage.getItem(BROWSER_ACCOUNT_KEY) ?? OWNER_BROWSER_ACCOUNT,+ );+ if (isSameAccount(current, parseAccountMarker(event.newValue))) return;+ // Stop sending until the marker arrives; a switch that never finishes still reloads.+ transitionPending = true;+ if (fenceTimer === null) fenceTimer = setTimeout(reload, ACCOUNT_FENCE_TIMEOUT_MS);+ return;+ }+ if (event.key !== BROWSER_ACCOUNT_KEY) return;+ const previous = parseAccountMarker(+ event.oldValue ?? OWNER_BROWSER_ACCOUNT,+ );+ if (isSameAccount(previous, parseAccountMarker(event.newValue))) return;+ reload();+ });+}diff --git a/studio/frontend/tests/account-auth-redirect.test.ts b/studio/frontend/tests/account-auth-redirect.test.tsnew file mode 100644index 00000000000..3af52df5cd9--- /dev/null+++ b/studio/frontend/tests/account-auth-redirect.test.ts@@ -0,0 +1,50 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";+import type * as AuthApi from "../src/features/auth/api.ts";++for (const mode of ["single", "multi"]) {+ test(`${mode} auth redirect reconciles the correct password-change requirement`, async (t) => {+ const previousWindow = globalThis.window;+ const previousFetch = globalThis.fetch;+ let change = false;+ const location = { pathname: "/chat", href: "" };+ globalThis.window = { location } as unknown as Window & typeof globalThis;+ globalThis.fetch = async (path) =>+ String(path).endsWith("/status")+ ? Response.json({ login_mode: mode, requires_password_change: false })+ : Response.json(+ { detail: "Password change required" },+ { status: 403 },+ );+ t.after(() => {+ globalThis.window = previousWindow;+ globalThis.fetch = previousFetch;+ });+ const api = loadWithStubs<typeof AuthApi>(+ new URL("../src/features/auth/api.ts", import.meta.url),+ {+ "@/lib/api-base": { apiUrl: (path: string) => path, isTauri: false },+ "@/lib/account-transition": { accountTransitionPending: () => false },+ "./session": {+ getAuthToken: () => "setup-token",+ getRefreshToken: () => null,+ mustChangePassword: () => change,+ setMustChangePassword: (required: boolean) => {+ change = required;+ },+ },+ },+ );+ assert.equal((await api.authFetch("/api/accounts")).status, 403);+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(+ location.href,+ mode === "multi" ? "/change-password" : "/login",+ );+ assert.equal(change, mode === "multi");+ });+}diff --git a/studio/frontend/tests/account-desktop-auth.test.ts b/studio/frontend/tests/account-desktop-auth.test.tsnew file mode 100644index 00000000000..e26a4a6f527--- /dev/null+++ b/studio/frontend/tests/account-desktop-auth.test.ts@@ -0,0 +1,303 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++type AutoAuth = {+ tauriAutoAuth(options?: { force?: boolean }): Promise<boolean>;+ isTauriLoginRequired(): boolean;+ getTauriAuthFailure(): string | null;+};++type Guards = {+ requireAuth(): Promise<void>;+ requireGuest(): Promise<void>;+ requirePasswordChangeFlow(): Promise<void>;+};++function fixture(t: { after(fn: () => void): void }, tauri = true) {+ const originalWindow = globalThis.window;+ const originalFetch = globalThis.fetch;+ const events: string[] = [];+ Object.assign(globalThis, {+ window: { dispatchEvent: (event: Event) => events.push(event.type) },+ });+ t.after(() => {+ Object.assign(globalThis, { window: originalWindow, fetch: originalFetch });+ });+ let access: string | null = null;+ let refresh: string | null = null;+ let passwordChange = false;+ let response: unknown = { access_token: "owner-access", refresh_token: "owner-refresh" };+ let invokeCalls = 0;+ let refreshCalls = 0;+ let refreshSucceeds = false;+ let statusCalls = 0;+ let status: {+ initialized: boolean;+ requires_password_change: boolean;+ login_mode: string;+ full_access?: boolean;+ } = { initialized: true, requires_password_change: false, login_mode: "single" };+ const navigations: unknown[] = [];+ const session = {+ hasAuthToken: () => !!access,+ hasRefreshToken: () => !!refresh,+ mustChangePassword: () => passwordChange,+ setMustChangePassword: (value: boolean) => { passwordChange = value; },+ storeAuthTokens: (a: string, r: string) => { access = a; refresh = r; },+ clearAuthTokens: () => { access = null; refresh = null; passwordChange = false; },+ getPostAuthRoute: () => tauri ? "/chat" : passwordChange ? "/change-password" : "/chat",+ refreshSession: async () => {+ refreshCalls++;+ if (!refreshSucceeds) return false;+ access = "refreshed-access";+ refresh = "refreshed-refresh";+ return true;+ },+ };+ const apiBase = { isTauri: tauri, apiUrl: (path: string) => path };+ const transitions: { account: unknown; route: string }[] = [];+ const loginModes: unknown[] = [];+ const auth = loadWithStubs<AutoAuth>(new URL("../src/features/auth/tauri-auto-auth.ts", import.meta.url), {+ "@/lib/api-base": apiBase,+ "./session": session,+ "./api": session,+ "./login-client": {+ setLoginMode: (mode: string, fullAccess?: boolean) => {+ loginModes.push([mode, fullAccess]);+ },+ },+ "@/lib/account-transition": {+ OWNER_BROWSER_ACCOUNT: "unsloth",+ transitionBrowserAccount: async (+ account: unknown,+ route: string,+ commitSession: () => void,+ ) => {+ transitions.push({ account, route });+ commitSession();+ return false;+ },+ },+ "@tauri-apps/api/core": {+ invoke: async (command: string) => {+ assert.equal(command, "desktop_auth");+ invokeCalls++;+ if (response instanceof Error) throw response;+ return response;+ },+ },+ "@/app/router": { router: { navigate: async (options: unknown) => { navigations.push(options); } } },+ });+ const guards = loadWithStubs<Guards>(new URL("../src/app/auth-guards.ts", import.meta.url), {+ "@tanstack/react-router": { redirect: (options: unknown) => options },+ "@/lib/api-base": apiBase,+ "@/features/auth": session,+ "@/features/auth/tauri-auto-auth": auth,+ "@/features/auth/login-client": {+ setLoginMode: (mode: string, fullAccess?: boolean) => {+ loginModes.push([mode, fullAccess]);+ },+ },+ });+ globalThis.fetch = async () => {+ statusCalls++;+ return new Response(JSON.stringify(status), { status: 200 });+ };+ return {+ auth, guards, session, events, navigations, loginModes, transitions,+ setResponse: (value: unknown) => { response = value; },+ setStatus: (value: typeof status) => { status = value; },+ setRefreshSucceeds: (value: boolean) => { refreshSucceeds = value; },+ get access() { return access; },+ get refresh() { return refresh; },+ get invokeCalls() { return invokeCalls; },+ get refreshCalls() { return refreshCalls; },+ get statusCalls() { return statusCalls; },+ };+}++const multi = { login_required: true, login_mode: "multi" };++test("single-account desktop keeps token storage, password bypass and coalescing", async (t) => {+ const f = fixture(t);+ f.session.setMustChangePassword(true);+ assert.deepEqual(await Promise.all([f.auth.tauriAutoAuth(), f.auth.tauriAutoAuth()]), [true, true]);+ assert.equal(f.invokeCalls, 1);+ assert.equal(f.access, "owner-access");+ assert.equal(f.refresh, "owner-refresh");+ assert.equal(f.session.mustChangePassword(), false);+ assert.equal(f.auth.isTauriLoginRequired(), false);+ assert.deepEqual(f.navigations, []);+});++test("single-account cached session stays local and startup guards keep their routes", async (t) => {+ const f = fixture(t);+ f.session.storeAuthTokens("existing", "refresh");+ assert.equal(await f.auth.tauriAutoAuth(), true);+ await f.guards.requireAuth();+ await assert.rejects(f.guards.requireGuest(), { to: "/chat" });+ await assert.rejects(f.guards.requirePasswordChangeFlow(), { to: "/chat" });+ assert.equal(f.invokeCalls, 0);+ assert.equal(f.refreshCalls, 0);+ assert.equal(f.statusCalls, 0);+});++test("forced multi-account startup opens login and releases the startup screen without tokens", async (t) => {+ const f = fixture(t);+ f.session.storeAuthTokens("old-owner", "old-refresh");+ f.setResponse(multi);+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), true);+ assert.equal(f.auth.isTauriLoginRequired(), true);+ assert.equal(f.access, null);+ assert.equal(f.refresh, null);+ assert.deepEqual(f.navigations, [{ to: "/login", replace: true }]);+ assert.equal(f.auth.getTauriAuthFailure(), null);+ assert.deepEqual(f.events, []);+ await f.guards.requireGuest();+ await assert.rejects(f.guards.requireAuth(), { to: "/login" });+ await assert.rejects(f.guards.requirePasswordChangeFlow(), { to: "/login" });+});++test("ordinary multi-account API recovery never reports an authenticated session", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ assert.equal(await f.auth.tauriAutoAuth(), false);+ assert.equal(f.access, null);+ assert.equal(f.auth.getTauriAuthFailure(), null);+});++test("an API retry sharing the forced startup probe still requires a session", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ const startup = f.auth.tauriAutoAuth({ force: true });+ const recovery = f.auth.tauriAutoAuth();+ assert.deepEqual(await Promise.all([startup, recovery]), [true, false]);+ assert.equal(f.invokeCalls, 1);+});++test("returning to one account restores desktop auto-login and guard shortcuts", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ await f.auth.tauriAutoAuth({ force: true });+ f.setResponse({ access_token: "restored-owner", refresh_token: "restored-refresh" });+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), true);+ assert.equal(f.auth.isTauriLoginRequired(), false);+ assert.equal(f.access, "restored-owner");+ await f.guards.requireAuth();+ await assert.rejects(f.guards.requireGuest(), { to: "/chat" });+ assert.equal(f.statusCalls, 0);+});++for (const passwordChange of [false, true]) {+ test(`a desktop account switch keeps the managed session it just created, password change ${passwordChange}`, async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ f.session.storeAuthTokens("alice-access", "alice-refresh");+ f.session.setMustChangePassword(passwordChange);+ f.setRefreshSucceeds(true);+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), true);+ assert.equal(f.access, "refreshed-access");+ assert.equal(f.refreshCalls, 1);+ assert.deepEqual(+ f.navigations,+ passwordChange ? [{ to: "/change-password", replace: true }] : [],+ );+ if (!passwordChange) await f.guards.requireAuth();+ });+}++test("owner tokens after the last managed account is deleted clear that account's browser data", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ await f.auth.tauriAutoAuth({ force: true });+ f.setResponse({ access_token: "owner-access", refresh_token: "owner-refresh" });+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), true);+ assert.deepEqual(f.transitions, [{ account: "unsloth", route: "/chat" }]);+ assert.deepEqual(f.loginModes, [["single", undefined]]);+ assert.equal(f.access, "owner-access");+});++test("a desktop probe with no usable refresh token still opens login", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ f.session.storeAuthTokens("stale-access", "stale-refresh");+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), true);+ assert.equal(f.refreshCalls, 1);+ assert.equal(f.access, null);+ assert.deepEqual(f.navigations, [{ to: "/login", replace: true }]);+});++test("a guard status read publishes the account policy it just learned", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ await f.auth.tauriAutoAuth({ force: true });+ f.session.storeAuthTokens("alice-access", "alice-refresh");+ f.setStatus({+ initialized: true,+ requires_password_change: false,+ login_mode: "multi",+ full_access: false,+ });+ await f.guards.requireAuth();+ assert.deepEqual(f.loginModes, [["multi", false]]);+});++test("a managed session stays signed in without another desktop exchange", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ await f.auth.tauriAutoAuth({ force: true });+ f.session.storeAuthTokens("alice-access", "alice-refresh");+ assert.equal(await f.auth.tauriAutoAuth(), true);+ assert.equal(f.access, "alice-access");+ assert.equal(f.invokeCalls, 1);+});++for (const tauri of [true, false]) {+ for (const requiresChange of [true, false]) {+ test(`${tauri ? "desktop" : "browser"} multi-account guards use session password flag ${requiresChange}`, async (t) => {+ const f = fixture(t, tauri);+ if (tauri) {+ f.setResponse(multi);+ await f.auth.tauriAutoAuth({ force: true });+ }+ f.session.storeAuthTokens("alice-access", "alice-refresh");+ f.session.setMustChangePassword(requiresChange);+ f.setStatus({ initialized: true, requires_password_change: !requiresChange, login_mode: "multi" });+ if (requiresChange) {+ await assert.rejects(f.guards.requireAuth(), { to: "/change-password" });+ await f.guards.requirePasswordChangeFlow();+ } else {+ await f.guards.requireAuth();+ await assert.rejects(f.guards.requireGuest(), { to: "/chat" });+ }+ assert.equal(f.session.mustChangePassword(), requiresChange);+ });+ }+}++test("backend-not-ready retains retry behavior and does not open login", async (t) => {+ const f = fixture(t);+ f.setResponse(new Error("Backend is not ready"));+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), false);+ assert.equal(f.auth.getTauriAuthFailure(), null);+ assert.deepEqual(f.navigations, []);+});++test("desktop secret failures remain failures", async (t) => {+ const f = fixture(t);+ f.setResponse(new Error("Desktop authentication failed"));+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), false);+ assert.equal(f.auth.getTauriAuthFailure(), "Desktop authentication failed");+ assert.deepEqual(f.events, ["tauri-auth-failed"]);+ assert.deepEqual(f.navigations, []);+});++test("browser mode never invokes the desktop shell", async (t) => {+ const f = fixture(t, false);+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), false);+ assert.equal(f.invokeCalls, 0);+});diff --git a/studio/frontend/tests/account-permissions.test.ts b/studio/frontend/tests/account-permissions.test.tsnew file mode 100644index 00000000000..c34285ff44a--- /dev/null+++ b/studio/frontend/tests/account-permissions.test.ts@@ -0,0 +1,89 @@+// 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 {+ loadWithStubs,+ stubJsxRuntime,+ type StubElement,+} from "./helpers/module-stubs.ts";++function permissionUi(loginMode: string, permissionMode: string) {+ const changes: string[] = [];+ const state = {+ permissionMode,+ setPermissionMode: (value: string) => {+ changes.push(value);+ },+ };+ const component = loadWithStubs<{+ PermissionModeMenuItems: (props: {+ onRequestFullAccess: () => void;+ }) => StubElement;+ FullAccessConfirmDialog: (props: {+ open: boolean;+ onOpenChange: () => void;+ }) => StubElement | null;+ }>(+ new URL("../src/features/chat/permission-mode-select.tsx", import.meta.url),+ {+ "react/jsx-runtime": stubJsxRuntime(),+ react: {+ useEffect: (effect: () => void) => effect(),+ useState: () => [false, () => {}],+ },+ "lucide-react": {+ ChevronDown: "ChevronDown",+ CircleAlert: "CircleAlert",+ Hand: "Hand",+ ShieldCheck: "ShieldCheck",+ },+ "@/features/auth/account-session": {+ useFullAccessAllowed: () => loginMode !== "multi",+ },+ "@/components/ui/alert-dialog": { AlertDialog: "AlertDialog" },+ "@/components/ui/button": { Button: "Button" },+ "@/components/ui/dropdown-menu": { DropdownMenuItem: "DropdownMenuItem" },+ "@/lib/chevron-icons": {},+ "@/lib/sparkles-icon": { SparklesGlyph: "SparklesGlyph" },+ "@/lib/tick-icon": {},+ "@/lib/utils": { cn: () => "" },+ "@hugeicons/react": {},+ "./stores/chat-runtime-store": {+ useChatRuntimeStore: (selector: (state: unknown) => unknown) =>+ selector(state),+ },+ },+ );+ return { component, changes };+}++for (const mode of ["single", "multi"]) {+ test(`${mode} permission menu enforces installation full-access policy`, () => {+ const ui = permissionUi(mode, "full");+ const menu = ui.component.PermissionModeMenuItems({+ onRequestFullAccess() {},+ });+ const rows = menu.props.children as StubElement[];+ assert.equal(rows.length, mode === "multi" ? 3 : 4);+ assert.deepEqual(ui.changes, mode === "multi" ? ["auto"] : []);+ const dialog = ui.component.FullAccessConfirmDialog({+ open: true,+ onOpenChange() {},+ });+ assert.equal(dialog === null, mode === "multi");+ });+}++test("multi-user policy leaves non-full preferences untouched", () => {+ for (const mode of ["ask", "auto", "off"]) {+ const ui = permissionUi("multi", mode);+ ui.component.PermissionModeMenuItems({+ onRequestFullAccess() {+ assert.fail("Full access must be unavailable");+ },+ });+ assert.deepEqual(ui.changes, []);+ }+});diff --git a/studio/frontend/tests/account-session-routing.test.ts b/studio/frontend/tests/account-session-routing.test.tsnew file mode 100644index 00000000000..9e5289ac02c--- /dev/null+++ b/studio/frontend/tests/account-session-routing.test.ts@@ -0,0 +1,49 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";+import type * as Session from "../src/features/auth/session.ts";++for (const [desktop, loginMode, change, expected] of [+ [true, "single", true, "/chat"],+ [true, "single", false, "/chat"],+ [true, "multi", true, "/change-password"],+ [true, "multi", false, "/chat"],+ [false, "single", true, "/change-password"],+ [false, "multi", true, "/change-password"],+] as const) {+ test(`${desktop ? "desktop" : "browser"} ${loginMode} session with change=${change} routes to ${expected}`, (t) => {+ const previousWindow = globalThis.window;+ const previousStorage = globalThis.localStorage;+ const storage = {+ getItem: () => (change ? "1" : null),+ } as unknown as Storage;+ globalThis.localStorage = storage;+ globalThis.window = {+ localStorage: storage,+ addEventListener() {},+ } as unknown as Window & typeof globalThis;+ t.after(() => {+ globalThis.window = previousWindow;+ globalThis.localStorage = previousStorage;+ });+ let listening = 0;+ const session = loadWithStubs<typeof Session>(+ new URL("../src/features/auth/session.ts", import.meta.url),+ {+ "@/lib/api-base": { isTauri: desktop },+ "@/lib/account-transition": {+ installAccountTransitionListener: () => {+ listening++;+ },+ },+ "./login-client": { getLoginMode: () => loginMode },+ "./session-events": {},+ },+ );+ assert.equal(session.getPostAuthRoute(), expected);+ assert.equal(listening, 1);+ });+}diff --git a/studio/frontend/tests/account-settings-ui.test.ts b/studio/frontend/tests/account-settings-ui.test.tsnew file mode 100644index 00000000000..859a048bebb--- /dev/null+++ b/studio/frontend/tests/account-settings-ui.test.ts@@ -0,0 +1,283 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";+import {+ loadWithStubs,+ stubJsxRuntime,+ type StubElement,+} from "./helpers/module-stubs.ts";+import { en } from "../src/i18n/locales/en.ts";+import { SETTINGS_SEARCH_INDEX } from "../src/features/settings/settings-search.ts";++const tabUrl = new URL(+ "../src/features/settings/tabs/accounts-tab.tsx",+ import.meta.url,+);+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));+function nodes(node: unknown): StubElement[] {+ if (Array.isArray(node)) return node.flatMap(nodes);+ if (!node || typeof node !== "object" || !("props" in node)) return [];+ const element = node as StubElement;+ return [element, ...nodes(element.props.children)];+}+function content(node: unknown): string {+ if (typeof node === "string") return node;+ if (Array.isArray(node)) return node.map(content).join(" ");+ if (node && typeof node === "object" && "props" in node)+ return content((node as StubElement).props.children);+ return "";+}+function translate(key: string, values: Record<string, string> = {}) {+ const message = key+ .split(".")+ .reduce<unknown>(+ (value, part) => (value as Record<string, unknown>)[part],+ en,+ ) as string;+ return message.replace(+ /\{([^}]+)\}/g,+ (_match, name: string) => values[name] ?? "",+ );+}+function tab(owner = true) {+ const states: unknown[] = [];+ const effects: (() => void)[] = [];+ let cursor = 0;+ const calls: string[] = [];+ const accounts = [+ {+ account_id: "owner",+ username: "unsloth",+ role: "owner",+ is_active: true,+ },+ {+ account_id: "alice-id",+ username: "alice",+ role: "user",+ is_active: true,+ },+ ];+ const setup = {+ account_id: "alice-id",+ username: "alice",+ setup_code: "one-time-secret",+ expires_at: "2026-09-06T13:00:00Z",+ };+ const api = loadWithStubs<{ AccountsTab: () => StubElement | null }>(tabUrl, {+ "react/jsx-runtime": stubJsxRuntime(),+ react: {+ useState: (initial: unknown) => {+ const index = cursor++;+ if (!(index in states)) states[index] = initial;+ return [+ states[index],+ (value: unknown) => {+ states[index] = value;+ },+ ];+ },+ useEffect: (effect: () => void) => {+ effects.push(effect);+ },+ },+ "@/features/auth": { useIsAccountOwner: () => owner },+ "@/components/ui/button": { Button: "Button" },+ "@/components/ui/input": { Input: "Input" },+ "@/components/ui/label": { Label: "Label" },+ "@/components/ui/alert-dialog": Object.fromEntries(+ [+ "AlertDialog",+ "AlertDialogAction",+ "AlertDialogCancel",+ "AlertDialogContent",+ "AlertDialogDescription",+ "AlertDialogFooter",+ "AlertDialogHeader",+ "AlertDialogTitle",+ ].map((name) => [name, name]),+ ),+ "@/lib/copy-to-clipboard": {+ copyToClipboard: async (value: string) => {+ calls.push(`copy:${value}`);+ return true;+ },+ },+ "@/i18n": { useT: () => translate },+ "../api/accounts": {+ fetchAccounts: async () => {+ calls.push("list");+ return accounts;+ },+ createAccount: async (username: string) => {+ calls.push(`create:${username}`);+ return setup;+ },+ regenerateSetupCode: async (accountId: string) => {+ calls.push(`regenerate:${accountId}`);+ return { ...setup, setup_code: "regenerated-secret" };+ },+ setAccountActive: async (accountId: string, active: boolean) => {+ calls.push(`active:${accountId}:${active}`);+ accounts[1].is_active = active;+ },+ deleteAccount: async (accountId: string) => {+ calls.push(`delete:${accountId}`);+ accounts.splice(1);+ },+ },+ });+ const render = () => {+ cursor = 0;+ const wrapper = api.AccountsTab();+ return wrapper ? (wrapper.type as () => StubElement)() : null;+ };+ return {+ render,+ calls,+ initialize: async () => {+ render();+ for (const effect of effects.splice(0)) effect();+ await tick();+ return render();+ },+ };+}+const confirm = async (tree: unknown) => {+ const action = nodes(tree).find((node) => node.type === "AlertDialogAction");+ assert.ok(action);+ (action.props.onClick as (event: unknown) => void)({ preventDefault() {} });+ await tick();+};+const click = async (tree: unknown, label: string) => {+ const button = nodes(tree).find(+ (node) => node.type === "Button" && content(node) === label,+ );+ assert.ok(button, label);+ (button.props.onClick as () => void)();+ await tick();+};++test("managed accounts mount no Accounts panel and send no list request", async () => {+ const ui = tab(false);+ assert.equal(await ui.initialize(), null);+ assert.deepEqual(ui.calls, []);+});++test("owner lists accounts without administrative actions on the owner row", async () => {+ const ui = tab();+ const tree = await ui.initialize();+ const ownerRow = nodes(tree).find(+ (node) => node.props["data-testid"] === "account-unsloth",+ );+ assert.ok(ownerRow);+ assert.equal(+ nodes(ownerRow).filter((node) => node.type === "Button").length,+ 0,+ );+ assert.match(content(tree), /Installation owner/);+});++test("create shows a copyable expiring setup code once and regeneration replaces it", async () => {+ const ui = tab();+ let tree = await ui.initialize();+ const input = nodes(tree).find(+ (node) => node.props.id === "new-account-username",+ );+ (input?.props.onChange as (event: unknown) => void)({+ target: { value: "alice" },+ });+ tree = ui.render();+ const form = nodes(tree).find((node) => node.type === "form");+ (form?.props.onSubmit as (event: unknown) => void)({ preventDefault() {} });+ await tick();+ tree = ui.render();+ assert.ok(ui.calls.includes("create:alice"));+ assert.match(content(tree), /one-time-secret/);+ assert.match(content(tree), /Expires/);+ assert.match(content(tree), /60 minutes/);+ await click(tree, "Copy setup code");+ assert.ok(ui.calls.includes("copy:one-time-secret"));+ await click(ui.render(), "Done");+ assert.doesNotMatch(content(ui.render()), /one-time-secret/);+ await click(ui.render(), "Regenerate setup code");+ assert.ok(!ui.calls.some((call) => call.startsWith("regenerate:")));+ await confirm(ui.render());+ assert.ok(ui.calls.includes("regenerate:alice-id"));+ assert.match(content(ui.render()), /regenerated-secret/);+});++test("regenerating a setup code names what it destroys before it runs", async () => {+ const ui = tab();+ await click(await ui.initialize(), "Regenerate setup code");+ const tree = ui.render();+ assert.match(content(tree), /Reset alice's password\?/);+ assert.match(content(tree), /revokes their API keys/);+ const dialog = nodes(tree).find((node) => node.type === "AlertDialog");+ assert.ok(dialog);+ (dialog.props.onOpenChange as (open: boolean) => void)(false);+ await tick();+ assert.ok(!ui.calls.some((call) => call.startsWith("regenerate:")));+ assert.doesNotMatch(content(ui.render()), /regenerated-secret/);+});++test("activation controls follow state and delete requires a named retirement confirmation", async () => {+ const ui = tab();+ let tree = await ui.initialize();+ await click(tree, "Deactivate");+ assert.ok(ui.calls.includes("active:alice-id:false"));+ await click(ui.render(), "Reactivate");+ assert.ok(ui.calls.includes("active:alice-id:true"));+ await click(ui.render(), "Delete account");+ tree = ui.render();+ assert.ok(!ui.calls.some((call) => call.startsWith("delete:")));+ assert.match(content(tree), /Delete alice\?/);+ assert.match(content(tree), /revokes alice's sessions/);+ assert.match(content(tree), /renamed aside, never deleted/);+ await confirm(tree);+ assert.ok(ui.calls.includes("delete:alice-id"));+});++test("desktop password control reaches managed accounts and the owner copy names the mode", () => {+ const general = readFileSync(+ new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),+ "utf8",+ );+ // Web keeps the row for everyone; on desktop only the owner is served by Remote access.+ assert.match(general, /\{isTauri && isOwner \? null : \(/);+ const remote = readFileSync(+ new URL(+ "../src/features/settings/components/remote-access-section.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(remote, /const multi = useLoginMode\(\) === "multi";/);+ assert.doesNotMatch(remote, /description="Remote browsers sign in as unsloth/);+});++test("Accounts is registered, searchable, and filtered from managed navigation and deferred panels", () => {+ assert.deepEqual(SETTINGS_SEARCH_INDEX.accounts, [+ "settings.accounts.title",+ "settings.accounts.create",+ ]);+ const dialog = readFileSync(+ new URL("../src/features/settings/settings-dialog.tsx", import.meta.url),+ "utf8",+ );+ const store = readFileSync(+ new URL(+ "../src/features/settings/stores/settings-dialog-store.ts",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(store, /"accounts"/);+ assert.match(dialog, /import\("\.\/tabs\/accounts-tab"\)/);+ assert.match(dialog, /settingsTabVisible\(tab\.id, isOwner\)/);+ assert.match(dialog, /resolveSettingsTab\(deferredTab, isOwner\)/);+ assert.equal((dialog.match(/visibleTabs\.map/g) ?? []).length, 2);+});diff --git a/studio/frontend/tests/account-transition-fonts.test.ts b/studio/frontend/tests/account-transition-fonts.test.tsnew file mode 100644index 00000000000..b948518dbec--- /dev/null+++ b/studio/frontend/tests/account-transition-fonts.test.ts@@ -0,0 +1,98 @@+// 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 {+ BROWSER_ACCOUNT_KEY,+ transitionBrowserAccount,+} from "../src/lib/account-transition.ts";++const APPEARANCE_KEY = "unsloth_appearance_customization";+const ALICE_FONT_BYTES = "data:font/woff2;base64,QUxJQ0VTRUNSRVQ=";++function appearanceValue(): string {+ return JSON.stringify({+ state: {+ customization: {+ uiFont: "Alice Sans",+ headingFont: null,+ chatFont: null,+ codeFont: null,+ importedFonts: [{ name: "Alice Sans", dataUrl: ALICE_FONT_BYTES }],+ contrast: 40,+ },+ },+ version: 7,+ });+}++function browserWith(values: Record<string, string>) {+ const data = new Map(Object.entries(values));+ const storage = {+ get length() {+ return data.size;+ },+ key: (index: number) => [...data.keys()][index] ?? null,+ getItem: (key: string) => data.get(key) ?? null,+ setItem: (key: string, value: string) => {+ data.set(key, value);+ },+ removeItem: (key: string) => {+ data.delete(key);+ },+ } as Storage;+ const browser = {+ localStorage: storage,+ sessionStorage: { length: 0, key: () => null, removeItem: () => {} },+ indexedDB: {+ deleteDatabase: () => {+ const request = {} as IDBOpenDBRequest;+ queueMicrotask(() =>+ request.onsuccess?.call(request, {} as IDBVersionChangeEvent),+ );+ return request;+ },+ },+ location: { replace: () => {} },+ } as unknown as Window;+ return { browser, data };+}++test("an account switch drops the previous account's uploaded font bytes", async () => {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ [APPEARANCE_KEY]: appearanceValue(),+ });+ assert.equal(+ await transitionBrowserAccount("bob", "/chat", () => {}, b.browser),+ true,+ );+ const persisted = b.data.get(APPEARANCE_KEY) ?? "";+ assert.equal(+ persisted.includes(ALICE_FONT_BYTES),+ false,+ "Alice's uploaded font bytes are still readable by Bob's session",+ );+ const parsed = JSON.parse(persisted);+ assert.deepEqual(parsed.state.customization.importedFonts, []);+ // A selection naming a purged font would render as a missing family.+ assert.equal(parsed.state.customization.uiFont, null);+ // Real chrome still survives the switch.+ assert.equal(parsed.state.customization.contrast, 40);+});++test("appearance chrome that carries no fonts is left byte-identical", async () => {+ const plain = JSON.stringify({+ state: { customization: { contrast: 40, uiFont: null } },+ version: 7,+ });+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ [APPEARANCE_KEY]: plain,+ theme: "dark",+ });+ await transitionBrowserAccount("bob", "/chat", () => {}, b.browser);+ assert.equal(b.data.get(APPEARANCE_KEY), plain);+ assert.equal(b.data.get("theme"), "dark");+});diff --git a/studio/frontend/tests/account-transition-peer-session.test.ts b/studio/frontend/tests/account-transition-peer-session.test.tsnew file mode 100644index 00000000000..eed15468c3e--- /dev/null+++ b/studio/frontend/tests/account-transition-peer-session.test.ts@@ -0,0 +1,101 @@+// 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 {+ getTrainingCompareHandoff,+ setTrainingCompareHandoff,+} from "../src/features/chat/lib/training-compare-handoff.ts";+import {+ BROWSER_ACCOUNT_KEY,+ installAccountTransitionListener,+ transitionBrowserAccount,+} from "../src/lib/account-transition.ts";++function storage(): Storage {+ const values = new Map<string, string>();+ return {+ get length() {+ return values.size;+ },+ key: (i: number) => [...values.keys()][i] ?? null,+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => {+ values.set(key, value);+ },+ removeItem: (key: string) => {+ values.delete(key);+ },+ clear: () => values.clear(),+ };+}++test("peer-tab account switch clears Alice's training handoff before Bob reloads", async () => {+ const localStorage = storage();+ localStorage.setItem(BROWSER_ACCOUNT_KEY, "account:a1:alice");+ localStorage.setItem("unsloth_auth_token", "alice-token");+ const peerSession = storage();+ peerSession.setItem("unsloth_server_user_stopped", "1");+ let listener: (event: Partial<StorageEvent>) => void;+ let handoffAtReload: unknown;+ let reloads = 0;+ const peer = {+ localStorage,+ sessionStorage: peerSession,+ addEventListener: (_type: string, fn: typeof listener) => {+ listener = fn;+ },+ location: {+ reload() {+ reloads++;+ assert.equal(localStorage.getItem("unsloth_auth_token"), "bob-token");+ // A real reload preserves sessionStorage. Read with the actual Chat consumer.+ handoffAtReload = getTrainingCompareHandoff();+ },+ },+ } as unknown as Window;+ const priorWindow = Object.getOwnPropertyDescriptor(globalThis, "window");+ Object.defineProperty(globalThis, "window", {+ value: peer,+ configurable: true,+ });+ try {+ setTrainingCompareHandoff("alice-private/confidential-finetune");+ installAccountTransitionListener(peer);+ const loginTab = {+ localStorage,+ sessionStorage: storage(),+ indexedDB: {+ deleteDatabase() {+ const request = {} as IDBOpenDBRequest;+ queueMicrotask(() => request.onsuccess?.call(request, {} as Event));+ return request;+ },+ },+ location: { replace() {} },+ } as unknown as Window;+ await transitionBrowserAccount(+ { username: "bob", accountId: "b1" },+ "/chat",+ () => localStorage.setItem("unsloth_auth_token", "bob-token"),+ loginTab,+ );+ listener!({+ key: BROWSER_ACCOUNT_KEY,+ oldValue: "account:a1:alice",+ newValue: localStorage.getItem(BROWSER_ACCOUNT_KEY),+ storageArea: localStorage,+ });+ assert.equal(reloads, 1);+ assert.equal(peerSession.getItem("unsloth_server_user_stopped"), "1");+ assert.equal(+ handoffAtReload,+ null,+ "Bob inherits Alice's pending training comparison",+ );+ } finally {+ if (priorWindow) Object.defineProperty(globalThis, "window", priorWindow);+ else delete (globalThis as { window?: Window }).window;+ }+});diff --git a/studio/frontend/tests/account-transition-peer-snapshot.test.ts b/studio/frontend/tests/account-transition-peer-snapshot.test.tsnew file mode 100644index 00000000000..3e2a2a9ee2a--- /dev/null+++ b/studio/frontend/tests/account-transition-peer-snapshot.test.ts@@ -0,0 +1,124 @@+// 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 { readFileSync } from "node:fs";+import { stripTypeScriptTypes } from "node:module";+import test from "node:test";+import vm from "node:vm";+import {+ BROWSER_ACCOUNT_KEY,+ installAccountTransitionListener,+ transitionBrowserAccount,+} from "../src/lib/account-transition.ts";++// Reuse the checked-in DOM/VM harness; execute the shipped snapshot script unchanged.+const sibling = readFileSync(+ new URL("./reload-snapshot.test.ts", import.meta.url),+ "utf8",+);+const harness = sibling.slice(+ sibling.indexOf("type Listener ="),+ sibling.indexOf("function storedSnapshot("),+);+const createEnvironment = new Function(+ "vm",+ "script",+ stripTypeScriptTypes(harness) + "\nreturn createEnvironment;",+)(+ vm,+ readFileSync(+ new URL("../public/reload-snapshot.js", import.meta.url),+ "utf8",+ ),+);++function storage(values: Map<string, string>): Storage {+ return {+ get length() {+ return values.size;+ },+ key: (i: number) => [...values.keys()][i] ?? null,+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => {+ values.set(key, value);+ },+ removeItem: (key: string) => {+ values.delete(key);+ },+ clear: () => values.clear(),+ };+}++for (const supportsPageSwap of [true, false]) {+ test(`account-switch reload must not paint Alice's chat for Bob (${supportsPageSwap ? "pageswap" : "pagehide"})`, async () => {+ const shared = new Map([+ [BROWSER_ACCOUNT_KEY, "account:a1:alice"],+ ["unsloth_auth_token", "alice-token"],+ ]);+ const localStorage = storage(shared);+ const outgoing = createEnvironment({+ navigationType: "navigate",+ localStorage: shared,+ supportsPageSwap,+ rootHtml: "<main>Alice confidential acquisition discussion</main>",+ styleSheets: ["/assets/index-abc123.css"],+ });+ let listener: (event: Partial<StorageEvent>) => void;+ let incoming: ReturnType<typeof createEnvironment> | undefined;+ const peer = {+ localStorage,+ sessionStorage: storage(outgoing.storage),+ addEventListener: (_type: string, fn: typeof listener) => {+ listener = fn;+ },+ location: {+ reload() {+ assert.equal(shared.get("unsloth_auth_token"), "bob-token");+ if (supportsPageSwap)+ outgoing.dispatch("pageswap", {+ activation: { navigationType: "reload" },+ });+ else outgoing.dispatch("pagehide", { persisted: false });+ incoming = createEnvironment({+ navigationType: "reload",+ storage: outgoing.storage,+ localStorage: shared,+ });+ incoming.loadStyleSheets();+ },+ },+ } as unknown as Window;+ installAccountTransitionListener(peer);+ const login = {+ localStorage,+ sessionStorage: storage(new Map()),+ indexedDB: {+ deleteDatabase() {+ const request = {} as IDBOpenDBRequest;+ queueMicrotask(() => request.onsuccess?.call(request, {} as Event));+ return request;+ },+ },+ location: { replace() {} },+ } as unknown as Window;+ await transitionBrowserAccount(+ { username: "bob", accountId: "b1" },+ "/chat",+ () => shared.set("unsloth_auth_token", "bob-token"),+ login,+ );+ listener!({+ key: BROWSER_ACCOUNT_KEY,+ oldValue: "account:a1:alice",+ newValue: shared.get(BROWSER_ACCOUNT_KEY),+ storageArea: localStorage,+ });+ assert.ok(incoming, "the peer reloaded with Bob's shared session");+ assert.doesNotMatch(+ incoming.shell?.html ?? "",+ /Alice confidential/,+ "Bob's reload paints Alice's private chat",+ );+ });+}diff --git a/studio/frontend/tests/account-transition.test.ts b/studio/frontend/tests/account-transition.test.tsnew file mode 100644index 00000000000..5eb9395652f--- /dev/null+++ b/studio/frontend/tests/account-transition.test.ts@@ -0,0 +1,573 @@+// 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 {+ ACCOUNT_CHROME_KEYS,+ ACCOUNT_DATABASES,+ BROWSER_ACCOUNT_FENCE_KEY,+ BROWSER_ACCOUNT_KEY,+ accountDatabaseName,+ accountTransitionPending,+ browserAccountMarker,+ installAccountTransitionListener,+ normalizeAccountUsername,+ resetFullAccessForMultiUser,+ transitionBrowserAccount,+} from "../src/lib/account-transition.ts";++function browserWith(+ values: Record<string, string> = {},+ databaseResult = "success",+ sessionValues: Record<string, string> = {},+) {+ const data = new Map(Object.entries(values));+ const sessionData = new Map(Object.entries(sessionValues));+ const removed: string[] = [];+ const deleted: string[] = [];+ const replaced: string[] = [];+ let reloads = 0;+ const listeners: ((event: Partial<StorageEvent>) => void)[] = [];+ const storage = {+ get length() {+ return data.size;+ },+ key: (index: number) => [...data.keys()][index] ?? null,+ getItem: (key: string) => data.get(key) ?? null,+ setItem: (key: string, value: string) => {+ data.set(key, value);+ },+ removeItem: (key: string) => {+ removed.push(key);+ data.delete(key);+ },+ } as Storage;+ const sessionStorage = {+ get length() {+ return sessionData.size;+ },+ key: (index: number) => [...sessionData.keys()][index] ?? null,+ getItem: (key: string) => sessionData.get(key) ?? null,+ setItem: (key: string, value: string) => {+ sessionData.set(key, value);+ },+ removeItem: (key: string) => {+ sessionData.delete(key);+ },+ } as Storage;+ const browser = {+ localStorage: storage,+ sessionStorage,+ indexedDB: {+ deleteDatabase: (name: string) => {+ deleted.push(name);+ const request = {} as IDBOpenDBRequest;+ queueMicrotask(() => {+ const callback =+ databaseResult === "blocked"+ ? request.onblocked+ : databaseResult === "error"+ ? request.onerror+ : request.onsuccess;+ callback?.call(request, {} as IDBVersionChangeEvent);+ });+ return request;+ },+ },+ location: {+ replace: (route: string) => {+ replaced.push(route);+ },+ reload: () => {+ reloads++;+ },+ },+ addEventListener: (+ _type: string,+ listener: (event: Partial<StorageEvent>) => void,+ ) => {+ listeners.push(listener);+ },+ } as unknown as Window;+ return {+ browser,+ data,+ sessionData,+ removed,+ deleted,+ replaced,+ listeners,+ reloads: () => reloads,+ };+}++for (const marker of [undefined, "unsloth"]) {+ test(`single-user login never purges, marker ${marker ?? "absent"}`, async () => {+ const b = browserWith({+ unsloth_chat_permission_mode: "full",+ "chat-draft:1": "keep",+ ...(marker ? { [BROWSER_ACCOUNT_KEY]: marker } : {}),+ });+ let committed = 0;+ assert.equal(+ await transitionBrowserAccount(+ " UNSLOTH ",+ "/chat",+ () => {+ committed++;+ },+ b.browser,+ ),+ false,+ );+ assert.equal(committed, 1);+ assert.deepEqual(b.removed, []);+ assert.deepEqual(b.deleted, []);+ assert.deepEqual(b.replaced, []);+ assert.equal(b.data.get("unsloth_chat_permission_mode"), "full");+ });+}++test("switch removes every content prefix and preserves only listed chrome and unrelated keys", async () => {+ const chrome = Object.fromEntries(+ [...ACCOUNT_CHROME_KEYS].map((key) => [key, "chrome"]),+ );+ const content = [+ "unsloth_auth_token",+ "unsloth_hf_token",+ "unsloth_new_feature",+ "unsloth_chat_permission_mode",+ "unsloth-profile",+ "chat-draft:1",+ "chat-draft-pastes:2",+ ];+ const b = browserWith({+ ...chrome,+ ...Object.fromEntries(content.map((key) => [key, "private"])),+ unrelated: "keep",+ "unsloth_web_update_dismissed:pip:1": "keep",+ [BROWSER_ACCOUNT_KEY]: "unsloth",+ });+ const changed = await transitionBrowserAccount(+ "Alice",+ "/change-password",+ () => {+ assert.deepEqual(b.deleted, [...ACCOUNT_DATABASES]);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "unsloth");+ b.data.set("unsloth_auth_token", "alice-token");+ },+ b.browser,+ );+ assert.equal(changed, true);+ // The fence is written before the tokens and lifted after the marker.+ assert.deepEqual(b.removed.sort(), [...content, BROWSER_ACCOUNT_FENCE_KEY].sort());+ for (const key of ACCOUNT_CHROME_KEYS)+ assert.equal(b.data.get(key), "chrome");+ assert.equal(b.data.get("unrelated"), "keep");+ assert.equal(b.data.get("unsloth_web_update_dismissed:pip:1"), "keep");+ assert.equal(b.data.get("unsloth_auth_token"), "alice-token");+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "alice");+ assert.deepEqual(b.replaced, ["/change-password"]);+});++test("a first managed login clears legacy owner data even without a marker", async () => {+ const b = browserWith({ "unsloth-old-content": "owner" });+ assert.equal(+ await transitionBrowserAccount("alice", "/chat", () => {}, b.browser),+ true,+ );+ assert.deepEqual(b.removed, ["unsloth-old-content", BROWSER_ACCOUNT_FENCE_KEY]);+});++test("same managed account keeps content and avoids IndexedDB work", async () => {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ "chat-draft:1": "alice",+ });+ await transitionBrowserAccount("ALICE", "/chat", () => {}, b.browser);+ assert.deepEqual(b.removed, []);+ assert.deepEqual(b.deleted, []);+ assert.deepEqual(b.replaced, []);+});++test("a username created again as a different account inherits nothing", async () => {+ const b = browserWith({});+ await transitionBrowserAccount(+ { username: "alice", accountId: "a1" },+ "/chat",+ () => {},+ b.browser,+ );+ b.data.set("chat-draft:1", "first alice");+ b.data.set("unsloth_hf_token", "first alice");+ const deletedOnFirstLogin = b.deleted.length;+ const changed = await transitionBrowserAccount(+ { username: "alice", accountId: "a2" },+ "/chat",+ () => {},+ b.browser,+ );+ assert.equal(changed, true);+ assert.equal(b.data.has("chat-draft:1"), false);+ assert.equal(b.data.has("unsloth_hf_token"), false);+ assert.deepEqual(b.deleted.slice(deletedOnFirstLogin), [+ ...ACCOUNT_DATABASES,+ ]);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "account:a2:alice");+});++test("one account keeps its data across a rename", async () => {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: browserAccountMarker({+ username: "alice",+ accountId: "a1",+ }),+ "chat-draft:1": "alice",+ });+ assert.equal(+ await transitionBrowserAccount(+ { username: "Alice2", accountId: "a1" },+ "/chat",+ () => {},+ b.browser,+ ),+ false,+ );+ assert.deepEqual(b.removed, []);+ assert.deepEqual(b.deleted, []);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "account:a1:alice2");+});++test("a marker written before account ids upgrades in place", async () => {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ "chat-draft:1": "alice",+ });+ assert.equal(+ await transitionBrowserAccount(+ { username: "alice", accountId: "a1" },+ "/chat",+ () => {},+ b.browser,+ ),+ false,+ );+ assert.deepEqual(b.removed, []);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "account:a1:alice");+});++test("a server that sends no account id keeps the session on the username", async () => {+ for (const account of [+ "alice",+ { username: "alice", accountId: null },+ ] as const) {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "account:a1:alice",+ "chat-draft:1": "alice",+ });+ assert.equal(+ await transitionBrowserAccount(account, "/chat", () => {}, b.browser),+ false,+ );+ assert.deepEqual(b.removed, []);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "alice");+ }+});++for (const marker of [undefined, "unsloth"]) {+ test(`an owner-only install never purges when ids arrive, marker ${marker ?? "absent"}`, async () => {+ const b = browserWith({+ "chat-draft:1": "keep",+ ...(marker ? { [BROWSER_ACCOUNT_KEY]: marker } : {}),+ });+ assert.equal(+ await transitionBrowserAccount(+ { username: "unsloth", accountId: "owner" },+ "/chat",+ () => {},+ b.browser,+ ),+ false,+ );+ assert.deepEqual(b.removed, []);+ assert.deepEqual(b.deleted, []);+ assert.deepEqual(b.replaced, []);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "account:owner:unsloth");+ });+}++test("a marker no build wrote can only compare as a different account", async () => {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "account:",+ "unsloth-private": "x",+ });+ assert.equal(+ await transitionBrowserAccount(+ { username: "alice", accountId: "a1" },+ "/chat",+ () => {},+ b.browser,+ ),+ true,+ );+ assert.equal(b.data.has("unsloth-private"), false);+});++test("returning to the owner clears the previous managed account", async () => {+ const b = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ "unsloth-private": "alice",+ });+ assert.equal(+ await transitionBrowserAccount("unsloth", "/chat", () => {}, b.browser),+ true,+ );+ assert.equal(b.data.has("unsloth-private"), false);+});++for (const failure of ["blocked", "error"]) {+ test(`IndexedDB ${failure} prevents new session publication and navigation`, async () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "unsloth" }, failure);+ let committed = false;+ await assert.rejects(+ transitionBrowserAccount(+ "alice",+ "/chat",+ () => {+ committed = true;+ },+ b.browser,+ ),+ );+ assert.equal(committed, false);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "unsloth");+ assert.deepEqual(b.replaced, []);+ });+}++test("cross-tab switches reload once, ignoring initial owner markers, removals and unrelated storage", () => {+ const b = browserWith();+ installAccountTransitionListener(b.browser);+ installAccountTransitionListener(b.browser);+ assert.equal(b.listeners.length, 1);+ const send = b.listeners[0];+ send({ key: BROWSER_ACCOUNT_KEY, oldValue: null, newValue: "unsloth" });+ send({ key: "unrelated", oldValue: "a", newValue: "b" });+ send({ key: BROWSER_ACCOUNT_KEY, oldValue: "alice", newValue: null });+ send({ key: BROWSER_ACCOUNT_KEY, oldValue: "alice", newValue: "ALICE" });+ send({+ key: BROWSER_ACCOUNT_KEY,+ oldValue: "unsloth",+ newValue: "alice",+ storageArea: {} as Storage,+ });+ assert.equal(b.reloads(), 0);+ send({+ key: BROWSER_ACCOUNT_KEY,+ oldValue: "unsloth",+ newValue: "alice",+ storageArea: b.browser.localStorage,+ });+ send({ key: BROWSER_ACCOUNT_KEY, oldValue: "alice", newValue: "bob" });+ assert.equal(b.reloads(), 1);+});++test("a switch fences peers before the new tokens and lifts the fence after the marker", async () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "unsloth", unsloth_auth_token: "alice-token" });+ let fenceAtCommit: string | null = null;+ await transitionBrowserAccount(+ { username: "bob", accountId: "b1" },+ "/chat",+ () => {+ fenceAtCommit = b.data.get(BROWSER_ACCOUNT_FENCE_KEY) ?? null;+ b.data.set("unsloth_auth_token", "bob-token");+ },+ b.browser,+ );+ assert.equal(fenceAtCommit, "account:b1:bob");+ assert.equal(b.data.has(BROWSER_ACCOUNT_FENCE_KEY), false);+ assert.equal(b.data.get(BROWSER_ACCOUNT_KEY), "account:b1:bob");+});++test("a peer holds requests from the fence until the marker reloads it", () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "unsloth" });+ installAccountTransitionListener(b.browser);+ const send = b.listeners[0];+ assert.equal(accountTransitionPending(), false);+ send({ key: BROWSER_ACCOUNT_FENCE_KEY, oldValue: null, newValue: "unsloth" });+ assert.equal(accountTransitionPending(), false);+ send({ key: BROWSER_ACCOUNT_FENCE_KEY, oldValue: null, newValue: "account:b1:bob" });+ assert.equal(accountTransitionPending(), true);+ assert.equal(b.reloads(), 0);+ send({ key: BROWSER_ACCOUNT_KEY, oldValue: "unsloth", newValue: "account:b1:bob" });+ assert.equal(b.reloads(), 1);+ send({ key: BROWSER_ACCOUNT_FENCE_KEY, oldValue: "account:b1:bob", newValue: null });+ assert.equal(b.reloads(), 1);+});++test("cross-tab reloads follow the account id, not the name", () => {+ const upgrade = browserWith();+ installAccountTransitionListener(upgrade.browser);+ upgrade.listeners[0]({+ key: BROWSER_ACCOUNT_KEY,+ oldValue: "alice",+ newValue: "account:a1:alice",+ storageArea: upgrade.browser.localStorage,+ });+ assert.equal(upgrade.reloads(), 0);+ const recreated = browserWith();+ installAccountTransitionListener(recreated.browser);+ recreated.listeners[0]({+ key: BROWSER_ACCOUNT_KEY,+ oldValue: "account:a1:alice",+ newValue: "account:a2:alice",+ storageArea: recreated.browser.localStorage,+ });+ assert.equal(recreated.reloads(), 1);+});++test("a marker carries the account id and the normalized name", () => {+ assert.equal(browserAccountMarker(" ALICE "), "alice");+ assert.equal(+ browserAccountMarker({ username: " ALICE ", accountId: "a1" }),+ "account:a1:alice",+ );+ assert.throws(() =>+ browserAccountMarker({ username: " ", accountId: "a1" }),+ );+});++test("multi-user policy resets full while preserving other permission modes", () => {+ const b = browserWith({ unsloth_chat_permission_mode: "full" });+ resetFullAccessForMultiUser(b.browser.localStorage);+ assert.equal(b.data.get("unsloth_chat_permission_mode"), "auto");+ for (const mode of ["ask", "auto", "off"]) {+ b.data.set("unsloth_chat_permission_mode", mode);+ resetFullAccessForMultiUser(b.browser.localStorage);+ assert.equal(b.data.get("unsloth_chat_permission_mode"), mode);+ }+});++test("username normalization matches the ASCII names the backend can store", () => {+ for (const [input, expected] of [+ [" UNSLOTH ", "unsloth"],+ ["Alice_01", "alice_01"],+ ["BOB-2", "bob-2"],+ [" Straße ", "straße"],+ ])+ assert.equal(normalizeAccountUsername(input), expected);+});++test("a legacy marker still compares on the name when neither side has an id", async () => {+ const same = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ "unsloth-private": "alice",+ });+ assert.equal(+ await transitionBrowserAccount(" ALICE ", "/chat", () => {}, same.browser),+ false,+ );+ assert.equal(same.data.get("unsloth-private"), "alice");+ const other = browserWith({+ [BROWSER_ACCOUNT_KEY]: "alice",+ "unsloth-private": "alice",+ });+ assert.equal(+ await transitionBrowserAccount("bob", "/chat", () => {}, other.browser),+ true,+ );+ assert.equal(other.data.has("unsloth-private"), false);+});++test("switching accounts clears the legacy browser-only chat store", async () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "unsloth" });+ await transitionBrowserAccount("alice", "/chat", () => {}, b.browser);+ assert.ok(b.deleted.includes("unsloth-chat"));+});++test("the owner's own first login keeps the legacy chat store to import", async () => {+ const b = browserWith({});+ await transitionBrowserAccount("unsloth", "/chat", () => {}, b.browser);+ assert.deepEqual(b.deleted, []);+});++test("switching accounts clears session content and keeps neutral session flags", async () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "alice" }, "success", {+ "chat:training-compare-handoff:v1": JSON.stringify({+ intent: "compare",+ baseModel: "alice-private/base",+ requestedAt: Date.now(),+ }),+ "unsloth.reload-snapshot.v1": "<div>alice</div>",+ "data-recipes:open-learning-recipes": "1",+ // USER_STOPPED_KEY: neutral, and clearing it would restart a server the user stopped.+ unsloth_server_user_stopped: "1",+ });+ assert.equal(+ await transitionBrowserAccount("bob", "/chat", () => {}, b.browser),+ true,+ );+ assert.equal(b.sessionData.has("chat:training-compare-handoff:v1"), false);+ assert.equal(b.sessionData.has("unsloth.reload-snapshot.v1"), false);+ assert.equal(b.sessionData.has("data-recipes:open-learning-recipes"), false);+ assert.equal(b.sessionData.get("unsloth_server_user_stopped"), "1");+});++test("the same account keeps a pending compare handoff", async () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "alice" }, "success", {+ "chat:training-compare-handoff:v1": "pending",+ });+ assert.equal(+ await transitionBrowserAccount("ALICE", "/chat", () => {}, b.browser),+ false,+ );+ assert.equal(+ b.sessionData.get("chat:training-compare-handoff:v1"),+ "pending",+ );+});++test("unreadable session storage never fails a sign-in", async () => {+ const b = browserWith({ [BROWSER_ACCOUNT_KEY]: "alice" });+ Object.defineProperty(b.browser, "sessionStorage", {+ get() {+ throw new Error("blocked");+ },+ });+ assert.equal(+ await transitionBrowserAccount("bob", "/chat", () => {}, b.browser),+ true,+ );+});++test("saved recipes live in a per-account store and are never purged", () => {+ assert.equal(+ ACCOUNT_DATABASES.includes("unsloth-data-recipes" as never),+ false,+ );+ const stored = (marker: string | null) => ({ getItem: () => marker });+ assert.equal(+ accountDatabaseName("unsloth-data-recipes", stored(null)),+ "unsloth-data-recipes",+ );+ assert.equal(+ accountDatabaseName("unsloth-data-recipes", stored("unsloth")),+ "unsloth-data-recipes",+ );+ assert.equal(+ accountDatabaseName(+ "unsloth-data-recipes",+ stored("account:owner:unsloth"),+ ),+ "unsloth-data-recipes",+ );+ assert.equal(+ accountDatabaseName("unsloth-data-recipes", stored("account:a1:alice")),+ "unsloth-data-recipes:a1",+ );+ assert.equal(+ accountDatabaseName("unsloth-data-recipes", stored("alice")),+ "unsloth-data-recipes:alice",+ );+});diff --git a/studio/frontend/tests/accounts-api.test.ts b/studio/frontend/tests/accounts-api.test.tsnew file mode 100644index 00000000000..e14b4f6c3e5--- /dev/null+++ b/studio/frontend/tests/accounts-api.test.ts@@ -0,0 +1,148 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";+import { normalizeAccountUsername } from "../src/lib/account-transition.ts";+import * as formatFastApiError from "../src/lib/format-fastapi-error.ts";+import type * as AccountsApi from "../src/features/settings/api/accounts.ts";++function client(response: () => Response) {+ const requests: { path: string; init?: RequestInit }[] = [];+ let refreshed = 0;+ const api = loadWithStubs<typeof AccountsApi>(+ new URL("../src/features/settings/api/accounts.ts", import.meta.url),+ {+ "@/features/auth": {+ authFetch: async (path: string, init?: RequestInit) => {+ requests.push({ path, init });+ return response();+ },+ },+ "@/features/auth/login-client": {+ fetchAuthStatus: async () => {+ refreshed++;+ },+ },+ "@/lib/account-transition": { normalizeAccountUsername },+ "@/lib/format-fastapi-error": formatFastApiError,+ },+ );+ return { api, requests, refreshed: () => refreshed };+}++test("lists accounts through authenticated fetch", async () => {+ const accounts = [+ {+ account_id: "owner",+ username: "unsloth",+ role: "owner",+ is_active: true,+ },+ ];+ const c = client(() => Response.json({ accounts }));+ assert.deepEqual(await c.api.fetchAccounts(), accounts);+ assert.deepEqual(c.requests, [{ path: "/api/accounts", init: undefined }]);+});++const backendSetup = (setup_code: string) => ({+ account: {+ account_id: "alice-id",+ username: "alice",+ role: "user",+ is_active: true,+ created_at: "2026-09-06T12:00:00Z",+ setup_code_pending: true,+ },+ setup_code,+ setup_code_expires_at: "2026-09-06T13:00:00Z",+});++test("creation sends normalized username and returns one-time code and expiry", async () => {+ const setup = {+ account_id: "alice-id",+ username: "alice",+ setup_code: "one-time-code",+ expires_at: "2026-09-06T13:00:00Z",+ };+ const c = client(() => Response.json(backendSetup("one-time-code")));+ assert.deepEqual(await c.api.createAccount(" ALICE "), setup);+ assert.deepEqual(c.requests[0], {+ path: "/api/accounts",+ init: {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ username: "alice" }),+ },+ });+ assert.equal(c.refreshed(), 1);+});++test("regeneration is keyed by the account id, encoded as one path segment", async () => {+ const setup = {+ account_id: "alice-id",+ username: "alice",+ setup_code: "new-code",+ expires_at: "2026-09-06T13:00:00Z",+ };+ const c = client(() => Response.json(backendSetup("new-code")));+ assert.deepEqual(await c.api.regenerateSetupCode("a/b?"), setup);+ assert.deepEqual(c.requests[0], {+ path: "/api/accounts/a%2Fb%3F/setup-code",+ init: { method: "POST" },+ });+});++test("deactivate, reactivate and delete accept empty success bodies and refresh policy", async () => {+ const c = client(() => new Response(null, { status: 204 }));+ await c.api.setAccountActive("alice-id", false);+ await c.api.setAccountActive("alice-id", true);+ await c.api.deleteAccount("alice-id");+ const patch = (active: boolean) => ({+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ is_active: active }),+ });+ assert.deepEqual(c.requests, [+ { path: "/api/accounts/alice-id", init: patch(false) },+ { path: "/api/accounts/alice-id", init: patch(true) },+ { path: "/api/accounts/alice-id", init: { method: "DELETE" } },+ ]);+ assert.equal(c.refreshed(), 3);+});++test("authorization, conflict and validation failures are shown without reporting success", async () => {+ for (const status of [403, 404, 409, 422]) {+ const c = client(() =>+ Response.json({ detail: "Account operation rejected" }, { status }),+ );+ await assert.rejects(+ c.api.createAccount("alice"),+ /Account operation rejected/,+ );+ assert.equal(c.refreshed(), 0);+ }+ const c = client(() => new Response("bad gateway", { status: 502 }));+ await assert.rejects(c.api.fetchAccounts(), /Account request failed \(502\)/);+});++test("a rejected username reports the field error FastAPI sends as an array", async () => {+ const c = client(() =>+ Response.json(+ {+ detail: [+ {+ loc: ["body", "username"],+ msg: "Value error, Username must contain 3 to 32 letters, digits, - or _.",+ },+ ],+ },+ { status: 422 },+ ),+ );+ await assert.rejects(+ c.api.createAccount("bad.name"),+ /username: Value error, Username must contain 3 to 32 letters/,+ );+});diff --git a/studio/frontend/tests/auth-fetch-timezone.test.ts b/studio/frontend/tests/auth-fetch-timezone.test.tsindex de0739fb8e1..f83a58e7e7f 100644--- a/studio/frontend/tests/auth-fetch-timezone.test.ts+++ b/studio/frontend/tests/auth-fetch-timezone.test.ts@@ -23,6 +23,7 @@ test("authFetch sends the browser timezone", async () => {new URL("../src/features/auth/api.ts", import.meta.url),{"@/lib/api-base": { apiUrl: (path: string) => path, isTauri: false },+ "@/lib/account-transition": { accountTransitionPending: () => false },"./session": {clearAuthTokens: () => {},getAuthToken: () => "access-token",diff --git a/studio/frontend/tests/hub-progress-token-boundary.test.ts b/studio/frontend/tests/hub-progress-token-boundary.test.tsindex da2ec818bc7..7045f29d534 100644--- a/studio/frontend/tests/hub-progress-token-boundary.test.ts+++ b/studio/frontend/tests/hub-progress-token-boundary.test.ts@@ -28,6 +28,7 @@ async function emittedHeaders(init?: RequestInit): Promise<Headers> {new URL("../src/features/auth/api.ts", import.meta.url),{"@/lib/api-base": { apiUrl: (path: string) => path, isTauri: false },+ "@/lib/account-transition": { accountTransitionPending: () => false },"./session": {clearAuthTokens: () => {},getAuthToken: () => "access-token",diff --git a/studio/frontend/tests/login-account-modes.test.ts b/studio/frontend/tests/login-account-modes.test.tsnew file mode 100644index 00000000000..6a9969ea3b3--- /dev/null+++ b/studio/frontend/tests/login-account-modes.test.ts@@ -0,0 +1,566 @@+// 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, { type TestContext } from "node:test";+import {+ loadWithStubs,+ stubJsxRuntime,+ type StubElement,+} from "./helpers/module-stubs.ts";+import * as transition from "../src/lib/account-transition.ts";+import * as deadline from "../src/features/auth/bootstrap-deadline.ts";+import type * as LoginClient from "../src/features/auth/login-client.ts";+import type * as AccountSession from "../src/features/auth/account-session.ts";++const formUrl = new URL(+ "../src/features/auth/components/auth-form.tsx",+ import.meta.url,+);+const clientUrl = new URL(+ "../src/features/auth/login-client.ts",+ import.meta.url,+);+const accountUrl = new URL(+ "../src/features/auth/account-session.ts",+ import.meta.url,+);+const base = { apiUrl: (path: string) => path };+const token = {+ access_token: "access",+ refresh_token: "refresh",+ must_change_password: false,+ account_id: "a1",+};++function elements(node: unknown): StubElement[] {+ if (Array.isArray(node)) return node.flatMap(elements);+ if (!node || typeof node !== "object" || !("props" in node)) return [];+ const element = node as StubElement;+ return [element, ...elements(element.props.children)];+}+function textContent(node: unknown): string {+ if (typeof node === "string") return node;+ if (Array.isArray(node)) return node.map(textContent).join(" ");+ if (node && typeof node === "object" && "props" in node)+ return textContent((node as StubElement).props.children);+ return "";+}+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));++function mountForm(+ client: typeof LoginClient,+ session: { access: string | null; change: boolean; owner?: boolean },+ switched = false,+ failTransitionOnce = false,+) {+ const state: unknown[] = [];+ let cursor = 0;+ const effects: (() => void)[] = [];+ const routes: string[] = [];+ const transitions: string[] = [];+ const api = loadWithStubs<{+ AuthForm: (props: { mode: string }) => StubElement | null;+ }>(formUrl, {+ "react/jsx-runtime": stubJsxRuntime(),+ react: {+ useState: (initial: unknown) => {+ const index = cursor++;+ if (!(index in state))+ state[index] = typeof initial === "function" ? initial() : initial;+ return [+ state[index],+ (value: unknown) => {+ state[index] =+ typeof value === "function" ? value(state[index]) : value;+ },+ ];+ },+ useRef: (current: unknown) => {+ const index = cursor++;+ if (!(index in state)) state[index] = { current };+ return state[index];+ },+ useEffect: (effect: () => void) => {+ effects.push(effect);+ },+ },+ "@/components/app-readiness": { useAppShellReadySignal: () => () => {} },+ "@/lib/api-base": base,+ "@/lib/account-transition": {+ normalizeAccountUsername: transition.normalizeAccountUsername,+ transitionBrowserAccount: async (+ account: transition.BrowserAccount | string,+ route: string,+ commit: () => void,+ ) => {+ // Transitions key on the immutable account id when the server sent one, since usernames are reusable.+ const identity =+ typeof account === "string"+ ? { username: account, accountId: null }+ : account;+ transitions.push(+ `${identity.username}@${identity.accountId ?? "none"}:${route}`,+ );+ if (failTransitionOnce && transitions.length === 1)+ throw new Error("Close other Unsloth tabs and retry");+ commit();+ return switched;+ },+ },+ "../account-session": {+ useLoginMode: client.getLoginMode,+ sessionAccount: () =>+ session.access+ ? { username: "alice", isOwner: session.owner ?? false }+ : null,+ },+ "../login-client": client,+ "@/components/ui/button": { Button: "Button" },+ "@/components/mascot-img": { MascotImg: "MascotImg" },+ "@/components/ui/input": { Input: "Input" },+ "@/components/ui/label": { Label: "Label" },+ "@tanstack/react-router": {+ Link: "Link",+ useNavigate:+ () =>+ ({ to }: { to: string }) => {+ routes.push(to);+ },+ },+ "lucide-react": { Eye: "Eye", EyeOff: "EyeOff" },+ "../api": { refreshSession: async () => true },+ "../bootstrap-deadline": deadline,+ "../session": {+ clearAuthTokens: () => {+ session.access = null;+ },+ getAuthToken: () => session.access,+ hasAuthToken: () => Boolean(session.access),+ hasRefreshToken: () => false,+ getPostAuthRoute: () => (session.change ? "/change-password" : "/chat"),+ mustChangePassword: () => session.change,+ setMustChangePassword: (change: boolean) => {+ session.change = change;+ },+ storeAuthTokens: (access: string) => {+ session.access = access;+ },+ },+ });+ const render = (mode = "login") => {+ cursor = 0;+ return api.AuthForm({ mode });+ };+ return {+ render,+ routes,+ transitions,+ initialize: async (mode = "login") => {+ render(mode);+ for (const effect of effects.splice(0)) effect();+ await tick();+ return render(mode);+ },+ };+}++function client() {+ return loadWithStubs<typeof LoginClient>(clientUrl, {+ "@/lib/api-base": base,+ "@/lib/account-transition": transition,+ });+}+function environment(t: TestContext) {+ const previousFetch = globalThis.fetch;+ const previousWindow = globalThis.window;+ const values = new Map<string, string>();+ globalThis.window = {+ dispatchEvent: () => true,+ localStorage: {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => {+ values.set(key, value);+ },+ removeItem: (key: string) => {+ values.delete(key);+ },+ },+ } as unknown as Window & typeof globalThis;+ t.after(() => {+ globalThis.fetch = previousFetch;+ globalThis.window = previousWindow;+ });+}++for (const mode of ["single", "multi"] as const) {+ test(`${mode} form renders the correct username fields and setup hint`, async (t) => {+ environment(t);+ globalThis.fetch = async () =>+ Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: mode,+ });+ const form = mountForm(client(), { access: null, change: false });+ const tree = await form.initialize();+ const username = elements(tree).find(+ (element) => element.props.id === "username",+ );+ assert.equal(Boolean(username), mode === "multi");+ if (username) assert.equal(username.props.autoComplete, "username");+ const password = elements(tree).find(+ (element) => element.props.id === "password",+ );+ assert.equal(password?.props.autoComplete, "current-password");+ assert.equal(+ textContent(tree).includes("setup code your administrator"),+ mode === "multi",+ );+ assert.deepEqual(form.routes, []);+ });+}++test("single mode still posts unsloth and does not refetch on success", async (t) => {+ environment(t);+ const requests: unknown[] = [];+ globalThis.fetch = async (path, init) => {+ requests.push([path, JSON.parse(String(init?.body))]);+ return Response.json(token);+ };+ assert.deepEqual(+ await client().loginFromForm("single", "ignored", "owner-password"),+ token,+ );+ assert.deepEqual(requests, [+ ["/api/auth/login", { username: "unsloth", password: "owner-password" }],+ ]);+});++test("multi mode case folds and trims username without changing password", async (t) => {+ environment(t);+ let sent: unknown;+ globalThis.fetch = async (_path, init) => {+ sent = JSON.parse(String(init?.body));+ return Response.json(token);+ };+ await client().loginFromForm("multi", " ALIce ", "Keep-CaSe ");+ assert.deepEqual(sent, { username: "alice", password: "Keep-CaSe " });+});++test("401 after a second account is created rerenders username entry without showing the error", async (t) => {+ environment(t);+ let statusReads = 0;+ globalThis.fetch = async (path) =>+ String(path).endsWith("/status")+ ? Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: ++statusReads === 1 ? "single" : "multi",+ })+ : Response.json({ detail: "bad password" }, { status: 401 });+ const form = mountForm(client(), { access: null, change: false });+ let tree = await form.initialize();+ const submit = elements(tree).find((element) => element.type === "form")+ ?.props.onSubmit as (event: unknown) => Promise<void>;+ await submit({ preventDefault() {} });+ tree = form.render();+ assert.ok(elements(tree).find((element) => element.props.id === "username"));+ assert.ok(!textContent(tree).includes("bad password"));+ assert.equal(statusReads, 2);+});++test("other login failures preserve the server error and only single-mode 401 probes status", async (t) => {+ environment(t);+ for (const [mode, status, reads] of [+ ["multi", 401, 1],+ ["single", 429, 1],+ ["single", 401, 2],+ ] as const) {+ let count = 0;+ globalThis.fetch = async (path) => {+ count++;+ return String(path).endsWith("/status")+ ? Response.json({ login_mode: "single" })+ : Response.json({ detail: "Server detail" }, { status });+ };+ await assert.rejects(+ client().loginFromForm(mode, "alice", "password"),+ /Server detail/,+ );+ assert.equal(count, reads);+ }+});++for (const owner of [false, true]) {+ test(`managed setup follows the token requirement despite public owner status, owner ${owner}`, async (t) => {+ environment(t);+ globalThis.fetch = async () =>+ Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: "multi",+ });+ const session = { access: "setup-session", change: true, owner };+ const form = mountForm(client(), session);+ const tree = await form.initialize("change-password");+ assert.ok(+ elements(tree).find((element) => element.props.id === "new-password"),+ );+ assert.equal(/setup code/i.test(textContent(tree)), !owner);+ assert.equal(+ elements(tree).find((element) => element.props.id === "current-password")+ ?.props["aria-describedby"],+ owner ? undefined : "current-setup-code-hint",+ );+ assert.equal(session.change, true);+ assert.deepEqual(form.routes, []);+ });+}++test("owner bootstrap still redirects single-mode login to password setup", async (t) => {+ environment(t);+ globalThis.fetch = async () =>+ Response.json({+ initialized: true,+ requires_password_change: true,+ login_mode: "single",+ });+ const form = mountForm(client(), { access: null, change: false });+ await form.initialize();+ assert.deepEqual(form.routes, ["/change-password"]);+});++test("successful login commits through transition and avoids SPA navigation when replacing", async (t) => {+ environment(t);+ globalThis.fetch = async (path) =>+ String(path).endsWith("/status")+ ? Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: "multi",+ })+ : Response.json({ ...token, must_change_password: true });+ const session = { access: null as string | null, change: false };+ const form = mountForm(client(), session, true);+ let tree = await form.initialize();+ const change = elements(tree).find(+ (element) => element.props.id === "username",+ )?.props.onChange as (event: unknown) => void;+ change({ target: { value: "alice" } });+ tree = form.render();+ const submit = elements(tree).find((element) => element.type === "form")+ ?.props.onSubmit as (event: unknown) => Promise<void>;+ await submit({ preventDefault() {} });+ assert.deepEqual(form.transitions, ["alice@a1:/change-password"]);+ assert.equal(session.change, true);+ assert.equal(session.access, "access");+ assert.deepEqual(form.routes, []);+});++test("owner visibility uses the authenticated subject or role and fails closed", () => {+ const session = loadWithStubs<typeof AccountSession>(accountUrl, {+ react: {},+ "./login-client": {},+ "./session": {},+ });+ const jwt = (payload: unknown) =>+ `e30.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.sig`;+ assert.equal(session.sessionAccount(jwt({ sub: "unsloth" }))?.isOwner, true);+ assert.equal(+ session.sessionAccount(jwt({ sub: "alice", role: "user" }))?.isOwner,+ false,+ );+ assert.equal(+ session.sessionAccount(jwt({ sub: "unsloth", role: "user" }))?.isOwner,+ false,+ );+ assert.equal(session.sessionAccount("malformed"), null);+ assert.equal(session.sessionAccount(null), null);+});++test("cleanup retries reuse an issued setup session without consuming the code again", async (t) => {+ environment(t);+ let logins = 0;+ globalThis.fetch = async (path) => {+ if (String(path).endsWith("/status"))+ return Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: "multi",+ });+ logins++;+ return Response.json({ ...token, must_change_password: true });+ };+ const session = { access: null as string | null, change: false };+ const form = mountForm(client(), session, true, true);+ let tree = await form.initialize();+ const username = elements(tree).find(+ (element) => element.props.id === "username",+ );+ (username?.props.onChange as (event: unknown) => void)({+ target: { value: "alice" },+ });+ for (let attempt = 0; attempt < 2; attempt++) {+ tree = form.render();+ const submit = elements(tree).find((element) => element.type === "form")+ ?.props.onSubmit as (event: unknown) => Promise<void>;+ await submit({ preventDefault() {} });+ if (attempt === 0) {+ assert.equal(session.access, null);+ assert.match(textContent(form.render()), /Close other Unsloth tabs/);+ }+ }+ assert.equal(logins, 1);+ assert.equal(session.access, "access");+ assert.equal(form.transitions.length, 2);+});++test("an owner-only browser never adds a startup status probe or changes stored preferences", async (t) => {+ environment(t);+ globalThis.fetch = async () => {+ assert.fail("single-user startup must not probe status");+ };+ const api = client();+ assert.equal(api.getLoginMode(), "single");+ api.ensureLoginMode();+ await tick();+ assert.equal(window.localStorage.getItem(api.LOGIN_MODE_HINT_KEY), null);+});++test("multi-user policy survives document reloads and revalidates only multi-user hints", async (t) => {+ environment(t);+ const first = client();+ first.setLoginMode("multi");+ const reloaded = client();+ assert.equal(reloaded.getLoginMode(), "multi");+ let requests = 0;+ globalThis.fetch = async () => {+ requests++;+ return Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: "multi",+ });+ };+ reloaded.ensureLoginMode();+ await tick();+ assert.equal(requests, 1);+});++test("creating an account hides full access in peer tabs without a status request", (t) => {+ environment(t);+ globalThis.fetch = async () => {+ assert.fail("storage synchronization must not fetch status");+ };+ const handlers = new Set<(event: Partial<StorageEvent>) => void>();+ window.addEventListener = ((+ _name: string,+ handler: (event: Partial<StorageEvent>) => void,+ ) => {+ handlers.add(handler);+ }) as typeof window.addEventListener;+ window.removeEventListener = ((+ _name: string,+ handler: (event: Partial<StorageEvent>) => void,+ ) => {+ handlers.delete(handler);+ }) as typeof window.removeEventListener;+ const api = client();+ let notified = 0;+ const unsubscribe = api.subscribeLoginMode(() => {+ notified++;+ });+ for (const handler of handlers)+ handler({+ key: api.LOGIN_MODE_HINT_KEY,+ oldValue: null,+ newValue: "multi",+ });+ assert.equal(api.getLoginMode(), "multi");+ assert.equal(notified, 1);+ for (const handler of handlers)+ handler({+ key: api.LOGIN_MODE_HINT_KEY,+ oldValue: "multi",+ newValue: null,+ });+ assert.equal(api.getLoginMode(), "multi");+ unsubscribe();+ assert.equal(handlers.size, 0);+});++test("a deactivated account keeps full access hidden while the form is back in single mode", async (t) => {+ environment(t);+ window.localStorage.setItem("unsloth_chat_permission_mode", "full");+ const api = client();+ assert.equal(api.getFullAccessAllowed(), true);+ globalThis.fetch = async () =>+ Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: "single",+ full_access: false,+ });+ await api.fetchAuthStatus();+ assert.equal(api.getLoginMode(), "single");+ assert.equal(api.getFullAccessAllowed(), false);+ assert.equal(+ window.localStorage.getItem("unsloth_chat_permission_mode"),+ "auto",+ );+ assert.equal(window.localStorage.getItem(api.LOGIN_MODE_HINT_KEY), "restricted");+ const reloaded = client();+ assert.equal(reloaded.getLoginMode(), "single");+ assert.equal(reloaded.getFullAccessAllowed(), false);+ api.setLoginMode("single");+ assert.equal(api.getFullAccessAllowed(), false);+ globalThis.fetch = async () =>+ Response.json({+ initialized: true,+ requires_password_change: false,+ login_mode: "single",+ full_access: true,+ });+ reloaded.ensureLoginMode();+ await tick();+ assert.equal(reloaded.getFullAccessAllowed(), true);+ await api.fetchAuthStatus();+ assert.equal(api.getFullAccessAllowed(), true);+ assert.equal(window.localStorage.getItem(api.LOGIN_MODE_HINT_KEY), null);+ api.setLoginMode("multi");+ assert.equal(api.getFullAccessAllowed(), false);+});++test("a deactivated account hides full access in peer tabs without changing the login form", (t) => {+ environment(t);+ const handlers = new Set<(event: Partial<StorageEvent>) => void>();+ window.addEventListener = ((+ _name: string,+ handler: (event: Partial<StorageEvent>) => void,+ ) => {+ handlers.add(handler);+ }) as typeof window.addEventListener;+ window.removeEventListener = ((+ _name: string,+ handler: (event: Partial<StorageEvent>) => void,+ ) => {+ handlers.delete(handler);+ }) as typeof window.removeEventListener;+ const api = client();+ let notified = 0;+ const unsubscribe = api.subscribeLoginMode(() => {+ notified++;+ });+ for (const handler of handlers)+ handler({+ key: api.LOGIN_MODE_HINT_KEY,+ oldValue: null,+ newValue: "restricted",+ });+ assert.equal(api.getLoginMode(), "single");+ assert.equal(api.getFullAccessAllowed(), false);+ assert.equal(notified, 1);+ unsubscribe();+ assert.equal(handlers.size, 0);+});diff --git a/studio/frontend/tests/settings-tab-visibility.test.ts b/studio/frontend/tests/settings-tab-visibility.test.tsnew file mode 100644index 00000000000..e6bd14078e2--- /dev/null+++ b/studio/frontend/tests/settings-tab-visibility.test.ts@@ -0,0 +1,30 @@+// 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 {+ OWNER_ONLY_SETTINGS_TABS,+ resolveSettingsTab,+ settingsTabVisible,+} from "../src/features/settings/settings-tab-visibility.ts";+import { SETTINGS_TABS } from "../src/features/settings/stores/settings-dialog-store.ts";++test("the owner sees every settings tab", () => {+ for (const tab of SETTINGS_TABS) {+ assert.equal(settingsTabVisible(tab, true), true, tab);+ assert.equal(resolveSettingsTab(tab, true), tab);+ }+});++test("a managed account never sees a tab whose routes are all owner-only", () => {+ const hidden = SETTINGS_TABS.filter((tab) => !settingsTabVisible(tab, false));+ assert.deepEqual(new Set(hidden), OWNER_ONLY_SETTINGS_TABS);+ for (const tab of ["accounts", "resources", "remote-lan", "agents", "debugging"] as const) {+ assert.ok(OWNER_ONLY_SETTINGS_TABS.has(tab), tab);+ assert.equal(resolveSettingsTab(tab, false), "general");+ }+ for (const tab of ["general", "api-keys", "data", "chat", "connections"] as const) {+ assert.equal(resolveSettingsTab(tab, false), tab);+ }+});diff --git a/studio/frontend/tests/tts-custom-connections-disabled.test.ts b/studio/frontend/tests/tts-custom-connections-disabled.test.tsindex d5490dacdf6..525d63339ca 100644--- a/studio/frontend/tests/tts-custom-connections-disabled.test.ts+++ b/studio/frontend/tests/tts-custom-connections-disabled.test.ts@@ -268,6 +268,7 @@ test("authFetch invokes its policy guard after refresh and before retry", asyncnew URL("../src/features/auth/api.ts", import.meta.url),{"@/lib/api-base": { apiUrl: (path: string) => path, isTauri: false },+ "@/lib/account-transition": { accountTransitionPending: () => false },"./session": {clearAuthTokens: () => {accessToken = null;diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rsindex 536c8c2e2b3..ed89b5c8ddf 100644--- a/studio/src-tauri/src/desktop_auth.rs+++ b/studio/src-tauri/src/desktop_auth.rs@@ -8,10 +8,46 @@ use std::path::{Path, PathBuf};static DESKTOP_AUTH_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());-#[derive(Debug, Serialize)]-pub struct DesktopAuthResponse {- pub access_token: String,- pub refresh_token: String,+#[derive(Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum DesktopAuthResponse {+ LoginRequired {+ login_required: LoginRequired,+ login_mode: MultiLoginMode,+ },+ Tokens {+ access_token: String,+ refresh_token: String,+ },+}++// Literal values keep malformed successful responses from becoming a session.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(try_from = "bool", into = "bool")]+pub struct LoginRequired;++impl TryFrom<bool> for LoginRequired {+ type Error = &'static str;++ fn try_from(value: bool) -> Result<Self, Self::Error> {+ if value {+ Ok(Self)+ } else {+ Err("login_required must be true")+ }+ }+}++impl From<LoginRequired> for bool {+ fn from(_: LoginRequired) -> Self {+ true+ }+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub enum MultiLoginMode {+ #[serde(rename = "multi")]+ Multi,}#[derive(Debug, Serialize, Deserialize)]@@ -19,12 +55,6 @@ struct DesktopAuthRequest {secret: String,}-#[derive(Debug, Deserialize)]-struct TokenResponse {- access_token: String,- refresh_token: String,-}-#[derive(Clone, Copy, Debug, Eq, PartialEq)]enum PortSource {Cached,@@ -213,14 +243,9 @@ async fn exchange_desktop_secret(}response- .json::<TokenResponse>()+ .json::<DesktopAuthResponse>().await- .map(|tokens| {- Some(DesktopAuthResponse {- access_token: tokens.access_token,- refresh_token: tokens.refresh_token,- })- })+ .map(Some).map_err(|e| AuthError::Failed(format!("Desktop auth failed: {}", e)))}@@ -379,22 +404,69 @@ mod tests {use tokio::net::TcpListener;async fn login_server(status: &str) -> u16 {+ login_server_with_body(status, "").await+ }++ async fn login_server_with_body(status: &str, body: &str) -> u16 {let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let port = listener.local_addr().unwrap().port();let status = status.to_string();+ let body = body.to_string();tokio::spawn(async move {let (mut stream, _) = listener.accept().await.unwrap();let mut buffer = [0; 1024];let _ = stream.read(&mut buffer).await.unwrap();- let response =- format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");+ let response = format!(+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );stream.write_all(response.as_bytes()).await.unwrap();});port}+ #[tokio::test]+ async fn desktop_login_required_is_a_success_without_tokens() {+ let body = r#"{"login_required":true,"login_mode":"multi"}"#;+ let port = login_server_with_body("200 OK", body).await;+ let response = exchange_desktop_secret(&Client::new(), port, "desktop-secret")+ .await+ .unwrap()+ .unwrap();+ assert!(matches!(response, DesktopAuthResponse::LoginRequired { .. }));+ assert_eq!(serde_json::to_string(&response).unwrap(), body);+ }++ #[tokio::test]+ async fn desktop_single_account_keeps_the_token_response_bytes() {+ let body = r#"{"access_token":"access","refresh_token":"refresh","token_type":"bearer","must_change_password":false}"#;+ let port = login_server_with_body("200 OK", body).await;+ let response = exchange_desktop_secret(&Client::new(), port, "desktop-secret")+ .await+ .unwrap()+ .unwrap();+ assert!(matches!(response, DesktopAuthResponse::Tokens { .. }));+ assert_eq!(+ serde_json::to_string(&response).unwrap(),+ r#"{"access_token":"access","refresh_token":"refresh"}"#+ );+ }++ #[test]+ fn malformed_desktop_success_never_becomes_login_required() {+ for body in [+ r#"{}"#,+ r#"{"login_required":false,"login_mode":"multi"}"#,+ r#"{"login_required":true,"login_mode":"single"}"#,+ r#"{"login_required":true}"#,+ r#"{"access_token":"access"}"#,+ ] {+ assert!(serde_json::from_str::<DesktopAuthResponse>(body).is_err());+ }+ }+#[test]fn retry_discovery_only_for_cached_recoverable_errors() {assert!(should_retry_with_discovered_port(diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rsindex 4d7dfb296e9..949eed29d59 100644--- a/studio/src-tauri/src/desktop_backend_owner.rs+++ b/studio/src-tauri/src/desktop_backend_owner.rs@@ -156,6 +156,32 @@ struct TokenResponse {access_token: String,}+/// The multi-account answer from /api/auth/desktop-login: the secret proved the shell+/// owns the backend, but the session belongs to whoever signs in, so no token is issued.+#[derive(Deserialize)]+struct MultiLoginRequired {+ login_required: bool,+ login_mode: String,+}++/// What an authenticated probe of the owned backend presents.+enum ProbeCredential {+ Bearer(String),+ DesktopSecret(String),+}++fn probe_credential(body: &[u8], secret: &str) -> Result<ProbeCredential, String> {+ if let Ok(tokens) = serde_json::from_slice::<TokenResponse>(body) {+ return Ok(ProbeCredential::Bearer(tokens.access_token));+ }+ match serde_json::from_slice::<MultiLoginRequired>(body) {+ Ok(multi) if multi.login_required && multi.login_mode == "multi" => {+ Ok(ProbeCredential::DesktopSecret(secret.to_string()))+ }+ _ => Err("desktop_auth_token_response_invalid".to_string()),+ }+}+pub(crate) fn desktop_candidate_ports() -> std::ops::RangeInclusive<u16> {DESKTOP_PORT_START..=DESKTOP_PORT_END}@@ -827,15 +853,15 @@ fn ready_for_use_status(health: Option<&HealthResponse>) -> OwnedBackendReadinesasync fn health_ready_status(port: u16,- access_token: Option<&str>,+ credential: Option<&ProbeCredential>,) -> Result<OwnedBackendReadiness, String> {- match fetch_health(port, access_token).await {+ match fetch_health(port, credential).await {Ok(health) => {let authenticated_version = health.as_ref().and_then(|health| health.version.as_deref()).filter(|version| !version.is_empty());- if access_token.is_some() {+ if credential.is_some() {let Some(version) = authenticated_version else {return Err("desktop_auth_health_unverified".to_string());};@@ -851,7 +877,7 @@ async fn health_ready_status(}Ok(ready_for_use_status(health.as_ref()))}- Err(reason) if access_token.is_some() => Err(reason),+ Err(reason) if credential.is_some() => Err(reason),Err(reason) => Ok(OwnedBackendReadiness::Stale { reason }),}}@@ -894,15 +920,19 @@ fn fetch_liveness_blocking(port: u16) -> Result<Option<DesktopLiveness>, String>}async fn fetch_health(port: u16,- access_token: Option<&str>,+ credential: Option<&ProbeCredential>,) -> Result<Option<HealthResponse>, String> {let client = crate::loopback_http::client(LOCAL_HTTP_TIMEOUT).map_err(|e| e.to_string())?;let mut request = client.get(format!("http://127.0.0.1:{port}/api/health"));- if let Some(access_token) = access_token {- request = request.bearer_auth(access_token);+ match credential {+ Some(ProbeCredential::Bearer(token)) => request = request.bearer_auth(token),+ Some(ProbeCredential::DesktopSecret(secret)) => {+ request = request.header("X-Desktop-Secret", secret)+ }+ None => {}}let response = request.send().await.map_err(|e| e.to_string())?;- if access_token.is_some()+ if credential.is_some()&& matches!(response.status(),reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN@@ -938,7 +968,7 @@ async fn desktop_login_route_compatible(port: u16, timeout: Duration) -> bool {}}-async fn desktop_secret_login(port: u16, secret: &str) -> Result<String, String> {+async fn desktop_secret_login(port: u16, secret: &str) -> Result<ProbeCredential, String> {let client = crate::loopback_http::client(LOCAL_HTTP_TIMEOUT).map_err(|e| e.to_string())?;let response = client.post(format!("http://127.0.0.1:{port}/api/auth/desktop-login"))@@ -954,11 +984,11 @@ async fn desktop_secret_login(port: u16, secret: &str) -> Result<String, String>response.status()))} else {- response- .json::<TokenResponse>()+ let body = response+ .bytes().await- .map(|tokens| tokens.access_token)- .map_err(|_| "desktop_auth_token_response_invalid".to_string())+ .map_err(|_| "desktop_auth_secret_probe_failed".to_string())?;+ probe_credential(&body, secret)}}@@ -966,8 +996,8 @@ async fn authenticated_health_ready_status(port: u16,secret: &str,) -> Result<OwnedBackendReadiness, String> {- let access_token = desktop_secret_login(port, secret).await?;- health_ready_status(port, Some(&access_token)).await+ let credential = desktop_secret_login(port, secret).await?;+ health_ready_status(port, Some(&credential)).await}pub(crate) async fn probe_owned_backend_state(@@ -1206,15 +1236,19 @@ pub(crate) fn exact_port_http_shutdown_blocking(port: u16) -> Result<(), String>if !(200..300).contains(&login.status) {return Err(format!("desktop login returned HTTP {}", login.status));}- let tokens = serde_json::from_slice::<TokenResponse>(&login.body)- .map_err(|e| format!("desktop login response invalid: {e}"))?;- let shutdown = http_request_blocking(- port,- "POST",- "/api/shutdown",- &[format!("Authorization: Bearer {}", tokens.access_token)],- &[],- )?;+ let (path, header) = match probe_credential(&login.body, &secret)+ .map_err(|e| format!("desktop login response invalid: {e}"))?+ {+ ProbeCredential::Bearer(token) => {+ ("/api/shutdown", format!("Authorization: Bearer {token}"))+ }+ // Multi-account install: no session was minted, so the secret stops the backend.+ ProbeCredential::DesktopSecret(secret) => (+ "/api/desktop/shutdown",+ format!("X-Desktop-Secret: {secret}"),+ ),+ };+ let shutdown = http_request_blocking(port, "POST", path, &[header], &[])?;if (200..300).contains(&shutdown.status) {Ok(())} else {@@ -1427,6 +1461,47 @@ mod tests {.contains("authorization: bearer test-access-token"));}+ #[tokio::test]+ async fn authenticated_health_uses_the_secret_when_login_mints_no_session() {+ let (port, seen, server) = http_sequence_server(vec![+ ("200 OK", r#"{"login_required":true,"login_mode":"multi"}"#),+ (+ "200 OK",+ r#"{"version":"2026.8.4","native_path_leases_supported":true}"#,+ ),+ ])+ .await;++ let readiness = authenticated_health_ready_status(port, "desktop-test-secret")+ .await+ .unwrap();+ server.await.unwrap();++ assert!(matches!(readiness, OwnedBackendReadiness::Ready));+ let seen = seen.lock().unwrap();+ let health = seen[1].to_ascii_lowercase();+ assert!(health.contains("x-desktop-secret: desktop-test-secret"));+ assert!(!health.contains("authorization:"));+ }++ #[test]+ fn a_login_body_without_a_token_or_multi_marker_is_invalid() {+ assert_eq!(+ probe_credential(br#"{"login_required":true,"login_mode":"single"}"#, "s")+ .err()+ .as_deref(),+ Some("desktop_auth_token_response_invalid")+ );+ assert_eq!(+ probe_credential(b"{}", "s").err().as_deref(),+ Some("desktop_auth_token_response_invalid")+ );+ assert!(matches!(+ probe_credential(br#"{"access_token":"t"}"#, "s"),+ Ok(ProbeCredential::Bearer(token)) if token == "t"+ ));+ }+#[tokio::test]async fn authenticated_health_marks_missing_or_disabled_native_leases_stale() {for health in [diff --git a/tests/studio/multi_account/README.md b/tests/studio/multi_account/README.mdnew file mode 100644index 00000000000..61a2fbf384a--- /dev/null+++ b/tests/studio/multi_account/README.md@@ -0,0 +1,60 @@+# Account isolation integration gates++The backend suite is `studio/backend/tests/multi_account/`. It uses real authentication+and router handlers without running the GPU/download lifespan. The upgrade probe imports+the real `main.app` in a fresh process after seeding old SQLite schemas and binary files.++`legacy_studio_schema.sql` is the schema of `mu/base~1` (`cc0cdab40e`), generated once from+that local Git revision. Test-time seeding uses SQLite and files only. The old password+hash and encrypted credential vector are deterministic test data. The auth migration+must preserve the old columns' values, while other seeded files remain byte-identical.++The route inventory imports every module below `routes/`, including hidden routes and+nested routers. It records router-relative paths, not the mount aliases in `main.py`.+Regenerate the checked-in report from `studio/backend`:++```bash+PYTHONPATH=. python -m tests.multi_account.inventory --output ../../artifacts/route_inventory.md+```++Extend `FACTORIES` in `factories.py` with the inventory's `module:METHOD:/path` key.+Each registration gets five real-credential cases automatically, plus an owner success+case. Missing factories intentionally fail under a strict xfail and are explicitly+uncovered, not evidence that the endpoint is isolated. `WORKERS` in `inventory.py` is+a provisional mapping because the other worker prompts were not supplied. Confirm that+mapping when integrating. The first-use database schema regression awaits worker 02;+remove its strict xfail when per-account schema initialization lands.+The deactivated API-key regression awaits worker 01; unlike JWT authentication on the+contract branch, API-key authentication still admits an inactive account.++The five matrix actors target Alice's existing resource. The owner and Bob must get 404,+Alice must succeed, missing credentials must get 401/403, and a previously issued JWT+must get 401 after Alice is deactivated. Rejected requests also preserve Alice's logical+database contents. Factory workspaces are prepopulated to separate authorization from+the independently tested first-use migration problem.++Run the standalone timing gate from the repo root, with the Studio Python environment+active and no concurrent test job:++```bash+python tests/studio/multi_account/perf/compare.py --output artifacts/perf.json+```++Each of three rounds makes 2,000 status calls with an owner JWT header and 200 authenticated+chat-history listings of 100 saved threads on each revision. Status remains a public+endpoint, so attaching a JWT does not add a dependency that production does not have.+`test_hot_path_cost.py` separately measures a GET through the real authentication dependency.+The benchmark keeps a persistent TestClient portal, warms all routes 100 times, alternates+revision order, and compares the median round p50 and p95 independently against 5%.+All round measurements are retained. It exits nonzero if any percentile exceeds the limit;+it does not retry until a pass, widen the tolerance, or silently xfail latency regressions.++The base snapshot comes only from local Git objects, is extracted below this clone's+`.tmp/`, and is deleted after timing. The head is the working tree, and the artifact+records its current commit. Python bytecode writes are disabled. Keep environment caches+and pytest temporary directories within this clone, as in the task's test command.++Windows tests are lexical `ntpath`/`PureWindowsPath` tests, not native Windows execution.+Account UUIDs add 42 UTF-16 units to owner-relative leaves. MAX_PATH includes the trailing+NUL; arbitrarily long installation paths still require Windows long-path support or a+shorter root. The tests do not impose a new path restriction on existing owners.diff --git a/tests/studio/multi_account/perf/compare.py b/tests/studio/multi_account/perf/compare.pynew file mode 100644index 00000000000..9b6884da5c3--- /dev/null+++ b/tests/studio/multi_account/perf/compare.py@@ -0,0 +1,103 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Compare local pre-contract and working-tree TestClient p50/p95; fail above 5%. Run from the repo root: python tests/studio/multi_account/perf/compare.py --output artifacts/perf.json"""++import argparse+import json+import platform+import statistics+import subprocess+import sys+import tempfile+from pathlib import Path++REPO = Path(__file__).resolve().parents[4]+++def regressions(results: dict, *, tolerance: float = 0.05) -> list[str]:+ return [+ f"{endpoint} {percentile}: {results['head'][endpoint][percentile]:.4f} ms > "+ f"{results['base'][endpoint][percentile] * (1 + tolerance):.4f} ms"+ for endpoint in ("status", "history")+ for percentile in ("p50_ms", "p95_ms")+ if results["head"][endpoint][percentile]+ > results["base"][endpoint][percentile] * (1 + tolerance)+ ]+++def main() -> None:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument(+ "--base-ref", default = None, help = "defaults to the merge base with origin/main"+ )+ parser.add_argument("--rounds", type = int, default = 3)+ parser.add_argument("--output", type = Path, default = REPO / "artifacts/perf.json")+ args = parser.parse_args()+ assert args.rounds >= 1+ assert args.output.resolve().is_relative_to(REPO), "Benchmark artifacts must stay in this clone"+ sys.path.insert(0, str(REPO / "studio/backend/tests/multi_account"))+ from perf_utils import baseline_ref, materialize_revision, run_probe++ if args.base_ref is None:+ args.base_ref = baseline_ref()+ if args.base_ref is None:+ raise SystemExit("no baseline commit reachable; pass --base-ref")++ scratch_parent = REPO / ".tmp"+ scratch_parent.mkdir(exist_ok = True)+ with tempfile.TemporaryDirectory(prefix = "account-perf-", dir = scratch_parent) as directory:+ scratch = Path(directory)+ base = materialize_revision(args.base_ref, scratch / "baseline")+ series = {"base": [], "head": []}+ for iteration in range(args.rounds):+ # Alternate order to reduce a monotonic machine-load or temperature bias.+ for label in ("base", "head") if iteration % 2 == 0 else ("head", "base"):+ print(f"Round {iteration + 1}/{args.rounds}: {label}", flush = True)+ series[label].append(+ run_probe(+ base if label == "base" else REPO / "studio/backend",+ scratch / f"{label}-{iteration}",+ mode = "timing",+ )+ )+ results = {+ label: {+ endpoint: {+ metric: statistics.median(run[endpoint][metric] for run in runs)+ for metric in ("samples", "p50_ms", "p95_ms")+ }+ for endpoint in ("status", "history")+ }+ for label, runs in series.items()+ }+ results["rounds"] = series+ results["base_ref"] = args.base_ref+ results["base_commit"] = subprocess.check_output(+ ["git", "rev-parse", f"{args.base_ref}^{{commit}}"], cwd = REPO, text = True+ ).strip()+ results["head_commit"] = subprocess.check_output(+ ["git", "rev-parse", "HEAD"], cwd = REPO, text = True+ ).strip()+ results["python"] = platform.python_version()+ results["platform"] = platform.platform()+ failures = regressions(results)+ results["passed"] = not failures+ results["failures"] = failures+ args.output.parent.mkdir(parents = True, exist_ok = True)+ args.output.write_text(json.dumps(results, indent = 2) + "\n", encoding = "utf-8")+ for endpoint in ("status", "history"):+ for metric in ("p50_ms", "p95_ms"):+ base_value, head_value = (+ results["base"][endpoint][metric],+ results["head"][endpoint][metric],+ )+ print(+ f"{endpoint:7} {metric}: base={base_value:.4f} ms head={head_value:.4f} ms "+ f"delta={(head_value / base_value - 1) * 100:+.2f}%"+ )+ assert not failures, "; ".join(failures)+++if __name__ == "__main__":+ main()diff --git a/tests/studio/multi_account/perf/probe.py b/tests/studio/multi_account/perf/probe.pynew file mode 100644index 00000000000..4af47a9b019--- /dev/null+++ b/tests/studio/multi_account/perf/probe.py@@ -0,0 +1,127 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""One isolated benchmark process. Product imports happen after selecting the revision."""++import argparse+import json+import math+import os+import sqlite3+import statistics+import sys+import time+from collections import Counter+from contextlib import closing+from pathlib import Path+from unittest.mock import patch+++def summarize(samples: list[float]) -> dict:+ ordered = sorted(samples)+ return {+ "samples": len(samples),+ "p50_ms": statistics.median(ordered),+ "p95_ms": ordered[math.ceil(0.95 * len(ordered)) - 1],+ }+++def measure_cost(operation, warm = None) -> dict:+ counters = Counter(connections = 0, queries = 0, statements = 0, mkdir_calls = 0, directories_created = 0)+ connect, mkdir = sqlite3.connect, os.mkdir++ def trace(statement):+ counters["statements"] += 1+ if statement.lstrip().upper().startswith("SELECT"):+ counters["queries"] += 1++ def open_connection(*args, **kwargs):+ counters["connections"] += 1+ conn = connect(*args, **kwargs)+ conn.set_trace_callback(trace)+ return conn++ def create_directory(*args, **kwargs):+ counters["mkdir_calls"] += 1+ result = mkdir(*args, **kwargs)+ counters["directories_created"] += 1+ return result++ # Warm right before the measured call: the settings cache revalidates after one second idle.+ if warm is not None:+ warm()+ with (+ patch.object(sqlite3, "connect", open_connection),+ patch.object(os, "mkdir", create_directory),+ ):+ operation()+ return dict(counters)+++def main() -> None:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--backend", type = Path, required = True)+ parser.add_argument("--helpers", type = Path, required = True)+ parser.add_argument("--mode", choices = ("cost", "timing"), required = True)+ parser.add_argument("--samples", type = int, default = 2000)+ parser.add_argument("--history-samples", type = int, default = 200)+ args = parser.parse_args()+ sys.path[:0] = [str(args.backend), str(args.helpers)]++ from seed import seed_legacy_install++ home = Path(os.environ["UNSLOTH_STUDIO_HOME"])+ seed_legacy_install(home)+ with closing(sqlite3.connect(home / "studio.db")) as conn:+ conn.executemany(+ "INSERT INTO chat_threads (id,title,model_type,created_at,updated_at) VALUES (?,?,'base',1000,1000)",+ [(f"history-{index}", f"Historical conversation {index}") for index in range(99)],+ )+ conn.commit()++ from fastapi.testclient import TestClient+ from support import bearer, make_app+ from utils.paths import storage_roots++ assert Path(storage_roots.__file__).resolve().is_relative_to(args.backend.resolve())+ workspace_root = getattr(storage_roots, "workspace_root", storage_roots.studio_root)+ headers = bearer("unsloth")+ with TestClient(make_app()) as client:++ def get(path):+ response = client.get(path, headers = headers)+ assert response.status_code == 200, (path, response.status_code, response.text)+ return response++ for _ in range(100):+ get("/api/auth/status")+ get("/account-probe")+ listing = get("/api/chat/threads")+ assert len(listing.json()["threads"]) == 100+ if args.mode == "cost":+ measurements = {+ "status": measure_cost(+ lambda: get("/api/auth/status"), warm = lambda: get("/api/auth/status")+ ),+ "authenticated_get": measure_cost(+ lambda: get("/account-probe"), warm = lambda: get("/account-probe")+ ),+ "workspace_1000": measure_cost(lambda: [workspace_root() for _ in range(1000)]),+ }+ else:+ measurements = {}+ for label, path, count in (+ ("status", "/api/auth/status", args.samples),+ ("history", "/api/chat/threads", args.history_samples),+ ):+ durations = []+ for _ in range(count):+ start = time.perf_counter_ns()+ get(path)+ durations.append((time.perf_counter_ns() - start) / 1_000_000)+ measurements[label] = summarize(durations)+ print(json.dumps(measurements, sort_keys = True))+++if __name__ == "__main__":+ main()diff --git a/tests/studio/playwright_multi_account.py b/tests/studio/playwright_multi_account.pynew file mode 100644index 00000000000..79249ee9341--- /dev/null+++ b/tests/studio/playwright_multi_account.py@@ -0,0 +1,186 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Multi-account browser flow against a disposable Studio: the owner creates an account,+its setup code is private, and switching accounts in one browser clears account data.++ STUDIO_E2E_URL=http://127.0.0.1:8000 STUDIO_E2E_OWNER_PASSWORD=... \+ python tests/studio/playwright_multi_account.py++Skips (exit 0) without the owner password. The account it creates is deleted at the end.+"""++from __future__ import annotations++import json+import os+import re+import sys+import time+from datetime import datetime, timezone+import urllib.error+import urllib.request++from playwright.sync_api import Page, expect, sync_playwright++BASE_URL = os.environ.get("STUDIO_E2E_URL", "http://127.0.0.1:8000").rstrip("/")+OWNER_PASSWORD = os.environ.get("STUDIO_E2E_OWNER_PASSWORD")+ENGINE = os.environ.get("PW_ENGINE", "chromium")+STEP_TIMEOUT_MS = 30_000+++def api(+ method: str,+ path: str,+ token: str | None = None,+ body: dict | None = None,+) -> tuple[int, dict]:+ data = None if body is None else json.dumps(body).encode()+ request = urllib.request.Request(BASE_URL + path, data = data, method = method)+ request.add_header("Content-Type", "application/json")+ if token:+ request.add_header("Authorization", f"Bearer {token}")+ try:+ with urllib.request.urlopen(request, timeout = 60) as response:+ raw = response.read()+ return response.status, json.loads(raw) if raw else {}+ except urllib.error.HTTPError as error:+ raw = error.read()+ try:+ return error.code, json.loads(raw) if raw else {}+ except ValueError:+ return error.code, {}+++def login(page: Page, username: str, password: str) -> None:+ page.goto(f"{BASE_URL}/login")+ # Wait for the layout the server's login_mode implies rather than sampling before the page settles.+ _, status = api("GET", "/api/auth/status")+ username_field = page.get_by_role("textbox", name = "Username", exact = True)+ if status.get("login_mode") == "multi":+ expect(username_field).to_be_visible(timeout = STEP_TIMEOUT_MS)+ username_field.fill(username)+ else:+ expect(username_field).to_have_count(0)+ page.locator("#password").fill(password)+ page.get_by_role("button", name = "Login", exact = True).click()+++def log_out(page: Page) -> None:+ page.evaluate(+ """async () => {+ await fetch("/api/auth/logout", {+ method: "POST",+ headers: { Authorization: `Bearer ${localStorage.getItem("unsloth_auth_token")}` },+ });+ for (const key of ["unsloth_auth_token", "unsloth_auth_refresh_token",+ "unsloth_auth_must_change_password", "unsloth_auth_session_mark"]) {+ localStorage.removeItem(key);+ }+ }"""+ )+++def local(page: Page, key: str):+ return page.evaluate("key => localStorage.getItem(key)", key)+++def run(page: Page, context) -> None:+ username = f"e2e_{int(time.time())}"+ managed_password = f"Managed-{int(time.time())}-password"+ status, owner_login = api(+ "POST", "/api/auth/login", body = {"username": "unsloth", "password": OWNER_PASSWORD}+ )+ assert status == 200, ("owner login", status, owner_login)+ owner_token = owner_login["access_token"]+ account_id = None+ try:+ _, initial = api("GET", "/api/auth/status")+ page.goto(f"{BASE_URL}/login")+ page.evaluate(+ """() => {+ localStorage.setItem("unsloth_locale", "en");+ localStorage.setItem("theme", "dark");+ localStorage.setItem("unsloth_e2e_private", "owner-private");+ localStorage.setItem("chat-draft:e2e", "owner-draft");+ localStorage.setItem("unsloth_chat_permission_mode", "full");+ }"""+ )+ if initial.get("login_mode") == "single":+ expect(page.locator("#username")).to_have_count(0)+ login(page, "unsloth", OWNER_PASSWORD)+ expect(page).to_have_url(re.compile(r"/chat"), timeout = STEP_TIMEOUT_MS)+ assert local(page, "unsloth_e2e_private") == "owner-private"++ status, created = api("POST", "/api/accounts", owner_token, {"username": username})+ assert status == 201, ("create account", status, created)+ account_id = created["account"]["account_id"]+ setup_code = created["setup_code"]+ assert setup_code+ expires = datetime.fromisoformat(created["setup_code_expires_at"].replace("Z", "+00:00"))+ assert expires > datetime.now(timezone.utc), expires+ _, after = api("GET", "/api/auth/status")+ assert after.get("login_mode") == "multi", after++ log_out(page)+ page.goto(f"{BASE_URL}/login")+ second_tab = context.new_page()+ second_tab.goto(f"{BASE_URL}/login")+ expect(second_tab.locator("#username")).to_be_visible(timeout = STEP_TIMEOUT_MS)+ second_tab.evaluate("() => { window.oldAccountDocument = true; }")++ # Usernames are case-insensitive at login; the setup code is the first password.+ login(page, username.upper(), setup_code)+ expect(page).to_have_url(re.compile(r"/change-password"), timeout = STEP_TIMEOUT_MS)+ assert local(page, "unsloth_e2e_private") is None+ assert local(page, "chat-draft:e2e") is None+ # Appearance survives the switch; its value may have been replaced by the personalization sync.+ assert local(page, "theme") is not None, "the account switch cleared the theme"+ assert local(page, "unsloth_chat_permission_mode") != "full"+ deadline = time.monotonic() + STEP_TIMEOUT_MS / 1000+ while second_tab.evaluate("() => window.oldAccountDocument") is not None:+ assert time.monotonic() < deadline, "the other tab never reloaded on the account switch"+ time.sleep(0.2)++ page.locator("#current-password").fill(setup_code)+ page.locator("#new-password").fill(managed_password)+ page.locator("#confirm-password").fill(managed_password)+ page.get_by_role("button", name = "Change password", exact = True).click()+ expect(page).to_have_url(re.compile(r"/chat"), timeout = STEP_TIMEOUT_MS)+ managed_token = local(page, "unsloth_auth_token")+ status, _ = api("GET", "/api/accounts", managed_token)+ assert status == 403, ("managed account listing", status)+ page.evaluate("() => localStorage.setItem('unsloth_settings_active_tab', 'accounts')")+ page.reload()+ expect(page.get_by_test_id("settings-tab-accounts")).to_have_count(0)+ page.evaluate("() => localStorage.setItem('unsloth_e2e_private', 'managed-private')")+ log_out(page)+ login(page, "unsloth", OWNER_PASSWORD)+ expect(page).to_have_url(re.compile(r"/chat"), timeout = STEP_TIMEOUT_MS)+ assert local(page, "unsloth_e2e_private") is None+ second_tab.close()+ finally:+ if account_id:+ status, _ = api("DELETE", f"/api/accounts/{account_id}", owner_token)+ assert status == 204, ("delete account", status)+++def main() -> int:+ if not OWNER_PASSWORD:+ print("SKIP: set STUDIO_E2E_URL and STUDIO_E2E_OWNER_PASSWORD for a disposable Studio")+ return 0+ with sync_playwright() as playwright:+ browser = getattr(playwright, ENGINE).launch(headless = True)+ context = browser.new_context(viewport = {"width": 1440, "height": 900}, color_scheme = "light")+ context.set_default_timeout(STEP_TIMEOUT_MS)+ page = context.new_page()+ try:+ run(page, context)+ finally:+ browser.close()+ print("PASS: multi-account browser flow")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.pyindex bd581468ab9..b6b20e5f772 100644--- a/tests/studio/playwright_settings_tabs.py+++ b/tests/studio/playwright_settings_tabs.py@@ -45,6 +45,7 @@ TABS = ["keyboard-shortcuts","debugging","about",+ "accounts",]ENGINE = os.environ.get("PW_ENGINE", "chromium")diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.pyindex 6637535f47e..95db53c2a02 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_parity_shots.py@@ -549,6 +549,8 @@ NOT_GATED: dict[str, str] = {"studio/backend/core/inference/pricing.py": "cost figures, which the scene never renders","studio/backend/utils/utils.py": "generic helpers imported by most of the backend; gating on ""it would run this workflow on nearly every PR and defeat the filter",+ "studio/backend/utils/account_context.py": "request identity ContextVar imported across the "+ "backend; studiobench runs as the sole owner session, where it resolves to the legacy root",}diff --git a/tests/studio/test_auth_form_input_count.py b/tests/studio/test_auth_form_input_count.pyindex 1e7108260a7..a1d3d4f8158 100644--- a/tests/studio/test_auth_form_input_count.py+++ b/tests/studio/test_auth_form_input_count.py@@ -327,6 +327,7 @@ def test_auth_redirect_targets_are_idempotent_and_concurrent(tmp_path: Path):AUTH_API.read_text(encoding = "utf-8").replace('from "@/lib/api-base"', 'from "./stubs.mjs"').replace('from "./session"', 'from "./stubs.mjs"')+ .replace('from "@/lib/account-transition"', 'from "./stubs.mjs"'))(tmp_path / "api.ts").write_text(source)(tmp_path / "stubs.mjs").write_text(@@ -334,6 +335,7 @@ def test_auth_redirect_targets_are_idempotent_and_concurrent(tmp_path: Path):let access = null, refresh = null, passwordChange = false;export const apiUrl = (path) => path;export const isTauri = false;+ export const accountTransitionPending = () => false;export const reset = (a = null, r = null) => { access = a; refresh = r; passwordChange = false; };export const clearAuthTokens = () => { access = null; refresh = null; };export const getAuthToken = () => access;diff --git a/tests/studio/test_cancel_atomicity.py b/tests/studio/test_cancel_atomicity.pyindex 9282da6d528..6309bec4c03 100644--- a/tests/studio/test_cancel_atomicity.py+++ b/tests/studio/test_cancel_atomicity.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport astimport importlib.util+import sysimport randomimport threadingfrom pathlib import Path@@ -118,7 +119,13 @@ def _load_active_generations():path = SOURCE_PATH.parents[1] / "state" / "active_generations.py"spec = importlib.util.spec_from_file_location("studio_active_generations", path)module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)+ # Its one import resolves from studio/backend; expose that only for this load.+ backend = str(SOURCE_PATH.parents[1])+ sys.path.insert(0, backend)+ try:+ spec.loader.exec_module(module)+ finally:+ sys.path.remove(backend)return module@@ -142,7 +149,8 @@ def _load_registry_module():chunks.append(seg)mod = {"active_generations": _load_active_generations()}exec(- "import threading, time\nfrom typing import Optional\n" + "\n\n".join(chunks),+ "import threading, time\nfrom typing import Optional\n_account_cancel_key = lambda key: key\n"+ + "\n\n".join(chunks),mod,)return moddiff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex a2378a71c71..4f9853d070f 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -471,7 +471,7 @@ def test_desktop_manages_the_remote_password_through_the_account_dialog():assert "if (!(isTauri && status)) {" in rowassert "initial={status.passwordPending}" in rowassert "<RemotePasswordRow status={status} onDone={refreshStatus} />" in section- assert "{isTauri ? null : (" in GENERAL_TAB.read_text(encoding = "utf-8")+ assert "{isTauri && isOwner ? null : (" in GENERAL_TAB.read_text(encoding = "utf-8")# A password change rotates credentials outside the polling requests.refresh = section.split("const refreshStatus = useCallback(", 1)[1].split("}, []);", 1)[0]assert "mutationEpoch.current += 1;" in refreshdiff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 40d4a6183f5..b10b1057975 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -3092,7 +3092,10 @@ def test_clearing_the_log_keeps_a_request_that_is_still_running():"""Dropping an own row mid-flight loses the request outright: active_count falls tozero and the finish or fail that follows has no entry left to land on."""monitor = " ".join(_read_backend("core/inference/api_monitor.py").split())- assert 'if entry.shared or entry.subject != subject or entry.status == "running"' in monitor+ assert (+ "if entry.shared or not self._attributed(entry, subject) or "+ 'entry.status == "running"' in monitor+ )# ─────────────────────────────────────────────────────────────────────────────diff --git a/tests/studio/test_stream_cancel_registration_timing.py b/tests/studio/test_stream_cancel_registration_timing.pyindex 4066b1dcbd2..9625189ac3f 100644--- a/tests/studio/test_stream_cancel_registration_timing.py+++ b/tests/studio/test_stream_cancel_registration_timing.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport astimport asyncioimport importlib.util+import sysimport jsonimport threadingimport time@@ -267,7 +268,13 @@ def _load_active_generations():path = SOURCE_PATH.parents[1] / "state" / "active_generations.py"spec = importlib.util.spec_from_file_location("studio_active_generations", path)module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)+ # Its one import resolves from studio/backend; expose that only for this load.+ backend = str(SOURCE_PATH.parents[1])+ sys.path.insert(0, backend)+ try:+ spec.loader.exec_module(module)+ finally:+ sys.path.remove(backend)return module@@ -290,7 +297,9 @@ def _load_registry_module():):chunks.append(seg)mod = {"active_generations": _load_active_generations()}- exec("import threading, time\n" + "\n\n".join(chunks), mod)+ exec(+ "import threading, time\n_account_cancel_key = lambda key: key\n" + "\n\n".join(chunks), mod+ )return moddiff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 603ffd7ee4f..4201f1f8a36 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -1067,22 +1067,48 @@ def _cli_update_password("""CLI mirror of backend update_password + change-password effects, in one transaction. Filecleanup runs after commit, so it cannot roll back."""password_salt, password_hash = _hash_password(new_password)+ columns = {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}+ # Managed credentials live in the account_* columns behind the downgrade fence; the owner's row keeps the legacy columns.+ managed = False+ if "account_jwt_secret" in columns:+ row = conn.execute("SELECT role FROM auth_user WHERE username = ?", (username,)).fetchone()+ managed = bool(row) and row[0] not in (None, "owner")+ target_columns = (+ "account_password_salt = ?, account_password_hash = ?, account_jwt_secret = ?"+ if managed+ else "password_salt = ?, password_hash = ?, jwt_secret = ?"+ )with conn:conn.execute(- """+ f"""UPDATE auth_user- SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0+ SET {target_columns}, must_change_password = 0WHERE username = ?""",(password_salt, password_hash, secrets.token_urlsafe(64), username),)conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))- conn.execute(- "DELETE FROM app_secrets WHERE key IN (?, ?)",- (DESKTOP_SECRET_HASH_KEY, DESKTOP_SECRET_CREATED_AT_KEY),- )+ if username == DEFAULT_ADMIN_USERNAME:+ conn.execute(+ "DELETE FROM app_secrets WHERE key IN (?, ?)",+ (DESKTOP_SECRET_HASH_KEY, DESKTOP_SECRET_CREATED_AT_KEY),+ )if revoke_api_keys:- conn.execute("DELETE FROM api_keys")+ conn.execute("DELETE FROM api_keys WHERE username = ?", (username,))+ if managed:+ conn.execute(+ "DELETE FROM account_api_keys WHERE account_id = "+ "(SELECT account_id FROM auth_user WHERE username = ?)",+ (username,),+ )+ columns = {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}+ if "setup_code_hash" in columns:+ conn.execute(+ "UPDATE auth_user SET setup_code_hash = NULL, setup_code_expires_at = NULL WHERE username = ?",+ (username,),+ )+ if username != DEFAULT_ADMIN_USERNAME:+ returnstale_files = [BOOTSTRAP_PASSWORD_FILE, DESKTOP_SECRET_FILE]if revoke_api_keys:# Reset only: the rows are gone, so each cached key is now plaintext for a@@ -4286,14 +4312,30 @@ def provision_desktop_auth():typer.echo("Desktop auth ready.")-@studio_app.command("reset-password")-def reset_password():- """Reset the Unsloth admin password.+def _reset_password_username(conn: sqlite3.Connection, username: Optional[str]) -> str:+ columns = {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}+ active_filter = " WHERE is_active = 1" if "is_active" in columns else ""+ count = conn.execute("SELECT COUNT(*) FROM auth_user" + active_filter).fetchone()[0]+ if username is None and count > 1:+ typer.echo("Error: --username is required when multiple accounts are active.", err = True)+ raise typer.Exit(1)+ target = DEFAULT_ADMIN_USERNAME if username is None else username.casefold()+ if target == DEFAULT_ADMIN_USERNAME:+ _ensure_cli_default_admin(conn)+ elif conn.execute("SELECT 1 FROM auth_user WHERE username = ?", (target,)).fetchone() is None:+ typer.echo("Error: account not found.", err = True)+ raise typer.Exit(1)+ return target- Rotates the credential in place: a running Unsloth accepts the new password on- its next request, so there is nothing to restart. Shared /p preview links are- not revoked -- rotate those in Settings if the old password leaked.- """++@studio_app.command("reset-password")+def reset_password(+ username: Optional[str] = typer.Option(+ None, "--username", help = "Account to reset; required with multiple active accounts."+ ),+):+ """Reset an Unsloth account password. Rotates in place, so nothing needs restarting. Shared /p+ preview links are not revoked; rotate those in Settings if the old password leaked."""new_password = _generate_reset_password()try:conn = _connect_auth_db()@@ -4307,15 +4349,16 @@ def reset_password():raise typer.Exit(1)try:- _ensure_cli_default_admin(conn)- _cli_update_password(conn, DEFAULT_ADMIN_USERNAME, new_password, revoke_api_keys = True)+ conn.execute("BEGIN IMMEDIATE")+ target = _reset_password_username(conn, username)+ _cli_update_password(conn, target, new_password, revoke_api_keys = True)except (OSError, sqlite3.Error) as exc:typer.echo(f"Error: could not reset the password ({exc}).", err = True)raise typer.Exit(1)finally:conn.close()- typer.echo(f"New password for '{DEFAULT_ADMIN_USERNAME}': {new_password}")+ typer.echo(f"New password for '{target}': {new_password}")typer.echo("Sessions and API keys revoked. A running Unsloth takes it on the next request, ""though repeated failed logins can hold the rate limit shut for up to a minute."