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
Unsloth Studio / Desktop: log out, show the owner's profile in Accounts, and let the owner sign in with a chosen name (#15619)
Leo Borcherdingded2b14f4d7e
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.pyindex 73f3e22252d..a9ce886220f 100644--- a/studio/backend/auth/storage.py+++ b/studio/backend/auth/storage.py@@ -385,6 +385,8 @@ _ACCOUNT_COLUMNS = (("account_jwt_secret", "TEXT"),# JSON list of repo ids / ``org/*`` patterns; NULL = every model (#11650).("model_allowlist", "TEXT"),+ # Owner's extra sign-in name; NULL = "unsloth" only.+ ("login_alias", "TEXT"),)@@ -718,6 +720,7 @@ def _public_account(row) -> dict:if "model_allowlist" in row.keys()else None),+ "login_alias": row["login_alias"] if "login_alias" in row.keys() else None,}@@ -774,6 +777,8 @@ def issue_account_setup_code(with conn:conn.execute("BEGIN IMMEDIATE")if username is not None:+ if _login_alias_taken(conn, username):+ raise sqlite3.IntegrityError("Username is unavailable")account_id = uuid.uuid4().hexlegacy_salt, legacy_hash, legacy_secret = _legacy_dummies()conn.execute(@@ -811,6 +816,56 @@ def issue_account_setup_code(return {"account": account, "setup_code": code, "setup_code_expires_at": expires_at}+def _login_alias_taken(conn: sqlite3.Connection, name: str) -> bool:+ return (+ conn.execute("SELECT 1 FROM auth_user WHERE login_alias = ?", (name,)).fetchone()+ is not None+ )+++def resolve_login_username(username: str) -> str:+ if username == DEFAULT_ADMIN_USERNAME:+ return username+ conn = get_connection()+ try:+ # A real username always wins, should one ever collide with the alias.+ row = conn.execute(+ "SELECT username FROM auth_user WHERE login_alias = ? AND role = 'owner' "+ "AND NOT EXISTS (SELECT 1 FROM auth_user WHERE username = ?)",+ (username, username),+ ).fetchone()+ finally:+ conn.close()+ return row["username"] if row else username+++def set_owner_login_alias(alias: Optional[str]) -> Optional[str]:+ """None, blank or "unsloth" clears it."""+ alias = (alias or "").strip()+ alias = (+ None+ if alias.casefold() in ("", DEFAULT_ADMIN_USERNAME)+ else validate_account_username(alias)+ )+ conn = get_connection()+ try:+ with conn:+ conn.execute("BEGIN IMMEDIATE")+ # Same write lock as account creation, so neither can take a name the other just took.+ if (+ alias is not None+ and conn.execute("SELECT 1 FROM auth_user WHERE username = ?", (alias,)).fetchone()+ ):+ raise sqlite3.IntegrityError("Username is unavailable")+ conn.execute(+ "UPDATE auth_user SET login_alias = ? WHERE username = ?",+ (alias, DEFAULT_ADMIN_USERNAME),+ )+ finally:+ conn.close()+ return alias++def authenticate_account_login(username: str, password: str) -> Optional[Tuple[str, str, str, bool]]:diff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.pyindex c619a2d2c11..36cefda9bbe 100644--- a/studio/backend/models/auth.py+++ b/studio/backend/models/auth.py@@ -165,6 +165,15 @@ class AccountResponse(BaseModel):created_at: strsetup_code_pending: boolmodel_allowlist: Optional[list[str]] = None+ login_alias: Optional[str] = None+ display_name: Optional[str] = None+ avatar_url: Optional[str] = None+++class OwnerLoginAliasRequest(BaseModel):+ login_alias: Optional[str] = Field(+ None, description = 'Owner sign-in name; null, empty or "unsloth" clears it'+ )class AccountListResponse(BaseModel):diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.pyindex 072388f75e6..79ce4142a60 100644--- a/studio/backend/routes/accounts.py+++ b/studio/backend/routes/accounts.py@@ -3,8 +3,9 @@"""Owner-managed account lifecycle. Private roots are retired, never erased."""+import jsonimport sqlite3-from contextlib import contextmanager+from contextlib import closing, contextmanagerfrom datetime import datetime, timezonefrom pathlib import Path@@ -19,10 +20,13 @@ from models.auth import (AccountResponse,AccountSetupResponse,CreateAccountRequest,+ OwnerLoginAliasRequest,)from hub.services.models import account_accessfrom state import active_generations-from utils.account_context import AccountContext, run_as+from storage import sqlite_gate+from utils.account_context import OWNER, AccountContext, run_as+from utils.personalization_settings import PERSONALIZATION_SETTING_KEYfrom utils.paths import storage_roots@@ -138,9 +142,44 @@ def retire_account_roots(account: AccountContext):return restore+def _profile_of(account: dict) -> dict:+ """Read-only: get_connection would create and migrate a studio.db per listed account."""+ context = (+ OWNER+ if account["role"] == "owner"+ else AccountContext(account["account_id"], account["username"], account["role"])+ )+ try:+ path = run_as(context, storage_roots.studio_db_path)+ if not path.is_file():+ return {}+ with closing(sqlite_gate.connect(f"{path.resolve().as_uri()}?mode=ro", uri = True)) as conn:+ row = conn.execute(+ "SELECT value_json FROM app_settings WHERE key = ?", (PERSONALIZATION_SETTING_KEY,)+ ).fetchone()+ profile = json.loads(row[0]).get("profile") if row else None+ except Exception: # noqa: BLE001 - a missing or unreadable profile just shows the username+ return {}+ if not isinstance(profile, dict):+ return {}+ name, avatar = profile.get("displayName"), profile.get("avatarDataUrl")+ return {+ "display_name": name.strip() if isinstance(name, str) and name.strip() else None,+ "avatar_url": avatar if isinstance(avatar, str) and avatar else None,+ }++@router.get("", response_model = AccountListResponse)def list_accounts():- return {"accounts": storage.list_accounts()}+ return {+ "accounts": [{**account, **_profile_of(account)} for account in storage.list_accounts()]+ }++[email protected]("/owner/login-alias", response_model = OwnerLoginAliasRequest)+def set_owner_login_alias(payload: OwnerLoginAliasRequest):+ with _account_errors():+ return {"login_alias": storage.set_owner_login_alias(payload.login_alias)}@router.post("", response_model = AccountSetupResponse, status_code = status.HTTP_201_CREATED)diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex 4b098c9907c..6cd4de06dcf 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -445,9 +445,10 @@ def _login_failure_detail() -> str:@router.post("/login", response_model = Token)async def login(payload: AuthLoginRequest, request: Request) -> Token:"""Login with username/password. Per-account + per-IP rate-limited."""- username = (- payload.username.casefold() if policy.installation_is_multi_user() else payload.username- )+ username = payload.username+ if policy.installation_is_multi_user():+ # Before the bucket key, so the owner's sign-in name and "unsloth" share one budget.+ username = storage.resolve_login_username(username.casefold())key = _bucket_key(request, username)unknown_key = _unknown_user_key(request)blocked_for = max(_login_blocked(key), _login_blocked(unknown_key))diff --git a/studio/backend/tests/test_account_lifecycle.py b/studio/backend/tests/test_account_lifecycle.pyindex 82e5860d14a..3f0f6c03538 100644--- a/studio/backend/tests/test_account_lifecycle.py+++ b/studio/backend/tests/test_account_lifecycle.py@@ -135,6 +135,9 @@ def test_owner_alice_bob_endpoint_matrix(matrix, actor, operation, target):"created_at","setup_code_pending","model_allowlist",+ "login_alias",+ "display_name",+ "avatar_url",}for row in response.json()["accounts"])@@ -933,3 +936,165 @@ def test_keyless_callers_cannot_manage_accounts(auth_env):with pytest.raises(accounts.HTTPException) as refused:accounts._require_ui_session(via_api_key)assert refused.value.status_code == 403+++def set_alias(+ client,+ alias,+ actor = "unsloth",+):+ return client.put(+ "/api/accounts/owner/login-alias", headers = headers(actor), json = {"login_alias": alias}+ )+++def test_owner_signs_in_with_a_chosen_name_and_unsloth_keeps_working(auth_env):+ client, _, _ = auth_env+ assert create(client, "alice").status_code == 201+ response = set_alias(client, "Riley")+ assert response.status_code == 200 and response.json() == {"login_alias": "riley"}+ for name in ("Riley", "riley", "unsloth"):+ session = login(client, name, "owner-password")+ assert session.status_code == 200, name+ assert session.json()["account_id"] == "owner"+ assert login(client, "riley", "wrong-password").status_code == 401+ owner = next(+ a+ for a in client.get("/api/accounts", headers = headers()).json()["accounts"]+ if a["role"] == "owner"+ )+ assert owner["username"] == "unsloth" and owner["login_alias"] == "riley"+ assert set_alias(client, "unsloth").json() == {"login_alias": None}+ assert login(client, "riley", "owner-password").status_code == 401+++ "alias,status",+ [("ab", 400), ("admin", 400), ("has space", 400), ("alice", 409), ("", 200), (None, 200)],+)+def test_owner_sign_in_name_is_validated_like_a_username(auth_env, alias, status):+ client, _, _ = auth_env+ create(client, "alice")+ response = set_alias(client, alias)+ assert response.status_code == status+ assert storage.list_accounts()[0]["login_alias"] is None+++def test_owner_sign_in_name_cannot_be_taken_by_a_new_account(auth_env):+ client, _, _ = auth_env+ assert set_alias(client, "riley").status_code == 200+ assert create(client, "RILEY").status_code == 409+ assert storage.count_active_accounts() == 1+++def test_only_the_owner_sets_the_sign_in_name(matrix):+ client, _, _ = matrix+ assert set_alias(client, "mallory", actor = "alice").status_code == 403+ assert storage.list_accounts()[0]["login_alias"] is None+++def test_owner_sign_in_name_shares_the_owner_rate_limit_bucket(auth_env):+ client, auth, _ = auth_env+ create(client, "alice")+ set_alias(client, "riley")+ for _ in range(auth._LOGIN_MAX_FAILS):+ assert login(client, "riley", "wrong").status_code == 401+ assert login(client, "unsloth", "owner-password").status_code == 429+++def test_account_list_shows_each_profile_name_and_avatar_without_creating_databases(auth_env):+ client, _, _ = auth_env+ from utils.account_context import AccountContext+ from utils.personalization_settings import set_personalization++ alice_id = create(client, "alice").json()["account"]["account_id"]+ create(client, "bob")+ avatar = "data:image/png;base64,AAAA"+ run_as(+ OWNER, set_personalization, {"profile": {"displayName": " Riley ", "avatarDataUrl": avatar}}+ )+ alice = AccountContext(alice_id, "alice", "user")+ run_as(alice, set_personalization, {"profile": {"displayName": "Alice A."}})+ bob = storage.get_account("bob")+ bob_db = run_as(bob, storage_roots.studio_db_path)+ rows = {+ a["username"]: a for a in client.get("/api/accounts", headers = headers()).json()["accounts"]+ }+ assert (rows["unsloth"]["display_name"], rows["unsloth"]["avatar_url"]) == ("Riley", avatar)+ assert (rows["alice"]["display_name"], rows["alice"]["avatar_url"]) == ("Alice A.", None)+ assert (rows["bob"]["display_name"], rows["bob"]["avatar_url"]) == (None, None)+ assert not bob_db.exists()++[email protected]("alias,stored", [(" Riley ", "riley"), (" ", None), ("UNSLOTH", None)])+def test_owner_sign_in_name_trims_and_unsloth_or_blank_clears_it(auth_env, alias, stored):+ client, _, _ = auth_env+ set_alias(client, "before")+ assert set_alias(client, alias).json() == {"login_alias": stored}+++def test_owner_sign_in_name_and_usernames_collide_after_case_folding_either_way(auth_env):+ client, _, _ = auth_env+ # validate_account_username casefolds before its ASCII check: "ſ" folds to "s", "K" (Kelvin) to "k".+ assert create(client, "sam").status_code == 201+ assert set_alias(client, "ſam").status_code == 409+ assert set_alias(client, "Kai").json() == {"login_alias": "kai"}+ assert create(client, "Kai").status_code == 409+ assert set_alias(client, "rilëy").status_code == 400+ assert {a["username"] for a in storage.list_accounts()} == {"unsloth", "sam"}+++def test_alias_signs_in_as_the_owner_identity_and_survives_alias_changes(auth_env):+ client, _, _ = auth_env+ create(client, "alice")+ set_alias(client, "riley")+ session = login(client, "Riley", "owner-password").json()+ assert (+ authentication.jwt.decode(session["access_token"], options = {"verify_signature": False})[+ "sub"+ ]+ == "unsloth"+ )+ # Renaming or clearing the sign-in name is not a credential change.+ set_alias(client, "other")+ set_alias(client, None)+ me = {"Authorization": "Bearer " + session["access_token"]}+ assert client.get("/api/accounts", headers = me).status_code == 200+ refreshed = client.post("/api/auth/refresh", json = {"refresh_token": session["refresh_token"]})+ assert refreshed.status_code == 200 and refreshed.json()["account_id"] == "owner"+++def test_account_routes_cannot_reach_the_owner_through_its_sign_in_name(auth_env):+ client, _, _ = auth_env+ create(client, "alice")+ set_alias(client, "riley")+ before = db_rows("auth_user")+ assert (+ client.patch(+ "/api/accounts/riley", headers = headers(), json = {"is_active": False}+ ).status_code+ == 404+ )+ assert client.delete("/api/accounts/riley", headers = headers()).status_code == 404+ assert client.post("/api/accounts/riley/setup-code", headers = headers()).status_code == 404+ assert db_rows("auth_user") == before+++def test_single_mode_login_ignores_the_owner_sign_in_name(auth_env):+ client, _, _ = auth_env+ set_alias(client, "riley")+ assert policy.login_mode() == "single"+ assert login(client, "riley", "owner-password").status_code == 401+ assert login(client, "unsloth", "owner-password").status_code == 200+++def test_cli_reset_resolves_the_owner_sign_in_name(matrix, reset_cli):+ client, _, _ = matrix+ set_alias(client, "riley")+ result = reset_cli.invoke(studio_cli.studio_app, ["reset-password", "--username", "Riley"])+ assert result.exit_code == 0, result.output+ assert "New password for 'unsloth' (also signs in as 'riley'): reset-password" in result.output+ assert login(client, "riley", "reset-password").json()["account_id"] == "owner"+ assert login(client, "alice", "alice-password").status_code == 200+ result = reset_cli.invoke(studio_cli.studio_app, ["reset-password", "--username", "nobody"])+ assert result.exit_code == 1 and "account not found" in result.outputdiff --git a/studio/frontend/src/app/auth-guards.ts b/studio/frontend/src/app/auth-guards.tsindex 07eed1562ae..09f9e960e5e 100644--- a/studio/frontend/src/app/auth-guards.ts+++ b/studio/frontend/src/app/auth-guards.ts@@ -55,7 +55,8 @@ 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") {+ // Desktop never saw the seeded password, so the seeded-password setup page is no way back in.+ if (status.login_mode === "multi" || isTauri) {return { ...status, requires_password_change: mustChangePassword() };}// Server truth wins; keep localStorage in sync both ways.diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex d406a27b452..260759cad5d 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -274,7 +274,9 @@ import { videoNavHint } from "@/config/hardware-verdict";import {AUTH_SESSION_ENDING_EVENT,clearAuthTokens,+ fetchAuthStatus,logout,+ markDesktopSignedOut,useIsAccountOwner,} from "@/features/auth";import { TOUR_OPEN_EVENT, getTourId, useTourAvailable } from "@/features/tour";@@ -4307,23 +4309,41 @@ export function AppSidebar() {</>);- useShortcut(- "logOut",- () => {- // Desktop signs out through the OS account menu, not here.- if (isTauri) return;- void (async () => {- if (!window.dispatchEvent(new Event(AUTH_SESSION_ENDING_EVENT, { cancelable: true }))) return;- try {- await logout();- } catch {- clearAuthTokens();- }- void navigate({ to: "/login" });- })();- },- { enabled: !isTauri },- );+ async function signOut() {+ // Multi-account Desktop signs back in with a password, and the seeded one was never shown.+ if (isTauri && isOwner) {+ // Unknown is not "no password to lose": stay signed in rather than risk a lockout.+ const status = await fetchAuthStatus().catch(() => null);+ if (!status) {+ toast.error(t("shell.navigation.logOutFailed"));+ return;+ }+ if (status.login_mode === "multi" && status.requires_password_change) {+ toast.error(t("shell.navigation.logOutNeedsPassword"));+ useSettingsDialogStore.getState().openDialog("remote-lan");+ return;+ }+ }+ if (!window.dispatchEvent(new Event(AUTH_SESSION_ENDING_EVENT, { cancelable: true }))) return;+ // Marker before the revoke, else a relaunch or failing request signs straight back in.+ if (isTauri) {+ try {+ await markDesktopSignedOut();+ } catch {+ toast.error(t("shell.navigation.logOutFailed"));+ return;+ }+ }+ // Best-effort revocation; ignore network errors so the local clear still runs.+ try {+ await logout();+ } catch {+ clearAuthTokens();+ }+ void navigate({ to: "/login" });+ }++ useShortcut("logOut", () => void signOut());/** Filing a pinned chat takes its pin, else Pinned keeps drawing it. */function fileChatsInSection(chatIds: string[], sectionId: string | null) {@@ -6828,23 +6848,10 @@ export function AppSidebar() {</DropdownMenuItem></DropdownMenuSubContent></DropdownMenuSub>- {!isTauri && (- <DropdownMenuItem- onSelect={async () => {- if (!window.dispatchEvent(new Event(AUTH_SESSION_ENDING_EVENT, { cancelable: true }))) return;- // Best-effort revocation; ignore network errors so the local clear still runs.- try {- await logout();- } catch {- clearAuthTokens();- }- void navigate({ to: "/login" });- }}- >- <HugeiconsIcon icon={Logout05Icon} strokeWidth={1.75} className="size-icon" />- <span>{t("shell.navigation.logOut")}</span>- </DropdownMenuItem>- )}+ <DropdownMenuItem onSelect={() => void signOut()}>+ <HugeiconsIcon icon={Logout05Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("shell.navigation.logOut")}</span>+ </DropdownMenuItem>{!isTauri && (<DropdownMenuItem onSelect={() => setShutdownOpen(true)}><HugeiconsIcon icon={PowerIcon} strokeWidth={1.75} className="size-icon" />diff --git a/studio/frontend/src/features/auth/components/auth-form.tsx b/studio/frontend/src/features/auth/components/auth-form.tsxindex bce3a903ec6..ef5b2b8f708 100644--- a/studio/frontend/src/features/auth/components/auth-form.tsx+++ b/studio/frontend/src/features/auth/components/auth-form.tsx@@ -2,7 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { useAppShellReadySignal } from "@/components/app-readiness";-import { apiUrl } from "@/lib/api-base";+import { apiUrl, isTauri } 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";@@ -15,6 +15,7 @@ import { useEffect, useRef, useState } from "react";import type { ReactElement } from "react";import type { SyntheticEvent } from "react";import { refreshSession, refreshSessionOutcome } from "../api";+import { clearDesktopSignedOut, continueAsDesktopOwner } from "../tauri-auto-auth";import {deadlineFromStatus,formatCountdown,@@ -91,7 +92,7 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {// Server first: localStorage flags can be stale (e.g. tokens from a previous install).try {const result = await fetchAuthStatus();- const requiresChange = result.login_mode === "multi"+ const requiresChange = result.login_mode === "multi" || isTauri? hasAuthToken() && mustChangePassword(): result.requires_password_change;if (!canceled) {@@ -312,6 +313,8 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {token = (await response.json()) as TokenResponse;}+ // A failed clear only shows login on the next launch.+ if (isTauri) await clearDesktopSignedOut().catch(() => undefined);const finishSession = () => {setLoginMode(loginMode);if (!isLoginMode) setRequiresPasswordChange(false);@@ -339,6 +342,20 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {}}+ async function handleContinueAsOwner() {+ setError(null);+ setLoading(true);+ try {+ if (await continueAsDesktopOwner()) {+ navigate({ to: getPostAuthRoute() });+ } else {+ setError("Sign in with your username and password.");+ }+ } finally {+ setLoading(false);+ }+ }+if (statusLoading && initialized === null && error === null) return null;return (@@ -398,6 +415,9 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {<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>+ <p className="text-sm text-muted-foreground">+ Installation owner? Sign in as unsloth, or the sign-in name shown in Settings > Accounts.+ </p></div>)}{isLoginMode && (@@ -555,6 +575,18 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {>{loading ? "Please wait..." : submitLabel}</Button>+ {/* Single mode only: there the shell secret proves the owner, who may never have set a password. */}+ {isTauri && isLoginMode && loginMode === "single" && (+ <Button+ type="button"+ variant="ghost"+ className="mx-auto flex w-fit"+ disabled={loading || statusLoading}+ onClick={() => void handleContinueAsOwner()}+ >+ Continue as owner+ </Button>+ )}</form>{showSwitchLink && (diff --git a/studio/frontend/src/features/auth/index.ts b/studio/frontend/src/features/auth/index.tsindex 4fbbbd22d5e..e4b0a28c834 100644--- a/studio/frontend/src/features/auth/index.ts+++ b/studio/frontend/src/features/auth/index.ts@@ -10,6 +10,7 @@ export {refreshSessionOutcome,} from "./api";export { AUTH_SESSION_ENDING_EVENT } from "./session-events";+export { fetchAuthStatus } from "./login-client";export {AUTH_SESSION_CLEARED_EVENT,AUTH_SESSION_MARK_KEY,@@ -29,6 +30,7 @@ export {export {clearTauriAuthFailure,getTauriAuthFailure,+ markDesktopSignedOut,tauriAutoAuth,} from "./tauri-auto-auth";export {diff --git a/studio/frontend/src/features/auth/tauri-auto-auth.ts b/studio/frontend/src/features/auth/tauri-auto-auth.tsindex 06064e6dbfa..cd531be789a 100644--- a/studio/frontend/src/features/auth/tauri-auto-auth.ts+++ b/studio/frontend/src/features/auth/tauri-auto-auth.ts@@ -19,7 +19,8 @@ import {type DesktopAuthResponse =| { access_token: string; refresh_token: string }- | { login_required: true; login_mode: "multi" };+ | { login_required: true; login_mode: "multi" }+ | { signed_out: true };type TauriAutoAuthOptions = {force?: boolean;@@ -34,6 +35,18 @@ export function isTauriLoginRequired(): boolean {return tauriLoginRequired;}+// A shell marker file, not localStorage: WebView2 writes lazily, so a quick quit lost the sign-out.+export async function markDesktopSignedOut(): Promise<void> {+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("desktop_mark_signed_out");+ tauriLoginRequired = true;+}++export async function clearDesktopSignedOut(): Promise<void> {+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("desktop_clear_signed_out");+}+const TAURI_AUTH_FAILURE_FALLBACK ="Desktop authentication failed. Update or repair the managed Unsloth install, then restart Unsloth.";const BACKEND_NOT_READY_MESSAGE = "Backend is not ready";@@ -81,6 +94,14 @@ async function doTauriAutoAuth(options: TauriAutoAuthOptions): Promise<boolean>try {const { invoke } = await import("@tauri-apps/api/core");const tokens = await invoke<DesktopAuthResponse>("desktop_auth");+ if ("signed_out" in tokens) {+ tauriLoginRequired = true;+ clearAuthTokens();+ clearTauriAuthFailure();+ const { router } = await import("@/app/router");+ await router.navigate({ to: "/login", replace: true });+ return options.force === true;+ }if ("login_required" in tokens) {tauriLoginRequired = true;// A managed account signs in in the document; do not discard the session it holds.@@ -144,3 +165,9 @@ export function tauriAutoAuth(}return pending.promise;}++export async function continueAsDesktopOwner(): Promise<boolean> {+ await clearDesktopSignedOut();+ await tauriAutoAuth({ force: true });+ return !tauriLoginRequired && hasAuthToken();+}diff --git a/studio/frontend/src/features/settings/api/accounts.ts b/studio/frontend/src/features/settings/api/accounts.tsindex 26aef396ad6..51402b703a4 100644--- a/studio/frontend/src/features/settings/api/accounts.ts+++ b/studio/frontend/src/features/settings/api/accounts.ts@@ -14,6 +14,9 @@ export interface StudioAccount {created_at: string;// null = every model; set by the owner per account.model_allowlist?: string[] | null;+ login_alias?: string | null;+ display_name?: string | null;+ avatar_url?: string | null;}export interface AccountSetupCode {account_id: string;@@ -101,3 +104,13 @@ export async function setAccountModelAllowlist(body: JSON.stringify({ model_allowlist: allowlist }),});}+export async function setOwnerLoginAlias(+ alias: string | null,+): Promise<string | null> {+ const response = await accountsRequest("/owner/login-alias", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ login_alias: alias?.trim() || null }),+ });+ return ((await response.json()) as { login_alias: string | null }).login_alias;+}diff --git a/studio/frontend/src/features/settings/components/change-password-dialog.tsx b/studio/frontend/src/features/settings/components/change-password-dialog.tsxindex 20f14aca6cc..15f6974f32f 100644--- a/studio/frontend/src/features/settings/components/change-password-dialog.tsx+++ b/studio/frontend/src/features/settings/components/change-password-dialog.tsx@@ -14,15 +14,17 @@ import {import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import {+ fetchAuthStatus,getAuthToken,refreshSession,setMustChangePassword,storeAuthTokens,+ useIsAccountOwner,} from "@/features/auth";import { useT } from "@/i18n";-import { apiUrl } from "@/lib/api-base";+import { apiUrl, isTauri } from "@/lib/api-base";import { toast } from "@/lib/toast";-import { type FormEvent, useState } from "react";+import { type FormEvent, useEffect, useState } from "react";const MIN_PASSWORD_LENGTH = 8;const WRONG_CURRENT_PASSWORD_DETAIL = "Current password is incorrect";@@ -194,12 +196,19 @@ async function requestPasswordChange(export function ChangePasswordDialog({initial = false,onDone,+ open: controlledOpen,+ onOpenChange,}: {initial?: boolean;onDone?: () => void;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;}) {const t = useT();- const [open, setOpen] = useState(false);+ const [ownOpen, setOwnOpen] = useState(false);+ const controlled = controlledOpen !== undefined;+ const open = controlled ? controlledOpen : ownOpen;+ const setOpen = (next: boolean) => (controlled ? onOpenChange?.(next) : setOwnOpen(next));const [current, setCurrent] = useState("");const [next, setNext] = useState("");const [confirm, setConfirm] = useState("");@@ -271,11 +280,13 @@ export function ChangePasswordDialog({}}}>- <DialogTrigger asChild={true}>- <Button variant="outline" size="sm" >- {copy.trigger}- </Button>- </DialogTrigger>+ {controlled ? null : (+ <DialogTrigger asChild={true}>+ <Button variant="outline" size="sm" >+ {copy.trigger}+ </Button>+ </DialogTrigger>+ )}<DialogContentclassName="sm:max-w-sm"showCloseButton={!submitting}@@ -374,3 +385,27 @@ export function ChangePasswordDialog({</Dialog>);}++/** A Desktop owner still on the seeded password has none to give, so sets a first one instead. */+export function useOwnPasswordPending(): [boolean, () => void] {+ const owner = useIsAccountOwner();+ const [initial, setInitial] = useState(false);+ useEffect(() => {+ if (!(isTauri && owner)) return;+ let live = true;+ void fetchAuthStatus()+ .then((status) => {+ if (live) setInitial(status.requires_password_change);+ })+ .catch(() => undefined);+ return () => {+ live = false;+ };+ }, [owner]);+ return [initial, () => setInitial(false)];+}++export function AccountPasswordDialog() {+ const [initial, settled] = useOwnPasswordPending();+ return <ChangePasswordDialog initial={initial} onDone={settled} />;+}diff --git a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.tsindex ee97852423e..0f9f5d13658 100644--- a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts+++ b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts@@ -191,8 +191,7 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [def("clearAllUnreads", "Shift+Escape", {nonMacDefaultBinding: "Mod+Alt+Shift+KeyU",}),- // Desktop signs out through the OS account menu, so this chord could not fire there.- def("logOut", null, { webOnly: true }),+ def("logOut", null),def("openSettings", "Mod+Comma"),// Bare ⏎ / Esc register only while a tool call is waiting.def("approveToolRequest", "Enter", { allowBareKey: true }),diff --git a/studio/frontend/src/features/settings/tabs/accounts-tab.tsx b/studio/frontend/src/features/settings/tabs/accounts-tab.tsxindex 1517604aaab..70ed2eaa232 100644--- a/studio/frontend/src/features/settings/tabs/accounts-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/accounts-tab.tsx@@ -26,7 +26,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { useIsAccountOwner } from "@/features/auth";-import { UserAvatar } from "@/features/profile";+import { UserAvatar, useUserProfileStore } from "@/features/profile";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -58,10 +58,15 @@ import {regenerateSetupCode,setAccountActive,setAccountModelAllowlist,+ setOwnerLoginAlias,type AccountSetupCode,type StudioAccount,} from "../api/accounts";import { ManagedProviderUrlsSection } from "../components/managed-provider-urls-section";+import {+ ChangePasswordDialog,+ useOwnPasswordPending,+} from "../components/change-password-dialog";export function AccountsTab() {const owner = useIsAccountOwner();@@ -87,12 +92,22 @@ function OwnerAccountsTab() {const [busy, setBusy] = useState(false);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);+ const [aliasDraft, setAliasDraft] = useState("");+ const [ownerPasswordOpen, setOwnerPasswordOpen] = useState(false);+ const [ownerPasswordPending, ownerPasswordSet] = useOwnPasswordPending();+ // The owner's row matches the sidebar footer, which reads this store before the server copy syncs.+ const ownDisplayName = useUserProfileStore((s) => s.displayName).trim();+ const ownAvatar = useUserProfileStore((s) => s.avatarDataUrl);useEffect(() => {let canceled = false;void fetchAccounts().then((result) => {- if (!canceled) setAccounts(result);+ if (canceled) return;+ setAccounts(result);+ setAliasDraft(+ result.find((account) => account.role === "owner")?.login_alias ?? "",+ );}).catch((reason: unknown) => {if (!canceled)@@ -146,18 +161,30 @@ function OwnerAccountsTab() {});}+ function saveSignInName() {+ if (busy) return;+ void perform(async () => {+ setAliasDraft((await setOwnerLoginAlias(aliasDraft)) ?? "");+ });+ }+const confirming = resetting ?? retiring;const editorOpen = creating || setup !== null;const filteredAccounts = accounts.filter((account) =>- account.username- .toLocaleLowerCase(locale)- .includes(query.trim().toLocaleLowerCase(locale)),+ [account.username, shownName(account)].some((name) =>+ name+ .toLocaleLowerCase(locale)+ .includes(query.trim().toLocaleLowerCase(locale)),+ ),);const dateFormatter = new Intl.DateTimeFormat(locale, {year: "numeric",month: "short",day: "numeric",});+ function shownName(account: StudioAccount) {+ return (account.role === "owner" && ownDisplayName) || account.display_name || account.username;+ }function createdDate(account: StudioAccount) {// `new Date(null)` is the epoch, so check null created_at (possible after upgrade) explicitly.const raw = account.created_at;@@ -286,20 +313,30 @@ function OwnerAccountsTab() {<td className="rounded-l-md py-3 pl-3 pr-3"><div className="flex items-center gap-2.5"><UserAvatar- name={account.username}- imageUrl={null}+ name={shownName(account)}+ imageUrl={(account.role === "owner" && ownAvatar) || account.avatar_url || null}size="sm"className="size-8"/><div className="min-w-0 space-y-0.5"><p className="break-all text-sm font-medium">- {account.username}+ {shownName(account)}</p><p className="text-xs text-muted-foreground">{account.role === "owner"? t("settings.accounts.owner"): t("settings.accounts.privateAccount")}</p>+ <p className="break-all text-xs text-muted-foreground">+ {account.role === "owner" && account.login_alias+ ? t("settings.accounts.signsInAsOwner", {+ alias: account.login_alias,+ username: account.username,+ })+ : t("settings.accounts.signsInAs", {+ username: account.username,+ })}+ </p>{account.role !== "owner" &&account.model_allowlist?.length ? (<p className="text-xs text-muted-foreground">@@ -341,6 +378,44 @@ function OwnerAccountsTab() {</span></td><td className="rounded-r-md py-3 pr-3 text-right">+ {account.role === "owner" && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-sm"+ className="max-sm:size-9"+ disabled={busy}+ aria-label={t("settings.accounts.actionsFor", {+ username: shownName(account),+ })}+ >+ <HugeiconsIcon+ icon={MoreHorizontalIcon}+ className="size-4"+ aria-hidden="true"+ />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-max max-w-[calc(100vw-2rem)]"+ >+ <DropdownMenuItem onSelect={() => setOwnerPasswordOpen(true)}>+ <HugeiconsIcon+ icon={Key01Icon}+ className="size-4"+ aria-hidden="true"+ />+ {t(+ ownerPasswordPending+ ? "settings.general.passwordDialog.setSubmit"+ : "settings.general.passwordDialog.trigger",+ )}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}{account.role !== "owner" && (<DropdownMenu><DropdownMenuTrigger asChild>@@ -470,8 +545,42 @@ function OwnerAccountsTab() {)}</section>+ <section className="flex flex-col gap-2">+ <Label htmlFor="owner-sign-in-name" className="text-sm font-medium">+ {t("settings.accounts.signInName")}+ </Label>+ <p className="max-w-lg text-xs text-muted-foreground">+ {t("settings.accounts.signInNameDescription")}+ </p>+ <div className="flex items-center gap-3">+ <Input+ id="owner-sign-in-name"+ value={aliasDraft}+ onChange={(event) => setAliasDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") saveSignInName();+ }}+ placeholder="unsloth"+ autoCapitalize="none"+ autoComplete="off"+ spellCheck={false}+ className="min-w-0 flex-1"+ />+ <Button variant="outline" size="sm" disabled={busy} onClick={saveSignInName}>+ {t("settings.accounts.signInNameSave")}+ </Button>+ </div>+ </section>+<ManagedProviderUrlsSection />+ <ChangePasswordDialog+ initial={ownerPasswordPending}+ open={ownerPasswordOpen}+ onOpenChange={setOwnerPasswordOpen}+ onDone={ownerPasswordSet}+ />+<Dialogopen={editorOpen}onOpenChange={(open) => {diff --git a/studio/frontend/src/features/settings/tabs/profile-tab.tsx b/studio/frontend/src/features/settings/tabs/profile-tab.tsxindex 29100281347..7ef09e407ec 100644--- a/studio/frontend/src/features/settings/tabs/profile-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/profile-tab.tsx@@ -6,6 +6,8 @@ import {ProfileStatsPanel,} from "@/features/profile";import { useT } from "@/i18n";+import { AccountPasswordDialog } from "../components/change-password-dialog";+import { SettingsRow } from "../components/settings-row";export function ProfileTab() {const t = useT();@@ -28,6 +30,12 @@ export function ProfileTab() {</header><ProfilePersonalizationPanel />+ <SettingsRow+ label={t("settings.general.password")}+ description={t("settings.general.passwordDescription")}+ >+ <AccountPasswordDialog />+ </SettingsRow><ProfileStatsPanel /></div>);diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 212206f0698..20a613a79fa 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -789,6 +789,8 @@ export const ar = {guidedTour: "جولة إرشادية",help: "مساعدة",logOut: "تسجيل الخروج",+ logOutNeedsPassword: "عيّن كلمة مرور في الإعدادات > الوصول عن بُعد قبل تسجيل الخروج، حتى تتمكن من تسجيل الدخول مرة أخرى.",+ logOutFailed: "تعذّر تسجيل الخروج بأمان. حاول مرة أخرى بعد قليل.",shutdown: "إيقاف التشغيل",},commandPalette: {@@ -933,6 +935,11 @@ export const ar = {},settings: {accounts: {+ signsInAs: "يسجّل الدخول باسم {username}",+ signsInAsOwner: "يسجّل الدخول باسم {alias} أو {username}",+ signInName: "اسم تسجيل الدخول",+ signInNameDescription: "الاسم الذي تكتبه لتسجيل الدخول عندما يكون في هذا التثبيت أكثر من حساب. يعمل unsloth دائمًا أيضًا. اتركه فارغًا لاستخدام unsloth فقط.",+ signInNameSave: "حفظ الاسم",title: "الحسابات",description: "أنشئ حسابات Unsloth خاصة. يسجّل المستخدمون الجدد الدخول برمز إعداد يُستخدم مرة واحدة ثم يختارون كلمة مرور.",username: "اسم المستخدم",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex a19eddbaac1..387f43f6d3f 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -793,6 +793,8 @@ export const de = {guidedTour: "Geführte Tour",help: "Hilfe",logOut: "Abmelden",+ logOutNeedsPassword: "Legen Sie vor dem Abmelden unter Einstellungen > Fernzugriff ein Passwort fest, damit Sie sich wieder anmelden können.",+ logOutFailed: "Abmelden war nicht sicher möglich. Versuchen Sie es gleich noch einmal.",shutdown: "Herunterfahren",},commandPalette: {@@ -938,6 +940,11 @@ export const de = {},settings: {accounts: {+ signsInAs: "Meldet sich als {username} an",+ signsInAsOwner: "Meldet sich als {alias} oder {username} an",+ signInName: "Ihr Anmeldename",+ signInNameDescription: "Der Name, mit dem Sie sich anmelden, wenn diese Installation mehr als ein Konto hat. unsloth funktioniert immer auch. Leer lassen, um nur unsloth zu verwenden.",+ signInNameSave: "Name speichern",title: "Konten",description: "Private Unsloth-Konten anlegen. Neue Nutzer melden sich mit einem einmaligen Einrichtungscode an und wählen ein Passwort.",username: "Benutzername",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 24920146fdc..f48bb221b4a 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -846,6 +846,8 @@ export const en = {guidedTour: "Guided Tour",help: "Help",logOut: "Log out",+ logOutNeedsPassword: "Set a password in Settings > Remote access before logging out, so you can sign back in.",+ logOutFailed: "Couldn't log out safely. Try again in a moment.",shutdown: "Shutdown",},commandPalette: {@@ -991,6 +993,11 @@ export const en = {},settings: {accounts: {+ signsInAs: "Signs in as {username}",+ signsInAsOwner: "Signs in as {alias} or {username}",+ signInName: "Your sign-in name",+ signInNameDescription: "The name you type to sign in when this installation has more than one account. unsloth always works too. Leave empty to use only unsloth.",+ signInNameSave: "Save name",title: "Accounts",description: "Create private Unsloth accounts. New users sign in with a one-time setup code and choose a password.",username: "Username",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 5ccb7717c1c..7c839aaa7f4 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -792,6 +792,8 @@ export const es = {guidedTour: "Recorrido guiado",help: "Ayuda",logOut: "Cerrar sesión",+ logOutNeedsPassword: "Define una contraseña en Ajustes > Acceso remoto antes de cerrar sesión para poder volver a entrar.",+ logOutFailed: "No se pudo cerrar sesión de forma segura. Inténtalo de nuevo en un momento.",shutdown: "Apagar",},commandPalette: {@@ -937,6 +939,11 @@ export const es = {},settings: {accounts: {+ signsInAs: "Inicia sesión como {username}",+ signsInAsOwner: "Inicia sesión como {alias} o {username}",+ signInName: "Tu nombre de inicio de sesión",+ signInNameDescription: "El nombre que escribes para iniciar sesión cuando esta instalación tiene más de una cuenta. unsloth también funciona siempre. Déjalo vacío para usar solo unsloth.",+ signInNameSave: "Guardar nombre",title: "Cuentas",description: "Crea cuentas privadas de Unsloth. 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",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 0c923ce286e..f7181dde841 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -793,6 +793,8 @@ export const fr = {guidedTour: "Visite guidée",help: "Aide",logOut: "Se déconnecter",+ logOutNeedsPassword: "Définissez un mot de passe dans Paramètres > Accès à distance avant de vous déconnecter, pour pouvoir vous reconnecter.",+ logOutFailed: "Impossible de se déconnecter en toute sécurité. Réessayez dans un instant.",shutdown: "Arrêter",},commandPalette: {@@ -938,6 +940,11 @@ export const fr = {},settings: {accounts: {+ signsInAs: "Se connecte en tant que {username}",+ signsInAsOwner: "Se connecte en tant que {alias} ou {username}",+ signInName: "Votre nom de connexion",+ signInNameDescription: "Le nom à saisir pour vous connecter quand cette installation compte plusieurs comptes. unsloth fonctionne toujours aussi. Laissez vide pour n'utiliser que unsloth.",+ signInNameSave: "Enregistrer le nom",title: "Comptes",description: "Créez des comptes Unsloth privés. Les nouveaux utilisateurs se connectent avec un code de configuration à usage unique et choisissent un mot de passe.",username: "Nom d'utilisateur",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 7ed6dbd6fdf..15850375778 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -875,6 +875,8 @@ export const he = {guidedTour: "סיור מודרך",help: "עזרה",logOut: "התנתקות",+ logOutNeedsPassword: "לפני ההתנתקות, הגדירו סיסמה בהגדרות > גישה מרחוק כדי שתוכלו להתחבר שוב.",+ logOutFailed: "לא ניתן היה להתנתק בבטחה. נסו שוב בעוד רגע.",shutdown: "כיבוי",},commandPalette: {@@ -1019,6 +1021,11 @@ export const he = {},settings: {accounts: {+ signsInAs: "מתחבר בתור {username}",+ signsInAsOwner: "מתחבר בתור {alias} או {username}",+ signInName: "שם ההתחברות שלך",+ signInNameDescription: "השם שמקלידים כדי להתחבר כשבהתקנה הזו יש יותר מחשבון אחד. גם unsloth תמיד עובד. השאירו ריק כדי להשתמש רק ב-unsloth.",+ signInNameSave: "שמירת השם",title: "חשבונות",description:"צור חשבונות Unsloth פרטיים. משתמשים חדשים יתחברו באמצעות קוד הגדרה חד-פעמי ויבחרו סיסמה.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 799323bab72..512f4e9c7e5 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -793,6 +793,8 @@ export const hi = {guidedTour: "गाइडेड टूर",help: "सहायता",logOut: "लॉग आउट",+ logOutNeedsPassword: "लॉग आउट करने से पहले सेटिंग्स > रिमोट एक्सेस में पासवर्ड सेट करें, ताकि आप फिर से साइन इन कर सकें।",+ logOutFailed: "सुरक्षित रूप से लॉग आउट नहीं हो सका। थोड़ी देर बाद फिर से कोशिश करें।",shutdown: "शटडाउन",},commandPalette: {@@ -937,6 +939,11 @@ export const hi = {},settings: {accounts: {+ signsInAs: "{username} के रूप में साइन इन करता है",+ signsInAsOwner: "{alias} या {username} के रूप में साइन इन करता है",+ signInName: "आपका साइन-इन नाम",+ signInNameDescription: "जब इस इंस्टॉलेशन में एक से ज़्यादा अकाउंट हों, तब साइन इन के लिए टाइप किया जाने वाला नाम। unsloth भी हमेशा काम करता है। सिर्फ़ unsloth इस्तेमाल करने के लिए खाली छोड़ें।",+ signInNameSave: "नाम सेव करें",title: "खाते",description: "निजी Unsloth खाते बनाएँ। नए उपयोगकर्ता एक बार इस्तेमाल होने वाले सेटअप कोड से साइन इन करते हैं और पासवर्ड चुनते हैं।",username: "उपयोगकर्ता नाम",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex c8c6e31a53a..d43c120159f 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -694,6 +694,8 @@ export const it = {guidedTour: "Tour guidato",help: "Aiuto",logOut: "Esci",+ logOutNeedsPassword: "Imposta una password in Impostazioni > Accesso remoto prima di uscire, così potrai accedere di nuovo.",+ logOutFailed: "Impossibile uscire in modo sicuro. Riprova tra un momento.",shutdown: "Arresta",},commandPalette: {@@ -839,6 +841,11 @@ export const it = {},settings: {accounts: {+ signsInAs: "Accede come {username}",+ signsInAsOwner: "Accede come {alias} o {username}",+ signInName: "Il tuo nome di accesso",+ signInNameDescription: "Il nome da digitare per accedere quando questa installazione ha più di un account. Anche unsloth funziona sempre. Lascia vuoto per usare solo unsloth.",+ signInNameSave: "Salva nome",title: "Account",description: "Crea account Unsloth privati. I nuovi utenti accedono con un codice di configurazione monouso e scelgono una password.",username: "Nome utente",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 51b9eeaf305..a9e6034defd 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -791,6 +791,8 @@ export const ja = {guidedTour: "ガイドツアー",help: "ヘルプ",logOut: "ログアウト",+ logOutNeedsPassword: "ログアウトする前に、設定 > リモートアクセスでパスワードを設定してください。再びサインインするために必要です。",+ logOutFailed: "安全にログアウトできませんでした。しばらくしてからもう一度お試しください。",shutdown: "シャットダウン",},commandPalette: {@@ -935,6 +937,11 @@ export const ja = {},settings: {accounts: {+ signsInAs: "{username} としてサインイン",+ signsInAsOwner: "{alias} または {username} としてサインイン",+ signInName: "サインイン名",+ signInNameDescription: "このインストールに複数のアカウントがあるときにサインインで入力する名前です。unsloth も常に使えます。空欄にすると unsloth のみになります。",+ signInNameSave: "名前を保存",title: "アカウント",description: "個別の Unsloth アカウントを作成します。新しいユーザーは一度きりのセットアップコードでサインインし、パスワードを設定します。",username: "ユーザー名",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 3b61b4f3230..9212dc0f8e1 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -789,6 +789,8 @@ export const ko = {guidedTour: "가이드 투어",help: "도움말",logOut: "로그아웃",+ logOutNeedsPassword: "로그아웃하기 전에 설정 > 원격 액세스에서 비밀번호를 설정하세요. 다시 로그인하려면 필요합니다.",+ logOutFailed: "안전하게 로그아웃하지 못했습니다. 잠시 후 다시 시도하세요.",shutdown: "종료",},commandPalette: {@@ -933,6 +935,11 @@ export const ko = {},settings: {accounts: {+ signsInAs: "{username}(으)로 로그인",+ signsInAsOwner: "{alias} 또는 {username}(으)로 로그인",+ signInName: "로그인 이름",+ signInNameDescription: "이 설치에 계정이 둘 이상일 때 로그인할 때 입력하는 이름입니다. unsloth도 항상 사용할 수 있습니다. 비워 두면 unsloth만 사용합니다.",+ signInNameSave: "이름 저장",title: "계정",description: "개별 Unsloth 계정을 만듭니다. 새 사용자는 일회용 설정 코드로 로그인한 뒤 비밀번호를 정합니다.",username: "사용자 이름",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 67c0159e5f9..d7e1424624a 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -792,6 +792,8 @@ export const ptBR = {guidedTour: "Tour guiado",help: "Ajuda",logOut: "Sair",+ logOutNeedsPassword: "Defina uma senha em Configurações > Acesso remoto antes de sair, para conseguir entrar de novo.",+ logOutFailed: "Não foi possível sair com segurança. Tente de novo em instantes.",shutdown: "Desligar",},commandPalette: {@@ -936,6 +938,11 @@ export const ptBR = {},settings: {accounts: {+ signsInAs: "Entra como {username}",+ signsInAsOwner: "Entra como {alias} ou {username}",+ signInName: "Seu nome de login",+ signInNameDescription: "O nome que você digita para entrar quando esta instalação tem mais de uma conta. unsloth também funciona sempre. Deixe vazio para usar só unsloth.",+ signInNameSave: "Salvar nome",title: "Contas",description: "Crie contas privadas do Unsloth. Novos usuários entram com um código de configuração de uso único e escolhem uma senha.",username: "Nome de usuário",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 461824bbdb9..b8f0ed0d0f0 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -792,6 +792,8 @@ export const ru = {guidedTour: "Обзор интерфейса",help: "Справка",logOut: "Выйти",+ logOutNeedsPassword: "Перед выходом задайте пароль в разделе Настройки > Удалённый доступ, чтобы потом снова войти.",+ logOutFailed: "Не удалось безопасно выйти. Повторите попытку чуть позже.",shutdown: "Выключить",},commandPalette: {@@ -936,6 +938,11 @@ export const ru = {},settings: {accounts: {+ signsInAs: "Входит как {username}",+ signsInAsOwner: "Входит как {alias} или {username}",+ signInName: "Ваше имя для входа",+ signInNameDescription: "Имя, которое вы вводите для входа, когда в этой установке больше одной учётной записи. unsloth тоже всегда работает. Оставьте пустым, чтобы использовать только unsloth.",+ signInNameSave: "Сохранить имя",title: "Учётные записи",description: "Создавайте отдельные учётные записи Unsloth. Новые пользователи входят по одноразовому коду настройки и задают пароль.",username: "Имя пользователя",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 8c97a1d66a8..a1082654c7c 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -893,6 +893,8 @@ export const sv = {guidedTour: "Guidad tur",help: "Hjälp",logOut: "Logga ut",+ logOutNeedsPassword: "Ange ett lösenord under Inställningar > Fjärråtkomst innan du loggar ut, så att du kan logga in igen.",+ logOutFailed: "Det gick inte att logga ut säkert. Försök igen om en stund.",shutdown: "Stäng av",},commandPalette: {@@ -1039,6 +1041,11 @@ export const sv = {},settings: {accounts: {+ signsInAs: "Loggar in som {username}",+ signsInAsOwner: "Loggar in som {alias} eller {username}",+ signInName: "Ditt inloggningsnamn",+ signInNameDescription: "Namnet du skriver för att logga in när installationen har mer än ett konto. unsloth fungerar alltid också. Lämna tomt för att bara använda unsloth.",+ signInNameSave: "Spara namn",title: "Konton",description:"Skapa privata Unsloth-konton. Nya användare loggar in med en engångskod för konfiguration och väljer ett lösenord.",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex b955336d365..d776773b8a3 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -787,6 +787,8 @@ export const zhCN = {guidedTour: "引导教程",help: "帮助",logOut: "退出登录",+ logOutNeedsPassword: "退出登录前,请先在 设置 > 远程访问 中设置密码,以便重新登录。",+ logOutFailed: "无法安全退出登录,请稍后重试。",shutdown: "关闭服务",},commandPalette: {@@ -931,6 +933,11 @@ export const zhCN = {},settings: {accounts: {+ signsInAs: "以 {username} 登录",+ signsInAsOwner: "以 {alias} 或 {username} 登录",+ signInName: "你的登录名",+ signInNameDescription: "当此安装有多个账户时,登录时输入的名称。unsloth 也始终可用。留空则只使用 unsloth。",+ signInNameSave: "保存名称",title: "账户",description: "创建独立的 Unsloth 账户。新用户使用一次性设置码登录并设置密码。",username: "用户名",diff --git a/studio/frontend/tests/account-desktop-auth.test.ts b/studio/frontend/tests/account-desktop-auth.test.tsindex 88b8c8c1914..6c6ec460f90 100644--- a/studio/frontend/tests/account-desktop-auth.test.ts+++ b/studio/frontend/tests/account-desktop-auth.test.ts@@ -2,6 +2,8 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import ts from "@typescript/typescript6";import test from "node:test";import { loadWithStubs } from "./helpers/module-stubs.ts";@@ -9,6 +11,8 @@ type AutoAuth = {tauriAutoAuth(options?: { force?: boolean }): Promise<boolean>;isTauriLoginRequired(): boolean;getTauriAuthFailure(): string | null;+ markDesktopSignedOut(): Promise<void>;+ continueAsDesktopOwner(): Promise<boolean>;};type Guards = {@@ -17,12 +21,24 @@ type Guards = {requirePasswordChangeFlow(): Promise<void>;};-function fixture(t: { after(fn: () => void): void }, tauri = true) {+function fixture(+ t: { after(fn: () => void): void },+ tauri = true,+ // The Rust shell's sign-out marker file, shared by every window and every launch.+ shell = { signedOut: false },+) {const originalWindow = globalThis.window;const originalFetch = globalThis.fetch;const events: string[] = [];Object.assign(globalThis, {- window: { dispatchEvent: (event: Event) => events.push(event.type) },+ window: {+ dispatchEvent: (event: Event) => events.push(event.type),+ localStorage: {+ getItem: () => null,+ setItem: () => undefined,+ removeItem: () => undefined,+ },+ },});t.after(() => {Object.assign(globalThis, { window: originalWindow, fetch: originalFetch });@@ -32,6 +48,7 @@ function fixture(t: { after(fn: () => void): void }, tauri = true) {let passwordChange = false;let response: unknown = { access_token: "owner-access", refresh_token: "owner-refresh" };let invokeCalls = 0;+ const invokes: unknown[][] = [];let refreshCalls = 0;let refreshSucceeds = false;let refreshOutcome: "ok" | "rejected" | "unavailable" | null = null;@@ -91,9 +108,13 @@ function fixture(t: { after(fn: () => void): void }, tauri = true) {},},"@tauri-apps/api/core": {- invoke: async (command: string) => {+ invoke: async (command: string, args?: unknown) => {+ invokes.push([command, args]);+ if (command === "desktop_mark_signed_out") return void (shell.signedOut = true);+ if (command === "desktop_clear_signed_out") return void (shell.signedOut = false);assert.equal(command, "desktop_auth");invokeCalls++;+ if (shell.signedOut) return { signed_out: true };if (response instanceof Error) throw response;return response;},@@ -116,7 +137,7 @@ function fixture(t: { after(fn: () => void): void }, tauri = true) {return new Response(JSON.stringify(status), { status: 200 });};return {- auth, guards, session, events, navigations, loginModes, transitions,+ auth, guards, session, events, navigations, loginModes, transitions, shell,setResponse: (value: unknown) => { response = value; },setStatus: (value: typeof status) => { status = value; },setRefreshSucceeds: (value: boolean) => { refreshSucceeds = value; },@@ -126,6 +147,7 @@ function fixture(t: { after(fn: () => void): void }, tauri = true) {get access() { return access; },get refresh() { return refresh; },get invokeCalls() { return invokeCalls; },+ invokes,get refreshCalls() { return refreshCalls; },get statusCalls() { return statusCalls; },};@@ -336,3 +358,150 @@ test("browser mode never invokes the desktop shell", async (t) => {assert.equal(await f.auth.tauriAutoAuth({ force: true }), false);assert.equal(f.invokeCalls, 0);});++const SINGLE_SEEDED = { initialized: true, requires_password_change: true, login_mode: "single" };++test("an explicit desktop logout keeps the shell secret from signing the owner back in", async (t) => {+ const f = fixture(t);+ // A desktop owner who never set a password: the server still reports the seeded one.+ f.setStatus(SINGLE_SEEDED);+ await f.auth.markDesktopSignedOut();+ assert.equal(f.shell.signedOut, true);+ assert.equal(f.auth.isTauriLoginRequired(), true);+ assert.equal(await f.auth.tauriAutoAuth({ force: true }), true);+ assert.equal(await f.auth.tauriAutoAuth(), false);+ assert.equal(f.access, null);+ assert.deepEqual(f.navigations, [+ { to: "/login", replace: true },+ { to: "/login", replace: true },+ ]);+ assert.equal(f.auth.getTauriAuthFailure(), null);+ // The seeded-password setup page is no way back in for the desktop, so the guards keep login.+ await f.guards.requireGuest();+ await assert.rejects(f.guards.requireAuth(), { to: "/login" });+ await assert.rejects(f.guards.requirePasswordChangeFlow(), { to: "/login" });+});++test("a quit right after Log out cannot restore a session the webview never finished removing", async (t) => {+ const first = fixture(t);+ await first.auth.markDesktopSignedOut();+ // WebView2 lost the token removal: the relaunch still holds the old session, but the shell holds the marker.+ const relaunched = fixture(t, true, first.shell);+ relaunched.session.storeAuthTokens("stale-owner", "stale-refresh");+ relaunched.setRefreshSucceeds(true);+ assert.equal(await relaunched.auth.tauriAutoAuth({ force: true }), true);+ assert.equal(relaunched.access, null);+ assert.equal(relaunched.refreshCalls, 0);+ assert.equal(relaunched.auth.isTauriLoginRequired(), true);+ assert.deepEqual(relaunched.navigations, [{ to: "/login", replace: true }]);+});++test("Continue as owner clears the sign-out and signs a single-account owner in", async (t) => {+ const f = fixture(t);+ f.setStatus(SINGLE_SEEDED);+ await f.auth.markDesktopSignedOut();+ await f.auth.tauriAutoAuth({ force: true });+ assert.equal(await f.auth.continueAsDesktopOwner(), true);+ assert.equal(f.shell.signedOut, false);+ assert.equal(f.access, "owner-access");+ assert.equal(f.auth.isTauriLoginRequired(), false);+ assert.deepEqual(f.transitions, [{ account: "unsloth", route: "/chat" }]);+});++test("Continue as owner on a multi-account install leaves the login form up", async (t) => {+ const f = fixture(t);+ f.setResponse(multi);+ await f.auth.markDesktopSignedOut();+ assert.equal(await f.auth.continueAsDesktopOwner(), false);+ assert.equal(f.access, null);+ assert.equal(f.auth.isTauriLoginRequired(), true);+});++function sidebarSignOut(scope: Record<string, unknown>): () => Promise<void> {+ const source = readFileSync(new URL("../src/components/app-sidebar.tsx", import.meta.url), "utf8");+ const tree = ts.createSourceFile("app-sidebar.tsx", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let handler = "";+ const visit = (node: ts.Node) => {+ if (ts.isFunctionDeclaration(node) && node.name?.text === "signOut") handler = node.getText(tree);+ ts.forEachChild(node, visit);+ };+ visit(tree);+ assert.ok(handler);+ const { outputText } = ts.transpileModule(`return (${handler});`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ });+ return new Function(...Object.keys(scope), outputText)(...Object.values(scope));+}++type SignOutCase = { tauri: boolean; owner: boolean; status?: unknown; offline?: boolean; markerFails?: boolean };+async function runSignOut({ tauri, owner, status, offline, markerFails }: SignOutCase): Promise<string[]> {+ const events: string[] = [];+ await sidebarSignOut({+ isTauri: tauri,+ isOwner: owner,+ window: { dispatchEvent: () => true },+ Event,+ AUTH_SESSION_ENDING_EVENT: "ending",+ fetchAuthStatus: async () => {+ events.push("status");+ if (status === undefined) throw new Error("offline");+ return status;+ },+ toast: { error: () => events.push("toast") },+ t: (key: string) => key,+ useSettingsDialogStore: { getState: () => ({ openDialog: (tab: string) => events.push(`open:${tab}`) }) },+ markDesktopSignedOut: async () => {+ if (markerFails) throw new Error("permission denied");+ events.push("signed-out");+ },+ logout: async () => {+ events.push("logout");+ if (offline) throw new TypeError("Failed to fetch");+ },+ clearAuthTokens: () => events.push("clear"),+ navigate: ({ to }: { to: string }) => events.push(`navigate:${to}`),+ })();+ return events;+}++test("desktop Log out suppresses auto-auth before revoking, and still clears the session offline", async () => {+ const seeded = { login_mode: "single", requires_password_change: true };+ assert.deepEqual(await runSignOut({ tauri: true, owner: true, status: seeded }), [+ "status", "signed-out", "logout", "navigate:/login",+ ]);+ assert.deepEqual(await runSignOut({ tauri: true, owner: true, status: seeded, offline: true }), [+ "status", "signed-out", "logout", "clear", "navigate:/login",+ ]);+ // A managed account has no seeded password to worry about; the web build has no shell secret to hold back.+ assert.deepEqual(await runSignOut({ tauri: true, owner: false }), ["signed-out", "logout", "navigate:/login"]);+ assert.deepEqual(await runSignOut({ tauri: false, owner: true }), ["logout", "navigate:/login"]);+});++test("a multi-account desktop owner on the seeded password sets one before Log out", async () => {+ const events = await runSignOut({+ tauri: true,+ owner: true,+ status: { login_mode: "multi", requires_password_change: true },+ });+ assert.deepEqual(events, ["status", "toast", "open:remote-lan"]);+});++test("desktop Log out keeps the session when the password state or the marker is unknown", async () => {+ // Status unreachable: a seeded multi-account owner would be locked out.+ assert.deepEqual(await runSignOut({ tauri: true, owner: true }), ["status", "toast"]);+ // Marker not written: a relaunch would sign straight back in.+ const single = { login_mode: "single", requires_password_change: false };+ assert.deepEqual(await runSignOut({ tauri: true, owner: true, status: single, markerFails: true }), [+ "status", "toast",+ ]);+ assert.deepEqual(await runSignOut({ tauri: true, owner: false, markerFails: true }), ["toast"]);+});++test("a second desktop window cannot auto-sign in after another window logs out", async (t) => {+ const first = fixture(t);+ await first.auth.markDesktopSignedOut();+ const second = fixture(t, true, first.shell);+ // API recovery in the other window, after its tokens were cleared under it.+ assert.equal(await second.auth.tauriAutoAuth(), false);+ assert.equal(second.access, null);+});diff --git a/studio/frontend/tests/account-settings-ui.test.ts b/studio/frontend/tests/account-settings-ui.test.tsindex 2351f04821b..0ee9e6675d5 100644--- a/studio/frontend/tests/account-settings-ui.test.ts+++ b/studio/frontend/tests/account-settings-ui.test.ts@@ -45,6 +45,9 @@ function translate(key: string, values: Record<string, string> = {}) {type TabOptions = {stallRefresh?: boolean;accounts?: Record<string, unknown>[];+ // What the sidebar footer shows: the local profile store.+ localProfile?: { displayName: string; avatarDataUrl: string | null };+ ownerPasswordPending?: boolean;};function tab(owner = true,@@ -97,7 +100,15 @@ function tab(},},"@/features/auth": { useIsAccountOwner: () => owner },- "@/features/profile": { UserAvatar: "UserAvatar" },+ "@/features/profile": {+ UserAvatar: "UserAvatar",+ useUserProfileStore: (select: (state: unknown) => unknown) =>+ select(options.localProfile ?? { displayName: "", avatarDataUrl: null }),+ },+ "../components/change-password-dialog": {+ ChangePasswordDialog: "ChangePasswordDialog",+ useOwnPasswordPending: () => [options.ownerPasswordPending ?? false, () => {}],+ },"@hugeicons/core-free-icons": {},"@hugeicons/react": { HugeiconsIcon: "Icon" },"@/lib/tick-icon": {},@@ -179,6 +190,12 @@ function tab(calls.push(`delete:${accountId}`);accounts.splice(1);},+ setOwnerLoginAlias: async (alias: string | null) => {+ calls.push(`alias:${alias}`);+ const stored = alias?.trim().toLowerCase() || null;+ accounts[0].login_alias = stored;+ return stored;+ },setAccountModelAllowlist: async (accountId: string,allowlist: string[] | null,@@ -235,13 +252,31 @@ test("owner lists accounts without administrative actions on the owner row", asy(node) => node.props["data-testid"] === "account-unsloth",);assert.ok(ownerRow);- assert.equal(- nodes(ownerRow).filter((node) => node.type === "Button").length,- 0,+ // Only its own password, in an icon menu like the managed rows so no label can overflow the row.+ const trigger = nodes(ownerRow).filter((node) => node.type === "Button");+ assert.equal(trigger.length, 1);+ assert.equal(content(trigger[0]).trim(), "");+ assert.deepEqual(+ nodes(ownerRow)+ .filter((node) => node.type === "DropdownMenuItem")+ .map((node) => content(node).trim()),+ ["Change password"],);assert.match(content(tree), /Installation owner/);});+test("the owner row's password item opens the dialog, as Set password while the seeded one stands", async () => {+ for (const pending of [false, true]) {+ const ui = tab(true, null, { ownerPasswordPending: pending });+ const tree = await ui.initialize();+ const dialog = () => nodes(ui.render()).find((node) => node.type === "ChangePasswordDialog");+ assert.equal(dialog()?.props.open, false);+ assert.equal(dialog()?.props.initial, pending);+ await click(tree, pending ? "Set password" : "Change password");+ assert.equal(dialog()?.props.open, true);+ }+});+test("create shows a copyable expiring setup code once and regeneration replaces it", async () => {const ui = tab();let tree = await ui.initialize();@@ -528,3 +563,79 @@ test("model access edits one account's allowlist and an empty list restores ever);assert.ok(!content(view.render()).includes(en.settings.accounts.modelAccessLimited));});++test("rows show each profile name and avatar with the name to sign in with", async () => {+ const ui = tab(true, null, {+ accounts: [+ {+ account_id: "owner",+ username: "unsloth",+ role: "owner",+ is_active: true,+ created_at: "2026-09-01T12:00:00Z",+ login_alias: "riley",+ display_name: "Riley",+ avatar_url: "data:image/png;base64,AAAA",+ },+ {+ account_id: "alice-id",+ username: "alice",+ role: "user",+ is_active: true,+ created_at: "2026-09-01T12:00:00Z",+ },+ ],+ });+ const tree = await ui.initialize();+ const ownerRow = nodes(tree).find((node) => node.props["data-testid"] === "account-unsloth");+ const avatar = nodes(ownerRow).find((node) => node.type === "UserAvatar");+ assert.deepEqual([avatar?.props.name, avatar?.props.imageUrl], ["Riley", "data:image/png;base64,AAAA"]);+ assert.match(content(ownerRow), /Riley/);+ assert.match(content(ownerRow), /Signs in as riley or unsloth/);+ const aliceRow = nodes(tree).find((node) => node.props["data-testid"] === "account-alice");+ const aliceAvatar = nodes(aliceRow).find((node) => node.type === "UserAvatar");+ assert.deepEqual([aliceAvatar?.props.name, aliceAvatar?.props.imageUrl], ["alice", null]);+ assert.match(content(aliceRow), /Signs in as alice/);+ const input = nodes(tree).find((node) => node.props.id === "owner-sign-in-name");+ assert.equal(input?.props.value, "riley");+});++test("the owner sets a sign-in name and an empty one falls back to unsloth", async () => {+ const ui = tab();+ let tree = await ui.initialize();+ assert.match(content(tree), /Signs in as unsloth/);+ const type = (value: string) => {+ const input = nodes(tree).find((node) => node.props.id === "owner-sign-in-name");+ (input?.props.onChange as (event: unknown) => void)({ target: { value } });+ tree = ui.render();+ };+ const submit = async () => {+ await click(tree, "Save name");+ tree = ui.render();+ };+ type("Riley");+ await submit();+ assert.ok(ui.calls.includes("alias:Riley"));+ assert.match(content(tree), /Signs in as riley or unsloth/);+ type("");+ await submit();+ assert.ok(ui.calls.includes("alias:"));+ assert.match(content(tree), /Signs in as unsloth/);+ assert.doesNotMatch(content(tree), /riley or unsloth/);+});++test("the owner row matches the sidebar's local profile before the server copy and offers a password change", async () => {+ const ui = tab(true, null, {+ localProfile: { displayName: " Riley ", avatarDataUrl: "data:image/png;base64,LOCAL" },+ });+ const tree = await ui.initialize();+ const ownerRow = nodes(tree).find((node) => node.props["data-testid"] === "account-unsloth");+ const avatar = nodes(ownerRow).find((node) => node.type === "UserAvatar");+ assert.deepEqual([avatar?.props.name, avatar?.props.imageUrl], ["Riley", "data:image/png;base64,LOCAL"]);+ assert.match(content(ownerRow), /Riley/);+ assert.match(content(ownerRow), /Installation owner/);+ const aliceRow = nodes(tree).find((node) => node.props["data-testid"] === "account-alice");+ assert.ok(!content(aliceRow).includes("Change password"));+ // A managed account's row never borrows the owner's local profile.+ assert.equal(nodes(aliceRow).find((node) => node.type === "UserAvatar")?.props.imageUrl, null);+});diff --git a/studio/frontend/tests/audio-transcript-lifecycle.test.ts b/studio/frontend/tests/audio-transcript-lifecycle.test.tsindex 0fe8e053e0c..15437fd314a 100644--- a/studio/frontend/tests/audio-transcript-lifecycle.test.ts+++ b/studio/frontend/tests/audio-transcript-lifecycle.test.ts@@ -171,18 +171,20 @@ test("logout checks unsaved transcripts before revoking the session or navigatinassert.ok(protection);const sidebarTree = parse(sidebar);const handlers: string[] = [];+ // The menu item and the shortcut both call this one handler.function findLogout(node: ts.Node) {if (- ts.isArrowFunction(node) &&+ (ts.isArrowFunction(node) || ts.isFunctionDeclaration(node)) &&node.modifiers?.some((item) => item.kind === ts.SyntaxKind.AsyncKeyword) &&- node.body.getText(sidebarTree).includes("await logout()")+ node.body?.getText(sidebarTree).includes("await logout()")) {handlers.push(node.getText(sidebarTree));}ts.forEachChild(node, findLogout);}findLogout(sidebarTree);- assert.equal(handlers.length, 2);+ assert.equal(handlers.length, 1);+ assert.equal((sidebar.match(/void signOut\(\)/g) ?? []).length, 2);const execute = (expression: string, scope: Record<string, unknown>) => {const { outputText } = ts.transpileModule(`return (${expression});`, {compilerOptions: { target: ts.ScriptTarget.ES2022 },@@ -229,6 +231,8 @@ test("logout checks unsaved transcripts before revoking the session or navigatinwindow,Event,AUTH_SESSION_ENDING_EVENT: eventName,+ isTauri: false,+ isOwner: true,logout: async () => {events.push("logout");},diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.tsindex 8264d03a264..c92498dd0ab 100644--- a/studio/frontend/tests/keyboard-shortcuts.test.ts+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts@@ -1819,14 +1819,11 @@ test("the chat walk's bracket pair is reserved on macOS only", () => {assert.equal(defaultBindingFor(walk!, "primary", true), "Mod+Shift+BracketRight");});-// The desktop signs out through the OS account menu, so the chord can never fire there.-test("the logout row is not offered on the desktop build", async () => {+// The desktop signs out from the sidebar menu too, so its chord is offered there.+test("the logout row is offered on the desktop build", async () => {const logout = SHORTCUT_DEFS.find((def) => def.id === "logOut");- assert.equal(logout?.webOnly, true);- assert.deepEqual(- SHORTCUT_DEFS.filter((def) => def.webOnly).map((def) => def.id),- ["logOut"],- );+ assert.equal(logout?.webOnly, undefined);+ assert.deepEqual(SHORTCUT_DEFS.filter((def) => def.webOnly).map((def) => def.id), []);assert.match(KEYBOARD_SHORTCUTS_TAB, /!\(isTauri && def\.webOnly\)/);});diff --git a/studio/frontend/tests/login-account-modes.test.ts b/studio/frontend/tests/login-account-modes.test.tsindex e3ea72d4d89..0df00aaa66d 100644--- a/studio/frontend/tests/login-account-modes.test.ts+++ b/studio/frontend/tests/login-account-modes.test.ts@@ -60,6 +60,7 @@ function mountForm(},switched = false,failTransitionOnce = false,+ desktop: { continued: boolean; calls: string[] } | null = null,) {const state: unknown[] = [];let cursor = 0;@@ -93,7 +94,16 @@ function mountForm(},},"@/components/app-readiness": { useAppShellReadySignal: () => () => {} },- "@/lib/api-base": base,+ "@/lib/api-base": desktop ? { ...base, isTauri: true } : base,+ "../tauri-auto-auth": {+ clearDesktopSignedOut: async () => {+ desktop?.calls.push("clear");+ },+ continueAsDesktopOwner: async () => {+ desktop?.calls.push("continue");+ return desktop?.continued ?? false;+ },+ },"@/lib/account-transition": {normalizeAccountUsername: transition.normalizeAccountUsername,transitionBrowserAccount: async (@@ -667,3 +677,75 @@ test("a rejected refresh during a password change still drops the stored sessionassert.equal(session.clears, 1);assert.ok(requests.some((path) => path.endsWith("/api/auth/login")));});++test("desktop single mode offers Continue as owner instead of the seeded-password setup page", async (t) => {+ environment(t);+ // A desktop owner who never set a password: the server still reports the seeded one.+ globalThis.fetch = async () =>+ Response.json({ initialized: true, requires_password_change: true, login_mode: "single" });+ const desktop = { continued: true, calls: [] as string[] };+ const form = mountForm(client(), { access: null, change: false }, false, false, desktop);+ const tree = await form.initialize();+ assert.deepEqual(form.routes, []);+ assert.doesNotMatch(textContent(tree), /seeded credentials/);+ const owner = elements(tree).find(+ (element) => element.type === "Button" && textContent(element).trim() === "Continue as owner",+ );+ assert.ok(owner);+ (owner.props.onClick as () => void)();+ await tick();+ assert.deepEqual(desktop.calls, ["continue"]);+ assert.deepEqual(form.routes, ["/chat"]);+});++test("desktop Continue as owner that the server refuses keeps the form with a hint", async (t) => {+ environment(t);+ globalThis.fetch = async () =>+ Response.json({ initialized: true, requires_password_change: false, login_mode: "single" });+ const desktop = { continued: false, calls: [] as string[] };+ const form = mountForm(client(), { access: null, change: false }, false, false, desktop);+ const owner = elements(await form.initialize()).find(+ (element) => element.type === "Button" && textContent(element).trim() === "Continue as owner",+ );+ (owner?.props.onClick as () => void)();+ await tick();+ assert.deepEqual(form.routes, []);+ assert.match(textContent(form.render()), /Sign in with your username and password/);+});++test("multi mode asks for credentials, names the owner's sign-in name and offers no owner shortcut", async (t) => {+ environment(t);+ globalThis.fetch = async () =>+ Response.json({ initialized: true, requires_password_change: true, login_mode: "multi" });+ for (const desktop of [null, { continued: true, calls: [] as string[] }]) {+ const form = mountForm(client(), { access: null, change: false }, false, false, desktop);+ const tree = await form.initialize();+ assert.match(textContent(tree), /Installation owner\? Sign in as unsloth, or the sign-in name/);+ assert.doesNotMatch(textContent(tree), /Continue as owner/);+ assert.deepEqual(form.routes, []);+ }+});++test("a desktop password sign-in clears the explicit sign-out", async (t) => {+ environment(t);+ globalThis.fetch = async (input: RequestInfo | URL) =>+ String(input).endsWith("/status")+ ? Response.json({ initialized: true, requires_password_change: false, login_mode: "multi" })+ : Response.json(token);+ const desktop = { continued: false, calls: [] as string[] };+ const form = mountForm(client(), { access: null, change: false }, false, false, desktop);+ let tree = await form.initialize();+ const set = (id: string, value: string) =>+ (elements(tree).find((element) => element.props.id === id)?.props.onChange as (+ event: unknown,+ ) => void)({ target: { value } });+ set("username", "riley");+ tree = form.render();+ set("password", "owner-password");+ tree = form.render();+ const formElement = elements(tree).find((element) => element.type === "form");+ (formElement?.props.onSubmit as (event: unknown) => void)({ preventDefault() {} });+ await tick();+ await tick();+ assert.deepEqual(desktop.calls, ["clear"]);+});diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rsindex 69aa70abdd6..e286558637b 100644--- a/studio/src-tauri/src/desktop_auth.rs+++ b/studio/src-tauri/src/desktop_auth.rs@@ -20,6 +20,10 @@ pub enum DesktopAuthResponse {access_token: String,refresh_token: String,},+ // Built here, never parsed from the backend.+ SignedOut {+ signed_out: LoginRequired,+ },}// Literal values keep malformed successful responses from becoming a session.@@ -103,6 +107,44 @@ fn desktop_secret_path() -> Result<PathBuf, String> {Ok(auth_secret_path(&home_dir()?, ".desktop_secret"))}+// A file, not webview storage: WebView2 commits localStorage lazily, so a quit soon after Log out lost it.+fn signed_out_marker_path() -> Result<PathBuf, String> {+ Ok(auth_secret_path(&home_dir()?, ".desktop_signed_out"))+}++fn set_signed_out(path: &Path, signed_out: bool) -> Result<(), String> {+ let result = if signed_out {+ path.parent()+ .map_or(Ok(()), std::fs::create_dir_all)+ .and_then(|()| std::fs::write(path, b"1"))+ } else {+ match std::fs::remove_file(path) {+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ other => other,+ }+ };+ result.map_err(|e| format!("Could not record the desktop sign-out: {}", e))+}++fn signed_out_response(marker: &Path) -> Option<DesktopAuthResponse> {+ marker.exists().then_some(DesktopAuthResponse::SignedOut {+ signed_out: LoginRequired,+ })+}++#[tauri::command]+pub async fn desktop_mark_signed_out() -> Result<(), String> {+ // Under the auth lock, so no exchange already past the marker check can land after this returns.+ let _auth_guard = DESKTOP_AUTH_LOCK.lock().await;+ set_signed_out(&signed_out_marker_path()?, true)+}++#[tauri::command]+pub async fn desktop_clear_signed_out() -> Result<(), String> {+ let _auth_guard = DESKTOP_AUTH_LOCK.lock().await;+ set_signed_out(&signed_out_marker_path()?, false)+}+fn read_secret_if_exists(path: &Path) -> Result<Option<String>, String> {match std::fs::read_to_string(path) {Ok(s) => Ok(Some(s.trim().to_string())),@@ -366,6 +408,9 @@ async fn desktop_auth_inner(diagnostics: &DiagnosticsState,) -> Result<DesktopAuthResponse, String> {let _auth_guard = DESKTOP_AUTH_LOCK.lock().await;+ if let Some(signed_out) = signed_out_response(&signed_out_marker_path()?) {+ return Ok(signed_out);+ }let mut backend = current_backend_port(state).await?;if backend.source == PortSource::Discovered {diagnostics::record_attached_external_backend(diagnostics, backend.port);@@ -563,4 +608,20 @@ mod tests {"Running Unsloth backend is too old for this desktop app. Update that backend and restart.");}++ #[test]+ fn signed_out_marker_holds_desktop_auth_until_a_sign_in_clears_it() {+ let dir = tempfile::tempdir().unwrap();+ let marker = dir.path().join("auth").join(".desktop_signed_out");+ assert!(signed_out_response(&marker).is_none());+ set_signed_out(&marker, true).unwrap();+ let response = signed_out_response(&marker).unwrap();+ assert_eq!(+ serde_json::to_string(&response).unwrap(),+ r#"{"signed_out":true}"#+ );+ set_signed_out(&marker, false).unwrap();+ set_signed_out(&marker, false).unwrap();+ assert!(signed_out_response(&marker).is_none());+ }}diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 76d582a7955..e882db27f1b 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -2332,6 +2332,8 @@ fn main() {long_paths::windows_long_paths_status,long_paths::enable_windows_long_paths,desktop_auth::desktop_auth,+ desktop_auth::desktop_mark_signed_out,+ desktop_auth::desktop_clear_signed_out,desktop_update_policy::check_desktop_manual_update,desktop_update_policy::desktop_update_policy,desktop_updater::check_desktop_update,diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rsindex ffe348742f9..e8cbb824e2e 100644--- a/studio/src-tauri/src/native_file_dialogs.rs+++ b/studio/src-tauri/src/native_file_dialogs.rs@@ -846,9 +846,10 @@ fn select_export_session(Ok(crate::desktop_auth::DesktopAuthResponse::Tokens { access_token, .. }) => {Ok(access_token)}- Ok(crate::desktop_auth::DesktopAuthResponse::LoginRequired { .. }) => {- fallback.ok_or_else(|| LOGIN_REQUIRED.to_string())- }+ Ok(+ crate::desktop_auth::DesktopAuthResponse::LoginRequired { .. }+ | crate::desktop_auth::DesktopAuthResponse::SignedOut { .. },+ ) => fallback.ok_or_else(|| LOGIN_REQUIRED.to_string()),Err(error) => fallback.ok_or(error),}}diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 3225055c2f2..7e7f69d6da2 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -5164,6 +5164,15 @@ def provision_desktop_auth():typer.echo("Desktop auth ready.")+def _owner_login_alias(conn: sqlite3.Connection) -> Optional[str]:+ if "login_alias" not in {row[1] for row in conn.execute("PRAGMA table_info(auth_user)")}:+ return None+ row = conn.execute(+ "SELECT login_alias FROM auth_user WHERE username = ?", (DEFAULT_ADMIN_USERNAME,)+ ).fetchone()+ return row[0] if row else None++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 ""@@ -5175,8 +5184,10 @@ def _reset_password_username(conn: sqlite3.Connection, username: Optional[str])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)+ if _owner_login_alias(conn) != target:+ typer.echo("Error: account not found.", err = True)+ raise typer.Exit(1)+ target = DEFAULT_ADMIN_USERNAMEreturn target@@ -5203,6 +5214,7 @@ def reset_password(try:conn.execute("BEGIN IMMEDIATE")target = _reset_password_username(conn, username)+ alias = _owner_login_alias(conn) if target == DEFAULT_ADMIN_USERNAME else None_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)@@ -5210,7 +5222,8 @@ def reset_password(finally:conn.close()- typer.echo(f"New password for '{target}': {new_password}")+ signs_in_as = f" (also signs in as '{alias}')" if alias else ""+ typer.echo(f"New password for '{target}'{signs_in_as}: {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."