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
// 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";
import { en } from "../src/i18n/locales/en.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 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 mountForm(
client: typeof LoginClient,
session: {
access: string | null;
change: boolean;
owner?: boolean;
refresh?: boolean;
outcome?: "ok" | "rejected" | "unavailable";
clears?: number;
},
switched = false,
failTransitionOnce = false,
desktop: { continued: boolean; calls: string[] } | null = null,
) {
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": 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 (
account: transition.BrowserAccount | string,
route: string,
commit: () => void,
) => {
// Usernames are reusable, so key on the immutable account id when available.
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" },
"@/i18n": { useT: () => translate },
"@/components/ui/label": { Label: "Label" },
"@tanstack/react-router": {
Link: "Link",
useNavigate:
() =>
({ to }: { to: string }) => {
routes.push(to);
},
},
"@hugeicons/core-free-icons": { ViewIcon: "ViewIcon", ViewOffSlashIcon: "ViewOffSlashIcon" },
"@/lib/folder-icons": { ViewIcon: "ViewIcon", ViewOffSlashIcon: "ViewOffSlashIcon" },
"@hugeicons/react": { HugeiconsIcon: "HugeiconsIcon" },
"../api": {
refreshSession: async () => true,
refreshSessionOutcome: async () => session.outcome ?? "ok",
},
"../bootstrap-deadline": deadline,
"../session": {
clearAuthTokens: () => {
session.access = null;
session.refresh = false;
session.clears = (session.clears ?? 0) + 1;
},
getAuthToken: () => session.access,
hasAuthToken: () => Boolean(session.access),
hasRefreshToken: () => Boolean(session.refresh),
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 savedUsernames = elements(tree).filter(
(element) => element.props.autoComplete === "username",
);
assert.equal(savedUsernames.length, 1);
if (mode === "single") {
assert.equal(savedUsernames[0].props.value, "unsloth");
assert.equal(savedUsernames[0].props.readOnly, true);
}
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, []);
});
}
for (const mode of ["single", "multi"] as const) {
test(`${mode} change password form names the account for password managers`, async (t) => {
environment(t);
globalThis.fetch = async () =>
Response.json({
initialized: true,
requires_password_change: true,
login_mode: mode,
});
const form = mountForm(client(), { access: "access", change: true });
const tree = await form.initialize("change-password");
const savedUsernames = elements(tree).filter(
(element) => element.props.autoComplete === "username",
);
assert.equal(savedUsernames.length, 1);
assert.equal(savedUsernames[0].props.value, "alice");
});
}
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 restricts the legacy full-access hint in peer tabs", (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 the legacy hint restricted 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 restricts the legacy hint 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);
});
async function submitPasswordChange(
session: Parameters<typeof mountForm>[1],
requests: string[],
) {
globalThis.fetch = async (path) => {
requests.push(String(path));
return String(path).endsWith("/status")
? Response.json({
initialized: true,
requires_password_change: true,
login_mode: "single",
})
: Response.json(token);
};
const form = mountForm(client(), session);
let tree = await form.initialize("change-password");
for (const [id, value] of [
["current-password", "old-password-1"],
["new-password", "new-password-1"],
["confirm-password", "new-password-1"],
]) {
const change = elements(tree).find((element) => element.props.id === id)
?.props.onChange as (event: unknown) => void;
change({ target: { value } });
tree = form.render("change-password");
}
const submit = elements(tree).find((element) => element.type === "form")
?.props.onSubmit as (event: unknown) => Promise<void>;
await submit({ preventDefault() {} });
return form.render("change-password");
}
test("a busy refresh during a password change keeps the session and asks to retry", async (t) => {
environment(t);
const requests: string[] = [];
const session: Parameters<typeof mountForm>[1] = {
access: "access",
change: true,
refresh: true,
outcome: "unavailable",
};
const tree = await submitPasswordChange(session, requests);
assert.equal(session.access, "access");
assert.equal(session.refresh, true);
assert.equal(session.clears ?? 0, 0);
assert.ok(!requests.some((path) => path.endsWith("/api/auth/change-password")));
assert.match(textContent(tree), /Unsloth is busy/);
});
test("a rejected refresh during a password change still drops the stored session", async (t) => {
environment(t);
const requests: string[] = [];
const session: Parameters<typeof mountForm>[1] = {
access: "access",
change: true,
refresh: true,
outcome: "rejected",
};
await submitPasswordChange(session, requests);
assert.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"]);
});