Skip to content

Unsloth Studio: keep tabs signed in on plain-HTTP origins when two refresh at once - #16755

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
LeoBorcherding:studio/session-reset
Nov 7, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
LeoBorcherding:studio/session-reset

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Several Unsloth Studio tabs open on a plain-HTTP address (for example http://<lan-ip>:8888) could all sign out at once, or jump back to a new chat, in the middle of a running chat. It was reported in the Discord help thread on Firefox, Safari, Chromium and Brave, and happened more often with several tasks running. With this change, the tabs stay signed in.

Four tabs after a shared-token expiry, before and after

What was wrong

Refresh tokens are single-use. #16468 makes tabs take turns refreshing through Web Locks, but browsers only expose Web Locks in secure contexts (HTTPS or localhost). On a plain-HTTP LAN address, every tab still refreshes on its own. All tabs share one access token, so they hit its expiry together:

sequenceDiagram
    participant A as Tab A
    participant B as Tab B
    participant S as Server
    A->>S: refresh(token R)
    B->>S: refresh(token R)
    S-->>A: 200, new pair R2
    S-->>B: 401, R already used
    Note over B: before: clears the shared tokens<br/>or redirects to /login, which bounces to /chat
    Note over B: after: waits for R2 to land in storage, then retries
Loading
  • If B's 401 lands before A saves R2, B clears the shared tokens and every tab signs out.
  • If it lands after, B redirects to /login, and the login route bounces it to /chat. That's the "reset to New Chat".

The fix

The fix is in features/auth/api.ts and only applies when Web Locks is unavailable. A 401 from /api/auth/refresh waits up to 3 seconds for another tab's rotated tokens to appear in shared storage:

  • If they appear and the session mark is unchanged, the refresh counts as successful and the request is retried with the new tokens.
  • If another tab logs out, switches account or signs in during the wait, the wait ends as a rejection.
  • For a session that had no mark yet, the mark is read when the 401 arrives. That way, two tabs racing to write the first mark don't mistake each other for a switch.
  • A genuinely revoked token still signs out, just 3 seconds later.

Secure origins, the backend and the token rules are unchanged.

How it was tested

All runs were on a MacBook Pro (Apple M5, macOS 26).

what ran base a17bfe91ab this PR 46f7853c1f
4 tabs, headless Chromium, plain-HTTP LAN address (isSecureContext false), 4 forced expiries 0 of 4 tabs signed in after round 1, all at /login 4 of 4 signed in after 4 rounds, none moved
tests/auth-refresh-transient.test.ts, 4 new tests the 2 race orderings fail pass
full frontend Node suite, tsc -b, tsc -p tsconfig.test.json, backend auth suites (85) 14,928 pass, 0 fail, clean

The other two new tests cover a session replaced during the wait and a peer tab winning the first mark write. Each fails on the commit before its fix (e9114afc29, 17b0e6f2c0).

How the browser run worked: two isolated installs, both bound to 0.0.0.0. Four tabs started on Hub, Train, Export and Library. The token lifetime is a fixed 60 minutes, so each round broke the shared access token's signature instead, which takes the same 401 path as a real expiry. The successful refresh response was also held back 1.5 s, the way a slow remote link would delay it. The server log shows the same collision on both sides, one POST /api/auth/refresh 200 and three 401s within about 5 ms. On base, the losing tabs sign out. With this PR, they pick up the winner's tokens.

Not tested

  • Firefox, Safari and Brave. The browser run used Chromium only.
  • A real remote host. The run used the Mac's own LAN address.
  • The single Unsloth Desktop sign-out in the report. This change doesn't explain it, because Desktop runs on a secure origin where Web Locks is available.

Independent before/after check

Two isolated Studio installs (merge base a17bfe91ab vs this PR), headless Chromium, 4 tabs on /hub, /studio, /export, /library served from a non-localhost name (isSecureContext false, no navigator.locks). Each round breaks the shared access token's signature and fires a request from every tab; the winning refresh is held back 1.5 s.

base this PR
refresh statuses per round [200, 401] [401, 200] / [200, 401]
tabs signed in after round 1 0 of 4, all on /login, tokens cleared 4 of 4
tabs signed in after round 4 0 of 4 4 of 4, none moved

Hub tab after a shared-token expiry on a plain-HTTP origin, before and after

Hub tab after round 4: base shows the login page, this PR keeps the tab on Model hub.

… once

Web Locks only exist in secure contexts, so on http://<lan-ip>:<port> two
tabs can spend the same single-use refresh token. The loser's 401 used to
clear the shared tokens (every tab signed out) or, if the winner had already
stored its pair, redirect to /login and bounce back to a new chat. Without
locks, a 401 now waits briefly for a peer's rotation to land before treating
the session as rejected.
A sign-in or account switch in another tab during the wait also replaces the
refresh token; it must end the refresh, not be retried as this session.
Two plain-HTTP tabs refreshing a session that had no mark can each mint one;
the tab whose write lost would read the peer's rotation as a session switch.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Codex on the fork mirror: Didn't find any major issues at 46f7853c1f, the same commit as this head. Mirror CI at that commit is green (35 passed, 11 skipped, 0 failed).

@danielhanchen danielhanchen self-assigned this Nov 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-07T13:12:24.399686Z 43bf2b3 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fed622193e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +333 to +334
const currentMark = getAuthSessionMark();
mark ??= currentMark;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the logout boundary for legacy refreshes

Without Web Locks, if a legacy session starts with no mark and another tab logs out and signs back in before the refresh's 401 arrives, peerSessionMark is null and this assignment adopts the new sign-in's mark. Its refresh token also differs, so peerRotated returns true and authFetch replays the pre-logout request, including mutations such as saveChatSettingsPatch, under the new session. Same-account sign-ins do not set the account-switch fence or reload peer tabs, so accountTransitionPending() does not prevent this. Preserve a boundary from refresh start that distinguishes initial marker backfill from a completed logout/sign-in.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 43bf2b3: the peer wait now runs only when a session mark existed at refresh start, so a logout and sign-in can never be taken for a peer's rotation; a session with no mark keeps the old reject path until its first refresh backfills one.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 43bf2b3d92

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit f643501 into unslothai:main Nov 7, 2026
danielhanchen added a commit that referenced this pull request Nov 7, 2026
…tores window (#17055)

## Summary

Since #16755 merged, every `Frontend CI` run fails on both `Frontend
build + bundle sanity` and `Frontend unit tests (Windows)`, with the
same file. On PRs this includes #17010 and the cosmos3, images and voice
PRs, and the main push runs are red too:

```
# Error: Test "without Web Locks a session with no mark does not take a later sign-in for a peer's rotation"
  at tests/auth-refresh-transient.test.ts:453:1 generated asynchronous activity after the test ended.
  This activity created the error "TypeError: Cannot read properties of undefined (reading 'location')"
  and would have caused the test to fail, but instead triggered an unhandledRejection event.
not ok 140 - tests/auth-refresh-transient.test.ts
```

The product code is correct; the test does not wait for it. In the new
test, `authFetch` returns the 401, and the rejected-refresh path then
sends the tab to `/login` through `window.location` on a later turn. The
test ends right after the returned response. The fixture's `t.after`
then restores the real `globalThis.window`, which is `undefined` under
Node, so the deferred redirect throws. The sibling tests that take a 401
already `await f.settle()` before they finish. This one does not.

The failure depends on the Node version. CI pins Node 22 (`22.23.4`),
which fails the file every time. Node 24 does not, which is why the PR
was green where it was written.

## Change

`studio/frontend/tests/auth-refresh-transient.test.ts`, tests only:

- The fixture's `t.after` drains five turns before it restores `window`,
`fetch`, `setTimeout`, `clearTimeout` and `Date.now`. That is the same
drain as `f.settle()`. Deferred work from any test in the file now runs
against the fixture's window, not after it is gone.
- The new test settles and asserts what the rejected path does,
`location.href == "/login"`. It also keeps its existing checks: the
other sign-in's tokens stay and nothing is cleared.

## Testing

| | Node 22.23.4 (CI) | Node 24.22.1 |
|---|---|---|
| main | file fails (`# pass 23`, `# fail 1`, the error above) | 23 pass
|
| this branch | 23 pass | 23 pass |
| this branch, fixture drain alone (new assertion removed) | 23 pass | |
meefs pushed a commit to meefs/unsloth that referenced this pull request Nov 20, 2026
…thai#18353)

Every open Unsloth Studio tab could still sign out at once when the
answer to a successful session refresh never reached the browser. With
this change the session survives that.

## What was wrong

Refresh tokens are single-use. When `/api/auth/refresh` rotates a token,
the server deletes the old one and returns a new pair. If that answer is
lost on the way back, the browser keeps the old token, which is already
gone on the server:

- a tab is closed or reloaded while the refresh is in flight
- a reverse proxy times out the request after the server committed
- a phone or tablet suspends the page mid-request

The next refresh sends the spent token, gets a 401, and the client
clears the tokens in shared storage. That signs out every tab on that
browser.

unslothai#16468 (Web Locks) and unslothai#16755 (plain-HTTP peer wait) fixed the two-tab
race reported on Discord. This lost-answer case is the one path that
still ends the session.

## The fix

A token rotated by `/api/auth/refresh` stays exchangeable for 60 seconds
(`REFRESH_REUSE_GRACE_SECONDS`). Presenting it again in that window
rotates once more and returns a fresh pair instead of a 401. This makes
a retried refresh idempotent, the same idea as Supabase's refresh token
reuse interval and Okta's grace period.

- **Revocation is unchanged.** Logout, password changes, account revokes
and renames delete the grace rows in the same transaction as the live
tokens. All five call sites go through one helper,
`_delete_refresh_rows`. A password change is also caught by the existing
credential generation check.
- **Downgrade safe.** The grace rows live in a new `refresh_token_reuse`
table, and the spent token is still deleted from `refresh_tokens`. An
older build never reads the new table, so it cannot revive a spent
token.
- **Bounded.** One spent token mints at most `REFRESH_REUSE_MAX` (8)
pairs inside the window; later replays get a 401, which the client
already answers from a peer's stored pair.
- **Only stamped tokens get the window.** A token without a credential
generation stamp (legacy rows from before that column existed) stays
strictly single-use, so every reuse row is voided by any credential
change, including the CLI password reset that rotates the secret with
its own SQL.
- **Scope.** Only the rotation path opts in. `consume_refresh_token`
stays strictly single-use, and expired rows and rows older than the
window are purged on every rotation.
- **Frontend.** Without Web Locks (plain HTTP), two tabs racing on one
token now both get a 200. A tab whose own 200 lands after a peer already
stored a pair now reuses the peer's pair through the existing
`peerRotated` check, as the 401 path already did, instead of handing its
caller the original 401.

No new UI: the only visible change is that the tabs stay signed in.
Desktop, which runs on a secure origin with Web Locks, follows the same
path as before.

## Tests

| check | merge base | this PR |
|---|---|---|
| retry after a lost rotation answer | `401 Invalid or expired refresh
token` | `200`, new pair works |
| two tabs racing on one token | first 200, second 401 | both 200 |
| spent token after the window ends | 401 | 401 |
| logout, password change or CLI reset inside the window | 401 | 401 |
| legacy unstamped token reused | 401 | 401 |
| one spent token replayed 10 times in the window | 401 | 8 pairs, then
401 |
| `tests/test_refresh_reuse_grace.py` (11) | 3 fail, 8 pass | 11 pass |
| `tests/auth-refresh-transient.test.ts` | 23 pass, 2 fail | 25 pass |
| backend auth suites (11 files, 387 tests) | 1 fail | same 1 fail |
| full frontend `node --test` (16,708 tests) | same 2 new tests fail | 0
fail |
| frontend typecheck | | pass |

- The one backend failure on both sides,
`test_health_response_reports_desktop_capability_fields`, already fails
on main.
- The two tests in `test_auth_db_lock_contention.py` that pinned
"immediate reuse is a 401" now assert the 401 after the window instead.
- Mutation checks: dropping the grace-row delete from the revoke helper
fails `test_logout_inside_the_window_still_ends_the_session`; recording
unstamped tokens fails `test_a_legacy_unstamped_token_gets_no_window`.
- Staging on Linux, macOS (Apple Silicon) and Windows ran the PR's
backend and node tests at the final code: 32 backend tests passed and
the node refresh suite 25 pass / 0 fail on each OS.
- Studio regression journeys (auth, settings, route crawl, full access)
base vs head: no regression, 43 of 43 steps unchanged.

## Before and after in Studio

Two isolated Studio installs (merge base `daf25ce59` vs this branch).
Two tabs are signed in; page JS posts the stored refresh token to
`/api/auth/refresh` and drops the 200, so the server has rotated the
token while the browser still holds the spent one. The access token is
then invalidated and both tabs reload. Before, the spent token gets a
401 and both tabs land on the login page; after, both tabs stay signed
in on the chat page.

![Two tabs after a lost refresh answer, before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/18353/pr18353_pair_00-9c9e488bcc67.png)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants