Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Keep Studio windows signed in during concurrent session refresh (#16468)

Daniel Hanc1a651307426
diff --git a/studio/frontend/src/features/auth/api.ts b/studio/frontend/src/features/auth/api.ts
index db9284d9a78..94895fe7ddb 100644
--- a/studio/frontend/src/features/auth/api.ts
+++ b/studio/frontend/src/features/auth/api.ts
@@ -5,7 +5,9 @@ import { accountTransitionPending } from "@/lib/account-transition";
import { apiUrl, getApiPort, isTauri } from "@/lib/api-base";
import {
clearAuthTokens,
+ ensureAuthSessionMark,
getAuthToken,
+ getAuthSessionMark,
getRefreshToken,
mustChangePassword,
setMustChangePassword,
@@ -300,6 +302,7 @@ export type RefreshOutcome = "ok" | "rejected" | "unavailable";
// Never abort an in-flight POST: if the server already rotated the pair, dropping its answer loses the new token.
const REFRESH_MAX_ATTEMPTS = 3;
const REFRESH_BUDGET_MS = 8000;
+const REFRESH_LOCK_WAIT_MS = 8000;
const REFRESH_RETRY_DEFAULT_MS = 1000;
const REFRESH_RETRY_MIN_MS = 250;
const REFRESH_RETRY_MAX_MS = 5000;
@@ -316,7 +319,7 @@ function refreshRetryDelay(response: Response): number {
);
}
-async function runRefresh(refreshToken: string): Promise<RefreshOutcome> {
+async function runRefresh(refreshToken: string, preserveSessionMark = false): Promise<RefreshOutcome> {
const startGeneration = logoutGeneration;
const startedAt = Date.now();
const superseded = (): RefreshOutcome | null => {
@@ -349,7 +352,7 @@ async function runRefresh(refreshToken: string): Promise<RefreshOutcome> {
}
const stale = superseded();
if (stale) return stale;
- storeAuthTokens(payload.access_token, payload.refresh_token);
+ storeAuthTokens(payload.access_token, payload.refresh_token, preserveSessionMark);
setMustChangePassword(payload.must_change_password ?? false);
return "ok";
}
@@ -376,7 +379,37 @@ export async function refreshSessionOutcome(): Promise<RefreshOutcome> {
return refreshInflight;
}
- const promise = runRefresh(refreshToken);
+ const generation = logoutGeneration;
+ const locks = typeof window !== "undefined" ? window.navigator?.locks : undefined;
+ const sessionMark = locks ? ensureAuthSessionMark() : null;
+ if (getRefreshToken() !== refreshToken) return "unavailable";
+ const promise = locks
+ ? (async (): Promise<RefreshOutcome> => {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), REFRESH_LOCK_WAIT_MS);
+ try {
+ return await locks.request(
+ "unsloth-auth-refresh",
+ { signal: controller.signal },
+ async (): Promise<RefreshOutcome> => {
+ // Only bound the queue; a submitted POST may already have rotated.
+ clearTimeout(timer);
+ if (generation !== logoutGeneration) return "rejected";
+ const current = getRefreshToken();
+ if (!current) return "rejected";
+ if (accountTransitionPending() || getAuthSessionMark() !== sessionMark)
+ return "unavailable";
+ if (current !== refreshToken) return "ok";
+ return runRefresh(current, true);
+ },
+ );
+ } catch {
+ return "unavailable";
+ } finally {
+ clearTimeout(timer);
+ }
+ })()
+ : runRefresh(refreshToken);
refreshInflight = promise;
refreshInflightToken = refreshToken;
try {
diff --git a/studio/frontend/src/features/auth/session.ts b/studio/frontend/src/features/auth/session.ts
index eaf978be01b..f38d7d5831e 100644
--- a/studio/frontend/src/features/auth/session.ts
+++ b/studio/frontend/src/features/auth/session.ts
@@ -59,9 +59,26 @@ export function getRefreshToken(): string | null {
return localStorage.getItem(AUTH_REFRESH_TOKEN_KEY);
}
+export function getAuthSessionMark(): string | null {
+ if (!canUseStorage()) return null;
+ return localStorage.getItem(AUTH_SESSION_MARK_KEY);
+}
+
+/** Give sessions created before session markers the same cross-window boundary as new ones. */
+export function ensureAuthSessionMark(): string | null {
+ if (!canUseStorage()) return null;
+ let mark = getAuthSessionMark();
+ if (!mark) {
+ mark = `${Date.now()}.${Math.random()}`;
+ localStorage.setItem(AUTH_SESSION_MARK_KEY, mark);
+ }
+ return mark;
+}
+
export function storeAuthTokens(
accessToken: string,
refreshToken: string,
+ preserveSessionMark = false,
): void {
// must_change_password is set via setMustChangePassword() so CodeQL does not flag the JWT writes.
if (!canUseStorage()) return;
@@ -70,10 +87,12 @@ export function storeAuthTokens(
localStorage.setItem(AUTH_REFRESH_TOKEN_KEY, refreshToken);
if (sessionStarted) {
authSessionEpoch += 1;
- localStorage.setItem(
- AUTH_SESSION_MARK_KEY,
- `${Date.now()}.${Math.random()}`,
- );
+ if (!preserveSessionMark || !getAuthSessionMark()) {
+ localStorage.setItem(
+ AUTH_SESSION_MARK_KEY,
+ `${Date.now()}.${Math.random()}`,
+ );
+ }
window.dispatchEvent(new Event(AUTH_SESSION_STORED_EVENT));
} else if (!localStorage.getItem(AUTH_SESSION_MARK_KEY)) {
// Backfill the key for pre-existing sessions so a later sign-out has something to remove (and
diff --git a/studio/frontend/tests/account-session-routing.test.ts b/studio/frontend/tests/account-session-routing.test.ts
index ef5b27ee287..8b59f45cfd6 100644
--- a/studio/frontend/tests/account-session-routing.test.ts
+++ b/studio/frontend/tests/account-session-routing.test.ts
@@ -6,6 +6,30 @@ import test from "node:test";
import { loadWithStubs } from "./helpers/module-stubs.ts";
import type * as Session from "../src/features/auth/session.ts";
+test("refresh preserves a backfilled session marker when access token is missing", (t) => {
+ const previousWindow = globalThis.window;
+ const previousStorage = globalThis.localStorage;
+ const values = new Map([["unsloth_auth_refresh_token", "old-refresh"]]);
+ const storage = {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => { values.set(key, value); },
+ } as unknown as Storage;
+ globalThis.localStorage = storage;
+ globalThis.window = { localStorage: storage, addEventListener() {}, dispatchEvent() {} } as unknown as Window & typeof globalThis;
+ t.after(() => { globalThis.window = previousWindow; globalThis.localStorage = previousStorage; });
+ const session = loadWithStubs<typeof Session>(new URL("../src/features/auth/session.ts", import.meta.url), {
+ "@/lib/api-base": { isTauri: false },
+ "@/lib/account-transition": { installAccountTransitionListener: () => {} },
+ "./login-client": { getLoginMode: () => "single" },
+ "./session-events": { AUTH_SESSION_STORED_EVENT: "stored" },
+ });
+ const mark = session.ensureAuthSessionMark();
+ assert.ok(mark);
+ session.storeAuthTokens("new-access", "new-refresh", true);
+ assert.equal(session.getAuthSessionMark(), mark);
+ assert.equal(session.getRefreshToken(), "new-refresh");
+});
+
for (const [desktop, loginMode, change, expected] of [
[true, "single", true, "/chat"],
[true, "single", false, "/chat"],
diff --git a/studio/frontend/tests/auth-refresh-transient.test.ts b/studio/frontend/tests/auth-refresh-transient.test.ts
index a4a4ea32a9c..fabc612b5bc 100644
--- a/studio/frontend/tests/auth-refresh-transient.test.ts
+++ b/studio/frontend/tests/auth-refresh-transient.test.ts
@@ -28,6 +28,7 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
const previousWindow = globalThis.window;
const previousFetch = globalThis.fetch;
const previousSetTimeout = globalThis.setTimeout;
+ const previousClearTimeout = globalThis.clearTimeout;
const previousNow = Date.now;
const location = { pathname: "/chat", href: "" };
const tokens = {
@@ -37,24 +38,30 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
let now = 0;
let clears = 0;
let unexpected = 0;
+ let timerId = 0;
+ const timers = new Set<number>();
const delays: number[] = [];
const refreshBodies: string[] = [];
const apiTokens: (string | null)[] = [];
- const state = { onWait: null as null | (() => void) };
+ const state = { onWait: null as null | (() => void), mark: "session" as string | null };
globalThis.window = { location } as unknown as Window & typeof globalThis;
// A fake clock: a wait advances it and resolves on the next turn, not in real time.
Date.now = () => now;
globalThis.setTimeout = ((fn: () => void, ms?: number) => {
+ const id = ++timerId;
+ timers.add(id);
delays.push(ms ?? 0);
const hook = state.onWait;
state.onWait = null;
hook?.();
setImmediate(() => {
+ if (!timers.delete(id)) return;
now += ms ?? 0;
fn();
});
- return 0;
+ return id;
}) as unknown as typeof setTimeout;
+ globalThis.clearTimeout = ((id: number) => { timers.delete(id); }) as typeof clearTimeout;
globalThis.fetch = async (input, init) => {
const path = String(input);
if (path.endsWith("/status")) {
@@ -84,11 +91,14 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
globalThis.window = previousWindow;
globalThis.fetch = previousFetch;
globalThis.setTimeout = previousSetTimeout;
+ globalThis.clearTimeout = previousClearTimeout;
Date.now = previousNow;
assert.equal(unexpected, 0, "a refresh ran past its script");
});
const session = {
getAuthToken: () => tokens.access,
+ getAuthSessionMark: () => state.mark,
+ ensureAuthSessionMark: () => state.mark ??= "legacy-session",
getRefreshToken: () => tokens.refresh,
hasAuthToken: () => !!tokens.access,
hasRefreshToken: () => !!tokens.refresh,
@@ -102,6 +112,7 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
clears++;
tokens.access = null;
tokens.refresh = null;
+ state.mark = null;
},
};
const apiBase = {
@@ -109,7 +120,7 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
getApiPort: () => null,
isTauri: false,
};
- const api = loadWithStubs<typeof AuthApi>(
+ const makeApi = () => loadWithStubs<typeof AuthApi>(
new URL("../src/features/auth/api.ts", import.meta.url),
{
"@/lib/api-base": apiBase,
@@ -117,6 +128,7 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
"./session": session,
},
);
+ const api = makeApi();
const settle = async () => {
for (let i = 0; i < 5; i++) {
await new Promise<void>((resolve) => setImmediate(resolve));
@@ -124,6 +136,7 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
};
return {
api,
+ makeApi,
session,
apiBase,
tokens,
@@ -137,6 +150,114 @@ function fixture(t: TestContext, refreshes: Refresh[]) {
};
}
+test("two windows serialize rotation of their shared refresh token", async (t) => {
+ const f = fixture(t, [
+ () => new Promise<Response>((resolve) => setImmediate(() => resolve(rotated()))),
+ () => new Response(null, { status: 401 }),
+ ]);
+ let tail: Promise<unknown> = Promise.resolve();
+ Object.assign(window, { navigator: { locks: {
+ request: (_name: string, _options: unknown, callback: () => Promise<unknown>) => {
+ const result = tail.then(callback);
+ tail = result.catch(() => undefined);
+ return result;
+ },
+ } } });
+ const otherWindow = f.makeApi();
+ const results = await Promise.all([
+ f.api.refreshSessionOutcome(),
+ otherWindow.refreshSessionOutcome(),
+ ]);
+ assert.deepEqual(results, ["ok", "ok"]);
+ assert.equal(f.refreshBodies.length, 1);
+ assert.deepEqual(f.tokens, { access: "new-access", refresh: "new-refresh" });
+ assert.equal(f.clears(), 0);
+});
+
+test("a queued refresh does not use another account's session", async (t) => {
+ const f = fixture(t, []);
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ Object.assign(window, { navigator: { locks: {
+ request: async (_name: string, _options: unknown, callback: () => Promise<unknown>) => {
+ await gate;
+ return callback();
+ },
+ } } });
+ const pending = f.api.refreshSessionOutcome();
+ f.state.mark = "another-session";
+ f.tokens.access = "other-access";
+ f.tokens.refresh = "other-refresh";
+ release();
+ assert.equal(await pending, "unavailable");
+ assert.equal(f.refreshBodies.length, 0);
+ assert.deepEqual(f.tokens, { access: "other-access", refresh: "other-refresh" });
+});
+
+test("both windows reject a revoked refresh token without replaying it", async (t) => {
+ const f = fixture(t, [() => new Response(null, { status: 401 })]);
+ let tail: Promise<unknown> = Promise.resolve();
+ Object.assign(window, { navigator: { locks: {
+ request: (_name: string, _options: unknown, callback: () => Promise<unknown>) => {
+ const result = tail.then(callback);
+ tail = result.catch(() => undefined);
+ return result;
+ },
+ } } });
+ const peer = f.makeApi();
+ assert.deepEqual(await Promise.all([
+ f.api.refreshSessionOutcome(), peer.refreshSessionOutcome(),
+ ]), ["rejected", "rejected"]);
+ assert.equal(f.refreshBodies.length, 1);
+ assert.deepEqual(f.tokens, { access: null, refresh: null });
+ assert.equal(f.state.mark, null);
+});
+
+test("a legacy session without a marker shares the peer's rotation", async (t) => {
+ const f = fixture(t, [rotated]);
+ f.state.mark = null;
+ let tail: Promise<unknown> = Promise.resolve();
+ Object.assign(window, { navigator: { locks: {
+ request: (_name: string, _options: unknown, callback: () => Promise<unknown>) => {
+ const result = tail.then(callback);
+ tail = result.catch(() => undefined);
+ return result;
+ },
+ } } });
+ const otherWindow = f.makeApi();
+ assert.deepEqual(await Promise.all([
+ f.api.refreshSessionOutcome(), otherWindow.refreshSessionOutcome(),
+ ]), ["ok", "ok"]);
+ assert.equal(f.refreshBodies.length, 1);
+ assert.equal(f.state.mark, "legacy-session");
+});
+
+test("a hung refresh bounds another window's lock wait without aborting or replaying the POST", async (t) => {
+ let finish!: (response: Response) => void;
+ const f = fixture(t, [() => new Promise<Response>((resolve) => { finish = resolve; })]);
+ let held = false;
+ Object.assign(window, { navigator: { locks: {
+ request: (_name: string, options: { signal: AbortSignal }, callback: () => Promise<unknown>) => {
+ if (!held) {
+ held = true;
+ return Promise.resolve().then(callback);
+ }
+ return new Promise((_resolve, reject) => {
+ options.signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
+ });
+ },
+ } } });
+ const holder = f.api.refreshSessionOutcome();
+ await Promise.resolve();
+ const waiting = f.makeApi().refreshSessionOutcome();
+ assert.equal(await waiting, "unavailable");
+ assert.equal(f.refreshBodies.length, 1);
+ assert.equal(f.clears(), 0);
+ finish(rotated());
+ assert.equal(await holder, "ok");
+ assert.deepEqual(f.tokens, { access: "new-access", refresh: "new-refresh" });
+});
+
test("a 503 then 200 is retried and stores the rotated pair", async (t) => {
const f = fixture(t, [() => busy("0"), () => busy("1"), rotated]);
assert.equal(await f.api.refreshSession(), true);
diff --git a/tests/studio/test_auth_form_input_count.py b/tests/studio/test_auth_form_input_count.py
index 4b804fb15c3..c28e4a9f6ac 100644
--- a/tests/studio/test_auth_form_input_count.py
+++ b/tests/studio/test_auth_form_input_count.py
@@ -311,6 +311,8 @@ def test_auth_redirect_targets_are_idempotent_and_concurrent(tmp_path: Path):
export const reset = (a = null, r = null) => { access = a; refresh = r; passwordChange = false; };
export const clearAuthTokens = () => { access = null; refresh = null; };
export const getAuthToken = () => access;
+ export const getAuthSessionMark = () => null;
+ export const ensureAuthSessionMark = () => null;
export const getRefreshToken = () => refresh;
export const mustChangePassword = () => passwordChange;
export const setMustChangePassword = (value) => { passwordChange = value; };